auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void showImpl (RepInfo info) { String status = null; String mime = info.getMimeType (); if (mime != null) { if (info.getWellFormed () == RepInfo.TRUE) { if (info.getValid () == RepInfo.TRUE) { status = "valid"; } else { status = "well-formed"; } } else { status = "not well-formed"; } } else { status = "not found"; } String md5 = null; <START> List<?> list = info.getChecksum (); <END> int len = list.size (); for (int i=0; i<len; i++) { Checksum checksum = (Checksum) list.get (i); if (checksum.getType ().equals (ChecksumType.MD5)) { md5 = checksum.getValue (); break; } } if (_nAudit == 0) { String margin = getIndent (++_level); String [][] attrs = { {"home", _home} }; _writer.println (margin + elementStart ("audit", attrs)); } String margn2 = getIndent (_level) + " "; String uri = info.getUri (); int n = uri.indexOf (_home); if (n == 0) { uri = uri.substring (_home.length () + 1); } String [][] attrs = { {"mime", mime }, {"status", status}, {"md5", md5} }; _writer.println (margn2 + element ("file", attrs, uri)); _nAudit++; }</code><technical_language>List<Checksum></technical_language>

Target:
public void showImpl (RepInfo info) { String status = null; String mime = info.getMimeType (); if (mime != null) { if (info.getWellFormed () == RepInfo.TRUE) { if (info.getValid () == RepInfo.TRUE) { status = "valid"; } else { status = "well-formed"; } } else { status = "not well-formed"; } } else { status = "not found"; } String md5 = null; for (Checksum checksum : info.getChecksum()) { if (checksum.getType ().equals (ChecksumType.MD5)) { md5 = checksum.getValue (); break; } } if (_nAudit == 0) { String margin = getIndent (++_level); String [][] attrs = { {"home", _home} }; _writer.println (margin + elementStart ("audit", attrs)); } String margn2 = getIndent (_level) + " "; String uri = info.getUri (); int n = uri.indexOf (_home); if (n == 0) { uri = uri.substring (_home.length () + 1); } String [][] attrs = { {"mime", mime }, {"status", status}, {"md5", md5} }; _writer.println (margn2 + element ("file", attrs, uri)); _nAudit++; }
Source:
<code>private String getETag(File file) { try { <START> return com.google.common.io.Files.asByteSource(file).hash(Hashing.md5()).toString(); <END> } catch (IOException e) { Exceptions.ignore(e); } return null; }</code><technical_language>sirius.kernel.commons.Hasher.md5()... :-P</technical_language>

Target:
private String getETag(File file) { return Hasher.md5().hashFile(file).toHexString(); }
Source:
<code>private void performHardDeletes(List<MessageInfo> messageInfoList) throws StoreException { try { EnumSet<StoreGetOptions> getOptions = EnumSet.of(StoreGetOptions.Store_Include_Deleted, StoreGetOptions.Store_Include_Expired); List<BlobReadOptions> readOptions = new ArrayList<BlobReadOptions>(messageInfoList.size()); Map<StoreKey, MessageInfo> indexMessages = new HashMap<StoreKey, MessageInfo>(messageInfoList.size()); for (MessageInfo info : messageInfoList) { BlobReadOptions readInfo = getBlobReadInfo(info.getStoreKey(), getOptions); readOptions.add(readInfo); indexMessages.put(info.getStoreKey(), info); } StoreMessageReadSet readSet = log.getView(readOptions); Iterator<ReplaceInfo> hardDeleteIterator = hardDelete.replacementIterator(readSet, factory); Iterator<BlobReadOptions> readOptionsIterator = readOptions.iterator(); while (hardDeleteIterator.hasNext()) { ReplaceInfo replaceInfo = hardDeleteIterator.next(); long offsetToWriteAt = readOptionsIterator.next().getOffset(); if (replaceInfo != null) { log.writeFrom(replaceInfo.getChannel(), offsetToWriteAt, replaceInfo.getSize()); <START> metrics.cleanupDoneCount.inc(1); <END> } else { metrics.cleanupFailedCount.inc(1); } } } catch (IOException e) { throw new StoreException("IO exception while performing hard delete ", e, StoreErrorCodes.IOError); } }</code><technical_language>cleanupSucceeded</technical_language>

Target:
private void performHardDeletes(List<MessageInfo> messageInfoList) throws StoreException { try { EnumSet<StoreGetOptions> getOptions = EnumSet.of(StoreGetOptions.Store_Include_Deleted); List<BlobReadOptions> readOptions = new ArrayList<BlobReadOptions>(messageInfoList.size()); for (MessageInfo info : messageInfoList) { try { BlobReadOptions readInfo = getBlobReadInfo(info.getStoreKey(), getOptions); readOptions.add(readInfo); } catch (StoreException e) { logger.error( "Failed to read blob info for blobid during hard deletes, ignoring the blob. Caught exception {}", info.getStoreKey(), e); } } StoreMessageReadSet readSet = log.getView(readOptions); Iterator<HardDeleteInfo> hardDeleteIterator = hardDelete.getHardDeleteMessages(readSet, factory); Iterator<BlobReadOptions> readOptionsIterator = readOptions.iterator(); while (hardDeleteIterator.hasNext()) { HardDeleteInfo hardDeleteInfo = hardDeleteIterator.next(); long offsetToWriteAt = readOptionsIterator.next().getOffset(); if (hardDeleteInfo != null) { log.writeFrom(hardDeleteInfo.getChannel(), offsetToWriteAt, hardDeleteInfo.getSize()); metrics.hardDeleteDoneCount.inc(1); try { throttler.maybeThrottle(hardDeleteInfo.getSize()); } catch (InterruptedException e) { logger.error("Caught interrupted exception, continuing "); } } else { metrics.hardDeleteFailedCount.inc(1); } } } catch (IOException e) { throw new StoreException("IO exception while performing hard delete ", e, StoreErrorCodes.IOError); } }
Source:
<code>public static int getPercentCompleteFromTasksAndReviews(Artifact artifact) throws OseeCoreException { if (IAtsAction.isOfType(artifact)) { double percent = 0; for (IAtsTeamWorkflow team : AtsClientService.get().getWorkItemService().getTeams(artifact)) { if (!team.isCancelled()) { percent += getPercentCompleteFromTasksAndReviews((Artifact) team.getStoreObject()); } } if (percent == 0) { return 0; } Double rollPercent = percent / AtsClientService.get().getWorkItemService().getTeams(artifact).size(); return rollPercent.intValue(); } int spent = 0; int size = 0; <START> if (artifact.isOfType(AtsArtifactTypes.TeamWorkflow)) { <END> TeamWorkFlowArtifact TeamWorkFlowArtifact = (TeamWorkFlowArtifact) artifact; Collection<TaskArtifact> taskArts = TeamWorkFlowArtifact.getTaskArtifacts(); for (TaskArtifact taskArt : taskArts) { spent += PercentCompleteTotalUtil.getPercentCompleteTotal(taskArt, AtsClientService.get().getServices()); } size = taskArts.size(); } if (artifact.isOfType(AtsArtifactTypes.TeamWorkflow)) { TeamWorkFlowArtifact teamWf = (TeamWorkFlowArtifact) artifact; Collection<IAtsAbstractReview> reviewArts = AtsClientService.get().getReviewService().getReviews(teamWf); for (IAtsAbstractReview reviewArt : reviewArts) { spent += PercentCompleteTotalUtil.getPercentCompleteTotal(reviewArt, AtsClientService.get().getServices()); } size += reviewArts.size(); } if (size == 0) { return 0; } return spent / size; }</code><technical_language>work if artifact null, - intentional</technical_language>

