auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ListenableFuture<?> deliver(List<NodeRefreshRequest> events) { Map<InetSocketAddress, HostEvent> hosts = new HashMap<InetSocketAddress, HostEvent>(); for (NodeRefreshRequest req : events) { hosts.put(req.address, req.eventType); } List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(hosts.size()); for (final Entry<InetSocketAddress, HostEvent> entry : hosts.entrySet()) { InetSocketAddress address = entry.getKey(); HostEvent eventType = entry.getValue(); switch (eventType) { case UP: Host upHost = metadata.getHost(address); if (upHost == null) { upHost = metadata.add(address); if (upHost == null) continue; futures.add(schedule(hostAdded(upHost))); } else { futures.add(schedule(hostUp(upHost))); } break; case ADDED: Host newHost = metadata.add(address); if (newHost != null) { futures.add(schedule(hostAdded(newHost))); } else { Host existingHost = metadata.getHost(address); if (!existingHost.isUp()) futures.add(schedule(hostUp(existingHost))); } break; case DOWN: Host downHost = metadata.getHost(address); if (downHost != null) { if (downHost.convictionPolicy.hasActiveConnections()) { <START> logger.debug("Ignoring down event on because it still has active connections"); <END> } else { futures.add(execute(hostDown(downHost))); } } break; case REMOVED: Host removedHost = metadata.getHost(address); if (removedHost != null) futures.add(execute(hostRemoved(removedHost))); break; } } return Futures.allAsList(futures); }</code><technical_language>downHost added argument logged</technical_language>

Target:
public ListenableFuture<?> deliver(List<NodeRefreshRequest> events) { Map<InetSocketAddress, HostEvent> hosts = new HashMap<InetSocketAddress, HostEvent>(); for (NodeRefreshRequest req : events) { hosts.put(req.address, req.eventType); } List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(hosts.size()); for (final Entry<InetSocketAddress, HostEvent> entry : hosts.entrySet()) { InetSocketAddress address = entry.getKey(); HostEvent eventType = entry.getValue(); switch (eventType) { case UP: Host upHost = metadata.getHost(address); if (upHost == null) { upHost = metadata.add(address); if (upHost == null) continue; futures.add(schedule(hostAdded(upHost))); } else { futures.add(schedule(hostUp(upHost))); } break; case ADDED: Host newHost = metadata.add(address); if (newHost != null) { futures.add(schedule(hostAdded(newHost))); } else { Host existingHost = metadata.getHost(address); if (!existingHost.isUp()) futures.add(schedule(hostUp(existingHost))); } break; case DOWN: Host downHost = metadata.getHost(address); if (downHost != null) { if (downHost.convictionPolicy.hasActiveConnections()) { logger.debug("Ignoring down event on because it still has active connections", downHost); } else { futures.add(execute(hostDown(downHost))); } } break; case REMOVED: Host removedHost = metadata.getHost(address); if (removedHost != null) futures.add(execute(hostRemoved(removedHost))); break; } } return Futures.allAsList(futures); }
Source:
<code>public ExtendedHostStatuses getExtendedHostStatuses() { <START> Map<HostName, Collection<ApiHealthCheck>> hostHealth = getHostHealth(); <END> Map<HostName, ClusterManagerState> clusterManagerStateByHost = hostHealth.entrySet().stream() .flatMap(this::getScmHealthForHost) .collect(toMap(Pair::getLeft, Pair::getRight)); boolean hostCertExpiring = isHostCertExpiring(hostHealth); return new ExtendedHostStatuses(clusterManagerStateByHost, hostCertExpiring); }</code><technical_language>please add a log lines methods</technical_language>

Target:
public ExtendedHostStatuses getExtendedHostStatuses() { Map<HostName, Collection<ApiHealthCheck>> hostHealth = getHostHealth(); Map<HostName, ClusterManagerState> clusterManagerStateByHost = hostHealth.entrySet().stream() .flatMap(this::getScmHealthForHost) .collect(toMap(Pair::getLeft, Pair::getRight)); boolean hostCertExpiring = isHostCertExpiring(hostHealth); LOGGER.debug("Creating 'ExtendedHostStatuses' with and cert expiring [{}]", clusterManagerStateByHost, hostCertExpiring); return new ExtendedHostStatuses(clusterManagerStateByHost, hostCertExpiring); }
Source:
<code>public void notifyUnlock(Collection<? extends EObject> elements) { <START> for (IAuthorityListener listener : Lists.newArrayList(listeners)) { <END> listener.notifyIsReleased((Collection<EObject>) elements); } }</code><technical_language>do a new array do iteration? If is avoid ConcurrentModificationException in multi-thread case, a synchronized block more adapted</technical_language>

Target:
public void notifyUnlock(Collection<? extends EObject> elements) { for (IAuthorityListener listener : listeners) { listener.notifyIsReleased((Collection<EObject>) elements); } }
Source:
<code>public int getKeyBinding(int key) { checkWidget(); Integer action = <START> keyActionMap.get(new Integer(key)); <END> return action == null ? SWT.NULL : action.intValue(); }</code><technical_language>Revert</technical_language>

Target:
public int getKeyBinding(int key) { checkWidget(); Integer action = keyActionMap.get(key); return action == null ? SWT.NULL : action.intValue(); }
Source:
<code>private static AbstractConfigObject loadEnvVariables() { Properties props = new Properties(); props.putAll(System.getenv()); return (AbstractConfigObject) Parseable.newProperties(props, <START> ConfigParseOptions.defaults().setOriginDescription("env variables")).parse(); <END> }</code><technical_language>a cleaner I add a static method in PropertiesParser.java akin fromProperties instead fromStringMap(Map<String,String>), avoid Parseable indirection avoid creating a Properties object here</technical_language>

Target:
private static AbstractConfigObject loadEnvVariables() { return PropertiesParser.fromStringMap(newSimpleOrigin("env variables"), System.getenv()); }
Source:
<code>public Result getBuildResult(Boolean ignoreRunError) { if (ignoreRunError != null && ignoreRunError && "ERRORED".equals(result)) { if (totalCount == skipCount) { <START> result = "SKIPPED"; <END> } else if (stopCount > 0) { result = "STOPPED"; } else if (errorCount > 0) { result = "ERRORED"; } else if (failCount > 0) { result = "FAILED"; } else if (warnCount > 0) { result = "WARNED"; } else { result = "PASSED"; } } return resultMap.get(result); }</code><technical_language>enum consts for result strings</technical_language>

