auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testZooKeeperLeaderElectionRetrieval() throws Exception { final TestingLeaderElectionEventHandler electionEventHandler = new TestingLeaderElectionEventHandler(TEST_LEADER); final TestingLeaderRetrievalEventHandler retrievalEventHandler = new TestingLeaderRetrievalEventHandler(); LeaderElectionDriver leaderElectionDriver = null; LeaderRetrievalDriver leaderRetrievalDriver = null; try { <START> leaderElectionDriver = ZooKeeperUtils.createLeaderElectionDriverFactory(client, configuration) .createLeaderElectionDriver(electionEventHandler, electionEventHandler::handleError, TEST_URL); electionEventHandler.init(leaderElectionDriver); <END> leaderRetrievalDriver = ZooKeeperUtils.createLeaderRetrievalDriverFactory(client, configuration) .createLeaderRetrievalDriver(retrievalEventHandler, retrievalEventHandler::handleError); electionEventHandler.waitForLeader(timeout); assertThat(electionEventHandler.getConfirmedLeaderInformation(), is(TEST_LEADER)); retrievalEventHandler.waitForNewLeader(timeout); assertThat(retrievalEventHandler.getLeaderSessionID(), is(TEST_LEADER.getLeaderSessionID())); assertThat(retrievalEventHandler.getAddress(), is(TEST_LEADER.getLeaderAddress())); } finally { if (leaderElectionDriver != null) { leaderElectionDriver.close(); } if (leaderRetrievalDriver != null) { leaderRetrievalDriver.close(); } } }</code><technical_language>this factored out a method is reused</technical_language>

Target:
public void testZooKeeperLeaderElectionRetrieval() throws Exception { final TestingLeaderElectionEventHandler electionEventHandler = new TestingLeaderElectionEventHandler(TEST_LEADER); final TestingLeaderRetrievalEventHandler retrievalEventHandler = new TestingLeaderRetrievalEventHandler(); LeaderElectionDriver leaderElectionDriver = null; LeaderRetrievalDriver leaderRetrievalDriver = null; try { leaderElectionDriver = createAndInitLeaderElectionDriver(client, electionEventHandler); leaderRetrievalDriver = ZooKeeperUtils.createLeaderRetrievalDriverFactory(client, configuration) .createLeaderRetrievalDriver(retrievalEventHandler, retrievalEventHandler::handleError); electionEventHandler.waitForLeader(timeout); assertThat(electionEventHandler.getConfirmedLeaderInformation(), is(TEST_LEADER)); retrievalEventHandler.waitForNewLeader(timeout); assertThat(retrievalEventHandler.getLeaderSessionID(), is(TEST_LEADER.getLeaderSessionID())); assertThat(retrievalEventHandler.getAddress(), is(TEST_LEADER.getLeaderAddress())); } finally { if (leaderElectionDriver != null) { leaderElectionDriver.close(); } if (leaderRetrievalDriver != null) { leaderRetrievalDriver.close(); } } }
Source:
<code>protected static boolean processConfig() { CollectorConfiguration config = configService.getCollector(null, null, null, null); if (config != null) { try { updateInstrumentation(config); } catch (Exception e) { log.severe("Failed to update instrumentation rules: " + e); } <START> configExecutor.shutdownNow(); <END> } return config != null; }</code><technical_language>Is this call necessary? is called line 109</technical_language>

Target:
protected static boolean processConfig() { CollectorConfiguration config = configService.getCollector(null, null, null, null); if (config != null) { try { updateInstrumentation(config); } catch (Exception e) { log.severe("Failed to update instrumentation rules: " + e); } } return config != null; }
Source:
<code>public void should_format_passed_scenario() throws Throwable { CucumberFeature feature = TestHelper.feature("path/test.feature", "Feature: feature name\n" + " Scenario: scenario name\n" + " Given first step\n" + " When second step\n" + " Then third step\n"); features.add(feature); stepsToResult.put("first step", result("passed")); stepsToResult.put("second step", result("passed")); stepsToResult.put("third step", result("passed")); <START> stepDuration = Duration.ofNanos(1L); <END> String formatterOutput = runFeaturesWithFormatter(); String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<testsuite failures=\"0\" name=\"io.cucumber.core.plugin.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.003\">\n" + " <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.003\">\n" + " <system-out><![CDATA[" + "Given first step............................................................passed\n" + "When second step............................................................passed\n" + "Then third step.............................................................passed\n" + "]]></system-out>\n" + " </testcase>\n" + "</testsuite>\n"; assertXmlEqual(expected, formatterOutput); }</code><technical_language>change milis nanos here</technical_language>

Target:
public void should_format_passed_scenario() throws Throwable { CucumberFeature feature = TestHelper.feature("path/test.feature", "Feature: feature name\n" + " Scenario: scenario name\n" + " Given first step\n" + " When second step\n" + " Then third step\n"); features.add(feature); stepsToResult.put("first step", result("passed")); stepsToResult.put("second step", result("passed")); stepsToResult.put("third step", result("passed")); stepDuration = Duration.ofMillis(1L); String formatterOutput = runFeaturesWithFormatter(); String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<testsuite failures=\"0\" name=\"io.cucumber.core.plugin.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.003\">\n" + " <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.003\">\n" + " <system-out><![CDATA[" + "Given first step............................................................passed\n" + "When second step............................................................passed\n" + "Then third step.............................................................passed\n" + "]]></system-out>\n" + " </testcase>\n" + "</testsuite>\n"; assertXmlEqual(expected, formatterOutput); }
Source:
<code>public NoOpApexPluginDispatcher() { <START> super("NoOpPluginManager"); <END> }</code><technical_language>Inconsistent naming, class.getName()</technical_language>

