auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void test_evaluateAll() { DMNContext dmnContext = dmnClient.newContext(); dmnContext.set("Values", Arrays.asList(new BigDecimal(1), new BigDecimal(2), new BigDecimal(3))); ServiceResponse<DMNResult> evaluateAll = dmnClient.evaluateAll(CONTAINER_1_ID, dmnContext); <START> assertThat(evaluateAll.getType(), is(ResponseType.SUCCESS)); <END> DMNResult dmnResult = evaluateAll.getResult(); assertThat(dmnResult.getMessages().toString(), dmnResult.hasErrors(), is(false)); DMNContext result = dmnResult.getContext(); assertThat(result.get("Standard Deviation"), is(new BigDecimal(1))); }</code><technical_language>@tarilabs KieServerAssert.assertSuccess(ServiceResponse<?> response) - <LINK_0></technical_language>

Target:
public void test_evaluateAll() { DMNContext dmnContext = dmnClient.newContext(); dmnContext.set("Values", Arrays.asList(new BigDecimal(1), new BigDecimal(2), new BigDecimal(3))); ServiceResponse<DMNResult> evaluateAll = dmnClient.evaluateAll(CONTAINER_1_ID, dmnContext); KieServerAssert.assertSuccess(evaluateAll); DMNResult dmnResult = evaluateAll.getResult(); assertThat(dmnResult.getMessages().toString(), dmnResult.hasErrors(), is(false)); DMNContext result = dmnResult.getContext(); assertThat(result.get("Standard Deviation"), is(new BigDecimal(1))); }
Source:
<code>public void setUp() throws Exception { <START> bootstrap.start(1620, 8080, "dev.telcong.com"); <END> }</code><technical_language>bad a common port 8080..</technical_language>

Target:
public void setUp() throws Exception { bootstrap.start(); }
Source:
<code><START> public void findAnyDonorStartsWith_softDeleteRecordNotInclude() { <END> donorRepository.deleteDonor(228l); assertEquals("List size should be zero because matching donornumber record is softdeleted.",donorRepository.findAnyDonorStartsWith("000233").size(),0); }</code><technical_language>deleting Donor(228l), testing searching for Donor(000233)? Also, a lot of Donor Numbers Ids characters [a-z] in them, Donor Number Donor Id formats numeric: e.g. donor id: 167 e.g. donor number: 000189</technical_language>