Target:
public static int getPercentCompleteFromTasksAndReviews(Artifact artifact) throws OseeCoreException { if (IAtsAction.isOfType(artifact)) { double percent = 0; for (IAtsTeamWorkflow team : AtsClientService.get().getWorkItemService().getTeams(artifact)) { if (!team.isCancelled()) { percent += getPercentCompleteFromTasksAndReviews((Artifact) team.getStoreObject()); } } if (percent == 0) { return 0; } Double rollPercent = percent / AtsClientService.get().getWorkItemService().getTeams(artifact).size(); return rollPercent.intValue(); } int spent = 0; int size = 0; if (IAtsTeamWorkflow.isOfType(artifact)) { TeamWorkFlowArtifact TeamWorkFlowArtifact = (TeamWorkFlowArtifact) artifact; Collection<TaskArtifact> taskArts = TeamWorkFlowArtifact.getTaskArtifacts(); for (TaskArtifact taskArt : taskArts) { spent += PercentCompleteTotalUtil.getPercentCompleteTotal(taskArt, AtsClientService.get().getServices()); } size = taskArts.size(); TeamWorkFlowArtifact teamWf = (TeamWorkFlowArtifact) artifact; Collection<IAtsAbstractReview> reviewArts = AtsClientService.get().getReviewService().getReviews(teamWf); for (IAtsAbstractReview reviewArt : reviewArts) { spent += PercentCompleteTotalUtil.getPercentCompleteTotal(reviewArt, AtsClientService.get().getServices()); } size += reviewArts.size(); } if (size == 0) { return 0; } return spent / size; }
Source:
<code>public void awake_sleeping_awake_sleeping() { queueModeHelper.assertClientNotRegisterered(); queueModeHelper.client.start(); queueModeHelper.waitForRegistration(1); queueModeHelper.assertClientRegisterered(); assertArrayEquals(Link.parse("</>;rt=\"oma.lwm2m\",</1/0>,</2>,</3/0>,</2000/0>".getBytes()), queueModeHelper.getCurrentRegistration().getObjectLinks()); queueModeHelper.ensureClientAwake(); queueModeHelper.waitForAwakeTime(queueModeHelper.awaketime * 1010); queueModeHelper.ensureClientSleeping(); if (queueModeHelper.sleeptime != 0) { <START> queueModeHelper.waitForUpdate(queueModeHelper.sleeptime * 1010); <END> } else { queueModeHelper.waitForUpdate(1); } queueModeHelper.ensureClientAwake(); queueModeHelper.resetAwakeLatch(); queueModeHelper.waitForAwakeTime(queueModeHelper.awaketime * 1010); queueModeHelper.ensureClientSleeping(); queueModeHelper.client.stop(false); }</code><technical_language>/!\ WaitForUpdate timeout is in seconds milliseconds Check code, a lot update timeout >= 1000</technical_language>

