auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>ValueJson(String str) throws IOException { <START> int memFirst = Utils.getMemoryUsed(); <END> if (str == null) { this.json=mapper.createObjectNode(); this.string = this.json.toString(); } this.string = str.replaceAll("\n", ""); char c = this.string.charAt(0); if ('{' == c) { ObjectNode node = (ObjectNode) mapper.readTree(this.string); this.json = node; } else if ('[' == c) { ObjectMapper mapper = new ObjectMapper(); ArrayNode arr = (ArrayNode) mapper.readTree(this.string); this.json = arr; } else { TextNode stringVal = new TextNode(this.string); this.json = stringVal; } this.binarySize = Utils.getMemoryUsed() - memFirst; }</code><technical_language>Do this method in main code, reliable</technical_language>

Target:
ValueJson(String str) throws IOException { if (str == null) { this.json=mapper.createObjectNode(); this.string = this.json.toString(); } this.string = str.replaceAll("\n", ""); char c = this.string.charAt(0); if ('{' == c) { ObjectNode node = (ObjectNode) mapper.readTree(this.string); this.json = node; } else if ('[' == c) { ObjectMapper mapper = new ObjectMapper(); ArrayNode arr = (ArrayNode) mapper.readTree(this.string); this.json = arr; } else { TextNode stringVal = new TextNode(this.string); this.json = stringVal; } this.binarySize = string.length(); }
Source:
<code>private void upsertData() throws SQLException { Connection conn = DriverManager.getConnection(getUrl()); PreparedStatement sourceStmt = conn.prepareStatement(String.format(UPSERT_USER, sourceTableName)); PreparedStatement targetStmt = conn.prepareStatement(String.format(UPSERT_USER, targetTableName)); <START> for (int t = 0; t < 2; t++) { <END> for (int u = 1; u <= 10; u++) { String tenantId = sourceTenants.get(t); String userId = "user" + userNum++; int age = RANDOM.nextInt(99) + 1; upsertData(sourceStmt, tenantId, userId, age); if (tenantId.equals(sourceAndTargetTenant)) { upsertData(targetStmt, tenantId, userId, age); } } } for (int u = 1; u <= 10; u++) { upsertData(targetStmt, targetOnlyTenant); } conn.commit(); assertEquals(10, countUsers(sourceTableName, sourceOnlyTenant)); assertEquals(10, countUsers(sourceTableName, sourceAndTargetTenant)); assertEquals(0, countUsers(sourceTableName, targetOnlyTenant)); assertEquals(10, countUsers(targetTableName, sourceAndTargetTenant)); assertEquals(10, countUsers(targetTableName, targetOnlyTenant)); assertEquals(0, countUsers(targetTableName, sourceOnlyTenant)); }</code><technical_language>nit: simplify this creating 2 separate loops, Line 183-185. easier understand</technical_language>

Target:
private void upsertData() throws SQLException { Connection conn = DriverManager.getConnection(getUrl()); sourceStmt = conn.prepareStatement(String.format(UPSERT_USER, sourceTableName)); targetStmt = conn.prepareStatement(String.format(UPSERT_USER, targetTableName)); sourceSplitPoints = Lists.newArrayListWithExpectedSize(4); targetSplitPoints = Lists.newArrayListWithExpectedSize(2); upsertData(sourceOnlyTenant); upsertData(sourceAndTargetTenant); upsertData(targetOnlyTenant); conn.commit(); assertEquals(NUM_USERS, countUsers(sourceTableName, sourceOnlyTenant)); assertEquals(NUM_USERS, countUsers(sourceTableName, sourceAndTargetTenant)); assertEquals(0, countUsers(sourceTableName, targetOnlyTenant)); assertEquals(NUM_USERS, countUsers(targetTableName, sourceAndTargetTenant)); assertEquals(NUM_USERS, countUsers(targetTableName, targetOnlyTenant)); assertEquals(0, countUsers(targetTableName, sourceOnlyTenant)); }
Source:
<code>private MemoryImageBuilder createMemoryImageBuilder() { if (!isMemorySnapshotSupported()) { return new NullableMemoryImageBuilder(); } if (getParameters().getSnapshotType() == SnapshotType.STATELESS) { return new StatelessSnapshotMemoryImageBuilder(getVm()); } if (getParameters().isSaveMemory() && isLiveSnapshotApplicable()) { boolean wipeAfterDelete = <START> getDisksList().stream().anyMatch(d -> d.isWipeAfterDelete()); <END> return new LiveSnapshotMemoryImageBuilder(getVm(), cachedStorageDomainId, getStoragePool(), this, vmOverheadCalculator, getParameters().getDescription(), wipeAfterDelete); } return new NullableMemoryImageBuilder(); }</code><technical_language>replaced DiskImage::isWipeAfterDelete</technical_language>

Target:
private MemoryImageBuilder createMemoryImageBuilder() { if (!isMemorySnapshotSupported()) { return new NullableMemoryImageBuilder(); } if (getParameters().getSnapshotType() == SnapshotType.STATELESS) { return new StatelessSnapshotMemoryImageBuilder(getVm()); } if (getParameters().isSaveMemory() && isLiveSnapshotApplicable()) { boolean wipeAfterDelete = getDisksList().stream().anyMatch(DiskImage::isWipeAfterDelete); return new LiveSnapshotMemoryImageBuilder(getVm(), cachedStorageDomainId, getStoragePool(), this, vmOverheadCalculator, getParameters().getDescription(), wipeAfterDelete); } return new NullableMemoryImageBuilder(); }
Source:
<code>public List<ConsumerRecord<byte[], byte[]>> update(final TopicPartition partition, final List<ConsumerRecord<byte[], byte[]>> records) { log.trace("Updating standby replicas of its state store for partition [{}]", partition); long limit = offsetLimits.getOrDefault(partition, Long.MAX_VALUE); long lastOffset = -1L; final List<ConsumerRecord<byte[], byte[]>> restoreRecords = new ArrayList<>(records.size()); final List<ConsumerRecord<byte[], byte[]>> remainingRecords = new ArrayList<>(); if (!records.isEmpty() && records.get(records.size() - 1).offset() >= limit && <START> updateableOffsetLimits.remove(partition)) { <END> limit = updateOffsetLimits(partition); } for (final ConsumerRecord<byte[], byte[]> record : records) { if (record.offset() < limit) { restoreRecords.add(record); lastOffset = record.offset(); } else { remainingRecords.add(record); } } if (!restoreRecords.isEmpty()) { stateMgr.updateStandbyStates(partition, restoreRecords, lastOffset); commitNeeded = true; } return remainingRecords; }</code><technical_language>I remove is more efficient, header extract logic. simpler read if contains</technical_language>

Target:
public List<ConsumerRecord<byte[], byte[]>> update(final TopicPartition partition, final List<ConsumerRecord<byte[], byte[]>> records) { if (records.isEmpty()) { return Collections.emptyList(); } log.trace("Updating standby replicas of its state store for partition [{}]", partition); long limit = offsetLimits.getOrDefault(partition, Long.MAX_VALUE); long lastOffset = -1L; final List<ConsumerRecord<byte[], byte[]>> restoreRecords = new ArrayList<>(records.size()); final List<ConsumerRecord<byte[], byte[]>> remainingRecords = new ArrayList<>(); for (final ConsumerRecord<byte[], byte[]> record : records) { if (record.offset() >= limit && updateableOffsetLimits.contains(partition)) { limit = updateOffsetLimits(partition); } if (record.offset() < limit) { restoreRecords.add(record); lastOffset = record.offset(); } else { remainingRecords.add(record); } } if (!restoreRecords.isEmpty()) { stateMgr.updateStandbyStates(partition, restoreRecords, lastOffset); commitNeeded = true; } return remainingRecords; }
Source:
<code>private void addActionToTitle() { title.setOnLongClickListener(view -> { Utils.copy("place", title.getText().toString(), getContext()); <START> Toast.makeText(getContext(), "Text copied to clipboard", Toast.LENGTH_SHORT).show(); <END> return true; }); title.setOnClickListener(view -> { bottomSheetListBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } else { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } }); }</code><technical_language>putting hard coded strings</technical_language>

Target:
private void addActionToTitle() { title.setOnLongClickListener(view -> { Utils.copy("place", title.getText().toString(), getContext()); Toast.makeText(getContext(), R.string.text_copy, Toast.LENGTH_SHORT).show(); return true; }); title.setOnClickListener(view -> { bottomSheetListBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } else { bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } }); }
Source:
<code>private void getHistory(AbstractFile origFile, File resultDir) throws TskCoreException, FileNotFoundException { <START> ArrayList<File> historyFiles = getHistoryFiles(resultDir); <END> if (historyFiles == null) { return; } for (File file : historyFiles) { Scanner fileScanner; try { fileScanner = new Scanner(new FileInputStream(file.toString())); } catch (FileNotFoundException ex) { LOG.log(Level.WARNING, "Unable to find the ESEDatabaseView file at " + file.getPath(), ex); continue; } Collection<BlackboardArtifact> bbartifacts = new ArrayList<>(); try { List<String> headers = null; while (fileScanner.hasNext()) { String line = fileScanner.nextLine(); if (headers == null) { headers = Arrays.asList(line.toLowerCase().split(",")); continue; } if (line.contains(EDGE_KEYWORD_VISIT)) { BlackboardArtifact b = getHistoryArtifact(origFile, headers, line); if (b != null) { bbartifacts.add(b); this.indexArtifact(b); } } } } finally { fileScanner.close(); } if (!bbartifacts.isEmpty()) { services.fireModuleDataEvent(new ModuleDataEvent( RecentActivityExtracterModuleFactory.getModuleName(), BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_HISTORY, bbartifacts)); } } }</code><technical_language>I is a practice, done in other places in this class, declaring collection return variables in a avoids making type concrete code more adaptable. For example, if List interface instead of concrete class ArrayList, if return of getDownloadFiles changed LinkedList, this client code need changed</technical_language>

Target:
private void getHistory(AbstractFile origFile, File resultDir) throws TskCoreException, FileNotFoundException { ArrayList<File> historyFiles = getHistoryFiles(resultDir); if (historyFiles == null) { return; } for (File file : historyFiles) { Scanner fileScanner; try { fileScanner = new Scanner(new FileInputStream(file.toString())); } catch (FileNotFoundException ex) { LOG.log(Level.WARNING, "Unable to find the ESEDatabaseView file at " + file.getPath(), ex); continue; } Collection<BlackboardArtifact> bbartifacts = new ArrayList<>(); try { List<String> headers = null; while (fileScanner.hasNext()) { String line = fileScanner.nextLine(); if (headers == null) { headers = Arrays.asList(line.toLowerCase().split(",")); continue; } if (line.contains(EDGE_KEYWORD_VISIT)) { BlackboardArtifact ba = getHistoryArtifact(origFile, headers, line); if (ba != null) { bbartifacts.add(ba); this.indexArtifact(ba); } } } } finally { fileScanner.close(); } if (!bbartifacts.isEmpty()) { services.fireModuleDataEvent(new ModuleDataEvent( RecentActivityExtracterModuleFactory.getModuleName(), BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_HISTORY, bbartifacts)); } } }
Source:
<code>public GetUsersResult call() throws IOException, SignatureException, SSLSetupException, CommandException { try { <START> ModifyUserSpectraS3Request modifyRequest = new ModifyUserSpectraS3Request(this.userId); <END> for (String paramChange : this.modifyParams.keySet() ) { String paramNewValue = this.modifyParams.get(paramChange); if("default_data_policy_id".equalsIgnoreCase(paramChange)) { modifyRequest.withDefaultDataPolicyId(paramNewValue); } else if("name".equalsIgnoreCase(paramChange)) { throw new CommandException("Modify user name currently not supported." ); } else { throw new CommandException("Unrecognized user parameter: " + paramChange); } } final ModifyUserSpectraS3Response modifyResponse = getClient().modifyUserSpectraS3(modifyRequest); return new GetUsersResult(modifyResponse.getSpectraUserResult()); } catch (final FailedRequestException e) { throw new CommandException("Failed Modify User: " + e.getMessage(), e); } }</code><technical_language>Missing final</technical_language>

