auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void customizeBinding(Map<String, Object> binding, Cell cell, boolean html, ServiceProvider provider, Locale locale) { FunctionDefinition<? extends ParameterDefinition> function = loadFunction( cell.getTransformationIdentifier(), provider); binding.put("_constraintsEvaluated", false); binding.put("_hasValue", false); binding.put("_isReference", false); <START> if (!function.getTarget().isEmpty() && !cell.getTarget().isEmpty()) { <END> ParameterDefinition parameterDefinition = function.getTarget().iterator().next(); Entity entity = cell.getTarget().get(parameterDefinition.getName()).iterator().next(); if (entity != null) { ChildContext childContext = entity.getDefinition().getPropertyPath().iterator() .next(); PropertyDefinition resultProperty = childContext.getChild().asProperty(); TypeDefinition resultPropertyType = resultProperty.getPropertyType(); boolean isReference = resultProperty.getConstraint(Reference.class).isReference(); binding.put("_isReference", isReference); if (!isReference) { boolean hasValue = resultPropertyType.getConstraint(HasValueFlag.class) .isEnabled(); binding.put("_hasValue", hasValue); } else { binding.put("_hasValue", true); } binding.put("_constraintsEvaluated", true); } } }</code><technical_language>I need function information here. function target, need differentiate. CellUtil.getFirstEntity(cell.getTarget()) get target entity. avoids problem cell.getTarget() (in theory) null</technical_language>

Target:
protected void customizeBinding(Map<String, Object> binding, Cell cell, boolean html, ServiceProvider provider, Locale locale) { binding.put("_constraintsEvaluated", false); binding.put("_hasValue", false); binding.put("_isReference", false); Entity entity = CellUtil.getFirstEntity(cell.getTarget()); if (entity != null && entity.getDefinition().getDefinition() instanceof PropertyDefinition) { PropertyDefinition resultProperty = (PropertyDefinition) entity.getDefinition() .getDefinition(); TypeDefinition resultPropertyType = resultProperty.getPropertyType(); boolean isReference = resultProperty.getConstraint(Reference.class).isReference(); binding.put("_isReference", isReference); if (isReference) { binding.put("_hasValue", true); } else { boolean hasValue = resultPropertyType.getConstraint(HasValueFlag.class).isEnabled(); binding.put("_hasValue", hasValue); } binding.put("_constraintsEvaluated", true); } }
Source:
<code>public void startServer() throws IOException, CommandFailedException { controller.start(ManualTests.ARQUILLIAN_CONTAINER); offlineClient = ManagementClient.offline( OfflineOptions.standalone() .rootDirectory(new File(System.getProperty("user.dir"), "target/jboss-as")) .configurationFile("standalone.xml") .build()); <START> offlineClient.apply(CONFIGURATION_BACKUP.backup()); <END> }</code><technical_language>I do backup first, start server</technical_language>

Target:
public void startServer() throws IOException, CommandFailedException { offlineClient = ManagementClient.offline( OfflineOptions.standalone() .rootDirectory(new File(System.getProperty("user.dir"), "target/jboss-as")) .configurationFile("standalone.xml") .build()); offlineClient.apply(CONFIGURATION_BACKUP.backup()); controller.start(ManualTests.ARQUILLIAN_CONTAINER); }
Source:
<code>public static SubmoduleWalk forPath(Repository repository, AnyObjectId treeId, String path) throws IOException { try (SubmoduleWalk generator = new SubmoduleWalk(repository)) { generator.setTree(treeId); PathFilter filter = PathFilter.create(path); generator.setFilter(filter); generator.setRootTree(treeId); <START> while (generator.next()) if (filter.isDone(generator.walk)) { return generator; } return null; <END> } catch (IOException e) { throw e; } }</code><technical_language>Please add braces while-block. I initially thought 'return null' is done while</technical_language>

Target:
public static SubmoduleWalk forPath(Repository repository, AnyObjectId treeId, String path) throws IOException { try (SubmoduleWalk generator = new SubmoduleWalk(repository)) { try { generator.setTree(treeId); PathFilter filter = PathFilter.create(path); generator.setFilter(filter); generator.setRootTree(treeId); while (generator.next()) if (filter.isDone(generator.walk)) return generator; } catch (IOException e) { generator.close(); throw e; } } return null; }
Source:
<code>public ILaunchConfiguration[] getMappedConfigurations(IResource resource) { List<ILaunchConfiguration> configurations = new ArrayList<>(); for (ILaunchConfiguration config : getAllLaunchConfigurations()) { try { IResource[] resources = config.getMappedResources(); if(resources != null) { for (IResource <START> resource2 : <END> resources) { if(resource2.equals(resource)) { configurations.add(config); break; } else if (resource.getType() == IResource.PROJECT && resource2.getType() == IResource.FILE){ if (resource2.getProject().equals(resource)) { configurations.add(config); break; } } } } } catch (CoreException ce) { DebugPlugin.log(ce); } } return configurations.toArray(new ILaunchConfiguration[configurations.size()]); }</code><technical_language>rename res</technical_language>

Target:
public ILaunchConfiguration[] getMappedConfigurations(IResource resource) { List<ILaunchConfiguration> configurations = new ArrayList<>(); for (ILaunchConfiguration config : getAllLaunchConfigurations()) { try { IResource[] resources = config.getMappedResources(); if(resources != null) { for (IResource res : resources) { if(res.equals(resource)) { configurations.add(config); break; } else if (resource.getType() == IResource.PROJECT && res.getType() == IResource.FILE){ if (res.getProject().equals(resource)) { configurations.add(config); break; } } } } } catch (CoreException ce) { DebugPlugin.log(ce); } } return configurations.toArray(new ILaunchConfiguration[configurations.size()]); }
Source:
<code>public void setNewName(String newName) { this.fRenameResourceProcessor.setNewResourceName(newName); super.setForcePreview(true); <START> super.setForceFinish(true); <END> }</code><technical_language>Instead of calling 2 setters, try invoking validatePage care of fixing button enablement</technical_language>