Target:
public NoOpApexPluginDispatcher() { super(NoOpApexPluginDispatcher.class.getName()); }
Source:
<code>protected Endpoint createEndpoint(final String uri, final String remaining, final Map<String, Object> parameters) throws Exception { LOG.info("Creating CM Endpoint ... "); final String url = CMConstants.DEFAULT_SCHEME + remaining; if (!UrlValidator.getInstance().isValid(url)) { final String errorMessage = String.format("HOST provided: %s seem to be invalid. Remember SCHEME has to be excluded.", url); final Exception t = new InvalidURLException(errorMessage); <START> LOG.error(errorMessage, t); <END> throw t; } LOG.info("Uri=[{}], path=[{}], parameters=[{}]", new Object[] {URISupport.sanitizeUri(uri), URISupport.sanitizePath(remaining), parameters }); final CMConfiguration config = new CMConfiguration(); setProperties(config, parameters); LOG.info("Validating uri based configuration"); final Set<ConstraintViolation<CMConfiguration>> constraintViolations = validator.validate(config); if (constraintViolations.size() > 0) { final StringBuffer msg = new StringBuffer(); for (final ConstraintViolation<CMConfiguration> cv : constraintViolations) { msg.append(String.format("- Invalid value for %s: %s", cv.getPropertyPath().toString(), cv.getMessage())); } LOG.error(msg.toString()); throw new InvalidUriEndpointException(msg.toString()); } LOG.info("CMConfiguration - OK!"); LOG.info("Creating CMEndpoint"); final CMEndpoint endpoint = new CMEndpoint(uri, this); endpoint.setConfiguration(config); endpoint.setHost(remaining); return endpoint; }</code><technical_language>Do log throw error, throw error</technical_language>

Target:
protected Endpoint createEndpoint(final String uri, final String remaining, final Map<String, Object> parameters) throws Exception { LOG.debug("Creating CM Endpoint ... "); final String url = CMConstants.DEFAULT_SCHEME + remaining; if (!UrlValidator.getInstance().isValid(url)) { throw new ResolveEndpointFailedException(uri, String.format("HOST provided: %s seem to be invalid. Remember SCHEME has to be excluded.", url)); } LOG.debug("Uri=[{}], path=[{}], parameters=[{}]", new Object[] {URISupport.sanitizeUri(uri), URISupport.sanitizePath(remaining), parameters }); final CMConfiguration config = new CMConfiguration(); setProperties(config, parameters); LOG.debug("Validating uri based configuration"); final Set<ConstraintViolation<CMConfiguration>> constraintViolations = validator.validate(config); if (constraintViolations.size() > 0) { final StringBuffer msg = new StringBuffer(); for (final ConstraintViolation<CMConfiguration> cv : constraintViolations) { msg.append(String.format("- Invalid value for %s: %s", cv.getPropertyPath().toString(), cv.getMessage())); } throw new ResolveEndpointFailedException(uri, msg.toString()); } LOG.debug("CMConfiguration - OK!"); LOG.debug("Creating CMEndpoint"); final CMEndpoint endpoint = new CMEndpoint(uri, this); endpoint.setConfiguration(config); endpoint.setHost(remaining); return endpoint; }
Source:
<code>public ProjectSubmissionOutputFileParser(Reader source) { <START> if(source != null) { <END> bufferedReader = new BufferedReader(source); } }</code><technical_language>If source is null, throw a NullPointerException</technical_language>

Target:
public ProjectSubmissionOutputFileParser(Reader source) { if(source != null) { bufferedReader = new BufferedReader(source); } else throw new NullPointerException(); }
Source:
<code>public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { <START> return Mono.error(new AuthenticationRequiredException("Authenticating in this environment requires" + " specifying a TokenRequestContext.")); } <END> return authenticate(new TokenRequestContext().addScopes(defaultScope)); }</code><technical_language>log throw</technical_language>

Target:
public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(logger.logExceptionAsError(new CredentialUnavailableException("Authenticating in this " + "environment requires specifying a TokenRequestContext."))); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); }
Source:
<code>public void writeAllTo(OutputStream out) throws IOException { for (BytesInput input : inputs) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("write " + input.size() + " bytes to out"); } <START> if (LOGGER.isDebugEnabled() && input instanceof SequenceBytesIn) { <END> LOGGER.debug("{"); } input.writeAllTo(out); if (LOGGER.isDebugEnabled() && input instanceof SequenceBytesIn) { LOGGER.debug("}"); } } }</code><technical_language>this nested in if statement instead of calling isDebugEnabled twice</technical_language>

Target:
public void writeAllTo(OutputStream out) throws IOException { for (BytesInput input : inputs) { LOGGER.debug("write bytes to out", input.size()); if (input instanceof SequenceBytesIn) { LOGGER.debug("{"); } input.writeAllTo(out); if (input instanceof SequenceBytesIn) { LOGGER.debug("}"); } } }
Source:
<code>public Response get(@ApiParam(value = "Plan Id") @PathParam("id") Long id) { Plan plan = planService.get(id); if (plan == null) { return getPlanNotFound(id); <START> } else { <END> return Response.ok(plan).build(); } }</code><technical_language>similar for migration service ... throw exception service</technical_language>

Target:
public Response get(@ApiParam(value = "Plan Id") @PathParam("id") Long id) throws PlanNotFoundException { return Response.ok(planService.get(id)).build(); }
Source:
<code>public int hashCode() { <START> return (getElementName() + getJid().toString()).hashCode(); <END> }</code><technical_language>BTW, is hashCode() equals()</technical_language>

Target:
public final int hashCode() { return (getElementName() + getJid().toString()).hashCode(); }
Source:
<code>public static IOHub create(Executor executor) throws IOException { IOHub result = new IOHub(executor); executor.execute(result); <START> if (Launcher.isWindows()) { <END> LOGGER.log(Level.FINE, "IOHub runs on Windows. There are known issues with Selector#select() hanging, running an additional watcher thread. See JENKINS-47965 for more info"); executor.execute(new WindowsIOHubSelectorWatcher(result)); } return result; }</code><technical_language>BTW - I this is longer correct. network stack in experience behaves run Linux windows (ubuntu bash windows, for example) - checking for file separator character is longer correct. some want do windows paths, programes, some want do due differences in a protocol stack (like here)</technical_language>

Target:
public static IOHub create(Executor executor) throws IOException { IOHub result = new IOHub(executor); executor.execute(result); LOGGER.log(Level.FINE, "Staring an additional Selector wakeup thread. See JENKINS-47965 for more info"); executor.execute(new IOHubSelectorWatcher(result)); return result; }
Source:
<code>public Entry getEntryFromTuple(YailList tuple) { try { String xValue = tuple.getString(0); String yValue = tuple.getString(1); try { int x = (int)Math.floor(Float.parseFloat(xValue)); float y = Float.parseFloat(yValue); return new BarEntry(x, y); } catch (NumberFormatException e) { } <START> } catch (Exception e) { <END> } return null; }</code><technical_language>* Is a more specific exception catch here? * Please log error report user Form's ErrorOccurred method</technical_language>

Target:
public Entry getEntryFromTuple(YailList tuple) { try { String xValue = tuple.getString(0); String yValue = tuple.getString(1); try { int x = (int)Math.floor(Float.parseFloat(xValue)); float y = Float.parseFloat(yValue); return new BarEntry(x, y); } catch (NumberFormatException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_INVALID_CHART_ENTRY_VALUES, xValue, yValue); } } catch (NullPointerException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_NULL_CHART_ENTRY_VALUES); } catch (IndexOutOfBoundsException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_INSUFFICIENT_CHART_ENTRY_VALUES, getTupleSize(), tuple.size()); } return null; }
Source:
<code>public Map<String, ActionInfo> format(RevisionResource rsrc) throws OrmException { <START> ChangeData cd = changeDataFactory.create(db.get(), rsrc.getControl()); <END> return toRevisionActionInfoMap(cd, rsrc.getPatchSet().getId()); }</code><technical_language>need create a ChangeData here, in toRevisionActionInfoMap get a RevisionResource. Instead, pass in rsrc toRevisionActionInfoMap, other caller in toChangeActionInfoMap construct resource call site</technical_language>

Target:
public Map<String, ActionInfo> format(RevisionResource rsrc) { return toActionMap(rsrc); }
Source:
<code>@Test public void testRequestSuccess() throws Throwable { enqueueFromFile("announce_2016_11_21.json"); AnnouncementClient.Callback cb = mock(AnnouncementClient.Callback.class); request(cb); server().takeRequest(); <START> verify(cb).success(any(List.class)); <END> verify(cb, never()).error(any(Throwable.class)); }</code><technical_language>I anyListOf(Card.class)</technical_language>

Target:
@Test public void testRequestSuccess() throws Throwable { enqueueFromFile("announce_2016_11_21.json"); Callback cb = mock(Callback.class); request(cb); server().takeRequest(); verify(cb).success(anyListOf(Card.class)); verify(cb, never()).error(any(Throwable.class)); }
Source:
<code>public RoughToRealVerificationOperation(OrcsApi orcsApi, BranchId branchId, XResultData results, ArtifactReadable destinationArtifact, RoughArtifactCollector rawData, IArtifactImportResolver artifactResolver, boolean deleteUnmatchedArtifacts, IArtifactExtractor extractor) { this.results = results; this.orcsApi = orcsApi; this.branchId = branchId; this.rawData = rawData; this.artifactResolver = artifactResolver; this.destinationArtifact = destinationArtifact; this.roughToRealArtifacts = new HashMap<>(); <START> roughToRealArtifacts.put(rawData.getParentRoughArtifact(), this.destinationArtifact); <END> }</code><technical_language>remove "this"</technical_language>

Target:
public RoughToRealVerificationOperation(OrcsApi orcsApi, BranchId branchId, XResultData results, ArtifactReadable destinationArtifact, RoughArtifactCollector rawData, IArtifactImportResolver artifactResolver, boolean deleteUnmatchedArtifacts, IArtifactExtractor extractor) { this.results = results; this.orcsApi = orcsApi; this.branchId = branchId; this.rawData = rawData; this.artifactResolver = artifactResolver; this.destinationArtifact = destinationArtifact; this.roughToRealArtifacts = new HashMap<>(); roughToRealArtifacts.put(rawData.getParentRoughArtifact(), destinationArtifact); }
Source:
<code>private KualiDecimal getTotalRequestFileRequestAmount(ConcurRequestExtractFile requestExtractFile) { double detailLinesApprovedAmountSum = 0; if ( (requestExtractFile.getRequestDetails() == null) || (requestExtractFile.getRequestDetails().isEmpty()) ) { <START> return new KualiDecimal(detailLinesApprovedAmountSum); <END> } else { List<ConcurRequestExtractRequestDetailFileLine> requestDetailLines = requestExtractFile.getRequestDetails(); for (ConcurRequestExtractRequestDetailFileLine detailLine : requestDetailLines) { detailLinesApprovedAmountSum = detailLinesApprovedAmountSum + detailLine.getRequestAmount().doubleValue(); } return new KualiDecimal(detailLinesApprovedAmountSum); } }</code><technical_language>KualiDecimal.ZERO</technical_language>