Target:
public void findAnyDonorStartsWith_softDeleteRecordNotInclude() { List<Donor> listDonor = donorRepository.findAnyDonorStartsWith("00"); for (Donor donor : listDonor) { assertNotSame( "Donor Id 2 is deleted from donor table so, that record should not part of list.", 2, donor.getId()); } }
Source:
<code>public void testOpenSessionEditorByDoubleClick5() { designerProject.convertToModelingProject(); Display.getDefault().syncExec(() -> { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.eclipse.ui.navigator.ProjectExplorer"); } catch (PartInitException e) { e.printStackTrace(); } }); <START> SWTBotView packageExplorerView = bot.viewById("org.eclipse.ui.navigator.ProjectExplorer"); packageExplorerView.setFocus(); SWTBot packageExplorerViewBot = packageExplorerView.bot(); SWTBotTreeItem expandedNode = packageExplorerViewBot.tree().expandNode("DesignerTestProject", true); SWTBotTreeItem node = expandedNode.getNode("My.aird"); node.doubleClick(); bot.waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().getActiveEditor() != null; } @Override public String getFailureMessage() { return "Wrong Active editor is : " + PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().getActiveEditor().getEditorSite().getId(); } }); assertEquals("The session editor has not opened.", "org.eclipse.sirius.ui.editor.session", PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().getActiveEditor().getEditorSite().getId()); <END> }</code><technical_language>is</technical_language>

Target:
public void testOpenSessionEditorByDoubleClick5() { designerProject.convertToModelingProject(); Display.getDefault().syncExec(() -> { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.eclipse.ui.navigator.ProjectExplorer"); } catch (PartInitException e) { e.printStackTrace(); } }); SWTBotView packageExplorerView = bot.viewById("org.eclipse.ui.navigator.ProjectExplorer"); packageExplorerView.setFocus(); SWTBot packageExplorerViewBot = packageExplorerView.bot(); assertSessionEditorOpened(packageExplorerViewBot); }
Source:
<code>public double get(int i, int j) { <START> ensureIndexesAreInBounds(i, j); <END> return getOrElse(i, j, 0.0); }</code><technical_language>wrong indentation. 4 spaces</technical_language>

Target:
public double get(int i, int j) { return getOrElse(i, j, 0.0); }
Source:
<code>private void handleListTag(Editable output) { int size = mListParents.size(); <START> if (size > 0) { <END> if (mListParents.get(size - 1).equals("ul")) { output.append("\n"); String[] split = output.toString().split("\n"); int start = 0; if (split.length != 1) { int lastIndex = split.length - 1; start = output.length() - split[lastIndex].length() - 1; } output.setSpan(new BulletSpan(15 * mListParents.size()), start, output.length(), 0); } else if (mListParents.get(size - 1).equals("ol")) { mListItemCount++; output.append("\n"); String[] split = output.toString().split("\n"); int start = 0; if (split.length != 1) { int lastIndex = split.length - 1; start = output.length() - split[lastIndex].length() - 1; } output.insert(start, mListItemCount + ". "); output.setSpan(new LeadingMarginSpan.Standard(15 * mListParents.size()), start, output.length(), 0); } } }</code><technical_language>good call in checking for size > 0, assigned a var evaluated time. Thank you</technical_language>

Target:
private void handleListTag(Editable output) { int size = mListParents.size(); if (size > 0 && output != null) { if ("ul".equals(mListParents.get(size - 1))) { output.append("\n"); String[] split = output.toString().split("\n"); int start = 0; if (split.length != 1) { int lastIndex = split.length - 1; start = output.length() - split[lastIndex].length() - 1; } output.setSpan(new BulletSpan(SPAN_INDENT_WIDTH * mListParents.size()), start, output.length(), 0); } else if ("ol".equals(mListParents.get(size - 1))) { mListItemCount++; output.append("\n"); String[] split = output.toString().split("\n"); int start = 0; if (split.length != 1) { int lastIndex = split.length - 1; start = output.length() - split[lastIndex].length() - 1; } output.insert(start, mListItemCount + ". "); output.setSpan(new LeadingMarginSpan.Standard(SPAN_INDENT_WIDTH * mListParents.size()), start, output.length(), 0); } } }
Source:
<code>public static boolean isValidEditEvent(int event) { for (int <START> ignoreKeyEvent : <END> MemoryViewUtil.ignoreKeyEvents) { if (event == ignoreKeyEvent) return false; } return true; }</code><technical_language>rename keyEvent ignoredKeyKevent</technical_language>

Target:
public static boolean isValidEditEvent(int event) { for (int ignoredKeyKevent : MemoryViewUtil.ignoreKeyEvents) { if (event == ignoredKeyKevent) { return false; } } return true; }
Source:
<code>public void testReadingPendingMessageWithNoAutoACK() { Address address = new Address("Winterfell, Westeros"); Person person = new Person(address, "John Snow"); this.template.opsForStream() .createGroup(STREAM_KEY, this.redisStreamMessageProducer.getBeanName()) .as(StepVerifier::create) .assertNext(message -> assertThat(message).isEqualTo("OK")) .thenCancel() .verify(Duration.ofSeconds(10)); this.redisStreamMessageProducer.setCreateConsumerGroup(false); this.redisStreamMessageProducer.setAutoAck(false); this.redisStreamMessageProducer.setConsumerName(CONSUMER); this.redisStreamMessageProducer.afterPropertiesSet(); <START> this.redisStreamMessageProducer.start(); <END> this.messageHandler.handleMessage(new GenericMessage<>(person)); Mono<PendingMessagesSummary> pending = template.opsForStream().pending(STREAM_KEY, this.redisStreamMessageProducer.getBeanName()); StepVerifier.create(pending) .expectSubscription() .expectNextCount(1) .verifyComplete(); }</code><technical_language>chances consumed messages verify headers for IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK? pending verification call ack if is pending afterward left</technical_language>

Target:
public void testReadingPendingMessageWithNoAutoACK() { Address address = new Address("Winterfell, Westeros"); Person person = new Person(address, "John Snow"); this.template.opsForStream() .createGroup(STREAM_KEY, this.redisStreamMessageProducer.getBeanName()) .as(StepVerifier::create) .assertNext(message -> assertThat(message).isEqualTo("OK")) .thenCancel() .verify(Duration.ofSeconds(10)); this.redisStreamMessageProducer.setCreateConsumerGroup(false); this.redisStreamMessageProducer.setAutoAck(false); this.redisStreamMessageProducer.setConsumerName(CONSUMER); this.redisStreamMessageProducer.afterPropertiesSet(); this.redisStreamMessageProducer.start(); this.messageHandler.handleMessage(new GenericMessage<>(person)); Flux.from(this.fluxMessageChannel) .as(StepVerifier::create) .assertNext(message -> { assertThat(message.getPayload()).isEqualTo(person); assertThat(message.getHeaders()).containsKeys(IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK); }) .thenCancel() .verify(Duration.ofSeconds(10)); }
Source:
<code>private void addPatternToIndex(TripPattern tripPattern) { for (Stop stop: tripPattern.getStops()) { <START> if (!patternsForStop.containsEntry(stop, tripPattern)) { <END> patternsForStop.put(stop, tripPattern); } } }</code><technical_language>This conditional is necessary, a performance point of view. meaning clearer put() call conditional</technical_language>

Target:
private void addPatternToIndex(TripPattern tripPattern) { for (Stop stop: tripPattern.getStops()) { patternsForStop.put(stop, tripPattern); } }
Source:
<code>public static EndpointRegistry fromDTOtoEndpointRegistry(RegistryDTO registryDTO, String owner) { EndpointRegistry registry = new EndpointRegistry(); registry.setName(registryDTO.getName()); registry.setOwner(owner); registry.setType(registryDTO.getType().toString()); <START> registry.setMode(registryDTO.getType().toString()); <END> return registry; }</code><technical_language>38,39 lines same</technical_language>

Target:
public static EndpointRegistryInfo fromDTOtoEndpointRegistry(RegistryDTO registryDTO, String owner) { EndpointRegistryInfo registry = new EndpointRegistryInfo(); registry.setName(registryDTO.getName()); registry.setOwner(owner); registry.setType(registryDTO.getType().toString()); registry.setMode(registryDTO.getMode().toString()); return registry; }
Source:
<code>protected void executeCommand() { setActionReturnValue(getCurrentUser()); getReturnValue().setLoginResult(LoginResult.Autheticated); getReturnValue().setSessionId(engineSessionId); updateUserData(); ApplicationMode appMode = ApplicationMode.from(Config.<Integer> getValue(ConfigValues.ApplicationMode)); <START> SessionDataContainer.getInstance().setData("app_mode", appMode); <END> setSucceeded(true); }</code><technical_language>is point of putting application mode in session? read information simply read configuration</technical_language>

Target:
protected void executeCommand() { setActionReturnValue(getCurrentUser()); getReturnValue().setLoginResult(LoginResult.Autheticated); getReturnValue().setSessionId(engineSessionId); updateUserData(); setSucceeded(true); }
Source:
<code>public void t01_startDemoBulkWorkflow() { CreateWorkflowInstanceRequest req = new CreateWorkflowInstanceRequest(); req.type = DEMO_BULK_WORKFLOW_TYPE; req.stateVariables.put(BulkWorkflow.VAR_CONCURRENCY, 3); <START> List<Integer> childData = asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); <END> childrenCount = childData.size(); req.stateVariables.put(BulkWorkflow.VAR_CHILD_DATA, nflowObjectMapper().valueToTree(childData)); CreateWorkflowInstanceResponse resp = fromClient(workflowInstanceResource, true).put(req, CreateWorkflowInstanceResponse.class); assertThat(resp.id, notNullValue()); workflowId = resp.id; }</code><technical_language>If wanting express real count of children CHILD_COUNT constant, IntStream.rangeClosed(1, CHILD_COUNT).boxed().collect(toList())</technical_language>

Target:
public void t01_startDemoBulkWorkflow() { CreateWorkflowInstanceRequest req = new CreateWorkflowInstanceRequest(); req.type = DEMO_BULK_WORKFLOW_TYPE; req.stateVariables.put(BulkWorkflow.VAR_CONCURRENCY, 3); List<Integer> childData = IntStream.rangeClosed(1, CHILDREN_COUNT).boxed().collect(toList()); req.stateVariables.put(BulkWorkflow.VAR_CHILD_DATA, nflowObjectMapper().valueToTree(childData)); CreateWorkflowInstanceResponse resp = fromClient(workflowInstanceResource, true).put(req, CreateWorkflowInstanceResponse.class); assertThat(resp.id, notNullValue()); workflowId = resp.id; }
Source:
<code>public void cookie() throws Exception { final String name = "foo"; final String value = "bar"; final HttpServletResponse sresp = new HttpServletResponseFake( new RsEmpty() ); sresp.addCookie(new Cookie(name, value)); MatcherAssert.assertThat( "Can't add a cookie in servlet response", <START> sresp.getHeaders("Set-Cookie:"), <END> Matchers.hasItem( new FormattedText( "Set-Cookie: %s=%s;", name, value ).asString() ) ); }</code><technical_language>@fanifieiev put this in a constant</technical_language>

Target:
public void cookie() throws Exception { final String name = "foo"; final String value = "bar"; final HttpServletResponse sresp = new HttpServletResponseFake( new RsEmpty() ); sresp.addCookie(new Cookie(name, value)); MatcherAssert.assertThat( "Can't add a cookie in servlet response", sresp.getHeaders(HttpServletResponseFakeTest.SET_COOKIE), Matchers.hasItem( new FormattedText( "%s %s=%s;", HttpServletResponseFakeTest.SET_COOKIE, name, value ).asString() ) ); }
Source:
<code><START> private void putPreferred(String email) throws RestApiException, OrmException { List<EmailInfo> emails = getEmails.apply(rsrc); for (EmailInfo e : emails) { if (e.email.equals(email)) { putPreferred.apply(new AccountResource.Email(user, email), null); } } } <END></code><technical_language>swallow typo-case issue a warning? Delete email method matter, if a mail exist, is fine. rellies this command change something, spelled email wrong, fail, i think</technical_language>

Target:
private void putPreferred(String email) throws RestApiException, OrmException { putPreferred.apply(new AccountResource.Email(user, email), null); }
Source:
<code>private void addWorld() { this.getBuilder(Tags.Blocks.SLIMY_LOGS).add(WorldBlocks.congealed_green_slime.get(), WorldBlocks.congealed_blue_slime.get(), WorldBlocks.congealed_purple_slime.get(), WorldBlocks.congealed_blood_slime.get(), WorldBlocks.congealed_magma_slime.get()); for (SlimeGrassBlock.FoliageType type : SlimeGrassBlock.FoliageType.values()) { this.getBuilder(Tags.Blocks.SLIMY_LEAVES).add(WorldBlocks.slime_leaves.get(type)); this.getBuilder(Tags.Blocks.SLIMY_SAPLINGS).add(WorldBlocks.slime_sapling.get(type)); } <START> this.getBuilder(net.minecraftforge.common.Tags.Blocks.ORES).add(Tags.Blocks.ORES_COBALT, Tags.Blocks.ORES_ARDITE); <END> this.getBuilder(Tags.Blocks.ORES_COBALT).add(WorldBlocks.cobalt_ore.get()); this.getBuilder(Tags.Blocks.ORES_ARDITE).add(WorldBlocks.ardite_ore.get()); }</code><technical_language>In Ceramics, I [a helper](<LINK_0> get a list a EnumObject. a cleaner loops</technical_language>

Target:
private void addWorld() { this.getBuilder(Tags.Blocks.SLIMY_LOGS).add(WorldBlocks.congealed_slime.get(SlimeBlock.SlimeType.GREEN), WorldBlocks.congealed_slime.get(SlimeBlock.SlimeType.BLUE), WorldBlocks.congealed_slime.get(SlimeBlock.SlimeType.PURPLE), WorldBlocks.congealed_slime.get(SlimeBlock.SlimeType.BLOOD), WorldBlocks.congealed_slime.get(SlimeBlock.SlimeType.MAGMA)); for (SlimeGrassBlock.FoliageType type : SlimeGrassBlock.FoliageType.values()) { this.getBuilder(Tags.Blocks.SLIMY_LEAVES).add(WorldBlocks.slime_leaves.get(SlimeGrassBlock.FoliageType.BLUE), WorldBlocks.slime_leaves.get(SlimeGrassBlock.FoliageType.PURPLE), WorldBlocks.slime_leaves.get(SlimeGrassBlock.FoliageType.ORANGE)); this.getBuilder(Tags.Blocks.SLIMY_SAPLINGS).add(WorldBlocks.slime_sapling.get(type)); } this.getBuilder(net.minecraftforge.common.Tags.Blocks.ORES).add(Tags.Blocks.ORES_COBALT, Tags.Blocks.ORES_ARDITE); this.getBuilder(Tags.Blocks.ORES_COBALT).add(WorldBlocks.cobalt_ore.get()); this.getBuilder(Tags.Blocks.ORES_ARDITE).add(WorldBlocks.ardite_ore.get()); }
Source:
<code><START> protected Boolean getAutoCorrectFontMetrics() { <END> return false; }</code><technical_language>want allow <null> values, primitive boolean instead of java.lang.Boolean object</technical_language>

Target:
protected boolean getAutoCorrectFontMetrics() { return false; }
Source:
<code>private void finalizeMetadataChunk() { finalBlobProperties = new BlobProperties(getBlobSize(), passedInBlobProperties.getServiceId(), passedInBlobProperties.getOwnerId(), passedInBlobProperties.getContentType(), passedInBlobProperties.isPrivate(), passedInBlobProperties.getTimeToLiveInSeconds(), passedInBlobProperties.getCreationTimeInMs(), <START> passedInBlobProperties.getAccountId(), passedInBlobProperties.getContainerId(), false); <END> if (getNumDataChunks() > 1) { List<StoreKey> orderedChunkIdList = new ArrayList<>(indexToChunkIds.values()); buf = MetadataContentSerDe.serializeMetadataContent(routerConfig.routerMaxPutChunkSizeBytes, getBlobSize(), orderedChunkIdList); onFillComplete(false); } else { blobId = (BlobId) indexToChunkIds.get(0); state = ChunkState.Complete; operationCompleted = true; } }</code><technical_language>setting this false a correctness issue? GetBlobInfo relies returning BlobProperties of metadata chunk. this passedInBlobProperties.isEncrypted()</technical_language>

Target:
private void finalizeMetadataChunk() { finalBlobProperties = new BlobProperties(getBlobSize(), passedInBlobProperties.getServiceId(), passedInBlobProperties.getOwnerId(), passedInBlobProperties.getContentType(), passedInBlobProperties.isPrivate(), passedInBlobProperties.getTimeToLiveInSeconds(), passedInBlobProperties.getCreationTimeInMs(), passedInBlobProperties.getAccountId(), passedInBlobProperties.getContainerId(), passedInBlobProperties.isEncrypted()); if (getNumDataChunks() > 1) { List<StoreKey> orderedChunkIdList = new ArrayList<>(indexToChunkIds.values()); buf = MetadataContentSerDe.serializeMetadataContent(routerConfig.routerMaxPutChunkSizeBytes, getBlobSize(), orderedChunkIdList); onFillComplete(false); } else { blobId = (BlobId) indexToChunkIds.get(0); state = ChunkState.Complete; operationCompleted = true; } }
Source:
<code>void columnsTabToggle(final GuidedDecisionTableView.Presenter decisionTablePresenter) { <START> final boolean decisionTableIsEditable = !decisionTablePresenter.isReadOnly(); <END> final boolean decisionTableHasEditableColumns = decisionTablePresenter.hasEditableColumns(); if (!decisionTableIsEditable || !decisionTableHasEditableColumns) { disableColumnsPage(); } else { enableColumnsPage(); } }</code><technical_language>I this method work properly, please follow steps below: - Log UserA - Open Pricing loans table, append row / change some data - table opened unsaved changes UserA - Simultaneously in new private window log UserB - Open Pricing loans table, is locked UserA, is read Columns tab is enabled</technical_language>

Target:
void columnsTabToggle(final GuidedDecisionTableView.Presenter decisionTablePresenter) { columnsTabToggle(isGuidedDecisionTableEditable(decisionTablePresenter)); }
Source:
<code>protected org.ovirt.engine.core.common.businessentities.VM getVmPreview(Snapshot snapshot) { org.ovirt.engine.core.common.businessentities.VM vm = null; try { vm = getEntity(org.ovirt.engine.core.common.businessentities.VM.class, QueryType.GetVmConfigurationBySnapshot, new IdQueryParameters(asGuid(snapshot.getId())), null); } catch (WebFaultException wfe) { if (Response.Status.NOT_FOUND.getStatusCode() == wfe.getResponse().getStatus()) { <START> return null; <END> } } return vm; }</code><technical_language>I returning null is problematic NPE in BackendSnapshots - Disks/CdRoms/Nics - Resource, invoke this method reference returned VM. Also, I in place return a snapshot a VM configuration. In a case fail some 5** code omit problematic snapshot list, write a warning log. this case is rare (but possible) I ok omit bad snapshot write a log message it</technical_language>

Target:
protected org.ovirt.engine.core.common.businessentities.VM getVmPreview(Snapshot snapshot) { org.ovirt.engine.core.common.businessentities.VM vm = getEntity(org.ovirt.engine.core.common.businessentities.VM.class, QueryType.GetVmConfigurationBySnapshot, new IdQueryParameters(asGuid(snapshot.getId())), null); return vm; }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof FileAndName)) { return false; } FileAndName other = (FileAndName) obj; if (!NonNullUtils.equalsNullable(fTraceTypeId, other.fTraceTypeId)) { return false; } <START> return NonNullUtils.equalsNullable(fFile, other.fFile); <END> }</code><technical_language>check</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof FileAndName)) { return false; } FileAndName other = (FileAndName) obj; if (!equalsNullable(fTraceTypeId, other.fTraceTypeId)) { return false; } if (!equalsNullable(fFile, other.fFile)) { return false; } return true; }
Source:
<code>private void parsePath() { ImmutableList.Builder<SqlPathElement> builder = ImmutableList.builder(); <START> String[] schemas = rawPath.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); <END> for (String schema : schemas) { String catalogName; String schemaName; SqlPathElement element; String[] individual = schema.split("\\.(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); if (individual.length > 1) { catalogName = individual[0]; schemaName = individual[1]; element = new SqlPathElement(catalogName, schemaName); } else { element = new SqlPathElement(schema); } builder.add(element); } this.parsedPath = builder.build(); }</code><technical_language>If confirm special characters supported in catalog/schema names, simplify this this is hard understand</technical_language>

Target:
private void parsePath() { checkState(rawPath.isPresent(), "rawPath must be present to parse"); SqlParser parser = new SqlParser(); List<PathElement> pathSpecification = parser.createPathSpecification(rawPath.get()).getPath(); this.parsedPath = pathSpecification.stream() .map(pathElement -> new SqlPathElement(pathElement.getCatalog(), pathElement.getSchema())) .collect(toImmutableList()); }
Source:
<code>public void register(Class<? extends Converter<?>> converterClass) { Convert type = converterClass.getAnnotation(Convert.class); checkState(type != null, "The converter type %s should have the Convert annotation", converterClass.getName()); Class<? extends Converter<?>> other = findConverterType(type.value()); if (!other.equals(NullConverter.class)) { int priority = getConverterPriority(converterClass); int priorityOther = getConverterPriority(other); checkState(priority != priorityOther, "Converter %s have same priority than %s", converterClass, other); if (priority > priorityOther) { logger.debug("Overriding converter with because have more priority", other, converterClass); classes.remove(other); classes.add(converterClass); <START> } <END> } logger.debug("adding converter to {}", converterClass, type.value()); classes.add(converterClass); }</code><technical_language>rename other current, it, more clear overriding. log info warn converter override current one, user converter registered</technical_language>

Target:
public void register(Class<? extends Converter<?>> converterClass) { Convert type = converterClass.getAnnotation(Convert.class); checkState(type != null, "The converter type %s should have the Convert annotation", converterClass.getName()); Class<? extends Converter<?>> currentConverter = findConverterType(type.value()); if (!currentConverter.equals(NullConverter.class)) { int priority = getConverterPriority(converterClass); int priorityCurrent = getConverterPriority(currentConverter); checkState(priority != priorityCurrent, "Converter %s have same priority than %s", converterClass, currentConverter); if (priority > priorityCurrent) { logger.debug("Overriding converter with because have more priority", currentConverter, converterClass); classes.remove(currentConverter); classes.add(converterClass); } else { logger.debug("Converter not registered because have less priority than {}", converterClass, currentConverter); } } logger.debug("adding converter to {}", converterClass, type.value()); classes.add(converterClass); }
Source:
<code>private EmptyActionInput() { <START> execPath = null; <END> }</code><technical_language>Instead of setting field null handling case in of methods, easier a private class for empty marker singleton</technical_language>

Target:
private EmptyActionInput()
Source:
<code>public void testGetInstructorAccounts() throws Exception { <START> int numOfInstructors = 4; <END> createNewAccount(); List<AccountAttributes> instructorAccountsExpected = createInstructorAccounts(numOfInstructors); List<AccountAttributes> instructorAccountsActual = accountsDb.getInstructorAccounts(); assertEquals(numOfInstructors, instructorAccountsActual.size()); for (int i = 0; i < numOfInstructors; i++) { instructorAccountsExpected.get(i).createdAt = null; instructorAccountsExpected.get(i).studentProfile.modifiedDate = null; instructorAccountsActual.get(i).createdAt = null; instructorAccountsActual.get(i).studentProfile.modifiedDate = null; } AssertHelper.assertSameContentIgnoreOrder(instructorAccountsExpected, instructorAccountsActual); deleteInstructorAccounts(numOfInstructors); }</code><technical_language>do need change this</technical_language>

Target:
public void testGetInstructorAccounts() throws Exception { int numOfInstructors = 3; createNewAccount(); List<AccountAttributes> instructorAccountsExpected = createInstructorAccounts(numOfInstructors); List<AccountAttributes> instructorAccountsActual = accountsDb.getInstructorAccounts(); assertEquals(numOfInstructors, instructorAccountsActual.size()); for (int i = 0; i < numOfInstructors; i++) { instructorAccountsExpected.get(i).createdAt = null; instructorAccountsExpected.get(i).studentProfile.modifiedDate = null; instructorAccountsActual.get(i).createdAt = null; instructorAccountsActual.get(i).studentProfile.modifiedDate = null; } AssertHelper.assertSameContentIgnoreOrder(instructorAccountsExpected, instructorAccountsActual); deleteInstructorAccounts(numOfInstructors); }
Source:
<code>public List<Action> getActions() { <START> List<Action> actions = new Vector<>(super.getActions()); <END> actions.addAll(transientActions); return Collections.unmodifiableList(actions); }</code><technical_language>suggestion List<Action> actions = new Vector<>(getPersistedActions()); for clarity</technical_language>

Target:
public List<Action> getActions() { List<Action> actions = new Vector<>(getPersistedActions()); actions.addAll(transientActions); return Collections.unmodifiableList(actions); }
Source:
<code>public @Nonnull String filter(@Nonnull String input) { ContentMappings mappings = ContentMappings.get(); String filtered = input; List<String> searchList = new ArrayList<>(); List<String> replacementList = new ArrayList<>(); for (ContentMapping mapping : mappings) { searchList.add(mapping.getOriginal()); replacementList.add(mapping.getReplacement()); } if (!searchList.isEmpty()) { <START> filtered = StringUtils.replaceEach(input, searchList.toArray(new String[]{}), replacementList.toArray(new String[]{})); <END> } return filtered; }</code><technical_language>fix other array usage</technical_language>

Target:
public @Nonnull String filter(@Nonnull String input) { ContentMappings mappings = ContentMappings.get(); String filtered = input; List<String> searchList = new ArrayList<>(); List<String> replacementList = new ArrayList<>(); for (ContentMapping mapping : mappings) { searchList.add(mapping.getOriginal()); replacementList.add(mapping.getReplacement()); } if (!searchList.isEmpty()) { filtered = StringUtils.replaceEach(input, searchList.toArray(new String[0]), replacementList.toArray(new String[0])); } return filtered; }
Source:
<code>public Task createInstance(TaskDefinition taskDefinition) throws SchedulerException { try { Class<?> taskClass = OpenmrsClassLoader.getInstance().loadClass(taskDefinition.getTaskClass()); Task task = new TaskThreadedInitializationWrapper((Task) taskClass.newInstance()); log.debug("initializing {}", taskClass.getName()); <START> <END> task.initialize(taskDefinition); return task; } catch (ClassNotFoundException cnfe) { log.error("OpenmrsClassLoader could not load class: {}. Probably due to a module not being loaded", taskDefinition.getTaskClass()); log.debug("Full error trace of ClassNotFoundException {}", cnfe); throw new SchedulerException("could not load class", cnfe); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Error creating new task for class " + taskDefinition.getTaskClass(), e); } throw new SchedulerException("error creating new task for class " + taskDefinition.getTaskClass(), e); } }</code><technical_language>add this whitespace! remove it</technical_language>

Target:
public Task createInstance(TaskDefinition taskDefinition) throws SchedulerException { try { Class<?> taskClass = OpenmrsClassLoader.getInstance().loadClass(taskDefinition.getTaskClass()); Task task = new TaskThreadedInitializationWrapper((Task) taskClass.newInstance()); log.debug("initializing {}", taskClass.getName()); task.initialize(taskDefinition); return task; } catch (ClassNotFoundException cnfe) { log.error("OpenmrsClassLoader could not load class: {}. Probably due to a module not being loaded", taskDefinition.getTaskClass()); log.debug("Full error trace of ClassNotFoundException", cnfe); throw new SchedulerException("could not load class", cnfe); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Error creating new task for class " + taskDefinition.getTaskClass(), e); } throw new SchedulerException("error creating new task for class " + taskDefinition.getTaskClass(), e); } }
Source:
<code>public boolean execute(final IDebugCommandRequest request) { if (request.getElements().length == 0) { request.done(); return false; } getContainerDMContexts(request.getElements(), new DataRequestMonitor<IContainerDMContext[]>(fExecutor, null) { @Override protected void handleCompleted() { if (!isSuccess()) { request.setStatus(getStatus()); request.done(); } <START> else if (getData().length == 0){ <END> request.done(); } else { disconnect(getData(), new ImmediateRequestMonitor() { @Override protected void handleCompleted() { if (!isSuccess()) { request.setStatus(getStatus()); request.done(); } else { waitForTermination(request); } } }); } } }); return false; }</code><technical_language>canExecute() check for this case relies canDisconnect(getData()...) decision. consistent do delegate case disconnect(). actually, disconnect() checks for empty array, need remove if check</technical_language>

Target:
public boolean execute(final IDebugCommandRequest request) { if (request.getElements().length == 0) { request.done(); return false; } getContainerDMContexts(request.getElements(), new DataRequestMonitor<IContainerDMContext[]>(fExecutor, null) { @Override protected void handleCompleted() { if (!isSuccess()) { request.setStatus(getStatus()); request.done(); } else { disconnect(getData(), new ImmediateRequestMonitor() { @Override protected void handleCompleted() { if (!isSuccess()) { request.setStatus(getStatus()); request.done(); } else { waitForTermination(request); } } }); } } }); return false; }
Source:
<code>public void fluent_http() throws Exception { File litsDifferencesFile = FileLocation.of("target/differences").getFile(); File pomFile = FileLocation.of("../sources/fluent-http/pom.xml").getFile(); MavenBuild mavenBuild = MavenBuild.create().setPom(pomFile).setCleanPackageSonarGoals().addArgument("-DskipTests") .setProfile("rules") .setProperty("sonar.cpd.skip", "true") .setProperty("sonar.skipPackageDesign", "true") .setProperty("sonar.analysis.mode", "preview") .setProperty("sonar.issuesReport.html.enable", "true") .setProperty("dump.old", FileLocation.of("src/test/resources/fluent-http").getFile().getAbsolutePath()) .setProperty("dump.new", FileLocation.of("target/actual/fluent-http").getFile().getAbsolutePath()) .setProperty("lits.differences", litsDifferencesFile.getAbsolutePath()); <START> orchestrator.executeBuild(mavenBuild); <END> assertThat(Files.toString(litsDifferencesFile, StandardCharsets.UTF_8)).isEmpty(); }</code><technical_language>construction of mavenBuild object is for 4 new projects. factorized</technical_language>

Target:
public void fluent_http() throws Exception { test_project("fluent-http"); }
Source:
<code>protected TransactionalEditingDomain getTableEditingDomain() { ServicesRegistry registry = null; <START> if(null != getTableManager().getTable().eResource()){ <END> try { registry = ServiceUtilsForEObject.getInstance().getServiceRegistry(getTableManager().getTable()); return registry.getService(TransactionalEditingDomain.class); } catch (final ServiceException e) { Activator.log.error(Messages.NattableModelManager_ServiceRegistryNotFound, e); } } return null; }</code><technical_language>is a high potential of NPE concatenated calls</technical_language>

Target:
protected TransactionalEditingDomain getTableEditingDomain() { ServicesRegistry registry = null; if(null != getTableManager() && null != getTableManager().getTable() && null != getTableManager().getTable().eResource()){ try { registry = ServiceUtilsForEObject.getInstance().getServiceRegistry(getTableManager().getTable()); return registry.getService(TransactionalEditingDomain.class); } catch (final ServiceException e) { Activator.log.error(Messages.NattableModelManager_ServiceRegistryNotFound, e); } } return null; }
Source:
<code>public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map<String, byte[]> customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, EnumSet.noneOf(WriteFlag.class)) <START> .initiateAdv((long)(-1)); <END> } finally { closeLock.readLock().unlock(); } }</code><technical_language>touching this line, change (long)(-1) -1L</technical_language>

Target:
public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map<String, byte[]> customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, EnumSet.noneOf(WriteFlag.class)) .initiateAdv(-1L); } finally { closeLock.readLock().unlock(); } }
Source:
<code>public static void main(String[] args) throws InterruptedException { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder() .connectionString(connectionString) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName("<<queue-name>>") .buildAsyncClient(); Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptSession("greetings-id"); Disposable subscription = receiverMono.flatMapMany(receiver -> receiver.receiveMessages()) <START> .subscribe(message -> { <END> System.out.printf("Session: %s. Sequence #: %s. Contents: %s%n", message.getSessionId(), message.getSequenceNumber(), message.getBody()); }, error -> System.err.println("Error occurred: " + error)); TimeUnit.SECONDS.sleep(10); subscription.dispose(); sessionReceiver.close(); }</code><technical_language>this receiver close() , builder close connection</technical_language>

