auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void checkIndexValue(MockId id) throws StoreException { IndexValue value = state.getExpectedValue(id, false); IndexValue valueFromStore = state.index.findKey(id); assertEquals("Unexpected size in IndexValue", value.getSize(), valueFromStore.getSize()); assertEquals("Unexpected expiresAtMs in IndexValue", value.getExpiresAtMs(), valueFromStore.getExpiresAtMs()); <START> assertEquals("Unexpected op time in IndexValue " + value + ", actual " + valueFromStore, <END> value.getOperationTimeInMs(), valueFromStore.getOperationTimeInMs()); assertEquals("Unexpected service ID in IndexValue", value.getServiceId(), valueFromStore.getServiceId()); assertEquals("Unexpected container ID in IndexValue", value.getContainerId(), valueFromStore.getContainerId()); assertEquals("Unexpected flags in IndexValue", value.getFlags(), valueFromStore.getFlags()); }</code><technical_language>message need change</technical_language>

Target:
private void checkIndexValue(MockId id) throws StoreException { IndexValue value = state.getExpectedValue(id, false); IndexValue valueFromStore = state.index.findKey(id); assertEquals("Unexpected size in IndexValue", value.getSize(), valueFromStore.getSize()); assertEquals("Unexpected expiresAtMs in IndexValue", value.getExpiresAtMs(), valueFromStore.getExpiresAtMs()); assertEquals("Unexpected op time in IndexValue ", value.getOperationTimeInMs(), valueFromStore.getOperationTimeInMs()); assertEquals("Unexpected account ID in IndexValue", value.getAccountId(), valueFromStore.getAccountId()); assertEquals("Unexpected container ID in IndexValue", value.getContainerId(), valueFromStore.getContainerId()); assertEquals("Unexpected flags in IndexValue", value.getFlags(), valueFromStore.getFlags()); }
Source:
<code>public void testCheckNotClosed() { AbstractServiceConnectionManager<Object> connectionManager = new TestServiceConnectionManager(); connectionManager.checkNotClosed(); connectionManager.connect(new Object()); connectionManager.checkNotClosed(); connectionManager.disconnect(); connectionManager.checkNotClosed(); connectionManager.close(); try { <START> connectionManager.checkNotClosed(); <END> } catch (IllegalStateException expected) { } }</code><technical_language>fail is missing here</technical_language>

Target:
public void testCheckNotClosed() { AbstractServiceConnectionManager<Object> connectionManager = new TestServiceConnectionManager(); connectionManager.checkNotClosed(); connectionManager.connect(new Object()); connectionManager.checkNotClosed(); connectionManager.disconnect(); connectionManager.checkNotClosed(); connectionManager.close(); try { connectionManager.checkNotClosed(); fail("checkNotClosed() did not fail for a closed connection manager"); } catch (IllegalStateException expected) { } }
Source:
<code>public TimelockServiceStatus getTimelockServiceStatus() { Map<String, Meter> meters = AtlasDbMetrics.getMetricRegistry().getMeters(); if (!meters.containsKey("timelock.success") && !meters.containsKey("timelock.fail")) { log.error("Timelock client metrics is not properly set"); throw new IllegalStateException(); <START> } <END> boolean isHealthy = meters.get("timelock.success").getFiveMinuteRate() >= meters.get("timelock.fail").getFiveMinuteRate(); if (isHealthy) { return TimelockServiceStatus.HEALTHY; } else { return TimelockServiceStatus.UNHEALTHY; } }</code><technical_language>usage, condition want for this block is (you want fail missing) - written if 1 is present get NPE line 133 other meter. Also, good a message exception thrown</technical_language>

Target:
public TimelockServiceStatus getTimelockServiceStatus() { return timelockHealthCheck.getStatus(); }
Source:
<code>public synchronized boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } HelixAdmin helixAdmin = manager.getClusterManagmentTool(); InstanceConfig instanceConfig = helixAdmin.getInstanceConfig(clusterName, instanceName); if (instanceConfig == null) { throw new IllegalStateException( "No instance config found for cluster: \"" + clusterName + "\", instance: \"" + instanceName + "\""); } List<String> sealedReplicas = ClusterMapUtils.getSealedReplicas(instanceConfig); if (sealedReplicas == null) { sealedReplicas = new ArrayList<>(); } String partitionId = replicaId.getPartitionId().toPathString(); if (!isSealed && sealedReplicas.contains(partitionId)) { sealedReplicas.remove(partitionId); } else if (isSealed && !sealedReplicas.contains(partitionId)) { sealedReplicas.add(partitionId); } <START> else { <END> return true; } instanceConfig.getRecord().setListField(ClusterMapUtils.SEALED_STR, sealedReplicas); return helixAdmin.setInstanceConfig(clusterName, instanceName, instanceConfig); }</code><technical_language>formatting</technical_language>

Target:
public synchronized boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } List<String> sealedReplicas = getSealedReplicas(); if (sealedReplicas == null) { sealedReplicas = new ArrayList<>(); } String partitionId = replicaId.getPartitionId().toPathString(); boolean success = true; if (!isSealed && sealedReplicas.contains(partitionId)) { sealedReplicas.remove(partitionId); success = setSealedReplicas(sealedReplicas); } else if (isSealed && !sealedReplicas.contains(partitionId)) { sealedReplicas.add(partitionId); success = setSealedReplicas(sealedReplicas); } return success; }
Source:
<code>public CtfIterator getIterator(final CtfTmfContext context) { <START> CtfIterator retVal = fMap.get(context); <END> if (retVal == null) { fAccessLock.lock(); try { if (fRandomAccess.size() < MAX_SIZE) { retVal = fTrace.createIterator(); addElement(context, retVal); } else { retVal = replaceRandomElement(context); } if (context.getLocation() != null) { final CtfLocationInfo location = (CtfLocationInfo) context.getLocation().getLocationInfo(); retVal.seek(location); } } finally { fAccessLock.unlock(); } } return retVal; }</code><technical_language>I a feeling a C programmer named this variable... this opportunity rename</technical_language>