Target:
private KualiDecimal getTotalRequestFileRequestAmount(ConcurRequestExtractFile requestExtractFile) { KualiDecimal detailLinesApprovedAmountSum = KualiDecimal.ZERO; if ( (requestExtractFile.getRequestDetails() == null) || (requestExtractFile.getRequestDetails().isEmpty()) ) { return detailLinesApprovedAmountSum; } else { List<ConcurRequestExtractRequestDetailFileLine> requestDetailLines = requestExtractFile.getRequestDetails(); for (ConcurRequestExtractRequestDetailFileLine detailLine : requestDetailLines) { detailLinesApprovedAmountSum = detailLinesApprovedAmountSum.add(detailLine.getRequestAmount()); } return detailLinesApprovedAmountSum; } }
Source:
<code>public void eventReceived(Object output) { if (output instanceof MIOutput) { MIOOBRecord[] records = ((MIOutput)output).getMIOOBRecords(); for (MIOOBRecord r : records) { if (r instanceof MINotifyAsyncOutput) { MINotifyAsyncOutput notifyOutput = (MINotifyAsyncOutput)r; String asyncClass = notifyOutput.getAsyncClass(); if ("record-started".equals(asyncClass) || "record-stopped".equals(asyncClass)) { if ("record-stopped".equals(asyncClass)) { fReverseTraceMethod = ReverseTraceMethod.STOP_TRACE; getSession().dispatchEvent(new GdbReverseModeChangedDMEvent(fCommandControl.getContext(), false), <START> getProperties()); <END> } else { getConnection().queueCommand( fCommandFactory.createCLIInfoRecord(getConnection().getContext()), new DataRequestMonitor<MIinfoRecord>(getExecutor(), null) { @Override public void handleSuccess() { MIinfoRecord output = getData(); fReverseTraceMethod = output.getReverseMethod(); getSession().dispatchEvent(new GdbReverseModeChangedDMEvent(fCommandControl.getContext(), true), getProperties()); } }); } } } } } }</code><technical_language>In this case in need call setReverseModeEnabled() setting consistant. call send event for you. Another option more future-proof call super.eventReceived(output) done special logic necessary in this class</technical_language>

Target:
public void eventReceived(Object output) { if (output instanceof MIOutput) { MIOOBRecord[] records = ((MIOutput)output).getMIOOBRecords(); for (MIOOBRecord r : records) { if (r instanceof MINotifyAsyncOutput) { MINotifyAsyncOutput notifyOutput = (MINotifyAsyncOutput)r; String asyncClass = notifyOutput.getAsyncClass(); if ("record-started".equals(asyncClass) || "record-stopped".equals(asyncClass)) { if ("record-stopped".equals(asyncClass)) { fReverseTraceMethod = ReverseTraceMethod.STOP_TRACE; setReverseModeEnabled(false); } else { getConnection().queueCommand( fCommandFactory.createCLIInfoRecord(getConnection().getContext()), new DataRequestMonitor<CLIInfoRecordInfo>(getExecutor(), null) { @Override public void handleSuccess() { CLIInfoRecordInfo output = getData(); fReverseTraceMethod = output.getReverseMethod(); setReverseModeEnabled(true); } }); } } } } } }
Source:
<code>public void onClose(final int code, final String reason, final boolean remote) { if (state != ConnectionState.DISCONNECTED) { activityTimer.cancelTimeouts(); factory.queueOnEventThread(new Runnable() { @Override public void run() { updateState(ConnectionState.DISCONNECTED); factory.shutdownThreads(); } }); } else { log.error("Received close from underlying socket when already disconnected. " + "Close code [" + code + "], Reason [" + reason + "], Remote [" + remote + "]"); <START> } <END> }</code><technical_language>I a short circuit exit top clearer wrapping entire effective body of method in if. Also, log error level in expected circumstances</technical_language>

Target:
public void onClose(final int code, final String reason, final boolean remote) { if (state == ConnectionState.DISCONNECTED) { log.error("Received close from underlying socket when already disconnected. " + "Close code [" + code + "], Reason [" + reason + "], Remote [" + remote + "]"); return; } activityTimer.cancelTimeouts(); factory.queueOnEventThread(new Runnable() { @Override public void run() { updateState(ConnectionState.DISCONNECTED); factory.shutdownThreads(); } }); }
Source:
<code>public GatewayResponse capture(CaptureGatewayRequest request) { String url = stripeGatewayConfig.getUrl() + "/v1/charges/" + request.getTransactionId() + "/capture"; GatewayAccountEntity gatewayAccount = request.getGatewayAccount(); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse.GatewayResponseBuilder.responseBuilder(); try { Response captureResponse = client.postRequest( URI.create(url), StringUtils.EMPTY, ImmutableMap.of(AUTHORIZATION, StripeAuthUtil.getAuthHeaderValue(stripeGatewayConfig)), APPLICATION_FORM_URLENCODED_TYPE, format("gateway-operations.%s.%s.capture", gatewayAccount.getGatewayName(), gatewayAccount.getType())); return responseBuilder.withResponse(StripeCaptureResponse.of(captureResponse)).build(); } catch (GatewayClientException e) { GatewayError gatewayError = GatewayError.unexpectedStatusCodeFromGateway(e .getResponse() .readEntity(StripeErrorResponse.class) .getError() .getMessage()); return responseBuilder.withGatewayError(gatewayError).build(); } catch (GatewayClientRuntimeException e) { <START> return responseBuilder.withGatewayError(processGatewayException(e)).build(); <END> } }</code><technical_language>thoughts overloading responseBuilder's withGatewayError method exception? for example responseBuilder.withGatewayError(e)</technical_language>

Target:
public GatewayResponse capture(CaptureGatewayRequest request) { String url = stripeGatewayConfig.getUrl() + "/v1/charges/" + request.getTransactionId() + "/capture"; GatewayAccountEntity gatewayAccount = request.getGatewayAccount(); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse.GatewayResponseBuilder.responseBuilder(); try { Response captureResponse = client.postRequest( URI.create(url), StringUtils.EMPTY, ImmutableMap.of(AUTHORIZATION, StripeAuthUtil.getAuthHeaderValue(stripeGatewayConfig)), APPLICATION_FORM_URLENCODED_TYPE, format("gateway-operations.%s.%s.capture", gatewayAccount.getGatewayName(), gatewayAccount.getType())); return responseBuilder.withResponse(StripeCaptureResponse.of(captureResponse)).build(); } catch (GatewayClientException e) { GatewayError gatewayError = GatewayError.unexpectedStatusCodeFromGateway(e .getResponse() .readEntity(StripeErrorResponse.class) .getError() .getMessage()); return responseBuilder.withGatewayError(gatewayError).build(); } catch (GatewayClientRuntimeException e) { return responseBuilder.withGatewayError(GatewayError.of(e)).build(); } }
Source:
<code>private AuthConfig authConfigUsingCredentialsStoreOrHelper(String hostName, JsonNode config) throws Exception { <START> final String credsStoreName = config.at("/credsStore").asText(); <END> final String credHelper = config.at("/credHelpers/" + hostName).asText(); if (StringUtils.isNotBlank(credHelper)) { return runCredentialProvider(hostName, credHelper); } else if (StringUtils.isNotBlank(credsStoreName)) { return runCredentialProvider(hostName, credsStoreName); } else { throw new UnsupportedOperationException(); } }</code><technical_language>FYI asText() returns "null" instead of null null :) Also, config.path("/credsStore") faster (doesn't parse json path, null safety returning a missing node), critical :)</technical_language>

Target:
private AuthConfig authConfigUsingCredentialsStoreOrHelper(String hostName, JsonNode config) throws Exception { final JsonNode credsStoreName = config.at("/credsStore"); final JsonNode credHelper = config.at("/credHelpers/" + hostName); if (!credHelper.isMissingNode()) { return runCredentialProvider(hostName, credHelper.asText()); } else if (!credsStoreName.isMissingNode()) { return runCredentialProvider(hostName, credsStoreName.asText()); } else { throw new IllegalStateException("Unsupported Docker config auths settings!"); } }
Source:
<code>public void shouldRegisterDefaultHealthCheck() { Set<String> registered = healthCheckRegistryService.getNames(); assertNotNull(registered); System.out.println(registered); <START> assertTrue(registered.size() == 1); <END> assertTrue(registered.contains("threadDeadlockHealthCheck")); }</code><technical_language>assertEquals</technical_language>

Target:
public void shouldRegisterDefaultHealthCheck() { Set<String> registered = healthCheckRegistryService.getNames(); assertNotNull(registered); assertEquals(1, registered.size()); assertTrue(registered.contains("threadDeadlockHealthCheck")); }
Source:
<code>private void submit(long workerId, JobCommand.Builder command) { if (!mWorkerIdToPendingCommands.containsKey(workerId)) { <START> mWorkerIdToPendingCommands.put(workerId, Lists.newArrayList()); <END> } mWorkerIdToPendingCommands.get(workerId).add(command.build()); }</code><technical_language>Is this protected a lock</technical_language>

Target:
private synchronized void submit(long workerId, JobCommand.Builder command) { if (!mWorkerIdToPendingCommands.containsKey(workerId)) { mWorkerIdToPendingCommands.put(workerId, Lists.newArrayList()); } mWorkerIdToPendingCommands.get(workerId).add(command.build()); }
Source:
<code>private static String writeToJSON() { final JSONObject mainObject = new JSONObject(); final JSONObject soundtracksettings = new JSONObject(); soundtracksettings.put("soundtrackEnabled", State.isSoundtrackEnabled()); mainObject.put("soundtracksettings", soundtracksettings); final JSONObject soundeffectsettings = new JSONObject(); soundeffectsettings.put("soundEffectsEnabled", State.isSoundEffectsEnabled()); <START> mainObject.put("soundEffectssettings", soundeffectsettings); <END> mainObject.put("playername", State.getPlayerName()); mainObject.put("coins", State.getCoins()); final JSONObject highscore = new JSONObject(); highscore.put("score", State.getHighscore()); mainObject.put("highscore", highscore); return mainObject.toJSONString(); }</code><technical_language>I prefer if save settings (soundeffect soundtrack) in settings object, main object <review</technical_language>

Target:
private static String writeToJSON() { final JSONObject mainObject = new JSONObject(); final JSONObject settings = new JSONObject(); final JSONObject soundtracksettings = new JSONObject(); soundtracksettings.put("soundtrackEnabled", State.isSoundtrackEnabled()); settings.put("soundtracksettings", soundtracksettings); final JSONObject soundeffectsettings = new JSONObject(); soundeffectsettings.put("soundEffectsEnabled", State.isSoundEffectsEnabled()); settings.put("soundEffectssettings", soundeffectsettings); mainObject.put("playername", State.getPlayerName()); mainObject.put("coins", State.getCoins()); final JSONObject highscore = new JSONObject(); highscore.put("score", State.getHighscore()); mainObject.put("highscore", highscore); mainObject.put("settings", settings); return mainObject.toJSONString(); }
Source:
<code>void setupInputFields() { startValue.onkeyup = this::onKeyDown; <START> endValue.onkeyup = this::onKeyDown; <END> }</code><technical_language>I rename onKeyDown method onKeyUp, change assignment startValue.onkeydown endValue.onkeydown</technical_language>

Target:
void setupInputFields() { startValue.onkeyup = this::onKeyUp; endValue.onkeyup = this::onKeyUp; }
Source:
<code><START> public List<LinkedStructure> getUplinks() { <END> return uplinks; }</code><technical_language>multiple uplinks</technical_language>

Target:
public Uplinks getUplinks() { return uplinks; }
Source:
<code>public IndexingConfigurationBuilder autoConfig(boolean autoConfig) { <START> enable(); <END> attributes.attribute(AUTO_CONFIG).set(autoConfig); return this; }</code><technical_language>Enabling indexing if autoConfig == false? this auto-enabling happen if autoConfig==true</technical_language>

Target:
public IndexingConfigurationBuilder autoConfig(boolean autoConfig) { if (autoConfig) enable(); attributes.attribute(AUTO_CONFIG).set(autoConfig); return this; }
Source:
<code>private void writeObject(ObjectOutputStream oos) throws IOException { if (buf == null) { <START> buf = new byte[codec.sizeof(object)]; <END> codec.encode(object, buf); } oos.writeInt(hash); if (object == null) { oos.writeInt(buf.length); oos.write(buf); } else { oos.writeInt(codec.sizeof(object)); CodedOutputStream cos = CodedOutputStream.newInstance(oos); codec.encode(object, cos); cos.flush(); } }</code><technical_language>Please store buffer in object, doubles memory footprint</technical_language>

Target:
private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeInt(hash); Object d = data; if (d instanceof byte[]) { byte[] buf = (byte[]) d; oos.writeInt(buf.length); oos.write(buf); } else { T obj = (T) d; oos.writeInt(codec.sizeof(obj)); CodedOutputStream cos = CodedOutputStream.newInstance(oos); codec.encode(obj, cos); cos.flush(); } }
Source:
<code>public static DownloadMigratorBuilder newInstance(Context context) { Context applicationContext = context.getApplicationContext(); String channelId = context.getResources().getString(R.string.migration_notification_channel_name); String channelDescription = context.getResources().getString(R.string.migration_notification_channel_description); <START> NotificationCustomizer<MigrationStatus> customiser = new NotificationCustomizer<MigrationStatus>() { <END> private static final int MAX_PROGRESS = 100; @Override public Notification customNotificationFrom(NotificationCompat.Builder builder, MigrationStatus payload) { String title = payload.status().toRawValue(); String content = payload.percentageMigrated() + "% migrated"; return builder .setProgress(MAX_PROGRESS, payload.percentageMigrated(), false) .setSmallIcon(android.R.drawable.ic_menu_gallery) .setContentTitle(title) .setContentText(content) .build(); } }; NotificationConfig<MigrationStatus> defaultNotificationConfig = new NotificationConfig<>( applicationContext, channelId, channelDescription, customiser, NotificationManagerCompat.IMPORTANCE_LOW ); Handler handler = new Handler(Looper.getMainLooper()); return new DownloadMigratorBuilder(applicationContext, handler, defaultNotificationConfig); }</code><technical_language>I I prefer anonymous classes. I risk of making constructors super hard follow. If pull out anonymous classes contained. do think? do this too</technical_language>

Target:
public static DownloadMigratorBuilder newInstance(Context context) { Context applicationContext = context.getApplicationContext(); String channelId = context.getResources().getString(R.string.migration_notification_channel_name); String channelDescription = context.getResources().getString(R.string.migration_notification_channel_description); NotificationCustomizer<MigrationStatus> customizer = new MigrationNotificationCustomizer(); NotificationConfig<MigrationStatus> defaultNotificationConfig = new NotificationConfig<>( applicationContext, channelId, channelDescription, customizer, NotificationManagerCompat.IMPORTANCE_LOW ); Handler handler = new Handler(Looper.getMainLooper()); return new DownloadMigratorBuilder(applicationContext, handler, defaultNotificationConfig); }
Source:
<code>public String getActionUrl(final ContentType contentType, final User user) { final HttpServletRequest request = httpServletRequestThreadLocal.getRequest(); <START> String actionUrl = request != null? getActionUrl(request, contentType, user):null; <END> return actionUrl; }</code><technical_language>change this return request != null? getActionUrl(request, contentType, user):null;</technical_language>

Target:
public String getActionUrl(final ContentType contentType, final User user) { final HttpServletRequest request = httpServletRequestThreadLocal.getRequest(); return request != null ? getActionUrl(request, contentType, user):null; }
Source:
<code>public static List<Car> createCars() { return Arrays.asList(new Car("Jeep", "Wrangler", 2011, "Jeep"), new Car("Jeep", "Comanche", 1990, "Jeep"), <START> new Car("Dodge", "Avenger", 2010, "Sedan"), <END> new Car("Buick", "Cascada", 2016, "Convertible"), new Car("Ford", "Focus", 2012, "Sedan"), new Car("Chevrolet", "Geo Metro", 1992, "Convertible")); }</code><technical_language>@nikhilbarar implementation good. input, Enum for car category constants</technical_language>

Target:
public static List<Car> createCars() { return Arrays.asList(new Car("Jeep", "Wrangler", 2011, Category.JEEP), new Car("Jeep", "Comanche", 1990, Category.JEEP), new Car("Dodge", "Avenger", 2010, Category.SEDAN), new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), new Car("Ford", "Focus", 2012, Category.SEDAN), new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)); }
Source:
<code>public static FileObject getFileObject( String vfsFilename, VariableSpace space, FileSystemOptions fsOptions ) throws KettleFileException { if ( vfsFilename == null ) { throw new KettleFileException( "Unexpected null VFS filename", <START> new NullPointerException( "KettleVFS.getFileObject() vfsFilename is NULL" ) ); <END> } try { FileSystemManager fsManager = getInstance().getFileSystemManager(); int timeOut = TIMEOUT_LIMIT; String[] schemes = fsManager.getSchemes(); String scheme = getScheme( schemes, vfsFilename ); if ( hasSchemePattern( vfsFilename, PROVIDER_PATTERN_SCHEME ) ) { while ( scheme == null && timeOut > 0 ) { schemes = fsManager.getSchemes(); try { Thread.sleep( TIME_TO_SLEEP_STEP ); timeOut -= TIME_TO_SLEEP_STEP; scheme = getScheme( schemes, vfsFilename ); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); break; } } } fsOptions = getFileSystemOptions( scheme, vfsFilename, space, fsOptions ); String filename = normalizePath( vfsFilename, scheme ); return fsOptions != null ? fsManager.resolveFile( filename, fsOptions ) : fsManager.resolveFile( filename ); } catch ( IOException e ) { throw new KettleFileException( "Unable to get VFS File object for filename '" + cleanseFilename( vfsFilename ) + "' : " + e.getMessage(), e ); } }</code><technical_language>I IllegalArgumentException is more apropriate. Also, need encapsulate exception in a KettleFileException</technical_language>