Target:
public static void main(String[] args) throws InterruptedException { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder() .connectionString(connectionString) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName("<<queue-name>>") .buildAsyncClient(); Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptSession("greetings-id"); Disposable subscription = Flux.usingWhen(receiverMono, receiver -> receiver.receiveMessages(), receiver -> Mono.fromRunnable(() -> receiver.close())) .subscribe(message -> { System.out.printf("Session: %s. Sequence #: %s. Contents: %s%n", message.getSessionId(), message.getSequenceNumber(), message.getBody()); }, error -> System.err.println("Error occurred: " + error)); TimeUnit.SECONDS.sleep(10); subscription.dispose(); sessionReceiver.close(); }
Source:
<code>private int getEventAttributeLocation(InputMappingAttribute inputMappingAttribute, StreamDefinition streamDefinition) { int attributeLocation = 0; if (EventReceiverUtil.isMetaAttribute(inputMappingAttribute.getToElementKey())) { for (Attribute metaAttribute : streamDefinition.getMetaData()) { if ((EventReceiverConstants.META_DATA_PREFIX).concat(metaAttribute.getName()).equals(inputMappingAttribute.getToElementKey())) { return attributeLocation; } attributeLocation++; } } else if (EventReceiverUtil.isCorrelationAttribute(inputMappingAttribute.getToElementKey())) { for (Attribute correlationData : streamDefinition.getCorrelationData()) { if (EventReceiverConstants.CORRELATION_DATA_PREFIX.concat(correlationData.getName()).equals(inputMappingAttribute.getToElementKey())) { if (streamDefinition.getMetaData() != null) { attributeLocation += streamDefinition.getMetaData().size(); } <START> return attributeLocation; <END> } attributeLocation++; } } else { for (Attribute payloadData : streamDefinition.getPayloadData()) { if (payloadData.getName().equals(inputMappingAttribute.getToElementKey())) { if (streamDefinition.getMetaData() != null) { attributeLocation += streamDefinition.getMetaData().size(); } if (streamDefinition.getCorrelationData() != null) { attributeLocation += streamDefinition.getCorrelationData().size(); } return attributeLocation; } attributeLocation++; } } return -1; }</code><technical_language>@grainier get meta data size calculation out of for loop if condition retrieval of meta data size repeat for iteration? i.e. of loop, do metaSize = streamDefinition.getMetaData() == null ? 0: streamDefinition.getMetaData().size(), loop, simply do a return attributeLocation + metaSize;. However, this code in critical path, do if optimization compromise readability. WDYT</technical_language>

Target:
private int getEventAttributeLocation(InputMappingAttribute inputMappingAttribute, StreamDefinition streamDefinition) { int attributeLocation = 0; int metaSize = streamDefinition.getMetaData() != null ? streamDefinition.getMetaData().size() : 0; int correlationSize = streamDefinition.getCorrelationData() != null ? streamDefinition.getCorrelationData().size() : 0; if (EventReceiverUtil.isMetaAttribute(inputMappingAttribute.getToElementKey())) { for (Attribute metaAttribute : streamDefinition.getMetaData()) { if ((EventReceiverConstants.META_DATA_PREFIX).concat(metaAttribute.getName()).equals(inputMappingAttribute.getToElementKey())) { return attributeLocation; } attributeLocation++; } } else if (EventReceiverUtil.isCorrelationAttribute(inputMappingAttribute.getToElementKey())) { for (Attribute correlationData : streamDefinition.getCorrelationData()) { if (EventReceiverConstants.CORRELATION_DATA_PREFIX.concat(correlationData.getName()).equals(inputMappingAttribute.getToElementKey())) { return attributeLocation + metaSize; } attributeLocation++; } } else { for (Attribute payloadData : streamDefinition.getPayloadData()) { if (payloadData.getName().equals(inputMappingAttribute.getToElementKey())) { return attributeLocation + metaSize + correlationSize; } attributeLocation++; } } return -1; }
Source:
<code>public void removeChangeListeners() { SharedRealm sharedRealm = getSharedRealm(looperThread.realmConfiguration); Integer dummyObserver = 1; looperThread.keepStrongReference.add(dummyObserver); sharedRealm.realmNotifier.addChangeListener(dummyObserver, new RealmChangeListener<Integer>() { @Override public void onChange(Integer dummy) { fail(); } }); sharedRealm.realmNotifier.addChangeListener(sharedRealm, new RealmChangeListener<SharedRealm>() { @Override public void onChange(SharedRealm sharedRealm) { looperThread.testComplete(); } }); sharedRealm.realmNotifier.removeChangeListeners(dummyObserver); <START> new Thread(new Runnable() { <END> @Override public void run() { SharedRealm sharedRealm = getSharedRealm(looperThread.realmConfiguration); sharedRealm.beginTransaction(); sharedRealm.commitTransaction(); sharedRealm.close(); } }).start(); }</code><technical_language>call makeRemoteChanges</technical_language>

