auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onMapClick(@NonNull LatLng point) { final SymbolLayer marker = (SymbolLayer) mapboxMap.getLayer("selected-marker-layer"); final PointF pixel = mapboxMap.getProjection().toScreenLocation(point); List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, "marker-layer"); List<Feature> selectedFeature = mapboxMap.queryRenderedFeatures(pixel, "selected-marker-layer"); if (selectedFeature.size() > 0 && markerSelected) { return; } if (features.size() <= 0) { if (markerSelected) { deselectMarker(marker); } return; } FeatureCollection featureCollection = FeatureCollection.fromFeatures( new Feature[]{Feature.fromGeometry(features.get(0).getGeometry())}); GeoJsonSource source = mapboxMap.getSourceAs("selected-marker"); if (source != null) { source.setGeoJson(featureCollection); } if (markerSelected) { deselectMarker(marker); } if (features.size() > 0) { selectMarker(marker); } }

Target:
public void onMapClick(@NonNull LatLng point) { final SymbolLayer marker = (SymbolLayer) mapboxMap.getLayer("selected-marker-layer"); final PointF pixel = mapboxMap.getProjection().toScreenLocation(point); List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, "marker-layer"); List<Feature> selectedFeature = mapboxMap.queryRenderedFeatures(pixel, "selected-marker-layer"); if (selectedFeature.size() > 0 && markerSelected) { return; } if (features.isEmpty()) { if (markerSelected) { deselectMarker(marker); } return; } FeatureCollection featureCollection = FeatureCollection.fromFeatures( new Feature[]{Feature.fromGeometry(features.get(0).getGeometry())}); GeoJsonSource source = mapboxMap.getSourceAs("selected-marker"); if (source != null) { source.setGeoJson(featureCollection); } if (markerSelected) { deselectMarker(marker); } if (features.size() > 0) { selectMarker(marker); } }
Source:
private TaskLockPosse createOrFindLockPosse(Task task, TaskLock taskLock) { giant.lock(); Preconditions.checkArgument( task.getGroupId().equals(taskLock.getGroupId()), "lock groupId[%s] is different from task groupId[%s]", taskLock.getGroupId(), task.getGroupId() ); Preconditions.checkArgument( task.getDataSource().equals(taskLock.getDataSource()), "lock dataSource[%s] is different from task dataSource[%s]", taskLock.getDataSource(), task.getDataSource() ); Preconditions.checkArgument( task.getPriority() == taskLock.getPriority(), "lock priority[%s] is different from task priority[%s]", taskLock.getPriority(), task.getPriority() ); try { return createOrFindLockPosse( taskLock.getType(), task.getId(), taskLock.getGroupId(), taskLock.getDataSource(), taskLock.getInterval(), taskLock.getVersion(), taskLock.getPriority(), taskLock.isRevoked() ); } finally { giant.unlock(); } }

