auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void updateChildLinks() throws DAOException, DataException { Set<Integer> referencedChildren = new TreeSet<>(); addAllChildrenRecursive(workpiece.getRootElement(), referencedChildren); TreeSet<Integer> savedChildren = new TreeSet<>(); process.getChildren().parallelStream().map(Process::getId).forEachOrdered(savedChildren::add); Iterator<Integer> referencedChildrenIterator = referencedChildren.iterator(); Iterator<Integer> savedChildrenIterator = savedChildren.iterator(); boolean nextReferencedChild = true; boolean nextSavedChild = true; Integer referencedChildId = null; Integer savedChildId = null; boolean save = false; <START> do { <END> if (nextReferencedChild) { referencedChildId = referencedChildrenIterator.hasNext() ? referencedChildrenIterator.next() : null; nextReferencedChild = false; } if (nextSavedChild) { savedChildId = savedChildrenIterator.hasNext() ? savedChildrenIterator.next() : null; nextSavedChild = false; } if (Objects.nonNull(referencedChildId) && Objects.isNull(savedChildId) || referencedChildId < savedChildId) { Process childToAdd = ServiceManager.getProcessService().getById(referencedChildId); childToAdd.setParent(process); process.getChildren().add(childToAdd); save = true; nextReferencedChild = true; } else if (Objects.isNull(referencedChildId) && Objects.nonNull(savedChildId) || referencedChildId > savedChildId) { Process childToRemove = ServiceManager.getProcessService().getById(savedChildId); childToRemove.setParent(null); process.getChildren().remove(childToRemove); save = true; nextSavedChild = true; } else if (Objects.nonNull(referencedChildId) && Objects.nonNull(savedChildId)) { nextReferencedChild = true; nextSavedChild = true; } } while (nextReferencedChild || nextSavedChild); if (save) { ServiceManager.getProcessService().save(process); } }</code><technical_language>A regular while loop work too, set conditions true beforehand</technical_language>

Target:
private void updateChildLinks() throws DAOException, DataException { TreeSet<Integer> referencedChildren = new TreeSet<>(); addAllChildrenRecursive(workpiece.getRootElement(), referencedChildren); TreeSet<Integer> savedChildren = new TreeSet<>(); process.getChildren().parallelStream().map(Process::getId).forEachOrdered(savedChildren::add); Map<Integer, Boolean> differences = ProcessListComparator.compareLists(referencedChildren, savedChildren); for (Entry<Integer, Boolean> difference : differences.entrySet()) { Process child = ServiceManager.getProcessService().getById(difference.getKey()); if (difference.getValue()) { child.setParent(process); process.getChildren().add(child); } else { child.setParent(null); process.getChildren().remove(child); } ServiceManager.getProcessService().save(child); } if (!differences.isEmpty()) { ServiceManager.getProcessService().save(process); } }
Source:
<code>public static WUState getStateID(WorkunitInfo wu) { if (wu != null) { if (wu.getStateID() != null) { return getStateID(wu.getStateID()); <START> } else if (wu.getState() != null && wu.getState().trim().length() != 0) { <END> return Workunit.translateWUState(wu.getState()); } } return WUState.UNKNOWN; }</code><technical_language>trim in translateWUState() argument in translateWUstate call is trimmed well. is, pass this condition (wu.getState().trim().length() != 0), fail translate due leading trailing spaces valid state string</technical_language>

Target:
public static WUState getStateID(WorkunitInfo wu) { if (wu != null) { if (wu.getStateID() != null) { return getStateID(wu.getStateID()); } else if (wu.getState() != null) { return Workunit.translateWUState(wu.getState()); } } return WUState.UNKNOWN; }
Source:
<code>@Override public Location getLastLocation(LostApiClient client) { throwIfNotConnected(client); Location location = null; try { location = service.getLastLocation(); } catch (RemoteException e) { <START> Log.e(TAG, "Error occurred trying to get last Location " + e.getStackTrace()); <END> } finally { return location; } }</code><technical_language>is Log.e(TAG,message,throwable), this preferrable? method downsides I aware of</technical_language>

Target:
@Override public Location getLastLocation(LostApiClient client) { throwIfNotConnected(client); Location location = null; try { location = service.getLastLocation(); } catch (RemoteException e) { Log.e(TAG, "Error occurred trying to get last Location", e); } finally { return location; } }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Transfer {"); sb.append("id = ").append(id).append(", "); <START> sb.append("date = ").append(time).append(", "); <END> sb.append("fromAccountId = ").append(fromAccountId).append(", "); sb.append("toAccountId = ").append(toAccountId).append(", "); sb.append("fromAmount = ").append(fromAmount).append(", "); sb.append("toAmount = ").append(toAmount).append(", "); sb.append("fromDecimals = ").append(fromDecimals).append(", "); sb.append("toDecimals = ").append(toDecimals); sb.append("}"); return sb.toString(); }</code><technical_language>breaks format</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Transfer {"); sb.append("id = ").append(id).append(", "); sb.append("time = ").append(time).append(", "); sb.append("fromAccountId = ").append(fromAccountId).append(", "); sb.append("toAccountId = ").append(toAccountId).append(", "); sb.append("fromAmount = ").append(fromAmount).append(", "); sb.append("toAmount = ").append(toAmount).append(", "); sb.append("fromDecimals = ").append(fromDecimals).append(", "); sb.append("toDecimals = ").append(toDecimals); sb.append("}"); return sb.toString(); }
Source:
<code>public VMImage.OSDiskConfiguration getResult() { VMImage.OSDiskConfiguration result = VMImage.OSDiskConfiguration .create(name, hostCaching, osState, os, mediaLink, logicalDiskSizeInGB, ioType); <START> return result; <END> }</code><technical_language>return directly</technical_language>

Target:
public VMImage.OSDiskConfiguration getResult() { return VMImage.OSDiskConfiguration .create(name, hostCaching, osState, os, mediaLink, logicalDiskSizeInGB, ioType); }
Source:
<code>public void destroy() { super.destroy(); if (transport != null) { try { transport.close(); } catch (IOException e) { <START> log.debug("Error when closing graphite socket: ", e); <END> } transport = null; } }</code><technical_language>Maybe? suggestion log.debug("Error closing datadog client: ", e);</technical_language>

Target:
public void destroy() { super.destroy(); if (transport != null) { try { transport.close(); } catch (IOException e) { log.debug("Error when closing Datadog client: ", e); } transport = null; } }
Source:
<code>public ReceivePack create(HttpServletRequest req, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { final ProjectControl pc = getProjectControl(req); if (pc.getCurrentUser() instanceof IdentifiedUser) { final IdentifiedUser user = (IdentifiedUser) pc.getCurrentUser(); final Set<AccountGroup.Id> receiveGroup = serverCommandConfig.getReceiveGroup(); <START> if (receiveGroup != null && !receiveGroup.isEmpty()) { <END> if (!CollectionsUtil.isAnyIncludedIn(user.getEffectiveGroups(), receiveGroup)) { throw new ServiceNotAuthorizedException(); } } final ReceiveCommits rc = factory.create(pc, db); final ReceiveCommits.Capable s = rc.canUpload(); if (s != ReceiveCommits.Capable.OK) { final String who = user.getUserName(); final String why = s.getMessage(); log.warn("Rejected push from " + who + ": " + why); throw new ServiceNotEnabledException(); } rc.getReceivePack().setRefLogIdent(user.newRefLogIdent()); return rc.getReceivePack(); } else { throw new ServiceNotAuthorizedException(); } }</code><technical_language>above, push this ProjectControl class</technical_language>

Target:
public ReceivePack create(HttpServletRequest req, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { final ProjectControl pc = getProjectControl(req); if (pc.getCurrentUser() instanceof IdentifiedUser) { final IdentifiedUser user = (IdentifiedUser) pc.getCurrentUser(); if (!pc.canPerformPackAction(receiveGroup)) { throw new ServiceNotAuthorizedException(); } final ReceiveCommits rc = factory.create(pc, db); final ReceiveCommits.Capable s = rc.canUpload(); if (s != ReceiveCommits.Capable.OK) { final String who = user.getUserName(); final String why = s.getMessage(); log.warn("Rejected push from " + who + ": " + why); throw new ServiceNotEnabledException(); } rc.getReceivePack().setRefLogIdent(user.newRefLogIdent()); return rc.getReceivePack(); } else { throw new ServiceNotAuthorizedException(); } }
Source:
<code><START> public int getLastLocusInBin(Bin bin) { <END> if(bin == null || bin.getBinNumber() > getMaxBins()) { throw new SAMException("Tried to get last locus for invalid bin: " + bin); } int level = getLevelForBin(bin); int firstBinOnLevel = getFirstBinOnLevel(level); int levelSize = getLevelSize(level); return (bin.getBinNumber() - firstBinOnLevel + 1)*(getMaxSpan()/levelSize); }</code><technical_language>understanding is case of methods match bai result a wider range of inputs bai? nice if pull live instead of 2 similar slightly implementations. complicated though, of fact some of methods in superclass static changed overridden easily public in other places. necessary do for merging this PR, grumbling</technical_language>

Target:
public int getLastLocusInBin(Bin bin) { if(bin == null || bin.getBinNumber() > getMaxBins()) { throw new SAMException("Tried to get last locus for invalid bin: " + bin); } int level = getLevelForBin(bin); int firstBinOnLevel = getFirstBinInLevelForCSI(level); int levelSize = getLevelSize(level); return (bin.getBinNumber() - firstBinOnLevel + 1)*(getMaxSpan()/levelSize); }
Source:
<code>public void addToCache(String key, Group entry, String cacheName, int tenantId) { <START> if (validateAddToCacheRequest(key, entry, cacheName)) return; <END> try { startTenantFlow(tenantId); Cache<String, Group> cache = GroupIdResolverCache(cacheName); if (cache != null && !cache.containsKey(key)) { cache.put(key, entry); if (log.isDebugEnabled()) { log.debug("Cache: " + cacheName + " which is under " + GROUP_ID_RESOLVER_CACHE_MANAGER + "," + "added the entry: " + entry + " for the key: " + key + " successfully"); } } } finally { PrivilegedCarbonContext.endTenantFlow(); } }</code><technical_language>'isValidCacheRequest' method name, this is a boolean operation. reading method, right. feels if request is valid 'return'. if(isValid()){ }else{ returnl }</technical_language>

Target:
public void addToCache(String key, Group entry, String cacheName, int tenantId) { if (!isValidAddToCacheRequest(key, entry, cacheName)) return; try { startTenantFlow(tenantId); Cache<String, Group> cache = GroupIdResolverCache(cacheName); if (cache != null && !cache.containsKey(key)) { cache.put(key, entry); if (log.isDebugEnabled()) { log.debug("Cache: " + cacheName + " which is under " + GROUP_ID_RESOLVER_CACHE_MANAGER + "," + "added the entry: " + entry + " for the key: " + key + " successfully"); } } } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Source:
<code>public Node visitJoinRelation(SqlBaseParser.JoinRelationContext context) { Relation left = (Relation) visit(context.left); Relation right; if (context.CROSS() != null) { right = (Relation) visit(context.right); return new Join(Join.Type.CROSS, left, right, Optional.empty()); } JoinCriteria criteria; if (context.NATURAL() != null) { right = (Relation) visit(context.right); criteria = new NaturalJoin(); } else { right = (Relation) visit(context.rightRelation); if (context.joinCriteria().ON() != null) { criteria = new JoinOn((Expression) visit(context.joinCriteria().booleanExpression())); } else if (context.joinCriteria().USING() != null) { List<String> columns = identsToStrings(context.joinCriteria().ident()); <START> Table leftTable = (Table) left; <END> Table rightTable = (Table) right; criteria = new JoinUsing(leftTable.getName(), rightTable.getName(), columns); } else { throw new IllegalArgumentException("Unsupported join criteria"); } } return new Join(getJoinType(context.joinType()), left, right, Optional.of(criteria)); }</code><technical_language>Is safe cast Table here? if left right is a query</technical_language>

Target:
public Node visitJoinRelation(SqlBaseParser.JoinRelationContext context) { Relation left = (Relation) visit(context.left); Relation right; if (context.CROSS() != null) { right = (Relation) visit(context.right); return new Join(Join.Type.CROSS, left, right, Optional.empty()); } JoinCriteria criteria; if (context.NATURAL() != null) { right = (Relation) visit(context.right); criteria = new NaturalJoin(); } else { right = (Relation) visit(context.rightRelation); if (context.joinCriteria().ON() != null) { criteria = new JoinOn((Expression) visit(context.joinCriteria().booleanExpression())); } else if (context.joinCriteria().USING() != null) { List<String> columns = identsToStrings(context.joinCriteria().ident()); criteria = new JoinUsing(columns); } else { throw new IllegalArgumentException("Unsupported join criteria"); } } return new Join(getJoinType(context.joinType()), left, right, Optional.of(criteria)); }
Source:
<code>public void privParameterNameTest() throws Exception { final String[] expected = { "8:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "$arg1", privFormat), "9:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "ar$g2", privFormat), "10:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "arg3$", privFormat), "11:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "a_rg4", privFormat), "12:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "_arg5", privFormat), "13:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "arg6_", privFormat), "14:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "aArg7", privFormat), "15:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "aArg8", privFormat), "16:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "aar_g", privFormat), }; final String filePath = getPath("InputParameterNameSimple.java"); Integer[] warnList = getLinesWithWarn(filePath); final List<Integer> selected = new ArrayList<>(); Collections.addAll(selected, warnList); <START> selected.removeIf(line -> line > 16); <END> warnList = selected.toArray(new Integer[selected.size()]); verify(privConfig, filePath, expected, warnList); }</code><technical_language>This code easy read confused first. input file configurations? input files test simple conditional removes? If update input file, this kind of removal missed hide issues in file</technical_language>

Target:
public void privParameterNameTest() throws Exception { final String[] expected = { "8:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "$arg1", privFormat), "9:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "ar$g2", privFormat), "10:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "arg3$", privFormat), "11:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "a_rg4", privFormat), "12:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "_arg5", privFormat), "13:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "arg6_", privFormat), "14:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "aArg7", privFormat), "15:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "aArg8", privFormat), "16:21: " + getCheckMessage(privConfig.getMessages(), MSG_KEY, "aar_g", privFormat), }; final String filePath = getPath("InputParameterNameSimplePriv.java"); final Integer[] warnList = getLinesWithWarn(filePath); verify(privConfig, filePath, expected, warnList); }
Source:
<code>public AnnotationQueryHandlerAdapter(T target, ParameterResolverFactory parameterResolverFactory) { this(target, parameterResolverFactory, <START> new ClasspathHandlerDefinition(Thread.currentThread().getContextClassLoader())); <END> }</code><technical_language>target's class loader instead</technical_language>

