auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static PublicKey FromBytes(byte[] key) { <START> Preconditions.checkArgument(key != null); <END> Preconditions.checkArgument(key.length == PUBLIC_KEY_SIZE); return new PublicKey(JNI.PublicKey_FromBytes(key), true); }</code><technical_language>In order more consistent, _Preconditions.checkNotNull(key );_ method instead</technical_language>

Target:
public static PublicKey FromBytes(byte[] key) { Preconditions.checkNotNull(key); Preconditions.checkArgument(key.length == PUBLIC_KEY_SIZE); return new PublicKey(JNI.PublicKey_FromBytes(key), true); }
Source:
<code><START> if (fsa == null) { <END> fsa = new FSAccessJava(); }</code><technical_language>Style-nit: Braces necessary here</technical_language>

Target:
if (fsa == null) fsa = new FSAccessJava(); INSTANCE = fsa; } public static final Throwable getNativeImplementationLoadException() { return nativeLoadError; }
Source:
<code>public PaymentRequestEntity build() { PaymentRequestEntity entity = new PaymentRequestEntity(); <START> entity.setId(this.id); <END> entity.setReturnUrl(this.returnUrl); entity.setReference(this.reference); entity.setGatewayAccount(this.gatewayAccountEntity); entity.setExternalId(this.externalId); entity.setDescription(this.description); entity.setCreatedDate(this.createdDate); entity.setAmount(this.amount); return entity; }</code><technical_language>do want set this in fixture auto-generated value</technical_language>

Target:
public PaymentRequestEntity build() { PaymentRequestEntity entity = new PaymentRequestEntity(); entity.setReturnUrl(this.returnUrl); entity.setReference(this.reference); entity.setGatewayAccount(this.gatewayAccountEntity); entity.setExternalId(this.externalId); entity.setDescription(this.description); entity.setCreatedDate(this.createdDate); entity.setAmount(this.amount); return entity; }
Source:
<code>public void testCreate() throws Exception { server.enqueue(jsonResponse("/createvirtualmachineresponse.json")); String id = "/subscriptions/SUBSCRIPTIONID/" + "resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine"; final VirtualMachineApi vmAPI = api.getVirtualMachineApi("groupname"); VirtualMachine vm = vmAPI.create("windowsmachine", id, "windowsmachine", "westus", getProperties()); assertEquals(vm, getVM()); assertSent(server, "PUT", "/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute" + <START> "/virtualMachines/windowsmachine?api-version=2015-06-15&validating=false"); <END> }</code><technical_language>generated body needs verified</technical_language>

Target:
public void testCreate() throws Exception { server.enqueue(jsonResponse("/createvirtualmachineresponse.json")); final VirtualMachineApi vmAPI = api.getVirtualMachineApi("groupname"); VirtualMachine vm = vmAPI.create("windowsmachine", "westus", getProperties()); assertEquals(vm, getVM()); assertSent(server, "PUT", "/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute" + "/virtualMachines/windowsmachine?api-version=2015-06-15&validating=false", "{\"location\":\"westus\",\"properties\":" + "{\"vmId\":\"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\"," + "\"hardwareProfile\":{\"vmSize\":\"Standard_D1\"}," + "\"storageProfile\":{\"imageReference\":{\"publisher\":\"publisher\",\"offer\":\"offer\",\"sku\":\"sku\",\"version\":\"ver\"}," + "\"osDisk\":{\"osType\":\"Windows\",\"name\":\"windowsmachine\"," + "\"vhd\":{\"uri\":\"<LINK_0>\"},\"caching\":\"ReadWrite\",\"createOption\":\"FromImage\"},\"dataDisks\":[]}," + "\"osProfile\":{\"computerName\":\"windowsmachine\",\"adminUsername\":\"azureuser\",\"windowsConfiguration\":{\"provisionVMAgent\":false,\"enableAutomaticUpdates\":true}}," + "\"networkProfile\":{\"networkInterfaces\":[{\"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"}]}," + "\"diagnosticsProfile\":{\"bootDiagnostics\":{\"enabled\":true,\"storageUri\":\"<LINK_1>\"}},\"provisioningState\":\"Creating\"}}"); }
Source:
<code>private void cancelAutomaticTransitionToHalfOpen() { if (transitionToHalfOpenFuture != null) { <START> transitionToHalfOpenFuture.cancel(true); <END> } }</code><technical_language>if future is completed</technical_language>

Target:
private void cancelAutomaticTransitionToHalfOpen() { if (transitionToHalfOpenFuture != null && !transitionToHalfOpenFuture.isDone()) { transitionToHalfOpenFuture.cancel(true); } }
Source:
<code>public void addTopic(boolean internal, String name, List<TopicPartitionInfo> partitions, Map<String, String> configs) { if (allTopics.containsKey(name)) { throw new IllegalArgumentException(String.format("Topic %s was already added.", name)); } List<Node> replicas = null; for (TopicPartitionInfo partition : partitions) { if (!brokers.contains(partition.leader())) { throw new IllegalArgumentException("Leader broker unknown"); } if (!brokers.containsAll(partition.replicas())) { throw new IllegalArgumentException("Unknown brokers in replica list"); } if (!brokers.containsAll(partition.isr())) { throw new IllegalArgumentException("Unknown brokers in isr list"); } } <START> allTopics.put(name, new TopicMetadata(internal, partitions, configs)); <END> }</code><technical_language>is this</technical_language>

