auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>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); <START> firstFailure = e; <END> 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); } }</code><technical_language>firstFailure named lastFailure</technical_language>

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:
<code>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 { <START> return matchingURIs(object1, object2); <END> } }</code><technical_language>equals() replaced == I this a problem, assumes instance of meta-model is sides, I this is false in some weird use-cases (with dynamic EObjects involved). I wrong, @laurent.goubet know</technical_language>

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:
<code>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://")) { <START> final String tDir = System.getProperty("java.io.tmpdir"); <END> 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; }</code><technical_language>final</technical_language>

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:
<code>public void testMigrationPolicyChangeVmDown() { prepareVmToPassValidate(); vm.setStatus(VMStatus.Down); vm.setMigrationSupport(MigrationSupport.PINNED_TO_HOST); vmStatic.setMigrationSupport(MigrationSupport.MIGRATABLE); command.initEffectiveCompatibilityVersion(); ValidateTestUtils.runAndAssertValidateSuccess(command); <START> prepareVmToPassValidate(); vm.setMigrationSupport(MigrationSupport.PINNED_TO_HOST); vmStatic.setMigrationSupport(MigrationSupport.IMPLICITLY_NON_MIGRATABLE); command.initEffectiveCompatibilityVersion(); ValidateTestUtils.runAndAssertValidateSuccess(command); <END> }</code><technical_language>split this 2 tests. acting command instance. a @Before annotated method. bootstraps test data including command)</technical_language>

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:
<code>public EcoreDiagnosticCache(Notifier input) { <START> super(input); <END> 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); } }</code><technical_language>super call creates a diagnostic for EObject. this is currently done twice. I need adjust visibility of some private methods in super class</technical_language>

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:
<code>public void testDisksNotInBackupStorage() { final VM vm = new VM(); <START> vm.setStatus(VMStatus.Down); <END> 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()); }</code><technical_language>No, RunVmCommand is executed VM is running, VM's status</technical_language>

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:
<code>private ILaserTarget getTarget() { if (targetPos != null) { <START> return (ILaserTarget) world.getTileEntity(targetPos); <END> } return null; }</code><technical_language>blindly cast -- check if returned tile entity is ILaserTarget (it change get updated)</technical_language>

Target:
private ILaserTarget getTarget() { if (targetPos != null) { if (world.getTileEntity(targetPos) instanceof ILaserTarget) { return (ILaserTarget) world.getTileEntity(targetPos); } } return null; }
Source:
<code>private static long getHashCode(Object key) { int extraIdentity; if (key instanceof Block) { extraIdentity = (int) ((Block) key).getRetainedSizeInBytes(); } else if (key instanceof Slice) { <START> extraIdentity = System.identityHashCode(((Slice) key).getBase()); <END> } 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; }</code><technical_language>base null, a slice of a slice share base object. Is want? If not, size</technical_language>

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:
<code>public ScmArtifact getArtifact(IResource resource) throws CoreException { <START> Repository repository = getJGitRepository(resource); <END> 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; }</code><technical_language>Consider inlining code in getJGitRepos</technical_language>

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:
<code>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]; <START> for (int i = 0; i < uris.length; i++) <END> { urls[i] = ThrowingFunction.unchecked(URI::toURL).apply(uris[i]); } return new URLClassLoader(urls, parent); }</code><technical_language>loop in stream .toArray(URI[]::new);</technical_language>

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:
<code>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); } <START> driver.get(url); <END> return new FilePagePageObject(driver); }</code><technical_language>builder object is allready - in base ...</technical_language>

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:
<code>public void testTokens() { final PreferMethodReferenceCheck check = new PreferMethodReferenceCheck(); final int[] expected = { TokenTypes.LAMBDA, }; <START> assertArrayEquals(expected, check.getAcceptableTokens(), <END> "Acceptable required tokens are invalid"); assertArrayEquals(expected, check.getDefaultTokens(), "Default required tokens are invalid"); assertArrayEquals(expected, check.getRequiredTokens(), "Required required tokens are invalid"); }</code><technical_language>Truth here</technical_language>

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:
<code>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(), <START> Matchers.equalTo("PATCH") <END> ); container.stop(); }</code><technical_language>Request.PATCH constant</technical_language>

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:
<code>public void onBackPressed() { if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { String currentFragment = getSupportFragmentManager() .findFragmentById(R.id.container) .getClass().getSimpleName(); <START> if (!currentFragment.equalsIgnoreCase("SearchFragment")) { <END> 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); } }</code><technical_language>Ignore hardcoded strings, if necessary declare in constants util</technical_language>

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:
<code>public String toString() { <START> String govFeatureName = ((RelationAdapter) getSource()).getSourceFeatureName(); <END> 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(); }</code><technical_language>I avoid casting source RelationAdapter is guarantee source is a RelationAdapter (cf. source Object in constructor). option explicitly pass relation adapter additional type-checked argument. suggest considering pass entire adapter extract information is relevant. Mind toString() method meaning for debugging in other cases used. another option check if source is instance of RelationAdapter if for toString method... a bit hacky in some situation toString() produce format in others another format</technical_language>

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:
<code>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 " + <START> "committing the current consumed offsets. Try tuning 'default.api.timeout.ms' option"); <END> } } finally { release(); } }</code><technical_language>I feel a instruction needs a tuning direction, Try increasing 'default.api.timeout.ms'</technical_language>

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:
<code>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; <START> LinkedHashSet<String> definedFunctionParameters = methodNameKeyAndParameteresValue.get(methodInvTree.symbol()); <END> 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."); } } }</code><technical_language>This work. means need declare method **before** invocation in compilation unit. This is want, a special case general case</technical_language>

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:
<code>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() { <START> progressCallback.onUpdate((int) tempBody.getSize()); <END> } }, 0, 50); } IOUtils.copy(in, out); } finally { if(timer != null){ timer.cancel(); } out.close(); } return tempBody; }</code><technical_language>guarantee file size reflect actual number of bytes written FileOutputStream closed. prefer wrap stream in a CountingOutputStream get count there</technical_language>

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:
<code>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")); <START> assertTrue("Row does not contain column family [family].", row1.containsColumn("family")); <END> 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); }</code><technical_language>this work? comparing a string boolean returned containsColumn? caught @Test(expected=IllegalStateException.class) wrapper succeeding test</technical_language>

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:
<code>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)) { <START> logger.info("Redeploying job to container {}", jobName, targetName); <END> 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); } }</code><technical_language>if want do this in a subsequent PR, a lot of job/stream module redeploy logic is same. able extract common code methods invoked for streams jobs</technical_language>

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:
<code>GroupingSettingsViewHolder(View view, GroupingSettings settings) { ButterKnife.bind(this, view); this.settings = settings; <START> numberOfNamesInList.setText(numberOfNamesInList.getContext().getResources() <END> .getString(R.string.grouping_settings_number_of_names_in_list, settings.getListSize())); namesPerGroup.setText(String.valueOf(settings.getNumOfNamesPerGroup())); numGroups.setText(String.valueOf(settings.getNumOfGroups())); }</code><technical_language>For some reason, getString() priority in AOSP skip resources. suggestion numberOfNamesInList.setText(numberOfNamesInList.getContext()</technical_language>

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:
<code>public void close() throws Exception { eventTimeLogic.stopPeriodicWatermarkEmits(); <START> currentMainOutput.emitWatermark(Watermark.MAX_WATERMARK); <END> super.close(); }</code><technical_language>work in BATCH mode introduce shortly. In BATCH mode currentMainOutput ignore watermarks. time emit MAX_WATERMARK in BATCH mode</technical_language>

Target:
public void close() throws Exception { sourceReader.close(); eventTimeLogic.stopPeriodicWatermarkEmits(); super.close(); }
Source:
<code>public String toString() { return new StringJoiner(", ") .add("typeRef: " + typeRef) <START> .add("allowedValues: " + allowedValues) <END> .add("itemComponent: " + itemComponent) .add("typeLanguage: " + typeLanguage) .add("isCollection: " + isCollection) .toString(); }</code><technical_language>If defining toString for ItemDefinition, please ensure name (by method getName()) is of properties shown</technical_language>

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:
<code>private static Activity tryGetActivity(Context context) { if (context instanceof Activity) { return (Activity) context; } if (context instanceof ContextWrapper) { <START> final ContextWrapper contextWrapper = (ContextWrapper) context; <END> Context baseContext = contextWrapper.getBaseContext(); Activity result = tryGetActivity(baseContext); if (result != null) { return result; } } return null; }</code><technical_language>Prefer a while loop recursion. Faster simpler (IMO). java while (context != null) { if (context instanceof Activity) { return (Activity)context; } else if (context instanceof ContextWrapper) { context = ((ContextWrapper)context).getBaseContext(); } else { return null; } } return null;</technical_language>

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:
<code>public List<Reference> getProductReferences(Product product) throws CatalogException { Product prod = getProductById(product.getProductId(), true); if (prod != null) { return prod.getProductReferences(); } else { <START> throw new CatalogException("No product found with matching Id"); <END> } }</code><technical_language>if return empty list instead of throwing exception</technical_language>

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:
<code>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 { <START> this.tiles = new ArrayList<>(); <END> } }</code><technical_language>Collections.emptyList()</technical_language>

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:
<code>public void removeItem() { List<WebElement> list = driver.findElements(itemDeleteButtonsList); int listSize = list.size(); if (listSize>1) { WebElement inputDeleteElement = list.get(1); waitForElementByElement(inputDeleteElement); <START> clickAndWait(inputDeleteElement); <END> 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); } }</code><technical_language>click element</technical_language>

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:
<code>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); <START> if (service != null && service.length() > 0) { <END> 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(); }</code><technical_language>changed if(!StringUtils.isEmpty(service))</technical_language>

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:
<code>private DatabaseConfigFactory.SupportedDatabase determinDatabaseConfiguration(String dialect) { <START> if (dialect.matches("(?i)" + DatabaseConfigFactory.SupportedDatabase.MYSQL.getLabel())) { <END> return DatabaseConfigFactory.SupportedDatabase.MYSQL; } else if (dialect.matches("(?i)" + DatabaseConfigFactory.SupportedDatabase.ORACLE.getLabel())) { return DatabaseConfigFactory.SupportedDatabase.ORACLE; } return DatabaseConfigFactory.SupportedDatabase.POSTGRESQL; }</code><technical_language>is advantage of a regex instead of .equalsIgnoreCase? Also, I impression do inline case-insensitivity, applies group in modifier appears. I wrong, this a normal comparison</technical_language>

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:
<code><START> public LocalLockManager getLocalLockManager() <END> { return null; }</code><technical_language>this is consistent RandomAccessFile form. LocalLockManager instances created</technical_language>

Target:
public LocalLockManager getLocalLockManager() { return lockManager; }
Source:
<code>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) { <START> if (pattern.contains(new StringBuilder().append(Files.SEPARATOR).toString()) || pattern.startsWith(".")) { <END> throw new ServerConfigurationException(key, pattern); } return compiler.compile(pattern); } return compiler.compile("yyyy-MM-dd"); }</code><technical_language>I feel checks unnecessary. config file disk, attacker access file system. Additionally methods Chars.contains() others, check if CharSequence contains \ creating a string</technical_language>

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:
<code>public void convertInput() { <START> visitChildren(TextArea.class, (Component component, final IVisit<Void> visit) -> { <END> if (component instanceof TextArea) { TextArea textArea = (TextArea) component; textArea.updateModel(); } }); setConvertedInput(new DefaultValueConfigurations(configurations)); }</code><technical_language>out lambda conversion verbose (component, visit) ->, compiler able infer argument types own. do purpose reader</technical_language>

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

Target:
public static boolean isManagementNetwork(Network net) { return Config.<String> GetValue(ConfigValues.ManagementNetwork).equals(net.getName()); }
Source:
<code>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; <START> if (StringUtils.equalsIgnoreCase(SecurityConfigConstants.USER_ACCESS_PREFIX + authentication.getName(), <END> attribute.getAttribute())) { return ACCESS_GRANTED; } } } logAccessResult(result, object); return result; }</code><technical_language>log if land return in this if</technical_language>

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; }
Source:
<code><START> public Set<Template> collectAvailableTemplates(EObject eObject, EReference eReference) { <END> final Set<Template> templates = new TreeSet<Template>(new Comparator<Template>() { @Override public int compare(Template left, Template right) { if (!left.getPriority().equals(right.getPriority())) { return left.getPriority().compareTo(right.getPriority()); } return -1; } }); if (templateProviders.isEmpty()) { return templates; } for (final TemplateProvider provider : templateProviders) { if (!provider.canProvide(eObject, eReference)) { continue; } for (final Template template : provider.provide(eObject, eReference)) { if (template.getInstance() == null) { reportError("Ignoring template '{0}', as it does not contain a valid EObject instance", null, template.getName()); continue; } templates.add(template); } } return templates; }</code><technical_language>is this public</technical_language>