Target:
private TaskLockPosse createOrFindLockPosse(Task task, TaskLock taskLock) { giant.lock(); try { Preconditions.checkArgument( task.getGroupId().equals(taskLock.getGroupId()), "lock groupId[%s] is different from task groupId[%s]", taskLock.getGroupId(), task.getGroupId() ); Preconditions.checkArgument( task.getDataSource().equals(taskLock.getDataSource()), "lock dataSource[%s] is different from task dataSource[%s]", taskLock.getDataSource(), task.getDataSource() ); Preconditions.checkArgument( task.getPriority() == taskLock.getPriority(), "lock priority[%s] is different from task priority[%s]", taskLock.getPriority(), task.getPriority() ); return createOrFindLockPosse( taskLock.getType(), task.getId(), taskLock.getGroupId(), taskLock.getDataSource(), taskLock.getInterval(), taskLock.getVersion(), taskLock.getPriority(), taskLock.isRevoked() ); } finally { giant.unlock(); } }
Source:
public SshdSession getSession(URIish urIish, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { try { this.uri = urIishToUri(urIish); AuthenticationConfiguration config = CLIENT.getAuthenticationConfiguration(this.uri, context); CredentialCallback locationCallback = new CredentialCallback(SSHCredential.class, null); CredentialCallback keyPairCallback = new CredentialCallback(KeyPairCredential.class, null); Callback[] callbacks = {locationCallback, keyPairCallback}; CLIENT.getCallbackHandler(config).handle(callbacks); if (locationCallback.getCredential() != null) { SSHCredential sshCredential = locationCallback.getCredential().castAs(SSHCredential.class); this.setSshDirectory(sshCredential.getSshDirectory()); this.defaultIdentities = sshCredential.getPrivateKeyIdentities(); this.knownHostsFile = sshCredential.getKnownHostsFile(); } if (keyPairCallback.getCredential() != null) { KeyPairCredential keyPairCredential = keyPairCallback.getCredential().castAs(KeyPairCredential.class); this.keyPair = keyPairCredential.getKeyPair(); } } catch (IOException | UnsupportedCallbackException | URISyntaxException ex) { ServerLogger.ROOT_LOGGER.failedToLoadSSHCredentials(ex, ex.getMessage()); } return super.getSession(urIish, credentialsProvider, fs, tms); }

Target:
public SshdSession getSession(URIish urIish, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { if (context == null) return super.getSession(urIish, credentialsProvider, fs, tms); try { this.uri = urIishToUri(urIish); AuthenticationConfiguration config = CLIENT.getAuthenticationConfiguration(this.uri, context); CredentialCallback locationCallback = new CredentialCallback(SSHCredential.class, null); CredentialCallback keyPairCallback = new CredentialCallback(KeyPairCredential.class, null); Callback[] callbacks = {locationCallback, keyPairCallback}; CLIENT.getCallbackHandler(config).handle(callbacks); if (locationCallback.getCredential() != null) { SSHCredential sshCredential = locationCallback.getCredential().castAs(SSHCredential.class); this.setSshDirectory(sshCredential.getSshDirectory()); this.defaultIdentities = sshCredential.getPrivateKeyIdentities(); this.knownHostsFile = sshCredential.getKnownHostsFile(); } if (keyPairCallback.getCredential() != null) { KeyPairCredential keyPairCredential = keyPairCallback.getCredential().castAs(KeyPairCredential.class); this.keyPair = keyPairCredential.getKeyPair(); } } catch (IOException | UnsupportedCallbackException | URISyntaxException ex) { throw ServerLogger.ROOT_LOGGER.failedToLoadSSHCredentials(ex, ex.getMessage()); } return super.getSession(urIish, credentialsProvider, fs, tms); }
Source:
protected void processChild(BulldozerMovePath child, List<BulldozerMovePath> children, Map<Coords, BulldozerMovePath> shortestPathsToCoords) { int alpha = 1; MoveLegalityIndicator mli = isLegalMove((MovePath) child); boolean canLevel = child.needsLeveling() && !mli.outOfBounds && !mli.destinationImpassable && !mli.goingDownTooLow && !mli.goingUpTooHigh && !mli.wheeledTankRestriction && !mli.destinationHasWeakBridge && !mli.groundTankIntoWater; if((!shortestPathsToCoords.containsKey(child.getFinalCoords()) || (movePathComparator.compare(shortestPathsToCoords.get(child.getFinalCoords()), child) > 0)) && (mli.isLegal() || canLevel) && (child.getMpUsed() + child.getLevelingCost() < maximumCost)) { shortestPathsToCoords.put(child.getFinalCoords(), child); children.add(child); } }

Target:
protected void processChild(BulldozerMovePath child, List<BulldozerMovePath> children, Map<Coords, BulldozerMovePath> shortestPathsToCoords) { MoveLegalityIndicator mli = isLegalMove((MovePath) child); boolean canLevel = child.needsLeveling() && !mli.outOfBounds && !mli.destinationImpassable && !mli.goingDownTooLow && !mli.goingUpTooHigh && !mli.wheeledTankRestriction && !mli.destinationHasWeakBridge && !mli.groundTankIntoWater; if((!shortestPathsToCoords.containsKey(child.getFinalCoords()) || (movePathComparator.compare(shortestPathsToCoords.get(child.getFinalCoords()), child) > 0)) && (mli.isLegal() || canLevel) && (child.getMpUsed() + child.getLevelingCost() < maximumCost)) { shortestPathsToCoords.put(child.getFinalCoords(), child); children.add(child); } }
Source:
protected int getDetailsBatchSize() { String batchCfg = _configDao.getValue("detail.batch.query.size"); return batchCfg != null ? Integer.parseInt(batchCfg) : 2000; }

Target:
protected int getDetailsBatchSize() { String batchCfg = _configDao.getValue("detail.batch.query.size"); return batchCfg != null ? Integer.parseInt(batchCfg) : DEFAULT_BATCH_QUERY_SIZE; }
Source:
public void addToArchive( Path archiveDestination, DiagnosticsReporterProgressCallback monitor ) throws IOException { long size = fs.getFileSize( source ); InputStream in = fs.openAsInputStream( source ); ProgressAwareInputStream inStream = new ProgressAwareInputStream( in, size, monitor::percentChanged ); Files.copy( inStream, archiveDestination ); }

Target:
public void addToArchive( Path archiveDestination, DiagnosticsReporterProgressCallback monitor ) throws IOException { long size = fs.getFileSize( source ); InputStream in = fs.openAsInputStream( source ); try ( ProgressAwareInputStream inStream = new ProgressAwareInputStream( in, size, monitor::percentChanged ) ) { Files.copy( inStream, archiveDestination ); } }
Source:
public void visitElement(PsiElement element) { try { if (!(element instanceof MethodReference)) { return; } MethodReference methodReference = (MethodReference) element; PsiElement[] parameters = methodReference.getParameters(); if (parameters.length == 0) { return; } if (!"directive".equals(methodReference.getName())) { return; } Method method = Symfony2InterfacesUtil.getMultiResolvedMethod(methodReference); if (method == null) { return; } if (method.getContainingClass() == null || !availableClasses.contains(method.getContainingClass().getPresentableFQN())) { return; } if (!(parameters[0] instanceof StringLiteralExpression)) { return; } consumer.accept(Pair.create(element, ((StringLiteralExpression) parameters[0]).getContents())); } finally { super.visitElement(element); } }

Target:
public void visitElement(PsiElement element) { if (element instanceof MethodReference) { visitMethodReference((MethodReference) element); } super.visitElement(element); }
Source:
public static String getDirName(Props props) { String dirSuffix = props.get("azkaban.flow.nested.path"); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { dirSuffix = props.get("azkaban.job.id"); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { throw new RuntimeException("azkaban.flow.nested.path and azkaban.job.id were not set"); } } return "_link_" + dirSuffix; }

Target:
public static String getDirName(Props props) { String dirSuffix = props.get("azkaban.flow.nested.path"); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { dirSuffix = props.get("azkaban.job.id"); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { throw new RuntimeException("azkaban.flow.nested.path and azkaban.job.id were not set"); } } return "_resources_" + dirSuffix; }
Source:
private List<Match> find(String text, int offset, boolean firstOnly) { int textEnd= text.length(); List<Match> matches= new LinkedList<>(); Node node= root; for (int i= offset; i < textEnd; i++) { Character c= Character.valueOf(text.charAt(i)); Node next; while ((next= node.next(c)) == null) { node= node.fail; } node= next; if (node == root) { if (firstOnly && !matches.isEmpty()) { break; } } else { if (firstOnly && !node.hasChildren()) { matches.clear(); matches.add(new MatchResult(node.match, i - node.match.length() + 1)); break; } if (node.match != null) { matches.add(new MatchResult(node.match, i - node.match.length() + 1)); } if (!firstOnly || matches.isEmpty()) { Node out= node.output; while (out != null) { matches.add(new MatchResult(out.match, i - out.match.length() + 1)); out= out.output; } } } } return matches; }

Target:
private List<Match> find(String text, int offset, boolean firstOnly) { int textEnd= text.length(); List<Match> matches= new LinkedList<>(); Node node= root; for (int i= offset; i < textEnd; i++) { Character c= Character.valueOf(text.charAt(i)); Node next; while ((next= node.next(c)) == null) { if (firstOnly && !matches.isEmpty()) { return matches; } node= node.fail; } node= next; if (node != root) { if (firstOnly && !node.hasChildren()) { matches.clear(); matches.add(new MatchResult(node.match, i - node.match.length() + 1)); break; } if (node.match != null) { matches.add(new MatchResult(node.match, i - node.match.length() + 1)); } if (!firstOnly || matches.isEmpty()) { Node out= node.output; while (out != null) { matches.add(new MatchResult(out.match, i - out.match.length() + 1)); out= out.output; } } } } return matches; }
Source:
public static boolean mkdirsIfSaveable(File dir) { if (NO_FILE_CREATION) { return false; } Path path = dir.toPath(); Optional<Path> savesDirOpt = getCurrentSavesDirectory(); if (!savesDirOpt.isPresent()) { return dir.mkdirs(); } Path savesDir = savesDirOpt.get(); if (path.startsWith(savesDir) && !path.equals(savesDir)) { Path worldName = savesDir.relativize(path).getName(0); WorldProperties props; if (worldPropertiesByFolderName.containsKey(worldName.toString())) { props = worldPropertiesByFolderName.get(worldName.toString()); } else if (worldPropertiesByWorldUuid.size() == 1) { props = worldPropertiesByWorldUuid.values().iterator().next(); } else { Optional<WorldProperties> overworld = Sponge.getServer().getDefaultWorld(); if (!overworld.isPresent()) { return dir.mkdirs(); } props = overworld.get(); } if (props.getSerializationBehavior() == SerializationBehaviors.NONE) { return false; } } return dir.mkdirs(); }

Target:
public static boolean mkdirsIfSaveable(File dir) { if (PhaseTracker.getInstance().getSidedThread() == Thread.currentThread()) { IPhaseState state = PhaseTracker.getInstance().getCurrentState(); if (!state.shouldCreateWorldDirectories(PhaseTracker.getInstance().getCurrentContext())) { return false; } } Path path = dir.toPath(); Optional<Path> savesDirOpt = getCurrentSavesDirectory(); if (!savesDirOpt.isPresent()) { return dir.mkdirs(); } Path savesDir = savesDirOpt.get(); if (path.startsWith(savesDir) && !path.equals(savesDir)) { Path worldName = savesDir.relativize(path).getName(0); WorldProperties props; if (worldPropertiesByFolderName.containsKey(worldName.toString())) { props = worldPropertiesByFolderName.get(worldName.toString()); } else if (worldPropertiesByWorldUuid.size() == 1) { props = worldPropertiesByWorldUuid.values().iterator().next(); } else { Optional<WorldProperties> overworld = Sponge.getServer().getDefaultWorld(); if (!overworld.isPresent()) { return dir.mkdirs(); } props = overworld.get(); } if (props.getSerializationBehavior() == SerializationBehaviors.NONE) { return false; } } return dir.mkdirs(); }
Source:
public static String getFileName(String compressedName) { compressedName = compressedName.toLowerCase(); if(isZip(compressedName) || isTar(compressedName) || isRar(compressedName) || compressedName.endsWith(fileExtensionGzipTarShort)) { return compressedName.substring(0, compressedName.lastIndexOf(".")); } else if (isGzippedTar(compressedName)) { return compressedName.substring(0, Utils.nthToLastCharIndex(2, compressedName, '.')); } else { return compressedName; } }

Target:
public static String getFileName(String compressedName) { compressedName = compressedName.toLowerCase(); if(isZip(compressedName) || isTar(compressedName) || isRar(compressedName) || isGzippedTarShort(compressedName)) { return compressedName.substring(0, compressedName.lastIndexOf(".")); } else if (isGzippedTar(compressedName)) { return compressedName.substring(0, Utils.nthToLastCharIndex(2, compressedName, '.')); } else { return compressedName; } }
Source:
protected boolean validateDestStorage() { StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain()); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } if (!isSupportedByManagedBlockStorageDomain(getStorageDomain())) { return false; } boolean moveOrCopy = isMoveOperation() || isCopyOperation(); if (moveOrCopy && getImage().isShareable() && getStorageDomain().getStorageType() == StorageType.GLUSTERFS ) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANT_MOVE_SHAREABLE_DISK_TO_GLUSTERFS, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } if ( moveOrCopy && getImage().isShareable() && getStorageDomain().getStorageType().isBlockDomain() && getImage().getVolumeType() == VolumeType.Sparse ) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANT_MOVE_OR_COPY_SHAREABLE_THIN_DISK_TO_ISCSI, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } if (isMoveOperation()) { if (getImage().getStorageIds().contains(getStorageDomainId())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_DESTINATION_STORAGE_DOMAIN_ALREADY_CONTAINS_THE_DISK); } } return true; }