Target:
public void addTopic(boolean internal, String name, List<TopicPartitionInfo> partitions, Map<String, String> configs) { if (allTopics.containsKey(name)) { throw new IllegalArgumentException(String.format("Topic %s was already added.", name)); } List<Node> replicas = null; for (TopicPartitionInfo partition : partitions) { if (!brokers.contains(partition.leader())) { throw new IllegalArgumentException("Leader broker unknown"); } if (!brokers.containsAll(partition.replicas())) { throw new IllegalArgumentException("Unknown brokers in replica list"); } if (!brokers.containsAll(partition.isr())) { throw new IllegalArgumentException("Unknown brokers in isr list"); } if (replicas == null) { replicas = partition.replicas(); } else if (!replicas.equals(partition.replicas())) { throw new IllegalArgumentException("All partitions need to have the same replica nodes."); } } allTopics.put(name, new TopicMetadata(internal, partitions, configs)); }
Source:
<code><START> public boolean determineApplyLimitPushDown() <END> { final boolean forceLimitPushDown = validateAndGetForceLimitPushDown(); if (limitSpec instanceof DefaultLimitSpec) { DefaultLimitSpec defaultLimitSpec = (DefaultLimitSpec) limitSpec; if (defaultLimitSpec.getLimit() == Integer.MAX_VALUE) { return false; } if (forceLimitPushDown) { return true; } boolean sortHasNonGroupingFields = DefaultLimitSpec.sortingOrderHasNonGroupingFields( limitSpec, getDimensions() ); return !sortHasNonGroupingFields; } return false; }</code><technical_language>i this implemented in line return validateAndGetForceLimitPushDown() || DefaultLimitSpec.sortingOrderHasNonGroupingFields(..); add defaultLimitSpec.getLimit() == Integer.MAX_VALUE check DefaultLimitSpec.sortingOrderHasNonGroupingFields(..)</technical_language>

Target:
public boolean determineApplyLimitPushDown() { final boolean forceLimitPushDown = validateAndGetForceLimitPushDown(); if (limitSpec instanceof DefaultLimitSpec) { DefaultLimitSpec defaultLimitSpec = (DefaultLimitSpec) limitSpec; if (defaultLimitSpec.getLimit() == Integer.MAX_VALUE) { return false; } if (forceLimitPushDown) { return true; } boolean sortHasNonGroupingFields = DefaultLimitSpec.sortingOrderHasNonGroupingFields( (DefaultLimitSpec) limitSpec, getDimensions() ); return !sortHasNonGroupingFields; } return false; }
Source:
<code>void onAdd(InventoryScreen inventoryScreen) { inventoryScreen.setInteractText("---"); <START> inventoryScreen.getInteractButton().setAction(uiElement -> { <END> }); inventoryScreen.getInteractButton().setEnabled(false); }</code><technical_language>reason empty callback? If incomplete of yet, I recommend removing this, adding // TODO: Set callback</technical_language>

