auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Collection getCollection(BaseResource model, Class<? extends BaseResource> suggestedParentType) { ParentToCollectionMap collections = TYPES.get(model.getClass()); if (collections == null) { log.error("Map 'describing every possible collection' does not contain rather possible key for resource " + <START> "%1$s, returning 'null' instead.", model.getClass()); <END> return null; } if (suggestedParentType != null) { for (Entry<Class<? extends BaseResource>, Collection> entry : collections.entrySet()) { if (entry.getKey().equals(suggestedParentType)) { return entry.getValue(); } } } for (Entry<Class<? extends BaseResource>, Collection> parentTypeEntry : collections.entrySet()) { if (parentTypeEntry.getKey() != NO_PARENT && getParentModel(model, parentTypeEntry.getKey()) != null) { return parentTypeEntry.getValue(); } } return collections.get(NO_PARENT); }</code><technical_language>{} instaed of %1$s</technical_language>

Target:
private static Collection getCollection(BaseResource model, Class<? extends BaseResource> suggestedParentType) { ParentToCollectionMap collections = TYPES.get(model.getClass()); if (collections == null) { return null; } if (suggestedParentType != null) { for (Entry<Class<? extends BaseResource>, Collection> entry : collections.entrySet()) { if (entry.getKey().equals(suggestedParentType)) { return entry.getValue(); } } } for (Entry<Class<? extends BaseResource>, Collection> parentTypeEntry : collections.entrySet()) { if (parentTypeEntry.getKey() != NO_PARENT && getParentModel(model, parentTypeEntry.getKey()) != null) { return parentTypeEntry.getValue(); } } return collections.get(NO_PARENT); }
Source:
<code>public void notifyParentItemRangeInserted(int parentPositionStart, int itemCount) { int initialWrapperIndex; if (parentPositionStart < mParentItemList.size() - 1) { initialWrapperIndex = getParentWrapperIndex(parentPositionStart); } else { initialWrapperIndex = mItemList.size(); } int sizeChanged = 0; int wrapperIndex = initialWrapperIndex; int changed; <START> for (int i = parentPositionStart; i < parentPositionStart + itemCount; i++) { <END> ParentListItem parentListItem = mParentItemList.get(i); changed = addParentWrapper(wrapperIndex, parentListItem); wrapperIndex += changed; sizeChanged += changed; } notifyItemRangeInserted(initialWrapperIndex, sizeChanged); }</code><technical_language>wonky me. this read follows? java for (int i = 0; i < itemCount; i++) { ParentListItem parentListItem = mParentItemList.get(i + parentPositionStart); ..</technical_language>

Target:
public void notifyParentItemRangeInserted(int parentPositionStart, int itemCount) { int initialWrapperIndex; if (parentPositionStart < mParentItemList.size() - 1) { initialWrapperIndex = getParentWrapperIndex(parentPositionStart); } else { initialWrapperIndex = mItemList.size(); } int sizeChanged = 0; int wrapperIndex = initialWrapperIndex; int changed; int parentPositionEnd = parentPositionStart + itemCount; for (int i = parentPositionStart; i < parentPositionEnd; i++) { ParentListItem parentListItem = mParentItemList.get(i); changed = addParentWrapper(wrapperIndex, parentListItem); wrapperIndex += changed; sizeChanged += changed; } notifyItemRangeInserted(initialWrapperIndex, sizeChanged); }
Source:
<code>public String createProfile(String profileFolder, String profileName, String version, InputStream zipFile) throws IOException, ConfigurationException, MalformedObjectNameException { String profileId = getProfileName(profileFolder, profileName); String versionId = getOrCreateVersion(version); createProfile(versionId, profileId); ZipInputStream zis = new ZipInputStream(zipFile); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String name = ze.getName(); if (name.contains(FABRIC_MAIN_PROFILE_FILE)) { int count; byte data[] = new byte[2048]; File f = File.createTempFile("temp.fabric", "properties"); FileOutputStream fos = new FileOutputStream(f); while ((count = zis.read(data, 0, 2048)) != -1) { fos.write(data, 0, count); } fos.flush(); fos.close(); PropertiesConfiguration propertiesFile = new PropertiesConfiguration(f); parseProperties(profileId, versionId, propertiesFile); f.delete(); } else { if (!ze.isDirectory()) { int count; byte data[] = new byte[2048]; File f = File.createTempFile("temp.fabric", "properties"); FileOutputStream fos = new FileOutputStream(f); while ((count = zis.read(data, 0, 2048)) != -1) { fos.write(data, 0, count); } fos.flush(); fos.close(); <START> uploadProfilePropertiesFile(versionId, profileId, ze.getName(), new FileInputStream(f)); <END> f.delete(); } } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); refreshProfile(versionId, profileId); return profileId; }</code><technical_language>This input stream is closed</technical_language>

Target:
public String createProfile(String profileFolder, String profileName, String version, InputStream zipFile) throws IOException, ConfigurationException, MalformedObjectNameException { String profileId = getProfileName(profileFolder, profileName); String versionId = getOrCreateVersion(version); createProfile(versionId, profileId); ZipInputStream zis = new ZipInputStream(zipFile); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String name = ze.getName(); if (name.contains(FABRIC_MAIN_PROFILE_FILE)) { int count; byte data[] = new byte[2048]; File f = File.createTempFile("temp.fabric", "properties"); FileOutputStream fos = new FileOutputStream(f); while ((count = zis.read(data, 0, 2048)) != -1) { fos.write(data, 0, count); } fos.flush(); fos.close(); PropertiesConfiguration propertiesFile = new PropertiesConfiguration(f); parseProperties(profileId, versionId, propertiesFile); f.delete(); } else { if (!ze.isDirectory()) { int count; byte data[] = new byte[2048]; File f = File.createTempFile("temp.fabric", "properties"); FileOutputStream fos = null; try { fos = new FileOutputStream(f); while ((count = zis.read(data, 0, 2048)) != -1) { fos.write(data, 0, count); } fos.flush(); } finally { if (fos != null) { fos.close(); } } InputStream is = null; try { is = new FileInputStream(f); uploadProfilePropertiesFile(versionId, profileId, ze.getName(), is); } finally { if (is != null) { is.close(); } } f.delete(); } } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); refreshProfile(versionId, profileId); return profileId; }
Source:
<code>public boolean bind(final ClientEndpoint endpoint) { <START> if (isMCClient(endpoint) && !clientSelector.select(endpoint)) { <END> return false; } if (!endpointManager.registerEndpoint(endpoint)) { return true; } Connection conn = endpoint.getConnection(); if (conn instanceof TcpIpConnection) { InetSocketAddress socketAddress = conn.getRemoteSocketAddress(); if (socketAddress != null) { Address address = new Address(socketAddress); ((TcpIpConnection) conn).setEndPoint(address); } } if (!isMCClient(endpoint) && !clientSelector.select(endpoint)) { endpointManager.removeEndpoint(endpoint); return false; } return true; }</code><technical_language>I meant do if (!isMCClient(endpoint) && !clientSelector.select(endpoint))</technical_language>

Target:
public boolean bind(final ClientEndpoint endpoint) { if (!isClientAllowed(endpoint)) { return false; } if (!endpointManager.registerEndpoint(endpoint)) { return true; } Connection conn = endpoint.getConnection(); if (conn instanceof TcpIpConnection) { InetSocketAddress socketAddress = conn.getRemoteSocketAddress(); if (socketAddress != null) { Address address = new Address(socketAddress); ((TcpIpConnection) conn).setEndPoint(address); } } if (!isClientAllowed(endpoint)) { endpointManager.removeEndpoint(endpoint); return false; } return true; }
Source:
<code>public static Iterable<Object[]> data() { List<Object[]> parameters = new ArrayList<>(); Set<Class<? extends FormulaBrick>> formulaClasses = getAllSubClassesOf(FormulaBrick.class); <START> formulaClasses = removeAbstractClasses(formulaClasses); <END> formulaClasses = removeInnerClasses(formulaClasses); for (Class<?> formulaClazz : formulaClasses) { parameters.add(new Object[] {formulaClazz.getName(), formulaClazz}); } return parameters; }</code><technical_language>please exclude script bricks formula bricks this tested in a seperate test class</technical_language>

Target:
public static Iterable<Object[]> data() { List<Object[]> parameters = new ArrayList<>(); Set<Class<? extends FormulaBrick>> formulaClasses = getAllSubClassesOf(FormulaBrick.class); formulaClasses = removeAbstractClasses(formulaClasses); formulaClasses = removeInnerClasses(formulaClasses); for (Class<?> formulaClazz : formulaClasses) { if (!ScriptBrick.class.isAssignableFrom(formulaClazz)) { parameters.add(new Object[] {formulaClazz.getName(), formulaClazz}); } } return parameters; }
Source:
<code>public SimpleObject[] getMothers(@RequestParam("patientId") Patient patient,UiUtils ui) { List<Person> people = new ArrayList<Person>(); <START> if (patient == null) <END> return new SimpleObject[] {}; else { for (Relationship relationship : Context.getPersonService().getRelationshipsByPerson(patient)) { if (relationship != null) { if (relationship.getRelationshipType().getbIsToA().equals("Parent")) { if (relationship.getPersonB().getGender().equals("F")) people.add(relationship.getPersonB()); } if (relationship.getRelationshipType().getaIsToB().equals("Parent")) { if (relationship.getPersonA().getGender().equals("F")) { people.add(relationship.getPersonA()); } } } } } return ui.simplifyCollection(people); }</code><technical_language>This is redundant - patient null</technical_language>

Target:
public SimpleObject[] getMothers(@RequestParam("patientId") Patient patient,UiUtils ui) { List<Person> people = new ArrayList<Person>(); for (Relationship relationship : Context.getPersonService().getRelationshipsByPerson(patient)) { if (relationship.getRelationshipType().getbIsToA().equals("Parent")) { if (relationship.getPersonB().getGender().equals("F")) { people.add(relationship.getPersonB()); } } if (relationship.getRelationshipType().getaIsToB().equals("Parent")) { if (relationship.getPersonA().getGender().equals("F")) { people.add(relationship.getPersonA()); } } } return ui.simplifyCollection(people); }
Source:
<code>public void testGetChildWithParents() throws Exception { Response response = resource.getOntologyById(child.getId()); assertTrue(response.getStatus() == 200); List<TermResource> terms = (List<TermResource>) response.getEntity(); assertTrue(terms.size() == 1); TermResource term = terms.get(0); assertTrue(child.getId().equals(term.getId())); assertTrue(child.getLabel().equals(term.getLabel())); assertTrue(child.getDefinition().equals(term.getDefinition())); assertTrue(child.getSynonyms().equals(term.getSynonyms())); for (TermParent p : term.getParents()) { boolean parentChecked = false; if (p.getId().equals(parent1.getId())) { assertTrue(p.getLabel().equals(parent1.getLabel())); assertTrue(p.getDefinition().equals(parent1.getDefinition())); assertTrue(p.getSynonyms().equals(parent1.getSynonyms())); parentChecked = true; } else if (p.getId().equals(parent2.getId())) { assertTrue(p.getLabel().equals(parent2.getLabel())); assertTrue(p.getDefinition().equals(parent2.getDefinition())); assertTrue(p.getSynonyms().equals(parent2.getSynonyms())); parentChecked = true; } assertTrue(parentChecked); <START> } <END> }</code><technical_language>alternately, call term.getParents().sort(), passing in a Comparator compares based TermParent.getOrder(), check TermParent is parent1, TermParent is parent2</technical_language>

Target:
public void testGetChildWithParents() throws Exception { Response response = resource.getOntologyById(child.getId()); assertTrue(response.getStatus() == 200); List<TermResource> terms = (List<TermResource>) response.getEntity(); assertTrue(terms.size() == 1); TermResource term = terms.get(0); assertTrue(child.getId().equals(term.getId())); assertTrue(child.getLabel().equals(term.getLabel())); assertTrue(child.getDefinition().equals(term.getDefinition())); assertTrue(child.getSynonyms().equals(term.getSynonyms())); assertEquals("Expected two parents", 2, term.getParents().size()); term.getParents().sort(Comparator.comparingInt(TermParent::getOrder)); TermParent actualParent1 = term.getParents().get(0); TermParent actualParent2 = term.getParents().get(1); assertTrue(actualParent1.getLabel().equals(parent1.getLabel())); assertTrue(actualParent1.getDefinition().equals(parent1.getDefinition())); assertTrue(actualParent1.getSynonyms().equals(parent1.getSynonyms())); assertTrue(actualParent2.getLabel().equals(parent2.getLabel())); assertTrue(actualParent2.getDefinition().equals(parent2.getDefinition())); assertTrue(actualParent2.getSynonyms().equals(parent2.getSynonyms())); }
Source:
<code>public String next() { char c = input.read(); if (input.isAtEnd()) { return getTokenEOF(); } if (!keepBeginningWhiteSpace) { while (isWhitespace(c)) { c = input.read(); if (input.isAtEnd()) { return getTokenEOF(); } } } if (c == separator) { return getTokenSeparator(); } if (c == textMarker) { return onTextMarkerChar(); } if (c == '\r' || c == '\n') { return onLineEndingChar(c); } int length = 1; builder.append(c); while (true) { c = input.read(); if (input.isAtEnd()) { break; } if (c == separator || c == '\r' || c == '\n') { input.rewind(1); break; } builder.append(c); length++; } while (length > 0 && isWhitespace(builder.charAt(length-1))) { <START> length--; <END> } return getTokenValue(length); }</code><technical_language>builder.deleteCharAt(length-1). In general, length variable is required StringBuilder (It's equal builder.length())</technical_language>

Target:
public String next() { char c = input.read(); if (input.isAtEnd()) { return getTokenEOF(); } if (!keepBeginningWhiteSpace) { while (isWhitespace(c)) { c = input.read(); if (input.isAtEnd()) { return getTokenEOF(); } } } if (c == separator) { return getTokenSeparator(); } if (c == textMarker) { return onTextMarkerChar(); } if (c == '\r' || c == '\n') { return onLineEndingChar(c); } builder.append(c); while (true) { c = input.read(); if (input.isAtEnd()) { break; } if (c == separator || c == '\r' || c == '\n') { input.rewind(1); break; } builder.append(c); } int length = builder.length() - 1; while (length > 0 && isWhitespace(builder.charAt(length))) { builder.deleteCharAt(length); length--; } return getTokenValue(length); }
Source:
<code>public void init(ServletConfig config) throws ServletException { super.init(config); this.servletName = config.getServletName(); <START> this.async = Optional.ofNullable(config.getInitParameter(ASYNC_PARAM)) <END> .map(ObjectHelper::toBoolean) .orElse(Boolean.FALSE); log.trace("servlet '{}' initialized with: async={}", new Object[]{servletName, async}); }</code><technical_language>Please avoid/abuse optional for a simple check this</technical_language>

Target:
public void init(ServletConfig config) throws ServletException { super.init(config); this.servletName = config.getServletName(); final String asyncParam = config.getInitParameter(ASYNC_PARAM); this.async = asyncParam == null ? false : ObjectHelper.toBoolean(asyncParam); log.trace("servlet '{}' initialized with: async={}", new Object[]{servletName, async}); }
Source:
<code>private void hideMatchingResources(RepositoryResourceImpl newResource) throws RepositoryBackendException, RepositoryResourceException { String vanityURL = newResource.getVanityURL(); RepositoryConnection repo = newResource.getRepositoryConnection(); Collection<RepositoryResource> matchingResources = repo.getMatchingResources(FilterPredicate.areEqual(FilterableAttribute.VANITY_URL, vanityURL)); boolean found = false; for (RepositoryResource resource : matchingResources) { if (!isVisible(resource)) { continue; } if (!State.PUBLISHED.equals(((RepositoryResourceWritable) resource).getState())) { continue; } if (newResource.getId().equals(resource.getId())) { continue; } if (found) { throw new RepositoryResourceUpdateException("There is more than 1 resource with the vanity URL " + newResource.getVanityURL() + " in state visible, " + newResource.getName() + "(" + newResource.getId() + ") and " + resource.getName() + "(" + resource.getId() + ")", newResource.getId()); } found = true; <START> ((WebDisplayable) resource).setWebDisplayPolicy(DisplayPolicy.HIDDEN); <END> ((RepositoryResourceWritable) resource).uploadToMassive(new AddThenDeleteStrategy(null, State.DRAFT, true)); } }</code><technical_language>this point, I checked resource is instance of WebDisplayable Note isVisible returns true for non-WebDisplayable resources</technical_language>

Target:
private void hideMatchingResources(RepositoryResourceImpl newResource) throws RepositoryBackendException, RepositoryResourceException { String vanityURL = newResource.getVanityURL(); RepositoryConnection repo = newResource.getRepositoryConnection(); Collection<RepositoryResource> matchingResources = repo.getMatchingResources(FilterPredicate.areEqual(FilterableAttribute.VANITY_URL, vanityURL)); List<String> hiddenAssets = new ArrayList<String>(); for (RepositoryResource resource : matchingResources) { if (!isVisibleAndWebDisplayable(resource)) { continue; } if (!State.PUBLISHED.equals(((RepositoryResourceWritable) resource).getState())) { continue; } if (newResource.getId().equals(resource.getId())) { continue; } ((WebDisplayable) resource).setWebDisplayPolicy(DisplayPolicy.HIDDEN); ((RepositoryResourceWritable) resource).uploadToMassive(new AddThenDeleteStrategy(null, State.DRAFT, true)); hiddenAssets.add(resource.getId()); } if (hiddenAssets.size() > 1) { StringBuilder ids = new StringBuilder(); for (String id : hiddenAssets) { ids.append(id + ", "); } throw new RepositoryResourceUpdateException("There was more than 1 resource with the vanity URL " + newResource.getVanityURL() + " in state visible. New resource is " + newResource.getName() + "(" + newResource.getId() + ") and old asset ids were " + ids.toString(), newResource.getVanityURL()); } }
Source:
<code>private boolean isRequestFiltered(@Nullable Integer orderBy) { return orderBy != null && (orderBy == Constants.ORDER_BY_DISTANCE || orderBy == Constants.ORDER_BY_DATE || orderBy == Constants.ORDER_BY_STATUS || orderBy == Constants.ORDER_BY_NAME); <START> return false; <END> }</code><technical_language>I guess this is reached, right</technical_language>

Target:
private boolean isRequestFiltered(@Nullable Integer orderBy) { return orderBy != null && (orderBy == Constants.ORDER_BY_DISTANCE || orderBy == Constants.ORDER_BY_DATE || orderBy == Constants.ORDER_BY_STATUS || orderBy == Constants.ORDER_BY_NAME); }
Source:
<code>public List<Kill> getKills() { <START> List<Kill> flattenedKills = new ArrayList<Kill>(); <END> for(ArrayList<Kill> personKills : kills.values()) { flattenedKills.addAll(personKills); } return Collections.unmodifiableList(flattenedKills); }</code><technical_language>suggestion List<Kill> flattenedKills = new ArrayList<>();</technical_language>

Target:
public List<Kill> getKills() { List<Kill> flattenedKills = new ArrayList<>(); for(List<Kill> personKills : kills.values()) { flattenedKills.addAll(personKills); } return Collections.unmodifiableList(flattenedKills); }
Source:
<code>void updateActionLabels() { ImageDescriptor descriptor = ImageDescriptor.getMissingImageDescriptor(); final Image descImage = labelProvider.getImage(description); if (descImage != null) { descriptor = ImageDescriptor.createFromImage(descImage); } this.setImageDescriptor(descriptor); computeRepresentationName(); this.setText(name); this.setToolTipText(description.getEndUserDocumentation()); if (session instanceof DAnalysisSession) { DRepresentationContainer <START> representationContainer = <END> DAnalysisSessionHelper.findContainerForRepresentationDescription((DAnalysisSession) session, description); if (representationContainer != null) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(representationContainer); if (permissionAuthority != null && !permissionAuthority.canCreateIn(representationContainer)) { this.setEnabled(false); } } } }</code><technical_language>this DRepContainer end</technical_language>

Target:
void updateActionLabels() { ImageDescriptor descriptor = ImageDescriptor.getMissingImageDescriptor(); final Image descImage = labelProvider.getImage(description); if (descImage != null) { descriptor = ImageDescriptor.createFromImage(descImage); } this.setImageDescriptor(descriptor); computeRepresentationName(); this.setText(name); this.setToolTipText(description.getEndUserDocumentation()); if (session instanceof DAnalysisSession) { Collection<DRepresentationContainer> containers = DAnalysisSessionHelper.findContainerCandidatesForRepresentationDescription((DAnalysisSession) session, description); if (!containers.isEmpty()) { boolean enabled = false; for (DRepresentationContainer container : containers) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(container); if (permissionAuthority == null || permissionAuthority.canCreateIn(container)) { enabled = true; break; } } this.setEnabled(enabled); } } }
Source:
<code>public File file() throws IOException { final File license = File.createTempFile("LICENSE", ".txt"); FileUtils.forceDeleteOnExit(license); FileUtils.writeStringToFile( license, <START> StringUtils.join(this.lines, this.eol), <END> Charset.defaultCharset() ); if (this.directory != null) { this.makePackageInfo(this.directory); } return license; }</code><technical_language>@korthout Avoid static methods, EO principles; cactoos JoinedText instead</technical_language>

Target:
public File file() throws IOException { final File license = File.createTempFile("LICENSE", ".txt"); FileUtils.forceDeleteOnExit(license); FileUtils.writeStringToFile( license, new JoinedText(this.eol, this.lines).asString(), StandardCharsets.UTF_8 ); if (this.directory != null) { this.makePackageInfo(this.directory); } return license; }
Source:
<code>public void setLaunchAndWait(ILaunch launch) { this.launch = launch; this.myProcess = launch.getProcesses()[0]; synchronized (waiting) { if( checkAllCachedEvents()) { return; } try { <START> waiting.wait(); <END> } catch (InterruptedException ie) { } } }</code><technical_language>![CRITICAL](<LINK_1> 'Severity: CRITICAL') Remove this call "wait" move a "while" loop. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public void setLaunchAndWait(ILaunch launch) { this.launch = launch; this.myProcess = this.launch.getProcesses()[0]; synchronized (waiting) { while( !checkAllCachedEvents()) { try { waiting.wait(); } catch (InterruptedException ie) { } } } }
Source:
<code>protected ContainerPlacementMessage(UUID uuid, String deploymentId, String processorId, String destinationHost, Duration requestExpiry, StatusCode statusCode, long timestamp) { Preconditions.checkNotNull(uuid, "uuid cannot be null"); Preconditions.checkNotNull(deploymentId, "deploymentId cannot be null"); Preconditions.checkNotNull(processorId, "processorId cannot be null"); Preconditions.checkNotNull(destinationHost, "destinationHost cannot be null"); Preconditions.checkNotNull(statusCode, "statusCode cannot be null"); Preconditions.checkNotNull(timestamp, "Timestamp of the message cannot be null"); <START> this.uuid = uuid; <END> this.deploymentId = deploymentId; this.processorId = processorId; this.destinationHost = destinationHost; this.requestExpiry = requestExpiry; this.statusCode = statusCode; this.timestamp = timestamp; }</code><technical_language>do null check assignment in line: this.uuid = Preconditions.checkNotNull(uuid, "uuid null"); for others</technical_language>