Target:
public void removeChangeListeners() { SharedRealm sharedRealm = getSharedRealm(looperThread.realmConfiguration); Integer dummyObserver = 1; looperThread.keepStrongReference.add(dummyObserver); sharedRealm.realmNotifier.addChangeListener(dummyObserver, new RealmChangeListener<Integer>() { @Override public void onChange(Integer dummy) { fail(); } }); sharedRealm.realmNotifier.addChangeListener(sharedRealm, new RealmChangeListener<SharedRealm>() { @Override public void onChange(SharedRealm sharedRealm) { looperThread.testComplete(); } }); sharedRealm.realmNotifier.removeChangeListeners(dummyObserver); makeRemoteChanges(looperThread.realmConfiguration); }
Source:
<code>public void findEncounter_shouldThrowIllegalArgumentExceptionIfGivenVisitIsNull() throws Exception { EncounterParameters encounterParameters = EncounterParameters.instance() .setEncounterType(radiologyProperties.getRadiologyOrderEncounterType()) .setEncounterUuid(VOIDED_ENCOUNTER_UUID); <START> Visit visit = null; <END> expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("visit is required"); radiologyEncounterMatcher.findEncounter(visit, encounterParameters); }</code><technical_language>@bgeVam inline null</technical_language>

Target:
public void findEncounter_shouldThrowIllegalArgumentExceptionIfGivenVisitIsNull() throws Exception { EncounterParameters encounterParameters = EncounterParameters.instance() .setEncounterType(radiologyProperties.getRadiologyOrderEncounterType()) .setEncounterUuid(VOIDED_ENCOUNTER_UUID); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("visit is required"); radiologyEncounterMatcher.findEncounter(null, encounterParameters); }
Source:
<code>private <START> void scanGuiceModules(Set<Class<?>> <END> scriptClasses) throws IOException { try { Class<?> sysModuleBaseClass = Module.class; Class<?> httpModuleBaseClass = Class.forName("com.google.inject.servlet.ServletModule"); Class<?> sshModuleBaseClass = Class.forName("com.google.gerrit.sshd.CommandModule"); for (Class<?> scriptClass : scriptClasses) { if (sshModuleBaseClass.isAssignableFrom(scriptClass)) { sshModule = ((Class<? extends Module>) scriptClass); } else if (httpModuleBaseClass.isAssignableFrom(scriptClass)) { httpModule = ((Class<? extends Module>) scriptClass); } else if (sysModuleBaseClass.isAssignableFrom(scriptClass)) { sysModule = ((Class<? extends Module>) scriptClass); } } } catch (ClassNotFoundException e) { throw new IOException( "Cannot find base Gerrit classes for Guice Plugin Modules", e); } }</code><technical_language>more functional return a data structure contains module classes if remove module fields this object completely stateless. This is idea</technical_language>