Target:
public CtfIterator getIterator(final CtfTmfContext context) { CtfIterator iter = fMap.get(context); if (iter == null) { fAccessLock.lock(); try { if (fRandomAccess.size() < MAX_SIZE) { iter = fTrace.createIterator(); addElement(context, iter); } else { iter = replaceRandomElement(context); } if (context.getLocation() != null) { final CtfLocationInfo location = (CtfLocationInfo) context.getLocation().getLocationInfo(); iter.seek(location); } } finally { fAccessLock.unlock(); } } return iter; }
Source:
<code>private Iterator<BatchOfCellsToSweep> getBatchesToSweep(Iterator<List<CandidateCellForSweeping>> candidates, SweepBatchConfig batchConfig, SweepableCellFilter sweepableCellFilter, ExaminedCellLimit limit) { <START> Iterator<List<CandidateCellForSweeping>> validCandidates = <END> Iterators.filter(candidates, list -> list != null && !list.isEmpty()); Iterator<BatchOfCellsToSweep> cellsToSweep = Iterators.transform( validCandidates, sweepableCellFilter::getCellsToSweep); return new CellsToSweepPartitioningIterator(cellsToSweep, batchConfig.deleteBatchSize(), limit); }</code><technical_language>change here? If not, original version of this method diff smaller</technical_language>

Target:
private Iterator<BatchOfCellsToSweep> getBatchesToSweep(Iterator<List<CandidateCellForSweeping>> candidates, SweepBatchConfig batchConfig, SweepableCellFilter sweepableCellFilter, ExaminedCellLimit limit) { Iterator<BatchOfCellsToSweep> cellsToSweep = Iterators.transform( Iterators.filter(candidates, list -> !list.isEmpty()), sweepableCellFilter::getCellsToSweep); return new CellsToSweepPartitioningIterator(cellsToSweep, batchConfig.deleteBatchSize(), limit); }
Source:
<code>public ServiceCall<Collection> createCollection(CreateCollectionOptions createCollectionOptions) { String[] pathSegments = {"v4/collections"}; <START> RequestBuilder builder = <END> RequestBuilder.post(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments)); builder.query("version", versionDate); Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("watson_vision_combined", "v4", "createCollection"); for (Entry<String, String> header : sdkHeaders.entrySet()) { builder.header(header.getKey(), header.getValue()); } builder.header("Accept", "application/json"); final JsonObject contentJson = new JsonObject(); if (createCollectionOptions != null) { if (createCollectionOptions.name() != null) { contentJson.addProperty("name", createCollectionOptions.name()); } if (createCollectionOptions.description() != null) { contentJson.addProperty("description", createCollectionOptions.description()); } } builder.bodyJson(contentJson); ResponseConverter<Collection> responseConverter = ResponseConverterUtils.getValue( new com.google.gson.reflect.TypeToken<Collection>() {}.getType()); return createServiceCall(builder.build(), responseConverter); }</code><technical_language>Why? I need createCollectionOption null</technical_language>

Target:
public ServiceCall<Collection> createCollection(CreateCollectionOptions createCollectionOptions) { com.ibm.cloud.sdk.core.util.Validator.notNull( createCollectionOptions, "createCollectionOptions cannot be null"); String[] pathSegments = {"v4/collections"}; RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments)); builder.query("version", versionDate); Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("watson_vision_combined", "v4", "createCollection"); for (Entry<String, String> header : sdkHeaders.entrySet()) { builder.header(header.getKey(), header.getValue()); } builder.header("Accept", "application/json"); final JsonObject contentJson = new JsonObject(); if (createCollectionOptions != null) { if (createCollectionOptions.name() != null) { contentJson.addProperty("name", createCollectionOptions.name()); } if (createCollectionOptions.description() != null) { contentJson.addProperty("description", createCollectionOptions.description()); } } builder.bodyJson(contentJson); ResponseConverter<Collection> responseConverter = ResponseConverterUtils.getValue( new com.google.gson.reflect.TypeToken<Collection>() {}.getType()); return createServiceCall(builder.build(), responseConverter); }
Source:
<code>protected Map<String, String> readContext(final String property) throws JMSException { final String json = readProperty(property); IDoEntity context = m_contextDataObjectMapper.get().readValue(json, IDoEntity.class); if (context == null) { return Collections.emptyMap(); } <START> return context.allNodes().entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> assertInstance(e.getValue().get(), String.class))); <END> }</code><technical_language>assert ignore? Throwing exception changes API, it</technical_language>

Target:
protected Map<String, String> readContext(final String property) throws JMSException { final String json = readProperty(property); @SuppressWarnings("unchecked") Map<String, String> context = (Map<String, String>) m_contextDataObjectMapper.readValue(json, HashMap.class); if (context == null) { return Collections.emptyMap(); } return context; }
Source:
<code>public Collection<Sample> listByProjectId(long projectId) throws IOException { @SuppressWarnings("unchecked") <START> List<Sample> records = currentSession().createCriteria(SampleImpl.class).add(Restrictions.like("project.id", projectId)).list(); <END> return records; }</code><technical_language>I 'equals' instead of 'like' in place. downside Restrictions.eq here</technical_language>

Target:
public Collection<Sample> listByProjectId(long projectId) throws IOException { @SuppressWarnings("unchecked") List<Sample> records = currentSession().createCriteria(SampleImpl.class).add(Restrictions.eq("project.id", projectId)).list(); return records; }
Source:
<code>public Set<String> getIds() { File[] transformerFiles = transformerFolder.toFile().listFiles(); if (transformerFiles == null || transformerFiles.length == 0) { LOGGER.debug("No Input Transformer json files found in {}", transformerFolder); return Collections.emptySet(); } Set<String> allTransformerIds = new HashSet<>(); Gson gson = new Gson(); for (File transformerFile : transformerFiles) { if (!FilenameUtils.getExtension(transformerFile.toString()).equals("json")) { LOGGER.debug("Skipping non-json file {}", transformerFile); continue; } try (FileReader reader = new FileReader(transformerFile)) { List<String> filesTransformerIds = gson.fromJson(reader, new TypeToken<List<String>>() {}.getType()); allTransformerIds.addAll(filesTransformerIds); } catch (IOException e) { LOGGER.debug( "Error reading InputTransformer ids from file {}. The ids returned will not be the full set described in {}.", transformerFile, <START> transformerFolder); <END> } } return ImmutableSet.copyOf(allTransformerIds); }</code><technical_language>worth checking if file is malformed json report error user fix</technical_language>

