auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void clear(String sourceId) { Verify.verifyNotNull(sourceId, "argument 'sourceId' may not be null."); for (Iterator<ServiceRegistration<MetacardType>> iter = serviceRegistrations.iterator(); iter.hasNext(); ) { ServiceRegistration registration = iter.next(); if (registration.getReference() != null <START> && registration.getReference().getProperty((SOURCE_ID)) != null <END> && registration.getReference().getProperty(SOURCE_ID).equals(sourceId)) { registration.unregister(); iter.remove(); } } }</code><technical_language>Extra parentheses</technical_language>

Target:
public void clear(String sourceId) { Verify.verifyNotNull(sourceId, "argument 'sourceId' may not be null."); try { registryLock.lock(); for (Iterator<ServiceRegistration<MetacardType>> iter = serviceRegistrations.iterator(); iter.hasNext(); ) { ServiceRegistration registration = iter.next(); if (registration.getReference() != null && registration.getReference().getProperty(SOURCE_ID).equals(sourceId)) { registration.unregister(); iter.remove(); } } } finally { registryLock.unlock(); } }
Source:
<code>public static boolean isSupported(AST ast, int nodeType) { switch (nodeType) { case ASTNode.SWITCH_EXPRESSION: case ASTNode.YIELD_STATEMENT: if (ast.apiLevel() < AST.JLS14_INTERNAL) { return false; } break; case ASTNode.TEXT_BLOCK: <START> if (!ast.isPreviewEnabled()) { <END> return false; } } return true; }</code><technical_language>return ast.isPreviewEnabled() ; However, is a reason for skipping ast.apiLevel() == AST.JLS14_INTERNAL? [Consider case this is called <14 levels]</technical_language>

Target:
public static boolean isSupported(AST ast, int nodeType) { switch (nodeType) { case ASTNode.SWITCH_EXPRESSION: case ASTNode.YIELD_STATEMENT: if (ast.apiLevel() < AST.JLS14_INTERNAL) { return false; } break; case ASTNode.TEXT_BLOCK: return ast.isPreviewEnabled(); } return true; }
Source:
<code>public void testBlockingExecutorService() throws Exception { final int capacity = 3; final ExecutorService executorService = Execs.blockingSingleThreaded("test%d", capacity); final AtomicInteger producedCount = new AtomicInteger(); final AtomicInteger consumedCount = new AtomicInteger(); final CyclicBarrier barrier = new CyclicBarrier(2); Thread producer = new Thread("producer") { public void run() { for (int i = 0; i < 2 * capacity; i++) { final int taskID = i; System.out.println("Produced task"+ taskID); executorService.submit( new Runnable() { @Override public void run() { System.out.println("Starting task" + taskID); try { barrier.await(); } catch (Exception e) { throw Throwables.propagate(e); } consumedCount.incrementAndGet(); System.out.println("Completed task" + taskID); } } ); producedCount.incrementAndGet(); } } }; producer.start(); for(int i=0;i<capacity;i++){ <START> Thread.sleep(500); <END> Assert.assertEquals(consumedCount.intValue()+1+capacity,producedCount.intValue()); barrier.await(); } for(int i=0;i<capacity;i++){ barrier.await(); } }</code><technical_language>in general I UTs complete in < 1s</technical_language>

Target:
public void testBlockingExecutorService() throws Exception { final int capacity = 3; final ExecutorService blockingExecutor = Execs.newBlockingSingleThreaded("test%d", capacity); final CountDownLatch queueFullSignal = new CountDownLatch(capacity + 1); final CountDownLatch taskCompletedSignal = new CountDownLatch(2 * capacity); final CountDownLatch taskStartSignal = new CountDownLatch(1); final AtomicInteger producedCount = new AtomicInteger(); final AtomicInteger consumedCount = new AtomicInteger(); ExecutorService producer = Executors.newSingleThreadExecutor(); producer.submit( new Runnable() { public void run() { for (int i = 0; i < 2 * capacity; i++) { final int taskID = i; System.out.println("Produced task" + taskID); blockingExecutor.submit( new Runnable() { @Override public void run() { System.out.println("Starting task" + taskID); try { taskStartSignal.await(); consumedCount.incrementAndGet(); taskCompletedSignal.countDown(); } catch (Exception e) { throw Throwables.propagate(e); } System.out.println("Completed task" + taskID); } } ); producedCount.incrementAndGet(); queueFullSignal.countDown(); } } } ); queueFullSignal.await(); Assert.assertEquals(capacity + 1, producedCount.get()); taskStartSignal.countDown(); taskCompletedSignal.await(); Assert.assertEquals(2 * capacity, consumedCount.get()); blockingExecutor.shutdown(); producer.shutdown(); }
Source:
<code>public ArtifactInputStream getInputStream(String storageId, String repositoryId, String path) throws IOException { Repository repository = getConfiguration().getStorage(storageId).getRepository(repositoryId); final LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); final RepositoryPath artifactPath = layoutProvider.resolve(repository).resolve(path); logger.debug(" -> Checking local cache for ...", artifactPath); if (layoutProvider.containsPath(repository, path)) { logger.debug("The artifact was found in the local cache", artifactPath); return (ArtifactInputStream) Files.newInputStream(artifactPath); } <START> logger.debug("The artifact as not found in the local cache", artifactPath); <END> return null; }</code><technical_language>typo,</technical_language>

Target:
public ArtifactInputStream getInputStream(String storageId, String repositoryId, String path) throws IOException { Repository repository = getConfiguration().getStorage(storageId).getRepository(repositoryId); final LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); final RepositoryPath artifactPath = layoutProvider.resolve(repository).resolve(path); logger.debug(" -> Checking local cache for ...", artifactPath); if (layoutProvider.containsPath(repository, path)) { logger.debug("The artifact was found in the local cache", artifactPath); return (ArtifactInputStream) Files.newInputStream(artifactPath); } logger.debug("The artifact was not found in the local cache", artifactPath); return null; }
Source:
<code>public CompletableFuture<Void> modifyColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) { return CompletableFuture.supplyAsync(() -> { return Modification.newBuilder() .setId(columnFamilyDesc.getNameAsString()) .setCreate(new ColumnDescriptorAdapter().adapt((HColumnDescriptor) columnFamilyDesc) .build()); }).thenCompose( <START> d -> modifyColumn(tableName, columnFamilyDesc.getNameAsString(), "update", d)). <END> thenApply(r -> null); }</code><technical_language>rename d descriptor</technical_language>