Target:
public Result getBuildResult(Boolean ignoreRunError) { if (ignoreRunError != null && ignoreRunError && ExecutionResult.ERRORED.equals(result)) { if (totalCount == skipCount) { result = ExecutionResult.SKIPPED; } else if (stopCount > 0) { result = ExecutionResult.STOPPED; } else if (errorCount > 0) { result = ExecutionResult.ERRORED; } else if (failCount > 0) { result = ExecutionResult.FAILED; } else if (warnCount > 0) { result = ExecutionResult.WARNED; } else { result = ExecutionResult.PASSED; } } return resultMap.get(result); }
Source:
<code>private void assignLegalAndShared(boolean legalAndShared) { <START> UpdateAllTemplateDisksParameters parameters = new UpdateAllTemplateDisksParameters(getVmTemplateId(), legalAndShared, legalAndShared ? true : null); parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); parameters.setEndProcedure(VdcActionParametersBase.EndProcedure.COMMAND_MANAGED); <END> getBackend().runInternalAction(VdcActionType.UpdateAllTemplateDisks, parameters, cloneContextAndDetachFromParent()); }</code><technical_language>please extract a separate method</technical_language>

Target:
private void assignLegalAndShared(boolean legalAndShared) { VdcReturnValueBase returnValue = runInternalAction(VdcActionType.UpdateAllTemplateDisks, buildUpdateAllTemplateDisksParameters(legalAndShared), ExecutionHandler.createDefaultContextForTasks(getContext())); if (!returnValue.getSucceeded()) { throw new EngineException(returnValue.getFault().getError(), returnValue.getFault().getMessage()); } }
Source:
<code>private CommentDetail setCommentDetails(PatchSet.Id leftId, PatchSet.Id rightId, String fileName, IProgressMonitor monitor) throws GerritException { CommentDetail commentDetail = new CommentDetail(leftId, rightId); if (leftId != null) { Map<String, List<CommentInfo>> commentInfo_A = retrieveRevisionComments(leftId, monitor); adaptCommentDetails(commentInfo_A, leftId, commentDetail.getCommentsA(), fileName, commentDetail); } Map<String, List<CommentInfo>> commentInfo_B = retrieveRevisionComments(rightId, monitor); adaptCommentDetails(commentInfo_B, rightId, commentDetail.getCommentsB(), fileName, commentDetail); ChangeInfo changeInfo = getChangeInfo(rightId.getParentKey().get(), monitor); List<com.google.gerrit.common.data.AccountInfo> listAccountInfo = new ArrayList<com.google.gerrit.common.data.AccountInfo>(); com.google.gerrit.common.data.AccountInfo accountInfo = setAccountFromChangeInfo(changeInfo); listAccountInfo.add(accountInfo); <START> @SuppressWarnings("unchecked") <END> AccountInfoCache accCache = new AccountInfoCache(listAccountInfo); commentDetail.setAccountInfoCache(accCache); return commentDetail; }</code><technical_language>do need suppress warnings here</technical_language>

Target:
private CommentDetail setCommentDetails(PatchSet.Id leftId, PatchSet.Id rightId, String fileName, IProgressMonitor monitor) throws GerritException { CommentDetail commentDetail = new CommentDetail(leftId, rightId); if (leftId != null) { Map<String, List<CommentInfo>> commentInfo_A = retrieveRevisionComments(leftId, monitor); adaptCommentDetails(commentInfo_A, leftId, commentDetail.getCommentsA(), fileName, commentDetail); } Map<String, List<CommentInfo>> commentInfo_B = retrieveRevisionComments(rightId, monitor); adaptCommentDetails(commentInfo_B, rightId, commentDetail.getCommentsB(), fileName, commentDetail); ChangeInfo changeInfo = getChangeInfo(rightId.getParentKey().get(), monitor); List<com.google.gerrit.common.data.AccountInfo> listAccountInfo = new ArrayList<com.google.gerrit.common.data.AccountInfo>(); com.google.gerrit.common.data.AccountInfo accountInfo = setAccountFromChangeInfo(changeInfo); listAccountInfo.add(accountInfo); AccountInfoCache accCache = new AccountInfoCache(listAccountInfo); commentDetail.setAccountInfoCache(accCache); return commentDetail; }
Source:
<code>public void repartition(final String topic, final int partitionsNumber) throws CannotAddPartitionToTopicException, TopicConfigException { try (AdminClient adminClient = AdminClient.create(kafkaLocationManager.getProperties())) { adminClient.createPartitions(ImmutableMap.of(topic, NewPartitions.increaseTo(partitionsNumber))); final long timeoutMillis = TimeUnit.SECONDS.toMillis(5); <START> final Boolean allowsConsumption = Retryer.executeWithRetry(() -> { <END> try (Consumer<byte[], byte[]> consumer = kafkaFactory.getConsumer()) { return consumer.partitionsFor(topic).size() == partitionsNumber; } }, new RetryForSpecifiedTimeStrategy<Boolean>(timeoutMillis) .withWaitBetweenEachTry(100L) .withResultsThatForceRetry(Boolean.FALSE)); if (!Boolean.TRUE.equals(allowsConsumption)) { throw new TopicConfigException(String.format("Failed to repartition topic to %s", partitionsNumber)); } final Producer<String, String> producer = kafkaFactory.takeProducer(); kafkaFactory.terminateProducer(producer); kafkaFactory.releaseProducer(producer); } catch (Exception e) { throw new CannotAddPartitionToTopicException(String .format("Failed to increase the number of partition for %s topic to %s", topic, partitionsNumber), e); } }</code><technical_language>allowsConsumption ? :)</technical_language>

