auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isValid(Schema schema, IndexingConfig indexingConfig) { List<String> sortedColumns = indexingConfig.getSortedColumn(); boolean isValid = true; if (CollectionUtils.isNotEmpty(sortedColumns)) { final String sortedColumn = sortedColumns.get(0); if (sortedColumns.size() > 1) { _logger.warn("More than one sorted column configured. Using {}", sortedColumn); } FieldSpec fieldSpec = schema.getFieldSpecFor(sortedColumn); if (!fieldSpec.isSingleValueField()) { _logger.error("Cannot configure multi-valued column as sorted column", sortedColumn); isValid = false; } } try { SchemaUtils.validate(schema); } catch (Exception e) { isValid = false; } return isValid; }

Target:
private boolean isValid(Schema schema, IndexingConfig indexingConfig) { List<String> sortedColumns = indexingConfig.getSortedColumn(); boolean isValid = true; if (CollectionUtils.isNotEmpty(sortedColumns)) { final String sortedColumn = sortedColumns.get(0); if (sortedColumns.size() > 1) { _logger.warn("More than one sorted column configured. Using {}", sortedColumn); } FieldSpec fieldSpec = schema.getFieldSpecFor(sortedColumn); if (!fieldSpec.isSingleValueField()) { _logger.error("Cannot configure multi-valued column as sorted column", sortedColumn); isValid = false; } } try { SchemaUtils.validate(schema); } catch (Exception e) { _logger.error("Caught exception while validating schema: {}", schema.getSchemaName(), e); isValid = false; } return isValid; }
Source:
private void parseHeader(ParsableByteArray data) { String currentLine; while ((currentLine = data.readLine()) != null) { if (currentLine.startsWith("PlayResX:")) { playResX = Integer.valueOf(currentLine.substring(9).trim()); } if (currentLine.startsWith("PlayResY:")) { playResY = Integer.valueOf(currentLine.substring(9).trim()); } if (currentLine.startsWith("[Events]")) { return; } } }

