auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object instantiateItem(ViewGroup container, int position) { this.container=container; LayoutInflater inflater = LayoutInflater.from(container.getContext()); ViewGroup layout = (ViewGroup) inflater.inflate(PAGE_LAYOUTS[position], container, false); <START> if ( BuildConfig.FLAVOR == "beta"){ <END> TextView textView = (TextView) layout.findViewById(R.id.welcomeYesButton); if ( textView.getVisibility() != View.VISIBLE){ textView.setVisibility(View.VISIBLE); } ViewHolder holder = new ViewHolder(layout); layout.setTag(holder); if (position == PAGE_FINAL){ TextView moreInfo = layout.findViewById(R.id.welcomeInfo); moreInfo.setText(Html.fromHtml(WelcomeActivity.moreInformation)); ViewHolder holder1 = new ViewHolder(layout); layout.setTag(holder1); } } else { if (position == PAGE_FINAL) { ViewHolder holder = new ViewHolder(layout); layout.setTag(holder); } } container.addView(layout); return layout; }</code><technical_language>suggestion if (BuildConfig.FLAVOR == "beta") {</technical_language>

Target:
public Object instantiateItem(ViewGroup container, int position) { this.container=container; LayoutInflater inflater = LayoutInflater.from(container.getContext()); ViewGroup layout = (ViewGroup) inflater.inflate(PAGE_LAYOUTS[position], container, false); if (BuildConfig.FLAVOR == "beta") { TextView textView = layout.findViewById(R.id.welcomeYesButton); if (textView.getVisibility() != View.VISIBLE) { textView.setVisibility(View.VISIBLE); } ViewHolder holder = new ViewHolder(layout); layout.setTag(holder); if (position == PAGE_FINAL){ TextView moreInfo = layout.findViewById(R.id.welcomeInfo); moreInfo.setText(Html.fromHtml(WelcomeActivity.moreInformation)); ViewHolder holder1 = new ViewHolder(layout); layout.setTag(holder1); } } else { if (position == PAGE_FINAL) { ViewHolder holder = new ViewHolder(layout); layout.setTag(holder); } } container.addView(layout); return layout; }
Source:
<code>public void testPlatformAuthHandlerAvailable() throws Exception { if (!TestUtils.isCompatibilityAuthInstalled()) { <START> return; <END> } URL url = new URL("http://mylyn"); Platform.addAuthorizationInfo(url, "", "", Collections.EMPTY_MAP); assertNotNull("Tests require org.eclipse.core.runtime.compatibility.auth", Platform.getAuthorizationInfo(url, "", "")); }</code><technical_language>print a message test skipped do for browser tests</technical_language>

Target:
public void testPlatformAuthHandlerAvailable() throws Exception { if (!TestUtils.isCompatibilityAuthInstalled()) { System.err.println("Skipping TaskRepositoryCredentialsTest.testPlatformAuthHandlerAvailable()"); return; } URL url = new URL("http://mylyn"); Platform.addAuthorizationInfo(url, "", "", Collections.EMPTY_MAP); assertNotNull("Tests require org.eclipse.core.runtime.compatibility.auth", Platform.getAuthorizationInfo(url, "", "")); }
Source:
<code>public void timestampFiltersAreAdapted() { TimestampRangeFilter filter = new TimestampRangeFilter(10L, 20L); Filters.Filter expectedFilter = filterAdapter.adapt(emptyScanContext, filter); <START> Assert.assertEquals(10000L, expectedFilter.toProto().getTimestampRangeFilter().getStartTimestampMicros()); <END> Assert.assertEquals(20000L, expectedFilter.toProto().getTimestampRangeFilter().getEndTimestampMicros()); }</code><technical_language>please extract a variable for expectedFilter.toProto().getTimestampRangeFilter()</technical_language>

Target:
public void timestampFiltersAreAdapted() { TimestampRangeFilter filter = new TimestampRangeFilter(10L, 20L); Filters.Filter expectedFilter = filterAdapter.adapt(emptyScanContext, filter); TimestampRange expectedTimestampFilter = expectedFilter.toProto().getTimestampRangeFilter(); Assert.assertEquals(10000L, expectedTimestampFilter.getStartTimestampMicros()); Assert.assertEquals(20000L, expectedTimestampFilter.getEndTimestampMicros()); }
Source:
<code>public int[] getDefaultTokens() { return new int[] { TokenTypes.LITERAL_TRY, TokenTypes.LITERAL_CATCH, TokenTypes.LITERAL_FINALLY, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_ELSE, <START> TokenTypes.LAMBDA, <END> }; }</code><technical_language>@romani acceptable tokens in this check default. is ok lambda here? I add default tokens token do damage. decide this for lambda in this check</technical_language>

Target:
public int[] getDefaultTokens() { return new int[] { TokenTypes.LITERAL_TRY, TokenTypes.LITERAL_CATCH, TokenTypes.LITERAL_FINALLY, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_ELSE, }; }
Source:
<code>public boolean accept(File file) { <START> if (file.lastModified() / ONE_SECOND + this.age <= System.currentTimeMillis()) { <END> return true; } else if (this.discardCallback != null) { this.discardCallback.accept(file); } return false; }</code><technical_language>filterFiles() logic: missing divide System.currentTimeMillis() ONE_SECOND</technical_language>

Target:
public boolean accept(File file) { if (fileIsAged(file, System.currentTimeMillis() / ONE_SECOND)) { return true; } else if (this.discardCallback != null) { this.discardCallback.accept(file); } return false; }
Source:
<code>public boolean setSubtreeChecked(Object element, boolean state) { <START> IPreCheckStateListener preCheckStateListener = fPreCheckStateListener; <END> if (preCheckStateListener != null && preCheckStateListener.setSubtreeChecked(element, state)) { setChecked(element, false); return false; } checkSubtree(element, state); return fCheckboxTreeViewer.setSubtreeChecked(element, state); }</code><technical_language>This get executed in case TriStateFilteredCheckboxTree overrides setSubtreeChecked()</technical_language>

Target:
public boolean setSubtreeChecked(Object element, boolean state) { checkSubtree(element, state); return fCheckboxTreeViewer.setSubtreeChecked(element, state); }
Source:
<code>public void activate() { if (baseStation != null) { <START> logger.info("Smarthomatic Binding activated. BaseStation=" + baseStation.toString()); <END> } Bundle bundle = SmarthomaticActivator.getContext().getBundle(); URL fileURL = bundle.getEntry("xml/packet_layout.xml"); Packet packet = null; try { InputStream inputStream = fileURL.openConnection().getInputStream(); JAXBContext jaxbContext = JAXBContext.newInstance(Packet.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); packet = (Packet) jaxbUnmarshaller.unmarshal(inputStream); } catch (IOException e1) { e1.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } this.packet = packet; }</code><technical_language>Please logback parametrization instead of string concatenation</technical_language>

Target:
public void activate() { if (baseStation != null) { logger.info("Smarthomatic Binding activated. BaseStation= {}", baseStation.toString()); } Bundle bundle = SmarthomaticActivator.getContext().getBundle(); URL fileURL = bundle.getEntry("packet_layout.xml"); Packet packet = null; try { InputStream inputStream = fileURL.openConnection().getInputStream(); JAXBContext jaxbContext = JAXBContext.newInstance(Packet.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); packet = (Packet) jaxbUnmarshaller.unmarshal(inputStream); } catch (IOException e1) { e1.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } this.packet = packet; }
Source:
<code>public HttpServerResponse setStreamPriority(StreamPriority streamPriority) { if(!streamPriority.equals(stream.getStreamPriority())) { stream.setStreamPriority(streamPriority); <START> if(headWritten) { <END> stream.writePriorityFrame(); } } return this; }</code><technical_language>I stream figure out needs send a priority frame internally. HTTP/2 stream if header frame</technical_language>

Target:
public HttpServerResponse setStreamPriority(StreamPriority streamPriority) { if(!streamPriority.equals(stream.priority())) { stream.priority(streamPriority); if(headWritten) { stream.writePriorityFrame(); } } return this; }
Source:
<code>private boolean createJenkinsHook(GHRepository repo, URL url) { try { if (getDescriptor().isUseWebHooks()) { Collection<GHEvent> events = new ArrayList(); <START> events.add(GHEvent.PULL_REQUEST); <END> repo.createWebHook(new URL(url.toExternalForm()), events); } else { repo.createHook("jenkins", Collections.singletonMap("jenkins_hook_url", url.toExternalForm()), null, true); } return true; } catch (IOException e) { throw new GHException("Failed to update jenkins hooks", e); } }</code><technical_language>This plugin PRs</technical_language>

Target:
private boolean createJenkinsHook(GHRepository repo, URL url) { try { if (getDescriptor().isUseWebHooks()) { repo.createWebHook(new URL(url.toExternalForm())); } else { repo.createHook("jenkins", Collections.singletonMap("jenkins_hook_url", url.toExternalForm()), null, true); } return true; } catch (IOException e) { throw new GHException("Failed to update jenkins hooks", e); } }
Source:
<code>public byte[] getCacheKey() { byte[] fieldNameBytes = StringUtils.toUtf8WithNullToEmpty(fieldName); byte[] fieldExpressionBytes = StringUtils.toUtf8WithNullToEmpty(fieldExpression); <START> return ByteBuffer.allocate(1 + fieldNameBytes.length + fieldExpressionBytes.length) <END> .put(CACHE_TYPE_ID).put(fieldNameBytes).put(fieldExpressionBytes).array(); }</code><technical_language>place 0xff guys, in event a fieldName is matches a fieldExpression results</technical_language>

Target:
public byte[] getCacheKey() { byte[] fieldNameBytes = StringUtils.toUtf8WithNullToEmpty(fieldName); byte[] expressionBytes = StringUtils.toUtf8WithNullToEmpty(expression); return ByteBuffer.allocate(2 + fieldNameBytes.length + expressionBytes.length) .put(CACHE_TYPE_ID) .put(fieldNameBytes) .put(AggregatorUtil.STRING_SEPARATOR) .put(expressionBytes) .array(); }
Source:
<code>private void redraw() { renderFixtures(); kiePage.refresh(view, versionRecordManager.getCurrentPath(), <START> scenario); <END> importsWidget.setContent(dmo, scenario.getImports(), isReadOnly); }</code><technical_language>cover some tests</technical_language>

Target:
private void redraw() { renderFixtures(); settingsPage.refresh(view, versionRecordManager.getCurrentPath(), scenario); importsWidget.setContent(dmo, scenario.getImports(), isReadOnly); }
Source:
<code>private static JsonNode loadModulesYamlFile(String path) { try (InputStream is = new FileInputStream(path)) { <START> return yamlObjectMapper.readTree(is); <END> } catch (IOException e) { log.error("Failed to load a module's yaml property file at: {}", path); throw new InternalErrorException("Failed to load a module's yaml property file.", e); } }</code><technical_language>I prefer this of loading a YAML file: java YAMLMapper mapper = new YAMLMapper(); return mapper.readTree(new File(path));</technical_language>

Target:
private static JsonNode loadModulesYamlFile(String path) { try { YAMLMapper mapper = new YAMLMapper(); return mapper.readTree(new File(path)); } catch (IOException e) { log.error("Failed to load a module's yaml property file at: {}", path); throw new ModulePropertyNotFoundException("Failed to load a module's yaml property file.", e); } }
Source:
<code>protected boolean validateParameters() { if (getVdsGroup() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_CLUSTER_FOR_AFFINITY_GROUP); } if (getParameters().getAffinityGroup().getVmIds() != null) { VmStatic vmStatic = null; Set<Guid> vmSet = new HashSet<Guid>(); for (Guid vmId : getParameters().getAffinityGroup().getVmIds()) { <START> vmStatic = getVmStaticDAO().get(vmId); <END> if (vmStatic == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_VM_FOR_AFFINITY_GROUP); } if (!vmStatic.getVdsGroupId().equals(getVdsGroupId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_IN_AFFINITY_GROUP_CLUSTER); } if (vmSet.contains(vmStatic.getId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DUPLICTE_VM_IN_AFFINITY_GROUP); } else { vmSet.add(vmStatic.getId()); } } } return true; }</code><technical_language>Hmm... frequent is this called ? I loops of select in other places, still</technical_language>

Target:
protected boolean validateParameters() { if (getVdsGroup() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_CLUSTER_FOR_AFFINITY_GROUP); } if (getParameters().getAffinityGroup().getEntityIds() != null) { VmStatic vmStatic = null; Set<Guid> vmSet = new HashSet<Guid>(); for (Guid vmId : getParameters().getAffinityGroup().getEntityIds()) { vmStatic = getVmStaticDAO().get(vmId); if (vmStatic == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_VM_FOR_AFFINITY_GROUP); } if (!vmStatic.getVdsGroupId().equals(getVdsGroupId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_IN_AFFINITY_GROUP_CLUSTER); } if (vmSet.contains(vmStatic.getId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DUPLICTE_VM_IN_AFFINITY_GROUP); } else { vmSet.add(vmStatic.getId()); } } } return true; }
Source:
<code>public boolean doPreSetUserClaimValues(String userName, Map<String, String> claims, String profileName, UserStoreManager userStoreManager) throws UserStoreException { if(!IdentityValidationUtil.isValid(profileName,new String[]{"ALPHANUMERICS_ONLY","DIGITS_ONLY"},new String[]{ "WHITESPACE_EXISTS","URI_RESERVED_EXISTS","HTML_META_EXISTS","XML_META_EXISTS","REGEX_META_EXISTS", <START> "URL"})){ <END> throw new UserStoreException("profile name contains invalid characters!"); } return true; }</code><technical_language>constants</technical_language>

Target:
public boolean doPreSetUserClaimValues(String userName, Map<String, String> claims, String profileName, UserStoreManager userStoreManager) throws UserStoreException { if (!IdentityValidationUtil.isValid(profileName, new String[]{ALPHANUMERICS_ONLY, DIGITS_ONLY}, new String[]{ WHITESPACE_EXISTS, URI_RESERVED_EXISTS, HTML_META_EXISTS, XML_META_EXISTS, REGEX_META_EXISTS, URL})) { throw new UserStoreException("profile name contains invalid characters!"); } return true; }
Source:
<code>private long getTime(final Operator operator) { final WorkerQueryPartition workerQueryPartition = (WorkerQueryPartition) operator.getQueryPartition(); final long workerStartTimeMillis = workerQueryPartition.getBeginMilliseconds(); final long threadStartTimeMillis = operator.getSubTreeTask().getBeginMilliseconds(); <START> Preconditions.checkState(workerStartTimeMillis > 0, "Query initiualization time has not been recorded."); <END> Preconditions.checkState(threadStartTimeMillis > 0, "Thread time has not been recorded."); final long startupTimeMillis = threadStartTimeMillis - workerStartTimeMillis; Preconditions.checkState(startupTimeMillis >= 0, "Thread that works on fragment cannot run (%s) before query is initialized (%s).", workerStartTimeMillis, threadStartTimeMillis); final long threadStartNanos = operator.getSubTreeTask().getBeginNanoseconds(); final long activeTimeNanos = System.nanoTime() - threadStartNanos; return TimeUnit.MILLISECONDS.toNanos(startupTimeMillis) + activeTimeNanos; }</code><technical_language>typo</technical_language>

Target:
private long getTime(final Operator operator) { final WorkerQueryPartition workerQueryPartition = (WorkerQueryPartition) operator.getQueryPartition(); final long workerStartTimeMillis = workerQueryPartition.getBeginMilliseconds(); final long threadStartTimeMillis = operator.getSubTreeTask().getBeginMilliseconds(); Preconditions.checkState(workerStartTimeMillis > 0, "Query initialization time has not been recorded."); Preconditions.checkState(threadStartTimeMillis > 0, "Thread time has not been recorded."); final long startupTimeMillis = threadStartTimeMillis - workerStartTimeMillis; Preconditions.checkState(startupTimeMillis >= 0, "Thread that works on fragment cannot run (%s) before query is initialized (%s).", workerStartTimeMillis, threadStartTimeMillis); final long threadStartNanos = operator.getSubTreeTask().getBeginNanoseconds(); final long activeTimeNanos = System.nanoTime() - threadStartNanos; return TimeUnit.MILLISECONDS.toNanos(startupTimeMillis) + activeTimeNanos; }
Source:
<code>void pushFormAndAttachments(FormStatus form, List<Path> attachments, RunnerStatus runnerStatus, PushToAggregateTracker tracker, int part, int parts) { if (runnerStatus.isCancelled()) { tracker.trackCancellation("Push form"); return; } tracker.trackStartSendingFormAndAttachments(part, parts); Response<InputStream> response = http.execute(server.getPushFormRequest(form.getFormFile(briefcaseDir), attachments)); <START> for (InputStream stream : server.getFileStreams()) { closeInputStream(stream); } <END> server.getFileStreams().clear(); if (response.isSuccess()) tracker.trackEndSendingFormAndAttachments(part, parts); else tracker.trackErrorSendingFormAndAttachments(part, parts, response); }</code><technical_language>suggestion server.getFileStreams().forEach(UncheckedFiles::closeInputStream);</technical_language>

Target:
void pushFormAndAttachments(FormStatus form, List<Path> attachments, RunnerStatus runnerStatus, PushToAggregateTracker tracker, int part, int parts) { if (runnerStatus.isCancelled()) { tracker.trackCancellation("Push form"); return; } tracker.trackStartSendingFormAndAttachments(part, parts); Response response = http.execute(server.getPushFormRequest(form.getFormFile(briefcaseDir), attachments)); if (response.isSuccess()) tracker.trackEndSendingFormAndAttachments(part, parts); else tracker.trackErrorSendingFormAndAttachments(part, parts, response); }
Source:
<code>private Map<Pair<Integer, Integer>, ProjectVersion> loadExistingProjectsAsCache() { final Map<Pair<Integer, Integer>, ProjectVersion> allProjects = new ConcurrentHashMap<>(); logger.info("loading project dir metadata into memory"); for (final Path project : this.loadExistingProjects()) { if (Files.isDirectory(project)) { try { final String fileName = project.getFileName().toString(); final int projectId = Integer.parseInt(fileName.split("\\.")[0]); final int versionNum = Integer.parseInt(fileName.split("\\.")[1]); <START> final ProjectVersion version = <END> new ProjectVersion(projectId, versionNum, project.toFile()); final Path projectDirSizeFile = Paths .get(version.getInstalledDir().toString(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME); if (Files.exists(projectDirSizeFile)) { version.setDirSizeInBytes(FileIOUtils.readNumberFromFile(projectDirSizeFile)); } else { FlowPreparer.updateDirSize(version.getInstalledDir(), version); } allProjects.put(new Pair<>(projectId, versionNum), version); } catch (final Exception e) { logger.error("error while loading project dir metadata", e); } } logger.info("finish loading project dir metadata into memory"); } return allProjects; }</code><technical_language>naming called projVersion, version</technical_language>

Target:
private Map<Pair<Integer, Integer>, ProjectVersion> loadExistingProjectsAsCache() { final Map<Pair<Integer, Integer>, ProjectVersion> allProjects = new ConcurrentHashMap<>(); logger.info("loading project dir metadata into memory"); for (final Path project : this.loadExistingProjects()) { if (Files.isDirectory(project)) { try { final String fileName = project.getFileName().toString(); final int projectId = Integer.parseInt(fileName.split("\\.")[0]); final int versionNum = Integer.parseInt(fileName.split("\\.")[1]); final ProjectVersion projVersion = new ProjectVersion(projectId, versionNum, project.toFile()); final Path projectDirSizeFile = Paths .get(projVersion.getInstalledDir().toString(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME); if (!Files.exists(projectDirSizeFile)) { FlowPreparer.updateDirSize(projVersion.getInstalledDir(), projVersion); } projVersion.setDirSizeInBytes(FileIOUtils.readNumberFromFile(projectDirSizeFile)); allProjects.put(new Pair<>(projectId, versionNum), projVersion); } catch (final Exception e) { logger.error("error while loading project dir metadata", e); } } logger.info("finish loading project dir metadata into memory"); } return allProjects; }
Source:
<code>public void run_gradle_scirpt() { install("gradle-1.5", "1.5"); FreeStyleJob job = jenkins.jobs.create(); job.copyResource(resource("/gradle_plugin/script.gradle"), "build.gradle"); GradleStep step = job.addBuildStep(GradleStep.class); step.useVersion("gradle-1.5"); step.tasks.set("hello"); step.switches.set("--quiet"); job.save(); job.startBuild().shouldSucceed() .shouldContainsConsoleOutput("Hello world!") <START> .shouldContainsConsoleOutput("gradle[\\w\\\\/\"]* --quiet") <END> ; }</code><technical_language>gradle.*--quiet read fragile in case of other options that</technical_language>

Target:
public void run_gradle_scirpt() { install("gradle-1.5", "1.5"); FreeStyleJob job = jenkins.jobs.create(); job.copyResource(resource("/gradle_plugin/script.gradle"), "build.gradle"); GradleStep step = job.addBuildStep(GradleStep.class); step.useVersion("gradle-1.5"); step.tasks.set("hello"); step.switches.set("--quiet"); job.save(); job.startBuild().shouldSucceed() .shouldContainsConsoleOutput("Hello world!") .shouldContainsConsoleOutput("gradle.* --quiet") ; }
Source:
<code>public AsyncFuture<Void> mutateRow(final ByteString rowKey, final Mutations mutations) { return async.call(() -> { mutations.getMutations().forEach(mutation -> { switch (mutation.getMutationCase()) { case SET_CELL: final Mutation.SetCell setCell = mutation.getSetCell(); final ColumnFamily columnFamily = <START> table.getColumnFamily(setCell.getFamilyName()).get(); <END> if (columnFamily == null) { throw new IllegalArgumentException( "no such column family: " + setCell.getFamilyName()); } RowStorage rowStorage; synchronized (lock) { final Pair<ByteString, ColumnFamily> key = Pair.of(rowKey, columnFamily); rowStorage = rows.get(key); if (rowStorage == null) { rowStorage = new RowStorage(columnFamily); rows.put(key, rowStorage); } } rowStorage.runSetCell(setCell); break; default: throw new IllegalArgumentException( "Unsupported mutation: " + mutation.getMutationCase()); } }); return null; }); }</code><technical_language>Optional#orElseThrow(), get a non-descriptive error message optional is empty</technical_language>

Target:
public AsyncFuture<Void> mutateRow(final ByteString rowKey, final Mutations mutations) { return async.call(() -> { mutations.getMutations().forEach(mutation -> { switch (mutation.getMutationCase()) { case SET_CELL: final Mutation.SetCell setCell = mutation.getSetCell(); final ColumnFamily columnFamily = table .getColumnFamily(setCell.getFamilyName()) .orElseThrow(() -> new IllegalArgumentException( "no such column family: " + setCell.getFamilyName())); final RowStorage rowStorage; synchronized (lock) { final Pair<ByteString, ColumnFamily> key = Pair.of(rowKey, columnFamily); rowStorage = rows.computeIfAbsent(key, k -> new RowStorage(columnFamily)); } rowStorage.runSetCell(setCell); break; default: throw new IllegalArgumentException( "Unsupported mutation: " + mutation.getMutationCase()); } }); return null; }); }
Source:
<code>public String getInlineComments(int lines) { StringBuilder cmts = new StringBuilder(); final Repository repo = getRepository(); try { PatchList patchList = null; if (repo != null) { try { patchList = getPatchList(); } catch (PatchListNotAvailableException e) { patchList = null; } } Patch.Key currentFileKey = null; PatchFile currentFileData = null; for (final PatchLineComment c : inlineComments) { final Patch.Key pk = c.getKey().getParentKey(); if (!pk.equals(currentFileKey)) { if (Patch.COMMIT_MSG.equals(pk.get())) { cmts.append("Commit Message\n"); } else { <START> cmts.append(makeChangeLink(pk)); <END> cmts.append("\n"); cmts.append("File "); cmts.append(pk.getFileName()); cmts.append(":\n\n"); } currentFileKey = pk; if (patchList != null) { try { currentFileData = new PatchFile(repo, patchList, pk.get()); } catch (IOException e) { log.warn(String.format( "Cannot load %s from %s in %s", pk.getFileName(), patchList.getNewId().name(), projectState.getProject().getName()), e); currentFileData = null; } } } if (currentFileData != null) { appendComment(cmts, lines, currentFileData, c); } cmts.append("\n\n"); } } finally { if (repo != null) { repo.close(); } } return cmts.toString(); }</code><technical_language>COMMIT_MSG file hyperlinked to</technical_language>

Target:
public String getInlineComments(int lines) { StringBuilder cmts = new StringBuilder(); final Repository repo = getRepository(); try { PatchList patchList = null; if (repo != null) { try { patchList = getPatchList(); } catch (PatchListNotAvailableException e) { patchList = null; } } Patch.Key currentFileKey = null; PatchFile currentFileData = null; for (final PatchLineComment c : inlineComments) { final Patch.Key pk = c.getKey().getParentKey(); if (!pk.equals(currentFileKey)) { String link = makeLink(pk); if (link != null) { cmts.append(link).append('\n'); } if (Patch.COMMIT_MSG.equals(pk.get())) { cmts.append("Commit Message:\n\n"); } else { cmts.append("File ").append(pk.get()).append(":\n\n"); } currentFileKey = pk; if (patchList != null) { try { currentFileData = new PatchFile(repo, patchList, pk.get()); } catch (IOException e) { log.warn(String.format( "Cannot load %s from %s in %s", pk.getFileName(), patchList.getNewId().name(), projectState.getProject().getName()), e); currentFileData = null; } } } if (currentFileData != null) { appendComment(cmts, lines, currentFileData, c); } cmts.append("\n\n"); } } finally { if (repo != null) { repo.close(); } } return cmts.toString(); }
Source:
<code>public boolean eIsSet(int featureID) { switch (featureID) { case Csw20Package.QUERY_TYPE__ELEMENT_SET_NAME: return elementSetName != null; case Csw20Package.QUERY_TYPE__ELEMENT_NAME: return elementName != null && !elementName.isEmpty(); case Csw20Package.QUERY_TYPE__CONSTRAINT: return constraint != null; case Csw20Package.QUERY_TYPE__SORT_BY: <START> return SORT_BY_EDEFAULT == null ? sortBy != null : !Arrays.equals(SORT_BY_EDEFAULT, sortBy); <END> case Csw20Package.QUERY_TYPE__TYPE_NAMES: return typeNames != null; } return super.eIsSet(featureID); }</code><technical_language>I error prone in IntelliJ, @aaime guidance. error prone require some configuration ignore autogenerated folders</technical_language>

Target:
public boolean eIsSet(int featureID) { switch (featureID) { case Csw20Package.QUERY_TYPE__ELEMENT_SET_NAME: return elementSetName != null; case Csw20Package.QUERY_TYPE__ELEMENT_NAME: return elementName != null && !elementName.isEmpty(); case Csw20Package.QUERY_TYPE__CONSTRAINT: return constraint != null; case Csw20Package.QUERY_TYPE__SORT_BY: return SORT_BY_EDEFAULT == null ? sortBy != null : !SORT_BY_EDEFAULT.equals(sortBy); case Csw20Package.QUERY_TYPE__TYPE_NAMES: return typeNames != null; } return super.eIsSet(featureID); }
Source:
<code>public Collection<ReceiveCommand> getCommands() { <START> synchronized (lock) { <END> return commands; } }</code><technical_language>is this lock doing? list is returned unprotected. return unmodifiable list is created setting it</technical_language>

Target:
public Collection<ReceiveCommand> getCommands() { return commands; }
Source:
<code>public void toDuplicateCounterString(StringBuilder sb) { <START> sb.append("Unexpected Heartbeat"); <END> }</code><technical_language>2 messages "unexpected heartbeat": in caps this one. want more precise? e.g. "unexpected heartbeat" (no caps) for heartbeat "unexpected coalesced heartbeat" for this one</technical_language>

Target:
public void toDuplicateCounterString(StringBuilder sb) { sb.append("Unexpected Coalesced Heartbeat"); }
Source:
<code>public int hashCode() { final int prime = 31; int result = super.hashCode(); <START> result = prime * result + (Boolean.TRUE.equals(usingScsiReservation) ? 1231 : 1237); <END> result = prime * result + ((lun == null) ? 0 : lun.hashCode()); return result; }</code><technical_language>prefer implementation similar line 55 here</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((usingScsiReservation == null) ? 0 : usingScsiReservation.hashCode()); result = prime * result + ((lun == null) ? 0 : lun.hashCode()); return result; }
Source:
<code>Builder(MongoDBTracing mongoDBTracing) { this(mongoDBTracing.tracing); <START> maxAbbreviatedCommandLength(mongoDBTracing.maxAbbreviatedCommandLength); <END> clearCommandsWithCollectionName(); addAllCommandsWithCollectionName(mongoDBTracing.commandsWithCollectionName); }</code><technical_language>set maxAbbreviatedCommandLength = t.maxAbbreviated... need validate values a built object</technical_language>

Target:
Builder(MongoDBTracing mongoDBTracing) { tracing = mongoDBTracing.tracing; }
Source:
<code>public Mono<ServiceBusReceiverAsyncClient> acceptSession(String sessionId) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null")); } if (CoreUtils.isNullOrEmpty(sessionId)) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be empty")); } final ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), receiverOptions.getMaxLockRenewDuration(), receiverOptions.isEnableAutoComplete(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); if (CoreUtils.isNullOrEmpty(sessionId)) { return sessionSpecificManager.getActiveLink().map(receiveLink -> new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager)); <START> } else { <END> ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.getOrCreateConsumerAsync().map(consumer -> new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, consumer)); } }</code><technical_language>sessionId null empty for this method. This branch reachable runtime</technical_language>

