auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void deleteDnsRecordByFqdn(String environmentCrn, String accountId, List<String> fqdns) throws FreeIpaClientException { Stack stack = stackService.getByEnvironmentCrnAndAccountId(environmentCrn, accountId); MDCBuilder.buildMdcContext(stack); FreeIpa freeIpa = freeIpaService.findByStack(stack); <START> FreeIpaClient freeIpaClient = freeIpaClientFactory.getFreeIpaClientByAccountAndEnvironment(environmentCrn, accountId); <END> for (DnsZone dnsZone : freeIpaClient.findAllDnsZone()) { LOGGER.debug("Looking for records in zone [{}]", dnsZone.getIdnsname()); Set<DnsRecord> allDnsRecordsInZone = freeIpaClient.findAllDnsRecordInZone(dnsZone.getIdnsname()); deleteRegularRecords(freeIpaClient, dnsZone, allDnsRecordsInZone, fqdns, freeIpa.getDomain()); deleteSrvRecords(freeIpaClient, dnsZone, allDnsRecordsInZone, fqdns); } }</code><technical_language>Stack avoid a redundant read calling getFreeIpaClientForStack instead of getFreeIpaClientByAccountAndEnvironment</technical_language>

Target:
public void deleteDnsRecordByFqdn(String environmentCrn, String accountId, List<String> fqdns) throws FreeIpaClientException { Stack stack = stackService.getByEnvironmentCrnAndAccountId(environmentCrn, accountId); MDCBuilder.buildMdcContext(stack); FreeIpa freeIpa = freeIpaService.findByStack(stack); FreeIpaClient freeIpaClient = freeIpaClientFactory.getFreeIpaClientForStack(stack); for (DnsZone dnsZone : freeIpaClient.findAllDnsZone()) { LOGGER.debug("Looking for records in zone [{}]", dnsZone.getIdnsname()); Set<DnsRecord> allDnsRecordsInZone = freeIpaClient.findAllDnsRecordInZone(dnsZone.getIdnsname()); deleteRegularRecords(freeIpaClient, dnsZone, allDnsRecordsInZone, fqdns, freeIpa.getDomain()); deleteSrvRecords(freeIpaClient, dnsZone, allDnsRecordsInZone, fqdns); } }
Source:
<code>public boolean equals(final Object obj) { <START> return obj instanceof MultipartKey && Arrays.equals(keys, ((MultipartKey)obj).keys); <END> }</code><technical_language>Please do include unrelated changes in a single pull request. Thanks</technical_language>

Target:
public boolean equals(final Object obj) { return Arrays.equals(keys, ((MultipartKey)obj).keys); }
Source:
<code>private void testDeleteCount(boolean autoCommit, Integer limit) throws Exception { String tableName = generateUniqueName(); String ddl = "CREATE TABLE IF NOT EXISTS " + tableName + " (pk1 DECIMAL NOT NULL, v1 VARCHAR CONSTRAINT PK PRIMARY KEY (pk1))"; int numRecords = 1010; Properties props = new Properties(); props.setProperty(QueryServices.ENABLE_SERVER_SIDE_MUTATIONS, allowServerSideMutations); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { conn.createStatement().execute(ddl); <START> PreparedStatement preStmt = conn.prepareStatement("UPSERT INTO " + tableName + " (pk1, v1) VALUES (" + ? + ",'value')"); <END> for (int i = 0; i < numRecords ; i++) { preStmt.setBigDecimal(1, new BigDecimal(i)); preStmt.executeUpdate(); } conn.commit(); conn.setAutoCommit(autoCommit); String delete = "DELETE FROM " + tableName + " WHERE (pk1) <= (" + numRecords + ")" + (limit == null ? "" : (" limit " + limit)); try (PreparedStatement pstmt = conn.prepareStatement(delete)) { int numberOfDeletes = pstmt.executeUpdate(); assertEquals(limit == null ? numRecords : limit, numberOfDeletes); if (!autoCommit) { conn.commit(); } } } }</code><technical_language>nit: I extract SQL string for readability</technical_language>

Target:
private void testDeleteCount(boolean autoCommit, Integer limit) throws Exception { String tableName = generateUniqueName(); String ddl = "CREATE TABLE IF NOT EXISTS " + tableName + " (pk1 DECIMAL NOT NULL, v1 VARCHAR CONSTRAINT PK PRIMARY KEY (pk1))"; int numRecords = 1010; Properties props = new Properties(); props.setProperty(QueryServices.ENABLE_SERVER_SIDE_MUTATIONS, allowServerSideMutations); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { conn.createStatement().execute(ddl); String command = "UPSERT INTO " + tableName + " (pk1, v1) VALUES (" + ? + ",'value')" PreparedStatement preStmt = conn.prepareStatement(command); for (int i = 0; i < numRecords ; i++) { preStmt.setBigDecimal(1, new BigDecimal(i)); preStmt.executeUpdate(); } conn.commit(); conn.setAutoCommit(autoCommit); String delete = "DELETE FROM " + tableName + " WHERE (pk1) <= (" + numRecords + ")" + (limit == null ? "" : (" limit " + limit)); try (PreparedStatement pstmt = conn.prepareStatement(delete)) { int numberOfDeletes = pstmt.executeUpdate(); assertEquals(limit == null ? numRecords : limit, numberOfDeletes); if (!autoCommit) { conn.commit(); } } } }
Source:
<code>public BeaconState applyBlock(Beacon block, BeaconState to) { CrystallizedState crystallized = to.getCrystallizedState(); ActiveState activeState = to.getActiveState(); List<AttestationRecord> mergedAttestations = new ArrayList<>(); mergedAttestations.addAll(activeState.getPendingAttestations()); mergedAttestations.addAll(block.getAttestations()); <START> block.getAttestations().forEach(at -> beaconAttester.purgeAttestations(at)); <END> activeState = activeState .withPendingAttestations(mergedAttestations); if (block.getSlotNumber() - crystallized.getLastStateRecalc() >= CYCLE_LENGTH) { logger.info("Calculate new crystallized state, slot: {}, prev slot: {}", block.getSlotNumber(), crystallized.getLastStateRecalc()); Finality finality = finalityTransition.applyBlock(block, crystallized.getFinality()); Dynasty dynasty = dynastyTransition.applyBlock(block, crystallized.getDynasty()); crystallized = crystallized .withDynasty(dynasty) .withLastStateRecalc(cycleStartSlot(block)) .withFinality(finality); List<AttestationRecord> uptodateAttestations = new ArrayList<>(); for (AttestationRecord record : activeState.getPendingAttestations()) { if (record.getSlot() >= crystallized.getLastStateRecalc()) { uptodateAttestations.add(record); } } beaconAttester.removeOldSlots(crystallized.getLastStateRecalc()); activeState = activeState. withPendingAttestations(uptodateAttestations); } return new BeaconState(crystallized, activeState); }</code><technical_language>do if drive this part a pub/sub mechanism? avoid tight components coupling</technical_language>

Target:
public BeaconState applyBlock(Beacon block, BeaconState to) { CrystallizedState crystallized = to.getCrystallizedState(); ActiveState activeState = to.getActiveState(); block.getAttestations().forEach(at -> publisher.publish(onBeaconAttestationIncluded(at))); activeState = activeState.addPendingAttestations(block.getAttestations()); if (block.getSlotNumber() - crystallized.getLastStateRecalc() >= CYCLE_LENGTH) { logger.info("Calculate new crystallized state, slot: {}, prev slot: {}", block.getSlotNumber(), crystallized.getLastStateRecalc()); Finality finality = finalityTransition.applyBlock(block, crystallized.getFinality()); Dynasty dynasty = dynastyTransition.applyBlock(block, crystallized.getDynasty()); crystallized = crystallized .withDynasty(dynasty) .withLastStateRecalc(cycleStartSlot(block)) .withFinality(finality); if (publisher != null) { publisher.publish(onStateRecalc(crystallized.getLastStateRecalc())); } activeState = activeState.removeAttestationsPriorTo(crystallized.getLastStateRecalc()); } return new BeaconState(crystallized, activeState); }
Source:
<code>public RepositoriesViewContentProvider() { ICommandService srv = (ICommandService) PlatformUI.getWorkbench() .getService(ICommandService.class); commandState = srv.getCommand( <START> "org.eclipse.egit.ui.RepositoriesToggleBranchHierarchy") END> .getState("org.eclipse.ui.commands.toggleState"); commandState.addListener(this); try { this.branchHierarchyMode = ((Boolean) commandState.getValue()) .booleanValue(); } catch (Exception e) { Activator.handleError(e.getMessage(), e, false); } }</code><technical_language>cool if refactor this a RepositoriesToggleBranchHierarchy.ID constant</technical_language>

Target:
public RepositoriesViewContentProvider() { ICommandService srv = (ICommandService) PlatformUI.getWorkbench() .getService(ICommandService.class); commandState = srv.getCommand( ToggleBranchHierarchyCommand.ID) .getState(ToggleBranchHierarchyCommand.TOGGLE_STATE); commandState.addListener(this); try { this.branchHierarchyMode = ((Boolean) commandState.getValue()) .booleanValue(); } catch (Exception e) { Activator.handleError(e.getMessage(), e, false); } }
Source:
<code><START> private ClientAndIterator<T> executeAndCollectWithClient(String jobExecutionName) throws Exception { <END> TypeSerializer<T> serializer = getType().createSerializer(getExecutionEnvironment().getConfig()); String accumulatorName = "dataStreamCollect_" + UUID.randomUUID().toString(); StreamExecutionEnvironment env = getExecutionEnvironment(); CollectSinkOperatorFactory<T> factory = new CollectSinkOperatorFactory<>(serializer, accumulatorName); CollectSinkOperator<T> operator = (CollectSinkOperator<T>) factory.getOperator(); CollectResultIterator<T> iterator = new CollectResultIterator<>( operator.getOperatorIdFuture(), serializer, accumulatorName, env.getCheckpointConfig()); CollectStreamSink<T> sink = new CollectStreamSink<>(this, factory); sink.name("Data stream collect sink"); env.addOperator(sink.getTransformation()); final JobClient jobClient = env.executeAsync(jobExecutionName); iterator.setJobClient(jobClient); return new ClientAndIterator<>(jobClient, iterator); }</code><technical_language>duplicating code want remove DataStreamUtils in future</technical_language>

Target:
ClientAndIterator<T> executeAndCollectWithClient(String jobExecutionName) throws Exception { TypeSerializer<T> serializer = getType().createSerializer(getExecutionEnvironment().getConfig()); String accumulatorName = "dataStreamCollect_" + UUID.randomUUID().toString(); StreamExecutionEnvironment env = getExecutionEnvironment(); CollectSinkOperatorFactory<T> factory = new CollectSinkOperatorFactory<>(serializer, accumulatorName); CollectSinkOperator<T> operator = (CollectSinkOperator<T>) factory.getOperator(); CollectResultIterator<T> iterator = new CollectResultIterator<>( operator.getOperatorIdFuture(), serializer, accumulatorName, env.getCheckpointConfig()); CollectStreamSink<T> sink = new CollectStreamSink<>(this, factory); sink.name("Data stream collect sink"); env.addOperator(sink.getTransformation()); final JobClient jobClient = env.executeAsync(jobExecutionName); iterator.setJobClient(jobClient); return new ClientAndIterator<>(jobClient, iterator); }
Source:
<code>public boolean generateLaborLedgerBenefitClearingPendingEntries( GeneralLedgerPendingEntrySequenceHelper sequenceHelper) { LOG.debug("started generateLaborLedgerBenefitClearingPendingEntries()"); String chartOfAccountsCode = SpringContext.getBean(ParameterService.class).getParameterValueAsString( SalaryExpenseTransferDocument.class, LaborParameterConstants.BENEFIT_CLEARING_CHART); String accountNumber = SpringContext.getBean(ParameterService.class).getParameterValueAsString( SalaryExpenseTransferDocument.class, <START> LaborParameterConstants.BENEFIT_CLEARING_CHART); <END> List<LaborLedgerPendingEntry> benefitClearingPendingEntries = LaborPendingEntryGenerator.generateBenefitClearingPendingEntries(this, sequenceHelper, accountNumber, chartOfAccountsCode); if (benefitClearingPendingEntries != null && !benefitClearingPendingEntries.isEmpty()) { return this.getLaborLedgerPendingEntries().addAll(benefitClearingPendingEntries); } return true; }</code><technical_language>This BENEFIT_CLEARING_ACCOUNT instead</technical_language>

Target:
public boolean generateLaborLedgerBenefitClearingPendingEntries( GeneralLedgerPendingEntrySequenceHelper sequenceHelper) { LOG.debug("started generateLaborLedgerBenefitClearingPendingEntries()"); String chartOfAccountsCode = SpringContext.getBean(ParameterService.class).getParameterValueAsString( SalaryExpenseTransferDocument.class, LaborParameterConstants.BENEFIT_CLEARING_CHART); String accountNumber = SpringContext.getBean(ParameterService.class).getParameterValueAsString( SalaryExpenseTransferDocument.class, LaborParameterConstants.BENEFIT_CLEARING_ACCOUNT); List<LaborLedgerPendingEntry> benefitClearingPendingEntries = LaborPendingEntryGenerator.generateBenefitClearingPendingEntries(this, sequenceHelper, accountNumber, chartOfAccountsCode); if (benefitClearingPendingEntries != null && !benefitClearingPendingEntries.isEmpty()) { return this.getLaborLedgerPendingEntries().addAll(benefitClearingPendingEntries); } return true; }
Source:
<code>public RetryLimitReachedException(List<Exception> exceptions) { <START> super(""); <END> exceptions.forEach(this::addSuppressed); this.numRetries = exceptions.size(); }</code><technical_language>I thought preserve messages? e.g. in Remoting's SafeIoException , InvalidAcceptorCacheKeyException in Atlas suggestion super(MESSAGE);</technical_language>

Target:
public RetryLimitReachedException(List<Exception> exceptions) { super(MESSAGE); exceptions.forEach(this::addSuppressed); this.numRetries = exceptions.size(); }
Source:
<code>public Optional<Resource> getUsedResource(String accountId) throws NotFoundException, ServerException { final Account account = accountManager.getById(accountId); final long currentlyUsedRuntimes = <START> Lists.newArrayList( <END> iterate( (maxItems, skipCount) -> workspaceManagerProvider .get() .getByNamespace(account.getName(), false, maxItems, skipCount)) .iterator()) .stream() .filter(ws -> STOPPED != ws.getStatus()) .count(); if (currentlyUsedRuntimes > 0) { return Optional.of( new ResourceImpl( RuntimeResourceType.ID, currentlyUsedRuntimes, RuntimeResourceType.UNIT)); } else { return Optional.empty(); } }</code><technical_language>complex</technical_language>

Target:
public Optional<Resource> getUsedResource(String accountId) throws NotFoundException, ServerException { final Account account = accountManager.getById(accountId); final long currentlyUsedRuntimes = Pages.stream( (maxItems, skipCount) -> workspaceManagerProvider .get() .getByNamespace(account.getName(), false, maxItems, skipCount)) .filter(ws -> STOPPED != ws.getStatus()) .count(); if (currentlyUsedRuntimes > 0) { return Optional.of( new ResourceImpl( RuntimeResourceType.ID, currentlyUsedRuntimes, RuntimeResourceType.UNIT)); } else { return Optional.empty(); } }
Source:
<code>private void updateDefaultRights(Map<String, BaseObject> rightsObjects, XWikiDocument doc) { Visibility visibility = getVisibility(doc); if (visibility == null || "none".equals(visibility.getDefaultAccessLevel().getName())) { return; } BaseObject right; if ("view".equals(visibility.getDefaultAccessLevel().getName())) { right = rightsObjects.get("view"); } else if ("edit".equals(visibility.getDefaultAccessLevel().getName())) { right = rightsObjects.get("view,edit"); } else { return; } <START> setRights(right, "groups", "XWikiAllGroup.XWikiAllGroup"); <END> }</code><technical_language>group XWiki.XWikiAllGroup</technical_language>

Target:
private void updateDefaultRights(Map<String, BaseObject> rightsObjects, XWikiDocument doc) { Visibility visibility = getVisibility(doc); if (visibility == null || "none".equals(visibility.getDefaultAccessLevel().getName())) { return; } BaseObject right; if ("view".equals(visibility.getDefaultAccessLevel().getName())) { right = rightsObjects.get("view"); } else if ("edit".equals(visibility.getDefaultAccessLevel().getName())) { right = rightsObjects.get("view,edit"); } else { return; } setRights(right, "groups", "XWiki.XWikiAllGroup"); }
Source:
<code>private List<Integer> getPercentileValues(String percentileString) { List<Integer> percentileValues = new ArrayList<Integer>(); try { for (String rawPercentile: percentileString.split(",")) { percentileValues.add(Integer.parseInt(rawPercentile)); } } catch(Exception e) { System.err.println("[WARN] Couldn't read " + PERCENTILES_PROPERTY + " value: '" + percentileString + <START> "', the default of '" + PERCENTILES_PROPERTY_DEFAULT + "' will be used."); <END> return getPercentileValues(PERCENTILES_PROPERTY_DEFAULT); } return percentileValues; }</code><technical_language>print a stacktrace well</technical_language>

Target:
private List<Integer> getPercentileValues(String percentileString) { List<Integer> percentileValues = new ArrayList<Integer>(); try { for (String rawPercentile: percentileString.split(",")) { percentileValues.add(Integer.parseInt(rawPercentile)); } } catch(Exception e) { System.err.println("[WARN] Couldn't read " + PERCENTILES_PROPERTY + " value: '" + percentileString + "', the default of '" + PERCENTILES_PROPERTY_DEFAULT + "' will be used."); e.printStackTrace(); return getPercentileValues(PERCENTILES_PROPERTY_DEFAULT); } return percentileValues; }
Source:
<code>private DhisStatusResponse createEntity(Settings settings, String uri, String json) { HttpUriRequest request = generatePostRequest(settings, uri, json); LOGGER.debug(String.format("Initiating request to create resource: %s, request: %s", json, request.toString())); CloseableHttpResponse response = getResponseForRequest(request); LOGGER.debug(String.format("Received response to create resource: %s, request: %s", json, response)); DhisStatusResponse status; try (InputStream content = getContentForResponse(response)) { status = new ObjectMapper().readValue(content, DhisStatusResponse.class); } catch (IOException e) { String msg = String.format("Error parsing response from uri: %s, exception: %s", uri, e.toString()); statusMessageService.warn(msg, MODULE_NAME); throw new DhisWebException(msg, e); } finally { closeResponse(response); } LOGGER.debug(String.format("DHIS2 status response: %s", status.getStatus().toString())); <START> if (status.getStatus() == DhisStatus.ERROR) { <END> String msg = String.format("Error in DHIS2 status response: %s", status.getStatus().toString()); statusMessageService.warn(msg, MODULE_NAME); throw new DhisWebException(msg); } return status; }</code><technical_language>check correctly ? In ticket description JIRA is information response return 200 (OK) response body 'ERROR', do include this condition</technical_language>

Target:
private DhisStatusResponse createEntity(Settings settings, String uri, String json) { HttpUriRequest request = generatePostRequest(settings, uri, json); LOGGER.debug(String.format("Initiating request to create resource: %s, request: %s", json, request.toString())); CloseableHttpResponse response = getResponseForRequest(request); LOGGER.debug(String.format("Received response to create resource: %s, request: %s", json, response)); DhisStatusResponse status; try (InputStream content = getContentForResponse(response)) { String contentString = IOUtils.toString(content); status = new ObjectMapper().readValue(contentString, DhisStatusResponse.class); if (status.getStatus() == DhisStatus.ERROR) { String msg = String.format("Error in DHIS2 status response, error details: %s", contentString); throw new DhisWebException(msg); } } catch (IOException e) { String msg = String.format("Error parsing response from uri: %s, exception: %s", uri, e.toString()); statusMessageService.warn(msg, MODULE_NAME); throw new DhisWebException(msg, e); } finally { closeResponse(response); } return status; }
Source:
<code>private byte[] encode(ObjectId oldId, ObjectId newId, PersonIdent ident, String message) { final StringBuilder r = new StringBuilder(); r.append(ObjectId.toString(oldId)); r.append(' '); r.append(ObjectId.toString(newId)); r.append(' '); r.append(ident.toExternalString()); r.append('\t'); <START> r.append(message.replace("\n", " ")); <END> r.append('\n'); return Constants.encode(r.toString()); }</code><technical_language>\r\n Windows</technical_language>

Target:
private byte[] encode(ObjectId oldId, ObjectId newId, PersonIdent ident, String message) { final StringBuilder r = new StringBuilder(); r.append(ObjectId.toString(oldId)); r.append(' '); r.append(ObjectId.toString(newId)); r.append(' '); r.append(ident.toExternalString()); r.append('\t'); r.append(message.replace("\r\n", " ").replace("\n", " ")); r.append('\n'); return Constants.encode(r.toString()); }
Source:
<code>void drainLoop() { int missed = 1; JoinInnerSubscriber<T>[] s = this.subscribers; int n = s.length; Subscriber<? super T> a = this.actual; for (;;) { long r = requested.get(); long e = 0; middle: while (e != r) { if (cancelled) { cleanup(); return; } Throwable ex = errors.get(); if (ex != null) { cleanup(); a.onError(ex); return; } boolean d = done.get() == 0; boolean empty = true; <START> for (JoinInnerSubscriber<T> inner : s) { <END> SimplePlainQueue<T> q = inner.queue; if (q != null) { T v = q.poll(); if (v != null) { empty = false; a.onNext(v); inner.requestOne(); if (++e == r) { break middle; } } } } if (d && empty) { a.onComplete(); return; } if (empty) { break; } } if (e == r) { if (cancelled) { cleanup(); return; } Throwable ex = errors.get(); if (ex != null) { cleanup(); a.onError(ex); return; } boolean d = done.get() == 0; boolean empty = true; for (int i = 0; i < n; i++) { JoinInnerSubscriber<T> inner = s[i]; SimpleQueue<T> q = inner.queue; if (q != null && !q.isEmpty()) { empty = false; break; } } if (d && empty) { a.onComplete(); return; } } if (e != 0 && r != Long.MAX_VALUE) { requested.addAndGet(-e); } int w = get(); if (w == missed) { missed = addAndGet(-missed); if (missed == 0) { break; } } else { missed = w; } } }</code><technical_language>want leave allocate iterator</technical_language>

Target:
void drainLoop() { int missed = 1; JoinInnerSubscriber<T>[] s = this.subscribers; int n = s.length; Subscriber<? super T> a = this.actual; for (;;) { long r = requested.get(); long e = 0; middle: while (e != r) { if (cancelled) { cleanup(); return; } Throwable ex = errors.get(); if (ex != null) { cleanup(); a.onError(ex); return; } boolean d = done.get() == 0; boolean empty = true; for (int i = 0; i < s.length; i++) { JoinInnerSubscriber<T> inner = s[i]; SimplePlainQueue<T> q = inner.queue; if (q != null) { T v = q.poll(); if (v != null) { empty = false; a.onNext(v); inner.requestOne(); if (++e == r) { break middle; } } } } if (d && empty) { a.onComplete(); return; } if (empty) { break; } } if (e == r) { if (cancelled) { cleanup(); return; } Throwable ex = errors.get(); if (ex != null) { cleanup(); a.onError(ex); return; } boolean d = done.get() == 0; boolean empty = true; for (int i = 0; i < n; i++) { JoinInnerSubscriber<T> inner = s[i]; SimpleQueue<T> q = inner.queue; if (q != null && !q.isEmpty()) { empty = false; break; } } if (d && empty) { a.onComplete(); return; } } if (e != 0 && r != Long.MAX_VALUE) { requested.addAndGet(-e); } int w = get(); if (w == missed) { missed = addAndGet(-missed); if (missed == 0) { break; } } else { missed = w; } } }
Source:
<code>public List<Node> getMembers() { <START> List<Node> list = new ArrayList<>(); <END> for (Address address : this.view) { Node node = this.factory.createNode(address); list.add(node); } return list; }</code><technical_language>ArrayList constructed fixed capacity</technical_language>

Target:
public List<Node> getMembers() { List<Node> list = new ArrayList<>(this.view.size()); for (Address address : this.view) { list.add(this.factory.createNode(address)); } return list; }
Source:
<code>public void shouldPreserveOffsetsFromCommitByGroupMetadataOnAbortIfTransactionsAreEnabled() { buildMockProducer(true); producer.initTransactions(); producer.beginTransaction(); String group = "g"; Map<TopicPartition, OffsetAndMetadata> groupCommit = new HashMap<TopicPartition, OffsetAndMetadata>() { { put(new TopicPartition(topic, 0), new OffsetAndMetadata(42L, null)); put(new TopicPartition(topic, 1), new OffsetAndMetadata(73L, null)); } }; producer.sendOffsetsToTransaction(groupCommit, groupMetadata(group)); producer.commitTransaction(); producer.beginTransaction(); producer.abortTransaction(); Map<String, Map<TopicPartition, OffsetAndMetadata>> expectedResult = new HashMap<>(); expectedResult.put(group, groupCommit); <START> assertThat(producer.consumerGroupOffsetsHistory(), equalTo(Collections.singletonList(expectedResult))); <END> }</code><technical_language>this test case more interesting if commit a separate set of offsets aborting</technical_language>

Target:
public void shouldPreserveOffsetsFromCommitByGroupMetadataOnAbortIfTransactionsAreEnabled() { buildMockProducer(true); producer.initTransactions(); producer.beginTransaction(); String group = "g"; Map<TopicPartition, OffsetAndMetadata> groupCommit = new HashMap<TopicPartition, OffsetAndMetadata>() { { put(new TopicPartition(topic, 0), new OffsetAndMetadata(42L, null)); put(new TopicPartition(topic, 1), new OffsetAndMetadata(73L, null)); } }; producer.sendOffsetsToTransaction(groupCommit, new ConsumerGroupMetadata(group)); producer.commitTransaction(); producer.beginTransaction(); String group2 = "g2"; Map<TopicPartition, OffsetAndMetadata> groupCommit2 = new HashMap<TopicPartition, OffsetAndMetadata>() { { put(new TopicPartition(topic, 2), new OffsetAndMetadata(53L, null)); put(new TopicPartition(topic, 3), new OffsetAndMetadata(84L, null)); } }; producer.sendOffsetsToTransaction(groupCommit, new ConsumerGroupMetadata(group2)); producer.abortTransaction(); Map<String, Map<TopicPartition, OffsetAndMetadata>> expectedResult = new HashMap<>(); expectedResult.put(group, groupCommit); assertThat(producer.consumerGroupOffsetsHistory(), equalTo(Collections.singletonList(expectedResult))); }
Source:
<code>private synchronized int readPidFromPidFile(String... commands) throws IOException, InterruptedException { int pid = -1; <START> FilePath pidFile = ws.child(readPidFile(commands)); <END> for (int w = 0; w < 10 && !pidFile.exists(); w++) { try { wait(1000); } catch (InterruptedException e) { break; } } if (pidFile.exists()) { try { pid = Integer.parseInt(pidFile.readToString().trim()); } catch (NumberFormatException x) { throw new IOException("corrupted content in " + pidFile + ": " + x, x); } } return pid; }</code><technical_language>@iocanel readPidFile return null NPE 11:43:41 java.lang.NullPointerException 11:43:41 hudson.FilePath.isAbsolute(FilePath.java:281) 11:43:41 hudson.FilePath.resolvePathIfRelative(FilePath.java:266) 11:43:41 hudson.FilePath.<init>(FilePath.java:262) 11:43:41 hudson.FilePath.child(FilePath.java:1273) 11:43:41 org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator.readPidFromPidFile(ContainerExecDecorator.java:467) 11:43:41 org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator.access$1000(ContainerExecDecorator.java:69) 11:43:41 org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator$1.doLaunch(ContainerExecDecorator.java:335) 11:43:41 org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator$1.launch(ContainerExecDecorator.java:147)</technical_language>