Target:
private void parseHeader(ParsableByteArray data) { String currentLine; while ((currentLine = data.readLine()) != null) { if (currentLine.startsWith("PlayResX:")) { playResX = Integer.valueOf(currentLine.substring("PlayResX:".length()).trim()); } if (currentLine.startsWith("PlayResY:")) { playResY = Integer.valueOf(currentLine.substring("PlayResY:".length()).trim()); } if (currentLine.startsWith("[Events]")) { return; } } }
Source:
public void closeMoreInfoAboutEqualShareModal() { WebElement closeButton = browser.driver.findElement(By .xpath(" waitForElementToBeClickable(closeButton); click(closeButton); waitForElementToDisappear(By.id("more-info-equal-share-modal")); }

Target:
private void closeMoreInfoAboutEqualShareModal() { WebElement closeButton = browser.driver .findElement(By.xpath(" waitForElementToBeClickable(closeButton); click(closeButton); waitForElementToDisappear(By.id("more-info-equal-share-modal")); }
Source:
protected VDSReturnValue getAllVmStats() { VDSReturnValue returnValue = new VDSReturnValue(); try { V1VirtualMachineInstanceList result = listVMIs(vdsManager.getVdsName()); log.debug("got:\n{}", result); List<V1VirtualMachineInstance> vmis = result.getItems(); List<VdsmVm> vms = vmis.stream() .map(this::toVdsmVm) .filter(Objects::nonNull) .collect(Collectors.toList()); returnValue.setReturnValue(vms); returnValue.setSucceeded(true); } catch (Exception e) { if (ApiException.class.isInstance(e)) { KubevirtUtils.auditAuthorizationIssues((ApiException) e, auditLogDirector, providerDao.get(vdsManager.getClusterId())); } log.error("failed to retrieve kubevirt VMs for node {}: {}", vdsManager.getVdsName(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } return returnValue; }

Target:
protected VDSReturnValue getAllVmStats() { VDSReturnValue returnValue = new VDSReturnValue(); try { V1VirtualMachineInstanceList result = listVMIs(vdsManager.getVdsName()); log.debug("got:\n{}", result); List<V1VirtualMachineInstance> vmis = result.getItems(); List<VdsmVm> vms = vmis.stream() .map(this::toVdsmVm) .filter(Objects::nonNull) .collect(Collectors.toList()); returnValue.setReturnValue(vms); returnValue.setSucceeded(true); } catch (Exception e) { if (ApiException.class.isInstance(e)) { KubevirtAuditUtils.auditAuthorizationIssues((ApiException) e, auditLogDirector, providerDao.get(vdsManager.getClusterId())); } log.error("failed to retrieve kubevirt VMs for node {}: {}", vdsManager.getVdsName(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } return returnValue; }
Source:
public boolean validateKeyStore(KeyStore store) { try { Enumeration<String> aliases = store.aliases(); boolean res = true; while(aliases.hasMoreElements()) { String alias = aliases.nextElement(); logger.debug("Alias : " + alias); res = res && validateKeyFromKeyStore(store, alias); } logger.debug("KeyStore is valid: " + res); return res; } catch (KeyStoreException e) { logger.error("The KeyStore is not initialized", e); return false; } }

Target:
public void validateKeyStore(KeyStore store) throws KeyStoreException, CertificateExpiredException, CertificateNotYetValidException { Enumeration<String> aliases = store.aliases(); while(aliases.hasMoreElements()) { String alias = aliases.nextElement(); validateKeyFromKeyStore(store, alias); } }
Source:
static Integer resolveHistoricalNullIfNeeded(@Nullable Integer val) { return (val == null || val == HISTORICAL_NULL) ? null : val; }

Target:
static Integer resolveHistoricalNullIfNeeded(@Nullable Integer val) { return isEffectivelyNull(val) ? null : val; }
Source:
private static PushCertificate read(TreeWalk tw) throws IOException { if (tw == null || (tw.getRawMode(0) & FileMode.TYPE_FILE) == 0) { return null; } ObjectLoader loader = tw.getObjectReader().open(tw.getObjectId(0), OBJ_BLOB); try (InputStream in = loader.openStream(); Reader r = new BufferedReader(new InputStreamReader(in))) { return PushCertificateParser.fromReader(r); } }

Target:
private static PushCertificate read(TreeWalk tw) throws IOException { if (tw == null || (tw.getRawMode(0) & TYPE_FILE) != TYPE_FILE) { return null; } ObjectLoader loader = tw.getObjectReader().open(tw.getObjectId(0), OBJ_BLOB); try (InputStream in = loader.openStream(); Reader r = new BufferedReader(new InputStreamReader(in, UTF_8))) { return PushCertificateParser.fromReader(r); } }
Source:
public static File makeMetricFile(File dir, String metricName, ByteOrder order) { return new File(dir, StringUtils.safeFormat("met_%s_%s.drd", metricName, order)); }

Target:
public static File makeMetricFile(File dir, String metricName, ByteOrder order) { return new File(dir, StringUtils.format("met_%s_%s.drd", metricName, order)); }
Source:
public void verifyResolverResolvesWithFileUri() throws Exception { val props = new SamlIdPProperties(); val resolver = new JsonResourceMetadataResolver(props, openSamlConfigBean); assertNotNull(resolver); }

Target:
public void verifyResolverResolvesWithFileUri() throws Exception { val props = new SamlIdPProperties(); props.getMetadata().setLocation("file:/etc/cas/saml"); val resolver = new JsonResourceMetadataResolver(props, openSamlConfigBean); assertNotNull(resolver); }
Source:
protected void buildScript(int age) { if (age == 0) { init(); } addPendingClient(new BecauseYouReadClient()); addPendingClient(new ContinueReadingClient()); addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new IntegerListClient()); addPendingClient(new MostReadClient()); addPendingClient(new RandomClient(new RandomCard(getContext(), getSite()))); }

Target:
protected void buildScript(int age) { if (age == 0) { init(); } addPendingClient(new BecauseYouReadClient()); addPendingClient(new ContinueReadingClient()); addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new IntegerListClient()); addPendingClient(new MostReadClient()); addPendingClient(new RandomClient()); }
Source:
public static int findElement(final JSONArray array, final String element) { for (int i = 0; i < array.length(); i++) { if (element.equals(array.getString(i))) { return i; } } return -1; }

Target:
private static int findElement(final JSONArray array, final String element) { for (int i = 0; i < array.length(); i++) { if (element.equals(array.getString(i))) { return i; } } return -1; }
Source:
private void maybeRemoveStatisticsFromMetricsRecorder() { if (isRecordingLevelDebug) { metricsRecorder.removeStatistics(name); isRecordingLevelDebug = false; } }

Target:
private void maybeRemoveStatisticsFromMetricsRecorder() { if (isStatisticsRegistered) { metricsRecorder.removeStatistics(name); isStatisticsRegistered = false; } }
Source:
private boolean isOwnedTransaction() { TransactionAdapter transaction = (TransactionAdapter) TransactionCoordination.getInstance().getTransaction(); if (transaction == null || !transaction.getComponentLocation().isPresent()) { return false; } String transactionLocation = transaction.getComponentLocation().get().getLocation(); if (this.getLocation() == null) { if (flowLocation.isPresent()) { return transactionLocation.equals(flowLocation.get().toString()); } else { return sameRootContainerLocation(transaction); } } if (isTransactionInGlobalErrorHandler((transaction))) { return true; } else if (flowLocation.isPresent()) { return false; } String errorHandlerLocation = this.getLocation().getLocation(); if (!errorHandlerLocation.matches(".*/.*/.*")) { return sameRootContainerLocation(transaction); } errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); return (sameRootContainerLocation(transaction) && errorHandlerLocation.equals(transactionLocation)); }

Target:
private boolean isOwnedTransaction() { TransactionAdapter transaction = (TransactionAdapter) TransactionCoordination.getInstance().getTransaction(); if (transaction == null || !transaction.getComponentLocation().isPresent()) { return false; } if (inDefaultErrorHandler()) { return defaultErrorHandlerOwnsTransaction(transaction); } else if (isTransactionInGlobalErrorHandler((transaction))) { return true; } else if (flowLocation.isPresent()) { return false; } else { String errorHandlerLocation = this.getLocation().getLocation(); if (!ERROR_HANDLER_LOCATION_PATTERN.matcher(errorHandlerLocation).find()) { return sameRootContainerLocation(transaction); } String transactionLocation = transaction.getComponentLocation().get().getLocation(); errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); return (sameRootContainerLocation(transaction) && errorHandlerLocation.equals(transactionLocation)); } }
Source:
public boolean handles(String s) { return s.startsWith(CloudHandler.CLOUD_PREFIX_BOX) || s.startsWith(CloudHandler.CLOUD_PREFIX_DROPBOX) || s.startsWith(CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE) || s.startsWith(CloudHandler.CLOUD_PREFIX_ONE_DRIVE) || s.startsWith("smb:/") || s.startsWith("sftp:/"); }

Target:
public boolean handles(String s) { return s.startsWith(CloudHandler.CLOUD_PREFIX_BOX) || s.startsWith(CloudHandler.CLOUD_PREFIX_DROPBOX) || s.startsWith(CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE) || s.startsWith(CloudHandler.CLOUD_PREFIX_ONE_DRIVE) || s.startsWith("smb:/") || s.startsWith("ssh:/"); }
Source:
private MavenProject findProjectFromReactor(final Dependency d) { VersionRange depVersionAsRange; try { depVersionAsRange = VersionRange.createFromVersionSpec(d.getVersion()); } catch (InvalidVersionSpecificationException e) { throw new IllegalStateException("Could not parse the version of the dependency even though Maven" + " could: " + d); } for (final MavenProject p : reactorProjects) { DefaultArtifactVersion pv = new DefaultArtifactVersion(p.getVersion()); if (p.getGroupId().equals(d.getGroupId()) && p.getArtifactId().equals(d.getArtifactId()) && depVersionAsRange.containsVersion(pv)) { return p; } } return null; }

Target:
private MavenProject findProjectFromReactor(final Dependency d) { final VersionRange depVersionAsRange; try { depVersionAsRange = VersionRange .createFromVersionSpec(d.getVersion()); } catch (InvalidVersionSpecificationException e) { throw new AssertionError(e); } for (final MavenProject p : reactorProjects) { final DefaultArtifactVersion pv = new DefaultArtifactVersion( p.getVersion()); if (p.getGroupId().equals(d.getGroupId()) && p.getArtifactId().equals(d.getArtifactId()) && depVersionAsRange.containsVersion(pv)) { return p; } } return null; }
Source:
private static boolean loadSourceFiles(ISessionInfoVisitor infoStore, IExecutionDataVisitor dataStore, File... reports) { Boolean isCurrentVersionFormat = null; for (File report : reports) { if (report.isFile()) { try { JacocoReportReader jacocoReportReader = new JacocoReportReader(report).readJacocoReport(dataStore, infoStore); isCurrentVersionFormat = jacocoReportReader.useCurrentBinaryFormat(); } catch (IOException e) { throw new SonarException(String.format("Unable to read %s", report.getAbsolutePath()), e); } } } return BooleanUtils.isNotFalse(isCurrentVersionFormat); }

Target:
private static boolean loadSourceFiles(ISessionInfoVisitor infoStore, IExecutionDataVisitor dataStore, File... reports) { Boolean isCurrentVersionFormat = null; for (File report : reports) { if (report.isFile()) { JacocoReportReader jacocoReportReader = new JacocoReportReader(report).readJacocoReport(dataStore, infoStore); boolean reportFormatIsCurrent = jacocoReportReader.useCurrentBinaryFormat(); if (isCurrentVersionFormat == null) { isCurrentVersionFormat = reportFormatIsCurrent; } else if (!isCurrentVersionFormat.equals(reportFormatIsCurrent)) { throw new IllegalStateException("You are trying to merge two different JaCoCo binary formats. Please use only one version of JaCoCo."); } } } return BooleanUtils.isNotFalse(isCurrentVersionFormat); }
Source:
public IArtifactType getArtifactType(IAtsWorkItem workItem) { return ((Artifact) workItem.getStoreObject()).getArtifactType(); }

Target:
public IArtifactType getArtifactType(IAtsWorkItem workItem) { Assert.isNotNull(workItem, "Work Item can not be null"); return ((Artifact) workItem.getStoreObject()).getArtifactType(); }
Source:
protected void startProcess(ExecutorDriver driver, Task task) { if (task.process == null) { try { task.run(); redirectProcess(task.process); scheduleHealthCheck(driver, task.executableInfo.hostname(), task.executableInfo.httpPort()); try { Thread.sleep(10000); task.process.exitValue(); fail(driver); } catch (InterruptedException | IllegalThreadStateException e) { LOGGER.debug("task still running after 10s"); } } catch (IOException e) { LOGGER.error("Failed to run command", e); fail(driver); } } else { LOGGER.error("Tried to start process, but process already running"); } }

Target:
protected void startProcess(ExecutorDriver driver, Task task) { if (task.process == null) { try { task.run(); redirectProcess(task.process); try { Thread.sleep(10000); task.process.exitValue(); fail(driver); } catch (InterruptedException | IllegalThreadStateException e) { LOGGER.debug("task still running after 10s"); } } catch (IOException e) { LOGGER.error("Failed to run command", e); fail(driver); } } else { LOGGER.error("Tried to start process, but process already running"); } }
Source:
protected IProject getOrCreateProject(ILangProjectSupport projectSupport, String projectName, String targetLanguage) throws TransformationException { IProject genProject = ProjectManagement.getNamedProject(projectName); if ((genProject == null) || !genProject.exists()) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject[] projectsBeforeCreation = root.getProjects(); genProject = projectSupport.createProject(projectName); try { root.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); IProject[] projectsAfterCreation = root.getProjects(); boolean found = false; for(int i=0;i<projectsBeforeCreation.length; i++){ if(!projectsAfterCreation[i].getName().equals(projectsBeforeCreation[i].getName())){ genProject = projectsAfterCreation[i]; found = true; break; } } if((found == false) && (projectsBeforeCreation.length < projectsAfterCreation.length)){ genProject = projectsAfterCreation[projectsAfterCreation.length -1]; } } catch (CoreException e) { e.printStackTrace(); } if ((genProject == null) || !genProject.exists()) { if(targetLanguage.equals("Java")){ throw new RuntimeException("Could not create JDT project. This might indicate that there is a problem with your JDT installation."); }else if(targetLanguage.equals("C++")){ throw new RuntimeException("Could not create CDT project. This might indicate that there is a problem with your CDT installation."); } } UIContext.configureProject = true; } return genProject; }

Target:
protected IProject getOrCreateProject(ILangProjectSupport projectSupport, String projectName, String targetLanguage) throws TransformationException { IProject genProject = ProjectManagement.getNamedProject(projectName); if ((genProject == null) || !genProject.exists()) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject[] projectsBeforeCreation = root.getProjects(); genProject = projectSupport.createProject(projectName); try { root.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); IProject[] projectsAfterCreation = root.getProjects(); boolean found = false; for (int i = 0; i < projectsBeforeCreation.length; i++) { if (!projectsAfterCreation[i].getName().equals(projectsBeforeCreation[i].getName())) { genProject = projectsAfterCreation[i]; found = true; break; } } if ((found == false) && (projectsBeforeCreation.length < projectsAfterCreation.length)) { genProject = projectsAfterCreation[projectsAfterCreation.length - 1]; } } catch (CoreException e) { e.printStackTrace(); } if ((genProject == null) || !genProject.exists()) { throw new RuntimeException( "Could not create "+ targetLanguage +" project. This might indicate that there is a problem with your "+ targetLanguage +" installation."); } UIContext.configureProject = true; } return genProject; }
Source:
private void allTags() { allTags = new ArrayList<TagDto>(); SessionDataService.Async.getInstance().getAllTags(new AsyncCallback<List<TagDto>>() { @Override public void onFailure(Throwable throwable) { new ExceptionPanel("Fail to save data: " + throwable.getMessage()); } @Override public void onSuccess(List<TagDto> tagDtos) { allTags.addAll(tagDtos); allTagsLoadComplete = true; } }); }

Target:
private void allTags() { allTags = new ArrayList<TagDto>(); SessionDataService.Async.getInstance().getAllTags(new AsyncCallback<List<TagDto>>() { @Override public void onFailure(Throwable throwable) { new ExceptionPanel("Fail to fetch all tags from the database: " + throwable.getMessage()); } @Override public void onSuccess(List<TagDto> tagDtos) { allTags.addAll(tagDtos); allTagsLoadComplete = true; } }); }
Source:
public List<String> setUGI(String userName, List<String> groupNames) { groupNames.add(userName); return groupNames; }

Target:
public List<String> setUGI(String userName, List<String> groupNames) { List<String> result = new ArrayList(groupNames); result.add(userName); return result; }
Source:
public synchronized void loadProperties() { Properties properties = checkNotNull(home).getProperties("system.conf"); properties.put("NGRINDER_HOME", home.getDirectory().getAbsolutePath()); if (exHome.exists()) { Properties exProperties = exHome.getProperties("system-ex.conf"); if (exProperties.isEmpty()) { exProperties = exHome.getProperties("system.conf"); } properties.putAll(exProperties); } properties.putAll(System.getProperties()); controllerProperties = new PropertiesWrapper(properties, controllerPropertiesKeyMapper); System.setProperty("ngrinder.lib.path", getCurrentUnpackedFolder()); clusterProperties = new PropertiesWrapper(properties, clusterPropertiesKeyMapper); }

Target:
public synchronized void loadProperties() { Properties properties = checkNotNull(home).getProperties("system.conf"); properties.put("NGRINDER_HOME", home.getDirectory().getAbsolutePath()); if (exHome.exists()) { Properties exProperties = exHome.getProperties("system-ex.conf"); if (exProperties.isEmpty()) { exProperties = exHome.getProperties("system.conf"); } properties.putAll(exProperties); } properties.putAll(System.getProperties()); controllerProperties = new PropertiesWrapper(properties, controllerPropertiesKeyMapper); clusterProperties = new PropertiesWrapper(properties, clusterPropertiesKeyMapper); }
Source:
public void restoreAll(int itemcount){ if (excludedFolders.size()!=0){ for (int i=0;i<itemcount;i++){ h.clearAlbumExclude(excludedFolders.remove(0).getAbsolutePath()); } Toast.makeText(ExcludedAlbumsActivity.this,"All folders are restored!",Toast.LENGTH_SHORT).show(); finish(); } }

Target:
public void restoreAll(int itemcount){ if (excludedFolders.size()!=0){ for (int i=0;i<itemcount;i++){ h.clearAlbumExclude(excludedFolders.remove(0).getAbsolutePath()); } SnackBarHandler.show(findViewById(R.id.rl_ea), "All folders are restored", Snackbar.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); } },1000); } }
Source:
public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { boolean hasComma = false; int length = this.length(); writer.write('['); if (length == 1) { try { JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: 0", e); } } else if (length != 0) { final int newIndent = indent + indentFactor; for (int i = 0; i < length; i += 1) { if (hasComma) { writer.write(','); } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, newIndent); try { JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newIndent); } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: " + i, e); } hasComma = true; } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, indent); } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }

Target:
public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { boolean needsComma = false; int length = this.length(); writer.write('['); if (length == 1) { try { JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: 0", e); } } else if (length != 0) { final int newIndent = indent + indentFactor; for (int i = 0; i < length; i += 1) { if (needsComma) { writer.write(','); } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, newIndent); try { JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newIndent); } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: " + i, e); } needsComma = true; } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, indent); } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }
Source:
public ImmutableValue<Boolean> adult() { return new ImmutableSpongeValue<>(Keys.ADULT, this.adult); }

Target:
public ImmutableValue<Boolean> adult() { return ImmutableSpongeValue.cachedOf(Keys.IS_ADULT, true, this.adult); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_paged_list_shrink_view); CarToolbar toolbar = findViewById(R.id.car_toolbar); toolbar.setTitle(R.string.paged_list_view_title); toolbar.setNavigationIconOnClickListener(v -> finish()); PagedListView pagedListView = findViewById(R.id.paged_list_view); pagedListView.setAdapter(new DemoAdapter()); RadioGroup radioGroup = findViewById(R.id.radiogroup); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { ViewGroup.LayoutParams params = pagedListView.getLayoutParams(); switch(checkedId) { case R.id.radio1: params.height = 50; break; case R.id.radio2: params.height = 150; break; case R.id.radio3: params.height = 250; break; } pagedListView.requestLayout(); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_paged_list_shrink_view); Resources res = this.getResources(); CarToolbar toolbar = findViewById(R.id.car_toolbar); toolbar.setTitle(R.string.paged_list_view_title); toolbar.setNavigationIconOnClickListener(v -> finish()); PagedListView pagedListView = findViewById(R.id.paged_list_view); pagedListView.setAdapter(new DemoAdapter()); RadioGroup radioGroup = findViewById(R.id.radiogroup); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { ViewGroup.LayoutParams params = pagedListView.getLayoutParams(); switch(checkedId) { case R.id.radio1: params.height = res.getDimensionPixelSize( androidx.car.R.dimen.car_padding_5); break; case R.id.radio2: params.height = 2 * res.getDimensionPixelSize( androidx.car.R.dimen.car_single_line_list_item_height); break; case R.id.radio3: params.height = 2 * res.getDimensionPixelSize( androidx.car.R.dimen.car_keyline_4); break; default: break; } pagedListView.requestLayout(); } }); }
Source:
@Override public void afterTest() { stripedExecSvc.shutdown(); if (origStarvationThreshold != null) System.setProperty(IGNITE_STRIPED_POOL_STARVATION_THRESHOLD, origStarvationThreshold); }