Target:
public void setNewName(String newName) { this.fRenameResourceProcessor.setNewResourceName(newName); }
Source:
<code>private List<RichAttribute> getUserFacilityAttributes(PerunSession sess, Vo vo, AttributeDefinition attrDef) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { List<RichAttribute> listOfRichAttributes = new ArrayList<>(); List<Group> groupsFromVo = getPerunBl().getGroupsManagerBl().getGroups(sess, vo); for (Group groupElement : groupsFromVo) { List<Facility> groupFacilities = getPerunBl().getFacilitiesManagerBl().getAssignedFacilities(sess, groupElement); <START> List<Member> groupMembers = getPerunBl().getGroupsManagerBl().getGroupMembersExceptInvalid(sess, groupElement); <END> List<User> groupUsers = new ArrayList<>(); for (Member memberElement : groupMembers) { groupUsers.add(getPerunBl().getUsersManagerBl().getUserByMember(sess, memberElement)); } for (Facility facilityElement : groupFacilities) { for (User userElement : groupUsers) { Attribute attribute = getPerunBl().getAttributesManagerBl().getAttribute(sess, facilityElement, userElement, attrDef.getName()); listOfRichAttributes.add(new RichAttribute<>(facilityElement, userElement, attribute)); } } } listOfRichAttributes = new ArrayList<>(new HashSet<>(listOfRichAttributes)); return listOfRichAttributes; }</code><technical_language>careful, this is "isMemberAllowed", this return "disabled" members allowed</technical_language>

Target:
private List<RichAttribute> getUserFacilityAttributes(PerunSession sess, Vo vo, AttributeDefinition attrDef) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { List<RichAttribute> listOfRichAttributes = new ArrayList<>(); List<Group> groupsFromVo = getPerunBl().getGroupsManagerBl().getGroups(sess, vo); for (Group groupElement : groupsFromVo) { List<Facility> groupFacilities = getPerunBl().getFacilitiesManagerBl().getAssignedFacilities(sess, groupElement); List<Member> groupMembers = getPerunBl().getGroupsManagerBl().getGroupMembers(sess, groupElement); List<Member> allowedMembers = new ArrayList<>(); for(Member memberElement : groupMembers) { if(getPerunBl().getMembersManagerBl().isMemberAllowed(sess, memberElement)) { allowedMembers.add(memberElement); } } List<User> groupUsers = new ArrayList<>(); for (Member memberElement : allowedMembers) { groupUsers.add(getPerunBl().getUsersManagerBl().getUserByMember(sess, memberElement)); } for (Facility facilityElement : groupFacilities) { for (User userElement : groupUsers) { Attribute attribute = getPerunBl().getAttributesManagerBl().getAttribute(sess, facilityElement, userElement, attrDef.getName()); listOfRichAttributes.add(new RichAttribute<>(facilityElement, userElement, attribute)); } } } listOfRichAttributes = new ArrayList<>(new HashSet<>(listOfRichAttributes)); return listOfRichAttributes; }
Source:
<code>private PyUDFExpression() { name = ""; outputType = Type.BLOB_TYPE; <START> } <END></code><technical_language>I understand this is used, BLOB_TYPE is default here. give example of it</technical_language>

Target:
private PyUDFExpression()
Source:
<code>public JcrNode addNode( String repository, String workspace, String path, String name, String primaryType ) throws RemoteException { Session session = connector().find(repository).session(workspace); try { Node parent = (Node)session.getItem(path); Node n = parent.addNode(name, primaryType); JcrNode node = new JcrNode(repository, workspace, n.getName(), n.getPath(), n.getPrimaryNodeType().getName()); node.setMixins(mixinTypes(n)); node.setProperties(getProperties(repository, workspace, path, n)); node.setPropertyDefs(propertyDefs(n)); return node; } catch (RepositoryException e) { <START> e.printStackTrace(); <END> throw new RemoteException(e.getMessage()); } }</code><technical_language>logging this instead</technical_language>

Target:
public JcrNode addNode( String repository, String workspace, String path, String name, String primaryType ) throws RemoteException { Session session = connector().find(repository).session(workspace); try { Node parent = (Node)session.getItem(path); Node n = parent.addNode(name, primaryType); JcrNode node = new JcrNode(repository, workspace, n.getName(), n.getPath(), n.getPrimaryNodeType().getName()); node.setMixins(mixinTypes(n)); node.setProperties(getProperties(repository, workspace, path, n)); node.setPropertyDefs(propertyDefs(n)); return node; } catch (RepositoryException e) { logger.debug("Could not add node: " + e.getMessage()); throw new RemoteException(e.getMessage()); } }
Source:
<code>protected void executeCommand() { Guid storageDomainId = getStorageDomainId(); StoragePoolParametersBase parameters = new StoragePoolParametersBase(getStoragePoolId()); ActionReturnValue actionReturnValue = runInternalAction(ActionType.ProcessOvfUpdateForStoragePool, parameters, getContext()); Set<Guid> proccessedDomains = actionReturnValue.getActionReturnValue(); if (actionReturnValue.getSucceeded() && proccessedDomains != null && proccessedDomains.contains(storageDomainId)) { runInternalActionWithTasksContext(ActionType.ProcessOvfUpdateForStorageDomain, createProcessOvfUpdateForDomainParams()); } <START> log.info("OVFs update was ignored - nothing to update for storage domain '{}'", storageDomainId); <END> setSucceeded(true); }</code><technical_language>else clause, no</technical_language>