Target:
public Set<String> getIds() { File[] transformerFiles = transformerFolder.toFile().listFiles(); if (transformerFiles == null || transformerFiles.length == 0) { LOGGER.debug("No Input Transformer json files found in {}", transformerFolder); return Collections.emptySet(); } Set<String> allTransformerIds = new HashSet<>(); Gson gson = new Gson(); boolean malformed = false; for (File transformerFile : transformerFiles) { if (!FilenameUtils.getExtension(transformerFile.toString()).equalsIgnoreCase("json")) { LOGGER.debug("Skipping non-json file {}", transformerFile); continue; } try (FileReader reader = new FileReader(transformerFile)) { List<String> filesTransformerIds = gson.fromJson(reader, new TypeToken<List<String>>() {}.getType()); if (filesTransformerIds != null) { allTransformerIds.addAll(filesTransformerIds); } } catch (IOException e) { LOGGER.debug( "Error reading InputTransformer ids from file {}. The ids returned may not be the full set described in {}.", transformerFile, transformerFolder); } catch (JsonSyntaxException e) { LOGGER.error( "Malformed JSON file {}. Fix or remove the file before continuing. See debug logs for more info.", transformerFile); LOGGER.debug("Malformed InputTransformer JSON file {}", transformerFile, e); malformed = true; } } if (malformed) { throw new IllegalStateException("One or more InputTransformer JSON files were malformed."); } return ImmutableSet.copyOf(allTransformerIds); }
Source:
<code>public void reloadIndex_EXISTING() throws SolrServerException, IOException { when(solrServer.request(any())).thenReturn(buildSuccessResponse()); when(solrServer.request(isCheckStatus())).thenReturn(buildCheckStatusResponse()); IndexConfiguration indexConfiguration = new IndexConfiguration(); indexConfiguration.setName(EXISTING_INDEX_NAME); indexConfiguration.setInstanceDir("indexDirectory"); indexReloader.reloadIndex(indexConfiguration); ArgumentCaptor<SolrRequest> solrRequestArg = ArgumentCaptor.forClass(SolrRequest.class); verify(solrServer, times(2)).request(solrRequestArg.capture()); SolrRequest actualCheckRequest = solrRequestArg.getAllValues().get(0); SolrRequest actualReloadRequest = solrRequestArg.getAllValues().get(1); assertStatusRequest(actualCheckRequest); assertReloadRequest(actualReloadRequest, "indexName"); <START> <END> }</code><technical_language>EXISTING_INDEX_NAME here</technical_language>

Target:
public void reloadIndex_EXISTING() throws SolrServerException, IOException { when(solrServer.request(any())).thenReturn(buildSuccessResponse()); when(solrServer.request(isCheckStatus())).thenReturn(buildCheckStatusResponse()); IndexConfiguration indexConfiguration = new IndexConfiguration(); indexConfiguration.setName(EXISTING_INDEX_NAME); indexConfiguration.setInstanceDir("indexDirectory"); indexReloader.reloadIndex(indexConfiguration); ArgumentCaptor<SolrRequest> solrRequestArg = ArgumentCaptor.forClass(SolrRequest.class); verify(solrServer, times(2)).request(solrRequestArg.capture()); SolrRequest actualCheckRequest = solrRequestArg.getAllValues().get(0); SolrRequest actualReloadRequest = solrRequestArg.getAllValues().get(1); assertStatusRequest(actualCheckRequest); assertReloadRequest(actualReloadRequest, EXISTING_INDEX_NAME); }
Source:
<code>public Span[] tokenizePos(String d) { <START> List<Span> tokens = new ArrayList<Span>(); <END> BreakIterator bi = BreakIterator.getWordInstance(locale); bi.setText(d); int lastIndex = bi.first(); while (lastIndex != BreakIterator.DONE) { int firstIndex = lastIndex; lastIndex = bi.next(); if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(d.charAt(firstIndex))) { tokens.add(new Span(firstIndex, lastIndex)); } } return tokens.toArray(new Span[tokens.size()]); }</code><technical_language>need type RHS</technical_language>

Target:
public Span[] tokenizePos(String d) { List<Span> tokens = new ArrayList<>(); breakIterator.setText(d); int lastIndex = breakIterator.first(); while (lastIndex != BreakIterator.DONE) { int firstIndex = lastIndex; lastIndex = breakIterator.next(); if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(d.charAt(firstIndex))) { tokens.add(new Span(firstIndex, lastIndex)); } } return tokens.toArray(new Span[tokens.size()]); }
Source:
<code>private void printSummary(cucumber.runtime.Runtime runtime) { <START> runtime.getSummaryCounter().printSummary(out); <END> }</code><technical_language>ask. Remove getSummaryCounter() add a Runtime.printSummary(out) method instead</technical_language>

Target:
private void printSummary(cucumber.runtime.Runtime runtime) { runtime.printSummary(out); }
Source:
<code>public boolean step() { if (applyModulesThread != null) { if (!applyModulesThread.isAlive()) { if (oldEnvironment != null) { oldEnvironment.close(); } return true; } return false; } else { ModuleManager moduleManager = context.get(ModuleManager.class); List<Name> moduleIds = Lists.newArrayListWithCapacity(gameManifest.getModules().size()); <START> moduleIds.addAll(gameManifest.getModules().stream().map(NameVersion::getName).collect(Collectors.toList())); <END> DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry()); ResolutionResult result = resolver.resolve(moduleIds); if (result.isSuccess()) { oldEnvironment = moduleManager.getEnvironment(); ModuleEnvironment env = moduleManager.loadEnvironment(result.getModules(), true); for (Module moduleInfo : env.getModulesOrderedByDependencies()) { logger.info("Activating module: {}:{}", moduleInfo.getId(), moduleInfo.getVersion()); } EnvironmentSwitchHandler environmentSwitchHandler = context.get(EnvironmentSwitchHandler.class); applyModulesThread = new Thread(() -> environmentSwitchHandler.handleSwitchToGameEnvironment(context)); applyModulesThread.start(); return false; } else { logger.warn("Missing at least one required module or dependency: {}", moduleIds); context.get(GameEngine.class).changeState(new StateMainMenu("Missing required module or dependency")); return true; } } }</code><technical_language>list instead of adding elements a new list</technical_language>