Target:
@Override public void afterTest() { stripedExecSvc.shutdown(); }
Source:
public void cleanUpOrphanConnectorTasks(boolean cleanUpOrphanTasksInConnector) { if (!_isLeader) { return; } Map<String, Set<DatastreamTask>> assignmentsByInstance = getAllAssignedDatastreamTasks(); Set<DatastreamTask> validTasks = assignmentsByInstance.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); List<String> allConnectors = getAllConnectors(); for (String connector : allConnectors) { Set<String> connectorTaskList = getConnectorTasks(connector); connectorTaskList.removeAll(validTasks.stream() .filter(x -> x.getConnectorType().equals(connector)) .map(DatastreamTask::getDatastreamTaskName) .collect(Collectors.toSet())); if (connectorTaskList.size() > 0) { LOG.warn("Found orphan tasks: in connector: {}", connectorTaskList, connector); if (cleanUpOrphanTasksInConnector) { connectorTaskList.forEach(t -> deleteConnectorTask(connector, t)); } } } }

Target:
public int cleanUpOrphanConnectorTasks(boolean cleanUpOrphanTasksInConnector) { if (!_isLeader) { return 0; } Map<String, Set<DatastreamTask>> assignmentsByInstance = getAllAssignedDatastreamTasks(); Set<DatastreamTask> validTasks = assignmentsByInstance.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); List<String> allConnectors = getAllConnectors(); int orphanCount = 0; for (String connector : allConnectors) { Set<String> connectorTaskList = getConnectorTasks(connector); connectorTaskList.removeAll(validTasks.stream() .filter(x -> x.getConnectorType().equals(connector)) .map(DatastreamTask::getDatastreamTaskName) .collect(Collectors.toSet())); if (connectorTaskList.size() > 0) { LOG.warn("Found orphan tasks: in connector: {}", connectorTaskList, connector); if (cleanUpOrphanTasksInConnector) { connectorTaskList.forEach(t -> deleteConnectorTask(connector, t)); } } orphanCount += connectorTaskList.size(); } return orphanCount; }
Source:
public void testTransformItemWithEventRefs() { given(idCodec.decode("12345")).willReturn(BigInteger.valueOf(12345)); given(idCodec.decode("1234")).willReturn(BigInteger.valueOf(1234)); org.atlasapi.media.entity.Item complex = transformer.transform(getItemWithEventRefs()); assertEquals(1, complex.events().size()); assertThat(complex.events().get(0).id(), is(1234L)); }