Target:
protected void executeCommand() { Guid storageDomainId = getStorageDomainId(); StoragePoolParametersBase parameters = new StoragePoolParametersBase(getStoragePoolId()); ActionReturnValue actionReturnValue = runInternalAction(ActionType.ProcessOvfUpdateForStoragePool, parameters, getContext()); Set<Guid> proccessedDomains = actionReturnValue.getActionReturnValue(); if (actionReturnValue.getSucceeded() && proccessedDomains != null && proccessedDomains.contains(storageDomainId)) { runInternalActionWithTasksContext(ActionType.ProcessOvfUpdateForStorageDomain, createProcessOvfUpdateForDomainParams()); } else { log.info("OVFs update was ignored - nothing to update for storage domain '{}'", storageDomainId); } setSucceeded(true); }
Source:
<code>static public DecimalType deviationSince(Item item, AbstractInstant timestamp, String serviceName) { <START> DecimalType variance = varianceSince(item, timestamp, defaultService); <END> double deviation = Math.sqrt(variance.doubleValue()); return new DecimalType(deviation); }</code><technical_language>please change "defaultService" "serviceName"</technical_language>

Target:
static public DecimalType deviationSince(Item item, AbstractInstant timestamp, String serviceName) { DecimalType variance = varianceSince(item, timestamp, serviceName); double deviation = Math.sqrt(variance.doubleValue()); return new DecimalType(deviation); }
Source:
<code>public void postFailure(NamingException ex, int retryCount) { super.postFailure(ex, retryCount); <START> LOGGER.info("Retry failure: {}\n Retrying in seconds", ex.getLocalizedMessage(), getRetryInterval(retryCount) / 1000); <END> }</code><technical_language>expection is swallowed. \\n in log messages avoided. about: LOGGER.info("Retry failure. Retrying in seconds", getRetryInterval(retryCount) / 1000, ex);</technical_language>

Target:
public void postFailure(NamingException ex, int retryCount) { super.postFailure(ex, retryCount); LOGGER.info("Retry failure. Retrying in seconds", getRetryInterval(retryCount) / 1000, ex); }
Source:
<code>public FormValidation doCheckExample(@QueryParameter final String example, @QueryParameter final String regexp, @QueryParameter final String script) { if (StringUtils.isNotBlank(example) && StringUtils.isNotBlank(regexp) && StringUtils.isNotBlank(script)) { FormValidation response = parseExample(script, example, regexp, containsNewline(regexp)); if (example.length() <= MAX_EXAMPLE_SIZE) { return response; } <START> return FormValidation.aggregate(Arrays.asList(FormValidation.warning("Long examples will be truncated"), response)); <END> } else { return FormValidation.ok(); } }</code><technical_language>replace a localizable message</technical_language>

Target:
public FormValidation doCheckExample(@QueryParameter final String example, @QueryParameter final String regexp, @QueryParameter final String script) { if (StringUtils.isNotBlank(example) && StringUtils.isNotBlank(regexp) && StringUtils.isNotBlank(script)) { FormValidation response = parseExample(script, example, regexp, containsNewline(regexp)); if (example.length() <= MAX_EXAMPLE_SIZE) { return response; } return FormValidation.aggregate(Arrays.asList(FormValidation.warning(Messages.GroovyParser_long_examples_will_be_truncated()), response)); } else { return FormValidation.ok(); } }
Source:
<code>public void test_getListBlobItemDruidFactory_canCreateListBlobItemDruid() { <START> final Properties props = new Properties(); props.put("druid.azure.account", AZURE_ACCOUNT_NAME); props.put("druid.azure.key", AZURE_ACCOUNT_KEY); props.put("druid.azure.container", AZURE_CONTAINER); injector = makeInjectorWithProperties(props); <END> ListBlobItemHolderFactory factory = injector.getInstance(ListBlobItemHolderFactory.class); ListBlobItemHolder object1 = factory.create(blobItem1); ListBlobItemHolder object2 = factory.create(blobItem2); Assert.assertNotNull(object1); Assert.assertNotNull(object2); Assert.assertNotSame(object1, object2); }</code><technical_language>I this duplicated in a lot of tests, put in utility function</technical_language>

Target:
public void test_getListBlobItemDruidFactory_canCreateListBlobItemDruid() { injector = makeInjectorWithProperties(PROPERTIES); ListBlobItemHolderFactory factory = injector.getInstance(ListBlobItemHolderFactory.class); ListBlobItemHolder object1 = factory.create(blobItem1); ListBlobItemHolder object2 = factory.create(blobItem2); Assert.assertNotNull(object1); Assert.assertNotNull(object2); Assert.assertNotSame(object1, object2); }
Source:
<code>protected Image getDecorationImage(EditPart editPart) { if (isBroken(editPart)) { return WorkspaceImageFigure.flyWeightImage("/org.eclipse.sirius.diagram.ui/icons/delete.gif"); <START> } else { <END> return DiagramUIPlugin.getPlugin().getImage(SiriusEditPlugin.Implementation.getBundledImageDescriptor("icons/full/decorator/permission_denied.gif")); } }</code><technical_language>I return DiagramUIPlugin.Implementation.getBundledImageDescriptor(DiagramImagesPath.DELETE_FROM_DIAGRAM_ICON) instead of create a new image call</technical_language>

Target:
protected Image getDecorationImage(EditPart editPart) { if (isBroken(editPart)) { return DiagramUIPlugin.getPlugin().getImage(DiagramUIPlugin.Implementation.getBundledImageDescriptor(DiagramImagesPath.DELETE_FROM_DIAGRAM_ICON)); } else { return DiagramUIPlugin.getPlugin().getImage(SiriusEditPlugin.Implementation.getBundledImageDescriptor("icons/full/decorator/permission_denied.gif")); } }
Source:
<code>public Object setArg(String key, Object value) { Object oldVal = allArgs.put(key, value); <START> allArgsReadOnly = Collections.unmodifiableMap(allArgs); <END> return oldVal; }</code><technical_language>is this step needed? changing underlying map changed this too</technical_language>