Target:
protected boolean validateDestStorage() { StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain()); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } if (!isSupportedByManagedBlockStorageDomain(getStorageDomain())) { return false; } boolean moveOrCopy = isMoveOperation() || isCopyOperation(); if (moveOrCopy && getImage().isShareable()) { if (getStorageDomain().getStorageType() == StorageType.GLUSTERFS) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANT_MOVE_SHAREABLE_DISK_TO_GLUSTERFS, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } if (getStorageDomain().getStorageType().isBlockDomain() && getImage().getVolumeType() == VolumeType.Sparse) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANT_MOVE_OR_COPY_SHAREABLE_THIN_DISK_TO_ISCSI, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } } if (isMoveOperation()) { if (getImage().getStorageIds().contains(getStorageDomainId())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_DESTINATION_STORAGE_DOMAIN_ALREADY_CONTAINS_THE_DISK); } } return true; }
Source:
public List<Location> getLocationsByType(final Integer type, final int start, final int numOfRows) throws MiddlewareQueryException { final List<String> methods = Arrays.asList(COUNT_BY_TYPE, GET_BY_TYPE); return this.getFromCentralAndLocalByMethod(this.getLocationDao(), methods, start, numOfRows, new Object[] { type }, new Class[] { Integer.class }); }

Target:
public List<Location> getLocationsByType(final Integer type, final int start, final int numOfRows) throws MiddlewareQueryException { final List<String> methods = Arrays.asList(LocationDataManagerImpl.COUNT_BY_TYPE, LocationDataManagerImpl.GET_BY_TYPE); return this.getFromCentralAndLocalByMethod(this.getLocationDao(), methods, start, numOfRows, new Object[] { type }, new Class[] { Integer.class }); }
Source:
public void pull(PullFilters pullFilters, IPullController.Callback callback) { Log.d(TAG, "Starting PULL process..."); callback.onStep(PullStep.METADATA); try { mPullController.populateMetadataFromCsvs(pullFilters.isDemo()); if (isNetworkAvailable()) { checkCSVVersion(callback); } if(!pullFilters.isDemo()) { mPullController.pullData(pullFilters, new ArrayList<OrganisationUnit>(), callback); }else{ mPullController.onPullDataComplete(callback, true); callback.onComplete(); } } catch (Exception ex) { Log.e(TAG, "pull: " + ex.getLocalizedMessage()); callback.onError(ex); } }