Target:
public GetUsersResult call() throws IOException, SignatureException, SSLSetupException, CommandException { try { final ModifyUserSpectraS3Request modifyRequest = new ModifyUserSpectraS3Request(this.userId); for (final String paramChange : this.modifyParams.keySet()) { final String paramNewValue = this.modifyParams.get(paramChange); if("default_data_policy_id".equalsIgnoreCase(paramChange)) { modifyRequest.withDefaultDataPolicyId(paramNewValue); } else if("name".equalsIgnoreCase(paramChange)) { throw new CommandException("Modify user name currently not supported." ); } else { throw new CommandException("Unrecognized user parameter: " + paramChange); } } final ModifyUserSpectraS3Response modifyResponse = getClient().modifyUserSpectraS3(modifyRequest); return new GetUsersResult(modifyResponse.getSpectraUserResult()); } catch (final FailedRequestException e) { throw new CommandException("Failed Modify User: " + e.getMessage(), e); } }
Source:
<code>protected boolean drawState(TimeGraphColorScheme colors, ITimeEvent event, Rectangle rect, GC gc, boolean selected, boolean timeSelected) { int colorIdx = fTimeGraphProvider.getStateTableIndex(event); if (colorIdx < 0 && colorIdx != ITimeGraphPresentationProvider.TRANSPARENT) { return false; } boolean visible = rect.width == 0 ? false : true; Color black = Display.getDefault().getSystemColor(SWT.COLOR_BLACK); gc.setForeground(black); if (visible) { if (colorIdx == ITimeGraphPresentationProvider.TRANSPARENT) { gc.drawLine(rect.x, rect.y, rect.x + rect.width - 1, rect.y); gc.drawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width - 1, rect.y + rect.height - 1); if (rect.width == 1) { gc.drawPoint(rect.x, rect.y - 2); } return false; } Color stateColor = null; if (colorIdx < fEventColorMap.length) { stateColor = fEventColorMap[colorIdx]; } else { stateColor = black; } boolean reallySelected = timeSelected && selected; gc.setBackground(stateColor); gc.fillRectangle(rect); if (reallySelected) { <START> gc.drawRectangle(rect.x, rect.y - 1, rect.width -2, rect.height + 1); <END> } } else { gc.drawPoint(rect.x, rect.y - 2); } fTimeGraphProvider.postDrawEvent(event, rect, gc); return visible; }</code><technical_language>it, prefer black highlighting drawn lines. reason is 'real' state interval extends window limits, a rectangle highlighting false impression state starts ends window edges. tested this code ok: gc.drawLine(rect.x, rect.y - 1, rect.x + rect.width - 1, rect.y - 1); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width - 1, rect.y + rect.height); I guess alternatively draw highlighting rectangle fill state color overwrite left right edges..</technical_language>

Target:
protected boolean drawState(TimeGraphColorScheme colors, ITimeEvent event, Rectangle rect, GC gc, boolean selected, boolean timeSelected) { int colorIdx = fTimeGraphProvider.getStateTableIndex(event); if (colorIdx < 0 && colorIdx != ITimeGraphPresentationProvider.TRANSPARENT) { return false; } boolean visible = rect.width == 0 ? false : true; Color black = Display.getDefault().getSystemColor(SWT.COLOR_BLACK); gc.setForeground(black); if (visible) { if (colorIdx == ITimeGraphPresentationProvider.TRANSPARENT) { gc.drawLine(rect.x, rect.y, rect.x + rect.width - 1, rect.y); gc.drawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width - 1, rect.y + rect.height - 1); if (rect.width == 1) { gc.drawPoint(rect.x, rect.y - 2); } return false; } Color stateColor = null; if (colorIdx < fEventColorMap.length) { stateColor = fEventColorMap[colorIdx]; } else { stateColor = black; } boolean reallySelected = timeSelected && selected; gc.setBackground(stateColor); gc.fillRectangle(rect); if (reallySelected) { gc.drawLine(rect.x, rect.y - 1, rect.x + rect.width - 1, rect.y - 1); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width - 1, rect.y + rect.height); } } else { gc.drawPoint(rect.x, rect.y - 2); } fTimeGraphProvider.postDrawEvent(event, rect, gc); return visible; }
Source:
<code>private void loadConfig() { for (EventScript script : m_config.getEventScripts()) { Uei[] ueis = script.getUei(); if (ueis.length == 0) { <START> m_eventScripts.add(script); <END> } else { for (Uei uei : ueis) { String ueiName = uei.getName(); List<EventScript> list = m_eventScriptMap.get(ueiName); if (list == null) { list = new ArrayList<EventScript>(); list.add(script); m_eventScriptMap.put(ueiName, list); } else { list.add(script); } } } } }</code><technical_language>Is loadConfig() called multiple times? a COW list, end duplicates if reload configs</technical_language>

Target:
private void loadConfig() { m_eventScripts.clear(); m_eventScriptMap.clear(); for (EventScript script : m_config.getEventScripts()) { Uei[] ueis = script.getUei(); if (ueis.length == 0) { m_eventScripts.add(script); } else { for (Uei uei : ueis) { String ueiName = uei.getName(); Set<EventScript> list = m_eventScriptMap.get(ueiName); if (list == null) { list = new CopyOnWriteArraySet<>(); list.add(script); m_eventScriptMap.put(ueiName, list); } else { list.add(script); } } } } }
Source:
<code>public void should_not_execute_findbugs_if_no_active() throws Exception { <START> BugInstance bugInstance = getBugInstance("THIS_RULE_DOES_NOT_EXIST", 107); <END> Collection<ReportedBug> collection = Arrays.asList(new ReportedBug(bugInstance)); when(executor.execute(false, false)).thenReturn(collection); when(javaResourceLocator.classFilesToAnalyze()).thenReturn(Lists.newArrayList(new File("file"))); pico.addComponent(createRulesProfileWithActiveRules(false, false, false, false)); FindbugsSensor analyser = pico.getComponent(FindbugsSensor.class); analyser.execute(sensorContext); verify(executor, never()).execute(false, false); verify(sensorContext, never()).newIssue(); }</code><technical_language>I tests required. This test initially tested bug instance unknown id (for example a bug report is part of Sonar descriptions supported)</technical_language>