Target:
public void awake_sleeping_awake_sleeping() { queueModeHelper.assertClientNotRegisterered(); queueModeHelper.client.start(); queueModeHelper.waitForRegistration(1); queueModeHelper.assertClientRegisterered(); assertArrayEquals(Link.parse("</>;rt=\"oma.lwm2m\",</1/0>,</2>,</3/0>,</2000/0>".getBytes()), queueModeHelper.getCurrentRegistration().getObjectLinks()); queueModeHelper.ensureClientAwake(); queueModeHelper.waitForAwakeTime(awaketime * 1010); queueModeHelper.ensureClientSleeping(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.ensureClientAwake(); queueModeHelper.resetAwakeLatch(); queueModeHelper.waitForAwakeTime(awaketime * 1010); queueModeHelper.ensureClientSleeping(); queueModeHelper.client.stop(false); }
Source:
<code>public void endReporting() { if (!initialized()) { return; } if (startedReporting) { telescopeClient.endIngest(taskId); stoppedReporting = true; <START> log.debug("Finished reporting to Telescope (taskId:)", taskId); <END> } else { log.warn("Someone tried to stop a telescope report that has never started"); } }</code><technical_language>I missed a {}</technical_language>

Target:
public void endReporting() { if (!initialized()) { return; } if (startedReporting) { telescopeClient.endIngest(taskId); stoppedReporting = true; log.debug("Finished reporting to Telescope, taskId={}", taskId); } else { log.warn("Someone tried to stop a telescope report that has never started"); } }
Source:
<code><START> public void testResetPassword_shouldUpdatePassword() { <END> String username = "superuser"; PasswordResetBackingForm form = aPasswordResetBackingForm().withUsername(username).build(); controllerService.resetPassword(form); }</code><technical_language>@tumijacob This test testing anything</technical_language>

Target:
public void testResetPassword_shouldUpdatePassword() { String username = "superuser"; PasswordResetBackingForm form = aPasswordResetBackingForm().withUsername(username).build(); controllerService.resetPassword(form); verify(passwordResetService).resetUserPassword(username); }
Source:
<code>private static int getRotationAngle(RotationOptions rotationOptions, EncodedImage encodedImage) { if (!rotationOptions.rotationEnabled()) { return RotationOptions.NO_ROTATION; } int rotationFromMetadata = extractOrientationFromMetadata(encodedImage); if (rotationOptions.useImageMetadata()) { return rotationFromMetadata; } int angle = rotationFromMetadata + rotationOptions.getForcedAngle(); <START> while (angle >= FULL_ROUND) { <END> angle -= FULL_ROUND; } return angle; }</code><technical_language>this while loop, simply return angle % FULL_ROUND</technical_language>

Target:
private static int getRotationAngle(RotationOptions rotationOptions, EncodedImage encodedImage) { if (!rotationOptions.rotationEnabled()) { return RotationOptions.NO_ROTATION; } int rotationFromMetadata = extractOrientationFromMetadata(encodedImage); if (rotationOptions.useImageMetadata()) { return rotationFromMetadata; } return (rotationFromMetadata + rotationOptions.getForcedAngle()) % FULL_ROUND; }
Source:
<code>public synchronized Environment findOne(String application, String profile, String label) { NativeEnvironmentRepository delegate = new NativeEnvironmentRepository( getEnvironment()); Locations locations = getLocations(application, profile, label); delegate.setSearchLocations(locations.getLocations()); Environment result = delegate.findOne(application, profile, ""); result.setVersion(locations.getVersion()); result.setLabel(label); StringBuilder state = new StringBuilder(); if(locations.getTimestamp() > 0) { Date date = new Date(locations.getTimestamp()); state.append(DateFormat.getDateTimeInstance().format(date)); state.append(" "); } state.append(locations.getInfo()); <START> result.setState(state.toString()); <END> return this.cleaner.clean(result, getWorkingDirectory().toURI().toString(), getUri()); }</code><technical_language>Environment.state included for client side state, server side</technical_language>

Target:
public synchronized Environment findOne(String application, String profile, String label) { NativeEnvironmentRepository delegate = new NativeEnvironmentRepository( getEnvironment()); Locations locations = getLocations(application, profile, label); delegate.setSearchLocations(locations.getLocations()); Environment result = delegate.findOne(application, profile, ""); result.setVersion(locations.getVersion()); result.setLabel(label); StringBuilder additionalInfo = new StringBuilder(); if(locations.getTimestamp() > 0) { Date date = new Date(locations.getTimestamp()); additionalInfo.append(DateFormat.getDateTimeInstance().format(date)); additionalInfo.append(" "); } additionalInfo.append(locations.getInfo()); result.setDescription(additionalInfo.toString()); return this.cleaner.clean(result, getWorkingDirectory().toURI().toString(), getUri()); }
Source:
<code>public void registersExpectedExceptionMetrics() throws Exception { ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress("localhost", 0)); final HttpGet get = new HttpGet("http://localhost:" + server.getLocalPort() + "/"); final MetricName requestMetricName = MetricName.build("request"); final MetricName exceptionMetricName = MetricName.build("exception"); Thread serverThread = new Thread(() -> { try { final Socket socket = server.accept(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }); serverThread.start(); when(metricNameStrategy.getNameFor(anyString(), any(HttpRequest.class))) .thenReturn(requestMetricName); when(metricNameStrategy.getNameFor(anyString(), any(Exception.class))) .thenReturn(exceptionMetricName); try { client.execute(get); fail(); } catch (NoHttpResponseException expected) { } serverThread.interrupt(); <START> serverThread.join(); <END> assertThat(metricRegistry.getMeters()).containsKey(new MetricName("exception")); }</code><technical_language>I move cleanup code finally block in case *actually* a failed test case</technical_language>

Target:
public void registersExpectedExceptionMetrics() throws Exception { ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress("localhost", 0)); final HttpGet get = new HttpGet("http://localhost:" + server.getLocalPort() + "/"); final MetricName requestMetricName = MetricName.build("request"); final MetricName exceptionMetricName = MetricName.build("exception"); Thread serverThread = new Thread(() -> { try { final Socket socket = server.accept(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }); serverThread.start(); when(metricNameStrategy.getNameFor(anyString(), any(HttpRequest.class))) .thenReturn(requestMetricName); when(metricNameStrategy.getNameFor(anyString(), any(Exception.class))) .thenReturn(exceptionMetricName); try { client.execute(get); fail(); } catch (NoHttpResponseException expected) { assertThat(metricRegistry.getMeters()).containsKey(new MetricName("exception")); } finally { serverThread.interrupt(); serverThread.join(); } }
Source:
<code>private Collection<Container> distributeForRequestedCount(List<Container> candidates, int count) { int candidateCount = candidates.size(); if (candidateCount == 0) { return candidates; } if (count <= 0 || count >= candidateCount) { return candidates; } else if (count == 1) { <START> Collection<Container> targets = Collections.singleton(candidates.get(getAndRotateIndex(candidateCount))); <END> return targets; } else { List<Container> targets = new ArrayList<Container>(); while (targets.size() < count) { targets.add(candidates.get(getAndRotateIndex(candidateCount))); } return targets; } }</code><technical_language>simply return of Collections.singleton(...) instead of assigning variable targets</technical_language>

Target:
private Collection<Container> distributeForRequestedCount(List<Container> candidates, int count) { int candidateCount = candidates.size(); if (candidateCount == 0) { return candidates; } if (count <= 0 || count >= candidateCount) { return candidates; } else if (count == 1) { return Collections.singleton(candidates.get(getAndRotateIndex(candidateCount))); } else { List<Container> targets = new ArrayList<Container>(); while (targets.size() < count) { targets.add(candidates.get(getAndRotateIndex(candidateCount))); } return targets; } }
Source:
<code>private void flattenList(List<K> unflat, List<K> flat) { unflat.forEach(x -> { <START> if (x instanceof KItem && ((KItem) x).klabel().toString().equals(KLabels.AND)) { <END> flattenList(((KItem) x).items(), flat); } else { flat.add(x); } }); }</code><technical_language>do check equality based toString</technical_language>

Target:
private void flattenList(List<K> unflat, List<K> flat) { unflat.forEach(x -> { if (x instanceof KItem && ((KItem) x).klabel().name().equals(KLabels.AND)) { flattenList(((KItem) x).items(), flat); } else { flat.add(x); } }); }
Source:
<code>protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = cacheConfiguration(); <START> dcc.clustering().cacheMode(cacheMode).partitionHandling().whenSplit(partitionHandling); <END> createClusteredCaches(numMembersInCluster, dcc, new TransportFlags().withFD(true).withMerge(true)); waitForClusterToForm(CLUSTERED_LOCK_CACHE_NAME); }</code><technical_language>remove partition handling stuff well, hard-code cache mode. set this.cacheMode = null in constructor, REPL_SYNC in test reports (because default cache all)</technical_language>

Target:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = cacheConfiguration(); dcc.clustering().cacheMode(CacheMode.REPL_SYNC).partitionHandling().whenSplit(partitionHandling); createClusteredCaches(numMembersInCluster, dcc, new TransportFlags().withFD(true).withMerge(true)); waitForClusterToForm(CLUSTERED_LOCK_CACHE_NAME); }
Source:
<code>private <Info, Context, Handle extends AbstractChannelStateHandle<Info>> void readSequentially( StreamStateHandle streamStateHandle, List<Handle> channelStateHandles, RecoveredChannelStateHandler<Info, Context> stateHandler) throws IOException { try (FSDataInputStream is = streamStateHandle.openInputStream()) { serializer.readHeader(is); for (Tuple2<Long, Info> offsetAndChannelInfo : extractOffsetsSorted(channelStateHandles)) { chunkReader.readChunk(is, offsetAndChannelInfo.f0, stateHandler, offsetAndChannelInfo.f1); } } <START> } <END></code><technical_language>offsets unsorted? Is this more of a precaution is common? Is small file optimization</technical_language>

Target:
private <Info, Context, Handle extends AbstractChannelStateHandle<Info>> void readSequentially( StreamStateHandle streamStateHandle, List<Handle> channelStateHandles, RecoveredChannelStateHandler<Info, Context> stateHandler) throws IOException, InterruptedException { try (FSDataInputStream is = streamStateHandle.openInputStream()) { serializer.readHeader(is); for (Tuple2<Long, Info> offsetAndChannelInfo : extractOffsetsSorted(channelStateHandles)) { chunkReader.readChunk(is, offsetAndChannelInfo.f0, stateHandler, offsetAndChannelInfo.f1); } } }
Source:
<code>public synchronized boolean tryLock() { _baseDataAccessor.subscribeDataChanges(_lockPath, this); LockUpdater updater = new LockUpdater( new LockInfo(_userId, _lockMsg, getNonOverflowTimestamp(_leaseTimeout), _priority, _waitingTimeout, _cleanupTimeout, null, 0, 0, 0)); boolean updateResult = _baseDataAccessor.update(_lockPath, updater, AccessOption.PERSISTENT); <START> if (_isPending) { <END> try { wait(_pendingTimeout); } catch (InterruptedException e) { throw new HelixException( String.format("Interruption happened while %s is waiting for the " + "lock", _userId), e); } if (!_isLocked) { if (_isPreempted) { return false; } else { if (_isForceful) { ZNRecord znRecord = composeNewOwnerRecord(); LOG.info("Updating Zookeeper with new owner information", _userId); _baseDataAccessor .update(_lockPath, new ZNRecordUpdater(znRecord), AccessOption.PERSISTENT); return true; } else { throw new HelixException("Cleanup has not been finished by lock owner"); } } } } return updateResult; }</code><technical_language>Usually, if waiting for something, while do checks here</technical_language>

Target:
public boolean tryLock() { _baseDataAccessor.subscribeDataChanges(_lockPath, this); LockUpdater updater = new LockUpdater( new LockInfo(_userId, _lockMsg, getNonOverflowTimestamp(_leaseTimeout), _priority, _waitingTimeout, _cleanupTimeout, null, 0, 0, 0)); boolean updateResult = _baseDataAccessor.update(_lockPath, updater, AccessOption.PERSISTENT); ENDING. if (_lockStatus != LockConstants.LockStatus.PENDING) { if (!updateResult) { _baseDataAccessor.unsubscribeDataChanges(_lockPath, this); } return updateResult; } try { _countDownLatch.await(_pendingTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new HelixException( String.format("Interruption happened while %s is waiting for the lock", _userId), e); } if (_lockStatus != LockConstants.LockStatus.LOCKED) { if (_lockStatus == LockConstants.LockStatus.PREEMPTED) { _baseDataAccessor.unsubscribeDataChanges(_lockPath, this); return false; } if (_isForceful) { ZNRecord znRecord = composeNewOwnerRecord(); ForcefulUpdater forcefulUpdater = new ForcefulUpdater(new LockInfo(znRecord)); LOG.info("Updating Zookeeper with new owner information", _userId); _baseDataAccessor.update(_lockPath, forcefulUpdater, AccessOption.PERSISTENT); return true; } else { _baseDataAccessor.unsubscribeDataChanges(_lockPath, this); throw new HelixException("Cleanup has not been finished by lock owner"); } } return true; }
Source:
<code>public String getName() { String name = super.getName(); <START> if (name == null || name.isEmpty()) { <END> return ""; } else { return name; } }</code><technical_language>isEmpty method for Strings in Utils. Is good idea well? <LINK_0></technical_language>

Target:
public String getName() { String name = super.getName(); if (StringUtils.isEmpty(name)) { return ""; } else { return name; } }
Source:
<code>public void testListDroplets() { List<Droplet> droplets = api.getDropletApi().list(); <START> assertTrue(droplets.size() > 0, "Droplet list should not be empty"); <END> }</code><technical_language>!droplets.isEmpty()</technical_language>

Target:
public void testListDroplets() { List<Droplet> droplets = api.getDropletApi().list(); assertFalse(droplets.isEmpty(), "Droplet list should not be empty"); }
Source:
<code>public List<String> listAllConsumers() { long now = System.currentTimeMillis(); if (allConsumers == null || (now - allConsumersTime) > ALL_CONSUMERS_CACHE_TIMEOUT_MS) { try { allConsumers = getAdminClient().listConsumerGroups() .all() .get() .stream() <START> .map(group -> group.groupId()) <END> .collect(Collectors.toList()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new StreamRuntimeException(e); } catch (ExecutionException e) { throw new StreamRuntimeException(e); } if (!allConsumers.isEmpty()) { allConsumersTime = now; } } return allConsumers; }</code><technical_language>map(ConsumerGroupListing::groupId)</technical_language>

Target:
public synchronized List<String> listAllConsumers() { long now = System.currentTimeMillis(); if (allConsumers == null || (now - allConsumersTime) > ALL_CONSUMERS_CACHE_TIMEOUT_MS) { try { allConsumers = adminClient.listConsumerGroups() .all() .get() .stream() .map(ConsumerGroupListing::groupId) .collect(Collectors.toList()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new StreamRuntimeException(e); } catch (ExecutionException e) { throw new StreamRuntimeException(e); } if (!allConsumers.isEmpty()) { allConsumersTime = now; } } return allConsumers; }
Source:
<code>public void populateEntityDictionary(EntityDictionary dictionary) { if (dynamicCompiledClasses != null && dynamicCompiledClasses.size() != 0) { dynamicCompiledClasses.forEach(dynamicLoadedClass -> dictionary.bindEntity(dynamicLoadedClass, Collections.singleton(Join.class))); } ClassScanner.getAnnotatedClasses(AGGREGATION_STORE_CLASSES).forEach( <START> cls -> dictionary.bindEntity(getType(cls), Collections.singleton(Join.class)) <END> ); }</code><technical_language>bind entity class deferring a type</technical_language>

Target:
public void populateEntityDictionary(EntityDictionary dictionary) { if (dynamicCompiledClasses != null && dynamicCompiledClasses.size() != 0) { dynamicCompiledClasses.forEach(dynamicLoadedClass -> dictionary.bindEntity(dynamicLoadedClass, Collections.singleton(Join.class))); } ClassScanner.getAnnotatedClasses(AGGREGATION_STORE_CLASSES).forEach( cls -> dictionary.bindEntity(cls, Collections.singleton(Join.class)) ); }
Source:
<code>public void postLoadingHook(ResourceSet resourceSet, Collection<? extends URI> uris) { for (Resource resource : resourceSet.getResources()) { <START> if ((resource.getURI().fileExtension()).equals("notation")) { END> EList<EObject> contents = resource.getContents(); for (EObject object : contents) { if (object instanceof CSSDiagramImpl) { Diagram diagram = (Diagram)object; diagramMigration(getEditingDomain(resourceSet), diagram); } } } } }</code><technical_language>"notation".equals(resource.getURI().fileExtension()) avoid potential NPEs</technical_language>

Target:
public void postLoadingHook(ResourceSet resourceSet, Collection<? extends URI> uris) { for (Resource resource : resourceSet.getResources()) { if ("notation".equals(resource.getURI().fileExtension())) { EList<EObject> contents = resource.getContents(); for (EObject object : contents) { if (object instanceof Diagram) { Diagram diagram = (Diagram)object; diagramMigration(getEditingDomain(resourceSet), diagram); } } } } }
Source:
<code><START> public void testFoldLeftWithDirectionDependentOperationOnNonEmptyList() { <END> assertEquals( new Integer(0), ListOps.foldLeft( Arrays.asList(2, 5), 5, (accumulation, current) -> accumulation / current)); }</code><technical_language>is this direction dependent? I understand operation in is numbers get answer matter direction traverse list you? a test if case</technical_language>

Target:
public void testFoldLeftWithDirectionDependentOperationOnNonEmptyList() { assertEquals( new Integer(0), ListOps.foldLeft( Arrays.asList(2, 5), 5, (x, y) -> x / y)); }
Source:
<code>public void configure(final HttpSecurity http) throws Exception { LOG.info("Authentication mode: " + settings.getAuthMode()); if (settings.getAuthMode() == SecuritySettings.AuthMode.FULL) { http.authorizeRequests() .antMatchers(GET, "/event-types events events cursors events **").access(hasScope(nakadiAdminScope)) .antMatchers(POST, "/event-types/**").access(hasScope(eventTypeWriteScope)) .antMatchers(PUT, "/event-types/**").access(hasScope(eventTypeWriteScope)) .antMatchers(POST, "/subscriptions/**").access(hasScope(eventStreamReadScope)) <START> .antMatchers(GET, "/subscriptions/**").access(hasScope(eventStreamReadScope)) <END> .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else if (settings.getAuthMode() == SecuritySettings.AuthMode.BASIC) { http.authorizeRequests() .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else { http.authorizeRequests() .anyRequest().permitAll(); } }</code><technical_language>antMatchers(GET, "/subscriptions/_/events/_*").access(hasScope(eventStreamReadScope)) I I this line covers this case .antMatchers(GET, "/subscriptions/**").access(hasScope(eventStreamReadScope)) do</technical_language>

Target:
public void configure(final HttpSecurity http) throws Exception { LOG.info("Authentication mode: " + settings.getAuthMode()); if (settings.getAuthMode() == SecuritySettings.AuthMode.FULL) { http.authorizeRequests() .antMatchers(GET, "/event-types events events cursors cursors events **").access(hasScope(nakadiAdminScope)) .antMatchers(POST, "/event-types **").access(hasScope(eventStreamReadScope)) .antMatchers(POST, "/subscriptions/**").access(hasScope(eventStreamReadScope)) .antMatchers(GET, "/subscriptions/**").access(hasScope(eventStreamReadScope)) .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else if (settings.getAuthMode() == SecuritySettings.AuthMode.BASIC) { http.authorizeRequests() .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else { http.authorizeRequests() .anyRequest().permitAll(); } }
Source:
<code>public void sweep(Collection<WriteInfo> writes, Sweeper sweeper) { Map<TableReference, Map<Cell, Long>> maxTimestampByCell = writesPerTable(writes, sweeper); for (Map.Entry<TableReference, Map<Cell, Long>> entry : maxTimestampByCell.entrySet()) { try { Iterables.partition(entry.getValue().keySet(), SweepQueueUtils.BATCH_SIZE_KVS) .forEach(cells -> { Map<Cell, Long> maxTimestampByCellPartition = cells.stream() .collect(Collectors.toMap(Function.identity(), entry.getValue()::get)); follower.run(entry.getKey(), maxTimestampByCellPartition.keySet()); if (sweeper.shouldAddSentinels()) { kvs.addGarbageCollectionSentinelValues(entry.getKey(), maxTimestampByCellPartition.keySet()); kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition, false); } else { kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition, true); } }); } catch (IllegalArgumentException e) { <START> if (e.getCause() instanceof TableMappingNotFoundException <END> || e.getMessage().endsWith("does not exist")) { log.debug("Could not resolve full name for table reference {}, " + "assuming table has been deleted and therefore relevant cells as well.", LoggingArgs.tableRef(entry.getKey())); log.trace("Stack trace follows:", e); } else { throw e; } } } }</code><technical_language>Is other reason a TableMapingNotFoundryException thrown? a table renamed name in TS queue is out of date</technical_language>

Target:
public void sweep(Collection<WriteInfo> writes, Sweeper sweeper) { Map<TableReference, Map<Cell, Long>> maxTimestampByCell = writesPerTable(writes, sweeper); for (Map.Entry<TableReference, Map<Cell, Long>> entry : maxTimestampByCell.entrySet()) { try { Iterables.partition(entry.getValue().keySet(), SweepQueueUtils.BATCH_SIZE_KVS) .forEach(cells -> { Map<Cell, Long> maxTimestampByCellPartition = cells.stream() .collect(Collectors.toMap(Function.identity(), entry.getValue()::get)); follower.run(entry.getKey(), maxTimestampByCellPartition.keySet()); if (sweeper.shouldAddSentinels()) { kvs.addGarbageCollectionSentinelValues(entry.getKey(), maxTimestampByCellPartition.keySet()); kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition, false); } else { kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition, true); } }); } catch (IllegalArgumentException e) { if (e.getCause() instanceof TableMappingNotFoundException || e.getMessage().endsWith("does not exist")) { log.warn("Could not resolve full name for table reference {}, " + "assuming table has been deleted and therefore relevant cells as well.", LoggingArgs.tableRef(entry.getKey())); log.debug("Stack trace follows:", e); } else { throw e; } } } }
Source:
<code>public static List<IpNode> fromString(String addrString, int defaultPort) { List<IpNode> ipNodes = new ArrayList<IpNode>(); int port; for (String singleAddrString : addrString.split(",")) { Matcher addrMatch = ADDR_PATTERN.matcher(singleAddrString); if (addrMatch.matches()) { port = (addrMatch.group(2).isEmpty()) ? defaultPort : Integer.valueOf(addrMatch.group(2)); ipNodes.add(new IpNode(addrMatch.group(1), port)); } else { <START> logger.warn("Node definition is not valid.", singleAddrString); <END> } } return ipNodes; }</code><technical_language>If is a software bug get here, exception, stack trace is in logs for reporting bug. If get of a user misconfiguration, this caught else properly reported user status</technical_language>

Target:
public static List<IpNode> fromString(String addrString, int defaultPort) throws IllegalArgumentException { List<IpNode> ipNodes = new ArrayList<IpNode>(); int port; for (String singleAddrString : addrString.split(",")) { Matcher addrMatch = ADDR_PATTERN.matcher(singleAddrString); if (addrMatch.matches()) { port = (addrMatch.group(2).isEmpty()) ? defaultPort : Integer.valueOf(addrMatch.group(2)); ipNodes.add(new IpNode(addrMatch.group(1), port)); } else { throw new IllegalArgumentException(String.format("Node definition is not valid.", singleAddrString)); } } return ipNodes; }
Source:
<code>public NodeSelectionStrategy getNodeSelectionStrategy() { <START> return NodeSelectionStrategy.HARD_AFFINITY; <END> }</code><technical_language>static import</technical_language>

Target:
public NodeSelectionStrategy getNodeSelectionStrategy() { return HARD_AFFINITY; }
Source:
<code>private ValidationResult hostExists() { <START> if (getVds() == null) { <END> return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST); } return ValidationResult.VALID; }</code><technical_language>ternary if for this: return getVds() == null ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST) : ValidationResult.VALID;</technical_language>

Target:
private ValidationResult hostExists() { return getVds() == null ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST) : ValidationResult.VALID; }
Source:
<code>private Optional<Class<Event>> getEventForTransition(ChargeStatus fromChargeStatus, ChargeEventEntity chargeEventEntity) { Optional<Class<Event>> eventForTransition = paymentGatewayStateTransitions .getEventForTransition(fromChargeStatus, chargeEventEntity.getStatus()); if (eventForTransition.isEmpty()) { Optional<ChargeStatus> intermediateChargeStatus = paymentGatewayStateTransitions .getIntermediateChargeStatus(fromChargeStatus, chargeEventEntity.getStatus()); <START> if (intermediateChargeStatus.isPresent() && INTEMEDIATE_READY_STATES.contains(intermediateChargeStatus.get())) { <END> eventForTransition = paymentGatewayStateTransitions .getEventForTransition(intermediateChargeStatus.get(), chargeEventEntity.getStatus()); } else { logger.info("Historical Event emitter for Charge and Event - Couldn't derive event for transition from to [{}]", chargeEventEntity.getChargeEntity().getId(), chargeEventEntity.getId(), fromChargeStatus, chargeEventEntity.getStatus() ); } } return eventForTransition; }</code><technical_language>sense put this top of method cases intermediate state exist? simplify this method a lot, like: java ChargeStatus currentEventStatus = chargeEventEntity.getStatus(); if (INTERMEDIATE_READY_STATES.contains(currentEventStatus)) { return paymentGatewayStateTransitions.getIntermediateChargeStatus(fromChargeStatus, chargeEventStatus) .map(intermediate -> paymentGatewayStateTransitions.getEventForTransition(intermediate.get(), currentEventStatus); } else { return paymentGatewayStateTransitions.getEventForTransition(fromChargeStatus, currentEventStatus); }</technical_language>

Target:
private Optional<Class<Event>> getEventForTransition(ChargeStatus fromChargeStatus, ChargeEventEntity chargeEventEntity) { Optional<Class<Event>> eventForTransition = paymentGatewayStateTransitions .getEventForTransition(fromChargeStatus, chargeEventEntity.getStatus()); if (eventForTransition.isEmpty()) { Optional<ChargeStatus> intermediateChargeStatus = paymentGatewayStateTransitions .getIntermediateChargeStatus(fromChargeStatus, chargeEventEntity.getStatus()); if (intermediateChargeStatus.isPresent() && INTERMEDIATE_READY_STATES.contains(intermediateChargeStatus.get())) { eventForTransition = paymentGatewayStateTransitions .getEventForTransition(intermediateChargeStatus.get(), chargeEventEntity.getStatus()); } else { logger.info("Historical Event emitter for Charge and Event - Couldn't derive event for transition from to [{}]", chargeEventEntity.getChargeEntity().getId(), chargeEventEntity.getId(), fromChargeStatus, chargeEventEntity.getStatus() ); } } return eventForTransition; }
Source:
<code>public void optionalAbsent() { Optional<Integer> shouldBeAbsent = db.getSharedHandle().createQuery("select intValue from something where intValue = 100") .mapTo(int.class) .collect(GuavaCollectors.toOptional()); <START> assertThat(shouldBeAbsent.isPresent()).isFalse(); <END> }</code><technical_language>Meh: assertj-guava artifact for these</technical_language>

Target:
public void optionalAbsent() { Optional<Integer> shouldBeAbsent = db.getSharedHandle().createQuery("select intValue from something where intValue = 100") .mapTo(int.class) .collect(GuavaCollectors.toOptional()); assertThat(shouldBeAbsent).isAbsent(); }
Source:
<code>public LogReplicationEntry read(UUID logEntryRequestId) throws TrimmedException, IllegalTransactionStreamsException { List<OpaqueEntry> opaqueEntryList = new ArrayList<>(); int currentEntrySize = 0; int currentMsgSize = 0; try { while (currentMsgSize < maxDataSizePerMsg && !hasNoiseData) { if (lastOpaqueEntry != null && shouldProcess(lastOpaqueEntry)) { currentEntrySize = ReaderUtility.calculateOpaqueEntrySize(lastOpaqueEntry); if (!checkSizeOK(lastOpaqueEntry, currentMsgSize, currentEntrySize)) { break; } opaqueEntryList.add(lastOpaqueEntry); currentMsgSize += currentEntrySize; lastOpaqueEntry = null; } <START> if (hasNoiseData) { <END> break; } if (!txOpaqueStream.hasNext()) { break; } lastOpaqueEntry = txOpaqueStream.next(); } log.trace("Generate LogEntryDataMessage size with entries for maxDataSizePerMsg {}. lastEnry size {}", currentMsgSize, opaqueEntryList.size(), maxDataSizePerMsg, lastOpaqueEntry == null? 0 : currentEntrySize); if (opaqueEntryList.size() == 0 && hasNoiseData) { throw new IllegalTransactionStreamsException("There are noisy streams in the transaction log entry"); } if (opaqueEntryList.size() == 0) { return null; } LogReplicationEntry txMessage = generateMessageWithOpaqueEntryList(opaqueEntryList, logEntryRequestId); return txMessage; } catch (Exception e) { log.warn("Caught an exception {}", e); throw e; } }</code><technical_language>need break is in while condition, if want break while loop remove loop</technical_language>

Target:
public LogReplicationEntry read(UUID logEntryRequestId) throws TrimmedException, IllegalTransactionStreamsException { List<OpaqueEntry> opaqueEntryList = new ArrayList<>(); int currentEntrySize = 0; int currentMsgSize = 0; try { while (currentMsgSize < maxDataSizePerMsg && !hasNoiseData) { if (lastOpaqueEntry != null && shouldProcess(lastOpaqueEntry)) { currentEntrySize = ReaderUtility.calculateOpaqueEntrySize(lastOpaqueEntry); if (!checkValidSize(lastOpaqueEntry, currentMsgSize, currentEntrySize)) { break; } opaqueEntryList.add(lastOpaqueEntry); currentMsgSize += currentEntrySize; lastOpaqueEntry = null; } if (hasNoiseData) { break; } if (!txOpaqueStream.hasNext()) { break; } lastOpaqueEntry = txOpaqueStream.next(); } log.trace("Generate LogEntryDataMessage size with entries for maxDataSizePerMsg {}. lastEnry size {}", currentMsgSize, opaqueEntryList.size(), maxDataSizePerMsg, lastOpaqueEntry == null? 0 : currentEntrySize); if (opaqueEntryList.size() == 0 && hasNoiseData) { throw new IllegalTransactionStreamsException("There are noisy streams in the transaction log entry"); } if (opaqueEntryList.size() == 0) { return null; } LogReplicationEntry txMessage = generateMessageWithOpaqueEntryList(opaqueEntryList, logEntryRequestId); return txMessage; } catch (Exception e) { log.warn("Caught an exception {}", e); throw e; } }
Source:
<code>public Transceiver getCommentCount(Article article) { return new Transceiver() { @Override protected Object getData() throws IOException { Object result = hibernateTemplate.execute(session -> { Query query = session.createQuery("" + "SELECT NEW MAP(COUNT(*) AS all, SUM(CASE WHEN ann.parentID IS NULL THEN 1 ELSE 0 END) AS root) " + "FROM Annotation ann " + "WHERE ann.articleID = :articleID "); query.setParameter("articleID", article.getID()); <START> return query.uniqueResult(); <END> }); return result; } @Override protected Calendar getLastModifiedDate() throws IOException { return null; } }; }</code><technical_language>thing. I is interesting case for a "heavy-handed" view in this case... intuition is odd view output's root strings originate in middle of a SQL query. smells action-at-a-distance layers. well, a debate for another time if is interested</technical_language>

Target:
public Transceiver getCommentCount(Article article) { return new Transceiver() { @Override protected Map<String, Object> getData() throws IOException { Map<String, Object> result = (Map<String, Object>) hibernateTemplate.execute(session -> { Query query = session.createQuery("" + "SELECT NEW MAP(COUNT(*) AS all, SUM(CASE WHEN ann.parentID IS NULL THEN 1 ELSE 0 END) AS root) " + "FROM Annotation ann " + "WHERE ann.articleID = :articleID "); query.setParameter("articleID", article.getID()); return query.uniqueResult(); }); return result; } @Override protected Calendar getLastModifiedDate() throws IOException { return null; } }; }
Source:
<code>public PagingResponse<CandidateApplicationDTO> getApplicationsByCandidateId( Long candidateId, int page, int size) { Assert.notNull(candidateId); CandidateEntity candidateEntity = candidateRepository.findOne(candidateId); Pageable pageRequest = new PageRequest(page, size); Page<ApplicationEntity> pageResult = applicationsRepository.findByCandidateEntity(candidateEntity, pageRequest); <START> List<ApplicationEntity> applicationEntities = pageResult.getContent(); <END> List<CandidateApplicationDTO> candidateApplicationDTOs = converterService.convert(applicationEntities, CandidateApplicationDTO.class); Long total = pageResult.getTotalElements(); PagingResponse<CandidateApplicationDTO> response = new PagingResponse<>(total, candidateApplicationDTOs); return response; }</code><technical_language>this local variable is important. is 1 call, "pageResult.getContent()" there, if this local variable, final</technical_language>

Target:
public PagingResponse<CandidateApplicationDTO> getApplicationsByCandidateId( Long candidateId, int page, int size) { Assert.notNull(candidateId); CandidateEntity candidateEntity = candidateRepository.findOne(candidateId); Pageable pageRequest = new PageRequest(page, size); final Page<ApplicationEntity> pageResult = applicationsRepository.findByCandidateEntity(candidateEntity, pageRequest); List<CandidateApplicationDTO> candidateApplicationDTOs = converterService.convert(pageResult.getContent(), CandidateApplicationDTO.class); candidateApplicationDTOs = candidateApplicationDTOs.stream() .sorted((m1, m2) -> m2.getModificationDate().compareTo(m1.getModificationDate())) .collect(Collectors.toList()); return new PagingResponse<>(pageResult.getTotalElements(), candidateApplicationDTOs); }
Source:
<code><START> public void dismiss() { <END> DialogFragment dialog = (DialogFragment) activity.getSupportFragmentManager().findFragmentByTag(BOTTOM_SHEET_FRAGMENT_TAG); if (dialog != null) { dialog.dismiss(); } if (currentDialog != null && currentDialog.isShowing()) { currentDialog.dismiss(); } currentDialog = null; }</code><technical_language>Sorry, I clear earlier. I thinking: public void dismiss() { DialogFragment dialog = findFragmentByTag(); if (dialog != null) { dialog.dismiss(); } if (currentDialog != null) { currentDialog.setOnDismissListener(null); if (currentDialog.isShowing()) { // Is this conditional necessary? currentDialog.dismiss(); } } currentDialog = null; } reason is this scenario: 1 Client calls show(Dialog). 2 Client calls dismiss(). 3 Client calls show(Dialog) // dialog 4 System calls OnDismissListener.onDismiss. 5 Client calls dismiss() currentDialog is null Dialog dismiss</technical_language>

Target:
public void dismiss() { DialogFragment dialog = (DialogFragment) activity.getSupportFragmentManager().findFragmentByTag(BOTTOM_SHEET_FRAGMENT_TAG); if (dialog != null) { dialog.dismiss(); } if (currentDialog != null) { currentDialog.setOnDismissListener(null); currentDialog.dismiss(); } currentDialog = null; }
Source:
<code><START> public static <T> void checkPresence(Optional<T> opt, String errorMessage) <END> { if (!opt.isPresent()) { throw new TDClientException(TDClientException.ErrorType.INVALID_INPUT, errorMessage); } }</code><technical_language>this method private</technical_language>

Target:
private static <T> void checkPresence(Optional<T> opt, String errorMessage) { if (!opt.isPresent()) { throw new TDClientException(TDClientException.ErrorType.INVALID_INPUT, errorMessage); } }
Source:
<code>public void setup() { this.map = targetInstance.getMap(name); <START> generatedIds = generateStrings(keyCount, idLength); <END> }</code><technical_language>This lead a huge amount of data in memory; is readonly</technical_language>

Target:
public void setup() { this.map = targetInstance.getMap(name); }
Source:
<code>public static void main(String[] args) { FormTrainingAsyncClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_Key}")) .endpoint("https://{endpoint}.cognitiveservices.azure.com/") .buildAsyncClient().getFormTrainingAsyncClient(); <START> String trainingSetSource = "https://training-SAS-URL"; <END> PollerFlux<OperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingSetSource, true); CustomFormModel customFormModel = trainingPoller .last() .flatMap(trainingOperationResponse -> { if (trainingOperationResponse.getStatus().equals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)) { return trainingOperationResponse.getFinalResult(); } else { System.out.println("Polling completed unsuccessfully with status:" + trainingOperationResponse.getStatus()); return Mono.empty(); } }).block(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }</code><technical_language>Is this supposed a valid URL</technical_language>

Target:
public static void main(String[] args) { FormTrainingAsyncClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_Key}")) .endpoint("https://{endpoint}.cognitiveservices.azure.com/") .buildAsyncClient().getFormTrainingAsyncClient(); String trainingSetSource = "{training-set-SAS-URL}"; PollerFlux<OperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingSetSource, true); CustomFormModel customFormModel = trainingPoller .last() .flatMap(trainingOperationResponse -> { if (trainingOperationResponse.getStatus().equals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)) { return trainingOperationResponse.getFinalResult(); } else { return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:" + trainingOperationResponse.getStatus())); } }).block(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }