auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void visitControllerActions(@NotNull final Project project, @NotNull ControllerActionVisitor visitor, @Nullable String prefix) { Collection<PhpClass> allSubclasses = new HashSet<PhpClass>() {{ addAll(PhpIndex.getInstance(project).getAllSubclasses("\\Illuminate\\Routing\\Controller")); addAll(PhpIndex.getInstance(project).getAllSubclasses("\\App\\Http\\Controllers\\Controller")); }}; <START> HashSet<String> commonTraits = new HashSet<String>(); <END> commonTraits.add("ValidatesRequests"); commonTraits.add("DispatchesCommands"); commonTraits.add("AuthorizesRequests"); commonTraits.add("Controller"); String ns = getDefaultNamespace(project) + "\\"; String prefixedNs = ns + (prefix != null && !prefix.equals("") ? prefix + "\\":""); for(PhpClass phpClass: allSubclasses) { if(!phpClass.isAbstract()) { for(Method method: phpClass.getMethods()) { String className = phpClass.getPresentableFQN(); String methodName = method.getName(); if(!method.isStatic() && method.getAccess().isPublic() && !methodName.startsWith("__")) { PhpClass phpTrait = method.getContainingClass(); if(phpTrait == null || !commonTraits.contains(phpTrait.getName())) { boolean prioritised = false; if(prefix != null && className.startsWith(prefixedNs)) { className = className.substring(prefixedNs.length()); prioritised = true; } else if(className.startsWith(ns)) { className = className.substring(ns.length()); } if(StringUtils.isNotBlank(className)) { visitor.visit(phpClass, method, className + "@" + methodName, prioritised); } } } } } } }</code><technical_language>more abstract type. Set<String> commonTraits =. a static class variable, collection change runtime</technical_language>

Target:
public static void visitControllerActions(@NotNull final Project project, @NotNull ControllerActionVisitor visitor, @Nullable String prefix) { Collection<PhpClass> allSubclasses = new HashSet<PhpClass>() {{ addAll(PhpIndex.getInstance(project).getAllSubclasses("\\Illuminate\\Routing\\Controller")); addAll(PhpIndex.getInstance(project).getAllSubclasses("\\App\\Http\\Controllers\\Controller")); }}; String ns = getDefaultNamespace(project) + "\\"; String prefixedNs = ns + (prefix != null && !prefix.equals("") ? prefix + "\\":""); for(PhpClass phpClass: allSubclasses) { if(!phpClass.isAbstract()) { for(Method method: phpClass.getMethods()) { String className = phpClass.getPresentableFQN(); String methodName = method.getName(); if(!method.isStatic() && method.getAccess().isPublic() && !methodName.startsWith("__")) { PhpClass phpTrait = method.getContainingClass(); if(phpTrait == null || !commonControllerTraits.contains(phpTrait.getName())) { boolean prioritised = false; if(prefix != null && className.startsWith(prefixedNs)) { className = className.substring(prefixedNs.length()); prioritised = true; } else if(className.startsWith(ns)) { className = className.substring(ns.length()); } if(StringUtils.isNotBlank(className)) { visitor.visit(phpClass, method, className + "@" + methodName, prioritised); } } } } } } }
Source:
<code>private Set<ValueExtractorDescriptor> getRuntimeCompliantValueExtractors(Class<?> runtimeType, Set<ValueExtractorDescriptor> potentialValueExtractorDescriptors) { if ( nonContainerTypes.contains( runtimeType ) ) { return Collections.emptySet(); } Set<ValueExtractorDescriptor> valueExtractorDescriptors = possibleValueExtractorsByRuntimeType.get( runtimeType ); if ( valueExtractorDescriptors != null ) { return valueExtractorDescriptors; } Set<ValueExtractorDescriptor> possibleValueExtractors = potentialValueExtractorDescriptors .stream() .filter( e -> TypeHelper.isAssignable( e.getContainerType(), runtimeType ) ) .collect( Collectors.toSet() ); valueExtractorDescriptors = getMaximallySpecificValueExtractors( possibleValueExtractors ); if ( valueExtractorDescriptors.isEmpty() ) { <START> nonContainerTypes.put( runtimeType, NON_CONTAINER_VALUE ); <END> return Collections.emptySet(); } Set<ValueExtractorDescriptor> valueExtractorDescriptorsToCache = CollectionHelper.toImmutableSet( valueExtractorDescriptors ); Set<ValueExtractorDescriptor> cachedValueExtractorDescriptors = possibleValueExtractorsByRuntimeType.putIfAbsent( runtimeType, valueExtractorDescriptorsToCache ); return cachedValueExtractorDescriptors != null ? cachedValueExtractorDescriptors : valueExtractorDescriptorsToCache; }</code><technical_language>@gsmet, related this change, check beginning of methods: if ( nonContainerTypes.contains( runtimeType ) ) { this containsKey() instead? wrong se, currently defeats purpose of nonContainerTypes cache. Another question is usage of unbounded maps; in BeanMetaDataManagerImpl ConcurrentReferenceHashMap instead, release entries if need</technical_language>

Target:
private Set<ValueExtractorDescriptor> getRuntimeCompliantValueExtractors(Class<?> runtimeType, Set<ValueExtractorDescriptor> potentialValueExtractorDescriptors) { if ( nonContainerTypes.contains( runtimeType ) ) { return Collections.emptySet(); } Set<ValueExtractorDescriptor> valueExtractorDescriptors = possibleValueExtractorsByRuntimeType.get( runtimeType ); if ( valueExtractorDescriptors != null ) { return valueExtractorDescriptors; } Set<ValueExtractorDescriptor> possibleValueExtractors = potentialValueExtractorDescriptors .stream() .filter( e -> TypeHelper.isAssignable( e.getContainerType(), runtimeType ) ) .collect( Collectors.toSet() ); valueExtractorDescriptors = getMaximallySpecificValueExtractors( possibleValueExtractors ); if ( valueExtractorDescriptors.isEmpty() ) { nonContainerTypes.add( runtimeType ); return Collections.emptySet(); } Set<ValueExtractorDescriptor> valueExtractorDescriptorsToCache = CollectionHelper.toImmutableSet( valueExtractorDescriptors ); Set<ValueExtractorDescriptor> cachedValueExtractorDescriptors = possibleValueExtractorsByRuntimeType.putIfAbsent( runtimeType, valueExtractorDescriptorsToCache ); return cachedValueExtractorDescriptors != null ? cachedValueExtractorDescriptors : valueExtractorDescriptorsToCache; }
Source:
<code>private void writePOMModelOnFS(org.uberfire.java.nio.file.Path filePath, Model model) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.write(baos, model); <START> Files.delete(filePath); <END> Files.write(filePath, baos.toByteArray(), StandardOpenOption.CREATE_NEW); }</code><technical_language>Instead of 2 IO operations (delete write) operation: java Files.write(filePath, baos.toByteArray(), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); @porcelli confirm this is a valid approach, I avoid IO operations (think this trigger unnecessary indexing etc.)</technical_language>

Target:
private void writePOMModelOnFS(org.uberfire.java.nio.file.Path filePath, Model model) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.write(baos, model); Files.write(filePath, baos.toByteArray(), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); }
Source:
<code>private String createDisplayedRef() { String refToCheckOut = ""; if (refName != null) refToCheckOut = refName; else if (commitId != null) { <START> if (commitId != null) <END> refToCheckOut = commitId.getName().substring(0, 7)+ "... "; } else throw new IllegalStateException( "Both refName and commitId must not be null"); return refToCheckOut; }</code><technical_language>duplicate if</technical_language>

Target:
private String createDisplayedRef() { String refToCheckOut = ""; if (refName != null) refToCheckOut = refName; else if (commitId != null) refToCheckOut = commitId.getName().substring(0, 7)+ "... "; else throw new IllegalStateException( "Either refName or commitId must be non-null"); return refToCheckOut; }
Source:
<code>public UserAgentPolicy(HttpLogOptions httpLogOptions, Configuration configuration) { if (httpLogOptions == null) { this.httpLogOptions = new HttpLogOptions(); } else { this.httpLogOptions = httpLogOptions; } if (configuration == null) { <START> this.configuration = Configuration.getGlobalConfiguration().clone(); <END> } else { this.configuration = configuration; } }</code><technical_language>clone global configuration. need changed user some times</technical_language>

Target:
public UserAgentPolicy(HttpLogOptions httpLogOptions, Configuration configuration) { if (httpLogOptions == null) { this.httpLogOptions = new HttpLogOptions(); } else { this.httpLogOptions = httpLogOptions; } if (configuration == null) { this.configuration = Configuration.getGlobalConfiguration(); } else { this.configuration = configuration; } }
Source:
<code>protected void removeProvider(Provider<Rule> provider) { LOGGER.info("Rule provider: is removed.", provider); if (provider instanceof ManagedRuleProvider) { if (ruleRegistryReg != null) { <START> ruleRegistryReg.unregister(); <END> } } else { super.removeProvider(provider); } }</code><technical_language>RuleRegistry registered if managed provider is available. a rule other provider uid managed provider loaded rule engine changes stored in managed provider visible (the rule managed provider all). For this reason RuleEngine initialized rules managed provider is registered give change other providers add rules in RuleEngine. RuleRegistry unregistered managed provider is disappeared, return rules, update command throw exception</technical_language>

Target:
protected void removeProvider(Provider<Rule> provider) { logger.info("Rule provider: is removed.", provider); super.removeProvider(provider); }
Source:
<code>public void operationConst() { TemplateFactory factory = new TemplateFactory('\\'); <START> match("[0 ADD 1]", factory.create("{0+'1'}")); <END> match("[0 DIV 1.0]", factory.create("{0/'1.0'}")); }</code><technical_language>differentiate 1 '1'</technical_language>

Target:
public void operationConst() { TemplateFactory factory = new TemplateFactory('\\'); match("[0 ADD 1]", factory.create("{0+'1'}")); match("[0 DIV 1.0]", factory.create("{0/'1.0'}")); match("[0 MULT 3.141592653589793, ' / 180.0)']", factory.create("{0*'3.141592653589793'} / 180.0)")); }
Source:
<code>public void doRun() throws Exception { long iteration = 0; while (!context.isStopped()) { int partitionId = nextPartitionId(); <START> ICompletableFuture<Object> future = invoke(partitionId); <END> latency.started(); if (syncInvocation) { if (syncFrequency == 1) { future.get(); } else { if (iteration > 0 && iteration % syncFrequency == 0) { for (ICompletableFuture innerFuture : futureList) { innerFuture.get(); } futureList.clear(); } else { futureList.add(future); } } } else { future.andThen(this); } latency.done(); iteration++; if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " At iteration: " + iteration); } if (iteration % performanceUpdateFrequency == 0) { if (syncInvocation) { operations.addAndGet(performanceUpdateFrequency); } } } operations.addAndGet(iteration % performanceUpdateFrequency); }</code><technical_language>is added of parametrizing it? syntactical noise</technical_language>

Target:
private void doRun() throws Exception { long iteration = 0; while (!testContext.isStopped()) { int partitionId = nextPartitionId(); ICompletableFuture<Object> future = invoke(partitionId); if (syncInvocation) { if (syncFrequency == 1) { future.get(); } else { if (iteration > 0 && iteration % syncFrequency == 0) { for (ICompletableFuture innerFuture : futureList) { innerFuture.get(); } futureList.clear(); } else { futureList.add(future); } } } else { future.andThen(this); } iteration++; if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " at iteration: " + iteration); } if (iteration % performanceUpdateFrequency == 0) { if (syncInvocation) { operations.addAndGet(performanceUpdateFrequency); } } } operations.addAndGet(iteration % performanceUpdateFrequency); }
Source:
<code>private static Boolean isPartTextualBody(Part part) throws MessagingException { String disposition = part.getDisposition(); String dispositionType = null; String dispositionFilename = null; if (disposition != null) { dispositionType = MimeUtility.getHeaderParameter(disposition, null); dispositionFilename = MimeUtility.getHeaderParameter(disposition, "filename"); } <START> if ("attachment".equalsIgnoreCase(dispositionType) || dispositionFilename != null) { <END> return false; } return part.isMimeType("text/html") || part.isMimeType("text/plain") || part.isMimeType("application/pgp"); }</code><technical_language>This variable added intentionally if statement more readable</technical_language>