Target:
private synchronized int readPidFromPidFile(String... commands) throws IOException, InterruptedException { int pid = -1; String pidFilePath = readPidFile(commands); if (pidFilePath == null) { return pid; } FilePath pidFile = ws.child(pidFilePath); for (int w = 0; w < 10 && !pidFile.exists(); w++) { try { wait(1000); } catch (InterruptedException e) { break; } } if (pidFile.exists()) { try { pid = Integer.parseInt(pidFile.readToString().trim()); } catch (NumberFormatException x) { throw new IOException("corrupted content in " + pidFile + ": " + x, x); } } return pid; }
Source:
<code>public void initTrace(final IResource resource, final String path, final Class<CtfTmfEvent> eventType) throws TmfTraceException { setCacheSize(); super.initTrace(resource, path, eventType); @SuppressWarnings("unused") CtfTmfEventType type; try { this.fTrace = new CTFTrace(path); CtfIteratorManager.init(); CtfIteratorManager.AddTrace(this); <START> ctx = new CtfTmfLightweightContext(this); <END> ctx.setLocation(new CtfLocation(0L)); final CtfIterator iterator = CtfIteratorManager.getIterator(this, ctx); if(iterator.getLocation().equals(CtfIterator.NULL_LOCATION)) { this.setStartTime(TmfTimestamp.BIG_BANG); } else { this.setStartTime(iterator.getCurrentEvent().getTimestamp()); this.setEndTime(iterator.getCurrentEvent().getTimestamp()); } } catch (final CTFReaderException e) { throw new TmfTraceException(e.getMessage(), e); } buildStateSystem(); if ( resource != null) { try { resource.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { throw new TmfTraceException(e.getMessage(), e); } } }</code><technical_language>store a field variable (and if so, renamed)</technical_language>

Target:
public void initTrace(final IResource resource, final String path, final Class<CtfTmfEvent> eventType) throws TmfTraceException { setCacheSize(); super.initTrace(resource, path, eventType); @SuppressWarnings("unused") CtfTmfEventType type; try { this.fTrace = new CTFTrace(path); CtfIteratorManager.init(); CtfIteratorManager.addTrace(this); ctx = new CtfTmfLightweightContext(this); ctx.setLocation(new CtfLocation(0L)); final CtfIterator iterator = getIterator(); if(iterator.getLocation().equals(CtfIterator.NULL_LOCATION)) { this.setStartTime(TmfTimestamp.BIG_BANG); } else { this.setStartTime(iterator.getCurrentEvent().getTimestamp()); this.setEndTime(iterator.getCurrentEvent().getTimestamp()); } } catch (final CTFReaderException e) { throw new TmfTraceException(e.getMessage(), e); } buildStateSystem(); if ( resource != null) { try { resource.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { throw new TmfTraceException(e.getMessage(), e); } } }
Source:
<code>public MemberAssignment(Set<TopicPartition> topicPartitions) { <START> this.topicPartitions = Collections.unmodifiableSet(new HashSet<>(topicPartitions)); <END> }</code><technical_language>customary Objects.requireNonNull(topicPartitions). LGTM assuming tests pass</technical_language>

Target:
public MemberAssignment(Set<TopicPartition> topicPartitions) { Objects.requireNonNull(topicPartitions); this.topicPartitions = Collections.unmodifiableSet(new HashSet<>(topicPartitions)); }
Source:
<code><START> public void setUp() throws Exception { <END> logFileName = Platform.getInstallLocation().getURL().getPath() + ".." + File.separator + ".." + File.separator + "results" + File.separator + "chkpii"; }</code><technical_language>Remove throws Exception</technical_language>

Target:
public void setUp() { logFileName = Platform.getInstallLocation().getURL().getPath() + ".." + File.separator + ".." + File.separator + "results" + File.separator + "chkpii"; }
Source:
<code>public void testApplication() throws Exception { File modelFile = new File("src/test/resources/model/model_file_csv.json"); String model = FileUtils.readFileToString(modelFile); try { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); lma.prepareDAG(new Application(model), conf); LocalMode.Controller lc = lma.getController(); <START> lc.run(10 * 1000); END> } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } catch (Exception e) { Assert.fail("Exception: " + e); } }</code><technical_language>this is anti-pattern frequently in tests. decided avoid this in newer tests. Test wait for outputFile.exists() compare results actual results. Read discussion this <LINK_1> <LINK_0></technical_language>

Target:
public void testApplication() throws Exception { File modelFile = new File("src/test/resources/model/model_file_csv.json"); String model = FileUtils.readFileToString(modelFile); PrintStream originalSysout = System.out; ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); try { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); lma.prepareDAG(new Application(model), conf); LocalMode.Controller lc = lma.getController(); lc.runAsync(); waitTillStdoutIsPopulated(baos, 30000); lc.shutdown(); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } catch (Exception e) { Assert.fail("Exception: " + e); } System.setOut(originalSysout); String[] sout = baos.toString().split(System.lineSeparator()); Collection<String> filter = Collections2.filter(Arrays.asList(sout), Predicates.containsPattern("Delta Record:")); String[] actualLines = filter.toArray(new String[filter.size()]); Assert.assertEquals(6, actualLines.length); Assert.assertTrue(actualLines[0].contains("RowTime=Mon Feb 15 10:15:00 GMT 2016, Product=paint1")); Assert.assertTrue(actualLines[1].contains("RowTime=Mon Feb 15 10:16:00 GMT 2016, Product=paint2")); Assert.assertTrue(actualLines[2].contains("RowTime=Mon Feb 15 10:17:00 GMT 2016, Product=paint3")); Assert.assertTrue(actualLines[3].contains("RowTime=Mon Feb 15 10:18:00 GMT 2016, Product=paint4")); Assert.assertTrue(actualLines[4].contains("RowTime=Mon Feb 15 10:19:00 GMT 2016, Product=paint5")); Assert.assertTrue(actualLines[5].contains("RowTime=Mon Feb 15 10:10:00 GMT 2016, Product=abcde6")); }
Source:
<code>public SettingSelector setKeyFilter(String keyFilter) { <START> Objects.requireNonNull(keyFilter); <END> this.keyFilter = keyFilter; return this; }</code><technical_language>Actually, SDK guidelines, this verification allowing service return a bad request. <LINK_0></technical_language>

Target:
public SettingSelector setKeyFilter(String keyFilter) { this.keyFilter = keyFilter; return this; }
Source:
<code>public Mono<FileDownloadAsyncResponse> readWithResponse(FileRange range, DownloadRetryOptions options, <START> DataLakeRequestConditions accessConditions, boolean rangeGetContentMD5) { <END> try { return blockBlobAsyncClient.downloadWithResponse(Transforms.toBlobRange(range), Transforms.toBlobDownloadRetryOptions(options), Transforms.toBlobRequestConditions(accessConditions), rangeGetContentMD5).map(response -> new FileDownloadAsyncResponse(response.getRequest(), response.getStatusCode(), response.getHeaders(), response.getValue(), response.getDeserializedHeaders())); } catch (RuntimeException ex) { return monoError(logger, ex); } }</code><technical_language>Request conditions</technical_language>