Target:
void onAdd(InventoryScreen inventoryScreen) { inventoryScreen.setInteractText("---"); inventoryScreen.getInteractButton().setEnabled(false); }
Source:
<code>public List<F> filterFiles(F[] files) { if (files.length < 2) { return Collections.emptyList(); } <START> final Set<String> candidates = Arrays.asList(files).stream() <END> .map(f -> getFilename(f)) .collect(Collectors.toSet()); List<F> results = new ArrayList<>(); for (F file : files) { if (this.filtersAndFunctions.entrySet().stream().anyMatch(entry -> { F[] fileToCheck = (F[]) Array.newInstance(file.getClass(), 1); fileToCheck[0] = file; if (entry.getKey().filterFiles(fileToCheck).size() > 0) { String markerName = entry.getValue().apply(getFilename(file)); return markerName != null && candidates.contains(markerName); } return false; })) { results.add(file); } } return results; }</code><technical_language>![image](<LINK_0></technical_language>

Target:
public List<F> filterFiles(F[] files) { if (files.length < 2) { return Collections.emptyList(); } final Set<String> candidates = Arrays.stream(files) .map(this::getFilename) .collect(Collectors.toSet()); List<F> results = new ArrayList<>(); for (F file : files) { boolean anyMatch = this.filtersAndFunctions.entrySet().stream().anyMatch(entry -> { F[] fileToCheck = (F[]) Array.newInstance(file.getClass(), 1); fileToCheck[0] = file; if (entry.getKey().filterFiles(fileToCheck).size() > 0) { String markerName = entry.getValue().apply(getFilename(file)); return markerName != null && candidates.contains(markerName); } return false; }); if (anyMatch) { results.add(file); } } return results; }
Source:
<code>public void consume(MentionsData data) throws XWikiException { try { DocumentReference author = this.documentReferenceResolver.resolve(data.getAuthorReference()); this.initContext(author, data.getWikiId()); DocumentReference dr = this.documentReferenceResolver.resolve(data.getDocumentReference()); XWikiDocument doc = this.documentRevisionProvider.getRevision(dr, data.getVersion()); if (doc != null) { Syntax syntax = doc.getSyntax(); XWikiDocument oldDoc; if (doc.getPreviousVersion() != null) { oldDoc = this.documentRevisionProvider.getRevision(dr, doc.getPreviousVersion()); } else { oldDoc = null; } DocumentReference documentReference = doc.getDocumentReference(); DocumentReference authorReference = doc.getAuthorReference(); <START> if (oldDoc == null) { <END> handleOnCreate(doc.getXDOM(), documentReference, authorReference, MentionLocation.DOCUMENT); traverseXObjectsOnCreate(doc.getXObjects(), documentReference, authorReference, syntax); } else { handleOnUpdate(oldDoc.getXDOM(), doc.getXDOM(), documentReference, authorReference, MentionLocation.DOCUMENT); traverseXObjectsOnUpdate(oldDoc.getXObjects(), doc.getXObjects(), documentReference, authorReference, syntax); } } } catch (ExecutionContextException e) { this.logger.warn("Failed to initalize the context of the mention update runnable. Cause [{}]", getRootCauseMessage(e)); } finally { this.execution.removeContext(); } }</code><technical_language>this IF mergeable previous IF, no</technical_language>

Target:
public void consume(MentionsData data) throws XWikiException { try { DocumentReference author = this.documentReferenceResolver.resolve(data.getAuthorReference()); this.initContext(author, data.getWikiId()); DocumentReference dr = this.documentReferenceResolver.resolve(data.getDocumentReference()); XWikiDocument doc = this.documentRevisionProvider.getRevision(dr, data.getVersion()); if (doc != null) { Syntax syntax = doc.getSyntax(); DocumentReference documentReference = doc.getDocumentReference(); DocumentReference authorReference = doc.getAuthorReference(); if (doc.getPreviousVersion() == null) { handleOnCreate(doc.getXDOM(), documentReference, authorReference, DOCUMENT); traverseXObjectsOnCreate(doc.getXObjects(), documentReference, authorReference, syntax); } else { XWikiDocument oldDoc = this.documentRevisionProvider.getRevision(dr, doc.getPreviousVersion()); handleOnUpdate(oldDoc.getXDOM(), doc.getXDOM(), documentReference, authorReference, DOCUMENT); traverseXObjectsOnUpdate(oldDoc.getXObjects(), doc.getXObjects(), documentReference, authorReference, syntax); } } } catch (ExecutionContextException e) { this.logger.warn("Failed to initalize the context of the mention update runnable. Cause [{}]", getRootCauseMessage(e)); } finally { this.execution.removeContext(); } }
Source:
<code>public DaemonReloadPage open() { m_driver.get(baseURI + "opennms/admin/daemons/index.jsp"); <START> new WebDriverWait(m_driver, 5).until((Predicate<WebDriver>) (driver) -> getDaemonRows().size() == expectedDaemonCount); <END> return this; }</code><technical_language>This manually verified invoking open() instead of here. expectedDaemonCount a parameter, API strange use</technical_language>

Target:
public DaemonReloadPage open() { m_driver.get(getBaseUrl() + "opennms/admin/daemons/index.jsp"); return this; }
Source:
<code>boolean isCountryMatch(ChatChannelUser chatUser) { <START> var fieldValue = countryFilterField.getEditor().getText(); <END> if(fieldValue.isEmpty()) return true; Optional<Player> playerOptional = chatUser.getPlayer(); if(!playerOptional.isPresent()) return false; Player player = playerOptional.get(); var country = player.getCountry(); return country.toLowerCase().startsWith(fieldValue.toLowerCase()); }</code><technical_language>avoid var for code style reasons</technical_language>

Target:
boolean isCountryMatch(ChatChannelUser chatUser) { Optional<Player> playerOptional = chatUser.getPlayer(); if (!playerOptional.isPresent()) { return false; } String country = playerOptional.get().getCountry(); return currentSelectedCountries.contains(country); }
Source:
<code>private String buildQueryString(Operator op, List<String> predicateValues) { switch (op) { case IN_INSENSITIVE: case IN: { return predicateValues.stream() .map((str) -> "\"" + str + "\"") .collect(Collectors.joining(" | ")); } <START> case NOT_INSENSITIVE: <END> case NOT: { return predicateValues.stream() .map((str) -> "-\"" + str + "\"") .collect(Collectors.joining(" + ")); } case INFIX_CASE_INSENSITIVE: case PREFIX_CASE_INSENSITIVE: case PREFIX: case INFIX: { return predicateValues.stream() .map((str) -> str + "*") .collect(Collectors.joining(" | ")); } default: throw new IllegalArgumentException("Unsupported Predicate Operator: " + op); } }</code><technical_language>support fuzzy operator operator for phrase queries</technical_language>

Target:
private String buildQueryString(Operator op, List<String> predicateValues) { switch (op) { case INFIX_CASE_INSENSITIVE: case PREFIX_CASE_INSENSITIVE: case PREFIX: case INFIX: { return predicateValues.stream() .map((str) -> str + "*") .collect(Collectors.joining(" | ")); } default: throw new IllegalArgumentException("Unsupported Predicate Operator: " + op); } }
Source:
<code>public void close() throws IOException { <START> super.close(); exportJob.close(); <END> }</code><technical_language>Wenn super.close ne Exception wirft, wird der Export-Job nicht geschlossen :( suggestion try (Closeable c = super) { exportJob.close(); } Das try resources macht intern ziemlich viele coole Sachen: <LINK_0></technical_language>

Target:
public void close() throws IOException { try (Closeable c = exportJob) { super.close(); } }
Source:
<code>public boolean updateWithAccuCheckerReport(IoCAccuCheckerReport report) throws ArchiveException, IoCValidationException { if (report.getSource() == null || report.getSource().getId() == null || report.getSource().getId().getValue() == null) { throw new IoCValidationException("Accuchecker report doesn't have required field source.id.value."); } if (report.getAccuracy() == null) { throw new IoCValidationException("Accuchecker report doesn't have required field accuracy."); } boolean response = true; final HashMap<String, Integer> report_accuracy = report.getAccuracy(); String source_id_value = report.getSource().getId().getValue(); List<IoCRecord> iocs = archiveService.getMatchingEntries("source.id.value", source_id_value); for (IoCRecord ioc : iocs) { <START> HashMap<String, Integer> combined_accuracy = new HashMap<>(); <END> if (ioc.getAccuracy() != null) { combined_accuracy.putAll(ioc.getAccuracy()); } combined_accuracy.putAll(report_accuracy); ioc.setAccuracy(combined_accuracy); archiveService.setReportToIoCRecord(report, ioc.getDocumentId()); boolean cache_response = blacklistCacheService.addToCache(ioc); if (!cache_response) { response = false; } } return response; }</code><technical_language>@hugeox initialCapacity for theHashMap while it...</technical_language>

Target:
public boolean updateWithAccuCheckerReport(IoCAccuCheckerReport report) throws ArchiveException, IoCValidationException { if (report.getSource() == null || report.getSource().getId() == null || report.getSource().getId().getValue() == null) { throw new IoCValidationException("Accuchecker report doesn't have required field source.id.value."); } if (report.getAccuracy() == null) { throw new IoCValidationException("Accuchecker report doesn't have required field accuracy."); } boolean response = true; final HashMap<String, Integer> report_accuracy = report.getAccuracy(); String source_id_value = report.getSource().getId().getValue(); List<IoCRecord> iocs = archiveService.getMatchingActiveEnries("source.id.value", source_id_value); for (IoCRecord ioc : iocs) { HashMap<String, Integer> combined_accuracy = new HashMap<>(); if (ioc.getAccuracy() != null) { combined_accuracy.putAll(ioc.getAccuracy()); } combined_accuracy.putAll(report_accuracy); ioc.setAccuracy(combined_accuracy); archiveService.setReportToIoCRecord(report, ioc.getDocumentId()); boolean cache_response = blacklistCacheService.addToCache(ioc); if (!cache_response) { response = false; } } return response; }
Source:
<code>private void getRegisters(final IFrameDMContext frameDmc, final MIRegisterGroupDMC groupDmc, IContainerDMContext containerDmc, final DataRequestMonitor<IRegisterDMContext[]> rm) { fRegisterNameCache.execute(fCommandFactory.createMIDataListRegisterNames(containerDmc), <START> new DataRequestMonitor<MIDataListRegisterNamesInfo>(getExecutor(), rm) { <END> @Override protected void handleSuccess() { String[] regNames = getData().getRegisterNames(); if (regNames.length == 0) { rm.done(); return; } if (frameDmc == null) rm.setData(makeRegisterDMCs(groupDmc, regNames)); else rm.setData(makeRegisterDMCs(groupDmc, frameDmc, regNames)); rm.done(); } }); }</code><technical_language>ImmediateDM</technical_language>

Target:
private void getRegisters(final IFrameDMContext frameDmc, final MIRegisterGroupDMC groupDmc, IContainerDMContext containerDmc, final DataRequestMonitor<IRegisterDMContext[]> rm) { fRegisterNameCache.execute(fCommandFactory.createMIDataListRegisterNames(containerDmc), new ImmediateDataRequestMonitor<MIDataListRegisterNamesInfo>(rm) { @Override protected void handleSuccess() { String[] regNames = getData().getRegisterNames(); if (regNames.length == 0) { rm.done(); return; } if (frameDmc == null) rm.setData(makeRegisterDMCs(groupDmc, regNames)); else rm.setData(makeRegisterDMCs(groupDmc, frameDmc, regNames)); rm.done(); } }); }
Source:
<code>private Query buildQuery(final Message<?> requestMessage) { <START> Assert.isTrue(this.mongoDbQuery != null || this.mongoDbQueryExpression != null, "no query specified"); <END> Query query; if (this.mongoDbQuery != null) { query = new BasicQuery(this.mongoDbQuery); } else { Object expressionValue = this.mongoDbQueryExpression.getValue(this.evaluationContext, requestMessage, Object.class); if (expressionValue instanceof String) { query = new BasicQuery((String) expressionValue); } else if (expressionValue instanceof Query) { query = ((Query) expressionValue); } else { throw new IllegalStateException("'queryExpression' must evaluate to String or org.springframework.data.mongodb.core.query.Query"); } } return query; }</code><technical_language>Well, I query (queryExpression) is mandatory, do this Assert in doInit()</technical_language>

Target:
private Query buildQuery(final Message<?> requestMessage) { Query query; Object expressionValue = this.queryExpression.getValue(this.evaluationContext, requestMessage, Object.class); if (expressionValue instanceof String) { query = new BasicQuery((String) expressionValue); } else if (expressionValue instanceof Query) { query = ((Query) expressionValue); } else { throw new IllegalStateException("'queryExpression' must evaluate to " + "String or org.springframework.data.mongodb.core.query.Query"); } return query; }
Source:
<code>public boolean intersects(Interval1D that, double reciprocalRatio, int wiggle) { if (wiggle == 0) { return intersects(that, reciprocalRatio); } <START> long len_this = reciprocalRatio == 1.0 ? this.length() : (long) Math.max(Math.ceil(this.length() * reciprocalRatio), 1l); <END> long len_that = reciprocalRatio == 1.0 ? that.length() : (long) Math.max(Math.ceil(that.length() * reciprocalRatio), 1l); long maxOverlap = 0; long rightLim; long leftLim; if (getRight() < that.getRight()) { rightLim = Math.min(that.getRight(), getRight() + wiggle); } else { rightLim = Math.max(that.getRight(), getRight() - wiggle); } leftLim = rightLim - length() + 1l; long overlap = Math.min(rightLim, that.getRight()) - Math.max(leftLim, that.getLeft()) + 1l; maxOverlap = Math.max(maxOverlap, overlap); if (getLeft() < that.getLeft()) { leftLim = Math.min(that.getLeft(), getLeft() + wiggle); } else { leftLim = Math.max(that.getLeft(), getLeft() - wiggle); } rightLim = leftLim + length() - 1l; overlap = Math.min(rightLim, that.getRight()) - Math.max(leftLim, that.getLeft()) + 1l; maxOverlap = Math.max(maxOverlap, overlap); if (maxOverlap >= Math.max(len_this, len_that)) { return true; } return false; }</code><technical_language>logic simplified here. Please a <LINK_0> . Of course, need check works for 0 length intervals</technical_language>

Target:
public boolean intersects(Interval1D that, double reciprocalRatio, int wiggle) { reciprocalRatio = Math.max(reciprocalRatio, ((double)1/Long.MAX_VALUE)); long maxAllowedShift = Math.max(-wiggle, Math.min(wiggle, that.getLeft() - this.getLeft())); long maxOverlap = Math.min(this.getRight() + maxAllowedShift, that.getRight()) - Math.max(this.getLeft() + maxAllowedShift, that.getLeft()) + 1l; return maxOverlap >= Math.max(this.length(), that.length()) * reciprocalRatio; }
Source:
<code>public void issue1321() { CompilationUnit compilationUnit = JavaParser.parse("class X { X() private void testme() }"); LexicalPreservingPrinter.setup(compilationUnit); ClassOrInterfaceDeclaration type = compilationUnit.getClassByName("X").get(); type.getConstructors().get(0).setBody(new BlockStmt().addStatement("testme();")); <START> assertEquals("class X { X() {\n testme();\n} private void testme() }", LexicalPreservingPrinter.print(compilationUnit)); <END> }</code><technical_language>AppVeyor job: this test fails Windows. Try assertEqualsNoEol is called</technical_language>

Target:
public void issue1321() { CompilationUnit compilationUnit = JavaParser.parse("class X { X() private void testme() }"); LexicalPreservingPrinter.setup(compilationUnit); ClassOrInterfaceDeclaration type = compilationUnit.getClassByName("X").get(); type.getConstructors().get(0).setBody(new BlockStmt().addStatement("testme();")); assertEqualsNoEol("class X { X() {\n testme();\n} private void testme() }", LexicalPreservingPrinter.print(compilationUnit)); }
Source:
<code>public void handleAnalysisStarted(TmfStartAnalysisSignal signal) { IAnalysisModule module = signal.getAnalysisModule(); if (module instanceof ITmfAnalysisModuleWithStateSystems && !module.isAutomatic()) { <START> fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); <END> if (Iterables.contains(allModules(getTrace()), module)) { rebuild(); } else { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (Iterables.contains(allModules(trace), module)) { resetView(trace); break; } } } } }</code><technical_language>child modules of some of trace's modules leaking, do view reset rebuilt, returned allModules() below. examples of parent -> child TmfStatisticsModule -> TmfStatisticsEventTypesModule, TmfStatisticsTotalsModule XmlPatternAnalysis -> XmlPatternStateSystemModule</technical_language>