Target:
public Mono<ServiceBusReceiverAsyncClient> acceptSession(String sessionId) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null")); } if (CoreUtils.isNullOrEmpty(sessionId)) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be empty")); } final ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), receiverOptions.getMaxLockRenewDuration(), receiverOptions.isEnableAutoComplete(), sessionId, null); ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.createConsumerWithReceiveLink() .thenReturn(sessionSpecificAsyncClient); }
Source:
<code>public static User fromLdapUser(InetOrgPerson details) { final UserImpl user = new UserImpl(); final List<String> roles = new ArrayList<String>(); for (final GrantedAuthority ga : details.getAuthorities()) { roles.add(removePrefix(ga.toString(), LimsSecurityUtils.rolePrefix)); } user.setRoles(roles.toArray(new String[0])); user.setActive(details.isAccountNonExpired()); <START> user.setAdmin(roles.contains(new GrantedAuthorityImpl("ROLE_ADMIN"))); <END> user.setExternal(roles.contains(new GrantedAuthorityImpl("ROLE_EXTERNAL"))); user.setInternal(roles.contains(new GrantedAuthorityImpl("ROLE_INTERNAL"))); user.setLoginName(details.getUsername().toLowerCase()); if (details.getPassword() == null) { log.debug("This directory has been configured correctly and has properly returned a null password. Setting fake password " + "to satisfy the requirements of the MISO User object."); user.setPassword("fake_password_2905058jf8j84t1gkxi96841mvck48s9575"); } else { user.setPassword(details.getPassword()); } user.setFullName(details.getDisplayName()); user.setEmail(details.getMail()); return user; }</code><technical_language>GrantedAuthorityImpls get rolled constants</technical_language>