Target:
public Mono<FileReadAsyncResponse> readWithResponse(FileRange range, DownloadRetryOptions options, DataLakeRequestConditions accessConditions, boolean rangeGetContentMD5) { try { return blockBlobAsyncClient.downloadWithResponse(Transforms.toBlobRange(range), Transforms.toBlobDownloadRetryOptions(options), Transforms.toBlobRequestConditions(accessConditions), rangeGetContentMD5).map(Transforms::toFileReadAsyncResponse); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
<code>public void transformCalendarToLocalDate() throws DatatypeConfigurationException { LocalDate date = LocalDate.now(); <START> Calendar value = Calendar.getInstance(); <END> LocalDate transform = new DateTimeTransformer().transform(value, LocalDate.class); assertNotNull("LocalDate should not be null", transform); assertEquals("LocalDates should be equal", date, transform); }</code><technical_language>I guess forgot change represent date date... get dates. for other methods below</technical_language>

Target:
public void transformCalendarToLocalDate() throws DatatypeConfigurationException { Calendar value = Calendar.getInstance(TimeZone.getDefault()); LocalDate date = value.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate transform = new DateTimeTransformer().transform(value, LocalDate.class); assertNotNull("LocalDate should not be null", transform); assertEquals("LocalDates should be equal", date, transform); }
Source:
<code>public String toCsvString() { <START> SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.US); <END> StringBuilder sb = new StringBuilder(); sb.append(chart).append(KFSConstants.COMMA); sb.append(accountNumber).append(KFSConstants.COMMA); sb.append((StringUtils.isNotBlank(subAccountNumber) ? subAccountNumber : KFSConstants.EMPTY_STRING)).append(KFSConstants.COMMA); sb.append(accountClosedIndicator).append(KFSConstants.COMMA); sb.append(sdf.format(accountClosedDate)); return sb.toString(); }</code><technical_language>"MM/DD/yyyy" is defined a constant in KFSConstants</technical_language>

Target:
public String toCsvString() { SimpleDateFormat sdf = new SimpleDateFormat(KFSConstants.MONTH_DAY_YEAR_DATE_FORMAT, Locale.US); StringBuilder sb = new StringBuilder(); sb.append(chart).append(KFSConstants.COMMA); sb.append(accountNumber).append(KFSConstants.COMMA); sb.append((StringUtils.isNotBlank(subAccountNumber) ? subAccountNumber : KFSConstants.EMPTY_STRING)).append(KFSConstants.COMMA); sb.append(accountClosedIndicator).append(KFSConstants.COMMA); sb.append(sdf.format(accountClosedDate)); return sb.toString(); }
Source:
<code>public AnonymousAuthenticator( @JsonProperty("name") String name, @JsonProperty("authorizerName") String authorizerName, @JsonProperty("identity") String identity ) { this.name = name; this.authorizerName = authorizerName; this.identity = identity == null ? DEFAULT_IDENTITY : identity; <START> this.anonymousResult = new AuthenticationResult( <END> this.identity, this.authorizerName, this.name, null ); }</code><technical_language>anonymousResult needs a field in class, rest removed ? In case meant this class in JSON serde, please add @JsonProperty annotations fields create getter methods</technical_language>

Target:
public AnonymousAuthenticator( @JsonProperty("name") String name, @JsonProperty("authorizerName") String authorizerName, @JsonProperty("identity") String identity ) { this.anonymousResult = new AuthenticationResult( identity == null ? DEFAULT_IDENTITY : identity, authorizerName, name, null ); }
Source:
<code>public List<InternalJob> loadJobWithTasksIfNotRemoved(final JobId... jobIds) { return executeReadOnlyTransaction(session -> { Query jobQuery = session.getNamedQuery("loadJobDataIfNotRemoved").setReadOnly(true); <START> List<Long> ids = new ArrayList<>(jobIds.length); <END> for (JobId jobId : jobIds) { ids.add(jobId(jobId)); } List<InternalJob> result = new ArrayList<>(jobIds.length); batchLoadJobs(session, false, jobQuery, ids, result); return result; }); }</code><technical_language>addAll? stream</technical_language>

Target:
public List<InternalJob> loadJobWithTasksIfNotRemoved(final JobId... jobIds) { return executeReadOnlyTransaction(session -> { Query jobQuery = session.getNamedQuery("loadJobDataIfNotRemoved").setReadOnly(true); List<Long> ids = Arrays.stream(jobIds).map(SchedulerDBManager::jobId).collect(Collectors.toList()); List<InternalJob> result = new ArrayList<>(jobIds.length); batchLoadJobs(session, false, jobQuery, ids, result); return result; }); }
Source:
<code>public String toString() { return "ParameterizedMetricKey{" + "key=" + key <START> + ", options=" + version <END> + '}'; }</code><technical_language>options -> version</technical_language>

Target:
public String toString() { return "ParameterizedMetricKey{" + "key=" + key + ", version=" + version + '}'; }
Source:
<code>public void shouldFunction0ReturnNotNull() { <START> assertThat(function0(() -> null)).isNotNull(); <END> }</code><technical_language>more specific check instance of Function0 maybe</technical_language>

Target:
public void shouldFunction0ReturnNotNull() { assertThat(Function0(() -> null)).isNotNull(); }
Source:
<code>private String getCommandParamatersString(T params) { <START> final String GET = "get"; <END> StringBuilder buf = new StringBuilder(); List<String> methodNames = ReflectionUtils.getMethodNames(params); methodNames.removeAll(ReflectionUtils.getMethodNames(new VdcActionParametersBase())); for (String methodName : methodNames) { if (!methodName.startsWith(GET)) { continue; } Object retVal = ReflectionUtils.invokeMethodWithNoArgs(params, methodName); if (retVal == null) { continue; } if (buf.length() > 0) { buf.append(", "); } buf.append(methodName.substring(GET.length())); buf.append(" = "); buf.append(retVal.toString()); } return buf.toString(); }</code><technical_language>booleans start "is"</technical_language>

Target:
private String getCommandParamatersString(T params) { StringBuilder buf = new StringBuilder(); List<String> methodNames = ReflectionUtils.getMethodNames(params); List<String> fieldNames = ReflectionUtils.getFieldNames(params); fieldNames.removeAll(ReflectionUtils.getFieldNames(new VdcActionParametersBase())); for (String fieldName : fieldNames) { Method method = ReflectionUtils.getGetter(params, fieldName, methodNames); if (method == null) { continue; } Object retVal = ReflectionUtils.invokeMethodWithNoArgs(params, method); if (buf.length() > 0) { buf.append(", "); } buf.append(fieldName); buf.append(" = "); buf.append(retVal == null ? "null" : retVal.toString()); } return buf.toString(); }
Source:
<code><START> private static TreeItem firstOrNull(TreeItem[] items) { <END> if (items.length == 0) { return items[0]; } return null; }</code><technical_language>I items.length > 0</technical_language>

Target:
private static TreeItem firstOrNull(TreeItem[] items) { if (items.length > 0) { return items[0]; } return null; }
Source:
<code>public void commit(IProgressMonitor monitor) throws CoreException { if (isDirty()) { if (isConnected()) { super.commit(monitor); } else { File file = path.toFile(); try { java.nio.file.Path fp = file.toPath(); if (Files.isSymbolicLink(fp)) { String sp = new String(getContent(), StandardCharsets.UTF_8) .trim(); if (sp.indexOf('\n') > 0) { sp = sp.substring(0, sp.indexOf('\n')).trim(); } if (!sp.isEmpty()) { boolean wasBrokenLink = !file.exists(); java.nio.file.Path link = FileUtils .createSymLink(file, sp); updateLinkResource(wasBrokenLink, link); } } else { <START> if (!file.exists()) { FileUtils.createNewFile(file); } <END> try (OutputStream out = Files .newOutputStream(file.toPath())) { out.write(getContent()); } } fDirty = false; } catch (IOException e) { throw new CoreException( new Status( IStatus.ERROR, Activator.getPluginId(), UIText.LocalNonWorkspaceTypedElement_errorWritingContents, e)); } finally { fireChanges(); } } refreshTimestamp(); } }</code><technical_language>I this removed. Files.newOutputStream(path) create file if exist</technical_language>

Target:
public void commit(IProgressMonitor monitor) throws CoreException { if (isDirty()) { if (isConnected()) { super.commit(monitor); } else { File file = path.toFile(); try { java.nio.file.Path fp = file.toPath(); if (Files.isSymbolicLink(fp)) { String sp = new String(getContent(), StandardCharsets.UTF_8) .trim(); if (sp.indexOf('\n') > 0) { sp = sp.substring(0, sp.indexOf('\n')).trim(); } if (!sp.isEmpty()) { boolean wasBrokenLink = !file.exists(); java.nio.file.Path link = FileUtils .createSymLink(file, sp); updateLinkResource(wasBrokenLink, link); } } else { try (OutputStream out = Files .newOutputStream(file.toPath())) { out.write(getContent()); } } fDirty = false; } catch (IOException e) { throw new CoreException( new Status( IStatus.ERROR, Activator.getPluginId(), UIText.LocalNonWorkspaceTypedElement_errorWritingContents, e)); } finally { fireChanges(); } } refreshTimestamp(); } }
Source:
<code>public Number convert( final String value ) { <START> return new BigDecimal( value ); <END> }</code><technical_language>This in theory throw a NumberFormatException. This is caught in similar case in ListBoxByteSingletonDOMElementFactory, good catch too</technical_language>

Target:
public Number convert( final String value ) { try { return new BigDecimal( value ); } catch ( NumberFormatException nfe ) { return new BigDecimal( "0.0" ); } }
Source:
<code>public void eachNonZeroInRow(int i, MatrixProcedure procedure) { for (int j = 0; j < columns; j++) { <START> if (get(i, j) > Matrices.EPS) procedure.apply(i,j,get(i,j)); <END> } }</code><technical_language>Math.abs() is missed. negative values? please, add arround procedure.apply(...)</technical_language>

Target:
public void eachNonZeroInRow(int i, MatrixProcedure procedure) { for (int j = 0; j < columns; j++) { if (Math.abs(get(i, j)) > Matrices.EPS) { procedure.apply(i, j, get(i, j)); } } }
Source:
<code>private NatService.Builder newServiceBuilder(JcloudsLocation loc) { String endpoint = loc.getEndpoint(); String convertedUri; try { URI uri = URI.create(endpoint); convertedUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null).toString(); } catch (URISyntaxException e) { throw Exceptions.propagate(e); } <START> String trustStore = (String) loc.getAllConfigBag().getStringKey("trustStore"); <END> String trustStorePassword = (String) loc.getAllConfigBag().getStringKey("trustStorePassword"); return NatService.builder() .identity(loc.getIdentity()) .credential(loc.getCredential()) .endpoint(convertedUri) .trustStore(trustStore) .trustStorePassword(trustStorePassword); }</code><technical_language>This test test trustStore if config key is missing in brooklyn.properties, fail/skip either. Instead, give a false impression test passes. include assertNotNull(trustStore, "trustStore set location " + loc), for trustStorePassword</technical_language>