Target:
public CompletableFuture<Void> modifyColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) { return CompletableFuture.supplyAsync(() -> { return Modification.newBuilder() .setId(columnFamilyDesc.getNameAsString()) .setCreate(new ColumnDescriptorAdapter().adapt((HColumnDescriptor) columnFamilyDesc) .build()); }).thenCompose( descriptor -> modifyColumn(tableName, columnFamilyDesc.getNameAsString(), "update", descriptor)). thenApply(response -> null); }
Source:
<code>private Object getResultElementItem(DelegateExecution childExecution) { CommandContext commandContext = Context.getCommandContext(); if (commandContext.getCommand() instanceof CompleteTaskCmd) { <START> Map<String, Object> taskVariables = ((CompleteTaskCmd) commandContext <END> .getCommand()).getTaskVariables(); return taskVariables.get(getOutputDataItem()); } return childExecution.getVariable(getOutputDataItem()); }</code><technical_language>for CompleteTaskCmd</technical_language>

Target:
private Object getResultElementItem(DelegateExecution childExecution) { CommandContext commandContext = Context.getCommandContext(); if (commandContext.getCommand() instanceof CompleteTaskCmd) { Map<String, Object> taskVariables = ((CompleteTaskCmd) commandContext .getCommand()).getTaskVariables(); return taskVariables.get(getOutputDataItem()); } return childExecution.getVariableLocal(getOutputDataItem()); }
Source:
<code>protected void endWithFailure() { revertTasks(); if (getDestinationDiskImage() != null && !vmDao.getVmsListForDisk(getDestinationDiskImage().getId(), false).isEmpty()) { if (!getDestinationDiskImage().getParentId().equals(Guid.Empty)) { if (!getDestinationDiskImage().getParentId().equals(getDestinationDiskImage().getImageTemplateId())) { DiskImage previousSnapshot = diskImageDao.getSnapshotById(getDestinationDiskImage().getParentId()); previousSnapshot.setActive(true); if (getParameters().getOldLastModifiedValue() != null) { previousSnapshot.setLastModified(getParameters().getOldLastModifiedValue()); } imageDao.update(previousSnapshot.getImage()); } } } <START> runVdsCommand(VDSCommandType.DestroyImage, <END> createDestroyImageParameters()); super.endWithFailure(); }</code><technical_language>1. if getDestinationDiskImage() == null ? 2. happen if DestryImage command fails? this break flow</technical_language>

Target:
protected void endWithFailure() { revertTasks(); if (getDestinationDiskImage() != null && !vmDao.getVmsListForDisk(getDestinationDiskImage().getId(), false).isEmpty()) { if (!getDestinationDiskImage().getParentId().equals(Guid.Empty)) { if (!getDestinationDiskImage().getParentId().equals(getDestinationDiskImage().getImageTemplateId())) { DiskImage previousSnapshot = diskImageDao.getSnapshotById(getDestinationDiskImage().getParentId()); previousSnapshot.setActive(true); if (getParameters().getOldLastModifiedValue() != null) { previousSnapshot.setLastModified(getParameters().getOldLastModifiedValue()); } imageDao.update(previousSnapshot.getImage()); } } runVdsCommand(VDSCommandType.DestroyImage, createDestroyImageParameters()); } super.endWithFailure(); }
Source:
<code>public T thisNode() { <START> <END> return curNode; }</code><technical_language>change this logic: is essential for traversing a changed tree</technical_language>

Target:
public T thisNode() { assertFalse(this.nodeDeleted, "node is deleted"); if (newNode != null) { return newNode; } return curNode; }
Source:
<code>private static boolean importsManipulatedAllProperty(FileInput fileInput) { <START> return fileInput.globalVariables().stream().anyMatch(s -> s.name().equals("__all__") && s.usages().stream().anyMatch(u -> u.kind().equals(Usage.Kind.IMPORT))); <END> }</code><technical_language>_nitpick_ I prefer avoid nesting anyMatch a loop for global variables, a personal preference, feel free disregard</technical_language>

Target:
private static boolean importsManipulatedAllProperty(FileInput fileInput) { return fileInput.globalVariables().stream() .filter(s -> s.name().equals("__all__")) .flatMap(s -> s.usages().stream()) .anyMatch(u -> u.kind() == Usage.Kind.IMPORT); }
Source:
<code>protected boolean createKeys(List<Long> list) { if (skCase == null) { return true; } hashsetResults.getArtifactIds(hashsetName).forEach((id) -> { try { BlackboardArtifact art = skCase.getBlackboardArtifact(id); artifactHits.put(id, art); list.add(id); <START> } catch (TskException ex) { <END> logger.log(Level.WARNING, "TSK Exception occurred", ex); } }); return true; }</code><technical_language>this is a case database error, please change log level SEVERE instead of WARNING, while in this code</technical_language>

Target:
protected boolean createKeys(List<Long> list) { if (skCase == null) { return true; } hashsetResults.getArtifactIds(hashsetName).forEach((id) -> { try { BlackboardArtifact art = skCase.getBlackboardArtifact(id); artifactHits.put(id, art); list.add(id); } catch (TskException ex) { logger.log(Level.SEVERE, "TSK Exception occurred", ex); } }); return true; }
Source:
<code>public String getModuleNameForEntry(Entry entry) { Vector<Suite> installed = getInstalledSuites(); for (Suite s : installed) { for (Entry suiteEntry : s.getEntries().values()) { if (suiteEntry.getCommandId().equals(entry.getCommandId())) { <START> return s.getMenus().firstElement().getId(); <END> } } } return null; }</code><technical_language>HQ app builder support this, put <entry> number of modules/menus, is super helpful for cases</technical_language>