Target:
public void pull(PullFilters pullFilters, IPullController.Callback callback) { Log.d(TAG, "Starting PULL process..."); callback.onStep(PullStep.METADATA); try { if (isNetworkAvailable()) { checkCSVVersion(callback, pullFilters); } if(!pullFilters.isDemo()) { mPullController.pullData(pullFilters, new ArrayList<OrganisationUnit>(), callback); }else{ mPullController.onPullDataComplete(callback, true); callback.onComplete(); } } catch (Exception ex) { Log.e(TAG, "pull: " + ex.getLocalizedMessage()); callback.onError(ex); } }
Source:
public Object[] getElements(Object element) { if (element instanceof Object[]) { return (Object[]) element; } if (element instanceof Collection) { return ((Collection) element).toArray(); } return new Object[0]; }

Target:
public Object[] getElements(Object element) { if (element instanceof Object[]) return (Object[]) element; if (element instanceof Collection) return ((Collection) element).toArray(); return new Object[0]; }
Source:
public void setClientMetaData(Map<String, String> clientMetaData) { this.clientMetaData = clientMetaData; }

Target:
public void setClientMetaData(Map<String, String> clientMetaData) { this.clientMetaData = Collections.unmodifiableMap(clientMetaData); }
Source:
public void testUnknownMessage() throws InterruptedException { AgentMessageProcessor processor = new AgentMessageProcessor( new Agent()); processor.processMessage( new Message() { private static final long serialVersionUID = -3312628850227527510L; }); }

Target:
public void testUnknownMessage() { AgentMessageProcessor processor = new AgentMessageProcessor( new Agent()); processor.processMessage( new Message() { private static final long serialVersionUID = -3312628850227527510L; }); }
Source:
public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { StringBuffer command = createCommand(LTTngControlServiceConstants.COMMAND_LIST_KERNEL); ICommandResult result = executeCommand(command.toString(), monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); if (isError(result) && result.getErrorOutput() != null) { int index = 0; while (index < result.getErrorOutput().length) { String line = result.getErrorOutput()[index]; Matcher matcher = LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN.matcher(line); if (matcher.matches()) { return events; } index++; } throw new ExecutionException(Messages.TraceControl_CommandError + LTTngControlServiceConstants.COMMAND_LIST_KERNEL); } Document document = getDocumentFromStrings(result.getOutput()); NodeList rawEvents = document.getElementsByTagName(MIStrings.EVENT); getBaseEventInfo(rawEvents, events); return events; }

Target:
public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { StringBuffer command = createCommand(LTTngControlServiceConstants.COMMAND_LIST_KERNEL); ICommandResult result = executeCommand(command.toString(), monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); if (isError(result) && result.getErrorOutput() != null) { if (ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN)) { return events; } throw new ExecutionException(Messages.TraceControl_CommandError + LTTngControlServiceConstants.COMMAND_LIST_KERNEL); } Document document = getDocumentFromStrings(result.getOutput()); NodeList rawEvents = document.getElementsByTagName(MIStrings.EVENT); getBaseEventInfo(rawEvents, events); return events; }
Source:
private void filterAndUpdateStackingEntitlements( Map<Consumer, List<Entitlement>> consumerSortedEntitlements) { Map<Consumer, List<Entitlement>> stackingEntitlements = new HashMap<Consumer, List<Entitlement>>(); for (Consumer consumer : consumerSortedEntitlements.keySet()) { List<Entitlement> ents = consumerSortedEntitlements.get(consumer); if (CollectionUtils.isNotEmpty(ents)) { for (Entitlement ent : ents) { Pool pool = ent.getPool(); if (!"true".equals(pool.getAttributeValue("pool_derived")) && pool.getProduct().hasAttribute("stacking_id")) { if (!stackingEntitlements.containsKey(consumer)) { stackingEntitlements.put(consumer, new ArrayList<Entitlement>()); } stackingEntitlements.get(consumer).add(ent); } } } } for (Entry<Consumer, List<Entitlement>> entry : stackingEntitlements.entrySet()) { if (log.isDebugEnabled()) { log.debug("Found stacking entitlements to delete for consumer: {}", entry.getValue() .size(), entry.getKey()); } Set<String> stackIds = new HashSet<String>(); for (Entitlement ent : entry.getValue()) { stackIds.add(ent.getPool().getStackId()); } List<Pool> subPools = poolCurator.getSubPoolForStackIds(entry.getKey(), stackIds); if (CollectionUtils.isNotEmpty(subPools)) { poolRules.updatePoolsFromStack(entry.getKey(), subPools, true); } } }