Target:
private void scanGuiceModules(Set<Class<?>> scriptClasses) throws IOException { try { Class<?> sysModuleBaseClass = Module.class; Class<?> httpModuleBaseClass = Class.forName("com.google.inject.servlet.ServletModule"); Class<?> sshModuleBaseClass = Class.forName("com.google.gerrit.sshd.CommandModule"); for (Class<?> scriptClass : scriptClasses) { String scriptClassName = scriptClass.getName(); if (sshModuleBaseClass.isAssignableFrom(scriptClass)) { sshModuleClassName = scriptClassName; } else if (httpModuleBaseClass.isAssignableFrom(scriptClass)) { httpModuleClassName = scriptClassName;; } else if (sysModuleBaseClass.isAssignableFrom(scriptClass)) { sysModuleClassName = scriptClassName;; } } } catch (ClassNotFoundException e) { throw new IOException( "Cannot find base Gerrit classes for Guice Plugin Modules", e); } }
Source:
<code>public static void testGetCentresByBranch() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); OrganizationService organizationService = MambuAPIFactory.getOrganizationService(); String branchId = BRANCH_ID; String offset = "0"; String limit = "500"; System.out.println( <START> "\nIn testGetCentresByBranch" + " BranchID=" + branchId + " Offset=" + offset + " Limit=" + limit); <END> Date d1 = new Date(); List<Centre> centres = organizationService.getCentres(branchId, offset, limit); Date d2 = new Date(); long diff = d2.getTime() - d1.getTime(); System.out.println("Total Centres=" + centres.size() + " for branch=" + branchId + ". Total time=" + diff); for (Centre centre : centres) { System.out.println(" Name=" + centre.getName() + "\tId=" + centre.getId()); } System.out.println(); }</code><technical_language>nice new logging approach of tests. I here. do think</technical_language>