Target:
private static Boolean isPartTextualBody(Part part) throws MessagingException { String disposition = part.getDisposition(); String dispositionType = null; String dispositionFilename = null; if (disposition != null) { dispositionType = MimeUtility.getHeaderParameter(disposition, null); dispositionFilename = MimeUtility.getHeaderParameter(disposition, "filename"); } boolean isAttachmentDisposition = "attachment".equalsIgnoreCase(dispositionType) || dispositionFilename != null; if (isAttachmentDisposition) { return false; } return part.isMimeType("text/html") || part.isMimeType("text/plain") || part.isMimeType("application/pgp"); }
Source:
<code>private MachineStateDescriptor toDescriptor(MachineImpl machineState) throws ServerException { final List<ProjectBindingDescriptor> projectDescriptors = new ArrayList<>(); for (ProjectBinding project : machineState.getProjects()) { projectDescriptors.add(dtoFactory.createDto(ProjectBindingDescriptor.class) .withPath(project.getPath()) .withLinks(null)); } <START> MachineRecipe machineRecipe = dtoFactory.createDto(MachineRecipe.class) <END> .withType(machineState.getRecipe().getType()) .withScript(machineState.getRecipe().getScript()); final MachineStateDescriptor machineDescriptor = dtoFactory.createDto(MachineStateDescriptor.class) .withId(machineState.getId()) .withType(machineState.getType()) .withRecipe(machineRecipe) .withStatus(machineState.getStatus()) .withOwner(machineState.getOwner()) .withWorkspaceId(machineState.getWorkspaceId()) .withWorkspaceBound(machineState.isWorkspaceBound()) .withProjects(projectDescriptors) .withDisplayName(machineState.getDisplayName()) .withMemorySize(machineState.getMemorySize()); machineDescriptor.setLinks(null); return machineDescriptor; }</code><technical_language>FYI DtoFactory.newDto(MachineRecipe.class) instead. a new feature</technical_language>

Target:
private MachineStateDescriptor toDescriptor(MachineImpl machineState) throws ServerException { final List<ProjectBindingDescriptor> projectDescriptors = new ArrayList<>(); for (ProjectBinding project : machineState.getProjects()) { projectDescriptors.add(dtoFactory.createDto(ProjectBindingDescriptor.class) .withPath(project.getPath()) .withLinks(null)); } MachineRecipe machineRecipe = DtoFactory.newDto(MachineRecipe.class) .withType(machineState.getRecipe().getType()) .withScript(machineState.getRecipe().getScript()); final MachineStateDescriptor machineDescriptor = dtoFactory.createDto(MachineStateDescriptor.class) .withId(machineState.getId()) .withType(machineState.getType()) .withRecipe(machineRecipe) .withStatus(machineState.getStatus()) .withOwner(machineState.getOwner()) .withWorkspaceId(machineState.getWorkspaceId()) .withWorkspaceBound(machineState.isWorkspaceBound()) .withProjects(projectDescriptors) .withDisplayName(machineState.getDisplayName()) .withMemorySize(machineState.getMemorySize()); machineDescriptor.setLinks(null); return machineDescriptor; }
Source:
<code>private void sleep(final long sleepTime) { try { Thread.sleep(sleepTime); } catch (final InterruptedException e) { <START> LOGGER.error("thread sleep was interrupted", e); <END> } }</code><technical_language>uppercase in text: 'Thread sleep interrupted'</technical_language>

Target:
private void sleep(final long sleepTime) { try { Thread.sleep(sleepTime); } catch (final InterruptedException e) { LOGGER.error("Thread sleep was interrupted", e); } }
Source:
<code>private void setVmToNonHeadlessMode() { VmStatic vmStatic = vmStaticDao.get(getParameters().getDev().getVmId()); if (vmStatic != null && vmStatic.getDefaultDisplayType() == DisplayType.none) { vmStatic.setDefaultDisplayType(DisplayType.qxl); resourceManager.getVmManager(getParameters().getDev().getVmId()).update(vmStatic); } <START> if (getVmDeviceUtils().getVideoDevices(getParameters().getDev().getVmId()).isEmpty()) { <END> getVmDeviceUtils().addVideoDevices(vmStatic, getVmDeviceUtils().getNeededNumberOfVideoDevices(vmStatic)); } }</code><technical_language>I create a method in VmDeviceUtils for this, restoreVideoDevices(VmBase). This avoid code duplication need expose getNeededNumberOfVideoDevices() method</technical_language>

Target:
private void setVmToNonHeadlessMode() { VmStatic vmStatic = vmStaticDao.get(getVmBaseId()); if (vmStatic != null && vmStatic.getDefaultDisplayType() == DisplayType.none) { vmStatic.setDefaultDisplayType(DisplayType.qxl); resourceManager.getVmManager(getVmBaseId()).update(vmStatic); } vmDeviceUtils.addVideoDevicesOnlyIfNoVideoDeviceExists(vmStatic); }
Source:
<code>public SupremeCourtChamberDivision getOrCreateScChamberDivision(String chamberDivisionFullName) { <START> Preconditions.checkArgument(!StringUtils.isBlank(chamberDivisionFullName)); <END> SupremeCourtChamberDivision scChamberDivision = scChamberDivisionRepository.findOneByFullName(chamberDivisionFullName); if (scChamberDivision == null) { SupremeCourtChamber scChamber = findScChamber(chamberDivisionFullName); scChamberDivision = createAndSaveScChamberDivision(scChamber, chamberDivisionFullName); } return scChamberDivision; }</code><technical_language>J)</technical_language>

