auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldUnsetOtherPreferredIdentifiers() throws Exception { PatientIdentifier nonPreferred = service.getPatientIdentifierByUuid(getUuid()); long originalCount = getAllCount(); SimpleObject patientIdentifier = new SimpleObject(); patientIdentifier.add("identifier", "abc123ez"); patientIdentifier.add("identifierType", "2f470aa8-1d73-43b7-81b5-01f0c0dfa53c"); patientIdentifier.add("location", RestTestConstants1_8.LOCATION_UUID); patientIdentifier.add("preferred", true); String json = new ObjectMapper().writeValueAsString(patientIdentifier); MockHttpServletRequest req = request(RequestMethod.POST, getURI()); req.setContent(json.getBytes()); SimpleObject newPatientIdentifier = deserialize(handle(req)); assertNotNull(PropertyUtils.getProperty(newPatientIdentifier, "uuid")); assertEquals(originalCount + 1, getAllCount()); String preferredUuid = (String) PropertyUtils.getProperty(newPatientIdentifier, "uuid"); PatientIdentifier preferredIdentifer = service.getPatientIdentifierByUuid(preferredUuid); System.out.print("none prefered is " + nonPreferred.isPreferred()); System.out.print("prefered is " + preferredIdentifer.isPreferred()); assertEquals(nonPreferred.isPreferred(), false); assertEquals(preferredIdentifer.isPreferred(), true); }

Target:
public void shouldUnsetOtherPreferredIdentifiers() throws Exception { PatientIdentifier exisitingIdentifier = service.getPatientIdentifierByUuid(getUuid()); long originalCount = getAllCount(); assertTrue(exisitingIdentifier.isPreferred()); SimpleObject patientIdentifier = new SimpleObject(); patientIdentifier.add("identifier", "abc123ez"); patientIdentifier.add("identifierType", "2f470aa8-1d73-43b7-81b5-01f0c0dfa53c"); patientIdentifier.add("location", RestTestConstants1_8.LOCATION_UUID); patientIdentifier.add("preferred", true); String json = new ObjectMapper().writeValueAsString(patientIdentifier); MockHttpServletRequest req = request(RequestMethod.POST, getURI()); req.setContent(json.getBytes()); SimpleObject newPatientIdentifier = deserialize(handle(req)); Object uuid = PropertyUtils.getProperty(newPatientIdentifier, "uuid"); assertNotNull(uuid); assertEquals(originalCount + 1, getAllCount()); PatientIdentifier newIdentifer = service.getPatientIdentifierByUuid(uuid.toString()); assertFalse(exisitingIdentifier.isPreferred()); assertTrue(newIdentifer.isPreferred()); assertEquals(newIdentifer.getIdentifier(), "abc123ez"); }
Source:
protected static boolean hasPlaceholder(@NotNull String formatString) { return StringUtil.contains(formatString, "%"); }

Target:
public static boolean hasPlaceholder(@NotNull String formatString) { return StringUtil.containsChar(formatString, '%'); }
Source:
GenericIndexed( ByteBuffer buffer, ObjectStrategy<T> strategy, boolean allowReverseLookup ) { this.theBuffer = buffer; this.strategy = strategy; this.allowReverseLookup = allowReverseLookup; size = theBuffer.getInt(); numElementsPerValueFile = size; int indexOffset = theBuffer.position(); int valuesOffset = theBuffer.position() + (size << 2); buffer.position(valuesOffset); valueBuffers = Lists.newArrayList(buffer.slice()); buffer.position(indexOffset); headerBuffer = buffer.slice(); final ByteBuffer valueBuffer = valueBuffers.get(0); bufferIndexed = new BufferIndexed() { @Override public T get(int index) { if (index < 0) { throw new IAE("Index[%s] < 0", index); } if (index >= size) { throw new IAE(String.format("Index[%s] >= size[%s]", index, size)); } ByteBuffer copyHeaderBuffer = headerBuffer.asReadOnlyBuffer(); final int startOffset; final int endOffset; if (index == 0) { copyHeaderBuffer.position(0); startOffset = 4; endOffset = copyHeaderBuffer.getInt(); } else { copyHeaderBuffer.position((index - 1) * Ints.BYTES); startOffset = copyHeaderBuffer.getInt() + 4; endOffset = copyHeaderBuffer.getInt(); } return _get(valueBuffer.asReadOnlyBuffer(), startOffset, endOffset); } }; }

Target:
GenericIndexed( ByteBuffer buffer, ObjectStrategy<T> strategy, boolean allowReverseLookup ) { this.theBuffer = buffer; this.strategy = strategy; this.allowReverseLookup = allowReverseLookup; size = theBuffer.getInt(); int indexOffset = theBuffer.position(); int valuesOffset = theBuffer.position() + size * Ints.BYTES; buffer.position(valuesOffset); valueBuffers = Lists.newArrayList(buffer.slice()); buffer.position(indexOffset); headerBuffer = buffer.slice(); final ByteBuffer valueBuffer = valueBuffers.get(0); bufferIndexed = new BufferIndexed() { @Override public T get(int index) { checkIndex(index, size); final int startOffset; final int endOffset; if (index == 0) { startOffset = 4; endOffset = headerBuffer.getInt(0); } else { int headerPosition = (index - 1) * Ints.BYTES; startOffset = headerBuffer.getInt(headerPosition) + Ints.BYTES; endOffset = headerBuffer.getInt(headerPosition + Ints.BYTES); } return _get(valueBuffer.asReadOnlyBuffer(), startOffset, endOffset); } }; }
Source:
public void loginAsync_throwExceptionInErrorHandler() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); try { SyncCredentials credentials = SyncCredentials.usernamePassword("IWantToHackYou", "GeneralPassword", false); SyncUser.loginAsync(credentials, Constants.AUTH_URL, new SyncUser.Callback() { @Override public void onSuccess(SyncUser user) { fail(); } @Override public void onError(ObjectServerError error) { latch.countDown(); throw new IllegalArgumentException("Boom"); } }); Thread.sleep(1000); TestHelper.awaitOrFail(latch); fail(); } catch (IllegalArgumentException e) { assertEquals("Boom", e.getMessage()); } catch (Exception ignored) { fail(); } finally { looperThread.testComplete(); } }