Target:
public void testTransformItemWithEventRefs() { when(idCodec.decode("12345")).thenReturn(BigInteger.valueOf(12345)); when(idCodec.decode("1234")).thenReturn(BigInteger.valueOf(1234)); org.atlasapi.media.entity.Item complex = transformer.transform(getItemWithEventRefs()); assertEquals(1, complex.events().size()); assertThat(complex.events().get(0).id(), is(1234L)); }
Source:
public boolean onStopJob(JobParameters params) { AppLog.i(AppLog.T.READER, "reader service > stopped"); jobFinished(params, false); return false; }

Target:
public boolean onStopJob(JobParameters params) { AppLog.i(AppLog.T.READER, "reader job service > stopped"); jobFinished(params, false); return false; }
Source:
public SpecialVideosPageObject openSpecialVideoPage(){ getUrl(Domain+URLsContent.specialNewVideo); return new SpecialVideosPageObject(driver, Domain); }

Target:
public SpecialVideosPageObject openSpecialVideoPage(){ getUrl(Global.DOMAIN+URLsContent.specialNewVideo); return new SpecialVideosPageObject(driver, Global.DOMAIN); }
Source:
protected void setActionMessageParameters() { addValidationMessage(EngineMessage.VAR__ACTION__ADD); addValidationMessage(EngineMessage.VAR__TYPE__USER_PROFILE); }