Target:
public String getModuleNameForEntry(Entry entry) { Vector<Suite> installed = getInstalledSuites(); for (Suite suite : installed) { for (Entry suiteEntry : suite.getEntries().values()) { if (suiteEntry.getCommandId().equals(entry.getCommandId())) { return suite.getMenus().firstElement().getId(); } } } return null; }
Source:
<code>public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { <START> Assert.notNull(context, "context cannot be null"); <END> final List<OAuth2AuthorizedClient> clients = new ArrayList<>(); for (OAuth2AuthorizedClientProvider authorizedClientProvider: authorizedClientProviders) { final OAuth2AuthorizedClient auth2AuthorizedClient = authorizedClientProvider.authorize(context); if (auth2AuthorizedClient != null) { clients.add(auth2AuthorizedClient); } } if (!clients.isEmpty()) { return clients.get(0); } else { return null; } }</code><technical_language>need for a list. return null</technical_language>

Target:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); for (OAuth2AuthorizedClientProvider authorizedClientProvider : authorizedClientProviders) { OAuth2AuthorizedClient oauth2AuthorizedClient = authorizedClientProvider.authorize(context); if (oauth2AuthorizedClient != null) { return oauth2AuthorizedClient; } } return null; }
Source:
<code>private void setupHooks() { <START> varNames.addListener(new ChangeListener() { <END> @Override public void changed(ChangeEvent event, Actor actor) { if (varNames.getSelectedIndex() != -1) { String val = vars.getStringVariable(varNames.getSelected()); varName.setText(varNames.getSelected()); varVal.setText(val); } else { varName.setText(""); varVal.setText(""); } } }); changeName.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { DialogUtils.showInputDialog(getStage(), "New Name for Variable", "Name:", new InputDialogAdapter() { @Override public void finished(String input) { vars.removeVariable(varName.getText()); vars.setVariable(input, varVal.getText()); renderNames(); varNames.setSelected(input); varName.setText(input); } }); } }); updateValue.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { vars.setVariable(varName.getText(),varVal.getText()); } }); deleteVar.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { vars.removeVariable(varName.getText()); varName.setText(""); varVal.setText(""); renderNames(); varNames.setSelectedIndex(-1); } }); addVar.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { vars.setVariable(keyName.getText(), keyVal.getText()); keyName.setText(""); keyVal.setText(""); renderNames(); varNames.setSelectedIndex(-1); } }); }</code><technical_language>changing variable, need "update" item, calling item.updateDataVO();</technical_language>

Target:
private void setupHooks() { varNames.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (varNames.getSelectedIndex() != -1) { String val = vars.getStringVariable(varNames.getSelected()); varName.setText(varNames.getSelected()); varVal.setText(val); } else { varName.setText(""); varVal.setText(""); } } }); changeName.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { DialogUtils.showInputDialog(getStage(), "New Name for Variable", "Name:", new InputDialogAdapter() { @Override public void finished(String input) { vars.removeVariable(varName.getText()); vars.setVariable(input, varVal.getText()); item.updateDataVO(); renderNames(); varNames.setSelected(input); varName.setText(input); } }); } }); updateValue.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { vars.setVariable(varName.getText(),varVal.getText()); item.updateDataVO(); } }); deleteVar.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { vars.removeVariable(varName.getText()); item.updateDataVO(); varName.setText(""); varVal.setText(""); renderNames(); varNames.setSelectedIndex(-1); } }); addVar.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { vars.setVariable(keyName.getText(), keyVal.getText()); item.updateDataVO(); keyName.setText(""); keyVal.setText(""); renderNames(); varNames.setSelectedIndex(-1); } }); }
Source:
<code>public static void onBarcodeResult(BarcodeScanListener barcodeScanListener, int requestCode, int resultCode, Intent intent) { if (BuildConfig.DEBUG) { <START> if (!(requestCode == BARCODE_FETCH)) { <END> throw new IllegalArgumentException("requestCode should've been BARCODE_FETCH!"); } } if (resultCode == Activity.RESULT_OK) { String result = intent.getStringExtra("SCAN_RESULT"); barcodeScanListener.onBarcodeFetch(result, intent); } }</code><technical_language>This true call of onBarcodeResult is preceded a check resultCode == BARCODE_FETCH. vote is remove this adds clutter code read</technical_language>

Target:
public static void onBarcodeResult(BarcodeScanListener barcodeScanListener, int requestCode, int resultCode, Intent intent) { if (BuildConfig.DEBUG && !(requestCode == BARCODE_FETCH)) { throw new AssertionError("requestCode should be BARCODE_FETCH!"); } if (resultCode == Activity.RESULT_OK) { String result = intent.getStringExtra(SCAN_RESULT); barcodeScanListener.onBarcodeFetch(result, intent); } }
Source:
<code>public IConnectionWrapper getConnection() throws CoreException { <START> HashMap<String,Object> map = new HashMap<String,Object>(); <END> map.put(JolokiaConnectionWrapper.ID, name); map.put(JolokiaConnectionWrapper.URL, url); map.put(JolokiaConnectionWrapper.HEADERS, headers); map.put(JolokiaConnectionWrapper.IGNORE_SSL_ERRORS, ignoreSSL); map.put(JolokiaConnectionWrapper.GET_OR_POST, getOrPost); IConnectionProvider provider = ExtensionManager.getProvider(JolokiaConnectionProvider.PROVIDER_ID); return provider.createConnection(map); }</code><technical_language>Optional: more compact write Map<String,Object> map = new HashMap<>();</technical_language>