Target:
protected Set<Template> collectAvailableTemplates(EObject eObject, EReference eReference) { final Set<Template> templates = new TreeSet<Template>(new Comparator<Template>() { @Override public int compare(Template left, Template right) { if (!left.getPriority().equals(right.getPriority())) { return left.getPriority().compareTo(right.getPriority()); } return -1; } }); if (templateProviders.isEmpty()) { return templates; } for (final TemplateProvider provider : templateProviders) { if (!provider.canProvide(eObject, eReference)) { continue; } for (final Template template : provider.provide(eObject, eReference)) { if (template.getInstance() == null) { reportError("Ignoring template '{0}', as it does not contain a valid EObject instance", null, template.getName()); continue; } templates.add(template); } } return templates; }
Source:
<code>void display(final PluginMap plugins) { <START> while (1 < table.getRowCount()) <END> table.removeRow(table.getRowCount() - 1); List<PluginInfo> list = plugins.values().asList(); for (final PluginInfo p : list) { final int row = table.getRowCount(); table.insertRow(row); applyDataRowStyle(row); populate(row, p); } }</code><technical_language>nit: I need {}s this</technical_language>

Target:
void display(final PluginMap plugins) { while (1 < table.getRowCount()) { table.removeRow(table.getRowCount() - 1); } for (final PluginInfo p : plugins.values().asList()) { final int row = table.getRowCount(); table.insertRow(row); applyDataRowStyle(row); populate(row, p); } }
Source:
<code>private String getHashKeyForDuet(HashingAlgorithm hashingAlgorithm, Boolean shouldEncodeHashKey, Integer maxDigestBytes, Integer maxHashLength, String encoder) { if (null == hashingAlgorithm) { return null; } final String key = hashingAlgorithm.toString()+ maxDigestBytes != null ? maxDigestBytes.toString() : "-" + maxHashLength != null ? maxHashLength.toString() : "-" + encoder != null ? encoder : "-"; String val = hashedKeysByAlgorithmForDuet.get(key); if(val == null) { val = KeyHasher.getHashedKeyEncoded(getCanonicalKeyForDuet(), hashingAlgorithm, maxDigestBytes, maxHashLength, encoder); hashedKeysByAlgorithmForDuet.put(key , val); } <START> return null; <END> }</code><technical_language>return val</technical_language>

Target:
private String getHashKeyForDuet(HashingAlgorithm hashingAlgorithm, Boolean shouldEncodeHashKey, Integer maxDigestBytes, Integer maxHashLength, String encoder) { if (null == hashingAlgorithm) { return null; } final String key = hashingAlgorithm.toString()+ maxDigestBytes != null ? maxDigestBytes.toString() : "-" + maxHashLength != null ? maxHashLength.toString() : "-" + encoder != null ? encoder : "-"; String val = hashedKeysByAlgorithmForDuet.get(key); if(val == null) { val = KeyHasher.getHashedKeyEncoded(getCanonicalKeyForDuet(), hashingAlgorithm, maxDigestBytes, maxHashLength, encoder); hashedKeysByAlgorithmForDuet.put(key , val); } return val; }