Target:
public boolean step() { if (applyModulesThread != null) { if (!applyModulesThread.isAlive()) { if (oldEnvironment != null) { oldEnvironment.close(); } return true; } return false; } else { ModuleManager moduleManager = context.get(ModuleManager.class); List<Name> moduleIds = gameManifest.getModules().stream().map(NameVersion::getName) .collect(Collectors.toCollection(ArrayList::new)); DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry()); ResolutionResult result = resolver.resolve(moduleIds); if (result.isSuccess()) { oldEnvironment = moduleManager.getEnvironment(); ModuleEnvironment env = moduleManager.loadEnvironment(result.getModules(), true); for (Module moduleInfo : env.getModulesOrderedByDependencies()) { logger.info("Activating module: {}:{}", moduleInfo.getId(), moduleInfo.getVersion()); } EnvironmentSwitchHandler environmentSwitchHandler = context.get(EnvironmentSwitchHandler.class); applyModulesThread = new Thread(() -> environmentSwitchHandler.handleSwitchToGameEnvironment(context)); applyModulesThread.start(); return false; } else { logger.warn("Missing at least one required module or dependency: {}", moduleIds); context.get(GameEngine.class).changeState(new StateMainMenu("Missing required module or dependency")); return true; } } }
Source:
<code>private void handleSuccessfulRetry(ExecutionCompletedEvent<HermesResponse> event) { <START> HermesMessage message = event.getResult().getHermesMessage(); <END> messageDeliveryListeners.forEach(l -> l.onSuccessfulRetry(event.getResult(), event.getAttemptCount())); }</code><technical_language>This line is needed this point</technical_language>

Target:
private void handleSuccessfulRetry(ExecutionCompletedEvent<HermesResponse> event) { messageDeliveryListeners.forEach(l -> l.onSuccessfulRetry(event.getResult(), event.getAttemptCount())); }
Source:
<code>public void testClosureEntryPoint() throws Exception { Options opts = new Options(new String[] { <START> "foo.js", "--closure_entry_point", "entryPoint", "--externs", "extern1.js", "extern2.js", "-o", "output.d.ts" <END> }); assertThat(opts.arguments).containsExactly("foo.js"); assertThat(opts.entryPoints).containsExactly("entryPoint"); assertThat(opts.externs).containsExactly("extern1.js", "extern2.js").inOrder(); assertThat(opts.output).isEqualTo("output.d.ts"); }</code><technical_language>add multiple entry points, closure namespaced symbols 'ns.entryPoint1', etc</technical_language>

Target:
public void testClosureEntryPoint() throws Exception { Options opts = new Options(new String[] { "foo.js", "--closure_entry_points", "ns.entryPoint1", "ns.entryPoint2", "--externs", "extern1.js", "extern2.js", "-o", "output.d.ts" }); assertThat(opts.arguments).containsExactly("foo.js"); assertThat(opts.entryPoints).containsExactly("ns.entryPoint1", "ns.entryPoint2"); assertThat(opts.externs).containsExactly("extern1.js", "extern2.js").inOrder(); assertThat(opts.output).isEqualTo("output.d.ts"); }
Source:
<code>public static File newFile(final String parentDir, final String... childDirs) { final List<String> dirs = new ArrayList<>(); dirs.add(parentDir); dirs.addAll(List.of(childDirs)); <START> return new File(String.join(File.separator, dirs)); <END> }</code><technical_language>Thought: I java.nio.file.Path instead of java.io.File easily [Path#of](<LINK_0>,java.lang.String...)) for convinience instead of coding this logic ourselves</technical_language>

Target:
public static File newFile(final String parentDir, final String... childDirs) { return Path.of(parentDir, childDirs).toFile(); }
Source:
<code>public static DeviceManagementService getDeviceManagementService() throws DeviceManagementServiceException { DeviceManagementService deviceManagementService; PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext(); context.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); context.setTenantId(MultitenantConstants.SUPER_TENANT_ID); deviceManagementService = (DeviceManagementService) context .getOSGiService(DeviceManagementService.class, null); if (deviceManagementService == null) { String msg = "Device management service not initialized."; <START> log.error(msg); <END> throw new DeviceManagementServiceException(msg); } PrivilegedCarbonContext.endTenantFlow(); return deviceManagementService; }</code><technical_language>Log throw is generally considered anti-pattern. able get rid of log message in this line</technical_language>

Target:
public static DeviceManagementService getDeviceManagementService() throws DeviceManagementServiceException { DeviceManagementService deviceManagementService; PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext(); context.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); context.setTenantId(MultitenantConstants.SUPER_TENANT_ID); deviceManagementService = (DeviceManagementService) context .getOSGiService(DeviceManagementService.class, null); if (deviceManagementService == null) { throw new DeviceManagementServiceException("Device management service is not initialized."); } PrivilegedCarbonContext.endTenantFlow(); return deviceManagementService; }
Source:
<code>private ContentEquivalenceUpdater.Builder<Item> ebsItemUpdater(Set<Publisher> acceptablePublishers, Set<? extends EquivalenceScorer<Item>> scorers) { NullScoreAwareAveragingCombiner<Item> combiner = new NullScoreAwareAveragingCombiner<>(); combiner.setIgnoreNullScoringContent(true); return ContentEquivalenceUpdater.<Item> builder() .withGenerators(ImmutableSet.<EquivalenceGenerator<Item>> of( new BroadcastMatchingItemEquivalenceGenerator(scheduleResolver, channelResolver, acceptablePublishers, Duration.standardMinutes(5), Predicates.alwaysTrue()) )) .withExcludedUris(excludedUrisFromProperties()) .withScorers(scorers) .withCombiner(combiner) .withFilter(this.standardFilter()) .withExtractor(PercentThresholdAboveNextBestMatchEquivalenceExtractor.atLeastNTimesGreater(1.5)) .withHandler(new BroadcastingEquivalenceResultHandler<Item>(ImmutableList.of( EpisodeFilteringEquivalenceResultHandler.relaxed( new LookupWritingEquivalenceHandler<Item>(lookupWriter, acceptablePublishers), equivSummaryStore ), new ResultWritingEquivalenceHandler<Item>(equivalenceResultStore()), new EquivalenceSummaryWritingHandler<Item>(equivSummaryStore), MessageQueueingResultHandler.create( equivAssertDestination(), acceptablePublishers, lookupEntryStore ) ))); <START> } <END></code><technical_language>lots of lines greater >100 characters in this method</technical_language>