Target:
public void loginAsync_throwExceptionInErrorHandler() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); SyncCredentials credentials = SyncCredentials.usernamePassword("IWantToHackYou", "GeneralPassword", false); SyncUser.loginAsync(credentials, Constants.AUTH_URL, new SyncUser.Callback() { @Override public void onSuccess(SyncUser user) { Log.d("REALM", "onSuccess"); fail(); } @Override public void onError(ObjectServerError error) { Log.d("REALM", "onError 1"); latch.countDown(); Log.d("REALM", "onError 2"); throw new IllegalArgumentException("Boom"); } }); Log.d("REALM", "main 1"); TestHelper.awaitOrFail(latch); Log.d("REALM", "main 2"); looperThread.testComplete(); Log.d("REALM", "main 3"); }
Source:
private ReadCountCollection processReadCounts(@Nonnull final ReadCountCollection rawReadCounts) { if (rawReadCounts.columnNames().size() > 1) { return ReadCountCollectionUtils.removeTotallyUncoveredTargets(rawReadCounts, logger); } else { final long numUncoveredTargets = rawReadCounts.records().stream() .filter(rec -> (int)rec.getDouble(0) == 0).count(); final long numAllTargets = rawReadCounts.targets().size(); logger.info("Since only one sample is given for genotyping, the user is responsible for asserting" + " the aptitute of targets. Fully uncovered (irrelevant) targets can not be automatically" + " identified (total targets: " + numAllTargets + ", uncovered targets: " + numUncoveredTargets + ")"); return rawReadCounts; } }

Target:
private ReadCountCollection processReadCounts(@Nonnull final ReadCountCollection rawReadCounts) { if (rawReadCounts.columnNames().size() > 1) { return ReadCountCollectionUtils.removeTotallyUncoveredTargets(rawReadCounts, logger); } else { final long numUncoveredTargets = rawReadCounts.records().stream() .filter(rec -> (int)rec.getDouble(0) == 0).count(); final long numAllTargets = rawReadCounts.targets().size(); logger.info("Since only one sample is given for genotyping, the user is responsible for asserting" + " the aptitude of targets. Fully uncovered (irrelevant) targets can not be automatically" + " identified (total targets: " + numAllTargets + ", uncovered targets: " + numUncoveredTargets + ")"); return rawReadCounts; } }
Source:
private static String getFieldAlertProperty( int pluginId, String key, String contentDefault, ExtensionExportReport extensionExport) { if (key.contains("risk") || key.contains("reliability")) { return getMessage( extensionExport, "alertreport.export.pluginid." + key, contentDefault); } StringBuilder sbKey = new StringBuilder(50); sbKey.append("alertreport.export.pluginid."); sbKey.append(pluginId); sbKey.append('.'); sbKey.append(key); return getMessage(extensionExport, sbKey.toString(), contentDefault); }

Target:
private static String getFieldAlertProperty( int pluginId, String key, String contentDefault, ExtensionExportReport extensionExport) { if (key.contains("risk") || key.contains("reliability")) { return getMessage( extensionExport, "exportreport.export.pluginid." + key, contentDefault); } StringBuilder sbKey = new StringBuilder(50); sbKey.append("exportreport.export.pluginid."); sbKey.append(pluginId); sbKey.append('.'); sbKey.append(key); return getMessage(extensionExport, sbKey.toString(), contentDefault); }
Source:
public void waitForEntityStart() { if (log.isDebugEnabled()) log.debug("waiting to ensure doesn't abort prematurely", this); Duration startTimeout = getConfig(START_TIMEOUT); CountdownTimer timer = startTimeout.countdownTimer(); boolean isRunningResult = false; long delay = 100; Exception firstFailure = null; while (!isRunningResult && !timer.isExpired()) { Time.sleep(delay); try { isRunningResult = driver.isRunning(); if (log.isDebugEnabled()) log.debug("checked {}, 'is running' returned: {}", this, isRunningResult); } catch (Exception e) { Exceptions.propagateIfFatal(e); firstFailure = e; isRunningResult = false; if (driver != null) { log.error("checked " + this + ", 'is running' threw an exception", e); } else { log.error(this+" concurrent start and shutdown detected", e); } } delay = Math.min(delay*11/10, 5000); } if (!isRunningResult) { String msg = "Software process entity "+this+" did not pass is-running check within "+ "the required "+startTimeout+" limit ("+timer.getDurationElapsed().toStringRounded()+" elapsed)"; if (firstFailure != null) { msg += "; check failed with exception: " + firstFailure.getMessage(); } log.warn(msg+" (throwing)"); ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING); throw new IllegalStateException(msg, firstFailure); } }

Target:
public void waitForEntityStart() { if (log.isDebugEnabled()) log.debug("waiting to ensure doesn't abort prematurely", this); Duration startTimeout = getConfig(START_TIMEOUT); CountdownTimer timer = startTimeout.countdownTimer(); boolean isRunningResult = false; long delay = 100; Exception firstFailure = null; while (!isRunningResult && !timer.isExpired()) { Time.sleep(delay); try { isRunningResult = driver.isRunning(); if (log.isDebugEnabled()) log.debug("checked {}, 'is running' returned: {}", this, isRunningResult); } catch (Exception e) { Exceptions.propagateIfFatal(e); isRunningResult = false; if (driver != null) { String msg = "checked " + this + ", 'is running' threw an exception; logging subsequent exceptions at debug level"; if (firstFailure == null) { log.error(msg, e); } else { log.debug(msg, e); } } else { log.error(this+" concurrent start and shutdown detected", e); } if (firstFailure == null) { firstFailure = e; } } delay = Math.min(delay*11/10, 5000); } if (!isRunningResult) { String msg = "Software process entity "+this+" did not pass is-running check within "+ "the required "+startTimeout+" limit ("+timer.getDurationElapsed().toStringRounded()+" elapsed)"; if (firstFailure != null) { msg += "; check failed at least once with exception: " + firstFailure.getMessage() + ", see logs for details"; } log.warn(msg+" (throwing)"); ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING); throw new IllegalStateException(msg, firstFailure); } }
Source:
protected boolean matchingEObjects(EObject object1, EObject object2) { MatchSpec match = (MatchSpec)getMatch(object1); if (match != null) { eObjectMatch = match; return match.matches(object2); } else if (getTarget().getMatch(object2) != null || object1.eClass() != object2.eClass()) { return false; } else { return matchingURIs(object1, object2); } }

Target:
protected boolean matchingEObjects(EObject object1, EObject object2) { final boolean matching; MatchSpec match = (MatchSpec)getMatch(object1); if (match != null) { eObjectMatch = match; matching = match.matches(object2); } else if (getTarget().getMatch(object2) != null || object1.eClass() != object2.eClass()) { matching = false; } else { matching = matchingURIs(object1, object2); } return matching; }
Source:
public static boolean sendTweet( @ParamDoc(name = "tweetTxt", text = "text string to be sent as a Tweet") String tweetTxt, @ParamDoc(name = "tweetPicture", text = "the picture to attach") String tweetPicture) { if (!checkPrerequisites()) { return false; } File fileToAttach = null; boolean deleteTemporaryFile = false; if (StringUtils.startsWith(tweetPicture, "http://") || StringUtils.startsWith(tweetPicture, "https://")) { final String tDir = System.getProperty("java.io.tmpdir"); final String path = tDir + File.separator + "openhab-twitter-remote_attached_file" + "." + FilenameUtils.getExtension(tweetPicture); try { final URL url = new URL(tweetPicture); fileToAttach = new File(path); deleteTemporaryFile = true; FileUtils.copyURLToFile(url, fileToAttach); } catch (MalformedURLException e) { logger.warn("Can't read file from '{}'", tweetPicture, e); } catch (IOException e) { logger.warn("Can't save file from '{}' to '{}'", tweetPicture, path, e); } } else { fileToAttach = new File(tweetPicture); } if (fileToAttach != null && fileToAttach.isFile()) { logger.info("Image '{}' correctly found, will be included in tweet", tweetPicture); } else { logger.warn("Image '{}' not found, will only tweet text", tweetPicture); } boolean result = doSendTweet(tweetTxt, fileToAttach); if (deleteTemporaryFile) { FileUtils.deleteQuietly(fileToAttach); } return result; }

Target:
public static boolean sendTweet( @ParamDoc(name = "tweetTxt", text = "text string to be sent as a Tweet") String tweetTxt, @ParamDoc(name = "tweetPicture", text = "the picture to attach") String tweetPicture) { if (!checkPrerequisites()) { return false; } File fileToAttach = null; boolean deleteTemporaryFile = false; if (StringUtils.startsWith(tweetPicture, "http://") || StringUtils.startsWith(tweetPicture, "https://")) { String tDir = System.getProperty("java.io.tmpdir"); String path = tDir + File.separator + "openhab-twitter-remote_attached_file" + "." + FilenameUtils.getExtension(tweetPicture); try { URL url = new URL(tweetPicture); fileToAttach = new File(path); deleteTemporaryFile = true; FileUtils.copyURLToFile(url, fileToAttach); } catch (MalformedURLException e) { logger.warn("Can't read file from '{}'", tweetPicture, e); } catch (IOException e) { logger.warn("Can't save file from '{}' to '{}'", tweetPicture, path, e); } } else { fileToAttach = new File(tweetPicture); } if (fileToAttach != null && fileToAttach.isFile()) { logger.debug("Image '{}' correctly found, will be included in tweet", tweetPicture); } else { logger.warn("Image '{}' not found, will only tweet text", tweetPicture); } boolean result = sendTweet(tweetTxt, fileToAttach); if (deleteTemporaryFile) { FileUtils.deleteQuietly(fileToAttach); } return result; }
Source:
public void testMigrationPolicyChangeVmDown() { prepareVmToPassValidate(); vm.setStatus(VMStatus.Down); vm.setMigrationSupport(MigrationSupport.PINNED_TO_HOST); vmStatic.setMigrationSupport(MigrationSupport.MIGRATABLE); command.initEffectiveCompatibilityVersion(); ValidateTestUtils.runAndAssertValidateSuccess(command); prepareVmToPassValidate(); vm.setMigrationSupport(MigrationSupport.PINNED_TO_HOST); vmStatic.setMigrationSupport(MigrationSupport.IMPLICITLY_NON_MIGRATABLE); command.initEffectiveCompatibilityVersion(); ValidateTestUtils.runAndAssertValidateSuccess(command); }

Target:
public void testMigrationPolicyChangeVmDown() { prepareVmToPassValidate(); vm.setStatus(VMStatus.Down); vm.setMigrationSupport(MigrationSupport.PINNED_TO_HOST); vmStatic.setMigrationSupport(MigrationSupport.MIGRATABLE); command.initEffectiveCompatibilityVersion(); ValidateTestUtils.runAndAssertValidateSuccess(command); }
Source:
public EcoreDiagnosticCache(Notifier input) { super(input); TreeIterator<Object> allContents; if (ResourceSet.class.isInstance(input)) { allContents = EcoreUtil.getAllContents(ResourceSet.class.cast(input), false); } else if (Resource.class.isInstance(input)) { allContents = EcoreUtil.getAllContents(Resource.class.cast(input), false); } else if (EObject.class.isInstance(input)) { allContents = EcoreUtil.getAllContents(EObject.class.cast(input), false); } else { return; } while (allContents.hasNext()) { final Object next = allContents.next(); if (!EObject.class.isInstance(next)) { continue; } updateCache(EObject.class.cast(next), this); } }

Target:
public EcoreDiagnosticCache(Notifier input) { super(input); final Set<EObject> rootObjects = new LinkedHashSet<>(); if (ResourceSet.class.isInstance(input)) { final EList<Resource> resources = ResourceSet.class.cast(input).getResources(); resources.stream().map(Resource::getContents).forEach(rootObjects::addAll); } else if (Resource.class.isInstance(input)) { rootObjects.addAll(Resource.class.cast(input).getContents()); } else if (EObject.class.isInstance(input)) { rootObjects.add(EObject.class.cast(input)); } else { return; } rootObjects.forEach(this::depthFirstCacheUpdate); }
Source:
public void testDisksNotInBackupStorage() { final VM vm = new VM(); vm.setStatus(VMStatus.Down); vm.getDiskList().add(new DiskImage()); command.setVm(vm); command.getStorageDomain().isBackup(); doReturn(false).when(command).checkDisksNotInBackupStorage(); doNothing().when(command).fetchVmDisksFromDb(); assertEquals(RunVmFlow.RUN, command.getFlow()); }

Target:
public void testDisksNotInBackupStorage() { final VM vm = new VM(); vm.setStatus(VMStatus.Down); vm.getDiskList().add(new DiskImage()); command.setVm(vm); command.getStorageDomain().isBackup(); doReturn(false).when(command).checkDisksNotInBackupStorage(); ValidateTestUtils.runAndAssertValidateSuccess(command); }
Source:
private ILaserTarget getTarget() { if (targetPos != null) { return (ILaserTarget) world.getTileEntity(targetPos); } return null; }

Target:
private ILaserTarget getTarget() { if (targetPos != null) { if (world.getTileEntity(targetPos) instanceof ILaserTarget) { return (ILaserTarget) world.getTileEntity(targetPos); } } return null; }
Source:
private static long getHashCode(Object key) { int extraIdentity; if (key instanceof Block) { extraIdentity = (int) ((Block) key).getRetainedSizeInBytes(); } else if (key instanceof Slice) { extraIdentity = System.identityHashCode(((Slice) key).getBase()); } else if (key instanceof int[]) { extraIdentity = ((int[]) key).length; } else if (key instanceof boolean[]) { extraIdentity = ((boolean[]) key).length; } else if (key instanceof double[]) { extraIdentity = ((double[]) key).length; } else if (key instanceof long[]) { extraIdentity = ((long[]) key).length; } else if (key instanceof byte[]) { extraIdentity = ((byte[]) key).length; } else if (key instanceof short[]) { extraIdentity = ((short[]) key).length; } else { throw new IllegalArgumentException(format("Unsupported type for %s", key)); } return (((long) System.identityHashCode(key)) << Integer.SIZE) + extraIdentity; }

Target:
private static long getHashCode(Object key) { int extraIdentity; if (key == null) { extraIdentity = 0; } else if (key instanceof Block) { extraIdentity = (int) ((Block) key).getRetainedSizeInBytes(); } else if (key instanceof Slice) { extraIdentity = (int) ((Slice) key).getRetainedSize(); } else if (key.getClass().isArray()) { extraIdentity = getLength(key); } else { throw new IllegalArgumentException(format("Unsupported type for %s", key)); } return (((long) System.identityHashCode(key)) << Integer.SIZE) + extraIdentity; }
Source:
public ScmArtifact getArtifact(IResource resource) throws CoreException { Repository repository = getJGitRepository(resource); String resRepoRelPath = resolveRepoRelativePath(repository, resource); String revision = null; try { revision = resolveObject(repository, resRepoRelPath); } catch (Exception e) { } ScmArtifact artifact = null; if (revision != null) { GitRepository repo = getRepository(resource); artifact = new GitArtifact(revision, resRepoRelPath, repo); artifact.setProjectName(resource.getProject().getName()); artifact.setProjectRelativePath(resource.getProjectRelativePath().toPortableString()); } else { artifact = getArtifact(resource, null); } return artifact; }

Target:
public ScmArtifact getArtifact(IResource resource) throws CoreException { if (resource == null) { return null; } Repository repository; RepositoryMapping m = RepositoryMapping.getMapping(resource); try { repository = getRepositoryCache().lookupRepository(m.getGitDirAbsolutePath().toFile()); } catch (IOException e) { return null; } String resRepoRelPath = resolveRepoRelativePath(repository, resource); String revision = null; try { revision = resolveObject(repository, resRepoRelPath); } catch (Exception e) { } ScmArtifact artifact = null; if (revision != null) { GitRepository repo = getRepository(resource); artifact = new GitArtifact(revision, resRepoRelPath, repo); artifact.setProjectName(resource.getProject().getName()); artifact.setProjectRelativePath(resource.getProjectRelativePath().toPortableString()); } else { artifact = getArtifact(resource, null); } return artifact; }
Source:
public static URLClassLoader urlClassLoaderFromPaths(ClassLoader parent, Collection<Path> paths) { Assert.notNull(paths, "paths collection cannot be null"); final URL[] urls; final URI[] uris = paths.stream().map(Path::toUri).toArray(URI[]::new); urls = new URL[uris.length]; for (int i = 0; i < uris.length; i++) { urls[i] = ThrowingFunction.unchecked(URI::toURL).apply(uris[i]); } return new URLClassLoader(urls, parent); }

Target:
public static URLClassLoader urlClassLoaderFromPaths(ClassLoader parent, Collection<Path> paths) { Assert.notNull(paths, "paths collection cannot be null"); final URL[] urls = paths.stream().map(Path::toUri) .map(ThrowingFunction.unchecked(URI::toURL)) .toArray(URL[]::new); return new URLClassLoader(urls, parent); }
Source:
public FilePagePageObject openImage(String imageName, boolean noRedirect) { String url = getImageUrl(imageName); if (noRedirect) { String parameter = "redirect=no"; UrlBuilder builer = new UrlBuilder(); url = builer.appendQueryStringToURL(url, parameter); } driver.get(url); return new FilePagePageObject(driver); }