Target:
public AnnotationQueryHandlerAdapter(T target, ParameterResolverFactory parameterResolverFactory) { this(target, parameterResolverFactory, ClasspathHandlerDefinition.forClass(target.getClass())); }
Source:
<code>public void onBtnNextClick() { if (mViewPager.getCurrentItem() == SLIDE_POS_LOCATION_PERMISSION) { if (!haveStoragePermission()) { Toast.makeText(this, R.string.toast_write_storage_permission_required, Toast.LENGTH_LONG).show(); <START> this.finish(); <END> return; } } int current = getItem(+1); if (current < layouts.length) { mViewPager.setCurrentItem(current); btnBack.setVisibility(View.VISIBLE); } else { Log.v(TAG, "User completed first start UI."); mPreferences.edit().putBoolean(Constants.PREF_FIRST_START, false).apply(); startApp(); } }</code><technical_language>finish do in this case</technical_language>

Target:
public void onBtnNextClick() { if (mViewPager.getCurrentItem() == SLIDE_POS_LOCATION_PERMISSION) { if (!haveStoragePermission()) { Toast.makeText(this, R.string.toast_write_storage_permission_required, Toast.LENGTH_LONG).show(); return; } } int current = getItem(+1); if (current < mLayouts.length) { mViewPager.setCurrentItem(current); mBackButton.setVisibility(View.VISIBLE); } else { Log.v(TAG, "User completed first start UI."); mPreferences.edit().putBoolean(Constants.PREF_FIRST_START, false).apply(); startApp(); } }
Source:
<code>protected String suggestNewFieldName(final ContentType con, final Relationship relationship, final boolean isChild) { final String name = UtilMethods.capitalize(con.variable()); final boolean selfRelated = sameParentAndChild(relationship); String suffix = selfRelated? isChild?"Child" : "Parent": "s"; if(name.toLowerCase().endsWith(suffix)) { return name; } <START> String s = ""; <END> if(isChild){ if (relationship.getCardinality() != WebKeys.Relationship.RELATIONSHIP_CARDINALITY.ONE_TO_ONE.ordinal()){ s = selfRelated?"Children":suffix; } else if(selfRelated){ s = suffix; } } else{ if (relationship.getCardinality() == WebKeys.Relationship.RELATIONSHIP_CARDINALITY.MANY_TO_MANY.ordinal()){ s = selfRelated?"Parents":suffix; } else if(selfRelated){ s = suffix; } } return name + s; }</code><technical_language>rename this var</technical_language>

Target:
protected String suggestNewFieldName(final ContentType con, final Relationship relationship, final boolean isChild) { final String name = UtilMethods.capitalize(con.variable()); final boolean selfRelated = sameParentAndChild(relationship); String suffix = selfRelated? isChild?"Child" : "Parent": "s"; if(name.toLowerCase().endsWith(suffix)) { return name; } String finalSuffix = ""; if(isChild){ if (relationship.getCardinality() != WebKeys.Relationship.RELATIONSHIP_CARDINALITY.ONE_TO_ONE.ordinal()){ finalSuffix = selfRelated?"Children":suffix; } else if(selfRelated){ finalSuffix = suffix; } } else{ if (relationship.getCardinality() == WebKeys.Relationship.RELATIONSHIP_CARDINALITY.MANY_TO_MANY.ordinal()){ finalSuffix = selfRelated?"Parents":suffix; } else if(selfRelated){ finalSuffix = suffix; } } return name + finalSuffix; }
Source:
<code>public List<SDVariable> doDiff(List<SDVariable> i_v1) { SDVariable out = outputVariables()[0]; <START> int[] argShape = arg().getShape(); <END> SDVariable expandedOut = sameDiff.f().reductionBroadcastableWithOrigShape(argShape.length, dimensions, out); expandedOut = sameDiff.onesLike("temp0", arg()).mul("tempmul", expandedOut); SDVariable expandedGrad = sameDiff.f().reductionBroadcastableWithOrigShape(argShape.length, dimensions, i_v1.get(0)); SDVariable eq = sameDiff.eq(arg(), expandedOut); SDVariable ret = eq.mul(expandedGrad); return Collections.singletonList(ret); }</code><technical_language>Arg a shape. some place holder logic want put in here. checking for null shapes do this good</technical_language>

Target:
public List<SDVariable> doDiff(List<SDVariable> i_v1) { SDVariable out = outputVariables()[0]; int origRank = Shape.rankFromShape(arg().getShape()); SDVariable expandedOut = sameDiff.f().reductionBroadcastableWithOrigShape(origRank, dimensions, out); expandedOut = sameDiff.onesLike("temp0", arg()).mul("tempmul", expandedOut); SDVariable expandedGrad = sameDiff.f().reductionBroadcastableWithOrigShape(origRank, dimensions, i_v1.get(0)); SDVariable eq = sameDiff.eq(arg(), expandedOut); SDVariable ret = eq.mul(expandedGrad); return Collections.singletonList(ret); }
Source:
<code>public void publish(PublishChangeEditInput input) throws RestApiException { <START> String request = "/changes/"+id+"/edit:publish"; <END> String json = gerritRestClient.getGson().toJson(input); gerritRestClient.postRequest(request,json); }</code><technical_language>Please add spaces +. getRequestPath well</technical_language>

Target:
public void publish(PublishChangeEditInput input) throws RestApiException { String request = getRequestPath() + ":publish"; String json = gerritRestClient.getGson().toJson(input); gerritRestClient.postRequest(request,json); }
Source:
<code>public static List<Document> collect(Directory directory, int limit) throws IOException { MatchAllDocsQuery allDocsQuery = new MatchAllDocsQuery(); List<Document> docs = new ArrayList<>(limit); <START> IndexSearcher indexSearcher = openSearcher(directory); <END> TopDocs topDocs = indexSearcher.search(allDocsQuery, limit); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { docs.add(indexSearcher.doc(scoreDoc.doc)); } return docs; }</code><technical_language>this closed</technical_language>

Target:
public static List<Document> collect(Directory directory, int limit) throws IOException { try (DirectoryReader reader = DirectoryReader.open(directory)) { MatchAllDocsQuery allDocsQuery = new MatchAllDocsQuery(); List<Document> docs = new ArrayList<>(limit); IndexSearcher indexSearcher = new IndexSearcher(reader); TopDocs topDocs = indexSearcher.search(allDocsQuery, limit); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { docs.add(indexSearcher.doc(scoreDoc.doc)); } return docs; } }
Source:
<code>private Optional<Long> getLvmSizeForDevice(String device) { Optional<GlusterLocalLogicalVolume> thinVolume = logicalVolumes.stream() .filter(lvmMatchMapperName(device)) .filter(v -> <START> !"".equals(v.getPoolName().trim())) <END> .findAny(); thinVolume = thinVolume.flatMap(v -> logicalVolumes.stream() .filter(lv -> v.getPoolName().equals(lv.getLogicalVolumeName())) .findAny()); Optional<Long> result = thinVolume.map(GlusterLocalLogicalVolume::getFree); List<String> physicalDevices = thinVolume.map(GlusterLocalLogicalVolume::getVolumeGroupName) .map(v -> physicalVolumes.stream() .filter(g -> g.getVolumeGroupName().equals(v)) .map(GlusterLocalPhysicalVolume::getPhysicalVolumeName) .collect(Collectors.toList()) ).orElseGet(Collections::emptyList); if (physicalDevices.size() != 1) { return result; } Optional<Long> innerResult = getThinSizeForDevice(physicalDevices.get(0)); if (innerResult.isPresent()) { result = result.map(s -> s > innerResult.get() ? innerResult.get() : s); } return result; }</code><technical_language>clearer check if a string is empty .isEmpty() instead of "".equals()</technical_language>

Target:
private Optional<Long> getLvmSizeForDevice(String device) { Optional<GlusterLocalLogicalVolume> thinVolume = logicalVolumes.stream() .filter(lvmMatchMapperName(device)) .filter(v -> !v.getPoolName().trim().isEmpty()) .findAny(); thinVolume = thinVolume.flatMap(v -> logicalVolumes.stream() .filter(lv -> v.getPoolName().equals(lv.getLogicalVolumeName())) .findAny()); Optional<Long> result = thinVolume.map(GlusterLocalLogicalVolume::getFree); List<String> physicalDevices = thinVolume.map(GlusterLocalLogicalVolume::getVolumeGroupName) .map(v -> physicalVolumes.stream() .filter(g -> g.getVolumeGroupName().equals(v)) .map(GlusterLocalPhysicalVolume::getPhysicalVolumeName) .collect(Collectors.toList()) ).orElseGet(Collections::emptyList); if (physicalDevices.size() != 1) { return result; } Optional<Long> innerResult = getThinSizeForDevice(physicalDevices.get(0)); if (innerResult.isPresent()) { result = result.map(s -> s > innerResult.get() ? innerResult.get() : s); } return result; }
Source:
<code>public void addCube(Cube cube) { <START> throw new UnsupportedOperationException("Server must have sent Cubes before Columns"); <END> }</code><technical_language>do part of code add a cube there</technical_language>

Target:
public void addCube(Cube cube) { }
Source:
<code>protected String requireOption(String name, String errorMessage) { String value = options.get(name); if (isBlank(value)) { throw new IllegalArgumentException("Metric Reporter configuration requires option: " + name <START> + (isBlank(errorMessage) ? "" : errorMessage)); <END> } return value; }</code><technical_language>missing name errorMessage, space some separator</technical_language>

Target:
protected String requireOption(String name, String errorMessage) { String value = options.get(name); if (isBlank(value)) { throw new IllegalArgumentException("Metric Reporter configuration requires option: " + name + (isBlank(errorMessage) ? "" : " " + errorMessage)); } return value; }
Source:
<code>private void deleteOnExit(final Path path) { <START> recursiveDeleteDir(Paths.get("/tmp/maven-hack")); <END> Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> recursiveDeleteDir(path))); }</code><technical_language>@bsideup Thanks clue is a good one, requires load classes for FileVisitor Files. I idea a BiConsumer (second parameter is instance of file visitor I extracted a class). This code ok, error disappears</technical_language>