Target:
public IConnectionWrapper getConnection() throws CoreException { Map<String,Object> map = new HashMap<>(); map.put(JolokiaConnectionWrapper.ID, name); map.put(JolokiaConnectionWrapper.URL, url); map.put(JolokiaConnectionWrapper.HEADERS, headers); map.put(JolokiaConnectionWrapper.IGNORE_SSL_ERRORS, ignoreSSL); map.put(JolokiaConnectionWrapper.GET_OR_POST, getOrPost); IConnectionProvider provider = ExtensionManager.getProvider(JolokiaConnectionProvider.PROVIDER_ID); return provider.createConnection(map); }
Source:
<code>protected boolean canDoAction() { if (getDisk() == null) { <START> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); <END> } if (getVms() == null || getVms().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_NOT_VM_DISK); } if (getDiskType() == DiskStorageType.IMAGE) { DiskImage diskImage = (DiskImage) getDisk(); if (diskImage.getImageStatus() != ImageStatus.OK) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED); } } if (isImageLockNeeded()) { for (VM vm : getVms()) { if (vm.isRunningOrPaused()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } } } return true; }</code><technical_language>do add type operation. setActionMessageParameters method added</technical_language>

Target:
protected boolean canDoAction() { if (getDisk() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } if (getDiskType() == DiskStorageType.IMAGE) { if (((DiskImage) getDisk()).getImageStatus() != ImageStatus.OK) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED); } } if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_NOT_VM_DISK); } if (isImageLockNeeded() && getVm().isRunningOrPaused()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } if (getVdsIdInPool() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } if (!validate(new StoragePoolValidator(getStoragePoolDao().get(getStoragePoolId())).isUp())) { return false; } return true; }
Source:
<code>public void testConvertDs3RequestWithRequestPayload() { final Request testRequest = RequestConverter.toRequest( <START> new Ds3Request("CreateGetJobRequestHandler", <END> HttpVerb.PUT, Classification.spectrads3, null, null, Action.MODIFY, Resource.BUCKET, ResourceType.NON_SINGLETON, Operation.START_BULK_GET, true, null, ImmutableList.of( new Ds3Param("Aggregating", "boolean", false), new Ds3Param("ChunkClientProcessingOrderGuarantee", "com.spectralogic.s3.common.dao.domain.ds3.JobChunkClientProcessingOrderGuarantee", false), new Ds3Param("Name", "java.lang.String", true), new Ds3Param("Priority", "com.spectralogic.s3.common.dao.domain.ds3.BlobStoreTaskPriority", false)), ImmutableList.of( new Ds3Param("Operation", "com.spectralogic.s3.server.request.rest.RestOperationType", true)))); assertTrue(testRequest.hasRequestPayload()); }</code><technical_language>above, get this Ds3Request in Ds3ModelFixtures.getRequestBulkGet()</technical_language>

Target:
public void testConvertDs3RequestWithRequestPayload() { final Request testRequest = RequestConverter.toRequest(Ds3ModelFixtures.getRequestBulkGet()); assertTrue(testRequest.hasRequestPayload()); }
Source:
<code><START> public void buildDependencyGraph(final AbstractProject downstream, DependencyGraph graph) { <END> for (AbstractProject upstream : Items.fromNameList(downstream.getParent(), upstreamProjects, AbstractProject.class)) { graph.addDependency(new DependencyGraph.Dependency(upstream, downstream) { @Override public boolean shouldTriggerBuild(AbstractBuild upstreamBuild, TaskListener listener, List<Action> actions) { return shouldTrigger(upstreamBuild, listener); } }); } }</code><technical_language>Gratuitous whitespace-only changes avoided minimize work cherry-picking etc</technical_language>

Target:
@Override public void buildDependencyGraph(final AbstractProject downstream, DependencyGraph graph) { for (AbstractProject upstream : Items.fromNameList(downstream.getParent(), upstreamProjects, AbstractProject.class)) { graph.addDependency(new DependencyGraph.Dependency(upstream, downstream) { @Override public boolean shouldTriggerBuild(AbstractBuild upstreamBuild, TaskListener listener, List<Action> actions) { return shouldTrigger(upstreamBuild, listener); } }); } }
Source:
<code>public void init(String... args) throws Throwable { final InputStream in; final File propertiesFile; String path = System.getProperty(LauncherConstants.LAUNCHER_PROPERTIES); if (path != null) { Matcher matcher = Pattern.compile("^([\"'])(.*)\\1$") .matcher(path); if (matcher.matches()) { path = matcher.group(2); } propertiesFile = new File(path).getAbsoluteFile(); if (!propertiesFile.isFile()) errorAndExit("Specified launch file `%s' was not found - absolutePath='%s'", path, propertiesFile.getAbsolutePath()); in = IO.stream(propertiesFile); } else { propertiesFile = null; in = Launcher.class.getClassLoader() .getResourceAsStream(DEFAULT_LAUNCHER_PROPERTIES); if (in == null) { printUsage(); errorAndExit("Launch file not specified, and no embedded properties found."); return; } } Properties properties = new Properties(); load(in, properties); augmentWithSystemProperties(properties); for (String arg : args) { <START> if ("-v".equals(arg) || "-verbose".equals(arg)) { <END> properties.put(LauncherConstants.LAUNCH_TRACE, "true"); break; } } init(properties, null); }</code><technical_language>constants (like in EmbeddedLauncher) for strings</technical_language>