Target:
public static void testGetCentresByBranch() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); OrganizationService organizationService = MambuAPIFactory.getOrganizationService(); String branchId = BRANCH_ID; String offset = "0"; String limit = "500"; System.out.println("\nIn " + methodName + " BranchID=" + branchId + " Offset=" + offset + " Limit=" + limit); Date d1 = new Date(); List<Centre> centres = organizationService.getCentres(branchId, offset, limit); Date d2 = new Date(); long diff = d2.getTime() - d1.getTime(); System.out.println("Total Centres=" + centres.size() + " for branch=" + branchId + ". Total time=" + diff); for (Centre centre : centres) { System.out.println(" Name=" + centre.getName() + "\tId=" + centre.getId()); } System.out.println(); }
Source:
<code>public void checkEntryPermissions(final Optional<User> user, final Entry<? extends Entry, ? extends Version> entry) { if (!entry.getIsPublished()) { if (user.isEmpty()) { <START> throw new CustomWebApplicationException("This entry is not published.", HttpStatus.SC_UNAUTHORIZED); <END> } checkUser(user.get(), entry); } }</code><technical_language>I return a 404 in this case. If a private GitHub repo permissions to, get a 404, unauthorized error. logic this is want exists evil-doer. If exists, step. start break it. others opine this</technical_language>

Target:
public void checkEntryPermissions(final Optional<User> user, final Entry<? extends Entry, ? extends Version> entry) { if (!entry.getIsPublished()) { if (user.isEmpty()) { throw new CustomWebApplicationException("This entry is not published.", HttpStatus.SC_NOT_FOUND); } checkUser(user.get(), entry); } }