Target:
private void filterAndUpdateStackingEntitlements( Map<Consumer, List<Entitlement>> consumerSortedEntitlements) { Map<Consumer, List<Entitlement>> stackingEntitlements = new HashMap<Consumer, List<Entitlement>>(); for (Consumer consumer : consumerSortedEntitlements.keySet()) { List<Entitlement> ents = consumerSortedEntitlements.get(consumer); if (CollectionUtils.isNotEmpty(ents)) { for (Entitlement ent : ents) { Pool pool = ent.getPool(); if (!"true".equals(pool.getAttributeValue("pool_derived")) && pool.getProduct().hasAttribute("stacking_id")) { List<Entitlement> entList = stackingEntitlements.get(consumer); if (entList == null) { entList = new ArrayList<Entitlement>(); stackingEntitlements.put(consumer, entList); } entList.add(ent); } } } } for (Entry<Consumer, List<Entitlement>> entry : stackingEntitlements.entrySet()) { if (log.isDebugEnabled()) { log.debug("Found stacking entitlements to delete for consumer: {}", entry.getValue() .size(), entry.getKey()); } Set<String> stackIds = new HashSet<String>(); for (Entitlement ent : entry.getValue()) { stackIds.add(ent.getPool().getStackId()); } List<Pool> subPools = poolCurator.getSubPoolForStackIds(entry.getKey(), stackIds); if (CollectionUtils.isNotEmpty(subPools)) { poolRules.updatePoolsFromStack(entry.getKey(), subPools, true); } } }
Source:
static String getCleanedDescription(String description) { if (description != null) { description = CharMatcher.javaIsoControl().removeFrom(description); if (description.length() > MAX_DESCRIPTION) { description = description.substring(0, MAX_DESCRIPTION - Client.PADDING) + "..."; } } else { description = ""; } return description; }

Target:
static String getCleanedDescription(String description) { description = MoreObjects.firstNonNull(description, ""); description = CharMatcher.javaIsoControl().removeFrom(description); if (description.length() > MAX_DESCRIPTION) { description = description.substring(0, MAX_DESCRIPTION - Client.PADDING) + "..."; } return description; }
Source:
public void setWrongJsonAsTemplateFile() throws Exception { IRoute route = Mockito.mock(IRoute.class); when(route.getKind()).thenReturn(ResourceKind.ROUTE); when(factory.create(any(InputStream.class))).thenReturn(route); NotATemplateException ex = null; try { model.setLocalTemplateFileName("resources/jboss_infinispan-server_ImageStreamImport.json"); } catch (NotATemplateException e) { ex = e; assertEquals(ResourceKind.ROUTE, e.getResourceKind()); } assertNotNull(ex); }

Target:
public void setWrongJsonAsTemplateFile() throws Exception { IRoute route = Mockito.mock(IRoute.class); when(route.getKind()).thenReturn(ResourceKind.ROUTE); when(factory.create(any(InputStream.class))).thenReturn(route); try { model.setLocalTemplateFileName("resources/jboss_infinispan-server_ImageStreamImport.json"); fail("No NotATemplateException occurred"); } catch (NotATemplateException e) { assertEquals(ResourceKind.ROUTE, e.getResourceKind()); } }
Source:
public boolean canEditPipeline(String pipelineName, Username username) { return doesPipelineExist(pipelineName) && pipelineConfigNamed(new CaseInsensitiveString(pipelineName)).getOrigin().canEdit() && isUserAdminOfGroup(username.getUsername(), findGroupNameByPipeline(new CaseInsensitiveString(pipelineName))); }

Target:
public boolean canEditPipeline(String pipelineName, Username username) { PipelineConfig pipelineConfig; try { pipelineConfig = pipelineConfigNamed(new CaseInsensitiveString(pipelineName)); } catch (PipelineNotFoundException e) { return false; } return pipelineConfig != null && pipelineConfig.isLocal() && isUserAdminOfGroup(username.getUsername(), findGroupNameByPipeline(pipelineConfig.name())); }
Source:
private void exportMetacard(File dumpLocation, Metacard metacard) throws IOException, CatalogTransformerException { if (SERIALIZED_OBJECT_ID.matches(transformerId)) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(getOutputFile(dumpLocation, metacard)))) { oos.writeObject(new MetacardImpl(metacard)); oos.flush(); } } else { List<BinaryContent> binaryContents; if (metacard != null) { for (MultiMetacardTransformer transformer : transformers) { binaryContents = transformer.transform(Collections.singletonList(metacard), new HashMap<>()); if (CollectionUtils.isNotEmpty(binaryContents)) { try (FileOutputStream fos = new FileOutputStream(getOutputFile(dumpLocation, metacard))) { for (BinaryContent binaryContent : binaryContents) { fos.write(binaryContent.getByteArray()); } } break; } } } } }

Target:
private void exportMetacard(File dumpLocation, Metacard metacard) throws IOException, CatalogTransformerException { if (SERIALIZED_OBJECT_ID.matches(transformerId)) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(getOutputFile(dumpLocation, metacard)))) { oos.writeObject(new MetacardImpl(metacard)); oos.flush(); } } else { List<BinaryContent> binaryContents = getTransform() .transform( Collections.singletonList(metacard), transformerId, Collections.emptyMap()); if (CollectionUtils.isNotEmpty(binaryContents)) { if (binaryContents.size() == 1) { try (FileOutputStream fos = new FileOutputStream(getOutputFile(dumpLocation, metacard))) { fos.write(binaryContents.get(0).getByteArray()); } } else { createZip(binaryContents, dumpLocation, metacard); } } } }
Source:
public int getNumberOfEntries() { long flags = EnumUtil.bitSetOf(Flag.CACHE_MODE_LOCAL, Flag.SKIP_CACHE_LOAD); SizeCommand command = commandsFactory.buildSizeCommand(flags); return (Integer) invoker.invoke(icf.createInvocationContext(false, UNBOUNDED), command); }

Target:
public int getNumberOfEntries() { return cache.withFlags(Flag.CACHE_MODE_LOCAL).size(); }
Source:
private void waitTillRefCountZero() throws InterruptedException { if (isActive) { long singleWaitMs = Math.min(500, WAIT_TIME_FOR_CLEANUP_MS); long waitSoFar = 0; List<String> segmentsUnderCompaction = compactionLog.getCompactionDetails().getLogSegmentsUnderCompaction(); for (String segmentName : segmentsUnderCompaction) { while (srcLog.getSegment(segmentName).refCount() > 0 && waitSoFar < WAIT_TIME_FOR_CLEANUP_MS) { time.sleep(singleWaitMs); waitSoFar += singleWaitMs; } if (srcLog.getSegment(segmentName).refCount() > 0) { logger.debug("Ref count of in did not go down to 0", segmentName, dataDir); } } } }

Target:
private void waitTillRefCountZero() throws InterruptedException { if (isActive) { long singleWaitMs = Math.min(500, WAIT_TIME_FOR_CLEANUP_MS); long waitSoFar = 0; List<String> segmentsUnderCompaction = compactionLog.getCompactionDetails().getLogSegmentsUnderCompaction(); for (String segmentName : segmentsUnderCompaction) { while (srcLog.getSegment(segmentName).refCount() > 0 && waitSoFar < WAIT_TIME_FOR_CLEANUP_MS) { time.sleep(singleWaitMs); waitSoFar += singleWaitMs; } if (srcLog.getSegment(segmentName).refCount() > 0) { logger.debug("Ref count of in did not go down to 0", segmentName, storeId); } } } }
Source:
public void emit() { String src = group(1); String formatting = group(2); List<String> positional = new ArrayList<>(); positional.add("alt"); positional.add("width"); positional.add("height"); Map<String, String> properties = getFormattingProperties(formatting, positional); if (!properties.containsKey("alt") || properties.get("alt").isEmpty()) { int end = src.lastIndexOf("."); if (end != -1) { String firstSrc = src.substring(0, end); int start = Math.max(firstSrc.lastIndexOf("/") + 1, 0); properties.put("alt", firstSrc.substring(start)); } else { properties.put("alt", src); } } if (group(0).startsWith("image::")) { Attributes imageSpanAttributes = new Attributes(); imageSpanAttributes.setCssClass("imageblock"); builder.beginBlock(BlockType.DIV, imageSpanAttributes); Attributes contentAttr = new Attributes(); contentAttr.setCssClass("content"); builder.beginBlock(BlockType.DIV, contentAttr); emitImage(builder, src, properties); builder.endBlock(); if (properties.containsKey("title")) { Attributes attr = new Attributes(); attr.setCssClass("title"); builder.beginBlock(BlockType.DIV, attr); if (properties.containsKey("caption")) { builder.characters(properties.get("caption")); } builder.characters(properties.get("title")); builder.endBlock(); } builder.endBlock(); } else { Attributes imageblockattr = new Attributes(); imageblockattr.setCssClass("image"); builder.beginSpan(SpanType.SPAN, imageblockattr); emitImage(builder, src, properties); builder.endSpan(); } }

Target:
public void emit() { String src = group(1); String formatting = group(2); List<String> positional = new ArrayList<>(); positional.add("alt"); positional.add("width"); positional.add("height"); Map<String, String> properties = getFormattingProperties(formatting, positional); if (!properties.containsKey("alt") || properties.get("alt").isEmpty()) { int end = src.lastIndexOf("."); if (end != -1) { String firstSrc = src.substring(0, end); int start = Math.max(firstSrc.lastIndexOf("/") + 1, 0); properties.put("alt", firstSrc.substring(start)); } else { properties.put("alt", src); } } if (group(0).startsWith("image::")) { Attributes imageSpanAttributes = new Attributes(); imageSpanAttributes.setCssClass("imageblock"); builder.beginBlock(BlockType.DIV, imageSpanAttributes); Attributes contentAttr = new Attributes(); contentAttr.setCssClass("content"); builder.beginBlock(BlockType.DIV, contentAttr); emitImage(builder, src, properties); builder.endBlock(); if (properties.containsKey("title")) { Attributes attr = new Attributes(); attr.setCssClass("title"); builder.beginBlock(BlockType.DIV, attr); if (properties.containsKey("caption")) { builder.characters(properties.get("caption")); } builder.characters(properties.get("title")); builder.endBlock(); } builder.endBlock(); } else { Attributes imageBlockAttr = new Attributes(); imageBlockAttr.setCssClass("image"); builder.beginSpan(SpanType.SPAN, imageBlockAttr); emitImage(builder, src, properties); builder.endSpan(); } }
Source:
public void testWarningsParser() throws IOException { Collection<FileAnnotation> warnings = new ClangTidyParser().parse(openFile()); assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 5, warnings.size()); }

Target:
public void testWarningsParser() throws IOException { Collection<FileAnnotation> warnings = new ClangTidyParser().parse(openFile()); assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 6, warnings.size()); Iterator<FileAnnotation> iterator = warnings.iterator(); FileAnnotation annotation = iterator.next(); checkWarning(annotation, 1, 8, "implicit conversion changes signedness: 'int' to 'uint32_t' (aka 'unsigned int')", "src/../src/main.cpp", TYPE, "clang-diagnostic-sign-conversion", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 10, 20, "implicit conversion changes signedness: 'int' to 'uint32_t' (aka 'unsigned int')", "/src/main.cpp", TYPE, "clang-diagnostic-sign-conversion", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 83, 20, "implicit conversion changes signedness: 'int' to 'uint32_t' (aka 'unsigned int')", "/path/to/project/src/test2.cpp", TYPE, "clang-diagnostic-sign-conversion", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 25, 15, "suggest braces around initialization of subobject", "/path/to/project/src/test2.cpp", TYPE, "clang-diagnostic-missing-braces", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 29, 15, "suggest braces around initialization of subobject", "/path/to/project/src/test2.cpp", TYPE, "clang-diagnostic-missing-braces", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 4, 10, "'dbus/dbus.h' file not found", "/path/to/project/src/error_test.cpp", TYPE, "clang-diagnostic-error", Priority.HIGH); }
Source:
protected LockGranularityDeterminResult determineSegmentGranularity( TaskActionClient client, List<Interval> intervals ) throws IOException { if (requireLockExistingSegments()) { if (isPerfectRollup()) { log.info("Using timeChunk lock for perfrect rollup"); return new LockGranularityDeterminResult(LockGranularity.TIME_CHUNK, intervals, null); } else if (!intervals.isEmpty()) { return determineSegmentGranularity(findSegmentsToLock(client, intervals)); } else { log.info("Using segment lock for empty intervals"); return new LockGranularityDeterminResult(LockGranularity.SEGMENT, null, Collections.emptyList()); } } else { log.info("Using segment lock since we don't have to lock existing segments"); return new LockGranularityDeterminResult(LockGranularity.SEGMENT, null, Collections.emptyList()); } }

Target:
private LockGranularityDetermineResult determineSegmentGranularity(TaskActionClient client, List<Interval> intervals) throws IOException { if (requireLockExistingSegments()) { if (isPerfectRollup()) { log.info("Using timeChunk lock for perfect rollup"); return new LockGranularityDetermineResult(LockGranularity.TIME_CHUNK, intervals, null); } else if (!intervals.isEmpty()) { return determineSegmentGranularity(findSegmentsToLock(client, intervals)); } else { log.info("Using segment lock for empty intervals"); return new LockGranularityDetermineResult(LockGranularity.SEGMENT, null, Collections.emptyList()); } } else { log.info("Using segment lock since we don't have to lock existing segments"); return new LockGranularityDetermineResult(LockGranularity.SEGMENT, null, Collections.emptyList()); } }
Source:
public LoginResponse login(@Valid @RequestBody LoginRequest login, HttpServletRequest request) { if (login == null) { throw new HttpMessageNotReadableException("Missing login"); } if (userIs2fa()) { throw new BadCredentialsException( format("2 factor authentication is [ {0} ], you cannot login via the RESTAPI anymore", appSettings.getTwoFactorAuthentication())); } return runAsSystem(() -> { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()); authToken.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = authenticationManager.authenticate(authToken); if (!authentication.isAuthenticated()) { throw new BadCredentialsException("Unknown username or password"); } User user = dataService.findOne(USER, new QueryImpl<User>().eq(UserMetaData.USERNAME, authentication.getName()), User.class); SecurityContextHolder.getContext().setAuthentication(authentication); String token = tokenService.generateAndStoreToken(authentication.getName(), "Rest api login"); return new LoginResponse(token, user.getUsername(), user.getFirstName(), user.getLastName()); }); }

Target:
public LoginResponse login(@Valid @RequestBody LoginRequest login, HttpServletRequest request) { if (login == null) { throw new HttpMessageNotReadableException("Missing login"); } if (userIs2fa()) { throw new BadCredentialsException( "2 factor authentication is enabled, you cannot use /login via the RESTAPI anymore"); } return runAsSystem(() -> { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()); authToken.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = authenticationManager.authenticate(authToken); if (!authentication.isAuthenticated()) { throw new BadCredentialsException("Unknown username or password"); } User user = dataService.findOne(USER, new QueryImpl<User>().eq(UserMetaData.USERNAME, authentication.getName()), User.class); SecurityContextHolder.getContext().setAuthentication(authentication); String token = tokenService.generateAndStoreToken(authentication.getName(), "Rest api login"); return new LoginResponse(token, user.getUsername(), user.getFirstName(), user.getLastName()); }); }
Source:
public GraphiteEvent druidEventToGraphite(ServiceMetricEvent serviceMetricEvent) { ImmutableList.Builder metricPathBuilder = new ImmutableList.Builder<String>(); metricPathBuilder.add(GraphiteEmitter.sanitize(this.getNamespacePrefix())); if (this.isIgnoreServiceName() == false) { metricPathBuilder.add(GraphiteEmitter.sanitize(serviceMetricEvent.getService())); } if (this.isIgnoreHostname() == false) { metricPathBuilder.add(GraphiteEmitter.sanitize(serviceMetricEvent.getHost())); } ImmutableSortedSet<String> dimNames = ImmutableSortedSet.copyOf(serviceMetricEvent.getUserDims().keySet()); for (String dimName : dimNames) { metricPathBuilder.add(GraphiteEmitter.sanitize(String.valueOf(serviceMetricEvent.getUserDims() .get(dimName)))); } metricPathBuilder.add(GraphiteEmitter.sanitize(serviceMetricEvent.getMetric())); return new GraphiteEvent( Joiner.on(".").join(metricPathBuilder.build()), serviceMetricEvent.getValue().toString(), TimeUnit.MILLISECONDS.toSeconds(serviceMetricEvent.getCreatedTime().getMillis()) ); }

Target:
public GraphiteEvent druidEventToGraphite(ServiceMetricEvent serviceMetricEvent) { ImmutableList.Builder metricPathBuilder = new ImmutableList.Builder<String>(); metricPathBuilder.add(this.getNamespacePrefix()); if (!this.isIgnoreServiceName()) { metricPathBuilder.add(GraphiteEmitter.sanitize(serviceMetricEvent.getService())); } if (!this.isIgnoreHostname()) { metricPathBuilder.add(GraphiteEmitter.sanitize(serviceMetricEvent.getHost())); } ImmutableSortedSet<String> dimNames = ImmutableSortedSet.copyOf(serviceMetricEvent.getUserDims().keySet()); for (String dimName : dimNames) { metricPathBuilder.add(GraphiteEmitter.sanitize(String.valueOf(serviceMetricEvent.getUserDims() .get(dimName)))); } metricPathBuilder.add(GraphiteEmitter.sanitize(serviceMetricEvent.getMetric())); return new GraphiteEvent( Joiner.on(".").join(metricPathBuilder.build()), serviceMetricEvent.getValue().toString(), TimeUnit.MILLISECONDS.toSeconds(serviceMetricEvent.getCreatedTime().getMillis()) ); }
Source:
public void validate() { validateDictionaries(allWordsDictionaries); validateDictionaries(wordEndDictionaries); validateDictionaries(wordEndDictionaries); validateDictionaries(wordEndDictionaries); }

Target:
public void validate() { validateDictionaries(allWordsDictionaries); validateDictionaries(wordDictionaries); validateDictionaries(wordStartDictionaries); validateDictionaries(wordEndDictionaries); }
Source:
public static void connectStepTwo(final long siteId, long keyringConnectionId, final String serviceId, final String externalUserId) { RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { AppLog.d(AppLog.T.SHARING, "connect succeeded"); PublicizeConnection connection = PublicizeConnection.fromJson(jsonObject); PublicizeTable.addOrUpdateConnection(connection); EventBus.getDefault().post(new ActionCompleted(true, ConnectAction.CONNECT, serviceId)); } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { AppLog.e(AppLog.T.SHARING, volleyError); EventBus.getDefault().post(new ActionCompleted(false, ConnectAction.CONNECT, serviceId)); } }; Map<String, String> params = new HashMap<>(); params.put("keyring_connection_ID", Long.toString(keyringConnectionId)); if (!externalUserId.isEmpty() && !serviceId.equals(PublicizeConstants.TWITTER_ID)) { params.put("external_user_ID", externalUserId); } String path = String.format(Locale.ROOT, "/sites/%d/publicize-connections/new", siteId); WordPress.getRestClientUtilsV1_1().post(path, params, null, listener, errorListener); }