Target:
public SupremeCourtChamberDivision getOrCreateScChamberDivision(String chamberDivisionFullName) { Preconditions.checkArgument(StringUtils.isNotBlank(chamberDivisionFullName)); SupremeCourtChamberDivision scChamberDivision = scChamberDivisionRepository.findOneByFullName(chamberDivisionFullName); if (scChamberDivision == null) { SupremeCourtChamber scChamber = findScChamber(chamberDivisionFullName); scChamberDivision = createAndSaveScChamberDivision(scChamber, chamberDivisionFullName); } return scChamberDivision; }
Source:
<code>@Test public void compileFilesWithImportFromParentFileTest() throws IOException { Path source = Paths.get("src","test","resources","solidity","foo","file3.sol"); SolidityCompiler.Option allowPathsOption = new SolidityCompiler.Options.AllowPaths(Collections.singletonList(source.getParent().getParent().toFile())); SolidityCompiler.Result res = SolidityCompiler.compile(source.toFile(), true, ABI, BIN, INTERFACE, METADATA, allowPathsOption); System.out.println("Out: '" + res.output + "'"); System.out.println("Err: '" + res.errors + "'"); CompilationResult result = CompilationResult.parse(res.output); CompilationResult.ContractMetadata a = result.getContract(source, "test3"); CallTransaction.Contract contract = new CallTransaction.Contract(a.abi); System.out.print(contract.functions[0].toString()); <START> } <END></code><technical_language>assert 2 contracts totally is null queried name</technical_language>

Target:
@Test public void compileFilesWithImportFromParentFileTest() throws IOException { Path source = Paths.get("src","test","resources","solidity","foo","file3.sol"); SolidityCompiler.Option allowPathsOption = new SolidityCompiler.Options.AllowPaths(Collections.singletonList(source.getParent().getParent().toFile())); SolidityCompiler.Result res = SolidityCompiler.compile(source.toFile(), true, ABI, BIN, INTERFACE, METADATA, allowPathsOption); System.out.println("Out: '" + res.output + "'"); System.out.println("Err: '" + res.errors + "'"); CompilationResult result = CompilationResult.parse(res.output); Assert.assertEquals(2, result.getContractKeys().size()); Assert.assertEquals(result.getContract("test3"), result.getContract(source,"test3")); Assert.assertNotNull(result.getContract("test1")); CompilationResult.ContractMetadata a = result.getContract(source, "test3"); CallTransaction.Contract contract = new CallTransaction.Contract(a.abi); System.out.print(contract.functions[0].toString()); }
Source:
<code>public FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext) throws Exception { <START> return cachingFs.open(path); <END> }</code><technical_language>If fileContext is Cacheable caching used. hiveFileContext.isCacheable() provide information runtime if caching not</technical_language>

Target:
public FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext) throws Exception { if (hiveFileContext.isCacheable()) { return cachingFileSystem.openFile(path, hiveFileContext); } return dataTier.openFile(path, hiveFileContext); }
Source:
<code>public void launch(ISelection selection, String mode) { <START> if (selection instanceof IStructuredSelection) { <END> Object element = ((IStructuredSelection)selection).getFirstElement(); if (element != null && element instanceof IResource) { IResource selectedResource = (IResource) element; launch(selectedResource, mode); } } }</code><technical_language>is check selection.isEmpty() continuing other checks eliminating need for null checks</technical_language>

Target:
public void launch(ISelection selection, String mode) { if (!selection.isEmpty() && selection instanceof IStructuredSelection) { Object element = ((IStructuredSelection)selection).getFirstElement(); if (element instanceof IResource) { IResource selectedResource = (IResource) element; launch(selectedResource, mode); } } }
Source:
<code>public Question(long id, String code, String name, String uid, PhoneFormat phoneFormat, Type type, boolean compulsory, List<Option> options, Header header, int index, Visibility visibility, List<Rule> rules) { <START> setId(required(id, "id is required")); <END> setCode(required(code, "code is required")); setName(required(name, "name is required")); setUid(required(uid, "uid is required")); setPhoneFormat(phoneFormat); setType(required(type, "type is required")); setCompulsory(compulsory); setOptions(options); setHeader(header); setIndex(index); setVisibility(visibility); setRules(rules); }</code><technical_language>remove private setters? necessary private setters, reduce size of class</technical_language>

Target:
public Question(long id, String code, String name, String uid, PhoneFormat phoneFormat, Type type, boolean compulsory, List<Option> options, Header header, int index, Visibility visibility, List<Rule> rules) { this.id = required(id, "id is required"); this.code = required(code, "code is required"); this.name = required(name, "name is required"); this.uid = required(uid, "uid is required"); this.phoneFormat = phoneFormat; this.type = required(type, "type is required"); this.compulsory = compulsory; this.options = options; this.header = header; this.index = index; this.visibility = visibility; this.rules = rules; }
Source:
<code>protected NeedsPaging<OrderFrequency> doGetAll(RequestContext context) { <START> return new NeedsPaging<OrderFrequency>(Context.getOrderService().getOrderFrequencies(), context); <END> }</code><technical_language>adding includeRetired argument getOrderFrequencies, need pass in context.getIncludeAll()</technical_language>

Target:
protected NeedsPaging<OrderFrequency> doGetAll(RequestContext context) { return new NeedsPaging<OrderFrequency>(Context.getOrderService().getOrderFrequencies(context.getIncludeAll()), context); }
Source:
<code>public MergeViewerSide getOriginSide() { EObject origin = getEObject(MergeViewerSide.ANCESTOR); if (origin == null) { <START> List<MergeViewerSide> ret = getOtherSides(fSide); <END> ret.remove(MergeViewerSide.ANCESTOR); return ret.get(0); } else { return MergeViewerSide.ANCESTOR; } }</code><technical_language>this a lot fSide.opposite()</technical_language>

Target:
public MergeViewerSide getOriginSide() { EObject origin = getEObject(MergeViewerSide.ANCESTOR); if (origin == null) { return fSide.opposite(); } else { return MergeViewerSide.ANCESTOR; } }
Source:
<code>public boolean checkFileExistsInGlobalSpace(String pathname) { try { return this.globalSpace.resolveFile(pathname).exists(); <START> } catch (FileSystemException e) { <END> return false; } }</code><technical_language>log in debug of this error. in case. I guess contribute sysadmin</technical_language>

Target:
public boolean checkFileExistsInGlobalSpace(String pathname) { try { return this.globalSpace.resolveFile(pathname).exists(); } catch (FileSystemException e) { logger.debug(String.format("Can't parse the file name [%s] in the global space.", pathname), e); return false; } }
Source:
<code>public void getServiceStatsReturnsRequestId() { SearchServiceClient serviceClient = getSearchServiceClientBuilder().buildClient(); UUID expectedUuid = UUID.randomUUID(); RequestOptions requestOptions = new RequestOptions().setClientRequestId(expectedUuid); Response<ServiceStatistics> response = serviceClient.getServiceStatisticsWithResponse(requestOptions, Context.NONE); <START> assertEquals(expectedUuid.toString(), response.getHeaders().getValue("client-request-id")); <END> assertReflectionEquals(response.getValue(), getExpectedServiceStatistics(), IGNORE_DEFAULTS); }</code><technical_language>@alzimmermsft In next month so, deploying a service update set client-request-id x-ms-client-request-id response if return-client-request-id x-ms-return-client-request-id is specified</technical_language>

Target:
public void getServiceStatsReturnsRequestId() { SearchServiceClient serviceClient = getSearchServiceClientBuilder().buildClient(); RequestOptions requestOptions = new RequestOptions().setClientRequestId(UUID.randomUUID()); Response<ServiceStatistics> response = serviceClient.getServiceStatisticsWithResponse(requestOptions, Context.NONE); String actualRequestId = response.getHeaders().getValue("request-id"); String actualClientRequestId = response.getHeaders().getValue("client-request-id"); Assertions.assertNotNull(actualClientRequestId); Assertions.assertEquals(actualClientRequestId, actualRequestId); assertReflectionEquals(response.getValue(), getExpectedServiceStatistics(), IGNORE_DEFAULTS); }
Source:
<code>public void testNewTriggeredBuild() { Item item = Hudson.getInstance().getItem("freestyleJob"); assertThat("Item is not a FreeStyleProject", item, instanceOf(FreeStyleProject.class)); FreeStyleProject project = (FreeStyleProject)item; int number = project.getLastBuild().getNumber() + 1; server.waitForCommand(GERRIT_STREAM_EVENTS, 2000); PluginImpl.getInstance().getServer(PluginImpl.DEFAULT_SERVER_NAME).triggerEvent(Setup.createPatchsetCreated()); <START> DuplicatesUtil.waitForBuilds(project, number, DuplicatesUtil.DEFAULT_WAIT_BUILD_MS); <END> assertEquals(number, project.getLastCompletedBuild().getNumber()); assertSame(Result.SUCCESS, project.getLastCompletedBuild().getResult()); }</code><technical_language>adding a new method waitForBuilds(project, number) calls waitForBuilds(project, number, DuplicatesUtil.DEFAULT_WAIT_BUILD_MS) more appropriate</technical_language>

Target:
public void testNewTriggeredBuild() { Item item = Hudson.getInstance().getItem("freestyleJob"); assertThat("Item is not a FreeStyleProject", item, instanceOf(FreeStyleProject.class)); FreeStyleProject project = (FreeStyleProject)item; int number = project.getLastBuild().getNumber() + 1; server.waitForCommand(GERRIT_STREAM_EVENTS, 2000); PluginImpl.getInstance().getServer(PluginImpl.DEFAULT_SERVER_NAME).triggerEvent(Setup.createPatchsetCreated()); TestUtils.waitForBuilds(project, number); assertEquals(number, project.getLastCompletedBuild().getNumber()); assertSame(Result.SUCCESS, project.getLastCompletedBuild().getResult()); }
Source:
<code>public DockerTransientNode(@Nonnull String uniqueName, String workdir, ComputerLauncher launcher) throws Descriptor.FormException, IOException { super("docker-" + uniqueName, workdir, launcher); setNumExecutors(1); setMode(Mode.EXCLUSIVE); <START> setRetentionStrategy(new DockerOnceRetentionStrategy(10)); <END> }</code><technical_language>hurt store containerName attribute</technical_language>

Target:
public DockerTransientNode(@Nonnull String uniqueName, String workdir, ComputerLauncher launcher) throws Descriptor.FormException, IOException { super("docker-" + uniqueName, workdir, launcher); this.containerUniqueName = uniqueName; setNumExecutors(1); setMode(Mode.EXCLUSIVE); setRetentionStrategy(new DockerOnceRetentionStrategy(10)); }
Source:
<code>public List<SimpleDivision> findCcDivisions(int courtId) { List<CommonCourtDivision> courtDivisions = ccDivisionRepository.findAllByCourtId(courtId); CcDivisionComparator ccDivisionComparator = new CcDivisionComparator(); <START> Collections.sort(courtDivisions, ccDivisionComparator); <END> simpleDivisionConverter.getClass(); return simpleDivisionConverter.convertCcDivisions(courtDivisions); }</code><technical_language>shorter form courtDivisions.sort( new CcDivisionComparator());</technical_language>

Target:
public List<SimpleDivision> findCcDivisions(int courtId) { List<CommonCourtDivision> courtDivisions = ccDivisionRepository.findAllByCourtId(courtId); Collections.sort(courtDivisions, new CcDivisionComparator()); return simpleDivisionConverter.convertCcDivisions(courtDivisions); }
Source:
<code>public void doubleTap(WebElement webElement) { logger.entering(webElement); new TouchAction(this) .tap(webElement).release() <START> .waitAction(100) <END> .tap(webElement).release() .perform(); logger.exiting(); }</code><technical_language>100 acceptable here? magic number in this context. fix this</technical_language>