Target:
protected void setActionMessageParameters() { UserProfile existingProfile = getUserProfile(); if (existingProfile != null && isSSHPublicKeyUpdate(existingProfile)) { addValidationMessage(EngineMessage.VAR__ACTION__UPDATE); } else { addValidationMessage(EngineMessage.VAR__ACTION__ADD); } addValidationMessage(EngineMessage.VAR__TYPE__USER_PROFILE); }
Source:
public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store, CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) { Assert.notNull(processor, "'processor' must not be null"); Assert.notNull(store, "'store' must not be null"); setMessageStore(store); this.outputProcessor = processor; this.correlationStrategy = (correlationStrategy == null ? new HeaderAttributeCorrelationStrategy(IntegrationMessageHeaderAccessor.CORRELATION_ID) : correlationStrategy); this.releaseStrategy = releaseStrategy == null ? new SimpleSequenceSizeReleaseStrategy() : releaseStrategy; this.sequenceAware = this.releaseStrategy instanceof SequenceSizeReleaseStrategy; this.groupIds = new HashSet<>(); }

Target:
public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store, CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) { Assert.notNull(processor, "'processor' must not be null"); Assert.notNull(store, "'store' must not be null"); setMessageStore(store); this.outputProcessor = processor; this.correlationStrategy = (correlationStrategy == null ? new HeaderAttributeCorrelationStrategy(IntegrationMessageHeaderAccessor.CORRELATION_ID) : correlationStrategy); this.releaseStrategy = releaseStrategy == null ? new SimpleSequenceSizeReleaseStrategy() : releaseStrategy; this.sequenceAware = this.releaseStrategy instanceof SequenceSizeReleaseStrategy; }
Source:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); getDiskDao().getAllForVm(vm.getId()); disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), true)); } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }

Target:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), true)); } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }
Source:
void publishErrorRecord(ZNRecord record, String instanceName, String updateSubPath, String updateKey, String sessionId, HelixDataAccessor accessor, boolean isController) { _logger.error("StatusUpdate Error record: {}", record.toString()); if (!ERROR_LOG_TO_ZK_ENABLED) { return; } Builder keyBuilder = accessor.keyBuilder(); if (isController) { accessor.setProperty(keyBuilder.controllerTaskError(updateSubPath), new Error(record)); } else { accessor.updateProperty(keyBuilder.stateTransitionError(instanceName, sessionId, updateSubPath, updateKey), new Error(record)); } }

Target:
void publishErrorRecord(ZNRecord record, String instanceName, String updateSubPath, String updateKey, String sessionId, HelixDataAccessor accessor, boolean isController) { _logger.error("StatusUpdate Error record: {}", record); if (!ERROR_LOG_TO_ZK_ENABLED) { return; } Builder keyBuilder = accessor.keyBuilder(); if (isController) { accessor.setProperty(keyBuilder.controllerTaskError(updateSubPath), new Error(record)); } else { accessor.updateProperty(keyBuilder.stateTransitionError(instanceName, sessionId, updateSubPath, updateKey), new Error(record)); } }
Source:
protected boolean checkIfDisksExist(Iterable<DiskImage> disksList) { for (DiskImage disk : disksList) { GetImagesListVDSCommandParameters params = new GetImagesListVDSCommandParameters( imageToDestinationDomainMap.get(disk.getId()), getStoragePoolId()); VDSReturnValue runVdsCommand = getBackend().getResourceManager().RunVdsCommand( VDSCommandType.GetImagesList, params); if (runVdsCommand.getSucceeded()) { List<Guid> imagesOnStorageDomain = (List<Guid>) runVdsCommand.getReturnValue(); if (imagesOnStorageDomain.contains(disk.getId())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_ALREADY_CONTAINS_DISK); return false; } } else { addCanDoActionMessage(VdcBllMessages.ERROR_GET_IMAGE_LIST); return false; } } return true; }

Target:
protected boolean checkIfDisksExist(Iterable<DiskImage> disksList) { Map<Guid, List<Guid>> alreadyRetrieved = new HashMap<>(); for (DiskImage disk : disksList) { Guid targetStorageDomainId = imageToDestinationDomainMap.get(disk.getId()); List<Guid> imagesOnStorageDomain = alreadyRetrieved.get(targetStorageDomainId); if (imagesOnStorageDomain == null) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GetImagesList, new GetImagesListVDSCommandParameters(targetStorageDomainId, getStoragePoolId()) ); if (returnValue.getSucceeded()) { imagesOnStorageDomain = (List<Guid>) returnValue.getReturnValue(); alreadyRetrieved.put(targetStorageDomainId, imagesOnStorageDomain); } else { addCanDoActionMessage(String.format("$sdName %1$s", getStorageDomain(targetStorageDomainId).getName())); addCanDoActionMessage(VdcBllMessages.ERROR_GET_IMAGE_LIST); return false; } } if (imagesOnStorageDomain.contains(disk.getId())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_ALREADY_CONTAINS_DISK); return false; } } return true; }
Source:
public ImmutablePathsBuilder add(Map<String, List<String>> pathEntries) throws DuplicateResourceKeyException { for (Iterator<Map.Entry<String, List<String>>> it = pathEntries.entrySet().iterator(); it.hasNext();) { Map.Entry<String, List<String>> en = it.next(); List<String> availableValue = this.paths.get(en.getKey()); if (availableValue != null) { throw new DuplicateResourceKeyException("Ignoring path entry " + en + " because the given resource path was already provided: " + availableValue); } else { if (log.isDebugEnabled()) { log.debug("Adding path entry " + en); } this.paths.put(en.getKey(), Collections.unmodifiableList(new ArrayList<String>(en.getValue()))); } } return this; }

Target:
public ImmutablePathsBuilder add(Map<String, List<String>> pathEntries) throws DuplicateResourceKeyException { for (Entry<String, List<String>> en : pathEntries.entrySet()) { List<String> availableValue = this.paths.get(en.getKey()); if (availableValue != null) { throw new DuplicateResourceKeyException("Ignoring path entry " + en + " because the given resource path was already provided: " + availableValue); } else { if (log.isDebugEnabled()) { log.debug("Adding path entry " + en); } this.paths.put(en.getKey(), Collections.unmodifiableList(new ArrayList<String>(en.getValue()))); } } return this; }
Source:
public void startLifecyclesInRole(String role) { if (this.lazyLifecycles.size() > 0) { addLazyLifecycles(); } List<SmartLifecycle> lifecycles = new ArrayList<SmartLifecycle>(this.lifecycles.get(role)); if (lifecycles != null) { Collections.sort(lifecycles, new Comparator<SmartLifecycle>() { @Override public int compare(SmartLifecycle o1, SmartLifecycle o2) { return o1.getPhase() < o2.getPhase() ? -1 : o1.getPhase() > o2.getPhase() ? 1 : 0; } }); for (SmartLifecycle lifecycle : lifecycles) { try { lifecycle.start(); } catch (Exception e) { logger.error("Failed to start " + lifecycle + " in role " + role); } } } }

Target:
public void startLifecyclesInRole(String role) { if (this.lazyLifecycles.size() > 0) { addLazyLifecycles(); } List<SmartLifecycle> lifecycles = this.lifecycles.get(role); if (lifecycles != null) { lifecycles = new ArrayList<SmartLifecycle>(lifecycles); Collections.sort(lifecycles, new Comparator<SmartLifecycle>() { @Override public int compare(SmartLifecycle o1, SmartLifecycle o2) { return o1.getPhase() < o2.getPhase() ? -1 : o1.getPhase() > o2.getPhase() ? 1 : 0; } }); for (SmartLifecycle lifecycle : lifecycles) { try { lifecycle.start(); } catch (Exception e) { logger.error("Failed to start " + lifecycle + " in role " + role); } } } }
Source:
public void testClientReconnectOnExchangeHistoryExhaustion() throws Exception { startGrids(SRV_CNT); client = true; startClientGridsMultiThreaded(SRV_CNT, CLIENTS_CNT); waitForTopology(SRV_CNT + CLIENTS_CNT); awaitPartitionMapExchange(); verifyPartitionToNodeMappings(); verifyAffinityTopologyVersions(); verifyCacheOperationsOnClients(); }

Target:
public void testClientReconnectOnExchangeHistoryExhaustion() throws Exception { startGrids(SRV_CNT); startClientGridsMultiThreaded(SRV_CNT, CLIENTS_CNT); waitForTopology(SRV_CNT + CLIENTS_CNT); awaitPartitionMapExchange(); verifyPartitionToNodeMappings(); verifyAffinityTopologyVersions(); verifyCacheOperationsOnClients(); }
Source:
public Response setCompactionTaskLimit( @QueryParam("slotRatio") Double compactionTaskSlotRatio, @QueryParam("maxSlots") Integer maxCompactionTaskSlots, @HeaderParam(AuditManager.X_DRUID_AUTHOR) @DefaultValue("") final String author, @HeaderParam(AuditManager.X_DRUID_COMMENT) @DefaultValue("") final String comment, @Context HttpServletRequest req ) { CoordinatorCompactionConfig current = manager.watch( CoordinatorCompactionConfig.CONFIG_KEY, CoordinatorCompactionConfig.class ).get(); final CoordinatorCompactionConfig newCompactionConfig; if (current != null) { newCompactionConfig = CoordinatorCompactionConfig.from(current, compactionTaskSlotRatio, maxCompactionTaskSlots); } else { newCompactionConfig = new CoordinatorCompactionConfig(null, compactionTaskSlotRatio, maxCompactionTaskSlots); } if (!manager.set( CoordinatorCompactionConfig.CONFIG_KEY, newCompactionConfig, new AuditInfo(author, comment, req.getRemoteAddr()) )) { return Response.status(Response.Status.BAD_REQUEST).build(); } return Response.ok().build(); }