Target:
public void init(String... args) throws Throwable { final InputStream in; final File propertiesFile; String path = System.getProperty(LauncherConstants.LAUNCHER_PROPERTIES); if (path != null) { Matcher matcher = Pattern.compile("^([\"'])(.*)\\1$") .matcher(path); if (matcher.matches()) { path = matcher.group(2); } propertiesFile = new File(path).getAbsoluteFile(); if (!propertiesFile.isFile()) errorAndExit("Specified launch file `%s' was not found - absolutePath='%s'", path, propertiesFile.getAbsolutePath()); in = IO.stream(propertiesFile); } else { propertiesFile = null; in = Launcher.class.getClassLoader() .getResourceAsStream(DEFAULT_LAUNCHER_PROPERTIES); if (in == null) { printUsage(); errorAndExit("Launch file not specified, and no embedded properties found."); return; } } Properties properties = new Properties(); load(in, properties); augmentWithSystemProperties(properties); init(properties, null); }
Source:
<code>public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException { Collection<String> contentTypes = HeaderAccessUtils.caseInsensitiveGet(response.headers(), HttpHeaders.CONTENT_TYPE); if (contentTypes == null) { contentTypes = ImmutableSet.of(); } if (contentTypes.size() == 1 && Iterables.getOnlyElement(contentTypes, "").startsWith(CborDelegateEncoder.MIME_TYPE)) { InputStream inputStream = response.body().asInputStream(); if (!inputStream.markSupported()) { <START> inputStream = new BufferedInputStream(inputStream, 1); <END> } inputStream.mark(1); if (inputStream.read() == -1) { return null; } inputStream.reset(); return cborObjectMapper.readValue(inputStream, cborObjectMapper.constructType(type)); } else { return delegate.decode(response, type); } }</code><technical_language>buffer size 1, why</technical_language>

Target:
public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException { Collection<String> contentTypes = HeaderAccessUtils.caseInsensitiveGet(response.headers(), HttpHeaders.CONTENT_TYPE); if (contentTypes == null) { contentTypes = ImmutableSet.of(); } if (contentTypes.size() == 1 && Iterables.getOnlyElement(contentTypes, "").startsWith(CborDelegateEncoder.MIME_TYPE)) { int pushbackBufferSize = 1; PushbackInputStream pushbackInputStream = new PushbackInputStream( response.body().asInputStream(), pushbackBufferSize); int firstByte = pushbackInputStream.read(); if (firstByte == -1) { return null; } pushbackInputStream.unread(firstByte); return cborObjectMapper.readValue(pushbackInputStream, cborObjectMapper.constructType(type)); } else { return delegate.decode(response, type); } }
Source:
<code>public INodeDirectory getSnapshottableAncestorDir(final INodesInPath iip) throws IOException { final String path = iip.getPath(); final INode inode = iip.getLastINode(); final INodeDirectory dir; if (inode instanceof INodeDirectory) { dir = INodeDirectory.valueOf(inode, path); <START> if (dir.isSnapshottable()) { return dir; } <END> } else { dir = INodeDirectory.valueOf(iip.getINode(-2), iip.getParentPath()); } for (INodeDirectory snapRoot : this.snapshottables.values()) { if (dir.isAncestorDirectory(snapRoot)) { return snapRoot; } } return null; }</code><technical_language>This check moved right for-loop (line 389)</technical_language>

Target:
public INodeDirectory getSnapshottableAncestorDir(final INodesInPath iip) throws IOException { final String path = iip.getPath(); final INode inode = iip.getLastINode(); final INodeDirectory dir; if (inode instanceof INodeDirectory) { dir = INodeDirectory.valueOf(inode, path); } else { dir = INodeDirectory.valueOf(iip.getINode(-2), iip.getParentPath()); } if (dir.isSnapshottable()) { return dir; } for (INodeDirectory snapRoot : this.snapshottables.values()) { if (dir.isAncestorDirectory(snapRoot)) { return snapRoot; } } return null; }
Source:
<code>public void globalConfigAllowedWithManagePermission() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() .grant(Jenkins.MANAGE, Jenkins.READ).everywhere().toEveryone()); HtmlForm form = j.createWebClient().goTo("configure").getFormByName("config"); HtmlPage updated = j.submit(form); assertEquals("User with Jenkins.MANAGE permission should be able to update global configuration", <START> 200, updated.getWebResponse().getStatusCode()); <END> }</code><technical_language>NIT: if this returns other 200 run a CI system enough information diagnose test failure? if this is done in multiple places, a hamcrest matcher provide more diagnostics? assertThat("User Jenkins.MANAGE permission able update global configuration", updated.getWebResponse(), hasStatusCode(200)) describeMismatch error code contents</technical_language>

Target:
public void globalConfigAllowedWithManagePermission() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() .grant(Jenkins.MANAGE, Jenkins.READ).everywhere().toEveryone()); HtmlForm form = j.createWebClient().goTo("configure").getFormByName("config"); HtmlPage updated = j.submit(form); assertThat("User with Jenkins.MANAGE permission should be able to update global configuration", updated.getWebResponse(), hasResponseCode(HttpURLConnection.HTTP_OK)); }
Source:
<code>private void applyAttributes(Attributes attributes) { if (attributes.getId() != null) { writer.writeAttribute("id", attributes.getId()); } if (attributes.getCssClass() != null) { writer.writeAttribute("role", attributes.getCssClass()); } if (attributes instanceof ListAttributes) { ListAttributes <START> lattr = <END> (ListAttributes) attributes; if (lattr.getType() != null) { writer.writeAttribute("numeration", lattr.getType()); } } }</code><technical_language>please abbreviations this, instead spell out in full, e.g. listAttributes</technical_language>

Target:
private void applyAttributes(Attributes attributes) { if (attributes.getId() != null) { writer.writeAttribute("id", attributes.getId()); } if (attributes.getCssClass() != null) { writer.writeAttribute("role", attributes.getCssClass()); } if (attributes instanceof ListAttributes) { ListAttributes listAttributes = (ListAttributes) attributes; if (listAttributes.getType() != null) { writer.writeAttribute("numeration", listAttributes.getType()); } } }
Source:
<code>public ForemanHostProvider(final HostRepository hostRepository, @Assisted final Configuration configuration) { _hostRepository = hostRepository; getContext().system().scheduler().schedule( ConfigurationHelper.getFiniteDuration(configuration, "initialDelay"), ConfigurationHelper.getFiniteDuration(configuration, "interval"), getSelf(), TICK, getContext().dispatcher(), getSelf()); _client = new ForemanClient.Builder() <START> .setBaseUrl(URI.create(configuration.getString("foreman.baseUrl"))) <END> .build(); }</code><technical_language>is foreman.baseUrl a subkey a root level key of configuration for this host provider instance</technical_language>

Target:
public ForemanHostProvider(final HostRepository hostRepository, @Assisted final Configuration configuration) { _hostRepository = hostRepository; getContext().system().scheduler().schedule( ConfigurationHelper.getFiniteDuration(configuration, "initialDelay"), ConfigurationHelper.getFiniteDuration(configuration, "interval"), getSelf(), TICK, getContext().dispatcher(), getSelf()); _client = new ForemanClient.Builder() .setBaseUrl(URI.create(configuration.getString("baseUrl"))) .build(); }
Source:
<code>public void createDatabaseIfNotExists(String databaseName) throws TDClientException { if (!existsDatabase(databaseName)) { createDatabase(databaseName); } <START> } <END></code><technical_language>I understand this method is defined utility method. > types of implementation (using existDatabase try ... catch mentioned) do thing. meaning of 2 methods is 1st needs call API calls twice. Exception handling cost is cheaper 1 API call. createDatabase method throws 409 request ~~should~~ is retried API components. So, ConflictException handling is necessary. Please consider things</technical_language>

Target:
public void createDatabaseIfNotExists(String databaseName) throws TDClientException { try { createDatabase(databaseName); } catch (TDClientHttpConflictException e) { } }
Source:
<code>public Builder request(Request request) { checkNotNull(request, "the original request is required on all responses"); <START> this.request = Request.create( <END> request.method(), request.url(), request.headers(), null, request.charset()); return this; }</code><technical_language>IMO, Request Response object short lived, so, feels gain memory usage creating a new request, loose GC time for 2 objects.... If decides Response in memory for some reason, I think, Request. Lemme thoughts</technical_language>

Target:
public Builder request(Request request) { checkNotNull(request, "request is required"); this.request = request; return this; }
Source:
<code>public void saveForm_whenReasonRequiredToSave_returnsSaveResult_inChangeReasonRequiredState() { whenReasonRequiredToSave(); viewModel.saveForm(Uri.parse("file://form"), true, "", false); <START> LiveData<FormSaveViewModel.SaveResult> saveResult = viewModel.getSavedResult(); <END> assertThat(saveResult.getValue().getState(), equalTo(CHANGE_REASON_REQUIRED)); }</code><technical_language>I saveResult declarations call save good ensures LiveData instance is before/after call. This mimics ViewModel observation call action</technical_language>

Target:
public void saveForm_whenReasonRequiredToSave_returnsSaveResult_inChangeReasonRequiredState() { whenReasonRequiredToSave(); LiveData<FormSaveViewModel.SaveResult> saveResult = viewModel.getSavedResult(); viewModel.saveForm(Uri.parse("file://form"), true, "", false); assertThat(saveResult.getValue().getState(), equalTo(CHANGE_REASON_REQUIRED)); }
Source:
<code>public EObject getStereotypeApplication(final View view, Stereotype stereo) { EObject <START> appliedStereo = <END> null; if (isInStereotypeComment((Node) view)) { if (getCommentSemanticElement(getTopContainer(view)) != null) { appliedStereo = getCommentSemanticElement(getTopContainer(view)).getStereotypeApplication(stereo); } } if (getContainerSemanticElement(view) != null) { appliedStereo = getContainerSemanticElement(view).getStereotypeApplication(stereo); } return appliedStereo; }</code><technical_language>Change name of local variable</technical_language>

Target:
public EObject getStereotypeApplication(final View view, Stereotype stereo) { EObject appliedStereotypes = null; if (isInStereotypeComment((Node) view)) { if (getCommentSemanticElement(getTopContainer(view)) != null) { appliedStereotypes = getCommentSemanticElement(getTopContainer(view)).getStereotypeApplication(stereo); } } if (getContainerSemanticElement(view) != null) { appliedStereotypes = getContainerSemanticElement(view).getStereotypeApplication(stereo); } return appliedStereotypes; }
Source:
<code><START> public Monetary parse(String str) throws NumberFormatException { <END> return Coin.valueOf(parseValue(str)); }</code><technical_language>do return Monetary instead of Coin + Fiat respectively? Monetary is useful callers cast</technical_language>

Target:
public Coin parse(String str) throws NumberFormatException { return Coin.valueOf(parseValue(str, Coin.SMALLEST_UNIT_EXPONENT)); }
Source:
<code>private IEntityGroup findGroupByName(String groupName) { <START> EntityIdentifier[] identifiers = GroupService.searchForGroups(groupName, GroupService.IS, EntityEnum.GROUP.getClazz()); <END> logger.debug("Found indentifier(s) for group name {}", identifiers.length, groupName); for (EntityIdentifier entityIdentifier : identifiers) { logger.debug(entityIdentifier.toString()); if (entityIdentifier.getType().equals(IEntityGroup.class)) { return GroupService.findGroup(entityIdentifier.getKey()); } } return null; }</code><technical_language>I suspect 3rd argument IPerson.class -- or, alternately EntityEnum.PERSON refer (EntityEnum) in a package called org.jasig.portal.portlets.groupselector (to feels coloring-out-of-the-lines) I a lot of code already. (Perhaps enum moved.)</technical_language>