Target:
public static FileObject getFileObject( String vfsFilename, VariableSpace space, FileSystemOptions fsOptions ) throws KettleFileException { if ( vfsFilename == null ) { throw new IllegalArgumentException( "Unexpected null VFS filename." ); } try { FileSystemManager fsManager = getInstance().getFileSystemManager(); String[] schemes = fsManager.getSchemes(); String scheme = getScheme( schemes, vfsFilename ); int timeOut = TIMEOUT_LIMIT; if ( hasSchemePattern( vfsFilename, PROVIDER_PATTERN_SCHEME ) ) { while ( scheme == null && timeOut > 0 ) { schemes = fsManager.getSchemes(); try { Thread.sleep( TIME_TO_SLEEP_STEP ); timeOut -= TIME_TO_SLEEP_STEP; scheme = getScheme( schemes, vfsFilename ); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); break; } } } fsOptions = getFileSystemOptions( scheme, vfsFilename, space, fsOptions ); String filename = normalizePath( vfsFilename, scheme ); return fsOptions != null ? fsManager.resolveFile( filename, fsOptions ) : fsManager.resolveFile( filename ); } catch ( IOException e ) { throw new KettleFileException( "Unable to get VFS File object for filename '" + cleanseFilename( vfsFilename ) + "' : " + e.getMessage(), e ); } }
Source:
<code>public void evaluate_shouldReturnAllPatientsThatHaveTakenAllListedDrugs() throws Exception { List drugSetList = new ArrayList<Concept>(); drugSetList.add(new Concept(88)); drugSetList.add(new Concept(792)); cohortDefinition.setDrugSets(drugSetList); cohortDefinition.setWhich("ALL"); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); <START> System.out.println("Taking Drugs ALL" + cohort.getMemberIds() + " " + cohortDefinition); <END> Assert.assertTrue(cohort.contains(2)); Assert.assertEquals(1, cohort.size()); }</code><technical_language>a this? <LINK_0></technical_language>

Target:
public void evaluate_shouldReturnAllPatientsThatHaveTakenAllListedDrugs() throws Exception { List drugSetList = new ArrayList<Concept>(); drugSetList.add(new Concept(88)); drugSetList.add(new Concept(792)); cohortDefinition.setDrugSets(drugSetList); cohortDefinition.setWhich("ALL"); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); Assert.assertTrue(cohort.contains(2)); Assert.assertEquals(1, cohort.size()); }
Source:
<code><DATA_TYPE> void processBackgroundOperation(OperationAndData<DATA_TYPE> operationAndData, CuratorEvent event) { boolean isInitialExecution = (event == null); if ( isInitialExecution ) { performBackgroundOperation(operationAndData); return; } boolean doQueueOperation = false; do { <START> final KeeperException ke = KeeperException.create(event.getResultCode()); <END> if ( getZookeeperClient().getRetryPolicy().allowRetry(ke) ) { doQueueOperation = checkBackgroundRetry(operationAndData, event); break; } if ( operationAndData.getCallback() != null ) { sendToBackgroundCallback(operationAndData, event); break; } processEvent(event); } while ( false ); if ( doQueueOperation ) { queueOperation(operationAndData); } }</code><technical_language>for creating ke is unneeded. Create exception argument</technical_language>

Target:
<DATA_TYPE> void processBackgroundOperation(OperationAndData<DATA_TYPE> operationAndData, CuratorEvent event) { boolean isInitialExecution = (event == null); if ( isInitialExecution ) { performBackgroundOperation(operationAndData); return; } boolean doQueueOperation = false; do { if ( getZookeeperClient().getRetryPolicy().allowRetry(KeeperException.create(event.getResultCode())) ) { doQueueOperation = checkBackgroundRetry(operationAndData, event); break; } if ( operationAndData.getCallback() != null ) { sendToBackgroundCallback(operationAndData, event); break; } processEvent(event); } while ( false ); if ( doQueueOperation ) { queueOperation(operationAndData); } }
Source:
<code>private static Integer getPreparedStatementNumberOfParameters(@Nullable ExpressionTree tree) { if (tree != null && tree.is(Tree.Kind.METHOD_INVOCATION)) { Arguments arguments = ((MethodInvocationTree) tree).arguments(); if (!arguments.isEmpty()) { <START> ExpressionTree methodSelect = ((MethodInvocationTree) tree).methodSelect(); <END> String methodName = null; if (methodSelect.is(Tree.Kind.MEMBER_SELECT)) { methodName = ((MemberSelectExpressionTree) methodSelect).identifier().name(); } if (methodSelect.is(Tree.Kind.IDENTIFIER)) { methodName = ((IdentifierTree) methodSelect).name(); } if ("prepareStatement".equals(methodName)) { return getNumberQuery(arguments.get(0)); } } } return null; }</code><technical_language>MethodMatcher for this</technical_language>

Target:
private static Integer getPreparedStatementNumberOfParameters(@Nullable ExpressionTree tree) { if (tree != null && tree.is(Tree.Kind.METHOD_INVOCATION)) { Arguments arguments = ((MethodInvocationTree) tree).arguments(); if (!arguments.isEmpty() && PREPARE_STATEMENT.matches((MethodInvocationTree) tree)) { return getNumberQuery(arguments.get(0)); } } return null; }
Source:
<code>public LinkedHashMap<String, String> getAPIPacketParameters() { LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>(); <START> parameters.put("Phone number", new String(phoneNumber).replaceAll("\0", "")); <END> if (data != null) parameters.put("Data", data); return parameters; }</code><technical_language>add Transmit options field here</technical_language>

Target:
public LinkedHashMap<String, String> getAPIPacketParameters() { LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("Transmit options", HexUtils.byteToHexString((byte)transmitOptions)); parameters.put("Phone number", new String(phoneNumber).replaceAll("\0", "")); if (data != null) parameters.put("Data", data); return parameters; }
Source:
<code>private String evaluateExpression(String expr, int iterationIndex, Object[] dataValues) { String[] exprParts = expr.split("\\."); String firstPart = exprParts[0]; Object result; switch (firstPart) { case "featureName": result = feature.getName(); break; case "iterationCount": <START> System.err.println("WARNING: #iterationCount in unroll pattern is deprecated, use #iterationIndex instead"); <END> case "iterationIndex": result = String.valueOf(iterationIndex); break; default: int index = feature.getDataVariables().indexOf(firstPart); if (index < 0) { if (assertUnrollExpressions) { throw new SpockAssertionError("Error in @Unroll, could not find matching variable for expression: " + expr); } return "#Error:" + expr; } result = dataValues[index]; break; } try { for (int i = 1; i < exprParts.length; i++) { String currPart = exprParts[i]; if (currPart.endsWith("()")) { result = GroovyRuntimeUtil.invokeMethod(result, currPart.substring(0, currPart.length() - 2)); } else { result = GroovyRuntimeUtil.getProperty(result, currPart); } } return GroovyRuntimeUtil.toString(result); } catch (Exception e) { if (assertUnrollExpressions) { throw new SpockAssertionError("Error in @Unroll expression: " + expr, e); } return "#Error:" + expr; } }</code><technical_language>Thinking it, migration a simple s/#iterationCount/iterationIndex, need it. Spock logging stuff</technical_language>