Target:
protected ContainerPlacementMessage(UUID uuid, String deploymentId, String processorId, String destinationHost, Duration requestExpiry, StatusCode statusCode, long timestamp) { this.uuid = Preconditions.checkNotNull(uuid, "uuid cannot be null"); this.deploymentId = Preconditions.checkNotNull(deploymentId, "deploymentId cannot be null"); this.processorId = Preconditions.checkNotNull(processorId, "processorId cannot be null"); this.destinationHost = Preconditions.checkNotNull(destinationHost, "destinationHost cannot be null"); this.statusCode = Preconditions.checkNotNull(statusCode, "statusCode cannot be null"); this.timestamp = Preconditions.checkNotNull(timestamp, "Timestamp of the message cannot be null"); this.requestExpiry = requestExpiry; }
Source:
<code>public DataSet updateDataset(DataSetDTO dataset, Integer datasetId, Integer userId) { Timestamp now = new Timestamp(new Date().getTime()); DataSet old = getDatasetWithPropertiesById(datasetId); Set<DataSetProperty> oldProperties = old.getProperties(); List<DataSetPropertyDTO> dtos = dataset.getProperties(); List<DataSetProperty> jsonProperties = processDatasetProperties(datasetId, dtos); ; List<DataSetProperty> propertiesToAdd = jsonProperties.stream() .filter(p -> oldProperties.stream() .noneMatch(op -> op.getPropertyKey() == p.getPropertyKey())) .collect(Collectors.toList()); List<DataSetProperty> propertiesToUpdate = jsonProperties.stream() .filter(p -> oldProperties.stream() .noneMatch(op -> equalsProperty(op.getPropertyKey(), op.getPropertyValue(), p.getPropertyKey(), p.getPropertyValue()))) .collect(Collectors.toList()); if (propertiesToAdd.isEmpty() && propertiesToUpdate.isEmpty()) { <START> return null; <END> } propertiesToUpdate.stream().forEach(p -> dataSetDAO.updateDatasetProperty(datasetId, p.getPropertyKey(), p.getPropertyValue())); dataSetDAO.insertDataSetsProperties(propertiesToAdd); dataSetDAO.updateDataset(datasetId, now, userId); DataSet updatedDataset = getDatasetWithPropertiesById(datasetId); return updatedDataset; }</code><technical_language>A clearer handle this is return Optional<Dataset> instead of a Dataset. way, callers dataset is guaranteed do null checking. If return Optional.empty here, caller happened</technical_language>

Target:
public Optional<DataSet> updateDataset(DataSetDTO dataset, Integer datasetId, Integer userId) { Timestamp now = new Timestamp(new Date().getTime()); DataSet old = getDatasetWithPropertiesById(datasetId); Set<DataSetProperty> oldProperties = old.getProperties(); List<DataSetPropertyDTO> updateDatasetPropertyDTOs = dataset.getProperties(); List<DataSetProperty> updateDatasetProperties = processDatasetProperties(datasetId, updateDatasetPropertyDTOs); List<DataSetProperty> propertiesToAdd = updateDatasetProperties.stream() .filter(p -> oldProperties.stream() .noneMatch(op -> op.getPropertyKey() == p.getPropertyKey())) .collect(Collectors.toList()); List<DataSetProperty> propertiesToUpdate = updateDatasetProperties.stream() .filter(p -> oldProperties.stream() .noneMatch(op -> p.equals(op))) .collect(Collectors.toList()); List<DataSetProperty> propertiesToDelete = oldProperties.stream() .filter(op -> updateDatasetProperties.stream() .noneMatch(p -> p.getPropertyKey() == op.getPropertyKey()) ).collect(Collectors.toList()); if (propertiesToAdd.isEmpty() && propertiesToUpdate.isEmpty() && propertiesToDelete.isEmpty()) { return Optional.empty(); } updateDatasetProperties(propertiesToUpdate, propertiesToDelete, propertiesToAdd); dataSetDAO.updateDatasetUpdateUserAndDate(datasetId, now, userId); DataSet updatedDataset = getDatasetWithPropertiesById(datasetId); return Optional.of(updatedDataset); }
Source:
<code>public void init() { publisher.subscribe(to(BlockAdded.class, data -> { <START> data.getBlockSummary().getBlock().getTransactionsList().forEach(gasPriceTracker::onTransaction); <END> })); }</code><technical_language>this logic in gasPriceTracker instead</technical_language>

Target:
public void init() { worldManager.subscribe(to(BLOCK_ADDED, data -> gasPriceTracker.onBlock(data.getBlockSummary()))); }
Source:
<code>protected void initialize() { <START> setInstallLocation(new File("./").getAbsolutePath()); <END> loadConfig(); if (getPort().isPresent()) { getUrlDetector().setPort(getPort()); } else { LOG.info("No valid port in storm.yaml, using the on configured in the Url Detector " + getUrlDetector().getPort()); setPort(getUrlDetector().getPort()); } }</code><technical_language>new File("./").getAbsolutePath() a weird get current working dir. do this in a more idiomatic way</technical_language>

Target:
protected void initialize() { setInstallLocation(new File(".").getAbsolutePath()); loadConfig(); if (getPort().isPresent()) { getUrlDetector().setPort(getPort()); } else { LOG.info("No valid port in storm.yaml, using the on configured in the Url Detector " + getUrlDetector().getPort()); setPort(getUrlDetector().getPort()); } }
Source:
<code>private CacheLoader<Cell, byte[]> getCacheLoader(TableReference tableRef) { return new CacheLoader<Cell, byte[]>() { @Override public byte[] load(Cell key) throws Exception { byte[] res = CachingTransaction.super.get(tableRef, ImmutableSet.of(key)).get(key); if (res == null) { return PtBytes.EMPTY_BYTE_ARRAY; } else { return res; } } @Override public Map<Cell, byte[]> loadAll(Iterable<? extends Cell> keys) throws Exception { Map<Cell, byte[]> internalResult = CachingTransaction.super.get(tableRef, ImmutableSet.copyOf(keys)); Map<Cell, byte[]> res = Maps.newConcurrentMap(); for (Cell key : keys) { byte[] value = internalResult.get(key); if (value == null) { res.put(key, PtBytes.EMPTY_BYTE_ARRAY); } else { res.put(key, value); <START> } <END> } return res; } }; }</code><technical_language>want extract duplicate logic wrapValue</technical_language>

Target:
private CacheLoader<Cell, byte[]> getCacheLoader(TableReference tableRef) { return new CacheLoader<Cell, byte[]>() { @Override public byte[] load(Cell key) throws Exception { return setMissingKeysToEmpty(CachingTransaction.super.get(tableRef, ImmutableSet.of(key)), ImmutableSet.of(key)) .get(key); } @Override public Map<Cell, byte[]> loadAll(Iterable<? extends Cell> keys) throws Exception { Set<Cell> keySet = ImmutableSet.copyOf(keys); return setMissingKeysToEmpty(CachingTransaction.super.get(tableRef, ImmutableSet.copyOf(keys)), keySet); } }; }
Source:
<code>void deleteAll() { <START> assertThrows(IllegalStateException.class, <END> () -> storage().deleteAll(ImmutableList.of(newId(), newId())) ); }</code><technical_language>Please extract asserting of throwing ISE a method</technical_language>

Target:
void deleteAll() { assertISE(() -> storage().deleteAll(ImmutableList.of(newId(), newId()))); }
Source:
<code>public void checkReferenceSetFoundByAccession() throws AvroRemoteException { final SearchReferenceSetsRequest req = SearchReferenceSetsRequest.newBuilder() .setAccessions(TestData.REFERENCESET_ACCESSIONS) .build(); final SearchReferenceSetsResponse resp = client.references.searchReferenceSets(req); <START> <END> final List<ReferenceSet> refSets = resp.getReferenceSets(); assertThat(refSets).hasSize(1); final ReferenceSet refSet = refSets.get(0); assertThat(refSet.getAssemblyId()).isEqualTo(TestData.REFERENCESET_ASSEMBLY_ID); assertThat(refSet.getMd5checksum()).isEqualTo(TestData.REFERENCESET_MD5_CHECKSUM); assertThat(refSet.getSourceAccessions()).isEqualTo(TestData.REFERENCESET_ACCESSIONS); }</code><technical_language>3 methods identical. checking resp bit factored out</technical_language>

Target:
public void checkReferenceSetFoundByAccession() throws AvroRemoteException { final SearchReferenceSetsRequest req = SearchReferenceSetsRequest.newBuilder() .setAccessions(TestData.REFERENCESET_ACCESSIONS) .build(); final SearchReferenceSetsResponse resp = client.references.searchReferenceSets(req); final List<ReferenceSet> refSets = resp.getReferenceSets(); assertThat(refSets).hasSize(1); final ReferenceSet refSet = refSets.get(0); checkRefSetConstants(refSet); }
Source:
<code>void syncButtonPressed() { if (!ConnectivityStatus.isNetworkAvailable(StandardHomeActivity.this)) { if (ConnectivityStatus.isAirplaneModeOn(StandardHomeActivity.this)) { handleSyncNotAttempted(Localization.get("notification.sync.airplane.action")); CommCareApplication.notificationManager().reportNotificationMessage( NotificationMessageFactory.message( NotificationMessageFactory.StockMessages.Sync_AirplaneMode, AIRPLANE_MODE_CATEGORY)); } else { handleSyncNotAttempted(Localization.get("notification.sync.connections.action")); CommCareApplication.notificationManager().reportNotificationMessage( NotificationMessageFactory.message( NotificationMessageFactory.StockMessages.Sync_NoConnections, AIRPLANE_MODE_CATEGORY)); } FirebaseAnalyticsUtil.reportSyncFailure( AnalyticsParamValue.SYNC_TRIGGER_USER, AnalyticsParamValue.SYNC_MODE_SEND_FORMS, AnalyticsParamValue.SYNC_FAIL_NO_CONNECTION); return; <START> } else { <END> ConnectionDiagnosticTask<StandardHomeActivity> task = new ConnectionDiagnosticTask(getApplicationContext()); task.setListener(new ConnectionDiagnosticTask.ConnectionDiagnosticListener<StandardHomeActivity>() { @Override public void connected(StandardHomeActivity receiver) { CommCareApplication.notificationManager().clearNotifications(AIRPLANE_MODE_CATEGORY); receiver.sendFormsOrSync(true); } @Override public void failed(StandardHomeActivity receiver, String errorMessageId, MessageTag notificationTag, String analyticsMessage) { receiver.handleSyncNotAttempted(Localization.get(errorMessageId)); CommCareApplication.notificationManager().reportNotificationMessage( NotificationMessageFactory.message( notificationTag, AIRPLANE_MODE_CATEGORY)); FirebaseAnalyticsUtil.reportSyncFailure( AnalyticsParamValue.SYNC_TRIGGER_USER, AnalyticsParamValue.SYNC_MODE_SEND_FORMS, analyticsMessage); } }); task.connect(StandardHomeActivity.this); task.executeParallel(); } }</code><technical_language>performing granular task check here, check feels repeatetive. Is is merge two</technical_language>

Target:
void syncButtonPressed() { ConnectionDiagnosticTask<StandardHomeActivity> task = new ConnectionDiagnosticTask(getApplicationContext()); task.setListener(new ConnectionDiagnosticTask.ConnectionDiagnosticListener<StandardHomeActivity>() { @Override public void connected(StandardHomeActivity receiver) { CommCareApplication.notificationManager().clearNotifications(AIRPLANE_MODE_CATEGORY); receiver.sendFormsOrSync(true); } @Override public void failed(StandardHomeActivity receiver, String errorMessageId, MessageTag notificationTag, String analyticsMessage) { receiver.handleSyncNotAttempted(Localization.get(errorMessageId)); CommCareApplication.notificationManager().reportNotificationMessage( NotificationMessageFactory.message( notificationTag, AIRPLANE_MODE_CATEGORY)); FirebaseAnalyticsUtil.reportSyncFailure( AnalyticsParamValue.SYNC_TRIGGER_USER, AnalyticsParamValue.SYNC_MODE_SEND_FORMS, analyticsMessage); } }); task.connect(StandardHomeActivity.this); task.executeParallel(); }
Source:
<code>public void suspendMachine(MachineLocation rawLocation) { String instanceId = vmInstanceIds.remove(rawLocation); if (instanceId == null) { LOG.info("Attempt to suspend unknown machine " + rawLocation + " in " + this); throw new IllegalArgumentException("Unknown machine " + rawLocation); } <START> getComputeService().suspendNode(instanceId); <END> }</code><technical_language>skip removeChild(location)? location unmanaged</technical_language>

Target:
public void suspendMachine(MachineLocation rawLocation) { String instanceId = vmInstanceIds.remove(rawLocation); if (instanceId == null) { LOG.info("Attempt to suspend unknown machine " + rawLocation + " in " + this); throw new IllegalArgumentException("Unknown machine " + rawLocation); } LOG.info("Suspending machine in {}, instance id {}", new Object[]{rawLocation, this, instanceId}); Exception toThrow = null; try { getComputeService().suspendNode(instanceId); } catch (Exception e) { toThrow = e; LOG.error("Problem suspending machine " + rawLocation + " in " + this + ", instance id " + instanceId, e); } removeChild(rawLocation); if (toThrow != null) { throw Exceptions.propagate(toThrow); } }
Source:
<code>private void store(LookupEntry newEntry, @Nullable LookupEntry existingEntry) { int newHashCode = translator.removeFieldsForHash(translator.toDbo(newEntry)).hashCode(); <START> Integer existingHashCode = existingEntry == null ? null : translator.removeFieldsForHash(translator.toDbo(existingEntry)).hashCode(); <END> if (existingHashCode != null && newHashCode == existingHashCode) { log.debug("Hash code not changed for URI {}; skipping write", newEntry.uri()); return; } log.debug("New entry or hash code changed for URI {}; writing", newEntry.uri()); lookup.update(MongoBuilders.where().idEquals(newEntry.uri()).build(), translator.toDbo(newEntry), UPSERT, SINGLE); }</code><technical_language>aside, tempted pull out translator.removeFieldsForHash(translator.toDbo(existingEntry)).hashCode(); a toHash() function for clarity</technical_language>