Target:
private NatService.Builder newServiceBuilder(JcloudsLocation loc) { String endpoint = loc.getEndpoint(); String convertedUri; try { URI uri = URI.create(endpoint); convertedUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null).toString(); } catch (URISyntaxException e) { throw Exceptions.propagate(e); } String trustStore = (String) loc.getAllConfigBag().getStringKey("trustStore"); String trustStorePassword = (String) loc.getAllConfigBag().getStringKey("trustStorePassword"); assertNotNull(trustStorePassword, "trustStorePassword not set on location " + loc); return NatService.builder() .identity(loc.getIdentity()) .credential(loc.getCredential()) .endpoint(convertedUri) .trustStore(trustStore) .trustStorePassword(trustStorePassword); }
Source:
<code><START> public void sendBlockEntityChange(Location location, CompoundTag nbt, GlowBlockEntity type) throws NullPointerException { <END> Validate.notNull(location, "Location cannot be null"); Validate.notNull(nbt, "NBT cannot be null"); Validate.notNull(type, "Type cannot be null"); afterBlockChanges.add(new UpdateBlockEntityMessage(location.getBlockX(), location.getBlockY(), location.getBlockZ(), type.getValue(), nbt)); }</code><technical_language>throws is required</technical_language>

Target:
public void sendBlockEntityChange(Location location, CompoundTag nbt, GlowBlockEntity type) { Validate.notNull(location, "Location cannot be null"); Validate.notNull(nbt, "NBT cannot be null"); Validate.notNull(type, "Type cannot be null"); afterBlockChanges.add(new UpdateBlockEntityMessage(location.getBlockX(), location.getBlockY(), location.getBlockZ(), type.getValue(), nbt)); }