Target:
public void repartition(final String topic, final int partitionsNumber) throws CannotAddPartitionToTopicException, TopicConfigException { try (AdminClient adminClient = AdminClient.create(kafkaLocationManager.getProperties())) { adminClient.createPartitions(ImmutableMap.of(topic, NewPartitions.increaseTo(partitionsNumber))); final long timeoutMillis = TimeUnit.SECONDS.toMillis(5); final Boolean areNewPartitionsAdded = Retryer.executeWithRetry(() -> { try (Consumer<byte[], byte[]> consumer = kafkaFactory.getConsumer()) { return consumer.partitionsFor(topic).size() == partitionsNumber; } }, new RetryForSpecifiedTimeStrategy<Boolean>(timeoutMillis) .withWaitBetweenEachTry(100L) .withResultsThatForceRetry(Boolean.FALSE)); if (!Boolean.TRUE.equals(areNewPartitionsAdded)) { throw new TopicConfigException(String.format("Failed to repartition topic to %s", partitionsNumber)); } final Producer<String, String> producer = kafkaFactory.takeProducer(); kafkaFactory.terminateProducer(producer); kafkaFactory.releaseProducer(producer); } catch (Exception e) { throw new CannotAddPartitionToTopicException(String .format("Failed to increase the number of partition for %s topic to %s", topic, partitionsNumber), e); } }
Source:
<code>public String toString() { <START> return "AssetRecord [assetStatus=" + this.assetStatus + ", channelId=" + this.channelName + ", timestamp=" <END> + this.timestamp + ", value=" + this.value + "]"; }</code><technical_language>channelId => channelName</technical_language>

Target:
public String toString() { return "AssetRecord [assetStatus=" + this.assetStatus + ", channelName=" + this.channelName + ", timestamp=" + this.timestamp + ", value=" + this.value + "]"; }
Source:
<code>public boolean handleRequest(RestRequest originalRequest, RestRequest darkRequest, RequestContext requestContext) { <START> int numRequestDuplicates = getNumDuplicateRequests(_random.nextFloat()); <END> return _baseDarkClusterDispatcher.sendRequest(originalRequest, darkRequest, requestContext, numRequestDuplicates); }</code><technical_language>need include _random argument instance variable</technical_language>

Target:
public boolean handleRequest(RestRequest originalRequest, RestRequest darkRequest, RequestContext requestContext) { int numRequestDuplicates = getNumDuplicateRequests(); return _baseDarkClusterDispatcher.sendRequest(originalRequest, darkRequest, requestContext, numRequestDuplicates); }
Source:
<code>public void canRebase() throws GitAPIException, IOException, RestApiException, Exception { <START> String subject = "test commit"; String file = "a.txt"; String contents = "contents"; <END> PushOneCommit push = pushFactory.create(db, admin.getIdent()); PushOneCommit.Result r1 = push.to(git, "refs/for/master"); merge(r1); push = pushFactory.create(db, admin.getIdent(), "non-conflicting", "b.txt", "other contents"); PushOneCommit.Result r2 = push.to(git, "refs/for/master"); assertFalse(gApi.changes() .id(r2.getChangeId()) .revision(r2.getCommit().name()) .canRebase()); merge(r2); git.checkout().setName(r1.getCommit().name()).call(); push = pushFactory.create(db, admin.getIdent(), subject, file, contents); PushOneCommit.Result r3 = push.to(git, "refs/for/master"); assertTrue(gApi.changes() .id(r3.getChangeId()) .revision(r3.getCommit().name()) .canRebase()); }</code><technical_language>put in variables if line 168</technical_language>

Target:
public void canRebase() throws GitAPIException, IOException, RestApiException, Exception { PushOneCommit push = pushFactory.create(db, admin.getIdent()); PushOneCommit.Result r1 = push.to(git, "refs/for/master"); merge(r1); push = pushFactory.create(db, admin.getIdent()); PushOneCommit.Result r2 = push.to(git, "refs/for/master"); assertFalse(gApi.changes() .id(r2.getChangeId()) .revision(r2.getCommit().name()) .canRebase()); merge(r2); git.checkout().setName(r1.getCommit().name()).call(); push = pushFactory.create(db, admin.getIdent()); PushOneCommit.Result r3 = push.to(git, "refs/for/master"); assertTrue(gApi.changes() .id(r3.getChangeId()) .revision(r3.getCommit().name()) .canRebase()); }
Source:
<code>public TDJobSummary checkStatus() { try { return ensureRunningOrSucceeded(); } catch (TDJobException ex) { try { TDJob job = getJobInfo(); String message = job.getCmdOut() + "\n" + job.getStdErr(); throw new TaskExecutionException(message, buildExceptionErrorConfig(ex)); } catch (Exception getJobInfoFailed) { getJobInfoFailed.addSuppressed(ex); throw Throwables.propagate(getJobInfoFailed); } } catch (InterruptedException ex) { <START> throw Throwables.propagate(ex); <END> } }</code><technical_language>Restore interrupted status</technical_language>

Target:
public TDJobSummary checkStatus() { try { return ensureRunningOrSucceeded(); } catch (TDJobException ex) { try { TDJob job = getJobInfo(); String message = job.getCmdOut() + "\n" + job.getStdErr(); throw new TaskExecutionException(message, buildExceptionErrorConfig(ex)); } catch (Exception getJobInfoFailed) { getJobInfoFailed.addSuppressed(ex); throw Throwables.propagate(getJobInfoFailed); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw Throwables.propagate(ex); } }
Source:
<code>public static void verifyBlobContents(Digest expected, Digest actual) throws IOException { if (!expected.equals(actual)) { String msg = String.format( "Output download failed: Expected to download a blob of %d bytes with hash '%s', " + "got %d bytes with '%s'.", <START> expected.getSizeBytes(), expected.getHash(), actual.getSizeBytes(), actual.getHash()); <END> throw new IOException(msg); } }</code><technical_language>Personally, prefer format digests <hash>/<size>. WDYT</technical_language>

Target:
public static void verifyBlobContents(Digest expected, Digest actual) throws IOException { if (!expected.equals(actual)) { String msg = String.format( "Output download failed: Expected digest '%s/%d' does not match " + "received digest '%s/%d'.", expected.getHash(), expected.getSizeBytes(), actual.getHash(), actual.getSizeBytes()); throw new IOException(msg); } }
Source:
<code>void failsContainerOnEmptyName() { var results = execute("testWithEmptyName", String.class); results.allEvents().assertThatEvents() <START> .haveAtLeast(1, event(container(), displayName("testWithEmptyName(String)"), END> finishedWithFailure(message(msg -> msg.contains("must be declared with a non-empty name"))))); }</code><technical_language>do need modify this test</technical_language>

Target:
void failsContainerOnEmptyName() { var results = execute("testWithEmptyName", String.class); results.allEvents().assertThatEvents() .haveExactly(1, event(container(), displayName("testWithEmptyName(String)"), finishedWithFailure(message(msg -> msg.contains("must be declared with a non-empty name"))))); }
Source:
<code>private static Map<String, Function> initFunctions() { final HashMap<String, Function> m = new HashMap<String, Function>(); m.put("toLowerCase", new Function() { @Override String apply(String a) { return a.toLowerCase(); } }); m.put("toUpperCase", new Function() { @Override String apply(String a) { return a.toUpperCase(); } }); m.put("localPart", new Function() { @Override String apply(String a) { int at = a.indexOf('@'); return at < 0 ? a : a.substring(0, at); <START> } <END> }); m.put("localPartLowerCase", new Function() { @Override String apply(String a) { String s = a.toLowerCase(); int at = s.indexOf('@'); return at < 0 ? s : s.substring(0, at); } }); m.put("localPartUpperCase", new Function() { @Override String apply(String a) { String s = a.toUpperCase(); int at = s.indexOf('@'); return at < 0 ? s : s.substring(0, at); } }); return Collections.unmodifiableMap(m); }</code><technical_language>a super class: class LocalPartFunction extends Function { @Override String apply(String a) { int = a.indexOf('@'); return < 0 ? a : a.substring(0, at); } } reused below</technical_language>

Target:
private static Map<String, Function> initFunctions() { final HashMap<String, Function> m = new HashMap<String, Function>(); m.put("toLowerCase", new Function() { @Override String apply(String a) { return a.toLowerCase(); } }); m.put("toUpperCase", new Function() { @Override String apply(String a) { return a.toUpperCase(); } }); m.put("localPart", new Function() { @Override String apply(String a) { int at = a.indexOf('@'); return at < 0 ? a : a.substring(0, at); } }); return Collections.unmodifiableMap(m); }
Source:
<code><START> protected Map<String, Object> getRequestedEntities(XmlrpcControllerSlice ndlSlice) { <END> Map<String, Object> ticketedRequestEntities = new HashMap<>(); if ((ndlSlice.getComputedReservations() != null) && (ndlSlice.getComputedReservations().size() > 0)) { for (TicketReservationMng currRes : ndlSlice.getComputedReservations()) { Map<String, Object> currResMap = currRes.toMap(); ticketedRequestEntities.put(currRes.getReservationID(), currResMap); } } return ticketedRequestEntities; }</code><technical_language>I this a method XmlrpcControllerSlice</technical_language>

Target:
protected Map<String, Object> getRequestedEntities(XmlrpcControllerSlice ndlSlice) { Map<String, Object> ticketedRequestEntities = new HashMap<>(); if ((ndlSlice.getComputedReservations() != null) && (ndlSlice.getComputedReservations().size() > 0)) { for (TicketReservationMng currRes : ndlSlice.getComputedReservations()) { ticketedRequestEntities.put(currRes.getReservationID(), currRes.toMap()); } } return ticketedRequestEntities; }
Source:
<code><START> public RevTree getTree(ObjectId id) { <END> return getIfPresent(id, RevTree.class); }</code><technical_language>type specific getters call get instead of getIfPresent, supposed fail if object is found, instead of returning null</technical_language>

Target:
public RevTree getTree(ObjectId id) { return get(id, RevTree.class); }
Source:
<code>public void init() { <START> isDebug = (getInitParameter("debug", Boolean.class) == null) ? false : getInitParameter("debug", Boolean.class); <END> }</code><technical_language>If modify this changeset, give a try Optional</technical_language>

Target:
public void init() { isDebug = Optional.ofNullable(getInitParameter("debug", Boolean.class)).orElse(false); }
Source:
<code>public BuildStepMonitor getRequiredMonitorService() { <START> return BuildStepMonitor.NONE; <END> }</code><technical_language>This is default behavior need override it</technical_language>

Target:
public BuildStepMonitor getRequiredMonitorService() { return buildStep.getRequiredMonitorService(); }
Source:
<code>private void onIncrementTime(CommandTime self, MinecraftServer server, int time, MinecraftServer server2, ICommandSender sender, String[] args) { <START> World world = sender.getEntityWorld(); <END> world.setWorldTime(world.getWorldTime() + time); }</code><technical_language>reason separate this</technical_language>

Target:
private void onIncrementTime(CommandTime self, MinecraftServer server, int time, MinecraftServer server2, ICommandSender sender, String[] args) { sender.getEntityWorld().setWorldTime(sender.getEntityWorld().getWorldTime() + time); }
Source:
<code>private ListenableFuture<Connection> enqueue(int maxQueueSize) { if (maxQueueSize == 0) { return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is busy (no available connection and the max queue size is 0)")); } while (true) { int count = pendingBorrowCount.get(); if (count >= maxQueueSize) { return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is busy (no available connection and the queue has reached its max size " + maxQueueSize <START> + " )")); <END> } if (pendingBorrowCount.compareAndSet(count, count + 1)) { break; } } SettableFuture<Connection> future = SettableFuture.create(); pendingBorrows.add(future); return future; }</code><technical_language>extra space here, i.e. : reached max size 256 )</technical_language>

Target:
private ListenableFuture<Connection> enqueue(int maxQueueSize) { if (maxQueueSize == 0) { return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), 0)); } while (true) { int count = pendingBorrowCount.get(); if (count >= maxQueueSize) { return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), maxQueueSize)); } if (pendingBorrowCount.compareAndSet(count, count + 1)) { break; } } SettableFuture<Connection> future = SettableFuture.create(); pendingBorrows.add(future); if (phase.get() == Phase.CLOSING) { future.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); } return future; }
Source:
<code>private ResponseEntity processJSONException(final JSONException e, final NativeWebRequest nativeWebRequest) { <START> if (e.getCause() == null) { <END> return create(crateProblem(e), nativeWebRequest); } return create(Problem.valueOf(Response.Status.BAD_REQUEST), nativeWebRequest); }</code><technical_language>is correct. interested exceptions cause</technical_language>