Target:
private void store(LookupEntry newEntry, @Nullable LookupEntry existingEntry) { if (existingEntry != null && lookupEntryHasher.writeHashFor(newEntry) == lookupEntryHasher.writeHashFor(existingEntry)) { log.debug("Hash code not changed for URI {}; skipping write", newEntry.uri()); return; } log.debug("New entry or hash code changed for URI {}; writing", newEntry.uri()); lookup.update(MongoBuilders.where().idEquals(newEntry.uri()).build(), translator.toDbo(newEntry), UPSERT, SINGLE); }
Source:
<code>private static void addHostNetworksAndUpdateInterfaces(VDS vds, Map<String, Object> xmlRpcStruct) { Map<String, Object> networks = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.NETWORKS); Map<String, Object> bridges = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.NETWORK_BRIDGES); Map<String, VdsNetworkInterface> vdsInterfaces = Entities.entitiesByName(vds.getInterfaces()); boolean bridgesReported = FeatureSupported.bridgesReportByVdsm(vds.getVdsGroupCompatibilityVersion()); if (networks != null) { vds.getNetworks().clear(); for (Entry<String, Object> entry : networks.entrySet()) { <START> Map<String, Object> network = (Map<String, Object>) entry.getValue(); <END> if (network != null) { String interfaceName = (String) network.get(VdsProperties.INTERFACE); VdsNetworkInterface networkIface = vdsInterfaces.get(interfaceName); Map<String, Object> bridge = (bridges == null) ? null : (Map<String, Object>) bridges.get(interfaceName); boolean bridgedNetwork = isBridgedNetwork(network); HostNetworkQos qos = new HostNetworkQosMapper(network).deserialize(); Network net = createNetworkData(entry.getKey(), network); List<VdsNetworkInterface> interfaces = findNetworkInterfaces(vdsInterfaces, bridgesReported, networkIface, bridgesReported ? bridge : network); for (VdsNetworkInterface iface : interfaces) { updateNetworkDetailsInInterface(iface, network, bridgedNetwork, qos, vds, net); } vds.getNetworks().add(net); reportInvalidInterfacesForNetwork(interfaces, net, vds); } } } }</code><technical_language>"Map<String, Object> network" is named network there. extracting "String networkName = entry.getKey();" clear, key is network name, worthy some clues kind of object in Map<String, Object>. I guess name-whatever pairs forming network properties</technical_language>

Target:
private static void addHostNetworksAndUpdateInterfaces(VDS vds, Map<String, Object> xmlRpcStruct) { Map<String, Map<String, Object>> networks = (Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORKS); Map<String, Map<String, Object>> bridges = (Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORK_BRIDGES); Map<String, VdsNetworkInterface> vdsInterfaces = Entities.entitiesByName(vds.getInterfaces()); boolean bridgesReported = FeatureSupported.bridgesReportByVdsm(vds.getVdsGroupCompatibilityVersion()); if (networks != null) { vds.getNetworks().clear(); for (Entry<String, Map<String, Object>> entry : networks.entrySet()) { Map<String, Object> network = entry.getValue(); if (network != null) { String interfaceName = (String) network.get(VdsProperties.INTERFACE); boolean bridgedNetwork = isBridgedNetwork(network); HostNetworkQos qos = new HostNetworkQosMapper(network).deserialize(); Network net = createNetworkData(entry.getKey(), network); List<VdsNetworkInterface> interfaces = bridgesReported ? findNetworkInterfaces(vdsInterfaces, interfaceName, bridges) : findBridgedNetworkInterfaces(network, vdsInterfaces); for (VdsNetworkInterface iface : interfaces) { updateNetworkDetailsInInterface(iface, network, bridgedNetwork, qos, vds, net); } vds.getNetworks().add(net); reportInvalidInterfacesForNetwork(interfaces, net, vds); } } } }
Source:
<code>List<ICompletionProposal> computeFilteredProposals(int offset, DocumentEvent event) { if (offset == fInvocationOffset && event == null) { fIsFilteredSubset= false; return fComputedProposals; } if (offset < fInvocationOffset) { fIsFilteredSubset= false; fInvocationOffset= offset; fContentAssistant.fireSessionRestartEvent(); fComputedProposals= computeProposals(fInvocationOffset); return fComputedProposals; } List<ICompletionProposal> proposals; if (offset < fFilterOffset) { proposals= fComputedProposals; fIsFilteredSubset= false; } else { proposals= fFilteredProposals; fIsFilteredSubset= true; } if (proposals == null) { fIsFilteredSubset= false; return null; } IDocument document= fContentAssistSubjectControlAdapter.getDocument(); int length= proposals.size(); List<ICompletionProposal> filtered= new ArrayList<>(length); <START> boolean recompute= false; <END> for (ICompletionProposal proposal : proposals) { if (proposal instanceof ICompletionProposalExtension2) { ICompletionProposalExtension2 p= (ICompletionProposalExtension2) proposal; try { if (p.validate(document, offset, event)) filtered.add(proposal); } catch (RuntimeException e) { } } else if (proposal instanceof ICompletionProposalExtension) { ICompletionProposalExtension p= (ICompletionProposalExtension) proposal; try { if (p.isValidFor(document, offset)) filtered.add(proposal); } catch (RuntimeException e) { } } else { return recomputeProposals(offset, event); } } return filtered; }</code><technical_language>This field useless</technical_language>