Target:
public void should_not_execute_findbugs_if_no_active() throws Exception { when(javaResourceLocator.classFilesToAnalyze()).thenReturn(Lists.newArrayList(new File("file"))); pico.addComponent(createRulesProfileWithActiveRules(false, false, false, false)); FindbugsSensor analyser = pico.getComponent(FindbugsSensor.class); analyser.execute(sensorContext); verify(executor, never()).execute(false, false); verify(sensorContext, never()).newIssue(); }
Source:
<code>public Partition(HardwareLayout hardwareLayout, JSONObject jsonObject) throws JSONException { <START> logger.trace("Partition " + jsonObject.toString()); <END> this.id = jsonObject.getLong("id"); this.partitionState = PartitionState.valueOf(jsonObject.getString("partitionState")); this.replicaCapacityInBytes = jsonObject.getLong("replicaCapacityInBytes"); this.replicas = new ArrayList<Replica>(jsonObject.getJSONArray("replicas").length()); for (int i = 0; i < jsonObject.getJSONArray("replicas").length(); ++i) { this.replicas.add(i, new Replica(hardwareLayout, this, jsonObject.getJSONArray("replicas").getJSONObject(i))); } validate(); }</code><technical_language>jsonObject.toString do string concats</technical_language>

Target:
public Partition(HardwareLayout hardwareLayout, JSONObject jsonObject) throws JSONException { if (logger.isTraceEnabled()) logger.trace("Partition " + jsonObject.toString()); this.id = jsonObject.getLong("id"); this.partitionState = PartitionState.valueOf(jsonObject.getString("partitionState")); this.replicaCapacityInBytes = jsonObject.getLong("replicaCapacityInBytes"); this.replicas = new ArrayList<Replica>(jsonObject.getJSONArray("replicas").length()); for (int i = 0; i < jsonObject.getJSONArray("replicas").length(); ++i) { this.replicas.add(i, new Replica(hardwareLayout, this, jsonObject.getJSONArray("replicas").getJSONObject(i))); } validate(); }
Source:
<code>private String translateWord(String word) { if (wordStartsWithVowelLike(word)) { return word + AY; } <START> if(hasYAfterConsonantCluster(word)){ <END> return word.substring(yLocation) + word.substring(0, yLocation) + AY; } if (wordStartsWithPrefixes(word, THR, SCH)) { return word.substring(3) + word.substring(0, 3) + AY; } if (wordStartsWithPrefixes(word, CH, QU, TH)) { return word.substring(2) + word.substring(0, 2) + AY; } if (wordStartsWithConsonantAndQu(word)) { return word.substring(3) + word.toCharArray()[0] + QUAY; } return word.substring(1) + word.toCharArray()[0] + AY; }</code><technical_language>white space if {, other if statements in this file</technical_language>

Target:
private String translateWord(String word) { if (wordStartsWithVowelLike(word)) { return word + AY; } if (getLocationOfYAfterConsonantCluster(word) != -1) { int yPos = getLocationOfYAfterConsonantCluster(word); return word.substring(yPos) + word.substring(0, yPos) + AY; } if (wordStartsWithPrefixes(word, THR, SCH)) { return word.substring(3) + word.substring(0, 3) + AY; } if (wordStartsWithPrefixes(word, CH, QU, TH)) { return word.substring(2) + word.substring(0, 2) + AY; } if (wordStartsWithConsonantAndQu(word)) { return word.substring(3) + word.toCharArray()[0] + QUAY; } return word.substring(1) + word.toCharArray()[0] + AY; }
Source:
<code>public void testKillContainer() throws Exception { sut.pull(BUSYBOX_LATEST); final ContainerConfig containerConfig = ContainerConfig.builder() .image(BUSYBOX_LATEST) .cmd("sh", "-c", "while :; do sleep 1; done") .build(); final String containerName = randomName(); final ContainerCreation containerCreation = sut.createContainer(containerConfig, containerName); final String containerId = containerCreation.id(); sut.startContainer(containerId); { final ContainerInfo containerInfo = sut.inspectContainer(containerId); assertThat(containerInfo.state().running(), equalTo(true)); } sut.killContainer(containerId); { <START> final ContainerInfo containerInfoLatest = sut.inspectContainer(containerId); <END> assertFalse(containerInfoLatest.state().running()); } }</code><technical_language>curious: wrap this in a block if names for ContainerInfo instances is name collision</technical_language>

Target:
public void testKillContainer() throws Exception { sut.pull(BUSYBOX_LATEST); final ContainerConfig containerConfig = ContainerConfig.builder() .image(BUSYBOX_LATEST) .cmd("sh", "-c", "while :; do sleep 1; done") .build(); final String containerName = randomName(); final ContainerCreation containerCreation = sut.createContainer(containerConfig, containerName); final String containerId = containerCreation.id(); sut.startContainer(containerId); final ContainerInfo containerInfo = sut.inspectContainer(containerId); assertThat(containerInfo.state().running(), equalTo(true)); sut.killContainer(containerId); final ContainerInfo containerInfoLatest = sut.inspectContainer(containerId); assertFalse(containerInfoLatest.state().running()); }
Source:
<code>public void testConcurrentUpload() throws IOException, InterruptedException, ExecutionException, TimeoutException { final int concurrency = 10; ExecutorService pool = Executors.newFixedThreadPool(concurrency); final CyclicBarrier barrier = new CyclicBarrier(concurrency); final DistributedFileSystem fs = miniCluster.getFileSystem(); final Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); List<Future<Boolean>> futures = new ArrayList<>(); for (int i = 0; i < concurrency; i++) { futures.add( pool.submit( new Callable() { @Override public Boolean call() throws Exception { int id = barrier.await(); Job job = Job.getInstance(conf, "test-job-" + id); Path intermediatePathForJob = new Path(intermediatePath, "job-" + id); <START> barrier.await(); <END> JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePathForJob, fs, job); Assert.assertTrue(fs.exists(expectedJarPath)); Assert.assertFalse(fs.exists(new Path(intermediatePathForJob, dummyJarFile.getName()))); Assert.assertEquals( expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES) ); return true; } } ) ); } for (Future<Boolean> future : futures) { Assert.assertTrue(future.get(30, TimeUnit.SECONDS)); } pool.shutdownNow(); }</code><technical_language>need await() for time</technical_language>

Target:
public void testConcurrentUpload() throws IOException, InterruptedException, ExecutionException, TimeoutException { final int concurrency = 10; ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(concurrency)); final CyclicBarrier barrier = new CyclicBarrier(concurrency); final DistributedFileSystem fs = miniCluster.getFileSystem(); final Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); List<ListenableFuture<Boolean>> futures = new ArrayList<>(); for (int i = 0; i < concurrency; i++) { futures.add( pool.submit( new Callable() { @Override public Boolean call() throws Exception { int id = barrier.await(); Job job = Job.getInstance(conf, "test-job-" + id); Path intermediatePathForJob = new Path(intermediatePath, "job-" + id); JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePathForJob, fs, job); Assert.assertTrue(fs.exists(expectedJarPath)); Assert.assertFalse(fs.exists(new Path(intermediatePathForJob, dummyJarFile.getName()))); Assert.assertEquals( expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES) ); return true; } } ) ); } Futures.allAsList(futures).get(30, TimeUnit.SECONDS); pool.shutdownNow(); }
Source:
<code>protected void doRun() { AtomicInteger runningCallsCount = new AtomicInteger(); AtomicInteger queuedCallsCount = new AtomicInteger(); KubernetesClientProvider.clients.asMap().forEach((s, client) -> { KubernetesClient kClient = client.getClient(); if (kClient instanceof HttpClientAware) { OkHttpClient httpClient = ((HttpClientAware) kClient).getHttpClient(); Dispatcher dispatcher = httpClient.dispatcher(); runningCallsCount.addAndGet(dispatcher.runningCallsCount()); <START> queuedCallsCount.addAndGet(dispatcher.queuedCallsCount()); <END> } }); KubernetesClientProvider.runningCallsCount = runningCallsCount.get(); KubernetesClientProvider.queuedCallsCount = queuedCallsCount.get(); }</code><technical_language>Easier a plain for loop local int variables</technical_language>

Target:
protected void doRun() { int runningCallsCount = 0; int queuedCallsCount = 0; for (Client client : KubernetesClientProvider.clients.asMap().values()) { KubernetesClient kClient = client.getClient(); if (kClient instanceof HttpClientAware) { OkHttpClient httpClient = ((HttpClientAware) kClient).getHttpClient(); Dispatcher dispatcher = httpClient.dispatcher(); runningCallsCount += dispatcher.runningCallsCount(); queuedCallsCount += dispatcher.queuedCallsCount(); } } KubernetesClientProvider.runningCallsCount = runningCallsCount; KubernetesClientProvider.queuedCallsCount = queuedCallsCount; }
Source:
<code>private void visitIfStatement(IfStatementTree tree) { PhpCfgBlock successor = currentBlock; PhpCfgBlock elseBlock = currentBlock; buildSubFlow(tree.statements(), successor); PhpCfgBlock thenBlock = currentBlock; PhpCfgBranchingBlock branchingBlock = createBranchingBlock(tree, thenBlock, elseBlock); <START> currentBlock = branchingBlock; <END> }</code><technical_language>add condition element of this block</technical_language>

