auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void validateCursors(final ZkSubscriptionClient subscriptionClient, final List<SubscriptionCursor> cursors, final String streamId) throws NakadiException { final ZkSubscriptionNode subscription = subscriptionClient.getZkSubscriptionNodeLocked(); if (!Arrays.stream(subscription.getSessions()).anyMatch(session -> session.getId().equals(streamId))) { throw new InvalidStreamIdException("Session with stream id " + streamId + " not found"); } final Map<Partition.PartitionKey, Partition> partitions = Arrays.stream(subscription.getPartitions()) .collect(Collectors.toMap(Partition::getKey, Function.identity())); final List<SubscriptionCursor> invalidCursors = cursors.stream().filter(cursor -> Try.cons(() -> eventTypeRepository.findByName(cursor.getEventType())).getO().map(eventType -> { final Partition.PartitionKey key = new Partition.PartitionKey(eventType.getTopic(), cursor.getPartition()); final Partition partition = partitions.get(key); return partition == null || !streamId.equals(partition.getSession()); }).orElseGet(() -> false)).collect(Collectors.toList()); if (!invalidCursors.isEmpty()) { <START> throw new InvalidStreamIdException("Cursors " + invalidCursors + " cannot be commited with stream id " <END> + streamId); } }</code><technical_language>commited->committed</technical_language>

Target:
private void validateCursors(final ZkSubscriptionClient subscriptionClient, final List<SubscriptionCursor> cursors, final String streamId) throws NakadiException { final ZkSubscriptionNode subscription = subscriptionClient.getZkSubscriptionNodeLocked(); if (!Arrays.stream(subscription.getSessions()).anyMatch(session -> session.getId().equals(streamId))) { throw new InvalidStreamIdException("Session with stream id " + streamId + " not found"); } final Map<Partition.PartitionKey, Partition> partitions = Arrays.stream(subscription.getPartitions()) .collect(Collectors.toMap(Partition::getKey, Function.identity())); final List<SubscriptionCursor> invalidCursors = cursors.stream().filter(cursor -> Try.cons(() -> eventTypeRepository.findByName(cursor.getEventType())).getO().map(eventType -> { final Partition.PartitionKey key = new Partition.PartitionKey(eventType.getTopic(), cursor.getPartition()); final Partition partition = partitions.get(key); return partition == null || !streamId.equals(partition.getSession()); }).orElseGet(() -> false)).collect(Collectors.toList()); if (!invalidCursors.isEmpty()) { throw new InvalidStreamIdException("Cursors " + invalidCursors + " cannot be committed with stream id " + streamId); } }
Source:
<code><START> protected void loopOfflinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws Exception { <END> loopOfflinePlayersConsumer(server, sender, multipleStringMatches, matchWildcards, searchTerm, user -> updatePlayer(server, sender, user, commandArgs)); }</code><technical_language>this; sure, this is a lot of exceptions in method signature, this encourages throwing want caring catch</technical_language>

Target:
protected void loopOfflinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { loopOfflinePlayersConsumer(server, sender, multipleStringMatches, matchWildcards, searchTerm, user -> updatePlayer(server, sender, user, commandArgs)); }
Source:
<code>public Response register(Action action) { BackendVnicProfileHelper.validateVnicMappings(action, this); ImportVmTemplateFromConfParameters params = new ImportVmTemplateFromConfParameters(); ExternalRegistrationConfigurationMapper.mapFromModel(action.getRegistrationConfiguration(), params); params.setContainerId(guid); params.setStorageDomainId(parent.getStorageDomainId()); if (action.isSetCluster()) { params.setClusterId(getClusterId(action)); } params.setImagesExistOnTargetStorageDomain(true); <START> params.setExternalVnicProfileMappings(ExternalVnicProfileMappingMapper.mapFromModel(action.getVnicProfileMappings())); <END> if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if (action.isSetVm() && action.getTemplate().isSetName()) { params.getVmTemplate().setName(action.getTemplate().getName()); } } if (action.isSetAllowPartialImport()) { params.setAllowPartialImport(action.isAllowPartialImport()); } return doAction(ActionType.ImportVmTemplateFromConfiguration, params, action); }</code><technical_language>This conditional: if (action.isSetVnicProfileMappings()) { ... } do this in general avoid side effects of running code request value</technical_language>

Target:
public Response register(Action action) { BackendVnicProfileHelper.validateVnicMappings(this, action); ImportVmTemplateFromConfParameters params = new ImportVmTemplateFromConfParameters(); ExternalRegistrationConfigurationMapper.mapFromModel(action.getRegistrationConfiguration(), params); params.setContainerId(guid); params.setStorageDomainId(parent.getStorageDomainId()); if (action.isSetCluster()) { params.setClusterId(getClusterId(action)); } params.setImagesExistOnTargetStorageDomain(true); params.setExternalVnicProfileMappings(ExternalVnicProfileMappingMapper.mapFromModel(action.getVnicProfileMappings())); if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if (action.isSetVm() && action.getTemplate().isSetName()) { params.getVmTemplate().setName(action.getTemplate().getName()); } } if (action.isSetAllowPartialImport()) { params.setAllowPartialImport(action.isAllowPartialImport()); } return doAction(ActionType.ImportVmTemplateFromConfiguration, params, action); }
Source:
<code>public static boolean boundedShutdown(List<Runnable> shutdownTasks, String message, long timeoutMs) { ExecutorService shutdownExecutorService = Executors.newCachedThreadPool(new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(0); <START> @Override <END> public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); thread.setName(message + "-" + counter.incrementAndGet()); return thread; } }); shutdownTasks.forEach(shutdownExecutorService::submit); shutdownExecutorService.shutdown(); try { shutdownExecutorService.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.error("Shutdown was interrupted for " + message, e); } if (shutdownExecutorService.isTerminated()) { LOG.info("Shutdown complete for {}", message); return true; } else { LOG.error("Shutdown function for remains unfinished after timeout({}ms) or interruption", message, timeoutMs); Util.logThreadDump(message); shutdownExecutorService.shutdownNow(); return false; } }</code><technical_language>cleaner gauva's ThreadFactoryBuilder instead of write own. remove AtomicInteger</technical_language>