Target:
public void doubleTap(WebElement webElement) { logger.entering(webElement); new TouchAction(this) .tap(webElement).release() .waitAction(DOUBLE_TAP_WAIT_TIME) .tap(webElement).release() .perform(); logger.exiting(); }
Source:
<code>public void testToMap() { Map<?, ?> map = ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"hello", "world"}}); assertEquals("bar", map.get("foo")); assertEquals("world", map.get("hello")); assertNull(ArrayUtils.toMap(null)); assertThrows(IllegalArgumentException.class, () -> ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"short"}})); assertThrows(IllegalArgumentException.class, () -> ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, "illegal type"})); assertThrows(IllegalArgumentException.class, () -> ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, null})); map = ArrayUtils.toMap(new Object[]{new Map.Entry<Object, Object>() { @Override public Object getKey() { return "foo"; } @Override public Object getValue() { return "bar"; } @Override public Object setValue(final Object value) { throw new UnsupportedOperationException(); } @Override public boolean equals(final Object o) { throw new UnsupportedOperationException(); } @Override public int hashCode() { throw new UnsupportedOperationException(); } }}); assertEquals("bar", map.get("foo")); assertEquals(Collections.emptyMap(), ArrayUtils.toMap(new Object[0])); map = ArrayUtils.toMap(new Object[][] { {null, null}, {null, null} }); <START> assertEquals(new HashMap<Object, Object>() { <END> private static final long serialVersionUID = 1L; { put(null, null); } }, map); map = ArrayUtils.toMap(new Object[][] { {"key", "value2"}, {"key", "value1"} }); assertEquals(new HashMap<Object, Object>() { private static final long serialVersionUID = 1L; { put("key", "value1"); } }, map); }</code><technical_language>expected map creation is obtuse IMO, Java provides instead: Collections.singletonMap(null, null);</technical_language>

Target:
public void testToMap() { Map<?, ?> map = ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"hello", "world"}}); assertEquals("bar", map.get("foo")); assertEquals("world", map.get("hello")); assertNull(ArrayUtils.toMap(null)); assertThrows(IllegalArgumentException.class, () -> ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"short"}})); assertThrows(IllegalArgumentException.class, () -> ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, "illegal type"})); assertThrows(IllegalArgumentException.class, () -> ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, null})); map = ArrayUtils.toMap(new Object[]{new Map.Entry<Object, Object>() { @Override public Object getKey() { return "foo"; } @Override public Object getValue() { return "bar"; } @Override public Object setValue(final Object value) { throw new UnsupportedOperationException(); } @Override public boolean equals(final Object o) { throw new UnsupportedOperationException(); } @Override public int hashCode() { throw new UnsupportedOperationException(); } }}); assertEquals("bar", map.get("foo")); assertEquals(Collections.emptyMap(), ArrayUtils.toMap(new Object[0])); map = ArrayUtils.toMap(new Object[][] { {null, null}, {null, null} }); assertEquals(Collections.singletonMap(null, null), map); map = ArrayUtils.toMap(new Object[][] { {"key", "value2"}, {"key", "value1"} }); assertEquals(Collections.singletonMap("key", "value1"), map); }
Source:
<code>public HierarchicalBrowseResultResponse getExpandedStructurePath(HierarchicalBrowseRequest browseRequest) { HierarchicalBrowseResultResponse browseResponse = new HierarchicalBrowseResultResponse(); AccessGroupSet principals = browseRequest.getAccessGroups(); BriefObjectMetadata contentRootMd = getContentRootMetadata(principals); browseResponse.getResultList().add(contentRootMd); CutoffFacet path = getObjectPath(browseRequest.getRootPid(), principals); <START> if (path.getFacetNodes() == null) { <END> return browseResponse; } CutoffFacet stepPath = new CutoffFacet(ANCESTOR_PATH.name(), asList(), 0); for (HierarchicalFacetNode stepFacetNode : path.getFacetNodes()) { stepPath.addNode(stepFacetNode); SearchState stepState = new SearchState(browseRequest.getSearchState()); HierarchicalBrowseRequest stepRequest = new HierarchicalBrowseRequest(stepState, 1, principals); HierarchicalBrowseResultResponse tierResponse = retrieveTier(stepRequest, stepPath); browseResponse.populateItemResults(tierResponse.getResultList()); } assignCounts(browseRequest.getSearchState(), principals, browseResponse.getResultList()); filterToDirectMatches(browseRequest, browseResponse); browseResponse.generateResultTree(); retrieveFacets(browseRequest, browseResponse); return browseResponse; }</code><technical_language>store path.getFacetNodes() in a var below</technical_language>

Target:
public HierarchicalBrowseResultResponse getExpandedStructurePath(HierarchicalBrowseRequest browseRequest) { HierarchicalBrowseResultResponse browseResponse = new HierarchicalBrowseResultResponse(); AccessGroupSet principals = browseRequest.getAccessGroups(); BriefObjectMetadata contentRootMd = getContentRootMetadata(principals); browseResponse.getResultList().add(contentRootMd); CutoffFacet path = getObjectPath(browseRequest.getRootPid(), principals); List<HierarchicalFacetNode> pathFacetNodes = path.getFacetNodes(); if (pathFacetNodes == null) { return browseResponse; } CutoffFacet stepPath = new CutoffFacet(ANCESTOR_PATH.name(), asList(), 0); for (HierarchicalFacetNode stepFacetNode : pathFacetNodes) { stepPath.addNode(stepFacetNode); SearchState stepState = new SearchState(browseRequest.getSearchState()); HierarchicalBrowseRequest stepRequest = new HierarchicalBrowseRequest(stepState, 1, principals); HierarchicalBrowseResultResponse tierResponse = retrieveTier(stepRequest, stepPath); browseResponse.populateItemResults(tierResponse.getResultList()); } assignCounts(browseRequest.getSearchState(), principals, browseResponse.getResultList()); filterToDirectMatches(browseRequest, browseResponse); browseResponse.generateResultTree(); retrieveFacets(browseRequest, browseResponse); return browseResponse; }
Source:
<code>void cleanup () { for (Entry<String, CacheFileCopy> entry : this.filesTable.entrySet()) { <START> String tempFilePathname = RAImageIngestModule.getRATempPath(currentCase, moduleName) + File.separator + entry.getKey(); <END> try { entry.getValue().getFileCopy().getChannel().close(); entry.getValue().getFileCopy().close(); File tmpFile = new File(tempFilePathname); if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } catch (IOException ex) { logger.log(Level.WARNING, String.format("Failed to delete cache file copy %s", tempFilePathname), ex); } } }</code><technical_language>I suggest Paths call toFile Path object</technical_language>