Target:
private ResponseEntity processJSONException(final JSONException e, final NativeWebRequest nativeWebRequest) { if (e.getCause() == null) { return create(createProblem(e), nativeWebRequest); } return create(Problem.valueOf(Response.Status.BAD_REQUEST), nativeWebRequest); }
Source:
<code>private void updateTitle() { if(tableSorter==null || !tableSorter.isFiltered()) { <START> dockingPanelParameters.setTitle(I18N.tr("Table Editor of {0} {1}/{2}",tableEditableElement.getSourceName(),table.getSelectedRowCount(),table.getRowCount())); <END> }else{ dockingPanelParameters.setTitle(I18N.tr("Table Editor of {0} (Filtered) {1}/{2}",tableEditableElement.getSourceName(),table.getSelectedRowCount(),table.getRowCount())); } }</code><technical_language>lines long... nice lines more 100 characters. I this is possible, are, for instance, easy break</technical_language>

Target:
private void updateTitle() { String sourceName = tableEditableElement.getSourceName(); int tableSelectedRowCount = table.getSelectedRowCount(); int tableRowCount = table.getRowCount(); if(tableSorter==null || !tableSorter.isFiltered()) { dockingPanelParameters.setTitle( I18N.tr("Table Editor of {0} {1}/{2}", sourceName,tableSelectedRowCount,tableRowCount)); }else{ dockingPanelParameters.setTitle( I18N.tr("Table Editor of {0} (Filtered) {1}/{2}", sourceName,tableSelectedRowCount,tableRowCount)); } }
Source:
<code>public void batchedTimestampCallShouldReturnAtLeastOneUsableTimestamp() { when(allocator.getRelevantModuli(UUID_ONE)).thenReturn(RESIDUE_ONE); when(timestamps.getFreshTimestamps(anyInt())) .thenReturn(TIMESTAMP_RANGE); <START> assertThat(service.getFreshTimestampsForClient(UUID_ONE, 2).stream()) <END> .hasSize(1) .first() .isEqualTo(RESIDUE_ONE_TIMESTAMP_IN_RANGE.timestamp()); verify(allocator).getRelevantModuli(UUID_ONE); verify(timestamps).getFreshTimestamps(anyInt()); }</code><technical_language>is a containsExactly method here? assertThat(service.getFreshTimestampsForClient(UUID_ONE, 2).stream()).containsExactly(RESIDUE_ONE_TIMESTAMP_IN_RANGE.timstamp());</technical_language>

Target:
public void batchedTimestampCallShouldReturnAtLeastOneUsableTimestamp() { when(allocator.getRelevantModuli(UUID_ONE)).thenReturn(RESIDUE_ONE); when(timestamps.getFreshTimestamps(anyInt())) .thenReturn(TIMESTAMP_RANGE); assertThat(service.getFreshTimestampsForClient(UUID_ONE, 2).stream()) .containsExactly(RESIDUE_ONE_TIMESTAMP_IN_RANGE.timestamp()); verify(allocator).getRelevantModuli(UUID_ONE); verify(timestamps).getFreshTimestamps(anyInt()); }
Source:
<code>public void checkAutocompleteFeature() { editor.selectTabByName(PYTHON_FILE_NAME); editor.goToPosition(18, 53); <START> editor.typeTextIntoEditor("\n\n"); <END> editor.typeTextIntoEditor("object = MyClass()\nprint(object."); editor.launchAutocompleteAndWaitContainer(); editor.waitTextIntoAutocompleteContainer("function"); editor.waitTextIntoAutocompleteContainer("var"); editor.waitTextIntoAutocompleteContainer("variable"); editor.enterAutocompleteProposal("function() "); editor.waitTextIntoEditor("print(object.function"); editor.typeTextIntoEditor("())"); }</code><technical_language>typeTextIntoEditor commands united single command: editor.typeTextIntoEditor("\n\nobject = MyClass()\nprint(object.");</technical_language>

Target:
public void checkAutocompleteFeature() { editor.selectTabByName(PYTHON_FILE_NAME); editor.goToPosition(19, 1); editor.typeTextIntoEditor("\n\nobject = MyClass()\nprint(object."); editor.launchAutocompleteAndWaitContainer(); editor.waitTextIntoAutocompleteContainer("function"); editor.waitTextIntoAutocompleteContainer("var"); editor.waitTextIntoAutocompleteContainer("variable"); editor.enterAutocompleteProposal("function() "); editor.waitTextIntoEditor("print(object.function"); }
Source:
<code>private <T> CachedObject<T> getCachedObject(String cacheKey) { try { return cache.get(Preconditions.checkNotNull(cacheKey)); } catch (Exception e) { <START> log.error(String.format("Error accessing cache using key: %s", cacheKey), e); <END> return null; } }</code><technical_language>do this slf4j: <LINK_0></technical_language>

Target:
private <T> CachedObject<T> getCachedObject(String cacheKey) { try { return cache.get(Preconditions.checkNotNull(cacheKey)); } catch (Exception e) { log.error("Error accessing cache using key: {}", cacheKey, e); return null; } }
Source:
<code>protected void executeCommand() { List<String> errors = new ArrayList<String>(); entity = getGlusterHookDao().getById(getParameters().getHookId()); for (Guid upServerId : getUpServerIds()) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.EnableGlusterHook, new GlusterHookVDSParameters(upServerId, entity.getGlusterCommand(), entity.getGlusterHookStage(), entity.getName())); if (!returnValue.getSucceeded()) { errors.add(returnValue.getVdsError().getMessage()); } } if (!errors.isEmpty()) { handleVdsErrors(AuditLogType.GLUSTER_HOOK_ENABLE_FAILED, errors); } <START> <END> if (getUpServerIds().size() > errors.size()) { UpdateHookStatusInDb(getParameters().getClusterId(), entity.getName(), GlusterHookStatus.ENABLED); setSucceeded(true); } }</code><technical_language>status set enabled in DB if hook enable succeeded servers in cluster</technical_language>