Target:
public FilePagePageObject openImage(String imageName, boolean noRedirect) { String url = getImageUrl(imageName); if (noRedirect) { String parameter = "redirect=no"; url = urlBuilder.appendQueryStringToURL(url, parameter); } driver.get(url); return new FilePagePageObject(driver); }
Source:
public void testTokens() { final PreferMethodReferenceCheck check = new PreferMethodReferenceCheck(); final int[] expected = { TokenTypes.LAMBDA, }; assertArrayEquals(expected, check.getAcceptableTokens(), "Acceptable required tokens are invalid"); assertArrayEquals(expected, check.getDefaultTokens(), "Default required tokens are invalid"); assertArrayEquals(expected, check.getRequiredTokens(), "Required required tokens are invalid"); }

Target:
public void testTokens() { final PreferMethodReferenceCheck check = new PreferMethodReferenceCheck(); final int[] expected = { TokenTypes.LAMBDA, }; assertThat(check.getAcceptableTokens()).isEqualTo(expected); assertThat(check.getDefaultTokens()).isEqualTo(expected); assertThat(check.getRequiredTokens()).isEqualTo(expected); }
Source:
public void executePatchRequest() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_OK, "{\"msg\":\"hi\"}") ).start(); final GhLabel label = new GhLabel( new ApacheRequest(container.home()), new DefaultGithub() .repos().get(new Coordinates.Simple("jeff", "patch")), "enhance" ); label.patch( Json.createObjectBuilder() .add("content", "hi you!") .build() ); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo("PATCH") ); container.stop(); }

Target:
public void executePatchRequest() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_OK, "{\"msg\":\"hi\"}") ).start(); final GhLabel label = new GhLabel( new ApacheRequest(container.home()), GhLabelTest.repo(), "enhance" ); label.patch( Json.createObjectBuilder() .add("content", "hi you!") .build() ); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.PATCH) ); container.stop(); }
Source:
public void onBackPressed() { if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { String currentFragment = getSupportFragmentManager() .findFragmentById(R.id.container) .getClass().getSimpleName(); if (!currentFragment.equalsIgnoreCase("SearchFragment")) { replaceFragment(new SearchFragment(), false, R.id.container); return; } if (doubleBackToExitPressedOnce) { setMenuCreateClient(true); setMenuCreateCentre(true); setMenuCreateGroup(true); super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, R.string.back_again, Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; } }, 2000); } }

Target:
public void onBackPressed() { if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { String currentFragment = getSupportFragmentManager() .findFragmentById(R.id.container) .getClass().getSimpleName(); if (!currentFragment.equalsIgnoreCase(Constants.SEARCH_FRAGMENT)) { replaceFragment(new SearchFragment(), false, R.id.container); return; } if (doubleBackToExitPressedOnce) { setMenuCreateClient(true); setMenuCreateCentre(true); setMenuCreateGroup(true); super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, R.string.back_again, Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; } }, 2000); } }
Source:
public String toString() { String govFeatureName = ((RelationAdapter) getSource()).getSourceFeatureName(); Feature govFeature = annotation.getType().getFeatureByBaseName(govFeatureName); AnnotationFS govToken = (AnnotationFS) annotation.getFeatureValue(govFeature); StringBuilder builder = new StringBuilder(); builder.append("RelationCreatedEvent ["); if (document != null) { builder.append("docID="); builder.append(document.getId()); builder.append(", user="); builder.append(user); builder.append(", "); } builder.append("relation=["); builder.append(annotation.getBegin()); builder.append("-"); builder.append(annotation.getEnd()); builder.append("]("); builder.append(annotation.getCoveredText()); builder.append(") <-["); builder.append(govToken.getBegin()); builder.append("-"); builder.append(govToken.getEnd()); builder.append("]("); builder.append(govToken.getCoveredText()); builder.append(")]"); return builder.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("RelationCreatedEvent ["); if (document != null) { builder.append("docID="); builder.append(document.getId()); builder.append(", user="); builder.append(user); builder.append(", "); } builder.append("relation=["); builder.append(targetAnno.getBegin()); builder.append("-"); builder.append(targetAnno.getEnd()); builder.append("]("); builder.append(targetAnno.getCoveredText()); builder.append(") <-["); builder.append(sourceAnno.getBegin()); builder.append("-"); builder.append(sourceAnno.getEnd()); builder.append("]("); builder.append(sourceAnno.getCoveredText()); builder.append(")]"); return builder.toString(); }
Source:
public void commitSync(Duration timeout) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); if (!coordinator.commitOffsetsSync(subscriptions.allConsumed(), time.timer(timeout))) { throw new TimeoutException("Timeout of " + timeout.toMillis() + "ms expired before successfully " + "committing the current consumed offsets. Try tuning 'default.api.timeout.ms' option"); } } finally { release(); } }

Target:
public void commitSync(Duration timeout) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); if (!coordinator.commitOffsetsSync(subscriptions.allConsumed(), time.timer(timeout))) { throw new TimeoutException("Timeout of " + timeout.toMillis() + "ms expired before successfully " + "committing the current consumed offsets. Try increasing 'default.api.timeout.ms' option"); } } finally { release(); } }
Source:
public void visitNode(Tree tree) { if (tree.is(Tree.Kind.METHOD)) { MethodTree methodTree = (MethodTree) tree; methodNameKeyAndParameteresValue.put(methodTree.symbol(), new LinkedHashSet<>(methodTree.parameters().stream().map(param -> param.simpleName().name() .toLowerCase(Locale.ENGLISH)).collect(Collectors.toList()))); return; } else { MethodInvocationTree methodInvTree = (MethodInvocationTree) tree; LinkedHashSet<String> definedFunctionParameters = methodNameKeyAndParameteresValue.get(methodInvTree.symbol()); LinkedHashSet<String> invocationParameters = new LinkedHashSet<>( methodInvTree.arguments().stream().map(param -> param.toString().toLowerCase(Locale.ENGLISH)).collect(Collectors.toList())); if (definedFunctionParameters == null || invocationParameters.isEmpty()) { return; } if (matchParameters(definedFunctionParameters, invocationParameters)) { return; } else { reportIssue(methodInvTree, "Parameters to " + methodInvTree.symbol().name() + " have the same names but not the same order as the method arguments."); } } }