Target:
public Object setArg(String key, Object value) { return allArgs.put(key, value); }
Source:
<code>public void locatorLauncherUsesSpecifiedConfigFileWithGeodePlugins() throws Exception { ProcessBuilder processBuilder = new ProcessBuilder() .redirectErrorStream(true) .redirectOutput(stdoutFile.toFile()) .directory(temporaryFolder.getRoot()) .command("java", "-Dgemfire.http-service-port=" + httpServicePort, "-Dgemfire.jmx-manager-start=true", "-Djava.awt.headless=true", "-Dlog4j.configurationFile=" + configWithGeodePluginsFile.toAbsolutePath(), "-cp", geodeDependencies.toFile().getAbsolutePath(), "org.apache.geode.distributed.LocatorLauncher", "start", LOCATOR_NAME, "--port", String.valueOf(locatorPort)); System.out.println("Launching command: " + processBuilder.command()); locator = processBuilder .start(); assertThat(locator.isAlive()).isTrue(); await().untilAsserted(() -> { assertThat(locatorLogFile) .doesNotExist(); <START> assertThat(pulseLogFile) <END> .doesNotExist(); LogFileAssert.assertThat(stdoutFile.toFile()) .exists() .contains("Located war: geode-pulse") .contains("Adding webapp /pulse") .contains("Starting server location for Distribution Locator") .doesNotContain("geode-pulse war file was not found") .doesNotContain("java.lang.IllegalStateException: No factory method found for class"); }); }</code><technical_language>understanding is GEODE-8197 related bug is fixed, this @Ignore annotation removed</technical_language>

Target:
public void locatorLauncherUsesSpecifiedConfigFileWithGeodePlugins() throws Exception { ProcessBuilder processBuilder = new ProcessBuilder() .redirectErrorStream(true) .redirectOutput(stdoutFile.toFile()) .directory(temporaryFolder.getRoot()) .command(javaBin.toFile().getAbsolutePath(), "-Dgemfire.http-service-port=" + httpServicePort, "-Dgemfire.jmx-manager-start=true", "-Djava.awt.headless=true", "-Dlog4j.configurationFile=" + configWithGeodePluginsFile.toAbsolutePath(), "-cp", geodeDependencies.toFile().getAbsolutePath(), "org.apache.geode.distributed.LocatorLauncher", "start", LOCATOR_NAME, "--port", String.valueOf(locatorPort)); System.out.println("Environment: " + System.getenv()); System.out.println("Launching command: " + processBuilder.command()); locator = processBuilder .start(); assertThat(locator.isAlive()).isTrue(); await().untilAsserted(() -> { assertThat(locatorLogFile) .as(locatorLogFile.toFile().getAbsolutePath()) .doesNotExist(); assertThat(pulseLogFile) .as(pulseLogFile.toFile().getAbsolutePath()) .doesNotExist(); LogFileAssert.assertThat(stdoutFile.toFile()) .as(stdoutFile.toFile().getAbsolutePath()) .exists() .contains("Located war: geode-pulse") .contains("Adding webapp /pulse") .contains("Starting server location for Distribution Locator") .doesNotContain("geode-pulse war file was not found") .doesNotContain("java.lang.IllegalStateException: No factory method found for class"); }); }
Source:
<code>private boolean isTaskCompleted( ScheduledTask<?> task ) { <START> return !task.getTaskState().isActiveOrSubmitted(); <END> }</code><technical_language>if task is SLEEPING is completed? this hide task is sleeping run</technical_language>

Target:
private boolean isTaskCompleted( ScheduledTask<?> task ) { return TaskState.WAITING.equals( task.getTaskState() ) || TaskState.FINISHED.equals( task.getTaskState() ) || TaskState.BROKEN.equals( task.getTaskState() ) || TaskState.CANCELLED.equals( task.getTaskState() ); }
Source:
<code>public double pvbp(KnownAmountPaymentPeriod period, RatesProvider provider) { <START> return 0; <END> }</code><technical_language>If result calculated, throw UnsupportedOperationException</technical_language>

Target:
public double pvbp(KnownAmountPaymentPeriod period, RatesProvider provider) { throw new UnsupportedOperationException("Unable to calculate PVBP for KnownAmountPaymentPeriod"); }
Source:
<code>public void install(File artifact) throws Exception { LOGGER.debug("ConnectorDeployer.install(\"{}\")", artifact.getAbsolutePath()); ConnectorFile configFile = oldConfigs.get(artifact); Dictionary<String, Object> properties = new Hashtable<String, Object>(configFile.getProperties()); if (properties.get(Constants.SERVICE_RANKING) == null && ConnectorFile.isRootService(artifact)) { properties.put(Constants.SERVICE_RANKING, "-1"); } LOGGER.info("Loading instance {}", configFile.getConnectorId()); <START> authenticate(AUTH_USER, AUTH_PASSWORD); <END> serviceManager.create(configFile.getConnectorId(), new ConnectorDescription(configFile.getAttributes(), properties)); }</code><technical_language>log-out action again</technical_language>