Target:
public Response setCompactionTaskLimit( @QueryParam("slotRatio") Double compactionTaskSlotRatio, @QueryParam("maxSlots") Integer maxCompactionTaskSlots, @HeaderParam(AuditManager.X_DRUID_AUTHOR) @DefaultValue("") final String author, @HeaderParam(AuditManager.X_DRUID_COMMENT) @DefaultValue("") final String comment, @Context HttpServletRequest req ) { CoordinatorCompactionConfig current = manager.watch( CoordinatorCompactionConfig.CONFIG_KEY, CoordinatorCompactionConfig.class ).get(); final CoordinatorCompactionConfig newCompactionConfig; if (current != null) { newCompactionConfig = CoordinatorCompactionConfig.from(current, compactionTaskSlotRatio, maxCompactionTaskSlots); } else { newCompactionConfig = new CoordinatorCompactionConfig(null, compactionTaskSlotRatio, maxCompactionTaskSlots); } final SetResult setResult = manager.set( CoordinatorCompactionConfig.CONFIG_KEY, newCompactionConfig, new AuditInfo(author, comment, req.getRemoteAddr()) ); if (setResult.isOk()) { return Response.ok().build(); } else { return Response.status(Response.Status.BAD_REQUEST) .entity(ImmutableMap.of("error", setResult.getException())) .build(); } }
Source:
public void embeddedLdapServerRegistersExpectedAuthenticationProvider() { UserDetails ldapUser = ldapUserDetailsService.loadUserByUsername("przemyslaw.fusik"); assertThat(ldapUser, CoreMatchers.instanceOf(LdapUserDetailsImpl.class)); LdapUserDetails ldapUserDetails = (LdapUserDetailsImpl) ldapUser; assertThat(ldapUserDetails.getDn(), CoreMatchers.equalTo("uid=przemyslaw.fusik,ou=Users,dc=carlspring,dc=com")); assertThat(ldapUserDetails.getPassword(), CoreMatchers.equalTo("password")); assertThat(ldapUserDetails.getUsername(), CoreMatchers.equalTo("przemyslaw.fusik")); assertThat(ldapUser.getAuthorities(), CoreMatchers.hasItems(CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_CREATE_REPO), CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_DELETE_REPO), CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_CREATE_REPO))); }

Target:
public void embeddedLdapServerRegistersExpectedAuthenticationProvider() { UserDetails ldapUser = ldapUserDetailsService.loadUserByUsername("przemyslaw.fusik"); assertThat(ldapUser, CoreMatchers.instanceOf(LdapUserDetailsImpl.class)); LdapUserDetails ldapUserDetails = (LdapUserDetailsImpl) ldapUser; assertThat(ldapUserDetails.getDn(), CoreMatchers.equalTo("uid=przemyslaw.fusik,ou=Users,dc=carlspring,dc=com")); assertThat(ldapUserDetails.getPassword(), CoreMatchers.equalTo("password")); assertThat(ldapUserDetails.getUsername(), CoreMatchers.equalTo("przemyslaw.fusik")); assertThat(ldapUser.getAuthorities(), CoreMatchers.hasItems(CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_CREATE_REPO), CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_DELETE_REPO), CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_CREATE_REPO), CoreMatchers.equalTo(new SimpleGrantedAuthority("VIEW_USER")))); }
Source:
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { final DlmsPushNotification message = (DlmsPushNotification) e.getMessage(); final String correlationId = UUID.randomUUID().toString().replace("-", ""); final String deviceIdentification = message.getEquipmentIdentifier(); final String ipAddress = this.retrieveIpAddress(ctx, deviceIdentification); if (PUSH_SMS_TRIGGER.equals(message.getTriggerType())) { this.logMessage(message); final PushNotificationSms pushNotificationSms = new PushNotificationSms(deviceIdentification, ipAddress); final RequestMessage requestMessage = new RequestMessage(correlationId, "no-organisation", deviceIdentification, ipAddress, pushNotificationSms); LOGGER.info("Sending push notification sms wakeup to OSGP with correlation ID: " + correlationId); this.osgpRequestMessageSender.send(requestMessage, DeviceFunction.PUSH_NOTIFICATION_SMS.name()); } else if (PUSH_ALARM_TRIGGER.equals(message.getTriggerType())) { this.logMessage(message); final PushNotificationAlarm pushNotificationAlarm = new PushNotificationAlarm(deviceIdentification, message.getAlarms()); final RequestMessage requestMessage = new RequestMessage(correlationId, "no-organisation", deviceIdentification, ipAddress, pushNotificationAlarm); LOGGER.info("Sending push notification alarm to OSGP with correlation ID: " + correlationId); this.osgpRequestMessageSender.send(requestMessage, DeviceFunction.PUSH_NOTIFICATION_ALARM.name()); } else { LOGGER.info("Unknown received message, skip processing"); } }

Target:
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { final DlmsPushNotification message = (DlmsPushNotification) e.getMessage(); final String correlationId = UUID.randomUUID().toString().replace("-", ""); final String deviceIdentification = message.getEquipmentIdentifier(); final String ipAddress = this.retrieveIpAddress(ctx, deviceIdentification); this.processPushedMessage(message, correlationId, deviceIdentification, ipAddress); }
Source:
public static String formatSmsMessage(long userId, Event event, Position position) { VelocityContext velocityContext = prepareContext(userId, event, position); String smsTemplatesPath = Context.getConfig().getString("sms.templatesPath", "sms") + "/"; Template template = null; try { template = Context.getVelocityEngine().getTemplate(smsTemplatesPath + event.getType() + ".vm", StandardCharsets.UTF_8.name()); } catch (ResourceNotFoundException error) { Log.warning(error); template = Context.getVelocityEngine().getTemplate(smsTemplatesPath + "unknown.vm", StandardCharsets.UTF_8.name()); } StringWriter writer = new StringWriter(); template.merge(velocityContext, writer); return writer.toString(); }

Target:
public static String formatSmsMessage(long userId, Event event, Position position) { VelocityContext velocityContext = prepareContext(userId, event, position); StringWriter writer = new StringWriter(); getTemplate(event, Context.getConfig().getString("sms.templatesPath", "sms") + "/") .merge(velocityContext, writer); return writer.toString(); }