Target:
public void visitNode(Tree tree) { MethodInvocationTree methodInvTree = (MethodInvocationTree) tree; MethodTree methodDeclaration = (MethodTree) methodInvTree.symbol().declaration(); if (methodDeclaration == null) { return; } ParametersList formalParameterList = parametersByMethod.computeIfAbsent(methodInvTree.symbol(), m -> new ParametersList(methodDeclaration)); List<IdentifierTree> argumentsList = methodInvTree.arguments().stream().map(this::argumentToIdentifier).collect(Collectors.toList()); if (matchingNames(formalParameterList, argumentsList) && matchingTypesWrongOrder(formalParameterList, argumentsList)) { List<JavaFileScannerContext.Location> flow = methodDeclaration.parameters().stream().map(param -> new JavaFileScannerContext.Location("Formal Parameters", param)) .collect(Collectors.toList()); reportIssue(methodInvTree.arguments(), "Parameters to " + methodInvTree.symbol().name() + " have the same names but not the same order as the method arguments.", flow, null); } }
Source:
public static Body createBody(InputStream in, String contentTransferEncoding, String contentType, final AttachmentProgressCallback progressCallback) throws IOException { if (contentTransferEncoding != null) { contentTransferEncoding = MimeUtility.getHeaderParameter(contentTransferEncoding, null); } final BinaryTempFileBody tempBody; if (MimeUtil.isMessage(contentType)) { tempBody = new BinaryTempFileMessageBody(contentTransferEncoding); } else { tempBody = new BinaryTempFileBody(contentTransferEncoding); } OutputStream out = tempBody.getOutputStream(); Timer timer = null; try { if(progressCallback != null){ timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { progressCallback.onUpdate((int) tempBody.getSize()); } }, 0, 50); } IOUtils.copy(in, out); } finally { if(timer != null){ timer.cancel(); } out.close(); } return tempBody; }

Target:
public static Body createBody(InputStream in, String contentTransferEncoding, String contentType, final AttachmentProgressCallback progressCallback) throws IOException { if (contentTransferEncoding != null) { contentTransferEncoding = MimeUtility.getHeaderParameter(contentTransferEncoding, null); } final BinaryTempFileBody tempBody; if (MimeUtil.isMessage(contentType)) { tempBody = new BinaryTempFileMessageBody(contentTransferEncoding); } else { tempBody = new BinaryTempFileBody(contentTransferEncoding); } OutputStream out = tempBody.getOutputStream(); final CountingOutputStream countingOutputStream = new CountingOutputStream(out); Timer timer = null; try { if (progressCallback != null) { timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { progressCallback.onUpdate((int) countingOutputStream.getCount()); } }, 0, 50); } IOUtils.copy(in, countingOutputStream); } finally { if (timer != null) { timer.cancel(); } out.close(); } return tempBody; }
Source:
public void testGetValues() throws IOException { final KijiTable table = mKiji.openTable("table"); final KijiTableReader reader = table.openTableReader(); final KijiRowData row1 = reader.get(table.getEntityId("row1"), KijiDataRequest.create("family")); assertTrue("Row does not contain column family [family].", row1.containsColumn("family")); assertTrue("Row does not contain column [family:column1].", row1.containsColumn("family", "column1")); assertTrue("Row does not contain column [family:column2].", row1.containsColumn("family", "column2")); final NavigableMap<String, NavigableMap<Long, CharSequence>> stringGet = row1.getValues( "family"); final NavigableMap<String, NavigableMap<Long, Integer>> intGet = row1.getValues("family"); assertEquals("I am not a string! () for the stringGet.", "I am a String", stringGet.get("column1").get(1L).toString()); intGet.get("column1").get(1L); }

Target:
public void testGetValues() throws IOException { assertTrue("Row does not contain column family [family].", mRow1.containsColumn("family")); assertTrue("Row does not contain column [family:column1].", mRow1.containsColumn("family", "column1")); assertTrue("Row does not contain column [family:column2].", mRow1.containsColumn("family", "column2")); final NavigableMap<String, NavigableMap<Long, CharSequence>> stringGet = mRow1.getValues( "family"); final NavigableMap<String, NavigableMap<Long, Integer>> intGet = mRow1.getValues("family"); assertEquals("I am not a string! () for the stringGet.", "I am a String", stringGet.get("column1").get(1L).toString()); try { intGet.get("column1").get(1L); fail("Didn't throw an exception!"); } catch (IllegalStateException ex) { assertEquals("Incorrect Exception message: ", "getValues(String family) is only enabled on" + "map type column families. The column family [family], is a group type column family." + "Please use getValues(String family, String qualifier) method.", ex.getMessage()); } }
Source:
private void redeployJob(CuratorFramework client, Job job) throws Exception { String jobName = job.getName(); String moduleLabel = job.getJobModuleDescriptor().getModuleLabel(); ModuleDescriptor moduleDescriptor = job.getJobModuleDescriptor(); ModuleDeploymentProperties moduleDeploymentProperties = DeploymentUtility.createModuleDeploymentProperties( job.getDeploymentProperties(), moduleDescriptor); if (moduleDeploymentProperties.getCount() > 0) { Iterator<Container> iterator = containerMatcher.match(moduleDescriptor, moduleDeploymentProperties, containerRepository).iterator(); List<String> containersForJobModule = getContainersForJobModule(client, moduleDescriptor); boolean jobModuleDeployed = false; while (iterator.hasNext()) { Container target = iterator.next(); String targetName = target.getName(); if (!containersForJobModule.contains(targetName)) { logger.info("Redeploying job to container {}", jobName, targetName); ModuleDeploymentWriter.Result result = moduleDeploymentWriter.writeDeployment(moduleDescriptor, target); moduleDeploymentWriter.validateResult(result); jobModuleDeployed = true; break; } } if (!jobModuleDeployed) { logger.warn("No containers available for redeployment of job {}", jobName); } } else { logUnwantedRedeployment(moduleDeploymentProperties.getCriteria(), moduleLabel); } }