Target:
private String evaluateExpression(String expr, int iterationIndex, Object[] dataValues) { String[] exprParts = expr.split("\\."); String firstPart = exprParts[0]; Object result; switch (firstPart) { case "featureName": result = feature.getName(); break; case "iterationIndex": result = String.valueOf(iterationIndex); break; default: int index = feature.getDataVariables().indexOf(firstPart); if (index < 0) { if (assertUnrollExpressions) { throw new SpockAssertionError("Error in @Unroll, could not find matching variable for expression: " + expr); } return "#Error:" + expr; } result = dataValues[index]; break; } try { for (int i = 1; i < exprParts.length; i++) { String currPart = exprParts[i]; if (currPart.endsWith("()")) { result = GroovyRuntimeUtil.invokeMethod(result, currPart.substring(0, currPart.length() - 2)); } else { result = GroovyRuntimeUtil.getProperty(result, currPart); } } return toStringOrDump(result); } catch (Exception e) { if (assertUnrollExpressions) { throw new SpockAssertionError("Error in @Unroll expression: " + expr, e); } return "#Error:" + expr; } }
Source:
<code>public void malformedInputRegexpTest() throws MSDKException { File file = new File("target/test-classes/malformed_query.mgf"); MgfFileImportMethod importMethod = new MgfFileImportMethod(file); <START> thrown.expect(MSDKException.class); <END> thrown.expectMessage("Incorrect data format"); List<MgfMsSpectrum> spectrums = importMethod.execute(); }</code><technical_language>is a simpler syntax define expected exception: <LINK_0></technical_language>

Target:
public void malformedInputRegexpTest() throws MSDKException { final String file = "malformed_query.mgf"; File inputFile = getResourcePath(file).toFile(); MgfFileImportMethod importMethod = new MgfFileImportMethod(inputFile); importMethod.execute(); }
Source:
<code><START> public boolean equals(Object o) { <END> if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ServiceFiltersBuilder filters1 = (ServiceFiltersBuilder) o; return filters.equals(filters1.filters); }</code><technical_language>EqualsBuilder</technical_language>

Target:
public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); }
Source:
<code>public void detectControlledResources() { final Collection<Resource> semantics = session.getSemanticResources(); final Collection<Resource> resourcesToCheck = new ArrayList<Resource>(session.getTransactionalEditingDomain().getResourceSet().getResources()); List<Resource> controlledResources = session.getControlledResources(); List<Resource> controlledResourcesBefore = new ArrayList<Resource>(session.getControlledResources()); for (final Resource resource : Iterables.filter(resourcesToCheck, Predicates.not(Predicates.in(controlledResources)))) { if (hasControlledRootInSemantics(resource, semantics)) { controlledResources.add(resource); } } ListIterator<Resource> listIterator = controlledResources.listIterator(); while (listIterator.hasNext()) { Resource resource = listIterator.next(); if (!resourcesToCheck.contains(resource)) listIterator.remove(); } if (!controlledResourcesBefore.equals(controlledResources)) { session.transfertNotification(SessionListener.SEMANTIC_CHANGE); <START> session.resetSemanticResource(); <END> } }</code><technical_language>I understand reset semantic resource a change of controlled resources..</technical_language>

Target:
public void detectControlledResources() { final Collection<Resource> semantics = session.getSemanticResources(); final Collection<Resource> resourcesToCheck = new ArrayList<Resource>(session.getTransactionalEditingDomain().getResourceSet().getResources()); List<Resource> controlledResources = session.getControlledResources(); List<Resource> controlledResourcesBefore = new ArrayList<Resource>(session.getControlledResources()); for (final Resource resource : Iterables.filter(resourcesToCheck, Predicates.not(Predicates.in(controlledResources)))) { if (hasControlledRootInSemantics(resource, semantics)) { controlledResources.add(resource); } } ListIterator<Resource> listIterator = controlledResources.listIterator(); while (listIterator.hasNext()) { Resource resource = listIterator.next(); if (!resourcesToCheck.contains(resource)) listIterator.remove(); } if (!controlledResourcesBefore.equals(controlledResources)) { session.transfertNotification(SessionListener.SEMANTIC_CHANGE); session.setSemanticResourcesNotUptodate(); } }
Source:
<code>public boolean isMainThread() { <START> return looper == Looper.getMainLooper(); <END> }</code><technical_language>looper != null && looper == Looper.getMainLooper() (if getMainLooper() is expensive)</technical_language>

Target:
public boolean isMainThread() { return looper != null && looper == Looper.getMainLooper(); }
Source:
<code>public void run() { ISelection selection = planViewer.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; Iterator selectionIterator = structuredSelection.iterator(); <START> while (selectionIterator.hasNext()) { <END> Object nextSelection = selectionIterator.next(); if (!(nextSelection instanceof PlanElement)) { continue; } PlanElement planElement = (PlanElement) nextSelection; planElement.setPlanElementAction(action); } actionToolbarProvider.mapActionItemsToSelection(selection); } }</code><technical_language>for(Object nextSelection : structuredSelection.toList())</technical_language>

Target:
public void run() { ISelection selection = planViewer.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; for (Object selectedRow : structuredSelection.toList()) { if (selectedRow instanceof PlanElement) { PlanElement planElement = (PlanElement) selectedRow; planElement.setPlanElementAction(action); } } actionToolbarProvider.mapActionItemsToSelection(selection); } }