Target:
protected void executeCommand() { List<String> errors = new ArrayList<String>(); entity = getGlusterHooksDao().getById(getParameters().getHookId()); List <VDS> servers = getAllUpServers(getParameters().getClusterId()); for (VDS upServer : servers) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.EnableGlusterHook, new GlusterHookVDSParameters(upServer.getId(), entity.getGlusterCommand(), entity.getStage(), entity.getName())); if (!returnValue.getSucceeded()) { errors.add(returnValue.getVdsError().getMessage()); saveServerHookInDb(getParameters().getHookId(), upServer.getId(), entity.getChecksum(), entity.getStatus()); updateHookInSyncInDb(getParameters().getHookId(), false); } } if (servers.size() > errors.size()) { updateHookStatusInDb(getParameters().getHookId(), null, GlusterHookStatus.ENABLED); } setSucceeded(true); }
Source:
<code>private Expression readAggregate() { int tokenT = token.tokenType; <START> String udaf = token.tokenString; <END> Expression aggExpr; read(); readThis(Tokens.OPENBRACKET); aggExpr = readAggregateExpression(tokenT, udaf); readThis(Tokens.CLOSEBRACKET); if (token.tokenType == Tokens.OVER) { read(); aggExpr = readWindowSpecification(tokenT, aggExpr); if (aggExpr instanceof ExpressionWindowed) { ExpressionWindowed aggWinExpr = (ExpressionWindowed)aggExpr; if (aggWinExpr.isDistinct()) { throw Error.error("DISTINCT is not allowed in window functions.", "", -1); } } } return aggExpr; }</code><technical_language>variable name udaf is obvious is. more verbose variable names is more obvious is</technical_language>

Target:
private Expression readAggregate() { int tokenT = token.tokenType; String funcName = token.tokenString; Expression aggExpr; read(); readThis(Tokens.OPENBRACKET); aggExpr = readAggregateExpression(tokenT, funcName); readThis(Tokens.CLOSEBRACKET); if (token.tokenType == Tokens.OVER) { read(); aggExpr = readWindowSpecification(tokenT, aggExpr); if (aggExpr instanceof ExpressionWindowed) { ExpressionWindowed aggWinExpr = (ExpressionWindowed)aggExpr; if (aggWinExpr.isDistinct()) { throw Error.error("DISTINCT is not allowed in window functions.", "", -1); } } } return aggExpr; }
Source:
<code>public static int testInvokeMethodStatic1(boolean needsThrow) throws Throwable { if (needsThrow) { throw new Throwable("test exception"); } <START> return 567; <END> }</code><technical_language>nit: Consider a final field for readability</technical_language>

Target:
public static int testInvokeMethodStatic1(boolean needsThrow) throws Throwable { if (needsThrow) { throw new Throwable("test exception"); } return InvokeMethodTestInterface.RETURN_VALUE; }
Source:
<code>public EncounterListResult queryForAllEncountersByPatientId(Config config, String id) { String responseJson = getJson(config, "/encounter?patient={id}&v=full", id); List<Encounter> encounterList = new ArrayList<>(); <START> JsonArray allEncounters = prepareJsonArray(responseJson); <END> for (JsonElement encounter : allEncounters) { encounterList.add(checkVersionAndSetEncounter(config, encounter.toString())); } EncounterListResult encounters = new EncounterListResult(); encounters.setResults(encounterList); return encounters; }</code><technical_language>rename prepareJsonArray function prepareAllEncountersList remove additional allEncounters variable call function for declaration</technical_language>

Target:
public EncounterListResult queryForAllEncountersByPatientId(Config config, String id) { String responseJson = getJson(config, "/encounter?patient={id}&v=full", id); List<Encounter> encounterList = new ArrayList<>(); for (JsonElement encounter : prepareAllEncountersList(responseJson)) { encounterList.add(checkVersionAndSetEncounter(config, encounter.toString())); } EncounterListResult encounters = new EncounterListResult(); encounters.setResults(encounterList); return encounters; }
Source:
<code>public void createPdpFeedsFromRequestExtracts() { List<String> filesToProcess = getConcurRequestExtractFileService().getUnprocessedRequestExtractFiles(); if (filesToProcess.isEmpty()) { LOG.info("createPdpFeedsFromRequestExtracts: No Request Extract files found to process."); <START> getConcurRequestExtractReportService().sendResultsEmail(null, null); <END> } else { LOG.info("createPdpFeedsFromRequestExtracts: Found " + filesToProcess.size() + " file(s) to process."); for (String requestExtractFullyQualifiedFileName : filesToProcess) { try { LOG.info("createPdpFeedsFromRequestExtracts: Begin processing for filename: " + requestExtractFullyQualifiedFileName + "."); if (getConcurRequestExtractFileService().processFile(requestExtractFullyQualifiedFileName)) { LOG.info("createPdpFeedsFromRequestExtracts: SUCCESSFUL processing for Request Extract File: " + requestExtractFullyQualifiedFileName); } else { LOG.error("createPdpFeedsFromRequestExtracts: Processing was UNSUCCESSFUL for Request Extract File: " + requestExtractFullyQualifiedFileName); } } catch (Exception e) { LOG.error("createPdpFeedsFromRequestExtracts: Processing to create PDP Files from Request Extract [" + requestExtractFullyQualifiedFileName + "] generated Exception: " + e.getMessage()); } finally { getConcurBatchUtilityService().removeDoneFileFor(requestExtractFullyQualifiedFileName); } } } }</code><technical_language>add a separate service method for sending a no-files-processed email, need rely null values null-checks do so</technical_language>

Target:
public void createPdpFeedsFromRequestExtracts() { List<String> filesToProcess = getConcurRequestExtractFileService().getUnprocessedRequestExtractFiles(); if (filesToProcess.isEmpty()) { LOG.info("createPdpFeedsFromRequestExtracts: No Request Extract files found to process."); getConcurRequestExtractReportService().sendEmailThatNoFileWasProcesed(); } else { LOG.info("createPdpFeedsFromRequestExtracts: Found " + filesToProcess.size() + " file(s) to process."); for (String requestExtractFullyQualifiedFileName : filesToProcess) { try { LOG.info("createPdpFeedsFromRequestExtracts: Begin processing for filename: " + requestExtractFullyQualifiedFileName + "."); if (getConcurRequestExtractFileService().processFile(requestExtractFullyQualifiedFileName)) { LOG.info("createPdpFeedsFromRequestExtracts: SUCCESSFUL processing for Request Extract File: " + requestExtractFullyQualifiedFileName); } else { LOG.error("createPdpFeedsFromRequestExtracts: Processing was UNSUCCESSFUL for Request Extract File: " + requestExtractFullyQualifiedFileName); } } catch (Exception e) { LOG.error("createPdpFeedsFromRequestExtracts: Processing to create PDP Files from Request Extract [" + requestExtractFullyQualifiedFileName + "] generated Exception: " + e.getMessage()); } finally { getConcurBatchUtilityService().removeDoneFileFor(requestExtractFullyQualifiedFileName); } } } }
Source:
<code>protected void finalize() throws Throwable { if (!closed.get()) { log.warn("Not closed! Object was[%s]. Allowing gc to prevent leak.", object); } <START> super.finalize(); <END> }</code><technical_language>I this before</technical_language>

Target:
protected void finalize() throws Throwable { try { if (!closed.get()) { log.warn("Not closed! Object was[%s]. Allowing gc to prevent leak.", object); } } finally { super.finalize(); } }
Source:
<code>public ProfileGenericDataResponse getProfileGenericDataResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final ProfileGenericDataAsyncRequest request) throws OsgpException { LOGGER.debug("Incoming ProfileGenericDataAsyncRequest for meter: {}.", request.getDeviceIdentification()); ProfileGenericDataResponse response = null; try { final MeterResponseData meterResponseData = this.monitoringService .dequeueProfileGenericDataResponse(request.getCorrelationUid()); this.throwExceptionIfResultNotOk(meterResponseData, "retrieving profile generic data"); response = this.monitoringMapper.map(meterResponseData.getMessageData(), ProfileGenericDataResponse.class); } catch (final Exception e) { LOGGER.error( "Exception: while sending GetProfileGenericDataAsyncRequest for correlation UID: for organisation {}.", <START> new Object[] { e.getMessage(), request.getCorrelationUid(), organisationIdentification }); <END> this.handleException(e); } return response; }</code><technical_language>I missing something, array creation new Object[] { ... } is needed, removed</technical_language>

Target:
public ProfileGenericDataResponse getProfileGenericDataResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final ProfileGenericDataAsyncRequest request) throws OsgpException { LOGGER.debug("Incoming ProfileGenericDataAsyncRequest for meter: {}.", request.getDeviceIdentification()); ProfileGenericDataResponse response = null; try { final MeterResponseData meterResponseData = this.monitoringService .dequeueProfileGenericDataResponse(request.getCorrelationUid()); this.throwExceptionIfResultNotOk(meterResponseData, "retrieving profile generic data"); response = this.monitoringMapper.map(meterResponseData.getMessageData(), ProfileGenericDataResponse.class); } catch (final Exception e) { LOGGER.error( "Exception: while sending GetProfileGenericDataAsyncRequest for correlation UID: for organisation {}.", e.getMessage(), request.getCorrelationUid(), organisationIdentification); this.handleException(e); } return response; }
Source:
<code>public String getStudentStatus(StudentAttributes student) { if (student.isRegistered()) { return Const.STUDENT_COURSE_STATUS_JOINED; } else { <START> return Const.STUDENT_COURSE_STATUS_YET_TO_JOIN; <END> } }</code><technical_language>This a duplicate of getStudentStatus() in StudentAttributes. Is necessary redirect of calls getStudentStatus() (of classes) of them</technical_language>

Target:
public String getStudentStatus(StudentAttributes student) { return student.getStudentStatus(); }
Source:
<code>public PlanImpl build() { for (final String namespace : evaluatorsToAdd.keySet()) { for (final String evaluator : evaluatorsToAdd.get(namespace)) { if (evaluatorsToDelete.containsKey(namespace) && evaluatorsToDelete.get(namespace).contains(evaluator)) { <START> throw new RuntimeException(evaluator + " is planned both for addition and deletion."); <END> } } if (!allTransferSteps.containsKey(namespace)) { continue; } for (final TransferStep transferStep : allTransferSteps.get(namespace)) { if (evaluatorsToDelete.containsKey(namespace) && evaluatorsToDelete.get(namespace).contains(transferStep.getDstId())) { throw new RuntimeException(transferStep.getDstId() + " is planned for deletion."); } else if (evaluatorsToAdd.containsKey(namespace) && evaluatorsToAdd.get(namespace).contains(transferStep.getSrcId())) { throw new RuntimeException(transferStep.getSrcId() + " is planned for addition."); } } } return new PlanImpl(evaluatorsToAdd, evaluatorsToDelete, allTransferSteps); }</code><technical_language>for **both** addition deletion</technical_language>