Target:
public void handleAnalysisStarted(TmfStartAnalysisSignal signal) { IAnalysisModule module = signal.getAnalysisModule(); if (module instanceof ITmfAnalysisModuleWithStateSystems && !module.isAutomatic()) { if (Iterables.contains(allModules(getTrace()), module)) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); rebuild(); } else { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (Iterables.contains(allModules(trace), module)) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); resetView(trace); break; } } } } }
Source:
<code>public static void main(String[] args) { <START> System.out.println("to run the example use the following commands: " <END> + "start -> this command will initiate " + "seed node join <index> -> this command will join a node (seed) from the list list -> " + "will list the current cluster state and leaders selected kill<index> -> " + "will shutdown a node"); Scanner scanner = new Scanner(System.in); boolean notExitCLI = true; while (notExitCLI) { System.out.print("ScaleCube: "); String command = scanner.next(); if (command.equals("start")) { createNode(-1); list(); } else if (command.startsWith("join")) { String index = scanner.next(); int i=-2; try{ i = Integer.valueOf(index); }catch(NumberFormatException ex){ System.out.println("invalid input value must be valid index number"); }; if(i>=0 && i<nodes.size()){ createNode(i); list(); } } else if (command.startsWith("list")) { list(); } else if (command.startsWith("kill")) { String index = scanner.next(); int i = Integer.valueOf(index); ICluster nodeA = nodes.get(i); nodeA.shutdown(); ICluster addr = nodes.remove(i); leaders.remove(addr); list(); } } }</code><technical_language>this stuff for working command line is needed, simpler example show essence API</technical_language>

Target:
public static void main(String[] args) { System.out.println("to run the example use the following commands: " + "start -> this command will initiate " + "seed node join <index> -> this command will join a node (seed) from the list list -> " + "will list the current cluster state and leaders selected kill<index> -> " + "will shutdown a node"); Scanner scanner = new Scanner(System.in); boolean notExitCLI = true; while (notExitCLI) { System.out.print("ScaleCube: "); String command = scanner.next(); if (command.equals("start")) { createNode(-1); list(); } else if (command.startsWith("join")) { String index = scanner.next(); int i = -2; try { i = Integer.valueOf(index); } catch (NumberFormatException ex) { System.out.println("invalid input value must be valid index number"); } ; if (i >= 0 && i < nodes.size()) { createNode(i); list(); } } else if (command.startsWith("list")) { list(); } else if (command.startsWith("kill")) { String index = scanner.next(); int i = Integer.valueOf(index); ICluster nodeA = nodes.get(i); nodeA.shutdown(); ICluster addr = nodes.remove(i); leaders.remove(addr); list(); } } scanner.close(); }
Source:
<code>private void initializePresenter() { mainExecutor= new UIThreadExecutor(); IAsyncExecutor asyncExecutor = new AsyncExecutor(); IMediaRepository mediaRepository = new MediaRepository(); GetMediaUseCase getMediaUseCase = new GetMediaUseCase(mainExecutor, asyncExecutor, mediaRepository); settingsDataSource = new SettingsDataSource(); <START> mPresenter = new MediaPresenter(getMediaUseCase, settingsDataSource.getSettings()); <END> mPresenter.attachView(this); }</code><technical_language>presenter receive in constructor cases inkove</technical_language>

Target:
private void initializePresenter() { mainExecutor= new UIThreadExecutor(); IAsyncExecutor asyncExecutor = new AsyncExecutor(); IMediaRepository mediaRepository = new MediaRepository(); ISettingsRepository settingsDataSource = new SettingsDataSource(getActivity().getBaseContext()); GetMediaUseCase getMediaUseCase = new GetMediaUseCase(mainExecutor, asyncExecutor, mediaRepository); GetSettingsUseCase getSettingsUseCase = new GetSettingsUseCase(mainExecutor, asyncExecutor, settingsDataSource); SaveSettingsUseCase saveSettingsUseCase = new SaveSettingsUseCase(mainExecutor, asyncExecutor, settingsDataSource); mPresenter = new MediaPresenter(getMediaUseCase, getSettingsUseCase, saveSettingsUseCase); mPresenter.attachView(this); }
Source:
<code>public PushCommand setRefSpecs(RefSpec... specs) { checkCallable(); this.refSpecs.clear(); <START> for (RefSpec spec : specs) <END> refSpecs.add(spec); return this; }</code><technical_language>simplified: Collections.addAll(refsSpecs, specs);</technical_language>

Target:
public PushCommand setRefSpecs(RefSpec... specs) { checkCallable(); this.refSpecs.clear(); Collections.addAll(refSpecs, specs); return this; }
Source:
<code><START> public RebalanceTask(HelixManager manager, ClusterEventType clusterEventType, <END> long nextRebalanceTime) { this(manager, clusterEventType, nextRebalanceTime, true); }</code><technical_language>a simple Builder pattern; package-private class I assume constructor called in limited places</technical_language>

Target:
public RebalanceTask(HelixManager manager, ClusterEventType clusterEventType, long nextRebalanceTime) { this(manager, clusterEventType, nextRebalanceTime, Optional.empty()); }
Source:
<code>public void copyPreviewToClipBoard() { StringBuilder previewStringContent = new StringBuilder(); Document document = previewView.getEngine().getDocument(); NodeList nodeList = document.getElementsByTagName("html"); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); previewStringContent.append(element.getTextContent()); } <START> String previewStringContentString = previewStringContent.toString().replaceAll("function highlight[\\w\\W]*\\}", ""); <END> ClipboardContent content = new ClipboardContent(); content.putString(previewStringContentString); content.putHtml((String) previewView.getEngine().executeScript("document.documentElement.outerHTML")); clipBoardManager.setContent(content); }</code><technical_language>Extract Pattern Pattern.compile Alternatively strip <script > tags</technical_language>

Target:
public void copyPreviewToClipBoard() { StringBuilder previewStringContent = new StringBuilder(); Document document = previewView.getEngine().getDocument(); ClipboardContent content = new ClipboardContent(); content.putString(document.getElementById("content").getTextContent()); content.putHtml((String) previewView.getEngine().executeScript("document.documentElement.outerHTML")); clipBoardManager.setContent(content); }
Source:
<code>public static void removeApplicationBeanFromSession(HttpSession session, String spName) { Map<String, UUID> spUniqueIdMap = (HashMap<String, UUID>) session.getAttribute("spUniqueIdMap"); <START> if (spUniqueIdMap.get(spName) == null) { <END> return; } session.removeAttribute(spUniqueIdMap.get(spName).toString()); spUniqueIdMap.remove(spName); }</code><technical_language>NullPointerException if Map is in session. Follow pattern in getApplicationBeanFromSession()</technical_language>