Target:
public void install(File artifact) throws Exception { LOGGER.debug("ConnectorDeployer.install(\"{}\")", artifact.getAbsolutePath()); ConnectorFile configFile = oldConfigs.get(artifact); Dictionary<String, Object> properties = new Hashtable<String, Object>(configFile.getProperties()); if (properties.get(Constants.SERVICE_RANKING) == null && ConnectorFile.isRootService(artifact)) { properties.put(Constants.SERVICE_RANKING, "-1"); } LOGGER.info("Loading instance {}", configFile.getConnectorId()); login(); try { serviceManager.create(configFile.getConnectorId(), new ConnectorDescription(configFile.getAttributes(), properties)); } finally { logout(); } }
Source:
<code>public LanePhasingMetricsCollector(final Collection<Tile> laneTiles, boolean usePercentage) { final Map<TileTemplateRead, Float> medianPhasingMap = new TreeMap<TileTemplateRead, Float>(); final Map<TileTemplateRead, Float> medianPrePhasingMap = new TreeMap<TileTemplateRead, Float>(); final CollectionUtil.MultiMap<TileTemplateRead, Float> phasingValues = new CollectionUtil.MultiMap<TileTemplateRead, Float>(); final CollectionUtil.MultiMap<TileTemplateRead, Float> prePhasingValues = new CollectionUtil.MultiMap<TileTemplateRead, Float>(); for (final Tile tile : laneTiles) { for (final TileTemplateRead tileTemplateRead : tile.getPhasingMap().keySet()) { phasingValues.append(tileTemplateRead, tile.getPhasingMap().get(tileTemplateRead)); prePhasingValues.append(tileTemplateRead, tile.getPrePhasingMap().get(tileTemplateRead)); } } for (final TileTemplateRead tileTemplateRead : phasingValues.keySet()) { if (usePercentage) { <START> medianPhasingMap.put(tileTemplateRead, medianPercentage(phasingValues.get(tileTemplateRead))); <END> medianPrePhasingMap.put(tileTemplateRead, medianPercentage(prePhasingValues.get(tileTemplateRead))); } else { medianPhasingMap.put(tileTemplateRead, median(phasingValues.get(tileTemplateRead))); medianPrePhasingMap.put(tileTemplateRead, median(prePhasingValues.get(tileTemplateRead))); } } this.medianPhasingMap = Collections.unmodifiableMap(medianPhasingMap); this.medianPrePhasingMap = Collections.unmodifiableMap(medianPrePhasingMap); }</code><technical_language>clearer a new method accepts usePercentage e.g. median(Collection<Float> phaseValues, boolean usePercentage). avoid some duplicate code too</technical_language>

Target:
public LanePhasingMetricsCollector(final Collection<Tile> laneTiles, boolean usePercentage) { final Map<TileTemplateRead, Float> medianPhasingMap = new TreeMap<TileTemplateRead, Float>(); final Map<TileTemplateRead, Float> medianPrePhasingMap = new TreeMap<TileTemplateRead, Float>(); final CollectionUtil.MultiMap<TileTemplateRead, Float> phasingValues = new CollectionUtil.MultiMap<TileTemplateRead, Float>(); final CollectionUtil.MultiMap<TileTemplateRead, Float> prePhasingValues = new CollectionUtil.MultiMap<TileTemplateRead, Float>(); for (final Tile tile : laneTiles) { for (final TileTemplateRead tileTemplateRead : tile.getPhasingMap().keySet()) { phasingValues.append(tileTemplateRead, tile.getPhasingMap().get(tileTemplateRead)); prePhasingValues.append(tileTemplateRead, tile.getPrePhasingMap().get(tileTemplateRead)); } } for (final TileTemplateRead tileTemplateRead : phasingValues.keySet()) { medianPhasingMap.put(tileTemplateRead, median(phasingValues.get(tileTemplateRead), usePercentage)); medianPrePhasingMap.put(tileTemplateRead, median(prePhasingValues.get(tileTemplateRead), usePercentage)); } this.medianPhasingMap = Collections.unmodifiableMap(medianPhasingMap); this.medianPrePhasingMap = Collections.unmodifiableMap(medianPrePhasingMap); }
Source:
<code>private void configureCommandFactoryProviders() { <START> if (getEditingDomain() != null) { <END> IDiagramCommandFactory diagramCommandFactory = emfCommandFactoryProvider.getCommandFactory(getEditingDomain()); diagramCommandFactory.setUserInterfaceCallBack(new EMFCommandFactoryUI()); } }</code><technical_language>define a local variable for ED</technical_language>

Target:
private void configureCommandFactoryProviders() { TransactionalEditingDomain domain = getEditingDomain(); if (domain != null) { IDiagramCommandFactory diagramCommandFactory = emfCommandFactoryProvider.getCommandFactory(domain); diagramCommandFactory.setUserInterfaceCallBack(new EMFCommandFactoryUI()); } }
Source:
<code>public <START> HashMap<String, <END> String> createImageServerContent(String scheme) throws IOException { HashMap<String, String> map = new HashMap<String, String>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; }</code><technical_language>return Map instead of HashMap</technical_language>

Target:
public Map<String, String> createImageServerContent(String scheme) throws IOException { HashMap<String, String> map = new HashMap<>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; }
Source:
<code>private Set<String> parseClientTags(HttpServletRequest servletRequest) { <START> Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings(); <END> return ImmutableSet.copyOf(splitter.splitToList(nullToEmpty(servletRequest.getHeader(PRESTO_CLIENT_TAGS)))); }</code><technical_language>This disallows tags commas. Is ok? Do want other restrictions</technical_language>

Target:
private Set<String> parseClientTags(HttpServletRequest servletRequest) { Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings(); return ImmutableSet.copyOf(splitter.split(nullToEmpty(servletRequest.getHeader(PRESTO_CLIENT_TAGS)))); }
Source:
<code>public void run() { WeakReference<Object> reference = new WeakReference<Object>(new Object()); <START> Runtime runtime = Runtime.getRuntime(); <END> for (int i = 0; i < 20; ++i) { runtime.gc(); System.runFinalization(); try { Thread.sleep(1); } catch (InterruptedException e) { throw new AssertionError(e); } if (reference.get() == null) { System.logI("Sentry object has been freed so assuming CloseGuards have reported" + " any resource leakages"); break; } } CloseGuard.setReporter(closeGuardReporter); if (!closeGuardAllocationSites.isEmpty()) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); int i = 0; for (Throwable allocationSite : closeGuardAllocationSites) { printWriter.print(++i); printWriter.print(") "); allocationSite.printStackTrace(printWriter); printWriter.println(" --------------------------------"); } throw new AssertionError("Potential resource leakage detected:\n" + writer); } }</code><technical_language>Hiroshi: Is a do this</technical_language>