Target:
public static User fromLdapUser(InetOrgPerson details) { final UserImpl user = new UserImpl(); final List<String> roles = new ArrayList<String>(); for (final GrantedAuthority ga : details.getAuthorities()) { roles.add(removePrefix(ga.toString(), LimsSecurityUtils.rolePrefix)); } user.setRoles(roles.toArray(new String[0])); user.setActive(details.isAccountNonExpired()); user.setAdmin(roles.contains(MisoAuthority.ROLE_ADMIN.name())); user.setExternal(roles.contains(MisoAuthority.ROLE_EXTERNAL.name())); user.setInternal(roles.contains(MisoAuthority.ROLE_INTERNAL.name())); user.setLoginName(details.getUsername().toLowerCase()); user.setPassword(details.getPassword()); user.setFullName(details.getDisplayName()); user.setEmail(details.getMail()); return user; }
Source:
<code>private void writeAudits(final List<AccountGroupMember> toBeRemoved) throws OrmException { final Account.Id me = ((IdentifiedUser) self.get()).getAccountId(); for (final AccountGroupMember m : toBeRemoved) { AccountGroupMemberAudit audit = null; for (AccountGroupMemberAudit a : db.accountGroupMembersAudit() .byGroupAccount(m.getAccountGroupId(), m.getAccountId())) { if (a.isActive()) { audit = a; break; } } if (audit != null) { audit.removed(me); <START> db.accountGroupMembersAudit().update(Collections.singleton(audit)); <END> } else { audit = new AccountGroupMemberAudit(m, me); audit.removedLegacy(); db.accountGroupMembersAudit().insert(Collections.singleton(audit)); } } }</code><technical_language>batch updates inserts temporary lists in this method</technical_language>

Target:
private void writeAudits(final List<AccountGroupMember> toBeRemoved) throws OrmException { final Account.Id me = ((IdentifiedUser) self.get()).getAccountId(); final List<AccountGroupMemberAudit> auditUpdates = Lists.newLinkedList(); final List<AccountGroupMemberAudit> auditInserts = Lists.newLinkedList(); for (final AccountGroupMember m : toBeRemoved) { AccountGroupMemberAudit audit = null; for (AccountGroupMemberAudit a : db.accountGroupMembersAudit() .byGroupAccount(m.getAccountGroupId(), m.getAccountId())) { if (a.isActive()) { audit = a; break; } } if (audit != null) { audit.removed(me); auditUpdates.add(audit); } else { audit = new AccountGroupMemberAudit(m, me); audit.removedLegacy(); auditInserts.add(audit); } } db.accountGroupMembersAudit().update(auditUpdates); db.accountGroupMembersAudit().insert(auditInserts); }
Source:
<code><START> public boolean canSwitchToBroker() throws DeveloperAuthenticationException { <END> String packageName = mContext.getPackageName(); return !AuthenticationSettings.INSTANCE.getSkipBroker() && verifyManifestPermissions() && checkAccount(mAcctManager, "", "") && !packageName.equalsIgnoreCase(AuthenticationSettings.INSTANCE .getBrokerPackageName()) && !packageName .equalsIgnoreCase(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME) && verifyAuthenticator(mAcctManager); }</code><technical_language>I hope move verifyManifestPermission end of check. If signature of broker match, sense throw error calling app some permissions missing</technical_language>