Target:
public static boolean boundedShutdown(List<Runnable> shutdownTasks, String message, long timeoutMs) { ExecutorService shutdownExecutorService = Executors.newCachedThreadPool( new ThreadFactoryBuilder().setNameFormat(message + "-%d").setDaemon(true).build()); shutdownTasks.forEach(shutdownExecutorService::submit); shutdownExecutorService.shutdown(); try { shutdownExecutorService.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.error("Shutdown was interrupted for " + message, e); } if (shutdownExecutorService.isTerminated()) { LOG.info("Shutdown complete for {}", message); return true; } else { LOG.error("Shutdown function for remains unfinished after timeout({}ms) or interruption", message, timeoutMs); Util.logThreadDump(message); shutdownExecutorService.shutdownNow(); return false; } }
Source:
<code>public SystemStreamPartitionGrouper getSystemStreamPartitionGrouper(Config config) { if (!(new TaskConfigJava(config).getBroadcastSystemStreams().isEmpty())) { throw new ConfigException("The job configured with AllSspToSingleTaskGrouper cannot have broadcast streams."); } String processors = config.get(JobConfig.PROCESSOR_LIST()); <START> List<String> processorList = Arrays.asList(processors.split(",")); <END> return new AllSspToSingleTaskGrouper(processorList); }</code><technical_language>fail if list is empty</technical_language>

Target:
public SystemStreamPartitionGrouper getSystemStreamPartitionGrouper(Config config) { if (!(new TaskConfigJava(config).getBroadcastSystemStreams().isEmpty())) { throw new ConfigException("The job configured with AllSspToSingleTaskGrouper cannot have broadcast streams."); } String processors = config.get(JobConfig.PROCESSOR_LIST()); List<String> processorList = Arrays.asList(processors.split(",")); if (processorList.isEmpty()) { throw new SamzaException("processor list cannot be empty!"); } return new AllSspToSingleTaskGrouper(processorList); }
Source:
<code>public void setData(IComponent component){ if ( !(component instanceof ISequential ) ) return; this.rootComponent = component; mData.clear(); this.sections = new SectionRow[0]; if ( rootComponent != null ) { ISequential course = (ISequential)rootComponent; int sectionsNumber = course.getVerticals().size(); sections = new SectionRow[sectionsNumber]; int sectionPosition = 0, listPosition = 0; <START> for (char i=0; i<sectionsNumber; i++) { <END> IVertical vertical = course.getVerticals().get(i); SectionRow section = new SectionRow(SectionRow.SECTION, vertical ); section.sectionPosition = sectionPosition; section.listPosition = listPosition++; sections[sectionPosition] = section; mData.add(section); List<IUnit> units = vertical.getUnits(); for (int j=0;j<units.size();j++) { SectionRow item = new SectionRow(SectionRow.ITEM, units.get(j) ); item.sectionPosition = sectionPosition; item.listPosition = listPosition++; mData.add(item); } sectionPosition++; } } notifyDataSetChanged(); }</code><technical_language>another char loop</technical_language>

Target:
public void setData(IComponent component){ if ( !(component instanceof ISequential ) ) return; this.rootComponent = component; mData.clear(); this.sections = new SectionRow[0]; if ( rootComponent != null ) { ISequential course = (ISequential)rootComponent; int sectionsNumber = course.getVerticals().size(); sections = new SectionRow[sectionsNumber]; int sectionPosition = 0, listPosition = 0; for (int i=0; i<sectionsNumber; i++) { IVertical vertical = course.getVerticals().get(i); SectionRow section = new SectionRow(SectionRow.SECTION, vertical ); section.sectionPosition = sectionPosition; section.listPosition = listPosition++; sections[sectionPosition] = section; mData.add(section); List<IUnit> units = vertical.getUnits(); for (int j=0;j<units.size();j++) { SectionRow item = new SectionRow(SectionRow.ITEM, units.get(j) ); item.sectionPosition = sectionPosition; item.listPosition = listPosition++; mData.add(item); } sectionPosition++; } } notifyDataSetChanged(); }
Source:
<code>public boolean isClusterModified() { try { if (null == clusterVersion) { Cluster remoteCluster = getClusterFromBootstrapURL(clientConfig); <START> return currentCluster.equals(remoteCluster); <END> } else { Properties props = MetadataVersionStoreUtils.getProperties(metadataVersionSysStoreClient); long retrievedVersion = MetadataVersionStoreUtils.getVersion(props, SystemStoreConstants.CLUSTER_VERSION_KEY); return retrievedVersion > this.clusterVersion; } } catch(Exception e) { logger.info("Error retrieving cluster metadata version"); return true; } }</code><technical_language>this equals ? semantics cluster modified ? cache time if check equals avoid expensive call. time needs intialized cluster is initialized</technical_language>

Target:
public boolean isClusterModified() { try { if (null == clusterVersion) { long currentTime = System.currentTimeMillis(); Cluster remoteCluster = getClusterFromBootstrapURL(clientConfig); boolean remoteClusterConsistentWithLocalOne = currentCluster.equals(remoteCluster); if (remoteClusterConsistentWithLocalOne) { clusterVersion = currentTime; } return !remoteClusterConsistentWithLocalOne; } else { Properties props = MetadataVersionStoreUtils.getProperties(metadataVersionSysStoreClient); long retrievedVersion = MetadataVersionStoreUtils.getVersion(props, SystemStoreConstants.CLUSTER_VERSION_KEY); return retrievedVersion > this.clusterVersion; } } catch(Exception e) { logger.info("Error retrieving cluster metadata version"); return true; } }
Source:
<code>public List<HeliumPackage> getBundlePackagesToBundle() { <START> Map<String, List<HeliumPackageSearchResult>> allPackages = getAllPackageInfo(); <END> List<String> visOrder = heliumConf.getBundleDisplayOrder(); List<HeliumPackage> orderedBundlePackages = new LinkedList<>(); for (String name : visOrder) { List<HeliumPackageSearchResult> versions = allPackages.get(name); if (versions == null) { continue; } for (HeliumPackageSearchResult pkgInfo : versions) { if (canBundle(pkgInfo)) { orderedBundlePackages.add(pkgInfo.getPkg()); allPackages.remove(name); break; } } } for (List<HeliumPackageSearchResult> pkgInfos : allPackages.values()) { for (HeliumPackageSearchResult pkgInfo : pkgInfos) { if (canBundle(pkgInfo)) { orderedBundlePackages.add(pkgInfo.getPkg()); break; } } } return orderedBundlePackages; }</code><technical_language>fetch heliun.json web everytime. this intended</technical_language>

Target:
public List<HeliumPackage> getBundlePackagesToBundle() { List<String> visOrder = heliumConf.getBundleDisplayOrder(); Set<HeliumPackage> orderedBundlePackages = new HashSet<>(); List<HeliumPackage> output = new LinkedList<>(); for (String name : visOrder) { List<HeliumPackageSearchResult> versions = allPackages.get(name); if (versions == null) { continue; } for (HeliumPackageSearchResult pkgInfo : versions) { if (canBundle(pkgInfo)) { orderedBundlePackages.add(pkgInfo.getPkg()); break; } } } for (List<HeliumPackageSearchResult> pkgInfos : allPackages.values()) { for (HeliumPackageSearchResult pkgInfo : pkgInfos) { if (canBundle(pkgInfo)) { orderedBundlePackages.add(pkgInfo.getPkg()); break; } } } new LinkedList<>().addAll(orderedBundlePackages); return output; }
Source:
<code>public void accumulate(Node node, TransferResult<CFValue, CFStore> result, String... values) { Tree tree = node.getTree(); if (tree == null) { return; } AnnotatedTypeMirror oldType = typeFactory.getAnnotatedType(tree); <START> AnnotationMirror newAnno = getCombinedAnno(oldType, Arrays.asList(values)); <END> insertIntoStores(result, node, newAnno); if (tree.getKind() == Kind.METHOD_INVOCATION) { MethodInvocationNode methodInvocationNode = (MethodInvocationNode) node; Node receiver = methodInvocationNode.getTarget().getReceiver(); MethodInvocationTree invokedMethod = (MethodInvocationTree) tree; while (receiver != null && typeFactory.returnsThis(invokedMethod)) { insertIntoStores(result, receiver, newAnno); Tree receiverTree = receiver.getTree(); if (receiverTree == null || receiverTree.getKind() != Tree.Kind.METHOD_INVOCATION) { break; } invokedMethod = (MethodInvocationTree) receiver.getTree(); receiver = ((MethodInvocationNode) receiver).getTarget().getReceiver(); } } }</code><technical_language>is asList called? callee, getCombinedAnno, a copy anyway</technical_language>

Target:
public void accumulate(Node node, TransferResult<CFValue, CFStore> result, String... values) { List<String> valuesAsList = Arrays.asList(values); CFValue flowValue = result.getResultValue(); if (flowValue != null) { Set<AnnotationMirror> flowAnnos = flowValue.getAnnotations(); assert flowAnnos.size() <= 1; for (AnnotationMirror anno : flowAnnos) { List<String> oldFlowValues = ValueCheckerUtils.getValueOfAnnotationWithStringArgument(anno); if (oldFlowValues != null) { oldFlowValues.addAll(valuesAsList); valuesAsList = oldFlowValues; } } } AnnotationMirror newAnno = typeFactory.createAccumulatorAnnotation(valuesAsList); insertIntoStores(result, node, newAnno); Tree tree = node.getTree(); if (tree != null && tree.getKind() == Kind.METHOD_INVOCATION) { Node receiver = ((MethodInvocationNode) node).getTarget().getReceiver(); if (receiver != null && typeFactory.returnsThis((MethodInvocationTree) tree)) { accumulate(receiver, result, values); } } }
Source:
<code>private boolean check() throws IOException { final FileFilter fileFilter = new FileFilter(this.getIncludes(), this.getExcludes()); final BundleCreator creator = new BundleCreator(this.getProject(), fileFilter); final IBundleCoverage bundle = creator.createBundle(executionDataStore); boolean passed = true; CheckConfiguration overall = check.getOverall(); CheckConfiguration classLevel = check.getEachClass(); if (classLevel!=null){ Collection<IPackageCoverage> packages = bundle.getPackages(); for (IPackageCoverage aPackage : packages) { Collection<IClassCoverage> classes = aPackage.getClasses(); for (IClassCoverage aClass : classes) { <START> for (final CounterEntity entity : CounterEntity.values()) { <END> passed = this.checkCounter("Class "+aClass.getName(),entity, aClass.getCounter(entity), classLevel.getRatio(entity)) && passed; } } } } if (overall!=null){ for (final CounterEntity entity : CounterEntity.values()) { passed = this.checkCounter("Project "+this.getProject().getArtifactId(),entity, bundle.getCounter(entity), overall.getRatio(entity)) && passed; } } return passed; }</code><technical_language>If find nesting levels generally a good practice refactor code smaller methods</technical_language>

Target:
private boolean check() throws IOException { final FileFilter fileFilter = new FileFilter(this.getIncludes(), this.getExcludes()); final BundleCreator creator = new BundleCreator(this.getProject(), fileFilter); final IBundleCoverage bundle = creator.createBundle(executionDataStore); int totalFailureCount = checkBundleFailures(check, bundle); logIfFailed("Bundle Coverage Checks", totalFailureCount); List<Rule> rules = check.getRules(); boolean rulesAreValid= checkRuleDefinitionIsValid(rules); if (rulesAreValid) { for (Rule rule : rules) { totalFailureCount += checkRuleFailures(rule, bundle); } return totalFailureCount==0; } return false; }
Source:
<code>public BulkWrites getBulkWrites() throws Exception { Set<Entry<byte[], PartitionBuffer>> entries = this.buffers.entrySet(); Collection<BulkWrite> bws = new ArrayList<>(entries.size()); for (Entry<byte[], PartitionBuffer> regionEntry : this.buffers.entrySet()) { PartitionBuffer value = regionEntry.getValue(); if (value.isEmpty()) continue; BulkWrite bulkWrite = value.getBulkWrite(); bws.add(bulkWrite); Collection<KVPair> kvPairs = bulkWrite.getMutations(); for (KVPair kvPair:kvPairs) { <START> value.remove(kvPair); END> } } if(bws.isEmpty()) return null; else return new BulkWrites(bws, this.txn, this.buffers.lastKey(),token); }</code><technical_language>Is called a lot? a o(n*m) instead of o(n) value.buffer is ArrayList</technical_language>

Target:
public BulkWrites getBulkWrites() throws Exception { Set<Entry<byte[], PartitionBuffer>> entries = this.buffers.entrySet(); Collection<BulkWrite> bws = new ArrayList<>(entries.size()); for (Entry<byte[], PartitionBuffer> regionEntry : this.buffers.entrySet()) { PartitionBuffer value = regionEntry.getValue(); if (value.isEmpty()) continue; bws.add(value.getBulkWrite()); value.clear(); } if(bws.isEmpty()) return null; else return new BulkWrites(bws, this.txn, this.buffers.lastKey(),token); }
Source:
<code>protected GoFunctionOrMethodDeclaration findTestFunctionInContext(@NotNull PsiElement contextElement) { <START> GoFunctionOrMethodDeclaration function = PsiTreeUtil.getNonStrictParentOfType(contextElement, GoFunctionOrMethodDeclaration.class); <END> return function != null && GoTestFinder.isBenchmarkFunction(function) ? function : null; }</code><technical_language>I GoMethodDeclaration is appliable for gobench, type T int function (T) B<caret>enchmarkName() { } produce gobench run configuration, right? If replace GoFunctionDeclaration function = PsiTreeUtil.getNonStrictParentOfType(contextElement, GoFunctionDeclaration.class);</technical_language>

Target:
protected GoFunctionDeclaration findTestFunctionInContext(@NotNull PsiElement contextElement) { GoFunctionDeclaration function = PsiTreeUtil.getNonStrictParentOfType(contextElement, GoFunctionDeclaration.class); return function != null && GoTestFinder.isBenchmarkFunction(function) ? function : null; }
Source:
<code>private Vector<Entry> getEntriesForCommand(String commandId, OrderedHashtable<String, String> currentSessionData, boolean includeNested) { Vector<Entry> entries = new Vector<>(); if (commandId == null) { return entries; } for (Suite s : platform.getInstalledSuites()) { List<Menu> menusWithId = s.getMenusWithId(commandId); if (menusWithId != null) { List<Menu> menusToExamine = new ArrayList<>(menusWithId); while (!menusToExamine.isEmpty()) { <START> Menu menu = menusToExamine.remove(0); <END> entries.addAll(getStillValidEntriesFromMenu(menu, currentSessionData)); if (includeNested) { menusToExamine.addAll(s.getMenusWithRoot(menu.getId())); } } } if (s.getEntries().containsKey(commandId)) { entries.addElement(s.getEntries().get(commandId)); } } return entries; }</code><technical_language>Super minor point if this a Stack pop(), a queue poll() a bit more clear datatype</technical_language>

Target:
private Vector<Entry> getEntriesForCommand(String commandId, OrderedHashtable<String, String> currentSessionData, boolean includeNested) { Vector<Entry> entries = new Vector<>(); if (commandId == null) { return entries; } for (Suite s : platform.getInstalledSuites()) { List<Menu> menusWithId = s.getMenusWithId(commandId); if (menusWithId != null) { Queue<Menu> menusToExamine = new LinkedList<>(menusWithId); while (!menusToExamine.isEmpty()) { Menu menu = menusToExamine.poll(); entries.addAll(getStillValidEntriesFromMenu(menu, currentSessionData)); if (includeNested) { menusToExamine.addAll(s.getMenusWithRoot(menu.getId())); } } } if (s.getEntries().containsKey(commandId)) { entries.addElement(s.getEntries().get(commandId)); } } return entries; }
Source:
<code>public static byte[] serializeAuthenticatorUserMap( ObjectMapper objectMapper, Map<String, BasicAuthenticatorUser> userMap ) { try { return objectMapper.writeValueAsBytes(userMap); } catch (IOException ioe) { <START> throw new ISE("WTF? Couldn't serialize userMap!"); <END> } }</code><technical_language>Please add ioe exception</technical_language>

Target:
public static byte[] serializeAuthenticatorUserMap( ObjectMapper objectMapper, Map<String, BasicAuthenticatorUser> userMap ) { try { return objectMapper.writeValueAsBytes(userMap); } catch (IOException ioe) { throw new ISE(ioe, "WTF? Couldn't serialize userMap!"); } }
Source:
<code>protected Class<?> resolveName(String name) { String result; if (name.contains(".")) { result = name; } else if (name.equals("View") || name.equals("ViewGroup")) { result = "android.view." + name; } else { result = "android.widget." + name; } if (mappings.containsKey(result)) { logger.debug(getClass().getSimpleName() + " mapping " + name + " to " + mappings.get(result)); return mappings.get(result); } try { <START> logger.debug(getClass().getSimpleName() + " resolving " + name + " with " + result); <END> return Class.forName(result); } catch (ClassNotFoundException e) { if (mDebugMode) { throw new RuntimeException(e); } return null; } }</code><technical_language>getClass().getSimpleName() is expensive. extract a a constant</technical_language>

Target:
protected Class<?> resolveName(String name) { String result; if (name.contains(".")) { result = name; } else if (name.equals("View") || name.equals("ViewGroup")) { result = "android.view." + name; } else { result = "android.widget." + name; } if (mappings.containsKey(result)) { logger.debug(mLoggingTag + " mapping " + name + " to " + mappings.get(result)); return mappings.get(result); } try { logger.debug(mLoggingTag + " resolving " + name + " with " + result); return Class.forName(result); } catch (ClassNotFoundException e) { if (mDebugMode) { throw new RuntimeException(e); } return null; } }
Source:
<code>public Handler accept(final InetSocketAddress remoteAddress, final InetSocketAddress localAddress) { return buffer -> { final Header header = new Header(slice(buffer, Header.SIZE)); final Packet packet = header.parsePayload(slice(buffer, header.length - Header.SIZE)); <START> System.out.println(packet); <END> final BasicOutputBuffer output = new BasicOutputBuffer(); try (final BsonBinaryWriter writer = new BsonBinaryWriter(output)) { writer.writeStartDocument(); writer.writeInt32("@version", header.version); writer.writeString("@type", header.type.name()); packet.visit(new Serializer(writer)); writer.writeEndDocument(); } this.recordsDispatched.mark(); final TelemetryMessage message = new TelemetryMessage(remoteAddress, output.getByteBuffers().get(0).asNIO()); return dispatcher.send(message); }; }</code><technical_language>logger instead</technical_language>

Target:
public Handler accept(final InetSocketAddress remoteAddress, final InetSocketAddress localAddress) { return buffer -> { final Header header = new Header(slice(buffer, Header.SIZE)); final Packet packet = header.parsePayload(slice(buffer, header.length - Header.SIZE)); LOG.trace("Got packet: {}", packet); final BasicOutputBuffer output = new BasicOutputBuffer(); try (final BsonBinaryWriter writer = new BsonBinaryWriter(output)) { writer.writeStartDocument(); writer.writeInt32("@version", header.version); writer.writeString("@type", header.type.name()); packet.accept(new Serializer(writer)); writer.writeEndDocument(); } this.recordsDispatched.mark(); final TelemetryMessage message = new TelemetryMessage(remoteAddress, output.getByteBuffers().get(0).asNIO()); return dispatcher.send(message); }; }
Source:
<code>public void loginAsync_errorHandlerThrows() { <START> RealmLog.setLevel(LogLevel.INFO); <END> SyncCredentials credentials = SyncCredentials.usernamePassword("IWantToHackYou", "GeneralPassword", false); SyncUser.loginAsync(credentials, Constants.AUTH_URL, new SyncUser.Callback() { @Override public void onSuccess(SyncUser user) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.INVALID_CREDENTIALS, error.getErrorCode()); throw new IllegalArgumentException("BOOM"); } }); looperThread.postRunnableDelayed(new Runnable() { @Override public void run() { looperThread.testComplete(); } }, 1000); }</code><technical_language>log level needs reset default this test done</technical_language>

Target:
public void loginAsync_errorHandlerThrows() { final int defaultLevel = RealmLog.getLevel(); RealmLog.setLevel(LogLevel.INFO); SyncCredentials credentials = SyncCredentials.usernamePassword("IWantToHackYou", "GeneralPassword", false); SyncUser.loginAsync(credentials, Constants.AUTH_URL, new SyncUser.Callback() { @Override public void onSuccess(SyncUser user) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.INVALID_CREDENTIALS, error.getErrorCode()); throw new IllegalArgumentException("BOOM"); } }); looperThread.postRunnableDelayed(new Runnable() { @Override public void run() { RealmLog.setLevel(defaultLevel); looperThread.testComplete(); } }, 1000); }
Source:
<code>static <T> Option<Seq<T>> sequence(Iterable<? extends Option<? extends T>> values) { Objects.requireNonNull(values, "values is null"); Stream<T> stream = Stream.empty(); for (Option<? extends T> value : values) { if (value.isEmpty()) { return Option.none(); } stream = stream.append(value.get()); } <START> return Option.some(stream); <END> }</code><technical_language>is this Option exactly, simply return empty Seq instead? @danieldietrich</technical_language>

Target:
static <T> Option<Seq<T>> sequence(Iterable<? extends Option<? extends T>> values) { Objects.requireNonNull(values, "values is null"); Vector<T> vector = Vector.empty(); for (Option<? extends T> value : values) { if (value.isEmpty()) { return Option.none(); } vector = vector.append(value.get()); } return Option.some(vector); }
Source:
<code><START> public static void changeOutcomeSettings(OutcomeSettings settings){ <END> outcomeSettings = settings; outcomeEventsController.setOutcomeSettings(settings); }</code><technical_language>this is anywhere. if do need public</technical_language>

Target:
static void changeOutcomeSettings(OutcomeSettings settings) { outcomeSettings = settings; outcomeEventsController.setOutcomeSettings(settings); }
Source:
<code>public void testFindProcessInstanceWithParentIdAndProcessNameEqualsToFilter() throws Exception { Map<String, Object> parameters = new HashMap<>(); Long processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_EVALUATION, parameters); Assertions.assertThat(processInstanceId).isNotNull(); HashMap<ProcessInstanceField, Comparable<?>> compareList = new HashMap<>(); compareList.put(ProcessInstanceField.PARENTPROCESSINSTANCEID, -1); compareList.put(ProcessInstanceField.PROCESSNAME, PROCESS_NAME_EVALUATION); <START> testFindProcessInstanceWithQueryFilter(createQueryFilterEqualsTo(ProcessInstanceField.PARENTPROCESSINSTANCEID, -1), processInstanceId); <END> }</code><technical_language>missed add compareList parameter here</technical_language>

Target:
public void testFindProcessInstanceWithParentIdAndProcessNameEqualsToFilter() throws Exception { Map<String, Object> parameters = new HashMap<>(); Long processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_EVALUATION, parameters); Assertions.assertThat(processInstanceId).isNotNull(); HashMap<ProcessInstanceField, Comparable<?>> compareList = new HashMap<>(); compareList.put(ProcessInstanceField.PARENTPROCESSINSTANCEID, -1); compareList.put(ProcessInstanceField.PROCESSNAME, PROCESS_NAME_EVALUATION); testFindProcessInstanceWithQueryFilter(createQueryFilterAndEqualsTo(compareList), processInstanceId); }
Source:
<code>public void stripPrefixIfPresent() throws Exception { Assert.assertEquals("", mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME)); Assert.assertEquals("", mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME + "/")); Assert.assertEquals("test", mS3UnderFileSystem.stripPrefixIfPresent("test")); Assert.assertEquals("test", <START> mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME + "/test")); <END> }</code><technical_language>this test case? "s3a://" + BUCKET_NAME + "/test/"</technical_language>

Target:
public void stripPrefixIfPresent() throws Exception { Assert.assertEquals("", mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME)); Assert.assertEquals("", mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME + "/")); Assert.assertEquals("test/", mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME + "/test/")); Assert.assertEquals("test", mS3UnderFileSystem.stripPrefixIfPresent("test")); Assert.assertEquals("test/", mS3UnderFileSystem.stripPrefixIfPresent("test/")); Assert.assertEquals("test/", mS3UnderFileSystem.stripPrefixIfPresent("/test/")); Assert.assertEquals("test", mS3UnderFileSystem.stripPrefixIfPresent("/test")); Assert.assertEquals("", mS3UnderFileSystem.stripPrefixIfPresent("")); Assert.assertEquals("", mS3UnderFileSystem.stripPrefixIfPresent("/")); }
Source:
<code>public void testGetAllWithCompatibility() { RemoteCache<String, String> cache = client(0).getCache(); HashMap<String, String> cachedValues = new HashMap<>(); for(int i=0; i<100; i++){ String key = String.format("key-%d", i); String value = String.format("value-%d", i); cache.put(key, value); cachedValues.put(key, value); } <START> System.out.println("Key's added"); <END> Map<String, String> values = cache.getAll(cachedValues.keySet()); System.out.println("done"); assertEquals(cachedValues.size(), values.size()); for(String key : values.keySet()){ assertEquals(cachedValues.get(key), values.get(key)); } }</code><technical_language>Logging</technical_language>

Target:
public void testGetAllWithCompatibility() { RemoteCache<String, String> cache = client(0).getCache(); HashMap<String, String> cachedValues = new HashMap<>(); for(int i=0; i<100; i++){ String key = String.format("key-%d", i); String value = String.format("value-%d", i); cache.put(key, value); cachedValues.put(key, value); } Map<String, String> values = cache.getAll(cachedValues.keySet()); assertEquals(cachedValues.size(), values.size()); for(String key : values.keySet()){ assertEquals(cachedValues.get(key), values.get(key)); } }
Source:
<code>@Override public void remove() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (isEmpty()) throw new NoSuchElementException(); if (nextElementIndex != 1) { throw new UnsupportedOperationException("Removal is only permitted from the head."); } try { QueueFile.this.remove(); } catch (IOException e) { <START> throw new RuntimeException("todo: throw a proper error", e); <END> } expectedModCount = modCount; nextElementIndex--; }</code><technical_language>Java 8 UncheckedIOException perfect FileException is talk again... @swankjesse thoughts</technical_language>

Target:
@Override public void remove() { checkForComodification(); if (isEmpty()) throw new NoSuchElementException(); if (nextElementIndex != 1) { throw new UnsupportedOperationException("Removal is only permitted from the head."); } try { QueueFile.this.remove(); } catch (IOException e) { throw new RuntimeException("todo: throw a proper error", e); } expectedModCount = modCount; nextElementIndex--; }
Source:
<code>public void run() { if (this.state.compareAndSet(NEW, RUNNING)) { try { renameThread("RUNNING"); this.threadRef.set(Thread.currentThread()); this.jedis.sadd(key(WORKERS), this.name); this.jedis.set(key(WORKER, this.name, STARTED), new SimpleDateFormat(DATE_FORMAT).format(new Date())); this.listenerDelegate.fireEvent(WORKER_START, this, null, null, null, null, null); this.popScriptHash.set(this.jedis.scriptLoad(ScriptUtils.readScript(POP_LUA))); this.lpoplpushScriptHash.set(this.jedis.scriptLoad(ScriptUtils.readScript(LPOPLPUSH_LUA))); <START> this.multiPriorityQueuesScriptHash.set(this.jedis.scriptLoad(ScriptUtils.readScript(LPOPLPUSH_LUA))); <END> poll(); } catch (Exception ex) { LOG.error("Uncaught exception in worker run-loop!", ex); this.listenerDelegate.fireEvent(WORKER_ERROR, this, null, null, null, null, ex); } finally { renameThread("STOPPING"); this.listenerDelegate.fireEvent(WORKER_STOP, this, null, null, null, null, null); this.jedis.srem(key(WORKERS), this.name); this.jedis.del(key(WORKER, this.name), key(WORKER, this.name, STARTED), key(STAT, FAILED, this.name), key(STAT, PROCESSED, this.name)); this.jedis.quit(); this.threadRef.set(null); } } else if (RUNNING.equals(this.state.get())) { throw new IllegalStateException("This WorkerImpl is already running"); } else { throw new IllegalStateException("This WorkerImpl is shutdown"); } }</code><technical_language>this logic. script hashes for loading script, LPOPLPUSH_LUA? Is this supposed load workerScripts/fromMultiplePriorityQueues.lua</technical_language>

Target:
public void run() { if (this.state.compareAndSet(NEW, RUNNING)) { try { renameThread("RUNNING"); this.threadRef.set(Thread.currentThread()); this.jedis.sadd(key(WORKERS), this.name); this.jedis.set(key(WORKER, this.name, STARTED), new SimpleDateFormat(DATE_FORMAT).format(new Date())); this.listenerDelegate.fireEvent(WORKER_START, this, null, null, null, null, null); this.popScriptHash.set(this.jedis.scriptLoad(ScriptUtils.readScript(POP_LUA))); this.lpoplpushScriptHash.set(this.jedis.scriptLoad(ScriptUtils.readScript(LPOPLPUSH_LUA))); this.multiPriorityQueuesScriptHash.set(this.jedis.scriptLoad(ScriptUtils.readScript(POP_FROM_MULTIPLE_PRIO_QUEUES))); poll(); } catch (Exception ex) { LOG.error("Uncaught exception in worker run-loop!", ex); this.listenerDelegate.fireEvent(WORKER_ERROR, this, null, null, null, null, ex); } finally { renameThread("STOPPING"); this.listenerDelegate.fireEvent(WORKER_STOP, this, null, null, null, null, null); this.jedis.srem(key(WORKERS), this.name); this.jedis.del(key(WORKER, this.name), key(WORKER, this.name, STARTED), key(STAT, FAILED, this.name), key(STAT, PROCESSED, this.name)); this.jedis.quit(); this.threadRef.set(null); } } else if (RUNNING.equals(this.state.get())) { throw new IllegalStateException("This WorkerImpl is already running"); } else { throw new IllegalStateException("This WorkerImpl is shutdown"); } }
Source:
<code>void startBundles(List<Bundle> tobestarted) throws Exception { refresh(); trace("bundles administered %s", installedBundles.keySet()); if (security) policy.setDefaultPermissions(null); if (padmin != null && padmin.resolveBundles(null) == false) { List<String> failed = new ArrayList<>(); for (Bundle b : installedBundles.values()) { try { if (b.getState() == Bundle.INSTALLED) { b.start(); } } catch (Exception e) { failed.add(b.getSymbolicName() + "-" + b.getVersion() + " " + e + "\n"); } } error("could not resolve the bundles: %s", failed); } trace("Will start bundles: %s", tobestarted); List<Bundle> all = new ArrayList<>(tobestarted); all.addAll(wantsToBeStarted); int startOptions = Bundle.START_ACTIVATION_POLICY; if (parms.eagerActivation) { <START> startOptions = 0; <END> } for (Bundle b : tobestarted) { try { trace("starting %s", b.getSymbolicName()); if (!isFragment(b)) b.start(startOptions); trace("started %s", b.getSymbolicName()); } catch (BundleException e) { wantsToBeStarted.add(b); error("Failed to start bundle %s-%s, exception %s", b.getSymbolicName(), b.getVersion(), e); } } }</code><technical_language>I guess instead of setting 0, more future-proof AND-off bit</technical_language>

Target:
void startBundles(List<Bundle> tobestarted) throws Exception { refresh(); trace("bundles administered %s", installedBundles.keySet()); if (security) policy.setDefaultPermissions(null); if (padmin != null && padmin.resolveBundles(null) == false) { List<String> failed = new ArrayList<>(); for (Bundle b : installedBundles.values()) { try { if (b.getState() == Bundle.INSTALLED) { b.start(); } } catch (Exception e) { failed.add(b.getSymbolicName() + "-" + b.getVersion() + " " + e + "\n"); } } error("could not resolve the bundles: %s", failed); } trace("Will start bundles: %s", tobestarted); List<Bundle> all = new ArrayList<>(tobestarted); all.addAll(wantsToBeStarted); int startOptions = Bundle.START_ACTIVATION_POLICY; if (parms.activationEager) { startOptions &= ~Bundle.START_ACTIVATION_POLICY; } for (Bundle b : tobestarted) { try { trace("starting %s", b.getSymbolicName()); if (!isFragment(b)) b.start(startOptions); trace("started %s", b.getSymbolicName()); } catch (BundleException e) { wantsToBeStarted.add(b); error("Failed to start bundle %s-%s, exception %s", b.getSymbolicName(), b.getVersion(), e); } } }
Source:
<code>private JClassType getPreBootstrapper() throws UnableToCompleteException { <START> String typeName = lookupTypeNameByProperty("gwtp.prebootstrapper"); <END> if (typeName == null) { return null; } return findAndVerifyType(typeName, PreBootstrapper.class); }</code><technical_language>Static string constants</technical_language>

Target:
private JClassType getPreBootstrapper() throws UnableToCompleteException { String typeName = lookupTypeNameByProperty(PROPERTY_NAME_PREBOOTSTRAPPER); if (typeName == null) { return null; } return findAndVerifyType(typeName, PreBootstrapper.class); }
Source:
<code>public String toString() { <START> return "RuleImpl '" + getRule().uid + "' has been removed."; <END> }</code><technical_language>Hm, "RuleImpl" instead of "Rule"</technical_language>

Target:
public String toString() { return "Rule '" + getRule().uid + "' has been removed."; }
Source:
<code>private Node createGroupColorRegion(BibEntryTableViewModel entry, List<AbstractGroup> matchedGroups) { List<Color> groupColors = matchedGroups.stream() .flatMap(group -> OptionalUtil.toStream(group.getColor())) .collect(Collectors.toList()); if (!groupColors.isEmpty()) { HBox container = new HBox(); container.setSpacing(2); container.setMinWidth(10); <START> container.setAlignment(Pos.CENTER); <END> for (Color groupColor : groupColors) { Rectangle groupRectangle = new Rectangle(); groupRectangle.setWidth(3); groupRectangle.setHeight(18); groupRectangle.setFill(groupColor); groupRectangle.setStroke(Color.DARKGRAY); groupRectangle.setStrokeWidth(1); container.getChildren().add(groupRectangle); } String matchedGroupsString = matchedGroups.stream() .map(AbstractGroup::getName) .collect(Collectors.joining(", ")); Tooltip tooltip = new Tooltip(Localization.lang("Entry is contained in the following groups:") + "\n" + matchedGroupsString); Tooltip.install(container, tooltip); return container; } return new Pane(); }</code><technical_language>Is set left align? imho</technical_language>