Target:
public void run() { WeakReference<Object> reference = new WeakReference<Object>(new Object()); try { Runtime runtime = Runtime.getRuntime(); for (int i = 0; i < 20; ++i) { runtime.gc(); System.runFinalization(); try { Thread.sleep(1); } catch (InterruptedException e) { throw new AssertionError(e); } if (reference.get() == null) { System.logI("Sentry object has been freed so assuming CloseGuards have reported" + " any resource leakages"); break; } } } finally { CloseGuard.setReporter(closeGuardReporter); } if (!closeGuardAllocationSites.isEmpty()) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); int i = 0; for (Throwable allocationSite : closeGuardAllocationSites) { printWriter.print(++i); printWriter.print(") "); allocationSite.printStackTrace(printWriter); printWriter.println(" --------------------------------"); } throw new AssertionError("Potential resource leakage detected:\n" + writer); } }
Source:
<code>public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(mUser, flags); dest.writeString(mToken); dest.writeString(mSecret); try { ObjectOutputStream oos = new ObjectOutputStream(new ByteArrayOutputStream()); oos.writeObject(mException); <START> oos.close(); <END> dest.writeSerializable(mException); } catch (IOException e) { dest.writeSerializable(new FirebaseUiException(ErrorCodes.UNKNOWN_ERROR)); } }</code><technical_language>exception writeObject? If close stream in a finally block</technical_language>

Target:
public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(mUser, flags); dest.writeString(mToken); dest.writeString(mSecret); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new ByteArrayOutputStream()); oos.writeObject(mException); dest.writeSerializable(mException); } catch (IOException e) { dest.writeSerializable(new FirebaseUiException(ErrorCodes.UNKNOWN_ERROR)); } finally { if (oos != null) { try { oos.close(); } catch (IOException ignored) } } }
Source:
<code><START> protected boolean setAndValidateDiskProfiles() { <END> if (getImage() != null && DiskStorageType.IMAGE == getImage().getDiskStorageType()) { DiskImage diskImage = new DiskImage(); diskImage.setDiskProfileId(getParameters().getDiskProfileId()); Map<DiskImage, Guid> map = new HashMap<>(); map.put(diskImage, getParameters().getStorageDomainId()); return validate(DiskProfileHelper.setAndValidateDiskProfiles(map)); } return true; }</code><technical_language>this shoud executed if operation is "copy" (which is for template disks now, is disk profile relevant for template disks?). for a "move" scenario validated MoveDisksCommand</technical_language>

Target:
protected boolean setAndValidateDiskProfiles() { getImage().setDiskProfileId(getParameters().getDiskProfileId()); return validate(DiskProfileHelper.setAndValidateDiskProfiles(Collections.singletonMap(getImage(), getParameters().getStorageDomainId()))); }
Source:
<code>public void run() { try { InetSocketAddress connectAddr = new InetSocketAddress("127.0.0.1", 5140); ByteChannel out; if("tcp".equals(transport)) { SocketChannel channel = SocketChannel.open(); channel.connect(connectAddr); out = channel; } else { DatagramChannel channel = DatagramChannel.open(); channel.connect(connectAddr); out = channel; } ByteBuffer buff = ByteBuffer.wrap( ("<34>Oct 11 22:14:15 mymachine su: 'su root' failed for lonvick on /dev/pts/8\n").getBytes() ); for (int i = 0; i < runs; i++) { out.write(buff); buff.flip(); if("udp".equals(transport)) { Thread.sleep(5); } } out.close(); } <START> catch (IOException | InterruptedException e) { <END> throw new IllegalStateException(e); } }</code><technical_language>Unfortunately, multicatch syntax (Java 6 is min supported)</technical_language>

Target:
public void run() { try { InetSocketAddress connectAddr = new InetSocketAddress("127.0.0.1", 5140); ByteChannel out; if("tcp".equals(transport)) { SocketChannel channel = SocketChannel.open(); channel.connect(connectAddr); out = channel; } else { DatagramChannel channel = DatagramChannel.open(); channel.connect(connectAddr); out = channel; } ByteBuffer buff = ByteBuffer.wrap( ("<34>Oct 11 22:14:15 mymachine su: 'su root' failed for lonvick on /dev/pts/8\n").getBytes() ); for (int i = 0; i < runs; i++) { out.write(buff); buff.flip(); if("udp".equals(transport)) { Thread.sleep(5); } } out.close(); } catch (Exception e) { throw new IllegalStateException(e); } }
Source:
<code>public void testMqttSink() throws Exception { final int numSinks = 4; final List<String> outputStream = Arrays.asList( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "In in leo nec erat fringilla mattis eu non massa.", "Cras quis diam suscipit, commodo enim id, pulvinar nunc."); final CountDownLatch countDownLatch = new CountDownLatch(numSinks * outputStream.size()); final Map<String, List<String>> topicListMap = new ConcurrentHashMap<>(); final String topic = "topic"; subscriber.connect(); subscriber.setCallback(new TestMqttSubscriber(topicListMap, countDownLatch)); final List<Sink<MqttMessage>> sinks = new LinkedList<>(); for (int i = 0; i < numSinks; i++) { final Sink<MqttMessage> publisher = new MqttSink(MqttUtils.BROKER_URI, topic+i, mqttSharedResource); topicListMap.put(topic+i, new LinkedList<>()); sinks.add(publisher); subscriber.subscribe(topic+i); } outputStream.forEach((output) -> { for (final Sink<MqttMessage> sink : sinks) { sink.handle(new MqttMessage(output.getBytes())); } }); countDownLatch.await(); <START> for (List<String> received : topicListMap.values()) { <END> Assert.assertEquals(outputStream, received); } for (final Sink<MqttMessage> sink : sinks) { sink.close(); } }</code><technical_language>final</technical_language>