Target:
private void redeployJob(CuratorFramework client, Job job) throws Exception { String jobName = job.getName(); String moduleLabel = job.getJobModuleDescriptor().getModuleLabel(); ModuleDescriptor moduleDescriptor = job.getJobModuleDescriptor(); ModuleDeploymentProperties moduleDeploymentProperties = DeploymentPropertiesUtility.createModuleDeploymentProperties( job.getDeploymentProperties(), moduleDescriptor); if (moduleDeploymentProperties.getCount() > 0) { Iterator<Container> iterator = containerMatcher.match(moduleDescriptor, moduleDeploymentProperties, containerRepository).iterator(); List<String> containersForJobModule = getContainersForJobModule(client, moduleDescriptor); boolean jobModuleDeployed = false; while (iterator.hasNext()) { Container target = iterator.next(); String targetName = target.getName(); if (!containersForJobModule.contains(targetName)) { logger.info("Redeploying job to container {}", jobName, targetName); ModuleDeploymentWriter.Result result = moduleDeploymentWriter.writeDeployment(moduleDescriptor, target); moduleDeploymentWriter.validateResult(result); jobModuleDeployed = true; break; } } if (!jobModuleDeployed) { logger.warn("No containers available for redeployment of job {}", jobName); } } else { logUnwantedRedeployment(moduleDeploymentProperties.getCriteria(), moduleLabel); } }
Source:
GroupingSettingsViewHolder(View view, GroupingSettings settings) { ButterKnife.bind(this, view); this.settings = settings; numberOfNamesInList.setText(numberOfNamesInList.getContext().getResources() .getString(R.string.grouping_settings_number_of_names_in_list, settings.getListSize())); namesPerGroup.setText(String.valueOf(settings.getNumOfNamesPerGroup())); numGroups.setText(String.valueOf(settings.getNumOfGroups())); }

Target:
GroupingSettingsViewHolder(View view, GroupingSettings settings) { ButterKnife.bind(this, view); this.settings = settings; numberOfNamesInList.setText(numberOfNamesInList.getContext().getResources() .getString(R.string.grouping_settings_number_of_names_in_list, settings.getNameListSize())); namesPerGroup.setText(String.valueOf(settings.getNumOfNamesPerGroup())); numGroups.setText(String.valueOf(settings.getNumOfGroups())); }
Source:
public void close() throws Exception { eventTimeLogic.stopPeriodicWatermarkEmits(); currentMainOutput.emitWatermark(Watermark.MAX_WATERMARK); super.close(); }

Target:
public void close() throws Exception { sourceReader.close(); eventTimeLogic.stopPeriodicWatermarkEmits(); super.close(); }
Source:
public String toString() { return new StringJoiner(", ") .add("typeRef: " + typeRef) .add("allowedValues: " + allowedValues) .add("itemComponent: " + itemComponent) .add("typeLanguage: " + typeLanguage) .add("isCollection: " + isCollection) .toString(); }

Target:
public String toString() { return new StringJoiner(", ") .add("name: " + getName()) .add("typeRef: " + typeRef) .add("allowedValues: " + allowedValues) .add("itemComponent: " + itemComponent) .add("typeLanguage: " + typeLanguage) .add("isCollection: " + isCollection) .toString(); }
Source:
private static Activity tryGetActivity(Context context) { if (context instanceof Activity) { return (Activity) context; } if (context instanceof ContextWrapper) { final ContextWrapper contextWrapper = (ContextWrapper) context; Context baseContext = contextWrapper.getBaseContext(); Activity result = tryGetActivity(baseContext); if (result != null) { return result; } } return null; }

Target:
private static Activity tryGetActivity(Context context) { while (context != null) { if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } else { return null; } } return null; }
Source:
public List<Reference> getProductReferences(Product product) throws CatalogException { Product prod = getProductById(product.getProductId(), true); if (prod != null) { return prod.getProductReferences(); } else { throw new CatalogException("No product found with matching Id"); } }

Target:
public List<Reference> getProductReferences(Product product) throws CatalogException { Product prod = getProductById(product.getProductId(), true); if (prod != null) { return prod.getProductReferences(); } else { return Collections.emptyList(); } }
Source:
public PerTileFileUtil(final String extension, final File base, final FileFaker faker, final int lane, final boolean skipEmptyFiles) { super(true, extension, base, faker, lane, skipEmptyFiles); this.fileMap = getTiledFiles(base, matchPattern); if (!fileMap.isEmpty()) { this.tiles = new ArrayList<>(this.fileMap.keySet()); } else { this.tiles = new ArrayList<>(); } }

Target:
public PerTileFileUtil(final String extension, final File base, final FileFaker faker, final int lane, final boolean skipEmptyFiles) { super(true, extension, base, faker, lane, skipEmptyFiles); this.fileMap = getTiledFiles(base, matchPattern); if (!fileMap.isEmpty()) { this.tiles = new ArrayList<>(this.fileMap.keySet()); } else { this.tiles = Collections.emptyList(); } }
Source:
public void removeItem() { List<WebElement> list = driver.findElements(itemDeleteButtonsList); int listSize = list.size(); if (listSize>1) { WebElement inputDeleteElement = list.get(1); waitForElementByElement(inputDeleteElement); clickAndWait(inputDeleteElement); list = driver.findElements(itemDeleteButtonsList); if (listSize > list.size()) { PageObjectLogging.log("removeItem", "item removed", true, driver); } else { PageObjectLogging.log("removeItem", "item not removed", false, driver); } } else { PageObjectLogging.log("removeItem", "item nor removed - there are no items", false, driver); } }