Target:
public boolean canSwitchToBroker() throws UsageAuthenticationException { String packageName = mContext.getPackageName(); return AuthenticationSettings.INSTANCE.getUseBroker() && checkAccount(mAcctManager, "", "") && !packageName.equalsIgnoreCase(AuthenticationSettings.INSTANCE .getBrokerPackageName()) && !packageName .equalsIgnoreCase(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME) && verifyAuthenticator(mAcctManager) && verifyManifestPermissions(); }
Source:
<code>public void stop() { <START> pool.shutdownNow(); END> regionNormalizerTracker.stop(); }</code><technical_language>Ok if stopped? idempotent</technical_language>

Target:
public void stop() { synchronized (startStopLock) { if (!started) { throw new IllegalStateException("calling `stop` without first calling `start`."); } if (stopped) { return; } pool.shutdownNow(); regionNormalizerTracker.stop(); stopped = true; } }
Source:
<code>public void setStartTime(Long startTime) { <START> this.startTime = Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault()).toLocalDateTime(); <END> }</code><technical_language>setters Long param check null Instant.ofEpochMilli() fail NullPointerException. safely set null base object instead</technical_language>

Target:
public void setStartTime(Long startTime) { if (startTime != null) { this.startTime = Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault()).toLocalDateTime(); } else { this.startTime = null; } }
Source:
<code>public static @Nullable ITmfEventAspect<?> create(Iterable<ITmfEventAspect<?>> aspects, Class<?> aspectClass) { int size = Iterables.size(aspects); <START> if (size == 0) { return null; } if (size == 1) { return Iterables.get(aspects, 0); } <END> Set<String> names = new HashSet<>(); for (ITmfEventAspect<?> aspect : aspects) { if (aspect.getClass().isAssignableFrom(aspectClass)) { names.add(aspect.getName()); } else { throw new IllegalArgumentException("Aspects must belong to the same class as the \"aspectClass\" parameter."); } } if (names.size() != 1) { StringJoiner sj = new StringJoiner(", "); names.forEach(sj::add); LOGGER.log(Level.WARNING, () -> "Aspects do not have the same name: " + sj.toString()); } return new MultiAspect<>(Iterables.get(names, 0), aspects); }</code><technical_language>a problem: nullable annotations bananas. :(</technical_language>

Target:
public static @Nullable ITmfEventAspect<?> create(Iterable<ITmfEventAspect<?>> aspects, Class<?> aspectClass) { int size = Iterables.size(aspects); if (size == 0 || size == 1) { return Iterables.getFirst(aspects, null); } Set<String> names = new HashSet<>(); for (ITmfEventAspect<?> aspect : aspects) { if (aspect.getClass().isAssignableFrom(aspectClass)) { names.add(aspect.getName()); } else { throw new IllegalArgumentException("Aspects must belong to the same class as the \"aspectClass\" parameter."); } } if (names.size() != 1) { StringJoiner sj = new StringJoiner(", "); names.forEach(sj::add); LOGGER.log(Level.WARNING, () -> "Aspects do not have the same name: " + sj.toString()); } return new MultiAspect<>(Iterables.get(names, 0), aspects); }
Source:
<code>public void run() { <START> Socket socket; <END> OutputStream outputStream = null; try { socket = serverSocket.accept(); String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { } finally { StreamUtils.quietlyClose(outputStream); } }</code><technical_language>again: removing explicit initialization: worse,</technical_language>

Target:
public void run() { Socket socket = null; OutputStream outputStream = null; try { socket = serverSocket.accept(); String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { } finally { StreamUtils.quietlyClose(outputStream); } }
Source:
<code>public static MessageType fromId(String id) { for(MessageType current : values()) { <START> if(current.getId().equals(id)) { <END> return current; } } return UNKNOWN; }</code><technical_language>Minor: Please add space reserved keywords if for</technical_language>

Target:
public static Optional<MessageType> fromId(String id) { for (MessageType current : values()) { if (current.getId().equals(id)) { return Optional.of(current); } } return Optional.empty(); }
Source:
<code>private void checkForDuplicates(List<WindupRuleProvider> providers) { Set<WindupRuleProvider> dupeSet = new HashSet<>(providers.size()); for (WindupRuleProvider provider : providers) { if (dupeSet.contains(provider)) { <START> throw new WindupException("Found two providers with the same id: " + provider.getID()); <END> } dupeSet.add(provider); } }</code><technical_language>I if this list duplicate instances / types</technical_language>

Target:
private void checkForDuplicates(List<WindupRuleProvider> providers) { Map<WindupRuleProvider, WindupRuleProvider> dupeSet = new HashMap<>(providers.size()); for (WindupRuleProvider provider : providers) { WindupRuleProvider previousProvider = dupeSet.get(provider); if (previousProvider != null) { String typeMessage; if (previousProvider.getClass().equals(provider.getClass())) { typeMessage = " (type: " + Proxies.unwrapProxyClassName(provider.getClass()) + ")"; } else { typeMessage = " (types: " + Proxies.unwrapProxyClassName(previousProvider.getClass()) + " and " + Proxies.unwrapProxyClassName(provider.getClass()) + ")"; } throw new WindupException("Found two providers with the same id: " + provider.getID() + typeMessage); } dupeSet.put(provider, provider); } }
Source:
<code>public void setup() throws Exception{ this.metadataStore = new HazelcastMetadataStore(map); <START> metadataStore.afterPropertiesSet(); <END> }</code><technical_language>this. for properties access. Checkstyle concern</technical_language>

Target:
public void setup() throws Exception { this.metadataStore = new HazelcastMetadataStore(map); this.metadataStore.afterPropertiesSet(); }
Source:
<code>public CompletableFuture<Optional<Pair<PublicKeyHash, PublicBoxingKey>>> getPublicKeys(String username) { CompletableFuture<Optional<Pair<PublicKeyHash, PublicBoxingKey>>> empty = new CompletableFuture<>(); empty.complete(Optional.empty()); return network.coreNode.getPublicKeyHash(username) <START> .thenCompose(signerOpt -> !signerOpt.isPresent() ? empty : getSigningKey(signerOpt.get()) <END> .thenCompose(signer -> getWriterData(network, signerOpt.get(), signerOpt.get()) .thenCompose(wd -> getBoxingKey(wd.props.followRequestReceiver.get()) .thenApply(boxer -> Optional.of(new Pair<>(signerOpt.get(), boxer)))))); }</code><technical_language>signingOpt.map(..).orElse(CompleteableFuture.completedFuture(Optional.empty()))</technical_language>

Target:
public CompletableFuture<Optional<Pair<PublicKeyHash, PublicBoxingKey>>> getPublicKeys(String username) { return network.coreNode.getPublicKeyHash(username) .thenCompose(signerOpt -> signerOpt.map(signer -> getSigningKey(signer) .thenCompose(signer2 -> getWriterData(network, signerOpt.get(), signerOpt.get()) .thenCompose(wd -> getBoxingKey(wd.props.followRequestReceiver.get()) .thenApply(boxer -> Optional.of(new Pair<>(signerOpt.get(), boxer)))))) .orElse(CompletableFuture.completedFuture(Optional.empty()))); }
Source:
<code>private String getTerm(URL url) throws MalformedURLException { String query = url.getQuery(); if (query != null) return Utils.parseUrlQuery(query, "tags"); if (query == null) { if ((query = url.getPath()).startsWith("/post/index/")) { query = query.substring(12); int pos = query.indexOf('/'); if (pos == -1) return null; query = query.substring(pos + 1); if (query.endsWith("/")) query = query.substring(0, query.length() - 1); <START> try { <END> return URLDecoder.decode(query, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } else if (query.startsWith("/pool/show/")) { query = query.substring(11); if (query.endsWith("/")) query = query.substring(0, query.length() - 1); return query; } } return null; }</code><technical_language>completely remove implementation of sanitizeURL</technical_language>

Target:
private String getTerm(URL url) throws MalformedURLException{ if(gidPattern==null) gidPattern=Pattern.compile("^https?://(www\\.)?e621\\.net/post/index/[^/]+/([a-zA-Z0-9$_.+!*'(),%-]+)(/.*)?(#.*)?$"); if(gidPatternPool==null) gidPatternPool=Pattern.compile("^https?://(www\\.)?e621\\.net/pool/show/([a-zA-Z0-9$_.+!*'(),%-]+)(\\?.*)?(/.*)?(#.*)?$"); Matcher m = gidPattern.matcher(url.toExternalForm()); if(m.matches()) return m.group(2); m = gidPatternPool.matcher(url.toExternalForm()); if(m.matches()) return m.group(2); throw new MalformedURLException("Expected e621.net URL format: e621.net/post/index/1/searchterm - got "+url+" instead"); }
Source:
<code>public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (status == NO_ERROR_STATUS) { complete(buf.readInt()); } else { <START> complete(XAResource.XA_OK); <END> } }</code><technical_language>Is other status expected? completeExceptionally here</technical_language>

Target:
public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (status == NO_ERROR_STATUS) { complete(buf.readInt()); } else { complete(XAException.XA_HEURRB); } }
Source:
<code>public void onRequestPermissionsResult (int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (mCurrentChangeRequest == null) { <START> throw new IllegalStateException("mCurrentChangeRequest should be set before using cached request"); <END> } if (requestCode == REQUEST_AUDIO_PERMISSION && permissions.length == 1) { recreateEditingUi(mCurrentChangeRequest); } if (requestCode == REQUEST_CAMERA_PERMISSION && permissions.length == 1) { recreateEditingUi(mCurrentChangeRequest); } }</code><technical_language>This is basically a guaranteed crash right? avoided costs, making future work. A toast a fall note editor is throwing a RuntimeException if avoid</technical_language>

Target:
public void onRequestPermissionsResult (int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (mCurrentChangeRequest == null) { cancelActivityWithAssertionFailure("mCurrentChangeRequest should be set before requesting permissions"); return; } Timber.d("onRequestPermissionsResult. Code: %d", requestCode); if (requestCode == REQUEST_AUDIO_PERMISSION && permissions.length == 1) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { recreateEditingUIUsingCachedRequest(); return; } UIUtils.showThemedToast(this, getResources().getString(R.string.multimedia_editor_audio_permission_refused), true); UIRecreationHandler.onRequiredPermissionDenied(mCurrentChangeRequest, this); } if (requestCode == REQUEST_CAMERA_PERMISSION && permissions.length == 1) { if (grantResults[0] != PackageManager.PERMISSION_GRANTED) { UIUtils.showThemedToast(this, getResources().getString(R.string.multimedia_editor_camera_permission_refused), true); } recreateEditingUIUsingCachedRequest(); } }