Target:
List<ICompletionProposal> computeFilteredProposals(int offset, DocumentEvent event) { if (offset == fInvocationOffset && event == null) { fIsFilteredSubset= false; return fComputedProposals; } if (offset < fInvocationOffset) { fIsFilteredSubset= false; fInvocationOffset= offset; fContentAssistant.fireSessionRestartEvent(); fComputedProposals= computeProposals(fInvocationOffset); return fComputedProposals; } List<ICompletionProposal> proposals; if (offset < fFilterOffset) { proposals= fComputedProposals; fIsFilteredSubset= false; } else { proposals= fFilteredProposals; fIsFilteredSubset= true; } if (proposals == null) { fIsFilteredSubset= false; return null; } IDocument document= fContentAssistSubjectControlAdapter.getDocument(); int length= proposals.size(); List<ICompletionProposal> filtered= new ArrayList<>(length); for (ICompletionProposal proposal : proposals) { if (proposal instanceof ICompletionProposalExtension2) { ICompletionProposalExtension2 p= (ICompletionProposalExtension2) proposal; try { if (p.validate(document, offset, event)) filtered.add(proposal); } catch (RuntimeException e) { } } else if (proposal instanceof ICompletionProposalExtension) { ICompletionProposalExtension p= (ICompletionProposalExtension) proposal; try { if (p.isValidFor(document, offset)) filtered.add(proposal); } catch (RuntimeException e) { } } else { return recomputeProposals(offset, event); } } return filtered; }
Source:
<code>public static @Nullable SegmentStoreDataProvider create(ITmfTrace trace, @Nullable ISegmentStoreProvider provider) { if (provider == null) { return null; } <START> if (provider instanceof IAnalysisModule) { ((IAnalysisModule) provider).schedule(); } return new SegmentStoreDataProvider(trace, provider); <END> }</code><technical_language>return if provider is AnalysisModule</technical_language>

Target:
public static @Nullable SegmentStoreDataProvider create(ITmfTrace trace, @Nullable ISegmentStoreProvider provider) { if (provider == null) { return null; } if (provider instanceof IAnalysisModule) { ((IAnalysisModule) provider).schedule(); return new SegmentStoreDataProvider(trace, provider); } return null; }
Source:
<code>public FeatureVectorParser(String exampleFile, String lexiconFile) { this(exampleFile); <START> ObjectInputStream lexIn = null; <END> try { lexIn = new ObjectInputStream(new FileInputStream(lexiconFile)); } catch (Exception e) { logger.error("Can't open '" + lexiconFile + "' for input:"); e.printStackTrace(); System.exit(1); } try { lexicon = (Feature[]) lexIn.readObject(); } catch (Exception e) { logger.error("Can't read from '" + lexiconFile + "':"); e.printStackTrace(); System.exit(1); } try { lexIn.close(); } catch (Exception e) { logger.error("Can't close '" + lexiconFile + "':"); e.printStackTrace(); System.exit(1); } }</code><technical_language>print is a System.exit(), please print error STDERR. @danyaljj do agree</technical_language>

Target:
public FeatureVectorParser(String exampleFile, String lexiconFile) { this(exampleFile); ObjectInputStream lexIn = null; try { lexIn = new ObjectInputStream(new FileInputStream(lexiconFile)); } catch (Exception e) { System.err.println("Can't open '" + lexiconFile + "' for input:"); e.printStackTrace(); System.exit(1); } try { lexicon = (Feature[]) lexIn.readObject(); } catch (Exception e) { System.err.println("Can't read from '" + lexiconFile + "':"); e.printStackTrace(); System.exit(1); } try { lexIn.close(); } catch (Exception e) { System.err.println("Can't close '" + lexiconFile + "':"); e.printStackTrace(); System.exit(1); } }
Source:
<code>private void setAttribute(Element element, String name, String value) { <START> if (name.endsWith("$")) { <END> return; } if (value.contains("{{") && value.contains("}}")) { return; } if (value.contains("[[") && value.contains("]]")) { return; } element.setAttribute(name, value); }</code><technical_language>add debug log for skipped attributes if confusion issue in devug level logs</technical_language>

Target:
private void setAttribute(Element element, String name, String value) { if (name.endsWith("$")) { getLogger().debug( "Template contains an attribute in element which " + "ends with $ and ignored by initialization since this is an attribute binding", templateClass.getSimpleName(), name, element.getTag()); return; } if (value.contains("{{") && value.contains("}}")) { getLogger().debug( "Template contains an attribute in element whose value" + " contains two-way binding and it's ignored by initilization", templateClass.getSimpleName(), name, element.getTag()); return; } if (value.contains("[[") && value.contains("]]")) { getLogger().debug( "Template contains an attribute in element whose value" + " contains binding and it's ignored by initilization", templateClass.getSimpleName(), name, element.getTag()); return; } element.setAttribute(name, value); }
Source:
<code>public void testGetProjectedSchema5() throws Exception { MessageType originalMsg = MessageTypeParser.parseMessageType( "message hive_schema {\n" + " optional group structCol {\n" + " optional int32 a;\n" + " optional group subStructCol {\n" + " optional int64 b;\n" + " optional boolean c;\n" + " }\n" + " }\n" + " optional boolean d;\n" + "}\n"); testConversion("structCol", "struct<subStructCol:struct<b:bigint,c:boolean>>", DataWritableReadSupport .getProjectedSchema(originalMsg, Arrays.asList("structCol"), Arrays.asList(0), new HashSet<>(Arrays.asList("structCol.subStructCol", "structCol.subStructCol.b", <START> "structCol.subStructCol.c"))).toString()); <END> }</code><technical_language>extra space</technical_language>

Target:
public void testGetProjectedSchema5() throws Exception { MessageType originalMsg = MessageTypeParser.parseMessageType( "message hive_schema {\n" + " optional group structCol {\n" + " optional int32 a;\n" + " optional group subStructCol {\n" + " optional int64 b;\n" + " optional boolean c;\n" + " }\n" + " }\n" + " optional boolean d;\n" + "}\n"); testConversion("structCol", "struct<subStructCol:struct<b:bigint,c:boolean>>", DataWritableReadSupport .getProjectedSchema(originalMsg, Arrays.asList("structCol"), Arrays.asList(0), Sets.newHashSet("structCol.subStructCol", "structCol.subStructCol.b", "structCol.subStructCol.c")).toString()); }