Target:
void cleanup () { for (Entry<String, CacheFileCopy> entry : this.filesTable.entrySet()) { Path tempFilePath = Paths.get(RAImageIngestModule.getRATempPath(currentCase, moduleName), entry.getKey() ); try { entry.getValue().getFileCopy().getChannel().close(); entry.getValue().getFileCopy().close(); File tmpFile = tempFilePath.toFile(); if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } catch (IOException ex) { logger.log(Level.WARNING, String.format("Failed to delete cache file copy %s", tempFilePath.toString()), ex); } } }
Source:
<code>final static public < A extends LongAccess > ArrayImg< UnsignedVariableBitLengthType, A > unsignedVariableBitLengths( final A access, final int nbits, final long... dim ) { <START> final ArrayImg< UnsignedVariableBitLengthType, A > img = new ArrayImg<>( access, dim, new Fraction( 1, 64 ) ); <END> final UnsignedVariableBitLengthType t = new UnsignedVariableBitLengthType( img, nbits ); img.setLinkedType( t ); return img; }</code><technical_language>this new Fraction( t.getBitsPerPixel(), 64 ) instead of new Fraction( 1, 64 ) here</technical_language>

Target:
final static public < A extends LongAccess > ArrayImg< UnsignedVariableBitLengthType, A > unsignedVariableBitLengths( final A access, final int nbits, final long... dim ) { final ArrayImg< UnsignedVariableBitLengthType, A > img = new ArrayImg<>( access, dim, new Fraction( nbits, 64 ) ); final UnsignedVariableBitLengthType t = new UnsignedVariableBitLengthType( img, nbits ); img.setLinkedType( t ); return img; }
Source:
<code>private long measureMachinePerformance() { Random r = new Random(); final int NUMBER_ITERATIONS = 20000; double counter = 0.0; long start = System.currentTimeMillis(); for (int i = 0; i < NUMBER_ITERATIONS; i++) { <START> counter += r.nextDouble(); <END> } if (counter < 0) logger.info("this should never happen."); return System.currentTimeMillis() - start; }</code><technical_language>STDERR</technical_language>

Target:
private long measureMachinePerformance() { Random r = new Random(); final int NUMBER_ITERATIONS = 20000; double counter = 0.0; long start = System.currentTimeMillis(); for (int i = 0; i < NUMBER_ITERATIONS; i++) { counter += r.nextDouble(); } if (counter < 0) System.err.println("this should never happen."); return System.currentTimeMillis() - start; }
Source:
<code>public Path generateArtifact(URI uri, int size) throws IOException { <START> PypiWheelArtifactCoordinates coordinates = PypiWheelArtifactCoordinates.parse(FilenameUtils.getName(uri.getPath())); <END> return generateArtifact(coordinates); }</code><technical_language>@Firstmol uri.toString() here, instead of uri.getPath()</technical_language>

Target:
public Path generateArtifact(URI uri, int size) throws IOException { PypiWheelArtifactCoordinates coordinates = PypiWheelArtifactCoordinates.parse(FilenameUtils.getName(uri.toString())); return generateArtifact(coordinates); }
Source:
<code>public String addOrUpdateEntity(Referenceable referenceable, String uniqueAttrId) throws AtlasException { log.debug("Updating new entity [{}]", referenceable); Object attrValue = referenceable.getValuesMap().get(uniqueAttrId); Collection<Referenceable> entities = getEntities(referenceable.getTypeName(), Collections.singletonMap(uniqueAttrId, attrValue)); if (entities.isEmpty()) { Referenceable newEntity = new Referenceable(referenceable.getTypeName(), referenceable.getValuesMap()); return createEntity(newEntity); } Referenceable entity = entities.iterator().next(); entity.getValuesMap().clear(); entity.getValuesMap().putAll(referenceable.getValuesMap()); String entityJSON = InstanceSerialization.toJson(entity, true); AtlasClient.EntityResult entityResult = _updateEntities(entityJSON); log.debug("Updated instance for type [{}]", referenceable.getTypeName() + ", guids: " + entityResult.getUpdateEntities()); List<String> result = null; List<String> createdEntities = entityResult.getCreatedEntities(); if(createdEntities != null && !createdEntities.isEmpty()) { result = createdEntities; } else { result = entityResult.getUpdateEntities(); } <START> return result!= null && !result.isEmpty() ? result.get(0) : null; <END> }</code><technical_language>space "!" "result != null</technical_language>

Target:
public String addOrUpdateEntity(Referenceable referenceable, String uniqueAttrId) throws AtlasException { LOG.debug("Updating new entity [{}]", referenceable); Object attrValue = referenceable.getValuesMap().get(uniqueAttrId); Collection<Referenceable> entities = getEntities(referenceable.getTypeName(), Collections.singletonMap(uniqueAttrId, attrValue)); String result = null; if (entities.isEmpty()) { Referenceable newEntity = new Referenceable(referenceable.getTypeName(), referenceable.getValuesMap()); result = createEntity(newEntity); } else { Referenceable entity = entities.iterator().next(); entity.getValuesMap().clear(); entity.getValuesMap().putAll(referenceable.getValuesMap()); String entityJSON = InstanceSerialization.toJson(entity, true); AtlasClient.EntityResult entityResult = _updateEntities(entityJSON); LOG.debug("Updated instance for type [{}]", referenceable.getTypeName() + ", guids: " + entityResult.getUpdateEntities()); List<String> entityIds = null; List<String> createdEntities = entityResult.getCreatedEntities(); if (createdEntities != null && !createdEntities.isEmpty()) { entityIds = createdEntities; } else { entityIds = entityResult.getUpdateEntities(); } if (entityIds != null && !entityIds.isEmpty()) { result = entityIds.get(0); } } return result; }
Source:
<code>public void refreshGlusterServices() { if (getServiceNameMap().isEmpty()) { populateServiceMap(); } List<VDSGroup> clusters = getClusterDao().getAll(); for (VDSGroup cluster : clusters) { if (supportsGlusterServicesFeature(cluster)) { try { List<VDS> upServers = getClusterUtils().getAllUpServers(cluster.getId()); List<VDS> servers = getClusterUtils().getAllServers(cluster.getId()); List<Callable<Map<String, GlusterServiceStatus>>> taskListForNonRunningServers = createTaskListForNonRunningServers(servers); if (taskListForNonRunningServers != null && taskListForNonRunningServers.size() > 0) { ThreadPoolUtil.invokeAll(taskListForNonRunningServers); } log.debugFormat("Syncing gluster related services for cluster {0}", cluster.getname()); List<Callable<Map<String, GlusterServiceStatus>>> taskList = createTaskList(upServers); if (taskList != null && taskList.size() > 0) { refreshClusterServices(cluster, ThreadPoolUtil.invokeAll(createTaskList(upServers))); <START> } <END> } catch (Exception e) { log.errorFormat("Error while refreshing service statuses of cluster {0}!", cluster.getname(), e); } } } }</code><technical_language>if servers of cluster is down, cluster level status get updated</technical_language>