Target:
public void testMqttSink() throws Exception { final int numSinks = 4; final List<String> outputStream = Arrays.asList( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "In in leo nec erat fringilla mattis eu non massa.", "Cras quis diam suscipit, commodo enim id, pulvinar nunc."); final CountDownLatch countDownLatch = new CountDownLatch(numSinks * outputStream.size()); final Map<String, List<String>> topicListMap = new ConcurrentHashMap<>(); final String topic = "topic"; subscriber.connect(); subscriber.setCallback(new TestMqttSubscriber(topicListMap, countDownLatch)); final List<Sink<MqttMessage>> sinks = new LinkedList<>(); for (int i = 0; i < numSinks; i++) { final Sink<MqttMessage> publisher = new MqttSink(MqttUtils.BROKER_URI, topic+i, mqttSharedResource); topicListMap.put(topic+i, new LinkedList<>()); sinks.add(publisher); subscriber.subscribe(topic+i); } outputStream.forEach((output) -> { for (final Sink<MqttMessage> sink : sinks) { sink.handle(new MqttMessage(output.getBytes())); } }); countDownLatch.await(); for (final List<String> received : topicListMap.values()) { Assert.assertEquals(outputStream, received); } for (final Sink<MqttMessage> sink : sinks) { sink.close(); } }
Source:
<code>public void openFileOnGitHubTest() { projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/che/eclipse/sample/Aclass.java"); editor.selectLines(14, 8); editor.openContextMenuInEditor(); editor.clickOnItemInContextMenu(OPEN_ON_GITHUB); seleniumWebDriverHelper.switchToNextWindow(seleniumWebDriver.getWindowHandle()); <START> Assert.assertEquals( <END> seleniumWebDriver.getCurrentUrl(), testRepo.getHtmlUrl() + "/blob/master" + PATH_TO_EXPAND + "/Aclass.java#L14-L16"); }</code><technical_language><LINK_0></technical_language>

Target:
public void openFileOnGitHubTest() { projectExplorer.openItemByPath(PROJECT_NAME + "/" + PATH_TO_EXPAND + "/Aclass.java"); editor.selectLines(14, 1); editor.openContextMenuInEditor(); editor.clickOnItemInContextMenu(OPEN_ON_GITHUB); seleniumWebDriverHelper.switchToNextWindow(seleniumWebDriver.getWindowHandle()); seleniumWebDriverHelper.waitSuccessCondition( urlToBe(testRepo.getHtmlUrl() + "/blob/master/" + PATH_TO_EXPAND + "/Aclass.java#L15-L15")); }
Source:
<code>public RunResult runTests(Path path) { Path shadowDir = makeShadowBuildDir(path); try { ProcessResult qmakeBuild = buildWithQmake(shadowDir); if (qmakeBuild.statusCode != 0) { log.error("Building project with qmake failed: {}", qmakeBuild.errorOutput); return filledFailure(qmakeBuild.errorOutput); } <START> } catch (Exception e) { <END> log.error("Building project with qmake failed", e); throw new RuntimeException(e); } try { ProcessResult makeBuild = buildWithMake(shadowDir); if (makeBuild.statusCode != 0) { log.error("Building project with make failed: {}", makeBuild.errorOutput); return filledFailure(makeBuild.errorOutput); } } catch (Exception e) { log.error("Building project with make failed", e); throw new RuntimeException(e); } Path testResults = path.resolve(TMC_TEST_RESULTS); String target = "check"; String config = "TESTARGS=-o " + testResults.toString() + ",xml"; String[] makeCommand = {"make", target, config}; log.info("Testing project with command {}", Arrays.toString(makeCommand)); try { ProcessResult testRun = run(makeCommand, shadowDir); if (!Files.exists(testResults)) { log.error("Failed to get test output at {}", testResults); return filledFailure(testRun.output); } } catch (Exception e) { log.error("Testing with make check failed", e); throw new RuntimeException(e); } QTestResultParser parser = new QTestResultParser(); parser.loadTests(testResults); return parser.result(); }</code><technical_language>Prefer catching distinct exception types if possible. I underlying exception caught is IOException InterruptedException coming ProcessRunner.call()? This applies a places file, well</technical_language>

Target:
public RunResult runTests(Path path) { Path shadowDir = makeShadowBuildDir(path); try { ProcessResult qmakeBuild = buildWithQmake(shadowDir); if (qmakeBuild.statusCode != 0) { log.error("Building project with qmake failed: {}", qmakeBuild.errorOutput); return filledFailure(qmakeBuild.errorOutput); } } catch (IOException | InterruptedException e) { log.error("Building project with qmake failed", e); throw new QmakeBuildException(e); } try { ProcessResult makeBuild = buildWithMake(shadowDir); if (makeBuild.statusCode != 0) { log.error("Building project with make failed: {}", makeBuild.errorOutput); return filledFailure(makeBuild.errorOutput); } } catch (IOException | InterruptedException e) { log.error("Building project with make failed", e); throw new QmakeBuildException(e); } Path testResults = path.resolve(TMC_TEST_RESULTS); String target = "check"; String config = "TESTARGS=-o " + testResults.toString() + ",xml"; String[] makeCommand = {"make", target, config}; log.info("Testing project with command {}", Arrays.toString(makeCommand)); try { ProcessResult testRun = run(makeCommand, shadowDir); if (!Files.exists(testResults)) { log.error("Failed to get test output at {}", testResults); return filledFailure(testRun.output); } } catch (IOException | InterruptedException e) { log.error("Testing with make check failed", e); throw new QmakeBuildException(e); } QTestResultParser parser = new QTestResultParser(); parser.loadTests(testResults); return parser.result(); }
Source:
<code>public boolean addVertex(final V v) { if (!adjacent.containsKey(v)) { adjacent.put(v, new HashSet<>()); inDegrees.put(v, 0); rootVertices.add(v); return true; } else { <START> LOG.log(Level.WARNING, "The vertex {0} already exists", new Object[]{v}); <END> return false; } }</code><technical_language>is element, need object array</technical_language>

Target:
public boolean addVertex(final V v) { if (!adjacent.containsKey(v)) { adjacent.put(v, new HashSet<>()); inDegrees.put(v, 0); rootVertices.add(v); return true; } else { LOG.log(Level.WARNING, "The vertex {0} already exists", v); return false; } }
Source:
<code>public Response toolsIndexSearch(String query, MultivaluedMap<String, String> queryParameters, SecurityContext securityContext) { final String index = "tools"; <START> Response response = searchIndex(query, queryParameters, index); <END> return response; }</code><technical_language>Response is kinda redundant in methods (can return directly)</technical_language>

Target:
public Response toolsIndexSearch(String query, MultivaluedMap<String, String> queryParameters, SecurityContext securityContext) { if (!config.getEsConfiguration().getHostname().isEmpty()) { try (RestClient restClient = RestClient .builder(new HttpHost(config.getEsConfiguration().getHostname(), config.getEsConfiguration().getPort(), "http")) .build()) { HttpEntity entity = query == null ? null : new NStringEntity(query, ContentType.APPLICATION_JSON); Map<String, String> parameters = new HashMap<>(); if (queryParameters != null) { queryParameters.forEach((key, value) -> parameters.put(key, value.get(0))); } org.elasticsearch.client.Response get = restClient.performRequest("GET", "/" + ALL_INDICES + "/_search", parameters, entity); if (get.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new CustomWebApplicationException("Could not search " + ALL_INDICES + "index", HttpStatus.SC_INTERNAL_SERVER_ERROR); } return Response.ok().entity(get.getEntity().getContent()).build(); } catch (ResponseException e) { int[] codesToResurface = {HttpStatus.SC_BAD_REQUEST}; int statusCode = e.getResponse().getStatusLine().getStatusCode(); LOG.error("Could not use Elasticsearch search", e); if (ArrayUtils.contains(codesToResurface, statusCode)) { throw new CustomWebApplicationException(e.getMessage(), statusCode); } else { throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e2) { LOG.error("Could not use Elasticsearch search", e2); throw new CustomWebApplicationException(e2.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } return Response.ok().entity(0).build(); }
Source:
<code>public Builder initialData(Realm.Transaction transaction) { <START> if (readOnly) { <END> throw new IllegalStateException("initialData(Transaction) cannot be combined with read-only Realms."); } initialDataTransaction = transaction; return this; }</code><technical_language>SyncConfiguration this check in initialData() (RealmConfiguration it)</technical_language>

Target:
public Builder initialData(Realm.Transaction transaction) { initialDataTransaction = transaction; return this; }
Source:
<code>@Override public ByteBuffer marshal(Object obj, int off) throws IOException { <START> try(GridByteArrayOutputStream bOut = new GridByteArrayOutputStream(); <END> ObjectOutput out = new ObjectOutputStream(bOut)) { out.writeObject(obj); out.flush(); ByteBuffer buf = ByteBuffer.allocate(off + bOut.size()); buf.position(off); buf.put(bOut.internalArray(), 0, bOut.size()); buf.flip(); return buf; } }</code><technical_language>Need space try keyword</technical_language>

Target:
@Override public ByteBuffer marshal(Object obj, int off) throws IOException { GridByteArrayOutputStream bOut = new GridByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bOut); out.writeObject(obj); out.flush(); ByteBuffer buf = ByteBuffer.allocate(off + bOut.size()); buf.position(off); buf.put(bOut.internalArray(), 0, bOut.size()); buf.flip(); return buf; }
Source:
<code>void run(Handler<AsyncResult<Void>> completionHandler) { if (closeHooksRun) { throw new IllegalStateException("Close hooks already run"); } closeHooksRun = true; <START> if (closeHooks != null && !closeHooks.isEmpty()) { <END> Set<Closeable> copy = new HashSet<>(closeHooks); int num = copy.size(); if (num != 0) { AtomicInteger count = new AtomicInteger(); AtomicBoolean failed = new AtomicBoolean(); for (Closeable hook : copy) { Future<Void> a = Future.future(); a.setHandler(ar -> { if (ar.failed()) { if (failed.compareAndSet(false, true)) { completionHandler.handle(Future.failedFuture(ar.cause())); } } else { if (count.incrementAndGet() == num) { completionHandler.handle(Future.succeededFuture()); } } }); try { hook.close(a.completer()); } catch (Throwable t) { log.warn("Failed to run close hooks", t); if (!a.isComplete()) { a.fail(t); } } } } else { completionHandler.handle(Future.succeededFuture()); } } else { completionHandler.handle(Future.succeededFuture()); } }</code><technical_language>synchronization issue if add time</technical_language>

Target:
void run(Handler<AsyncResult<Void>> completionHandler) { Set<Closeable> copy = null; synchronized (this) { if (closeHooksRun) { throw new IllegalStateException("Close hooks already run"); } closeHooksRun = true; if (closeHooks != null && !closeHooks.isEmpty()) { copy = new HashSet<>(closeHooks); } } if (copy != null && !copy.isEmpty()) { int num = copy.size(); if (num != 0) { AtomicInteger count = new AtomicInteger(); AtomicBoolean failed = new AtomicBoolean(); for (Closeable hook : copy) { Future<Void> a = Future.future(); a.setHandler(ar -> { if (ar.failed()) { if (failed.compareAndSet(false, true)) { completionHandler.handle(Future.failedFuture(ar.cause())); } } else { if (count.incrementAndGet() == num) { completionHandler.handle(Future.succeededFuture()); } } }); try { hook.close(a.completer()); } catch (Throwable t) { log.warn("Failed to run close hooks", t); if (!a.isComplete()) { a.fail(t); } } } } else { completionHandler.handle(Future.succeededFuture()); } } else { completionHandler.handle(Future.succeededFuture()); } }
Source:
<code>private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) { checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet() .stream() .filter( partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId) .equals(this.ownerId)) .map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId)) <START> .collect(Collectors.toList())) <END> .subscribe(ignored -> { }, ex -> { logger.error("Error renewing partition ownership", ex); isLoadBalancerRunning.set(false); }, () -> isLoadBalancerRunning.set(false)); }</code><technical_language>Do need collect this a list if output</technical_language>

Target:
private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) { checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet() .stream() .filter( partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId) .getOwnerId().equals(this.ownerId)) .map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId)) .collect(Collectors.toList())) .subscribe(ignored -> { }, ex -> { logger.error("Error renewing partition ownership", ex); isLoadBalancerRunning.set(false); }, () -> isLoadBalancerRunning.set(false)); }