Target:
public static void connectStepTwo(final long siteId, long keyringConnectionId, final String serviceId, final String externalUserId) { RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { AppLog.d(AppLog.T.SHARING, "connect succeeded"); PublicizeConnection connection = PublicizeConnection.fromJson(jsonObject); PublicizeTable.addOrUpdateConnection(connection); EventBus.getDefault().post(new ActionCompleted(true, ConnectAction.CONNECT, serviceId)); } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { AppLog.e(AppLog.T.SHARING, volleyError); EventBus.getDefault().post(new ActionCompleted(false, ConnectAction.CONNECT, serviceId)); } }; Map<String, String> params = new HashMap<>(); params.put("keyring_connection_ID", Long.toString(keyringConnectionId)); if (!TextUtils.isEmpty(externalUserId) && !PublicizeConstants.TWITTER_ID.equals(serviceId)) { params.put("external_user_ID", externalUserId); } String path = String.format(Locale.ROOT, "/sites/%d/publicize-connections/new", siteId); WordPress.getRestClientUtilsV1_1().post(path, params, null, listener, errorListener); }
Source:
public static double topologyWorkerCpu(Map conf, TopologyDetails info) { Map topologyConfig = getFullTopologyConfig(conf, info); Object cpuObject = topologyConfig.get(WORKER_CPU_CONF); double topologyWorkerCpu = DEFAULT_WORKER_CPU; if (cpuObject != null && !(cpuObject instanceof Number)) { LOG.warn("Topology has invalid mesos cpu configuration: has type {}, when it should be a Number", info.getId(), cpuObject, cpuObject.getClass()); } else if (cpuObject != null && (cpuObject instanceof Number)) { topologyWorkerCpu = ((Number) cpuObject).doubleValue(); if (topologyWorkerCpu < MESOS_MIN_CPU) { LOG.warn("Topology has invalid mesos cpu configuration: is below which is the mesos minimum", info.getId(), topologyWorkerCpu, MESOS_MIN_CPU); topologyWorkerCpu = DEFAULT_WORKER_CPU; } } return topologyWorkerCpu; }

Target:
public static double topologyWorkerCpu(Map conf, TopologyDetails info) { Map topologyConfig = getFullTopologyConfig(conf, info); double topologyWorkerCpu = getScalarTopologyConf(topologyConfig, WORKER_CPU_CONF, info.getId(), DEFAULT_WORKER_CPU).doubleValue(); if (topologyWorkerCpu < MESOS_MIN_CPU) { LOG.warn("Topology has invalid option \'{}\' -- is below {}, which is the minimum defined by Mesos -- Falling back to default of {}", info.getId(), WORKER_CPU_CONF, topologyWorkerCpu, MESOS_MIN_CPU, DEFAULT_WORKER_CPU); topologyWorkerCpu = DEFAULT_WORKER_CPU; } return topologyWorkerCpu; }
Source:
private void createKioskMenu(Menu menu, MenuInflater menuInflater) throws Exception { StreamingService service = NewPipe.getService(currentServiceId); KioskList kl = service.getKioskList(); int i = 0; for(final String ks : kl.getAvailableKisoks()) { menu.add(0, KIOSK_MENU_OFFSETT + i, Menu.NONE, KioskTranslator.getTranslatedKioskName(ks, getContext())) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { try { NavigationHelper.openKioskFragment(getFragmentManager(), currentServiceId, ks); } catch (Exception e) { ErrorActivity.reportError(activity, e, activity.getClass(), null, ErrorActivity.ErrorInfo.make(UserAction.UI_ERROR, "none", "", R.string.app_ui_crash)); } return true; } }); i++; } }

Target:
private void createKioskMenu(Menu menu, MenuInflater menuInflater) throws Exception { StreamingService service = NewPipe.getService(currentServiceId); KioskList kl = service.getKioskList(); int i = 0; for(final String ks : kl.getAvailableKiosks()) { menu.add(0, KIOSK_MENU_OFFSETT + i, Menu.NONE, KioskTranslator.getTranslatedKioskName(ks, getContext())) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { try { NavigationHelper.openKioskFragment(getFragmentManager(), currentServiceId, ks); } catch (Exception e) { ErrorActivity.reportError(activity, e, activity.getClass(), null, ErrorActivity.ErrorInfo.make(UserAction.UI_ERROR, "none", "", R.string.app_ui_crash)); } return true; } }); i++; } }
Source:
public AssertChecker(Dim[] dimensions) { fDimensions = new HashSet<Dim>(); fDimensions.addAll(Arrays.asList(dimensions)); }

Target:
public AssertChecker(Dim[] dimensions) { fDimensions = new HashSet<>(); fDimensions.addAll(Arrays.asList(dimensions)); }
Source:
public static ErraiService initSingleton(final ErraiServiceConfigurator configurator) { synchronized (monitor) { if (isInitialized()) throw new IllegalStateException("service already set into singleton"); service = ErraiServiceFactory.create(configurator); if(!initProxy.isClosed()) { initProxy.closeProxy(service); } for (ErraiInitCallback erraiInitCallback : callbackList) { erraiInitCallback.onInit(service); } callbackList.clear(); return service; } }

Target:
public static ErraiService initSingleton(final ErraiServiceConfigurator configurator) { synchronized (monitor) { if (isActive()) throw new IllegalStateException("service already set into singleton"); service = ErraiServiceFactory.create(configurator); proxy.closeProxy(service); Iterator<InitCallbackBlock> it = callbacks.iterator(); while(it.hasNext()) { InitCallbackBlock block = it.next(); block.callback.onInit(service); if(!block.persistent) { it.remove(); } } return service; } }