Target:
public PlanImpl build() { for (final String namespace : evaluatorsToAdd.keySet()) { for (final String evaluator : evaluatorsToAdd.get(namespace)) { if (evaluatorsToDelete.containsKey(namespace) && evaluatorsToDelete.get(namespace).contains(evaluator)) { throw new RuntimeException(evaluator + " is planned for both addition and deletion."); } } if (!allTransferSteps.containsKey(namespace)) { continue; } for (final TransferStep transferStep : allTransferSteps.get(namespace)) { if (evaluatorsToDelete.containsKey(namespace) && evaluatorsToDelete.get(namespace).contains(transferStep.getDstId())) { throw new RuntimeException(transferStep.getDstId() + " is planned for deletion."); } else if (evaluatorsToAdd.containsKey(namespace) && evaluatorsToAdd.get(namespace).contains(transferStep.getSrcId())) { throw new RuntimeException(transferStep.getSrcId() + " is planned for addition."); } } } return new PlanImpl(evaluatorsToAdd, evaluatorsToDelete, allTransferSteps); }
Source:
<code>public InputStream getInputStream(String filepath) { File f = new File(filepath); if (f.isFile() && f.canRead()) { try { return new FileInputStream(f); } catch (FileNotFoundException e) { logger.debug("Configuration file could not be found even though we just checked it can be read...", filepath); } <START> } <END> return null; }</code><technical_language>worth adding else { logger.debug(..)? wrong filepath is user input</technical_language>

Target:
public InputStream getInputStream(String filepath) { File f = new File(filepath); if (f.isFile() && f.canRead()) { try { return new FileInputStream(f); } catch (FileNotFoundException e) { logger.debug("Configuration file could not be found even though we just checked it can be read...", filepath); } } else { logger.debug("The configuration file (which resolves to absolute path {}) doesn't exist, is not a file" + " or is not readable.", f, f.getAbsolutePath()); } return null; }
Source:
<code>private void shutdownExecutors() throws InterruptedException { if (persistExecutor != null) { persistExecutor.shutdownNow(); Preconditions.checkState( <START> persistExecutor.awaitTermination(365, TimeUnit.DAYS), <END> "persistExecutor not terminated" ); persistExecutor = null; } if (pushExecutor != null) { pushExecutor.shutdownNow(); Preconditions.checkState( pushExecutor.awaitTermination(365, TimeUnit.DAYS), "pushExecutor not terminated" ); pushExecutor = null; } if (intermediateTempExecutor != null) { intermediateTempExecutor.shutdownNow(); Preconditions.checkState( intermediateTempExecutor.awaitTermination(365, TimeUnit.DAYS), "intermediateTempExecutor not terminated" ); intermediateTempExecutor = null; } }</code><technical_language>methods close() closeNow() calling .. in closeNow() want finish asap wait want add a flag in shutdownExecutors() if want wait in close() flow. also, call xxx.shutdownNow() executors wait of stopping in parallel ? timeout is large.. if wrong some thread stuck potentially indefinitely . I wait for 5 minutes print error move on</technical_language>

Target:
private void shutdownExecutors() { if (persistExecutor != null) { persistExecutor.shutdownNow(); } if (pushExecutor != null) { pushExecutor.shutdownNow(); } if (intermediateTempExecutor != null) { intermediateTempExecutor.shutdownNow(); } }
Source:
<code>void testUpdateWhenResponseParametersAreNotEmpty() { when(resultEventData.getResponseParameters()).thenReturn("someValue"); underTest.update(mockAttemptAuditEventResultBuilder, resultEventData); verify(mockResultApiRequestDataBuilder, times(1)).setResponseParameters(anyString()); <START> } <END></code><technical_language>"someValue"</technical_language>

Target:
void testUpdateWhenResponseParametersAreNotEmpty() { String parametersValue = "someValue"; when(resultEventData.getResponseParameters()).thenReturn(parametersValue); underTest.update(mockAttemptAuditEventResultBuilder, resultEventData); verify(mockResultApiRequestDataBuilder, times(1)).setResponseParameters(anyString()); verify(mockResultApiRequestDataBuilder, times(1)).setResponseParameters(parametersValue); }
Source:
<code>public List<SchemaTableName> listTables(ConnectorSession session, String schemaNameOrNull) { Stream<SchemaTableName> stream = tables.listSystemTables(session).stream() .map(SystemTable::getTableMetadata) .map(ConnectorTableMetadata::getTable); if (schemaNameOrNull != null) { stream = stream <START> .filter(table -> table.getSchemaName().equals(schemaNameOrNull)); <END> } return stream.collect(toImmutableList()); }</code><technical_language>extract this a method: .stream() ... .filter(tableSchemaMatcher(schemaNameOrNull)) .collect</technical_language>

Target:
public List<SchemaTableName> listTables(ConnectorSession session, String schemaNameOrNull) { return tables.listSystemTables(session).stream() .map(SystemTable::getTableMetadata) .map(ConnectorTableMetadata::getTable) .filter(table -> schemaNameOrNull == null || table.getSchemaName().equals(schemaNameOrNull)) .collect(toImmutableList()); }
Source:
<code>protected void initAndTest() { for (MultimapCache<String, String> mc : multimapCacheCluster.values()) { <START> await(mc.size().thenAccept(s -> assertEquals(0, s.intValue()))); <END> } await(multimapCacheCluster.values().iterator().next().put("names", "oihana")); assertOnAllCachesAndOwnership("names", "oihana"); }</code><technical_language>IMHO assertEquals(0, mc.size().join()) is more readable</technical_language>

Target:
protected void initAndTest() { assertMultimapCacheSize(multimapCacheCluster, 0); putValuesOnMultimapCache(getMultimapCacheMember(), NAMES_KEY, OIHANA); assertValuesAndOwnership(NAMES_KEY, OIHANA); }
Source:
<code>static Iterator<SerializableFST> transform(Iterator<String> iterator) throws IOException { BytesRefSorter sorter = new InMemorySorter(Comparator.naturalOrder()); while (iterator.hasNext()) { sorter.add(new BytesRef(iterator.next())); } FST<Object> automaton = buildAutomaton(sorter); return automaton == null ? Iterators.emptyIterator() : <START> Collections.singletonList(new <END> SerializableFST(automaton)).iterator(); }</code><technical_language>static import</technical_language>

Target:
public static Iterator<SerializableFST> transform(Iterator<String> iterator) throws IOException { BytesRefSorter sorter = new InMemorySorter(Comparator.naturalOrder()); while (iterator.hasNext()) { sorter.add(new BytesRef(iterator.next())); } FST<Object> automaton = buildAutomaton(sorter); return automaton == null ? Iterators.emptyIterator() : Collections.singletonList(new SerializableFST(automaton)).iterator(); }
Source:
<code>protected void addInInterceptorCorrectingInterceptors(ServerFactoryBean sfb) { <START> if (isProxy() && isProxyEnvelope() && CxfUtils.interceptorOfClassIsPresent(sfb.getInInterceptors(), SAAJInInterceptor.class)) <END> { sfb.getInInterceptors().add(new SAAJEnvelopeCorrectionInterceptor()); } }</code><technical_language>static import</technical_language>

Target:
protected void addInInterceptorCorrectingInterceptors(ServerFactoryBean sfb) { if (isProxy() && isProxyEnvelope() && interceptorOfClassIsPresent(sfb.getInInterceptors(), SAAJInInterceptor.class)) { sfb.getInInterceptors().add(new SAAJEnvelopeCorrectionInterceptor()); } }
Source:
<code>public AdvancedInsightEndpoint(HttpWrapper httpWrapper, String baseUri) { super(httpWrapper); <START> uri = baseUri + "/ni/advanced/json"; <END> }</code><technical_language>extract "/ni/advanced/json" in a constant ADVANCED_ENDPOINT_PATH in setBaseUri? in other XxxEndpoint classes</technical_language>

Target:
public AdvancedInsightEndpoint(HttpWrapper httpWrapper, String baseUri) { super(httpWrapper); uri = baseUri + DEFAULT_PATH; }