Target:
private ContentEquivalenceUpdater.Builder<Item> ebsItemUpdater( Set<Publisher> acceptablePublishers, Set<? extends EquivalenceScorer<Item>> scorers ) { NullScoreAwareAveragingCombiner<Item> combiner = new NullScoreAwareAveragingCombiner<>(true); return ContentEquivalenceUpdater.<Item> builder() .withGenerators(ImmutableSet.<EquivalenceGenerator<Item>> of( new BroadcastMatchingItemEquivalenceGenerator( scheduleResolver, channelResolver, acceptablePublishers, Duration.standardMinutes(5), Predicates.alwaysTrue()) )) .withExcludedUris(excludedUrisFromProperties()) .withScorers(scorers) .withCombiner(combiner) .withFilter(this.standardFilter()) .withExtractor( PercentThresholdAboveNextBestMatchEquivalenceExtractor .atLeastNTimesGreater(1.5) ) .withHandler(new BroadcastingEquivalenceResultHandler<Item>(ImmutableList.of( EpisodeFilteringEquivalenceResultHandler.relaxed( new LookupWritingEquivalenceHandler<Item>( lookupWriter, acceptablePublishers), equivSummaryStore ), new ResultWritingEquivalenceHandler<Item>(equivalenceResultStore()), new EquivalenceSummaryWritingHandler<Item>(equivSummaryStore), MessageQueueingResultHandler.create( equivAssertDestination(), acceptablePublishers, lookupEntryStore ) ))); }
Source:
<code>public boolean shouldSkipField(FieldAttributes f) { GsonOmitField annotation = f.getAnnotation(GsonOmitField.class); if (annotation != null) return true; <START> <END> String fieldName = f.getName(); Class<?> definedIn = f.getDeclaringClass(); for (Entry<String, Class<?>> include : serializee.getIncludes().entries()) { if (isCompatiblePath(include, definedIn, fieldName)) { return false; } } for (Entry<String, Class<?>> exclude : serializee.getExcludes().entries()) { if (isCompatiblePath(exclude, definedIn, fieldName)) { return true; } } return !serializee.isRecursive() && !shouldSerializeField(new Mirror().on(definedIn).reflect().field(fieldName).getType()); }</code><technical_language>for isAnnotationPresent</technical_language>