Target:
public static void removeApplicationBeanFromSession(HttpSession session, String spName) { if(session.getAttribute("spUniqueIdMap") == null) { return; } Map<String, UUID> spUniqueIdMap = (HashMap<String, UUID>) session.getAttribute("spUniqueIdMap"); if (spUniqueIdMap.get(spName) == null) { return; } session.removeAttribute(spUniqueIdMap.get(spName).toString()); spUniqueIdMap.remove(spName); }
Source:
<code>protected Node loadXMLNode() { try { File XMLFile = fFilePath.toFile(); if (XMLFile == null || !XMLFile.exists() || !XMLFile.isFile()) { return null; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(XMLFile); doc.getDocumentElement().normalize(); NodeList stateproviderNodes = doc.getElementsByTagName(TmfXmlStrings.STATE_PROVIDER); Element stateproviderNode = null; for (int i = 0; i < stateproviderNodes.getLength(); i++) { Element node = (Element) stateproviderNodes.item(i); String analysisid = node.getAttribute(TmfXmlStrings.ANALYSIS_ID); if (analysisid.equals(fStateId)) { stateproviderNode = node; } } if (stateproviderNode == null) { return null; } NodeList definedStateNodes = stateproviderNode.getElementsByTagName(TmfXmlStrings.STATE_VALUE); for (int i = 0; i < definedStateNodes.getLength(); i++) { Element node = (Element) definedStateNodes.item(i); fStateValues.put(node.getAttribute(TmfXmlStrings.NAME), node.getAttribute(TmfXmlStrings.VALUE)); } NodeList locationNodes = stateproviderNode.getElementsByTagName(TmfXmlStrings.LOCATION); fLocations = new ArrayList<>(); <START> for (int i = 0; i < locationNodes.getLength(); i++) { <END> Node node = locationNodes.item(i); TmfXmlLocation location = new TmfXmlLocation(node, fStateValues); fLocations.add(location); } return stateproviderNode; } catch (ParserConfigurationException e) { Activator.logError("Error loading XML file", e); } catch (SAXException e) { Activator.logError(NLS.bind(Messages.XmlUtils_XmlValidationError, e.getLocalizedMessage()), e); } catch (IOException e) { Activator.logError("Error loading XML file", e); } return null; }</code><technical_language>Is NodeList Iterable? I check moment, if is, "for each" iteration, implementation give performance .item(i) .get(i)</technical_language>

Target:
private Element loadXMLNode() { try { File XMLFile = fFilePath.toFile(); if (XMLFile == null || !XMLFile.exists() || !XMLFile.isFile()) { return null; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(XMLFile); doc.getDocumentElement().normalize(); NodeList stateproviderNodes = doc.getElementsByTagName(TmfXmlStrings.STATE_PROVIDER); Element stateproviderNode = null; for (int i = 0; i < stateproviderNodes.getLength(); i++) { Element node = (Element) stateproviderNodes.item(i); String analysisid = node.getAttribute(TmfXmlStrings.ANALYSIS_ID); if (analysisid.equals(fStateId)) { stateproviderNode = node; } } return stateproviderNode; } catch (ParserConfigurationException | IOException e) { Activator.logError("Error loading XML file", e); } catch (SAXException e) { Activator.logError(NLS.bind(Messages.XmlUtils_XmlValidationError, e.getLocalizedMessage()), e); } return null; }
Source:
<code>public List<String> getResourceCrnListByResourceNameList(List<String> resourceNames) { return resourceNames.stream() <START> .map(resourceName -> blueprintRepository.findResourceCrnByNameAndAccountId(resourceName, ThreadBasedUserCrnProvider.getAccountId()).orElse(null)) <END> .collect(Collectors.toList()); }</code><technical_language>is throw a also, it</technical_language>

Target:
public List<String> getResourceCrnListByResourceNameList(List<String> resourceNames) { return resourceNames.stream() .map(resourceName -> blueprintRepository.findResourceCrnByNameAndAccountId(resourceName, ThreadBasedUserCrnProvider.getAccountId()) .orElseThrow(NotFoundException.notFound("Blueprint", resourceName))) .collect(Collectors.toList()); }
Source:
<code>public void applyState(ShapeState shapeState) { if (!this.state.equals(shapeState)) { this.state = shapeState; <START> if (ShapeState.SELECTED.equals(shapeState)) { <END> applyActiveState(ShapeState.SELECTED.getColor()); } else if (ShapeState.HIGHLIGHT.equals(shapeState)) { applyActiveState(ShapeState.HIGHLIGHT.getColor()); } else if (ShapeState.INVALID.equals(shapeState)) { applyActiveState(ShapeState.INVALID.getColor()); } else { applyNoneState(); } } }</code><technical_language>this if replaced switch, liner: java applyActiveState(shapge.State.getColor()); some minor refactoring</technical_language>

Target:
public void applyState(ShapeState shapeState) { if (!this.state.equals(shapeState)) { this.state = shapeState; switch (this.state) { case NONE: applyNoneState(); break; default: applyActiveState(shapeState.getColor()); } } }
Source:
<code>public static String normaliseName(final String name) { if (name == null) { return ""; } if (isEscaped(name)) { <START> return name.substring(1,name.length() - 1).replace("\"\"", "\""); <END> } return dbfit.util.NameNormaliser.normaliseName(name); }</code><technical_language>Missing space 1</technical_language>

Target:
public static String normaliseName(final String name) { if (name == null || name.isEmpty()) { return ""; } if (isEscaped(name)) { return name.substring(1, name.length() - 1).replace("\"\"", "\""); } return dbfit.util.NameNormaliser.normaliseName(name); }
Source:
<code>public void setRuleConfigValue(String key, String value) { for (RuleConfig token : rcs) { if (token.getKey().equals(key)) { <START> token.setValue(value); <END> return; } } }</code><technical_language>fireTableCellUpdated notify table of change</technical_language>

Target:
public void setRuleConfigValue(String key, String value) { int row = 0; for (RuleConfig token : rcs) { if (token.getKey().equals(key)) { token.setValue(value); this.fireTableCellUpdated(row, 2); return; } row++; } }
Source:
<code><START> public void scalarSubQueryInClause2() { <END> this.query() .select(employee) .from(employee) .where( SQLExpressions .select(employee.firstname) .from(employee) .orderBy(employee.salary.asc()) .limit(1) .in("Mike", "Mary") ) .fetch(); }</code><technical_language>add assertion complete</technical_language>

Target:
public void scalarSubQueryInClause2() { SQLSerializer serializer = new SQLSerializer(Configuration.DEFAULT); serializer.handle( this.query() .from(employee) .where( SQLExpressions .select(employee.firstname) .from(employee) .orderBy(employee.salary.asc()) .limit(1) .in("Mike", "Mary") )); expectedQuery = "(\nfrom EMPLOYEE e\n" + "where (select e.FIRSTNAME\n" + "from EMPLOYEE e\n" + "order by e.SALARY asc\n" + "limit ?) in (?, ?))"; assertEquals(expectedQuery, serializer.toString()); }
Source:
<code>public void getObjectWithSync() throws Exception { final String bucketName = "test_get_object_with_sync"; final String objectName = "beowulf.txt"; try { Util.copyFile(objectName, Util.RESOURCE_BASE_NAME, Util.DOWNLOAD_BASE_NAME); <START> File file = new File(Util.DOWNLOAD_BASE_NAME + "/" + objectName); <END> DateTime modTime = new DateTime().minusHours(1); file.setLastModified(modTime.getMillis()); Util.createBucket(client, bucketName); Util.loadBookTestData(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "get_object", "-b", bucketName, "-o", objectName, "-d", Util.DOWNLOAD_BASE_NAME, "--sync"}); CommandResponse response = Util.command(client, args); assertThat(response.getMessage(), is("SUCCESS: Finished syncing object.")); } finally { Util.deleteBucket(client, bucketName); Util.deleteLocalFile(objectName); } }</code><technical_language>OS-agnostic handle pathing</technical_language>

Target:
public void getObjectWithSync() throws Exception { final String bucketName = "test_get_object_with_sync"; final String objectName = "beowulf.txt"; try { Util.copyFile(objectName, Util.RESOURCE_BASE_NAME, Util.DOWNLOAD_BASE_NAME); final File file = new File(Util.DOWNLOAD_BASE_NAME + File.separator + objectName); final DateTime modTime = new DateTime().minusHours(1); file.setLastModified(modTime.getMillis()); Util.createBucket(client, bucketName); Util.loadBookTestData(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "get_object", "-b", bucketName, "-o", objectName, "-d", Util.DOWNLOAD_BASE_NAME, "--sync"}); final CommandResponse response = Util.command(client, args); assertThat(response.getMessage(), is("SUCCESS: Finished syncing object.")); } finally { Util.deleteBucket(client, bucketName); Util.deleteLocalFile(objectName); } }
Source:
<code>public Node visitCreateTable(SqlBaseParser.CreateTableContext context) { Optional<String> comment = Optional.empty(); if (context.COMMENT() != null) { comment = Optional.of(((StringLiteral) visit(context.string())).getValue()); } TableProperties properties; <START> if (context.tableProperties() != null) { <END> properties = (TableProperties) visit(context.tableProperties()); } else { properties = new TableProperties(); } return new CreateTable( getLocation(context), getQualifiedName(context.qualifiedName()), visit(context.tableElement(), TableElement.class), context.EXISTS() != null, properties, comment); }</code><technical_language>this IF block is repeated multiple times, please extract method</technical_language>

Target:
public Node visitCreateTable(SqlBaseParser.CreateTableContext context) { Optional<String> comment = Optional.empty(); if (context.COMMENT() != null) { comment = Optional.of(((StringLiteral) visit(context.string())).getValue()); } List<Property> properties = ImmutableList.of(); if (context.properties() != null) { properties = visit(context.properties().property(), Property.class); } return new CreateTable( getLocation(context), getQualifiedName(context.qualifiedName()), visit(context.tableElement(), TableElement.class), context.EXISTS() != null, properties, comment); }
Source:
<code>public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper( (HttpServletRequest) servletRequest) { @Override public String getRequestURI() { <START> String newNormal = URI.create(super.getRequestURI()).normalize().toString(); <END> while(newNormal.indexOf(" newNormal = newNormal.replace(" } return newNormal; } }; filterChain.doFilter(requestWrapper, servletResponse); }</code><technical_language>I return newNormal.replaceAll(Pattern.quote("//"), StringPool.SLASH);</technical_language>