Target:
public void refreshGlusterServices() { if (getServiceNameMap().isEmpty()) { populateServiceMap(); } List<VDSGroup> clusters = getClusterDao().getAll(); for (VDSGroup cluster : clusters) { if (supportsGlusterServicesFeature(cluster)) { try { List<VDS> serversList = getClusterUtils().getAllServers(cluster.getId()); List<Callable<Map<String, GlusterServiceStatus>>> taskList = createTaskList(serversList); if (taskList != null && taskList.size() > 0) { refreshClusterServices(cluster, ThreadPoolUtil.invokeAll(taskList)); } } catch (Exception e) { log.errorFormat("Error while refreshing service statuses of cluster {0}!", cluster.getname(), e); } } } }
Source:
<code>public GitService call() throws Exception { <START> configProperties = configManager.getDefaultProperties(); <END> branch = configProperties.getProperty("com.meltmedia.cadmium.branch"); repoUri = configProperties.getProperty("com.meltmedia.cadmium.git.uri"); GitService cloned = null; if(repoUri != null && branch != null) { Throwable t = null; try { logger.debug("Attempting to initialize content for `{}` into `{}`", warName, contentRoot); cloned = GitService.initializeContentDirectory(repoUri, branch, contentRoot, warName, historyManager, configManager); if(metaProcessor != null) { logger.debug("Processing META-INF dir in `{}`", warName); this.metaProcessor.processDir(contentDirectory); } if(servlet != null) { logger.debug("Switching content root of {}", warName); this.servlet.switchContent(System.currentTimeMillis()); } logger.debug("Successfully initialized `{}`", warName); } catch(RefNotFoundException e) { logger.warn("Branch `"+branch+"` does not exist.", e); return null; } catch(Throwable t1) { logger.error("Failed to initialize git repo `"+warName+"`", t); t = t1; } if(t != null) { throw new Exception(t); } } return cloned; }</code><technical_language>This broken. This field is reset time this method is called. This variable (and two) local this method</technical_language>

Target:
public GitService call() throws Exception { Properties configProperties = configManager.getDefaultProperties(); String branch = configProperties.getProperty("com.meltmedia.cadmium.branch"); String repoUri = configProperties.getProperty("com.meltmedia.cadmium.git.uri"); GitService cloned = null; if(repoUri != null && branch != null) { Throwable t = null; try { logger.debug("Attempting to initialize content for `{}` into `{}`", warName, contentRoot); cloned = GitService.initializeContentDirectory(repoUri, branch, contentRoot, warName, historyManager, configManager); if(metaProcessor != null) { logger.debug("Processing META-INF dir in `{}`", warName); this.metaProcessor.processDir(contentDirectory); } if(servlet != null) { logger.debug("Switching content root of {}", warName); this.servlet.switchContent(System.currentTimeMillis()); } logger.debug("Successfully initialized `{}`", warName); } catch(RefNotFoundException e) { logger.warn("Branch `"+branch+"` does not exist.", e); return null; } catch(Throwable t1) { logger.error("Failed to initialize git repo `"+warName+"`", t); t = t1; } if(t != null) { throw new Exception(t); } } return cloned; }
Source:
<code>protected void createCacheManagers() throws Throwable { Configuration replSync = getDefaultClusteredConfig(Configuration.CacheMode.REPL_SYNC); Configuration replAsync = getDefaultClusteredConfig(Configuration.CacheMode.REPL_ASYNC); Configuration invalSync = getDefaultClusteredConfig(Configuration.CacheMode.INVALIDATION_SYNC); Configuration invalAsync = getDefaultClusteredConfig(Configuration.CacheMode.INVALIDATION_ASYNC); Configuration local = getDefaultClusteredConfig(Configuration.CacheMode.LOCAL); createClusteredCaches(2, "replSync", replSync); defineConfigurationOnAllManagers("replAsync", replAsync); waitForClusterToForm("replAsync"); defineConfigurationOnAllManagers("invalSync", invalSync); waitForClusterToForm("invalSync"); defineConfigurationOnAllManagers("invalAsync", invalAsync); waitForClusterToForm("invalAsync"); defineConfigurationOnAllManagers("local", local); <START> waitForClusterToForm("local"); <END> }</code><technical_language>I this is necessary..</technical_language>

Target:
protected void createCacheManagers() throws Throwable { Configuration replSync = getDefaultClusteredConfig(Configuration.CacheMode.REPL_SYNC); Configuration replAsync = getDefaultClusteredConfig(Configuration.CacheMode.REPL_ASYNC); Configuration invalSync = getDefaultClusteredConfig(Configuration.CacheMode.INVALIDATION_SYNC); Configuration invalAsync = getDefaultClusteredConfig(Configuration.CacheMode.INVALIDATION_ASYNC); Configuration local = getDefaultClusteredConfig(Configuration.CacheMode.LOCAL); createClusteredCaches(2, "replSync", replSync); defineConfigurationOnAllManagers("replAsync", replAsync); waitForClusterToForm("replAsync"); defineConfigurationOnAllManagers("invalSync", invalSync); waitForClusterToForm("invalSync"); defineConfigurationOnAllManagers("invalAsync", invalAsync); waitForClusterToForm("invalAsync"); defineConfigurationOnAllManagers("local", local); }