Target:
private void visitIfStatement(IfStatementTree tree) { PhpCfgBlock successor = currentBlock; PhpCfgBlock elseBlock = currentBlock; buildSubFlow(tree.statements(), successor); PhpCfgBlock thenBlock = currentBlock; currentBlock = createBranchingBlock(tree, thenBlock, elseBlock); currentBlock.addElement(tree.condition().expression()); }
Source:
<code><START> public APIResult submitAndSchedule( <END> @PathParam("extension-name") String extensionName, @Context HttpServletRequest request, @DefaultValue("") @QueryParam("doAs") String doAsUser, @QueryParam("jobName") String jobName, @FormDataParam("entities") List<Entity> entities, @FormDataParam("config") InputStream config) { checkIfExtensionServiceIsEnabled(); try { ExtensionType extensionType = getExtensionType(extensionName); if (ExtensionType.TRUSTED.equals(extensionType)) { entities = generateEntities(extensionName, request); } List<String> entityNames = new ArrayList<>(); validateEntities(entities); for (Entity entity : entities) { submitInternal(entity, doAsUser); entityNames.add(entity.getName()); } ExtensionMetaStore metaStore = org.apache.falcon.extensions.store.ExtensionStore.get().getMetaStore(); metaStore.storeExtensionJob(jobName, extensionName, extensionType, entityNames, null); for (Entity entity : entities) { scheduleInternal(entity.getEntityType().name(), entity.getName(), null, null); } } catch (FalconException | IOException e) { LOG.error("Error when submitting extension job: ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } return new APIResult(APIResult.Status.SUCCEEDED, "Extension job submitted and scheduled successfully"); }</code><technical_language>a common submit method submit submitAndSchedule use</technical_language>

Target:
public APIResult submitAndSchedule( @PathParam("extension-name") String extensionName, @Context HttpServletRequest request, @DefaultValue("") @QueryParam("doAs") String doAsUser, @QueryParam("jobName") String jobName, @FormDataParam("entities") List<Entity> entities, @FormDataParam("config") InputStream config) { checkIfExtensionServiceIsEnabled(); try { entities = getEntityList(extensionName, entities, config); submitEntities(extensionName, doAsUser, jobName, entities, config); for (Entity entity : entities) { scheduleInternal(entity.getEntityType().name(), entity.getName(), null, null); } } catch (FalconException | IOException e) { LOG.error("Error when submitting extension job: ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } return new APIResult(APIResult.Status.SUCCEEDED, "Extension job submitted and scheduled successfully"); }
Source:
<code><START> private void handeLogin(ClickEvent<Button> buttonClickEvent) { <END> clearMessage(); if (login.isEmpty() || password.isEmpty()) { setMessage("All fields are required."); } if (!"admin".equals(login.getValue()) && !"user" .equals(login.getValue())) { setMessage("Faulty username or password!"); return; } ((HttpServletRequest) VaadinRequest.getCurrent()).changeSessionId(); RouteRegistry sessionRegistry = SessionRouteRegistry .getSessionRegistry(VaadinSession.getCurrent()); if ("admin".equals(login.getValue())) { RouteUtil.setAnnotatedRoute(AdminView.class, sessionRegistry); } else if ("user".equals(login.getValue())) { RouteUtil.setAnnotatedRoute(UserView.class, sessionRegistry); } RouteUtil.setRoute("version", VersionView.class, sessionRegistry); sessionRegistry.setRoute("time", TimeView.class, Arrays.asList(LooseCenterLayout.class, MainLayout.class)); UI.getCurrent().getPage().reload(); }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Remove this unused method parameter "buttonClickEvent". [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private void handeLogin(ClickEvent<Button> buttonClickEvent) { clearMessage(); if (login.isEmpty() || password.isEmpty()) { setMessage("All fields are required."); } if (!"admin".equals(login.getValue()) && !"user" .equals(login.getValue())) { setMessage("Faulty username or password!"); return; } ((HttpServletRequest) VaadinRequest.getCurrent()).changeSessionId(); RouteConfiguration session = RouteConfiguration.forSessionScope(); if ("admin".equals(login.getValue())) { session.setAnnotatedRoute(AdminView.class); } else if ("user".equals(login.getValue())) { session.setAnnotatedRoute(UserView.class); } session.setParentAnnotatedRoute("version", VersionView.class); session.setRoute("time", TimeView.class, LooseCenterLayout.class, MainLayout.class); UI.getCurrent().getPage().reload(); }
Source:
<code>private Expression assignmentExpression(AstNode astNode) { AstNode nameNode = astNode.getFirstChild(PythonGrammar.TEST); Name name = name(nameNode.getFirstDescendant(PythonGrammar.NAME)); <START> AstNode walrusNode = nameNode.getNextSibling(); <END> Token walrusToken = toPyToken(walrusNode.getToken()); Expression expression = expression(walrusNode.getNextSibling()); return new AssignmentExpressionImpl(name, walrusToken, expression); }</code><technical_language>getNextSibling, I astNode.getFirstChild(PythonPunctuator.WALRUS_OPERATOR)</technical_language>

Target:
private Expression assignmentExpression(AstNode astNode) { AstNode nameNode = astNode.getFirstChild(PythonGrammar.TEST); Expression nameExpression = expression(nameNode); if (!nameExpression.is(Tree.Kind.NAME)) { int line = nameNode.getTokenLine(); throw new RecognitionException(line, "Parse error at line " + line + ": The left-hand side of an assignment expression must be a name."); } Name name = (Name) nameExpression; AstNode operatorNode = astNode.getFirstChild(PythonPunctuator.WALRUS_OPERATOR); Token operatorToken = toPyToken(operatorNode.getToken()); Expression expression = expression(astNode.getLastChild(PythonGrammar.TEST)); return new AssignmentExpressionImpl(name, operatorToken, expression); }
Source:
<code><START> public Set<String> done(){ <END> ParametrizedTypeJavaType.typeSubstitutionSolver = null; bytecodeCompleter.done(); return bytecodeCompleter.classesNotFound(); }</code><technical_language>I this returned value. I prefer a dedicated object errors related semantic model, if (at first? for time being?) contains classes found</technical_language>

Target:
public void done(){ ParametrizedTypeJavaType.typeSubstitutionSolver = null; bytecodeCompleter.done(); }
Source:
<code>public void deleteBucketAcl() throws IOException, SignatureException { PutBucketAclForUserSpectraS3Response putBucketAclForUserSpectraS3Response = null; try { putBucketAclForUserSpectraS3Response = client.putBucketAclForUserSpectraS3( new PutBucketAclForUserSpectraS3Request(BUCKET_NAME, BucketAclPermission.DELETE, spectraUUID)); final DeleteBucketAclSpectraS3Response deleteBucketAclSpectraS3Response = client .deleteBucketAclSpectraS3(new DeleteBucketAclSpectraS3Request( putBucketAclForUserSpectraS3Response.getBucketAclResult().getId().toString())); assertThat(deleteBucketAclSpectraS3Response.getStatusCode(), is(204)); } catch (final Exception e){ <START> if (putBucketAclForUserSpectraS3Response != null) { <END> client.deleteBucketAclSpectraS3(new DeleteBucketAclSpectraS3Request( putBucketAclForUserSpectraS3Response.getBucketAclResult().getId().toString())); } throw e; } }</code><technical_language>Is a reason a catch block is instead of a finally block</technical_language>

Target:
public void deleteBucketAcl() throws IOException, SignatureException { PutBucketAclForUserSpectraS3Response putBucketAclForUserSpectraS3Response = null; try { putBucketAclForUserSpectraS3Response = client.putBucketAclForUserSpectraS3( new PutBucketAclForUserSpectraS3Request(BUCKET_NAME, BucketAclPermission.DELETE, spectraUUID)); final DeleteBucketAclSpectraS3Response deleteBucketAclSpectraS3Response = client .deleteBucketAclSpectraS3(new DeleteBucketAclSpectraS3Request( putBucketAclForUserSpectraS3Response.getBucketAclResult().getId().toString())); assertThat(deleteBucketAclSpectraS3Response.getStatusCode(), is(204)); } finally { if (putBucketAclForUserSpectraS3Response != null) { client.deleteBucketAclSpectraS3(new DeleteBucketAclSpectraS3Request( putBucketAclForUserSpectraS3Response.getBucketAclResult().getId().toString())); } } }
Source:
<code>protected static BiConsumer<Map<String, Object>, Integer> toLoaderEnrichedOnError( Consumer<Map<String, Object>> loader) { return (map, lineno) -> { try { loader.accept(map); } catch (DirectoryException e) { <START> e.addInfo(String.format("Exception: %s happened on line: %s", e.getMessage(), lineno)); <END> throw e; } }; }</code><technical_language>I do e.addInfo("At line: " + lineno) exception message is in exception itself</technical_language>

Target:
protected static BiConsumer<Map<String, Object>, Integer> toLoaderEnrichedOnError( Consumer<Map<String, Object>> loader) { return (map, lineno) -> { try { loader.accept(map); } catch (DirectoryException e) { e.addInfo("At line: " + lineno); throw e; } }; }
Source:
<code>public void resizeVideoWithSetting() { int resizeNumber = 250; String articleName = PageContent.ARTICLE_NAME_PREFIX + DateTime.now().getMillis(); VisualEditorPageObject ve = new VisualEditorPageObject(driver).openVEOnArticle(wikiURL, articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); VisualEditorAddMediaDialog mediaDialog = ve.clickVideoButton(); mediaDialog = mediaDialog.searchMedia("h"); ve = mediaDialog.addExistingMedia(1); ve.verifyVideos(1); Dimension source = ve.getVideoDimension(); ve.selectMedia(); VisualEditorMediaSettingsDialog mediaSettingsDialog = ve.openMediaSettings(); mediaSettingsDialog.selectSettings(Setting.ADVANCED); mediaSettingsDialog.setCustomSize(resizeNumber, ImageSize.WIDTH); mediaSettingsDialog.clickApplyChangesButton(); ve.verifyVideoResized(source); source = ve.getVideoDimension(); mediaSettingsDialog = ve.openMediaSettings(); mediaSettingsDialog.selectSettings(Setting.ADVANCED); mediaSettingsDialog.setCustomSize(resizeNumber, ImageSize.HEIGHT); mediaSettingsDialog.clickApplyChangesButton(); ve.verifyVideoResized(source); VisualEditorSaveChangesDialog save = ve.clickPublishButton(); ArticlePageObject article = save.savePage(); <START> article.verifyVEPublishComplete(); <END> }</code><technical_language>I try divide code meaningful chunks (small methods is method name)</technical_language>

Target:
public void resizeVideoWithSetting() { int resizeNumber = 250; String articleName = PageContent.ARTICLE_NAME_PREFIX + DateTime.now().getMillis(); VisualEditorPageObject ve = new VisualEditorPageObject(driver).openVEOnArticle(wikiURL, articleName); VisualEditorAddMediaDialog mediaDialog = ve.searchVideo("h"); ve = mediaDialog.addExistingMedia(1); ve.verifyVideos(1); Dimension source = ve.getVideoDimension(); ve.selectMedia(); ve.resizeMedia(resizeNumber, ImageSize.WIDTH); ve.verifyVideoResized(source); source = ve.getVideoDimension(); ve.resizeMedia(resizeNumber, ImageSize.HEIGHT); ve.verifyVideoResized(source); ve.publish(); }
Source:
<code>public Object getAdapter(Object element, Class key) { <START> BtfEvent tmfEvent = (BtfEvent) element; <END> if (IPropertySource.class.equals(key)) { return new BtfEventPropertySource(tmfEvent); } return null; }</code><technical_language>Type checked casting</technical_language>

Target:
public Object getAdapter(Object element, Class key) { if (element instanceof BtfEvent && IPropertySource.class.equals(key)) { BtfEvent tmfEvent = (BtfEvent) element; return new BtfEventPropertySource(tmfEvent); } return null; }
Source:
<code>public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ImportOrderCheck.class); final String[] expected = { "18: " + getCheckMessage(MSG_SEPARATED_IN_GROUP, <START> "sun.tools.util.ModifierFilter.ALL_ACCESS"), <END> "5: " + getCheckMessage(MSG_ORDERING, "java.awt.Dialog"), "9: " + getCheckMessage(MSG_ORDERING, "javax.swing.JComponent"), "11: " + getCheckMessage(MSG_ORDERING, "java.io.File"), "13: " + getCheckMessage(MSG_ORDERING, "java.io.IOException"), }; verify(checkConfig, getPath("InputImportOrder.java"), expected); }</code><technical_language>Please line numbers ordered</technical_language>

Target:
public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ImportOrderCheck.class); final String[] expected = { "5: " + getCheckMessage(MSG_ORDERING, "java.awt.Dialog"), "9: " + getCheckMessage(MSG_ORDERING, "javax.swing.JComponent"), "11: " + getCheckMessage(MSG_ORDERING, "java.io.File"), "13: " + getCheckMessage(MSG_ORDERING, "java.io.IOException"), "18: " + getCheckMessage(MSG_SEPARATED_IN_GROUP, "sun.tools.util.ModifierFilter.ALL_ACCESS"), }; verify(checkConfig, getPath("InputImportOrder.java"), expected); }
Source:
<code>public TestMediaWikiApiImageFetchingStrategy(Map<String, String> serverContent) { this.serverContent = <START> serverContent; <END> }</code><technical_language>Consider ImmutableMap.copyOf avoid side-effects</technical_language>

Target:
public TestMediaWikiApiImageFetchingStrategy(Map<String, String> serverContent) { Preconditions.checkNotNull(serverContent, "Please specify some server content for images used during the tests. See: TestMediaWikiApiImageFetchingStrategy#serverContent"); this.serverContent = ImmutableMap.copyOf(serverContent); }
Source:
<code>switch (logger) { case "slf4j": setLoggerAdapter(new Slf4jLoggerAdapter()); break; case "jcl": setLoggerAdapter(new JclLoggerAdapter()); break; case "log4j": setLoggerAdapter(new Log4jLoggerAdapter()); break; case "jdk": setLoggerAdapter(new JdkLoggerAdapter()); break; case "log4j2": setLoggerAdapter(new Log4j2LoggerAdapter()); break; default: List<Class<? extends LoggerAdapter>> candidates = Arrays.asList( Log4jLoggerAdapter.class, Slf4jLoggerAdapter.class, Log4j2LoggerAdapter.class, JclLoggerAdapter.class, JdkLoggerAdapter.class ); for (Class<? extends LoggerAdapter> clazz : candidates) { try { setLoggerAdapter(clazz.newInstance()); break; } catch (Throwable ignored) { } } <START> break; <END> }</code><technical_language>need break in default</technical_language>

Target:
switch (logger) { case "slf4j": setLoggerAdapter(new Slf4jLoggerAdapter()); break; case "jcl": setLoggerAdapter(new JclLoggerAdapter()); break; case "log4j": setLoggerAdapter(new Log4jLoggerAdapter()); break; case "jdk": setLoggerAdapter(new JdkLoggerAdapter()); break; case "log4j2": setLoggerAdapter(new Log4j2LoggerAdapter()); break; default: List<Class<? extends LoggerAdapter>> candidates = Arrays.asList( Log4jLoggerAdapter.class, Slf4jLoggerAdapter.class, Log4j2LoggerAdapter.class, JclLoggerAdapter.class, JdkLoggerAdapter.class ); for (Class<? extends LoggerAdapter> clazz : candidates) { try { setLoggerAdapter(clazz.newInstance()); break; } catch (Throwable ignored) { } } }
Source:
<code>public TriggerBasedScheduleLoader(final TriggerManager triggerManager) { this.triggerManager = triggerManager; <START> this.triggerSource = ScheduleManager.triggerSource; <END> }</code><technical_language>Guice inject ScheduleManager if a parameter of TriggerBasedScheduleLoader</technical_language>

Target:
public TriggerBasedScheduleLoader(final TriggerManager triggerManager) { this.triggerManager = triggerManager; this.triggerSource = ScheduleManager.SIMPLE_TIME_TRIGGER; }
Source:
<code>private void exit() { process.destroy(); try { process.waitFor(); } catch ( InterruptedException ex ) { <START> Thread.currentThread().interrupt(); <END> throw new RuntimeException( "Interrupted whilst waiting for forced stub shutdown", ex); } }</code><technical_language>interrupting current thread in interrupted block</technical_language>

Target:
private void exit() { process.destroy(); try { process.waitFor(); } catch ( InterruptedException ex ) { throw new RuntimeException( "Interrupted whilst waiting for forced stub shutdown", ex); } }
Source:
<code>WorkbenchConfigurer getWorkbenchConfigurer() { if (workbenchConfigurer == null) { <START> workbenchConfigurer = new WorkbenchConfigurer(e4Context); <END> } return workbenchConfigurer; }</code><technical_language>thinking create object DI: workbenchConfigurer = ContextInjectionFactory.make(WorkbenchConfigurer.class, e4Context);</technical_language>

Target:
WorkbenchConfigurer getWorkbenchConfigurer() { if (workbenchConfigurer == null) { workbenchConfigurer = ContextInjectionFactory.make(WorkbenchConfigurer.class, e4Context); } return workbenchConfigurer; }
Source:
<code><START> public <T> Configuration getEffectiveConfiguration( <END> final CustomCommandLine activeCustomCommandLine, final CommandLine commandLine, final ProgramOptions programOptions, final List<T> jobJars) throws FlinkException { final ExecutionConfigAccessor executionParameters = ExecutionConfigAccessor.fromProgramOptions( checkNotNull(programOptions), checkNotNull(jobJars)); final Configuration executorConfig = checkNotNull(activeCustomCommandLine) .applyCommandLineOptionsToConfiguration(commandLine); final Configuration effectiveConfiguration = new Configuration(executorConfig); executionParameters.applyToConfiguration(effectiveConfiguration); LOG.debug("Effective executor configuration: {}", effectiveConfiguration); return effectiveConfiguration; }</code><technical_language>this package-private public. annotate @VisibleForTesting</technical_language>

Target:
private <T> Configuration getEffectiveConfiguration( final CustomCommandLine activeCustomCommandLine, final CommandLine commandLine, final ProgramOptions programOptions, final List<T> jobJars) throws FlinkException { final ExecutionConfigAccessor executionParameters = ExecutionConfigAccessor.fromProgramOptions( checkNotNull(programOptions), checkNotNull(jobJars)); final Configuration executorConfig = checkNotNull(activeCustomCommandLine) .applyCommandLineOptionsToConfiguration(commandLine); final Configuration effectiveConfiguration = new Configuration(executorConfig); executionParameters.applyToConfiguration(effectiveConfiguration); LOG.debug("Effective executor configuration: {}", effectiveConfiguration); return effectiveConfiguration; }
Source:
<code>public AdminSourcePollerServiceBean(ConfigurationAdmin configurationAdmin) { <START> bundleContext = getBundleContext(); <END> this.configurationAdmin = configurationAdmin; mBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objName = null; try { objName = new ObjectName(AdminSourcePollerServiceBean.class.getName() + SERVICE_NAME); } catch (MalformedObjectNameException e) { LOGGER.error("Unable to create Admin Source Poller Service MBean with name [{}].", AdminSourcePollerServiceBean.class.getName() + SERVICE_NAME, e); } objectName = objName; }</code><technical_language>cache bundleContext. stale throw exceptions. call getBundleContext want it</technical_language>

Target:
public AdminSourcePollerServiceBean(ConfigurationAdmin configurationAdmin) { helper = getHelper(); helper.configurationAdmin = configurationAdmin; mBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objName = null; try { objName = new ObjectName(AdminSourcePollerServiceBean.class.getName() + SERVICE_NAME); } catch (MalformedObjectNameException e) { LOGGER.error("Unable to create Admin Source Poller Service MBean with name [{}].", AdminSourcePollerServiceBean.class.getName() + SERVICE_NAME, e); } objectName = objName; }