Target:
public void removeItem() { List<WebElement> list = driver.findElements(itemDeleteButtonsList); int listSize = list.size(); if (listSize>1) { WebElement inputDeleteElement = list.get(1); waitForElementByElement(inputDeleteElement); scrollAndClick(inputDeleteElement); list = driver.findElements(itemDeleteButtonsList); if (listSize > list.size()) { PageObjectLogging.log("removeItem", "item removed", true, driver); } else { PageObjectLogging.log("removeItem", "item not removed", false, driver); } } else { PageObjectLogging.log("removeItem", "item nor removed - there are no items", false, driver); } }
Source:
public String telnet(Channel channel, String message) { StringBuilder buf = new StringBuilder(); String service = null; boolean detail = false; if (message.length() > 0) { String[] parts = message.split("\\s+"); for (String part : parts) { if ("-l".equals(part)) { detail = true; } else { if (service != null && service.length() > 0) { return "Invalid parameter " + part; } service = part; } } } else { service = (String) channel.getAttribute(ChangeTelnetHandler.SERVICE_KEY); if (service != null && service.length() > 0) { buf.append("Use default service ").append(service).append(".\r\n"); } } if (service == null || service.length() == 0) { printAllServices(buf, detail); } else { printSpecifiedService(service, buf, detail); if (buf.length() == 0) { buf.append("No such service: ").append(service); } } return buf.toString(); }

Target:
public String telnet(Channel channel, String message) { StringBuilder buf = new StringBuilder(); String service = null; boolean detail = false; if (message.length() > 0) { String[] parts = message.split("\\s+"); for (String part : parts) { if ("-l".equals(part)) { detail = true; } else { if (!StringUtils.isEmpty(service)) { return "Invalid parameter " + part; } service = part; } } } else { service = (String) channel.getAttribute(ChangeTelnetHandler.SERVICE_KEY); if (service != null && service.length() > 0) { buf.append("Use default service ").append(service).append(".\r\n"); } } if (StringUtils.isEmpty(service)) { printAllServices(buf, detail); } else { printSpecifiedService(service, buf, detail); if (buf.length() == 0) { buf.append("No such service: ").append(service); } } return buf.toString(); }
Source:
private DatabaseConfigFactory.SupportedDatabase determinDatabaseConfiguration(String dialect) { if (dialect.matches("(?i)" + DatabaseConfigFactory.SupportedDatabase.MYSQL.getLabel())) { return DatabaseConfigFactory.SupportedDatabase.MYSQL; } else if (dialect.matches("(?i)" + DatabaseConfigFactory.SupportedDatabase.ORACLE.getLabel())) { return DatabaseConfigFactory.SupportedDatabase.ORACLE; } return DatabaseConfigFactory.SupportedDatabase.POSTGRESQL; }

Target:
private DatabaseConfigFactory.SupportedDatabase determinDatabaseConfiguration(String dialect) { if (StringUtils.containsIgnoreCase( dialect, DatabaseConfigFactory.SupportedDatabase.MYSQL.getLabel())) { return DatabaseConfigFactory.SupportedDatabase.MYSQL; } else if (StringUtils.containsIgnoreCase( dialect, DatabaseConfigFactory.SupportedDatabase.ORACLE.getLabel())) { return DatabaseConfigFactory.SupportedDatabase.ORACLE; } return DatabaseConfigFactory.SupportedDatabase.POSTGRESQL; }
Source:
public LocalLockManager getLocalLockManager() { return null; }

Target:
public LocalLockManager getLocalLockManager() { return lockManager; }
Source:
private TimestampFormat getTimestampFormat(Properties properties, String key, String defaultPattern) throws ServerConfigurationException { String pattern = properties.getProperty(key); if (null == pattern) { pattern = defaultPattern; } DateFormatCompiler compiler = new DateFormatCompiler(); if (null != pattern) { if (pattern.contains(new StringBuilder().append(Files.SEPARATOR).toString()) || pattern.startsWith(".")) { throw new ServerConfigurationException(key, pattern); } return compiler.compile(pattern); } return compiler.compile("yyyy-MM-dd"); }

Target:
private TimestampFormat getTimestampFormat(Properties properties, String key, String defaultPattern) throws ServerConfigurationException { String pattern = properties.getProperty(key); if (null == pattern) { pattern = defaultPattern; } DateFormatCompiler compiler = new DateFormatCompiler(); if (null != pattern) { return compiler.compile(pattern); } return compiler.compile("yyyy-MM-dd"); }
Source:
public void convertInput() { visitChildren(TextArea.class, (Component component, final IVisit<Void> visit) -> { if (component instanceof TextArea) { TextArea textArea = (TextArea) component; textArea.updateModel(); } }); setConvertedInput(new DefaultValueConfigurations(configurations)); }

Target:
public void convertInput() { visitChildren(TextArea.class, (component, visit) -> { if (component instanceof TextArea) { TextArea textArea = (TextArea) component; textArea.updateModel(); } }); setConvertedInput(new DefaultValueConfigurations(configurations)); }
Source:
public static boolean isManagementNetwork(Network net) { return Config.<String> GetValue(ConfigValues.ManagementNetwork).equalsIgnoreCase(net.getName()); }

Target:
public static boolean isManagementNetwork(Network net) { return Config.<String> GetValue(ConfigValues.ManagementNetwork).equals(net.getName()); }
Source:
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { int result = ACCESS_ABSTAIN; LOGGER.debug("Voting on the access to the for user with permissions {}", object, authentication.getPrincipal(), authentication.getAuthorities()); for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { LOGGER.debug("Verifying supported attribute: " + attribute.getAttribute()); result = ACCESS_DENIED; if (StringUtils.equalsIgnoreCase(SecurityConfigConstants.USER_ACCESS_PREFIX + authentication.getName(), attribute.getAttribute())) { return ACCESS_GRANTED; } } } logAccessResult(result, object); return result; }

Target:
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { int result = ACCESS_ABSTAIN; LOGGER.debug("Voting on the access to the for user with permissions {}", object, authentication.getPrincipal(), authentication.getAuthorities()); for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { LOGGER.debug("Verifying supported attribute: " + attribute.getAttribute()); result = ACCESS_DENIED; if (StringUtils.equalsIgnoreCase(SecurityConfigConstants.USER_ACCESS_PREFIX + authentication.getName(), attribute.getAttribute())) { result = ACCESS_GRANTED; break; } } } logAccessResult(result, object); return result; }