Target:
private static IEntityGroup findGroupByName(String groupName) { EntityIdentifier[] identifiers = GroupService.searchForGroups(groupName, GroupService.IS, IPerson.class); for (EntityIdentifier entityIdentifier : identifiers) { if (entityIdentifier.getType().equals(IEntityGroup.class)) { return GroupService.findGroup(entityIdentifier.getKey()); } } return null; }
Source:
<code>private void registerUser(String email) { Data myData = new Data.Builder() .putString(TravelBehaviorConstants.USER_EMAIL, email) .build(); Constraints constraints = new Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build(); OneTimeWorkRequest workRequest = new OneTimeWorkRequest. Builder(RegisterTravelBehaviorParticipantWorker.class) .setInputData(myData) .setConstraints(constraints) .build(); WorkManager workManager = WorkManager.getInstance(); workManager.enqueue(workRequest); ListenableFuture<WorkInfo> listenableFuture = workManager. getWorkInfoById(workRequest.getId()); Futures.addCallback(listenableFuture, new FutureCallback<WorkInfo>() { @Override public void onSuccess(@NullableDecl WorkInfo result) { startCollectingData(); Activity activity = (Activity) mActivityContext; activity.runOnUiThread(() -> Toast.makeText(mApplicationContext, R.string.travel_behavior_enroll_success, Toast.LENGTH_LONG).show()); <START> } <END> @Override public void onFailure(Throwable t) { Activity activity = (Activity) mActivityContext; activity.runOnUiThread(() -> Toast.makeText(mApplicationContext, R.string.travel_behavior_enroll_fail, Toast.LENGTH_LONG).show()); } }, TravelBehaviorFileSaverExecutorManager.getInstance().getThreadPoolExecutor()); }</code><technical_language>Great! I fine</technical_language>

Target:
private void registerUser(String email) { Data myData = new Data.Builder() .putString(TravelBehaviorConstants.USER_EMAIL, email) .build(); Constraints constraints = new Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build(); OneTimeWorkRequest workRequest = new OneTimeWorkRequest. Builder(RegisterTravelBehaviorParticipantWorker.class) .setInputData(myData) .setConstraints(constraints) .build(); WorkManager workManager = WorkManager.getInstance(); workManager.enqueue(workRequest); ListenableFuture<WorkInfo> listenableFuture = workManager. getWorkInfoById(workRequest.getId()); Futures.addCallback(listenableFuture, new FutureCallback<WorkInfo>() { @Override public void onSuccess(@NullableDecl WorkInfo result) { Activity activity = (Activity) mActivityContext; activity.runOnUiThread(() -> Toast.makeText(mApplicationContext, R.string.travel_behavior_enroll_success, Toast.LENGTH_LONG).show()); } @Override public void onFailure(Throwable t) { Activity activity = (Activity) mActivityContext; activity.runOnUiThread(() -> Toast.makeText(mApplicationContext, R.string.travel_behavior_enroll_fail, Toast.LENGTH_LONG).show()); } }, TravelBehaviorFileSaverExecutorManager.getInstance().getThreadPoolExecutor()); }
Source:
<code>public void setClaimedJobId(@NotBlank final String jobId) { <START> setIfNullOrTrow(jobId, claimedJobIdRef); <END> }</code><technical_language>misspelled</technical_language>

Target:
public void setClaimedJobId(@NotBlank final String jobId) { setIfNullOrThrow(jobId, claimedJobIdRef); }
Source:
<code>public static boolean isVerificationSuccessful(String captchaResponse) { if (captchaResponse == null || captchaResponse.isEmpty()) { return false; } try { URIBuilder urlb = new URIBuilder(VERIFY_URL); urlb.setParameter("secret", SECRET_KEY); urlb.setParameter("response", captchaResponse); HttpPost post = new HttpPost(urlb.build()); try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse resp = client.execute(post); <START> BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()))) { <END> String output = br.lines().collect(Collectors.joining(System.lineSeparator())); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { log.info("reCAPTCHA verification request successful:" + System.lineSeparator() + output); JsonObject jsonObject = JsonUtils.parse(output).getAsJsonObject(); if (jsonObject.has("error-codes")) { JsonArray errorCodes = jsonObject.get("error-codes").getAsJsonArray(); log.warning("Error codes during reCAPTCHA verification: " + errorCodes.toString()); } return Boolean.parseBoolean(jsonObject.get("success").toString()); } else { log.severe("reCAPTCHA verification request failure:" + System.lineSeparator() + output); return false; } } catch (IOException e) { log.severe("reCAPTCHA verification request failure: " + e.getMessage()); return false; } } catch (URISyntaxException e) { log.severe("reCAPTCHA verification request failure: " + e.getMessage()); return false; } }</code><technical_language>uhmmm research [here](<LINK_0>, exception in try-with-resource statement suppressed if is exception in try block well. if resp.getEntity() returns null getContent() some problems? moving this statement</technical_language>

Target:
public boolean isVerificationSuccessful(String captchaResponse) { return isVerificationSuccessful(captchaResponse, SECRET_KEY); }
Source:
<code>public DistributionSnapshot getRuntimeSnapshot() { if (isSiteMode()) { <START> throw new RuntimeException("Live runtime cannot be snapshotted."); <END> } if (runtimeSnapshot == null) { synchronized (this) { if (runtimeSnapshot == null) { runtimeSnapshot = RuntimeSnapshot.build(); } } } return runtimeSnapshot; }</code><technical_language>interesting throw a NuxeoException HTTP bad request status</technical_language>

Target:
public DistributionSnapshot getRuntimeSnapshot() { if (isSiteMode()) { throw new RuntimeServiceException("Live runtime cannot be snapshotted."); } if (runtimeSnapshot == null) { synchronized (this) { if (runtimeSnapshot == null) { runtimeSnapshot = RuntimeSnapshot.build(); } } } return runtimeSnapshot; }
Source:
<code>public void stop() { if (engine != null) { <START> engine.shutdown(); <END> } }</code><technical_language>this set engine null in a finally block? If not, checks for null (line 177)</technical_language>

Target:
public synchronized void stop() { if (engine != null) { engine.shutdown(); engine = null; } }
Source:
<code><START> public static XmlDataProviderManager getInstance() { <END> if (INSTANCE == null) { INSTANCE = new XmlDataProviderManager(); } return INSTANCE; }</code><technical_language>sync</technical_language>

Target:
public static synchronized XmlDataProviderManager getInstance() { if (INSTANCE == null) { INSTANCE = new XmlDataProviderManager(); } return INSTANCE; }
Source:
<code>public static Pattern generateNickHighlightPattern(final String nick) { <START> return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "\\b", Pattern.UNICODE_CASE); <END> }</code><technical_language>UNICODE_CASE sense CASE_INSENSITIVE, remove</technical_language>