Target:
private void deleteOnExit(final Path path) { BiConsumer<Path, DeleteFileVisitor> consumer = PathUtils::recursiveDeleteDir; Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> consumer.accept(path, new DeleteFileVisitor()))); }
Source:
<code>public void configure(final HttpSecurity http) throws Exception { LOG.info("Authentication mode: " + settings.getAuthMode()); if (settings.getAuthMode() == SecuritySettings.AuthMode.FULL) { http.authorizeRequests() .antMatchers(GET, "/event-types events events events **").access(hasScope(nakadiAdminScope)) .antMatchers(POST, "/event-types/**").access(hasScope(eventTypeWriteScope)) .antMatchers(PUT, "/event-types/**").access(hasScope(eventTypeWriteScope)) .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else if (settings.getAuthMode() == SecuritySettings.AuthMode.BASIC) { http.authorizeRequests() .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else { http.authorizeRequests() .anyRequest().permitAll(); } }</code><technical_language>Please forget extend security tests</technical_language>

Target:
public void configure(final HttpSecurity http) throws Exception { LOG.info("Authentication mode: " + settings.getAuthMode()); if (settings.getAuthMode() == SecuritySettings.AuthMode.FULL) { http.authorizeRequests() .antMatchers(GET, "/event-types events events cursors events **").access(hasScope(nakadiAdminScope)) .antMatchers(POST, "/event-types/**").access(hasScope(eventTypeWriteScope)) .antMatchers(PUT, "/event-types/**").access(hasScope(eventTypeWriteScope)) .antMatchers(POST, "/subscriptions/**").access(hasScope(eventStreamReadScope)) .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else if (settings.getAuthMode() == SecuritySettings.AuthMode.BASIC) { http.authorizeRequests() .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else { http.authorizeRequests() .anyRequest().permitAll(); } }
Source:
<code>public String name() { <START> return "cooperative"; <END> }</code><technical_language>cooperative-sticky? cooperative is general I think</technical_language>

Target:
public String name() { return "cooperative-sticky"; }
Source:
<code>protected void validatePositionOfPortOnContainer(String containerName, String portName, boolean pinBorderedNodes) { super.validatePositionOfPortOnContainer(containerName, portName, pinBorderedNodes); SWTBotGefEditPart swtbotContainerEditPart = editor.getEditPart(containerName); assertNotNull("No container edit part found with this name", swtbotContainerEditPart); EditPart containerSquareEP = swtbotContainerEditPart.part(); final AbstractBorderedShapeEditPart containerEP = (AbstractBorderedShapeEditPart) containerSquareEP.getParent(); final AbstractDiagramBorderNodeEditPart portEP = findPortInContainer(containerEP, portName); <START> assertTrue("The port " + portName + " of the container " + containerName + " is not aligned on the grid.", checkBorderNodeAlignOnGrid(portEP)); <END> }</code><technical_language>Add location of border node grid step in this message. In case of failure, helps understand problem</technical_language>

Target:
protected void validatePositionOfPortOnContainer(String containerName, String portName, boolean pinBorderedNodes) { super.validatePositionOfPortOnContainer(containerName, portName, pinBorderedNodes); SWTBotGefEditPart swtbotContainerEditPart = editor.getEditPart(containerName); assertNotNull("No container edit part found with this name", swtbotContainerEditPart); EditPart containerSquareEP = swtbotContainerEditPart.part(); final AbstractBorderedShapeEditPart containerEP = (AbstractBorderedShapeEditPart) containerSquareEP.getParent(); final AbstractDiagramBorderNodeEditPart portEP = findPortInContainer(containerEP, portName); checkBorderNodeAlignOnGrid(portEP, "port " + portName + " of the container " + containerName); }
Source:
<code><START> public void incrementAllCounters() { <END> aLong.incrementAndGet(); aInt.incrementAndGet(); evalLong += 1; counter.incr(); }</code><technical_language>this method private</technical_language>

Target:
private void incrementAllCounters() { aLong.incrementAndGet(); aInt.incrementAndGet(); evalLong += 1; counter.incr(); }
Source:
<code><START> private void addFreemarkerVariables(Map<String, Object> freemarkerVariables) <END> { }</code><technical_language>Overriding is quiet hard method is private ;-)</technical_language>

Target:
protected void addFreemarkerVariables(Map<String, Object> freemarkerVariables) { }
Source:
<code>public static CompletableFuture<AllCoordinatorSnapshots> triggerAllCoordinatorCheckpoints( final Collection<OperatorCoordinatorCheckpointContext> coordinators, final long checkpointId) throws Exception { final Collection<CompletableFuture<CoordinatorSnapshot>> individualSnapshots = new ArrayList<>(coordinators.size()); for (final OperatorCoordinatorCheckpointContext coordinator : coordinators) { final CompletableFuture<CoordinatorSnapshot> checkpointFuture = triggerCoordinatorCheckpoint(coordinator, checkpointId); coordinator.onCallTriggerCheckpoint(checkpointId); individualSnapshots.add(checkpointFuture); checkpointFuture.whenComplete((ignored, failure) -> { if (failure != null) { coordinator.abortCurrentTriggering(); } else { <START> coordinator.onCheckpointStateFutureComplete(checkpointId); <END> } }); } return FutureUtils.combineAll(individualSnapshots).thenApply(AllCoordinatorSnapshots::new); }</code><technical_language>If checkpointFuture is completed coordinator executor whenComplete is invoked shuts valve, some events get valve snapshot is valve is shut. result in inconsistent state TM Coordinator</technical_language>

Target:
public static CompletableFuture<AllCoordinatorSnapshots> triggerAllCoordinatorCheckpoints( final Collection<OperatorCoordinatorCheckpointContext> coordinators, final long checkpointId) throws Exception { final Collection<CompletableFuture<CoordinatorSnapshot>> individualSnapshots = new ArrayList<>(coordinators.size()); for (final OperatorCoordinatorCheckpointContext coordinator : coordinators) { final CompletableFuture<CoordinatorSnapshot> checkpointFuture = triggerCoordinatorCheckpoint(coordinator, checkpointId); individualSnapshots.add(checkpointFuture); } return FutureUtils.combineAll(individualSnapshots).thenApply(AllCoordinatorSnapshots::new); }
Source:
<code>public void init() throws RepositoryException { super.init(); if (httpFactory != null) { HttpClientBuilder clientBuilder = httpFactory.newBuilder(); clientBuilder.setDefaultSocketConfig( SocketConfig.custom() .setSoTimeout(retryPause) .build()); clientBuilder.setDefaultRequestConfig( RequestConfig.custom() .setConnectTimeout(retryPause) .build() ); httpClient = clientBuilder.build(); clientProvider.setHttpClientSupplier(this::getHttpClient); <START> clientProvider.setUsername(username); <END> clientProvider.setPassword(password); } }</code><technical_language>I timeout setting</technical_language>

Target:
public void init() throws RepositoryException { super.init(); if (httpFactory != null) { HttpClientBuilder clientBuilder = httpFactory.newBuilder(); clientBuilder.setDefaultSocketConfig( SocketConfig.custom() .setSoTimeout(timeout) .build()); clientBuilder.setDefaultRequestConfig( RequestConfig.custom() .setConnectTimeout(timeout) .build() ); httpClient = clientBuilder.build(); clientProvider.setHttpClientSupplier(this::getHttpClient); clientProvider.setUsername(username); clientProvider.setPassword(password); } }
Source:
<code>public void start(Stage stage) throws Exception { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/openpane.fxml")); <START> loader.setControllerFactory(new Callback<Class<?>, Object>() { <END> public Object call(Class<?> p) { return new DummyFileOpenController(); } }); AnchorPane openpane = loader.load(); Scene scene = new Scene(openpane, WIDTH, HEIGHT); stage.setScene(scene); stage.show(); control = loader.getController(); }</code><technical_language>do this a lambda</technical_language>

Target:
public void start(Stage stage) throws Exception { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/openpane.fxml")); loader.setControllerFactory((p) -> new DummyFileOpenController()); AnchorPane openpane = loader.load(); Scene scene = new Scene(openpane, WIDTH, HEIGHT); stage.setScene(scene); stage.show(); control = loader.getController(); }
Source:
<code>public void dumpEntities(@CommandParam(value = "componentNames", required = false) String componentNames) throws IOException { EngineEntityManager engineEntityManager = (EngineEntityManager) entityManager; PrefabSerializer prefabSerializer = new PrefabSerializer(engineEntityManager.getComponentLibrary(), engineEntityManager.getTypeSerializerLibrary()); WorldDumper worldDumper = new WorldDumper(engineEntityManager, prefabSerializer); if (componentNames == null) { worldDumper.save(PathManager.getInstance().getHomePath().resolve("entityDump.txt")); } else { Reflections reflections = new Reflections("org.terasology"); List<Class<? extends Component>> filterComponents = new LinkedList<>(); List<String> componentNamesList = Arrays.asList(componentNames.split(" ")); for (String componentName : componentNamesList) { if (componentName.trim().length() > 0) { Optional<Class<? extends Component>> component = reflections.getSubTypesOf(Component.class).stream().filter(e -> e.getSimpleName().equals(componentName)).findFirst(); component.ifPresent(filterComponents::add); } } <START> if (!filterComponents.isEmpty()) { <END> worldDumper.save(PathManager.getInstance().getHomePath().resolve("entityDump.txt"), filterComponents); } } }</code><technical_language>a message in console if components found</technical_language>

Target:
public String dumpEntities(@CommandParam(value = "componentNames", required = false) String componentNames) throws IOException { int savedEntitiCount = 0; EngineEntityManager engineEntityManager = (EngineEntityManager) entityManager; PrefabSerializer prefabSerializer = new PrefabSerializer(engineEntityManager.getComponentLibrary(), engineEntityManager.getTypeSerializerLibrary()); WorldDumper worldDumper = new WorldDumper(engineEntityManager, prefabSerializer); if (componentNames == null) { savedEntitiCount = worldDumper.save(PathManager.getInstance().getHomePath().resolve("entityDump.txt")); } else { List<String> componentNamesList = new LinkedList<>(Arrays.asList(componentNames.split(" "))); List<Class<? extends Component>> filterComponents = componentNamesList.stream() .filter(o -> o.trim().length() > 0) .map(String::trim) .map(o -> Streams.stream(moduleManager.getEnvironment().getSubtypesOf(Component.class)) .filter(e -> e.getSimpleName().equalsIgnoreCase(o)).findFirst()) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); if (!filterComponents.isEmpty()) { savedEntitiCount = worldDumper.save(PathManager.getInstance().getHomePath().resolve("entityDump.txt"), filterComponents); } } return "Number of entities saved: " + savedEntitiCount; }
Source:
<code>public void remappingFunctionReturnsIterableOfEntriesForEachInputEntry() throws Exception { final Store<K, V> kvStore = factory.newStore(new StoreConfigurationImpl<K, V>(factory.getKeyType(), factory .getValueType(), null, Predicates.<Cache.Entry<K, V>>all(), null, ClassLoader.getSystemClassLoader(), Expirations.noExpiration())); final K k1 = factory.createKey(1L); final V v1 = factory.createValue(1L); Set<K> set = new HashSet<K>(); set.add(k1); kvStore.put(k1, v1); try { kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() { @Override public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) { Map.Entry<? extends K, ? extends V> entry = entries.iterator().next(); assertThat(entry.getValue(), is(v1)); <START> return null; <END> } } ); } catch (CacheAccessException e) { System.err.println("Warning, an exception is thrown due to the SPI test"); e.printStackTrace(); } }</code><technical_language>return null compute method. This throws NPE for I run it. in other tests cases I besides</technical_language>

Target:
public void remappingFunctionReturnsIterableOfEntriesForEachInputEntry() throws Exception { final Store<K, V> kvStore = factory.newStore(new StoreConfigurationImpl<K, V>(factory.getKeyType(), factory .getValueType(), null, Predicates.<Cache.Entry<K, V>>all(), null, ClassLoader.getSystemClassLoader(), Expirations.noExpiration())); final K k1 = factory.createKey(1L); final V v1 = factory.createValue(1L); Set<K> set = new HashSet<K>(); set.add(k1); kvStore.put(k1, v1); try { kvStore.bulkCompute(Arrays.asList((K[]) set.toArray()), new Function<Iterable<? extends Map.Entry<? extends K, ? extends V>>, Iterable<? extends Map.Entry<? extends K, ? extends V>>>() { @Override public Iterable<? extends Map.Entry<? extends K, ? extends V>> apply(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) { Map.Entry<? extends K, ? extends V> entry = entries.iterator().next(); assertThat(entry.getValue(), is(v1)); Map<K, V> map = new HashMap<K, V>(); map.put(entry.getKey(), entry.getValue()); return map.entrySet(); } } ); } catch (CacheAccessException e) { System.err.println("Warning, an exception is thrown due to the SPI test"); e.printStackTrace(); } }
Source:
<code>private void generateFullRangeCheck(Versions ifVersions, Versions ifNotVersions, CodeBuffer buffer) { if (ifMember != null) { buffer.printf("if ((version >= %d) && (version <= %d)) {%n", containingVersions.lowest(), containingVersions.highest()); buffer.incrementIndent(); ifMember.generate(ifVersions); buffer.decrementIndent(); if (ifNotMember != null) { buffer.printf("} else {%n"); buffer.incrementIndent(); ifNotMember.generate(ifNotVersions); buffer.decrementIndent(); buffer.printf("}%n"); } else { <START> buffer.printf("}%n"); <END> } } else if (ifNotMember != null) { buffer.printf("if ((version < %d) || (version > %d)) {%n", containingVersions.lowest(), containingVersions.highest()); buffer.incrementIndent(); ifNotMember.generate(ifNotVersions); buffer.decrementIndent(); buffer.printf("}%n"); } }</code><technical_language>nit: This out line in if else block removed (it consistent IsNullConditional::generate method then</technical_language>

Target:
private void generateFullRangeCheck(Versions ifVersions, Versions ifNotVersions, CodeBuffer buffer) { if (ifMember != null) { buffer.printf("if ((version >= %d) && (version <= %d)) {%n", containingVersions.lowest(), containingVersions.highest()); buffer.incrementIndent(); ifMember.generate(ifVersions); buffer.decrementIndent(); if (ifNotMember != null) { buffer.printf("} else {%n"); buffer.incrementIndent(); ifNotMember.generate(ifNotVersions); buffer.decrementIndent(); } buffer.printf("}%n"); } else if (ifNotMember != null) { buffer.printf("if ((version < %d) || (version > %d)) {%n", containingVersions.lowest(), containingVersions.highest()); buffer.incrementIndent(); ifNotMember.generate(ifNotVersions); buffer.decrementIndent(); buffer.printf("}%n"); } }
Source:
<code>public ValidationResult validateOpenStackImageConstraints() { if (ProviderType.OPENSTACK_IMAGE != provider.getType()) { return ValidationResult.VALID; } List<Provider<?>> existingProviders = Injector.get(ProviderDao.class).getAllByTypes(ProviderType.OPENSTACK_IMAGE); <START> if (OpenStackTokenProviderFactory.isApiV3(provider)) { return openStackImageV3Constraints(existingProviders); } else { return openStackImageV2Constraints(existingProviders); } <END> }</code><technical_language>Consider ? : syntax - return ... ? x : y</technical_language>

Target:
public ValidationResult validateOpenStackImageConstraints() { if (ProviderType.OPENSTACK_IMAGE != provider.getType()) { return ValidationResult.VALID; } List<Provider<?>> existingProviders = Injector.get(ProviderDao.class).getAllByTypes(ProviderType.OPENSTACK_IMAGE); return OpenStackTokenProviderFactory.isApiV3(provider) ? openStackImageV3Constraints(existingProviders) : openStackImageV2Constraints(existingProviders); }
Source:
<code>protected void setUp() throws Exception { shell = Display.getDefault().getActiveShell(); renderer = new StackRendererTestable(); context = EclipseContextFactory.create(); context.set(CSSRenderingUtils.class, new CSSRenderingUtils()); <START> part = (MPart) Proxy.newProxyInstance(getClass().getClassLoader(), <END> new Class<?>[] { MPart.class }, new InvocationHandler() { public Object invoke(Object obj, Method method, Object[] args) throws Throwable { if ("getContext".equals(method.getName())) { return context; } return null; } }); }</code><technical_language>curious, issue in MBasicFactory.INSTANCE.createPart() set factory</technical_language>

Target:
protected void setUp() throws Exception { shell = Display.getDefault().getActiveShell(); renderer = new StackRendererTestable(); part = MBasicFactory.INSTANCE.createPart(); }
Source:
<code>private static Statement parseFormatted(SqlParser sqlParser, ParsingOptions parsingOptions, String sql, Node tree) { try { return sqlParser.createStatement(sql, parsingOptions); } catch (ParsingException e) { String error = format("failed to parse formatted SQL: %s\nerror: %s\ntree: %s", sql, e.getMessage(), tree); <START> throw new AssertionError(error, e); <END> } }</code><technical_language>I inline error. you</technical_language>

Target:
private static Statement parseFormatted(SqlParser sqlParser, ParsingOptions parsingOptions, String sql, Node tree) { try { return sqlParser.createStatement(sql, parsingOptions); } catch (ParsingException e) { throw new AssertionError(format("failed to parse formatted SQL: %s\nerror: %s\ntree: %s", sql, e.getMessage(), tree), e); } }
Source:
<code>public ILaunchConfiguration getActiveLaunchConfiguration() throws CoreException { ILaunchConfiguration activeConfig = getLaunchConfiguration(activeLaunchDesc, activeLaunchTarget); if (activeConfig != null) { <START> saveActiveTargetMapping(activeConfig, activeLaunchTarget); <END> } return activeConfig; }</code><technical_language>+1 of a place though. place a real launch configuration</technical_language>

Target:
public ILaunchConfiguration getActiveLaunchConfiguration() throws CoreException { ILaunchConfiguration activeConfig = getLaunchConfiguration(activeLaunchDesc, activeLaunchTarget); if (activeConfig != null) { remoteLaunchConfigService.setActiveConnection(activeConfig, activeLaunchTarget); } return activeConfig; }
Source:
<code>synchronized void handleResult(List<MutateRowsResponse> result) { AtomicReference<Long> backoffTime = new AtomicReference<>(); if (this.currentRequestManager == null) { LOG.warn("Got duplicate responses for bulk mutation."); return; } if (result == null || result.isEmpty()) { perfromFullRetry(backoffTime, new IllegalStateException("MutateRowResponse result or statuses")); return; } List<MutateRowsResponse.Entry> entries = new ArrayList<>(); for (MutateRowsResponse response : result) { entries.addAll(response.getEntriesList()); } if (entries.isEmpty()) { <START> perfromFullRetry(backoffTime, new IllegalStateException("MutateRowResponse result or statuses")); <END> return; } try { String tableName = currentRequestManager.request.getTableName(); RequestManager retryRequestManager = new RequestManager(tableName); int processedCount = handleResponses(backoffTime, entries, retryRequestManager); handleExtraFutures(backoffTime, processedCount, retryRequestManager, entries); completeOrRetry(backoffTime, retryRequestManager); } catch (RuntimeException e) { LOG.error( "Unexpected Exception occurred. Treating this issue as a temporary issue and retrying.", e); perfromFullRetry(backoffTime, e); } }</code><technical_language>MutateRowResponse -> MutateRowsResponse. above</technical_language>

Target:
synchronized void handleResult(List<MutateRowsResponse> result) { AtomicReference<Long> backoffTime = new AtomicReference<>(); if (this.currentRequestManager == null) { LOG.warn("Got duplicate responses for bulk mutation."); return; } if (result == null || result.isEmpty()) { performFullRetry( backoffTime, new IllegalStateException("No MutateRowResponses were found.")); return; } List<MutateRowsResponse.Entry> entries = new ArrayList<>(); for (MutateRowsResponse response : result) { entries.addAll(response.getEntriesList()); } if (entries.isEmpty()) { performFullRetry( backoffTime, new IllegalStateException("No MutateRowsResponses entries were found.")); return; } try { String tableName = currentRequestManager.request.getTableName(); RequestManager retryRequestManager = new RequestManager(tableName); int processedCount = handleResponses(backoffTime, entries, retryRequestManager); handleExtraFutures(backoffTime, processedCount, retryRequestManager, entries); completeOrRetry(backoffTime, retryRequestManager); } catch (RuntimeException e) { LOG.error( "Unexpected Exception occurred. Treating this issue as a temporary issue and retrying.", e); performFullRetry(backoffTime, e); } }