Target:
public boolean shouldSkipField(FieldAttributes f) { SkipSerialization annotation = f.getAnnotation(SkipSerialization.class); if (annotation != null) return true; String fieldName = f.getName(); Class<?> definedIn = f.getDeclaringClass(); for (Entry<String, Class<?>> include : serializee.getIncludes().entries()) { if (isCompatiblePath(include, definedIn, fieldName)) { return false; } } for (Entry<String, Class<?>> exclude : serializee.getExcludes().entries()) { if (isCompatiblePath(exclude, definedIn, fieldName)) { return true; } } return !serializee.isRecursive() && !shouldSerializeField(new Mirror().on(definedIn).reflect().field(fieldName).getType()); }
Source:
<code>private List<ReferenceCountingResourceHolder<ByteBuffer>> getMergeBuffersHolder( int numBuffers, boolean hasTimeout, long timeoutAt ) { try { if (numBuffers > mergeBufferPool.maxSize()) { <START> throw new ResourceLimitExceededException( <END> "Query needs " + numBuffers + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers were configured" ); } final List<ReferenceCountingResourceHolder<ByteBuffer>> mergeBufferHolder; if (hasTimeout) { final long timeout = timeoutAt - System.currentTimeMillis(); if (timeout <= 0) { throw new TimeoutException(); } if ((mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers, timeout)).isEmpty()) { throw new InsufficientResourcesException("Cannot acquire enough merge buffers"); } } else { mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers); } return mergeBufferHolder; } catch (Exception e) { throw new QueryInterruptedException(e); } }</code><technical_language>This error include "Try raising druid.processing.numMergeBuffers."</technical_language>

Target:
private List<ReferenceCountingResourceHolder<ByteBuffer>> getMergeBuffersHolder( int numBuffers, boolean hasTimeout, long timeoutAt ) { try { if (numBuffers > mergeBufferPool.maxSize()) { throw new ResourceLimitExceededException( "Query needs " + numBuffers + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers were configured. " + "Try raising druid.processing.numMergeBuffers." ); } final List<ReferenceCountingResourceHolder<ByteBuffer>> mergeBufferHolder; if (hasTimeout) { final long timeout = timeoutAt - System.currentTimeMillis(); if (timeout <= 0) { throw new TimeoutException(); } if ((mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers, timeout)).isEmpty()) { throw new TimeoutException("Cannot acquire enough merge buffers"); } } else { mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers); } return mergeBufferHolder; } catch (Exception e) { throw new QueryInterruptedException(e); } }
Source:
<code><START> public void GetSQLWithPreservedColumnOrder() { <END> com.mysema.query.sql.domain.QEmployee emp1 = new com.mysema.query.sql.domain.QEmployee("emp1"); SQLInsertClause insert = new SQLInsertClause(null, SQLTemplates.DEFAULT, emp1); insert.populate(emp1); SQLBindings sql = insert.getSQL().get(0); assertEquals("The order of columns in generated sql should be predictable", "insert into EMPLOYEE (SALARY, SUPERIOR_ID, DATEFIELD, FIRSTNAME, TIMEFIELD, ID, LASTNAME)" + "values (EMPLOYEE.SALARY, EMPLOYEE.SUPERIOR_ID, EMPLOYEE.DATEFIELD, EMPLOYEE.FIRSTNAME, " + "EMPLOYEE.TIMEFIELD, EMPLOYEE.ID, EMPLOYEE.LASTNAME)", sql.getSQL()); }</code><technical_language>Haha, so</technical_language>

Target:
public void GetSQLWithPreservedColumnOrder() { QEmployee emp1 = new QEmployee("emp1"); SQLInsertClause insert = new SQLInsertClause(null, SQLTemplates.DEFAULT, emp1); insert.populate(emp1); SQLBindings sql = insert.getSQL().get(0); assertEquals("The order of columns in generated sql should be predictable", "insert into EMPLOYEE (ID, FIRSTNAME, LASTNAME, SALARY, DATEFIELD, TIMEFIELD, SUPERIOR_ID)\n" + "values (EMPLOYEE.ID, EMPLOYEE.FIRSTNAME, EMPLOYEE.LASTNAME, EMPLOYEE.SALARY, EMPLOYEE.DATEFIELD, EMPLOYEE.TIMEFIELD, EMPLOYEE.SUPERIOR_ID)", sql.getSQL()); }
Source:
<code>private static MapBasedEndpointContext setInfo(OSCoreCtx oscoreCtx, EndpointContext endpointContext) { MapBasedEndpointContext newEndpointContext = MapBasedEndpointContext.addEntries( endpointContext, <START> OSCORE, Boolean.TRUE.toString(), <END> OSCORE_SENDER_ID, oscoreCtx.getSenderIdString(), OSCORE_RECIPIENT_ID, oscoreCtx.getRecipientIdString(), OSCORE_CONTEXT_ID, oscoreCtx.getContextIdString(), OSCORE_URI, oscoreCtx.getUri()); return newEndpointContext; }</code><technical_language>Consider remove "OSCORE, Boolean.TRUE.toString()" entry. E.g. get(OSCORE_URI) != null do same, or</technical_language>

Target:
private static MapBasedEndpointContext setInfo(OSCoreCtx oscoreCtx, EndpointContext endpointContext) { if (endpointContext == null) { return null; } List<String> attributes = new ArrayList<String>(); add(attributes, OSCORE_SENDER_ID, oscoreCtx.getSenderIdString()); add(attributes, OSCORE_RECIPIENT_ID, oscoreCtx.getRecipientIdString()); add(attributes, OSCORE_CONTEXT_ID, oscoreCtx.getContextIdString()); add(attributes, OSCORE_URI, oscoreCtx.getUri()); MapBasedEndpointContext newEndpointContext = MapBasedEndpointContext.addEntries(endpointContext, attributes.toArray(new String[attributes.size()])); return newEndpointContext; }
Source:
<code>protected int countEvents(Map<Object, LinkedList<ITmfEvent>> tbl) { Iterator<Entry<Object, LinkedList<ITmfEvent>>> iterator = tbl.entrySet().iterator(); int count = 0; while (iterator.hasNext()) { count += iterator.next().getValue().size(); <START> } <END> return count; }</code><technical_language>a tad simpler do: for (List<ITmfEvent> list : tbl.values()) { count += list.size(); }</technical_language>

Target:
protected int countEvents(Map<Object, LinkedList<ITmfEvent>> tbl) { int count = 0; for (LinkedList<ITmfEvent> entry : tbl.values()) { count += entry.size(); } return count; }
Source:
<code>public static String formatDateTimeForComments(Date date, double sessionTimeZone) { if (date == null) { return ""; } SimpleDateFormat sdf = null; Calendar c = Calendar.getInstance(SystemParams.TIME_ZONE); c.setTime(date); String sign = sessionTimeZone > 0 ? "+" : "-"; int hours = (int) sessionTimeZone; int minutes = (int) ((sessionTimeZone - Math.floor(sessionTimeZone)) * 60); String offset = Integer.toString(hours); if (minutes != 0) { offset = Integer.toString(hours) + ":" + Integer.toString(minutes); } <START> String timeZone = TimeZone.getTimeZone("GMT" + sign + offset).getID(); <END> if (c.get(Calendar.HOUR_OF_DAY) == 12 && c.get(Calendar.MINUTE) == 0) { sdf = new SimpleDateFormat("EEE, dd MMM yyyy, hh:mm"); sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); return sdf.format(date) + " NOON UTC"; } sdf = new SimpleDateFormat("EEE, dd MMM yyyy, hh:mm a Z"); sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); return sdf.format(date); }</code><technical_language>extract this part a separate method</technical_language>

Target:
public static String formatDateTimeForComments(Date date, double sessionTimeZone) { if (date == null) { return ""; } SimpleDateFormat sdf = null; Calendar c = Calendar.getInstance(SystemParams.TIME_ZONE); TimeZone timeZone = getTimeZoneFromDoubleOffset(sessionTimeZone); c.setTimeZone(timeZone); c.setTime(date); String periodIndicator = c.get(Calendar.HOUR_OF_DAY) == 12 && c.get(Calendar.MINUTE) == 0 ? "'NOON'" : "a"; sdf = new SimpleDateFormat("EEE, dd MMM yyyy, hh:mm " + periodIndicator + " 'UTC'Z"); sdf.setTimeZone(timeZone); return sdf.format(date); }
Source:
<code>public void telemetrySentWorks() throws InterruptedException { for(int i = 0; i < 5; i++) { try { cl.loadClass("sun.java.MyNonExistentClass"); } catch (ClassNotFoundException ignored) { } } ExtensionList.lookupSingleton(Telemetry.TelemetryReporter.class).doRun(); do { <START> Thread.sleep(250); <END> } while (received == null); assertEquals(MissingClassTelemetry.class.getName(), received.getString("type")); JSONArray events = received.getJSONObject("payload").getJSONArray("classMissingEvents"); assertEquals(1, events.size()); assertEquals("sun.java.MyNonExistentClass", ((JSONObject) events.get(0)).get("className")); assertEquals(5, Integer.parseInt( (String) ((JSONObject) events.get(0)).get("occurrences"))); }</code><technical_language>killing here! In a test</technical_language>

Target:
public void telemetrySentWorks() throws InterruptedException { Assume.assumeTrue("The telemetry should be enabled", MissingClassTelemetry.enabled()); for(int i = 0; i < 5; i++) { try { cl.loadClass("sun.java.MyNonExistentClass"); } catch (ClassNotFoundException ignored) { } } ExtensionList.lookupSingleton(Telemetry.TelemetryReporter.class).doRun(); do { Thread.sleep(250); } while (received == null); assertEquals(MissingClassTelemetry.class.getName(), received.getString("type")); JSONArray events = received.getJSONObject("payload").getJSONArray("classMissingEvents"); assertEquals(1, events.size()); assertEquals("sun.java.MyNonExistentClass", ((JSONObject) events.get(0)).get("className")); assertEquals(5, Integer.parseInt( (String) ((JSONObject) events.get(0)).get("occurrences"))); }
Source:
<code>protected int doWrite() { WriteData wd = writeQueue.poll(); if(wd != null) { try { return channel.send(wd.getBuffer(), wd.getAddress()); } catch (IOException e) { return 0; } finally { <START> if(wd.getSlf() != null && !wd.getSlf().isDone()) { <END> wd.getSlf().setResult(0L); } } } return 0; }</code><technical_language>This !wd.getSlf().isDone() check is good enough, potential for a check act race condition. option is a ClientSettableListenableFuture this complete ClientExecutor thread, correct? If not, construct SettableListenableFuture false</technical_language>

Target:
protected int doWrite() { WriteData wd = writeQueue.poll(); if(wd != null) { int size = 0; try { size = channel.send(wd.getBuffer(), wd.getAddress()); wd.getSlf().setResult((long)size); return size; } catch (Exception e) { wd.getSlf().setFailure(e); return 0; } } return 0; }
Source:
<code>private static byte getSaltingByte(byte[] value, int offset, int length, int bucketNum) { <START> HashCode digest = MD5.hashBytes(value, offset, length); <END> byte bucketByte = (byte) ((Math.abs(digest.asInt()) % bucketNum) & 0x0f); return bucketByte; }</code><technical_language>MD5 overkill here. expensive is it? compare Arrays.hashCode() key,offset, length</technical_language>

Target:
public static byte getSaltingByte(byte[] value, int offset, int length, int bucketNum) { int hash = hashCode(value, offset, length); byte bucketByte = (byte) ((Math.abs(hash) % bucketNum)); return bucketByte; }
Source:
<code>public ConfigInfos validateConnectorConfig(String connClassName, Map<String, String> connConfig) throws JsonProcessingException { String url = endpointForResource(String.format("connector-plugins/%s/config/validate", connClassName)); ObjectMapper mapper = new ObjectMapper(); String content; try { content = mapper.writeValueAsString(connConfig); } catch (IOException e) { throw new ConnectException("Could not serialize connector configuration and execute PUT request"); } Response response = requestPut(url, content); if (response.getStatus() < Response.Status.BAD_REQUEST.getStatusCode()) { <START> return mapper.readValue(response.getEntity().toString(), ConfigInfos.class); <END> } throw new ConnectRestException(response.getStatus(), "Could not execute PUT request. Error response: " + responseToString(response)); }</code><technical_language>responseToString below, increases similarities configureConnector</technical_language>

Target:
public ConfigInfos validateConnectorConfig(String connClassName, Map<String, String> connConfig) { String url = endpointForResource(String.format("connector-plugins/%s/config/validate", connClassName)); String response = putConnectorConfig(url, connConfig); ConfigInfos configInfos; try { configInfos = new ObjectMapper().readValue(response, ConfigInfos.class); } catch (IOException e) { throw new ConnectException("Unable deserialize response into a ConfigInfos object"); } return configInfos; }
Source:
<code>private boolean updateVm(VM vm, Version oldClusterVersion) { VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setClusterLevelChangeFromVersion(oldClusterVersion); VdcReturnValueBase result = runInternalAction( <START> END> VdcActionType.UpdateVm, updateParams, cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { getReturnValue().setFault(result.getFault()); return false; } return true; }</code><technical_language>relevant</technical_language>

Target:
private boolean updateVm(VM vm, Version oldClusterVersion) { VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setLockProperties(LockProperties.create(LockProperties.Scope.None)); updateParams.setClusterLevelChangeFromVersion(oldClusterVersion); VdcReturnValueBase result = runInternalAction( VdcActionType.UpdateVm, updateParams, cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { getReturnValue().setFault(result.getFault()); return false; } return true; }
Source:
<code>private ClientAuth requireClientAuth(SslConfiguration sslConfig) { <START> return sslConfig.enabled() ? ClientAuth.REQUIRE : ClientAuth.NONE; <END> }</code><technical_language>This sslConfig.requireClientAuth() ;) TL;DR turning [SSL Debug](<LINK_0> turned out server challenges client for certificate (which client keystore). This suggested client cert file is wrong server challenge is wrong. I lucky :)</technical_language>

Target:
private ClientAuth requireClientAuth(SslConfiguration sslConfig) { return sslConfig.requireClientAuth() ? ClientAuth.REQUIRE : ClientAuth.NONE; }
Source:
<code>public synchronized void syncRoutingTable(final String serverId) { if (!storeIdToEndpointId.containsValue(serverId)) { msgSender.get().sendRoutingTableSyncReplyMsg(serverId); } else { <START> ongoingSyncs.add(serverId); <END> } }</code><technical_language>logic related ongoingSyncs potential concurrency issue. worker sends sync reply message if scenario occurs: statement is executed in sequence L193 (if clause is true) -> L204 (if clause is false) -> L194~196 (if clause is false) -> L207</technical_language>

Target:
public void syncRoutingTable(final String serverId) { checkInitialization(); synchronized (this) { if (!storeIdToBlockIds.containsKey(serverId)) { msgSender.get().sendRoutingTableSyncReplyMsg(serverId); } else { ongoingSyncs.add(serverId); } } }
Source:
<code>private int setWifiTethering(final boolean enable) { <START> int rval = TETHER_ERROR_MASTER_ERROR; <END> final long ident = Binder.clearCallingIdentity(); try { synchronized (mPublicSync) { final WifiManager mgr = getWifiManager(); if (mgr == null) { mLog.e("setWifiTethering: failed to get WifiManager!"); return TETHER_ERROR_SERVICE_UNAVAIL; } if ((enable && mgr.startSoftAp(null )) || (!enable && mgr.stopSoftAp())) { mWifiTetherRequested = enable; return TETHER_ERROR_NO_ERROR; } return TETHER_ERROR_MASTER_ERRROR; } } finally { Binder.restoreCallingIdentity(ident); } return rval; }</code><technical_language>For clarity, remove this</technical_language>

Target:
private int setWifiTethering(final boolean enable) { final long ident = Binder.clearCallingIdentity(); try { synchronized (mPublicSync) { final WifiManager mgr = getWifiManager(); if (mgr == null) { mLog.e("setWifiTethering: failed to get WifiManager!"); return TETHER_ERROR_SERVICE_UNAVAIL; } if ((enable && mgr.startSoftAp(null )) || (!enable && mgr.stopSoftAp())) { mWifiTetherRequested = enable; return TETHER_ERROR_NO_ERROR; } } } finally { Binder.restoreCallingIdentity(ident); } return TETHER_ERROR_MASTER_ERROR; }
Source:
<code>private static String env(ServletContext context) { <START> String systemEnv = System.getenv("VRAPTOR_ENVIRONMENT"); <END> if (systemEnv != null) { return systemEnv; } String systemProperty = System.getProperty(ENVIRONMENT_PROPERTY); if (systemProperty != null) { return systemProperty; } return context.getInitParameter(ENVIRONMENT_PROPERTY); }</code><technical_language>"VRAPTOR_ENV"? in "RAILS_ENV", "RACK_ENV", =)</technical_language>

Target:
private static String env(ServletContext context) { String systemEnv = System.getenv("VRAPTOR_ENV"); if (systemEnv != null) { return systemEnv; } String systemProperty = System.getProperty(ENVIRONMENT_PROPERTY); if (systemProperty != null) { return systemProperty; } return context.getInitParameter(ENVIRONMENT_PROPERTY); }
Source:
<code>public static void onFailedAdminLogin(HttpSession httpSess, String username, int tenantId, String tenantDomain, String remoteAddress, String reason) throws Exception { if (httpSess != null) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setUsername(username); carbonContext.setTenantId(tenantId); if (tenantDomain == null) { tenantDomain = carbonContext.getTenantDomain(true); } carbonContext.setTenantDomain(tenantDomain); } Date currentTime = Calendar.getInstance().getTime(); SimpleDateFormat date = new SimpleDateFormat("'['yyyy-MM-dd HH:mm:ss,SSSZ']'"); <START> String msg = "Non-Admin user login attempt \'" + username + "[" + tenantId + "]\' at " <END> + date.format(currentTime); if(!CarbonUtils.isRunningOnLocalTransportMode()){ msg += " from IP address " + remoteAddress; } log.warn(msg); audit.warn(msg); if (httpSess != null) { httpSess.invalidate(); } LoginAttempt loginAttempt = new LoginAttempt(username, tenantId, remoteAddress, new Date(), false, reason); LoginStatDatabase.recordLoginAttempt(loginAttempt); }</code><technical_language>need mention a failed attempt? do print correct message is a failed admin login attempt</technical_language>

Target:
public static void onFailedAdminLogin(HttpSession httpSess, String username, int tenantId, String tenantDomain, String remoteAddress, String reason) throws Exception { if (httpSess != null) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setUsername(username); carbonContext.setTenantId(tenantId); if (tenantDomain == null) { tenantDomain = carbonContext.getTenantDomain(true); } carbonContext.setTenantDomain(tenantDomain); } Date currentTime = Calendar.getInstance().getTime(); SimpleDateFormat date = new SimpleDateFormat("'['yyyy-MM-dd HH:mm:ss,SSSZ']'"); String msg = "Login failed. Unauthorized login attempt \'" + username + "[" + tenantId + "]\' at " + date.format(currentTime); if(!CarbonUtils.isRunningOnLocalTransportMode()){ msg += " from IP address " + remoteAddress; } log.warn(msg); audit.warn(msg); if (httpSess != null) { httpSess.invalidate(); } LoginAttempt loginAttempt = new LoginAttempt(username, tenantId, remoteAddress, new Date(), false, reason); LoginStatDatabase.recordLoginAttempt(loginAttempt); }
Source:
<code><START> public @ResponseBody Promise<CodeSystems> searchByGet(final CodeSystemRestSearch params) { <END> final IEventBus bus = getBus(); return RepositoryRequests.prepareSearch() .all() .buildAsync() .execute(bus) .thenWith(repos -> searchByGet(params, repos, bus)); }</code><technical_language>responsebody annotation removed, class is annotated RestController. suggestion public Promise<CodeSystems> searchByGet(final CodeSystemRestSearch params) {</technical_language>

Target:
public Promise<CodeSystems> searchByGet(final CodeSystemRestSearch params) { checkArgument(params.getSearchAfter() == null, "Parameter 'searchAfter' is not supported for code system search."); final IEventBus bus = getBus(); return RepositoryRequests.prepareSearch() .all() .buildAsync() .execute(bus) .thenWith(repos -> searchByGet(params, repos, bus)); }
Source:
<code>public CompletableFuture<Iterator<Result>> apply(Collection<ConditionalMutation> input) { CompletableFuture<Iterator<Result>> cfRes = new CompletableFuture<>(); if (input.size() == 0) { cfRes.complete(Collections.<Result>emptyList().iterator()); return cfRes; } semaphore.acquire(input.size()); Iterator<Result> iter = cw.write(input.iterator()); <START> CompletableFuture.runAsync(() -> { <END> try { Iterator<Result> iterRes = new IterTask(iter, input.size()).call(); cfRes.complete(iterRes); } catch (Exception e) { cfRes.completeExceptionally(e); } }, es); return cfRes; }</code><technical_language>inline remove IterTask do following. java return CompletableFuture.supplyAsync(() -> { try { Builder<Result> imlb = ImmutableList.builder(); while (iter.hasNext()) { Result result = iter.next(); imlb.add(result); } return imlb.build().iterator(); } finally { semaphore.release(permitsAcquired); } }, es);</technical_language>

Target:
public CompletableFuture<Iterator<Result>> apply(Collection<ConditionalMutation> input) { if (input.size() == 0) { return CompletableFuture.completedFuture(Collections.<Result>emptyList().iterator()); } semaphore.acquire(input.size()); Iterator<Result> iter = cw.write(input.iterator()); return CompletableFuture.supplyAsync(() -> { try { Builder<Result> imlb = ImmutableList.builder(); while (iter.hasNext()) { Result result = iter.next(); imlb.add(result); } return imlb.build().iterator(); } finally { semaphore.release(input.size()); } }, es); }