Target:
public static Pattern generateNickHighlightPattern(final String nick) { return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "\\b"); }
Source:
<code>public double getLogProb(double value) { <START> return Math.log(getProb(value)); <END> }</code><technical_language>need calculate logprob directly</technical_language>

Target:
public double getLogProb(double value) { checkHasParams(); if (value < 0) { return Double.NEGATIVE_INFINITY; } else { return logLambda - lambda * value + (k - 1) * Math.log(lambda * value) - logGammaK; } }
Source:
<code><START> private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException { <END> is.defaultReadObject(); this.internalParameters = new HashMap<>(); }</code><technical_language>I this method is necessary. If this is initializing transient map, do in field declaration</technical_language>

Target:
private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException { is.defaultReadObject(); this.internalParameters = new HashMap<>(INTERNAL_PARAMETERS_INITIAL_CAPACITY); }
Source:
<code><START> public static String getCheckerWorkflowPath(DockstoreWebserviceConfiguration config, Entry entry) { <END> if (entry.getCheckerWorkflow() == null) { return null; } else { String newID = "#workflow/" + entry.getCheckerWorkflow().getWorkflowPath(); return getUrlFromId(config, newID); } }</code><technical_language>else, this private</technical_language>

Target:
private static String getCheckerWorkflowPath(DockstoreWebserviceConfiguration config, Entry entry) { if (entry.getCheckerWorkflow() == null) { return null; } else { String newID = "#workflow/" + entry.getCheckerWorkflow().getWorkflowPath(); return getUrlFromId(config, newID); } }
Source:
<code>private void createSubscriptionLocked() { if (getZk().createSubscription()) { final Map<Partition.PartitionKey, String> cursors = getKafka().getSubscriptionOffsets().entrySet() .stream().collect( Collectors.toMap( Map.Entry::getKey, entry -> entry.getValue().getOffset() ) ); getZk().fillEmptySubscription(cursors); } else { final Session[] sessions = getZk().listSessions(); final Partition[] partitions = getZk().listPartitions(); if (sessions.length >= partitions.length) { switchState(new CleanupState(new NoStreamingSlotsAvailable(partitions.length))); return; } } if (getZk().isCursorResetInProgress()) { switchState(new CleanupState( <START> new NakadiException("Resetting subscription cursors request still in the progress") { <END> @Override protected Response.StatusType getStatus() { return Response.Status.CONFLICT; } })); return; } registerSession(); try { getOut().onInitialized(getSessionId()); switchState(new StreamingState()); } catch (final IOException e) { getLog().error("Failed to notify of initialization. Switch to cleanup directly", e); switchState(new CleanupState(e)); } }</code><technical_language>in progress -> in progress</technical_language>

Target:
private void createSubscriptionLocked() { if (getZk().createSubscription()) { final Map<Partition.PartitionKey, String> cursors = getKafka().getSubscriptionOffsets().entrySet() .stream().collect( Collectors.toMap( Map.Entry::getKey, entry -> entry.getValue().getOffset() ) ); getZk().fillEmptySubscription(cursors); } else { final Session[] sessions = getZk().listSessions(); final Partition[] partitions = getZk().listPartitions(); if (sessions.length >= partitions.length) { switchState(new CleanupState(new NoStreamingSlotsAvailable(partitions.length))); return; } } if (getZk().isCursorResetInProgress()) { switchState(new CleanupState( new NakadiException("Resetting subscription cursors request is still in progress") { @Override protected Response.StatusType getStatus() { return Response.Status.CONFLICT; } })); return; } registerSession(); try { getOut().onInitialized(getSessionId()); switchState(new StreamingState()); } catch (final IOException e) { getLog().error("Failed to notify of initialization. Switch to cleanup directly", e); switchState(new CleanupState(e)); } }
Source:
<code>private Object getHiveTableProperty(String tableName, Function<HiveTableLayoutHandle, Object> propertyGetter) { Session session = getSession(); Metadata metadata = ((DistributedQueryRunner) getQueryRunner()).getCoordinator().getMetadata(); return transaction(getQueryRunner().getTransactionManager(), getQueryRunner().getAccessControl()) .readOnly() .execute(session, transactionSession -> { Optional<TableHandle> tableHandle = metadata.getTableHandle(transactionSession, new QualifiedObjectName(catalog, TPCH_SCHEMA, tableName)); assertTrue(tableHandle.isPresent()); TableLayout layout = metadata.getLayout(transactionSession, tableHandle.get(), Constraint.alwaysTrue(), Optional.empty()) <START> .get() <END> .getLayout(); return propertyGetter.apply((HiveTableLayoutHandle) layout.getHandle().getConnectorHandle()); }); }</code><technical_language>nit: .get() -> .orElseThrow(() -> new AssertionError("layout is present"))</technical_language>

Target:
private Object getHiveTableProperty(String tableName, Function<HiveTableLayoutHandle, Object> propertyGetter) { Session session = getSession(); Metadata metadata = ((DistributedQueryRunner) getQueryRunner()).getCoordinator().getMetadata(); return transaction(getQueryRunner().getTransactionManager(), getQueryRunner().getAccessControl()) .readOnly() .execute(session, transactionSession -> { Optional<TableHandle> tableHandle = metadata.getTableHandle(transactionSession, new QualifiedObjectName(catalog, TPCH_SCHEMA, tableName)); assertTrue(tableHandle.isPresent()); TableLayout layout = metadata.getLayout(transactionSession, tableHandle.get(), Constraint.alwaysTrue(), Optional.empty()) .getLayout(); return propertyGetter.apply((HiveTableLayoutHandle) layout.getNewTableHandle().getLayout().get()); }); }