Target:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper( (HttpServletRequest) servletRequest) { @Override public String getRequestURI() { try { String newNormal = URI.create(super.getRequestURI()).normalize().toString(); newNormal = newNormal.startsWith(DOUBLEPEROIDS) ? newNormal.replace(DOUBLEPEROIDS, "") : newNormal; newNormal = newNormal.startsWith(SLASH) ? newNormal : SLASH + newNormal; newNormal = newNormal.indexOf(QUESTION )>-1 ? newNormal.substring(0,newNormal.indexOf(StringPool.QUESTION)) : newNormal; while(newNormal.indexOf(DOUBLESLASH)>-1) { newNormal = newNormal.replace(DOUBLESLASH, SLASH); } return newNormal; } catch(IllegalArgumentException ill) { Logger.warnAndDebug(this.getClass(),ill); HttpServletResponse response= (HttpServletResponse) servletResponse; try { response.sendError(HttpServletResponse.SC_FORBIDDEN); response.flushBuffer(); } catch(Exception e) return "/"; } } }; filterChain.doFilter(requestWrapper, servletResponse); }
Source:
<code>public void execute() throws RuntimeException, InterruptedException { Session session = initSession(); session.execute("USE " + keyspace); session.execute(TRUNCATE_TAGS_IDX_QUERY); session.execute(TRUNCATE_METRICS_IDX_QUERY); <START> session.close(); <END> }</code><technical_language>close Cluster instance well, process running completing. this in a finally block close in case of error</technical_language>

Target:
public void execute() throws RuntimeException, InterruptedException { try { initSession(); session.execute(TRUNCATE_TAGS_IDX_QUERY); session.execute(TRUNCATE_METRICS_IDX_QUERY); } finally { this.shutdown(); } }
Source:
<code>protected ImmutableValue<Boolean> constructImmutableValue(Boolean value) { <START> return ImmutableSpongeValue.cachedOf(Keys.ENTITY_HAS_GRAVITY, DataConstants.DEFAULT_HAS_GRAVITY, value); <END> }</code><technical_language>this.key here</technical_language>

Target:
protected ImmutableValue<Boolean> constructImmutableValue(Boolean value) { return ImmutableSpongeValue.cachedOf(this.key, DataConstants.DEFAULT_HAS_GRAVITY, value); }
Source:
<code>void validateBarcode(final LabelsGeneratorInput labelsGeneratorInput, final LabelsData labelsData) { final BindingResult errors = new MapBindingResult(new HashMap<String, String>(), Integer.class.getName()); if(!labelsGeneratorInput.isAutomaticBarcode()){ <START> for (Map<Integer, String> data:labelsData.getData()){ <END> List<Integer> barcodeIds = labelsGeneratorInput.getBarcodeFields().stream().filter(labelId -> data.get(labelId) == null).collect( Collectors.toList()); if(!barcodeIds.isEmpty()){ errors.reject("label.fields.barcodes.selected.empty.value",""); throw new ApiRequestValidationException(errors.getAllErrors()); } } } }</code><technical_language>@cuenyad final</technical_language>

Target:
void validateBarcode(final LabelsGeneratorInput labelsGeneratorInput, final LabelsData labelsData) { final BindingResult errors = new MapBindingResult(new HashMap<String, String>(), Integer.class.getName()); if(!labelsGeneratorInput.isAutomaticBarcode()){ for (final Map<Integer, String> data:labelsData.getData()){ List<Integer> barcodeIds = labelsGeneratorInput.getBarcodeFields().stream().filter(labelId -> data.get(labelId) == null).collect( Collectors.toList()); if(!barcodeIds.isEmpty()){ errors.reject("label.fields.barcodes.selected.empty.value",""); throw new ApiRequestValidationException(errors.getAllErrors()); } } } }
Source:
<code>private SearchRow getSearchRow(SearchRow row, int columnId, Value v, boolean max) { Column column = columnId == SearchRow.ROWID_INDEX ? table.getRowIdColumn() : table.getColumn(columnId); int vType = v.getType(); int resType = Value.getHigherOrder(column.getType(), vType); if(vType != resType) { v = column.convert(v, session.getDatabase().getMode()); <START> } <END> if (row == null) { row = table.getTemplateRow(); } else { v = getMax(row.getValue(columnId), v, max); } if (columnId == SearchRow.ROWID_INDEX) { row.setKey(v.getLong()); } else { row.setValue(columnId, v); } return row; }</code><technical_language>this new chunk of logic need some explanation "replace magic constant" ? is fixing a bug</technical_language>

Target:
private SearchRow getSearchRow(SearchRow row, int columnId, Value v, boolean max) { if (row == null) { row = table.getTemplateRow(); } else { v = getMax(row.getValue(columnId), v, max); } if (columnId == SearchRow.ROWID_INDEX) { row.setKey(v.getLong()); } else { row.setValue(columnId, v); } return row; }
Source:
<code>private static <T extends InputSplit> T deserializeInputSplitInternal( Configuration conf, DataInputStream in, Class<T> clazz) throws IOException { T split = ReflectionUtils.newInstance(clazz, conf); SerializationFactory factory = new SerializationFactory(conf); Deserializer<T> deserializer = factory.getDeserializer(clazz); <START> deserializer.open(new UncloseableDataInputStream((DataInputStream) in)); <END> return deserializer.deserialize(split); }</code><technical_language>layers of wrapping UncloseableDataInputStream if one. done in this method</technical_language>

Target:
private static <T extends InputSplit> T deserializeInputSplitInternal( Configuration conf, DataInputStream in, Class<T> clazz) throws IOException { T split = ReflectionUtils.newInstance(clazz, conf); SerializationFactory factory = new SerializationFactory(conf); Deserializer<T> deserializer = factory.getDeserializer(clazz); deserializer.open(in instanceof UncloseableDataInputStream ? in : new UncloseableDataInputStream(in)); return deserializer.deserialize(split); }