Target:
private Node createGroupColorRegion(BibEntryTableViewModel entry, List<AbstractGroup> matchedGroups) { List<Color> groupColors = matchedGroups.stream() .flatMap(group -> OptionalUtil.toStream(group.getColor())) .collect(Collectors.toList()); if (!groupColors.isEmpty()) { HBox container = new HBox(); container.setSpacing(2); container.setMinWidth(10); container.setAlignment(Pos.CENTER_LEFT); container.setPadding(new Insets(0, 2, 0, 2)); for (Color groupColor : groupColors) { Rectangle groupRectangle = new Rectangle(); groupRectangle.setWidth(3); groupRectangle.setHeight(18); groupRectangle.setFill(groupColor); groupRectangle.setStroke(Color.DARKGRAY); groupRectangle.setStrokeWidth(1); container.getChildren().add(groupRectangle); } String matchedGroupsString = matchedGroups.stream() .map(AbstractGroup::getName) .collect(Collectors.joining(", ")); Tooltip tooltip = new Tooltip(Localization.lang("Entry is contained in the following groups:") + "\n" + matchedGroupsString); Tooltip.install(container, tooltip); return container; } return new Pane(); }
Source:
<code>protected String generateUserAgent() { String prodName = null; String version = null; IPropertiesProvider productInfo = PropertiesHelper.getPropertiesProvider(); if(productInfo instanceof VersionPropertiesProvider ) { VersionPropertiesProvider prov = (VersionPropertiesProvider)productInfo; prodName = prov.getContext(); version = prov.getCurrentVersion(); } else { prodName = "unknown"; version = "unknown"; } String os = System.getProperty("os.name"); String osVers = System.getProperty("os.version"); String osArch = System.getProperty("os.arch"); <START> String javaVersion = "Java " + System.getProperty("java.version"); <END> String inParens = String.join(";", new String[] {os, osVers, osArch, javaVersion}); String ret = prodName+"/" + version + " (" + inParens + ")"; return ret; }</code><technical_language>I choose Eclipse JBoss Tools for default product version</technical_language>

Target:
protected String generateUserAgent() { String prodName = null; String version = null; IPropertiesProvider productInfo = PropertiesHelper.getPropertiesProvider(); if(productInfo instanceof VersionPropertiesProvider ) { VersionPropertiesProvider prov = (VersionPropertiesProvider)productInfo; prodName = prov.getContext(); version = prov.getCurrentVersion(); } else { prodName = "jbosstools"; version = "unknown"; } String os = System.getProperty("os.name"); String osVers = System.getProperty("os.version"); String osArch = System.getProperty("os.arch"); String javaVersion = "Java " + System.getProperty("java.version"); String inParens = String.join(";", new String[] {os, osVers, osArch, javaVersion}); String ret = prodName+"/" + version + " (" + inParens + ")"; return ret; }
Source:
<code>public TextArgs add(Object... args) { if (positionedArgsBuilder == null) { throw new IllegalArgumentException("Positioned arguments were already accessed, to add" + <START> "more arguments use TextArgs.copy()"); <END> } positionedArgsBuilder.add(args); return this; }</code><technical_language>Another space add</technical_language>

Target:
public TextArgs add(Object... args) { return new TextArgs( ImmutableList.builder().addAll(positionedArgs).add(args).build(), namedArgs ); }
Source:
<code>private Method checkProxy(Method methodArg, Object bean) { Method method = methodArg; if (AopUtils.isJdkDynamicProxy(bean)) { try { method = bean.getClass().getMethod(method.getName(), method.getParameterTypes()); Class<?>[] proxiedInterfaces = ((Advised) bean).getProxiedInterfaces(); for (Class<?> iface : proxiedInterfaces) { try { method = iface.getMethod(method.getName(), method.getParameterTypes()); break; } catch (NoSuchMethodException noMethod) { } } } catch (SecurityException ex) { ReflectionUtils.handleReflectionException(ex); } catch (NoSuchMethodException ex) { throw new IllegalStateException(String.format( "@StreamListener method '%s' found on bean target class '%s', " + "but not found in any interface(s) for bean JDK proxy. Either " + "pull the method up to an interface or switch to subclass (CGLIB) " <START> + "proxies by setting proxy-target-class/proxyTargetClass " + "attribute to 'true'", <END> method.getName(), method.getDeclaringClass().getSimpleName()), ex); } } return method; }</code><technical_language>unnecessary concatenation line some formatting changes</technical_language>

Target:
private Method checkProxy(Method methodArg, Object bean) { Method method = methodArg; if (AopUtils.isJdkDynamicProxy(bean)) { try { method = bean.getClass().getMethod(method.getName(), method.getParameterTypes()); Class<?>[] proxiedInterfaces = ((Advised) bean).getProxiedInterfaces(); for (Class<?> iface : proxiedInterfaces) { try { method = iface.getMethod(method.getName(), method.getParameterTypes()); break; } catch (NoSuchMethodException noMethod) { } } } catch (SecurityException ex) { ReflectionUtils.handleReflectionException(ex); } catch (NoSuchMethodException ex) { throw new IllegalStateException(String.format( "@StreamListener method '%s' found on bean target class '%s', " + "but not found in any interface(s) for bean JDK proxy. Either " + "pull the method up to an interface or switch to subclass (CGLIB) " + "proxies by setting proxy-target-class/proxyTargetClass attribute to 'true'", method.getName(), method.getDeclaringClass().getSimpleName()), ex); } } return method; }