auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void run() { MessageContext context = null; ObjectMapper mapper = new ObjectMapper(); while (true) { try { context = this.queue.take(); if (context.getClient() == null) { break; } if (log.isDebugEnabled()) { log.debug("Message received: " + new String(context.getMessage(), UTF8)); } JsonNode rootNode = mapper.readTree(context.getMessage()); if (!rootNode.isArray()) { processIncomingObject(context.getClient(), rootNode); } else { final Iterator<JsonNode> iter = rootNode.getElements(); while (iter.hasNext()) { final JsonNode node = iter.next(); processIncomingObject(context.getClient(), node); } } } catch (Exception e) { <START> log.warn("Exception thrown during message processing"); <END> continue; } } }</code><technical_language>print exception log.debug</technical_language>

Target:
public void run() { MessageContext context = null; ObjectMapper mapper = new ObjectMapper(); while (true) { try { context = this.queue.take(); if (context.getClient() == null) { break; } if (log.isDebugEnabled()) { log.debug("Message received: " + new String(context.getMessage(), UTF8)); } JsonNode rootNode = mapper.readTree(context.getMessage()); if (!rootNode.isArray()) { processIncomingObject(context.getClient(), rootNode); } else { final Iterator<JsonNode> iter = rootNode.getElements(); while (iter.hasNext()) { final JsonNode node = iter.next(); processIncomingObject(context.getClient(), node); } } } catch (Exception e) { log.warn("Exception thrown during message processing"); if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } continue; } } }
Source:
<code>public Map<Measure, Result<?>> calculate( T target, Set<Measure> measures, CalculationParameters parameters, ScenarioMarketData marketData, ReferenceData refData) { boolean measureRequested = measures.contains(calculationFunction.measure()); Set<Measure> requiredMeasures = requiredMeasuresSupported && measureRequested ? Sets.union(measures, calculationFunction.requiredMeasures()) : measures; Map<Measure, Result<?>> delegateResults = delegate.calculate(target, requiredMeasures, parameters, marketData, refData); if (!measureRequested) { return delegateResults; } <START> Result<?> result = calculateMeasure(target, delegateResults, parameters, marketData, refData); <END> Map<Measure, Result<?>> requestedResults = MapStream.of(delegateResults) .filterKeys(measures::contains) .filterKeys(measure -> !measure.equals(calculationFunction.measure())) .toMap(); return ImmutableMap.<Measure, Result<?>>builder() .put(calculationFunction.measure(), result) .putAll(requestedResults) .build(); }</code><technical_language>delegate receive Map<Measure, Result<?>>, Map<Measure, Object>. This avoid exposing failures delegate, remove delegates ability handle failures. sure</technical_language>

Target:
public Map<Measure, Result<?>> calculate( T target, Set<Measure> measures, CalculationParameters parameters, ScenarioMarketData marketData, ReferenceData refData) { if (!measures.contains(derivedFunction.measure())) { return delegate.calculate(target, measures, parameters, marketData, refData); } Set<Measure> requiredMeasures = Sets.union(measures, derivedFunction.requiredMeasures()); Map<Measure, Result<?>> delegateResults = delegate.calculate(target, requiredMeasures, parameters, marketData, refData); Result<?> result = calculateMeasure(target, delegateResults, parameters, marketData, refData); Map<Measure, Result<?>> requestedResults = MapStream.of(delegateResults) .filterKeys(measures::contains) .filterKeys(measure -> !measure.equals(derivedFunction.measure())) .toMap(); return ImmutableMap.<Measure, Result<?>>builder() .put(derivedFunction.measure(), result) .putAll(requestedResults) .build(); }
Source:
<code>private static String stripLeadingZeros(String input) { <START> for (int i = 0; i < input.length(); i++) { <END> if (input.charAt(i) != '0') { return input.substring(i); } } return ""; }</code><technical_language>Code conventions: curly brackets single line blocks</technical_language>

Target:
private static String stripLeadingZeros(String input) { for (int i = 0; i < input.length(); i++) if (input.charAt(i) != '0') return input.substring(i); return ""; }
Source:
<code>public IContainerDMContext[] getTargetFilters() throws CoreException { <START> synchronized (fFilteredThreadsByTarget) { <END> Set<IContainerDMContext> set = fFilteredThreadsByTarget.keySet(); return set.toArray(new IContainerDMContext[set.size()]); } }</code><technical_language>I is safe synchronize iteration of next line. is ok if set changes while iterating it</technical_language>

Target:
public IContainerDMContext[] getTargetFilters() throws CoreException { Set<IContainerDMContext> set = fFilteredThreadsByTarget.keySet(); synchronized (fFilteredThreadsByTarget) { return set.toArray(new IContainerDMContext[set.size()]); } }
Source:
<code>static void loadGame(final String path) { try { final URL pathURL = new File(path).toURI().toURL(); final InputStream stream = pathURL.openStream(); final Base64Reader reader = new Base64Reader(new BufferedReader( <START> new InputStreamReader(stream, "UTF-8"))); <END> final String mainString = reader.readString(); final JSONParser parser = new JSONParser(); final JSONObject mainObject = (JSONObject) parser.parse(mainString); parseJSON(mainObject); writeToState(); writeToSkins(); reader.close(); } catch (IOException e) { OBSERVABLE.notify(Category.ERROR, Error.IOEXCEPTION, "Parser.loadGame(String)", e.getMessage()); } catch (ParseException e) { OBSERVABLE.notify(Category.ERROR, Error.PARSEEXCEPTION, "Parser.loadGame(String)", e.getMessage()); } }</code><technical_language>easier create a factory method in Base64Reader (maybe in Writer) creates a Base64Reader InputStream? greatly enhance readability of lines. <review, logic, interface</technical_language>

Target:
static void loadGame(final String path) { try { final URL pathURL = new File(path).toURI().toURL(); final InputStream stream = pathURL.openStream(); final Base64Reader reader = new Base64Reader(new BufferedReader( new InputStreamReader(stream, "UTF-8"))); final String mainString = reader.readString(); final JSONParser parser = new JSONParser(); final JSONObject mainObject = (JSONObject) parser.parse(mainString); parseJSON(mainObject); writeToState(); writeToSkins(); writeToSoundtracks(); reader.close(); } catch (IOException e) { OBSERVABLE.notify(Category.ERROR, Error.IOEXCEPTION, "Parser.loadGame(String)", e.getMessage()); } catch (ParseException e) { OBSERVABLE.notify(Category.ERROR, Error.PARSEEXCEPTION, "Parser.loadGame(String)", e.getMessage()); } }
Source:
<code>public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { ProjectNode parent = (ProjectNode) node; PlanNode child = lookup.resolve(parent.getSource()); if (!(child instanceof JoinNode)) { return Optional.empty(); } JoinNode joinNode = (JoinNode) child; if (!joinNode.isCrossJoin()) { return Optional.empty(); } return pruneInputs(child.getOutputSymbols(), parent.getAssignments().getExpressions()) <START> .map(ImmutableSet::copyOf) <END> .map(dependencies -> parent.replaceChildren(ImmutableList.of( joinNode.replaceChildren(ImmutableList.of( restrictOutputs(idAllocator, joinNode.getLeft(), dependencies).orElse(joinNode.getLeft()), restrictOutputs(idAllocator, joinNode.getRight(), dependencies).orElse(joinNode.getRight())))))); }</code><technical_language>pruneInputs return a set instead? IMO is strange returns a list, order duplicates needed properties of returned collection. I missing something</technical_language>

Target:
public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { ProjectNode parent = (ProjectNode) node; PlanNode child = lookup.resolve(parent.getSource()); if (!(child instanceof JoinNode)) { return Optional.empty(); } JoinNode joinNode = (JoinNode) child; if (!joinNode.isCrossJoin()) { return Optional.empty(); } return pruneInputs(child.getOutputSymbols(), parent.getAssignments().getExpressions()) .map(ImmutableSet::copyOf) .map(dependencies -> parent.replaceChildren(ImmutableList.of( restrictChildOutputs(idAllocator, joinNode, dependencies, dependencies).get()))); }
Source:
<code>GssapiServer(final String protocol, final String serverName, final Map<String, ?> props, final CallbackHandler callbackHandler) throws SaslException { super(GSSAPI, protocol, serverName, props, callbackHandler, log); GSSManager manager = GSSManager.getInstance(); GSSContext gssContext = null; GSSCredential ourCredential = null; ServerCredentialCallback gssCredentialCallback = new ServerCredentialCallback(GSSKerberosCredential.class); try { log.trace("Obtaining GSSCredential for the service from callback handler..."); callbackHandler.handle(new Callback[] { gssCredentialCallback }); ourCredential = gssCredentialCallback.applyToCredential(GSSKerberosCredential.class, GSSKerberosCredential::getGssCredential); } catch (IOException | UnsupportedCallbackException e) { <START> log.trace("Unable to obtain GSSCredential from CallbackHandler", e); <END> } try { if (ourCredential == null) { String localName = protocol + "@" + serverName; log.tracef("Our name '%s'", localName); GSSName ourName = manager.createName(localName, GSSName.NT_HOSTBASED_SERVICE, KERBEROS_V5); ourCredential = manager.createCredential(ourName, GSSContext.INDEFINITE_LIFETIME, KERBEROS_V5, GSSCredential.ACCEPT_ONLY); } gssContext = manager.createContext(ourCredential); } catch (GSSException e) { throw log.mechUnableToCreateGssContext(getMechanismName(), e).toSaslException(); } this.gssContext = gssContext; }</code><technical_language>I if IOException is thrown authentication fail, callback handler is signalling a problem opposed supporting operation. WDYT</technical_language>

Target:
GssapiServer(final String protocol, final String serverName, final Map<String, ?> props, final CallbackHandler callbackHandler) throws SaslException { super(GSSAPI, protocol, serverName, props, callbackHandler, log); GSSManager manager = GSSManager.getInstance(); GSSContext gssContext = null; GSSCredential ourCredential = null; ServerCredentialCallback gssCredentialCallback = new ServerCredentialCallback(GSSKerberosCredential.class); try { log.trace("Obtaining GSSCredential for the service from callback handler..."); callbackHandler.handle(new Callback[] { gssCredentialCallback }); ourCredential = gssCredentialCallback.applyToCredential(GSSKerberosCredential.class, GSSKerberosCredential::getGssCredential); } catch (IOException e) { throw log.mechCallbackHandlerFailedForUnknownReason(GSSAPI, e).toSaslException(); } catch (UnsupportedCallbackException e) { log.trace("Unable to obtain GSSCredential from CallbackHandler", e); } try { if (ourCredential == null) { String localName = protocol + "@" + serverName; log.tracef("Our name '%s'", localName); GSSName ourName = manager.createName(localName, GSSName.NT_HOSTBASED_SERVICE, KERBEROS_V5); ourCredential = manager.createCredential(ourName, GSSContext.INDEFINITE_LIFETIME, KERBEROS_V5, GSSCredential.ACCEPT_ONLY); } gssContext = manager.createContext(ourCredential); } catch (GSSException e) { throw log.mechUnableToCreateGssContext(getMechanismName(), e).toSaslException(); } this.gssContext = gssContext; }
Source:
<code>public Collection<Replay> getLocalReplays() { Collection<Replay> replayInfos = new ArrayList<>(); String replayFileGlob = clientProperties.getReplay().getReplayFileGlob(); Path replaysDirectory = preferencesService.getReplaysDirectory(); if (Files.notExists(replaysDirectory)) { noCatch(() -> createDirectories(replaysDirectory)); } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replaysDirectory, replayFileGlob)) { for (Path replayFile : directoryStream) { try { LocalReplayInfo replayInfo = replayFileReader.parseMetaData(replayFile); <START> FeaturedMod featuredMod = modService.getFeaturedMod(replayInfo.getFeaturedMod()).get(); <END> mapService.findByMapFolderName(replayInfo.getMapname()) .thenAccept(mapBean -> { if (!mapBean.isPresent()) { notificationService.addNotification(new ImmediateNotification( i18n.get("errorTitle"), i18n.get("mapNotFound", replayInfo.getMapname()), WARN )); return; } replayInfos.add(new Replay(replayInfo, replayFile, featuredMod, mapBean.get())); }); } catch (Exception e) { logger.warn("Could not read replay file ({})", replayFile, e.getMessage()); moveCorruptedReplayFile(replayFile); } } } return replayInfos; }</code><technical_language>getNow() get(), instead thenAccept(), right</technical_language>

Target:
public CompletableFuture<Collection<Replay>> getLocalReplays() { Collection<Replay> replayInfos = new ArrayList<>(); ArrayList<CompletableFuture<LocalReplayInfo>> localReplayInfoFutures = new ArrayList<>(); String replayFileGlob = clientProperties.getReplay().getReplayFileGlob(); Path replaysDirectory = preferencesService.getReplaysDirectory(); if (Files.notExists(replaysDirectory)) { noCatch(() -> createDirectories(replaysDirectory)); } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replaysDirectory, replayFileGlob)) { for (Path replayFile : directoryStream) { try { LocalReplayInfo replayInfo = replayFileReader.parseMetaData(replayFile); CompletableFuture<LocalReplayInfo> localReplayInfoCompletableFuture = modService.getFeaturedMod(replayInfo.getFeaturedMod()). thenCombine(mapService.findByMapFolderName(replayInfo.getMapname()), (featuredMod, mapBean) -> { if (!mapBean.isPresent()) { notificationService.addNotification(new ImmediateNotification( i18n.get("errorTitle"), i18n.get("mapNotFound", replayInfo.getMapname()), WARN )); throw new IllegalStateException(MessageFormat.format("Map not available for replay with map name: '{}'", replayInfo.getMapname())); } replayInfos.add(new Replay(replayInfo, replayFile, featuredMod, mapBean.get())); return replayInfo; }).exceptionally(throwable -> { onUnableToParseReplay(replayFile, throwable); return null; }); localReplayInfoFutures.add(localReplayInfoCompletableFuture); } catch (Exception e) { onUnableToParseReplay(replayFile, e); } } } CompletableFuture[] arrayOfFutures = new CompletableFuture[localReplayInfoFutures.size()]; localReplayInfoFutures.toArray(arrayOfFutures); return CompletableFuture.allOf(arrayOfFutures).thenApply(aVoid -> replayInfos); }
Source:
<code>@Override public void onContinueClick() { <START> viewPager.setCurrentItem(DescriptionEditTutorialPage.PAGE_TWO.code(), true); <END> }</code><technical_language>optional consider: viewPager.setCurrentItem(Math.min(viewPager.getCurrentItem() + 1, viewPager.getAdapter().getCount() - 1), true);</technical_language>

Target:
@Override public void onContinueClick() { int nextPageIndex = viewPager.getCurrentItem() + 1; int lastPageIndex = viewPager.getAdapter().getCount() - 1; viewPager.setCurrentItem(Math.min(nextPageIndex, lastPageIndex), true); }
Source:
<code>public Optional<DefaultValueBridgeExpectations<BigDecimal, ?>> getDefaultValueBridgeExpectations() { return Optional.of( new DefaultValueBridgeExpectations<BigDecimal, BigDecimal>() { @Override public Class<BigDecimal> getProjectionType() { return BigDecimal.class; } @Override public Class<BigDecimal> getIndexFieldJavaType() { return BigDecimal.class; } @Override public List<BigDecimal> getEntityPropertyValues() { <START> return Arrays.asList( BigDecimal.valueOf( -100000.0 ), BigDecimal.valueOf( -1.0 ), BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN, <END> BigDecimal.valueOf( 100000.0 ) ); } @Override public List<BigDecimal> getDocumentFieldValues() { return getEntityPropertyValues(); } @Override public Class<?> getTypeWithValueBridge1() { return TypeWithValueBridge1.class; } @Override public Object instantiateTypeWithValueBridge1(int identifier, BigDecimal propertyValue) { TypeWithValueBridge1 instance = new TypeWithValueBridge1(); instance.id = identifier; instance.myProperty = propertyValue; return instance; } @Override public Class<?> getTypeWithValueBridge2() { return TypeWithValueBridge2.class; } } ); }</code><technical_language>want values represented a big decimal. change results of test, bridge implementation is a pass-through, feel more... correct, point of a BigDecimal. Example: BigDecimal.valueOf( 42571524, 231254 ). (42571524 * 10 ^ -231254) Later, implement support for BigDecimal/etc. in backend, I expect similar values in backend tests. *there* matter, reveal problems in implementation</technical_language>

Target:
public Optional<DefaultValueBridgeExpectations<BigDecimal, ?>> getDefaultValueBridgeExpectations() { return Optional.of( new DefaultValueBridgeExpectations<BigDecimal, BigDecimal>() { @Override public Class<BigDecimal> getProjectionType() { return BigDecimal.class; } @Override public Class<BigDecimal> getIndexFieldJavaType() { return BigDecimal.class; } @Override public List<BigDecimal> getEntityPropertyValues() { return Arrays.asList( BigDecimal.valueOf( -100000.0 ), BigDecimal.valueOf( -1.0 ), BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN, BigDecimal.valueOf( 100000.0 ), BigDecimal.valueOf( 42571524, 231254 ) ); } @Override public List<BigDecimal> getDocumentFieldValues() { return getEntityPropertyValues(); } @Override public Class<?> getTypeWithValueBridge1() { return TypeWithValueBridge1.class; } @Override public Object instantiateTypeWithValueBridge1(int identifier, BigDecimal propertyValue) { TypeWithValueBridge1 instance = new TypeWithValueBridge1(); instance.id = identifier; instance.myProperty = propertyValue; return instance; } @Override public Class<?> getTypeWithValueBridge2() { return TypeWithValueBridge2.class; } } ); }
Source:
<code>private static EventFiringWebDriver getChromeInstance() { String chromeBinaryName; String OSName = System.getProperty("os.name").toUpperCase(); if (OSName.contains("WINDOWS")) { chromeBinaryName = "chromedriver.exe"; File chromeBinary = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ChromeDriver" + File.separator + chromeBinaryName ); System.setProperty("webdriver.chrome.driver", chromeBinary.getAbsolutePath()); } if (browserName.equals("CHROMEMOBILE")) { chromeOptions.addArguments( "--user-agent=" + userAgentRegistry.getUserAgent("iPhone") ); return new EventFiringWebDriver(new ChromeDriver(chromeOptions)); } LoggingPreferences loggingprefs = new LoggingPreferences(); loggingprefs.enable(LogType.BROWSER, Level.SEVERE); caps.setCapability(CapabilityType.LOGGING_PREFS, loggingprefs); <START> <END> return new EventFiringWebDriver(new ChromeDriver(caps)); }</code><technical_language>is code duplication, merge one</technical_language>

Target:
private static EventFiringWebDriver getChromeInstance() { String chromeBinaryName; String OSName = System.getProperty("os.name").toUpperCase(); if (OSName.contains("WINDOWS")) { chromeBinaryName = "chromedriver.exe"; File chromeBinary = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ChromeDriver" + File.separator + chromeBinaryName ); System.setProperty("webdriver.chrome.driver", chromeBinary.getAbsolutePath()); } if (browserName.equals("CHROMEMOBILE")) { chromeOptions.addArguments( "--user-agent=" + userAgentRegistry.getUserAgent("iPhone") ); return new EventFiringWebDriver(new ChromeDriver(chromeOptions)); } setBrowserLogging(Level.SEVERE); return new EventFiringWebDriver(new ChromeDriver(caps)); }
Source:
<code>private HTTPEndpointManager() { super(); internalInboundPort = ConfigurationLoader.getInternalInboundPort(); <START> if (internalInboundPort != -1) { <END> internalAPIList = ConfigurationLoader.loadInternalAPIs(Constants.INTERNAL_APIS_FILE); internalAPIDispatcher = new InternalAPIDispatcher(internalAPIList); } }</code><technical_language>here, I ca skip this check setting a default port</technical_language>

Target:
private HTTPEndpointManager() { super(); internalInboundPort = ConfigurationLoader.getInternalInboundPort(); if (internalInboundPort != -1) { List<InternalAPI> internalAPIList = ConfigurationLoader.loadInternalAPIs(Constants.INTERNAL_APIS_FILE); internalAPIDispatcher = new InternalAPIDispatcher(internalAPIList); internalApiEnabled = internalAPIList != null && internalAPIList.isEmpty(); } }
Source:
<code><START> private String getServiceFromVolumesFrom(String volumesFrom) throws IllegalArgumentException { <END> String service = volumesFrom; if (volumesFrom != null) { String[] split = service.split(":"); if (split.length != 1 && split.length != 2) { throw new IllegalArgumentException(format("Service volumes_from '%s' is invalid", volumesFrom)); } service = split[0]; } return service; }</code><technical_language>code is in getServiceFromMachineLink method, reused</technical_language>

Target:
private String getServiceFromVolumesFrom(String volumesFrom) throws IllegalArgumentException { String service = volumesFrom; if (volumesFrom != null) { String[] split = service.split(":"); if (split.length > 2) { throw new IllegalArgumentException(format("Service volumes_from '%s' is invalid", volumesFrom)); } service = split[0]; } return service; }
Source:
<code>private ListBoxValues createDefaultListBoxValues() { return new ListBoxValues(ComboBoxWidgetView.CUSTOM_PROMPT, <START> "Edit" + " ", <END> null); }</code><technical_language>I18n</technical_language>

Target:
private ListBoxValues createDefaultListBoxValues() { return new ListBoxValues(ComboBoxWidgetView.CUSTOM_PROMPT, translationService.getValue(StunnerBPMNConstants.EDIT) + " ", null); }
Source:
<code>private void renderDrafts(JsArray<CommentInfo> drafts) { List<CommentInfo> sorted = sortComment(drafts); for (CommentInfo info : sorted) { DisplaySide side; if (info.side() == Side.PARENT) { if (base != null) { continue; } side = DisplaySide.A; } else { side = drafts == draftsBase ? DisplaySide.A : DisplaySide.B; } DraftBox box = new DraftBox( this, getCmFromSide(side), side, commentLinkProcessor, getPatchSetIdFromSide(side), info); <START> if (getPrefs().get().isExpandAllComments()) { box.setOpen(true); } <END> if (publishedBase != null || publishedRevision != null) { PublishedBox replyToBox = publishedMap.get(info.in_reply_to()); if (replyToBox != null) { replyToBox.registerReplyBox(box); } } if (!info.has_line()) { diffTable.addFileCommentBox(box); continue; } lineActiveBoxMap.put( getCmFromSide(side).getLineHandle(info.line() - 1), box); addCommentBox(info, box); } }</code><technical_language>This is of dumbest options support but, OK</technical_language>

Target:
private void renderDrafts(JsArray<CommentInfo> drafts) { List<CommentInfo> sorted = sortComment(drafts); for (CommentInfo info : sorted) { DisplaySide side; if (info.side() == Side.PARENT) { if (base != null) { continue; } side = DisplaySide.A; } else { side = drafts == draftsBase ? DisplaySide.A : DisplaySide.B; } DraftBox box = new DraftBox( this, getCmFromSide(side), side, commentLinkProcessor, getPatchSetIdFromSide(side), info); if (prefs.get().isExpandAllComments()) { box.setOpen(true); } if (publishedBase != null || publishedRevision != null) { PublishedBox replyToBox = publishedMap.get(info.in_reply_to()); if (replyToBox != null) { replyToBox.registerReplyBox(box); } } if (!info.has_line()) { diffTable.addFileCommentBox(box); continue; } lineActiveBoxMap.put( getCmFromSide(side).getLineHandle(info.line() - 1), box); addCommentBox(info, box); } }
Source:
<code>public void prepare(KubernetesEnvironment k8sEnv, String workspaceId, long timeoutMillis) throws InfrastructureException { TracingTags.WORKSPACE_ID.set(workspaceId); if (EphemeralWorkspaceUtility.isEphemeral(k8sEnv.getAttributes())) { return; } if (k8sEnv.getPersistentVolumeClaims().isEmpty()) { return; } final KubernetesPersistentVolumeClaims k8sClaims = factory.create(workspaceId).persistentVolumeClaims(); LOG.debug("Creating PVCs for workspace '{}'", workspaceId); k8sClaims.createIfNotExist(k8sEnv.getPersistentVolumeClaims().values()); if (waitBound) { <START> LOG.debug("Waiting PVCs for workspace '{}' to be bound", workspaceId); <END> for (PersistentVolumeClaim pvc : k8sEnv.getPersistentVolumeClaims().values()) { k8sClaims.waitBound(pvc.getMetadata().getName(), timeoutMillis); } } LOG.debug("Preparing PVCs done for workspace '{}'", workspaceId); }</code><technical_language>Is intentional "Waiting PVCs" (multiple PVCs), in CommonPVCStrategy.java "Waiting PVC" (one singular PVC)</technical_language>

Target:
public void prepare(KubernetesEnvironment k8sEnv, String workspaceId, long timeoutMillis) throws InfrastructureException { TracingTags.WORKSPACE_ID.set(workspaceId); if (EphemeralWorkspaceUtility.isEphemeral(k8sEnv.getAttributes())) { return; } if (k8sEnv.getPersistentVolumeClaims().isEmpty()) { return; } final KubernetesPersistentVolumeClaims k8sClaims = factory.create(workspaceId).persistentVolumeClaims(); LOG.debug("Creating PVCs for workspace '{}'", workspaceId); k8sClaims.createIfNotExist(k8sEnv.getPersistentVolumeClaims().values()); if (waitBound) { LOG.debug("Waiting for PVC(s) of workspace '{}' to be bound", workspaceId); for (PersistentVolumeClaim pvc : k8sEnv.getPersistentVolumeClaims().values()) { k8sClaims.waitBound(pvc.getMetadata().getName(), timeoutMillis); } } LOG.debug("Preparing PVCs done for workspace '{}'", workspaceId); }
Source:
<code>protected Comparator<Object[]> createSortComparator( final QueryContext context, final Columns columns ) { assert context != null; final Comparator<Location> typeComparator = Location.getComparator(); return new Comparator<Object[]>() { @Override public int compare( Object[] tuple1, Object[] tuple2 ) { int result = 0; for (String selectorName : columns.getSelectorNames()) { <START> int locationIndex = columns.getLocationIndex(selectorName); <END> Location value1 = (Location)tuple1[locationIndex]; Location value2 = (Location)tuple2[locationIndex]; result = typeComparator.compare(value1, value2); if (result != 0) return result; } return result; } }; }</code><technical_language>Again, indexes calculated of compare method Comparator is initialized (where firstLocationIndex calculated), preparation of query. values for calls, query execution (e.g., processing of tuples in query results) fast possible</technical_language>

Target:
protected Comparator<Object[]> createSortComparator( final QueryContext context, final Columns columns ) { assert context != null; final Comparator<Location> typeComparator = Location.getComparator(); final int[] locationIndexes = getLocationIndexes(columns); return new Comparator<Object[]>() { @Override public int compare( Object[] tuple1, Object[] tuple2 ) { int result = 0; for (int locationIndex : locationIndexes) { Location value1 = (Location)tuple1[locationIndex]; Location value2 = (Location)tuple2[locationIndex]; result = typeComparator.compare(value1, value2); if (result != 0) return result; } return result; } }; }
Source:
<code>protected Stream<URL> listBundleComponents(Bundle bundle) { String list = OSGiRuntimeService.getComponentsList(bundle); String name = bundle.getSymbolicName(); log.debug("PartialBundle: " + name + " components: " + list); if (list == null) { return Stream.empty(); } else { <START> return Arrays.stream(list.split("[, \t\n\r\f]")).map(bundle::getEntry).filter(Objects::nonNull); <END> } }</code><technical_language>replace Arrays#stream Stream#of for consistency</technical_language>

Target:
protected Stream<URL> listBundleComponents(Bundle bundle) { String list = OSGiRuntimeService.getComponentsList(bundle); String name = bundle.getSymbolicName(); log.debug("PartialBundle: " + name + " components: " + list); if (list == null) { return Stream.empty(); } else { return Stream.of(list.split("[, \t\n\r\f]")).map(bundle::getEntry).filter(Objects::nonNull); } }
Source:
<code>public void testIndependentZKConnections() throws IOException { try (ReadOnlyZKClient zk1 = REGISTRY.getZKClient()) { Configuration otherConf = new Configuration(TEST_UTIL.getConfiguration()); otherConf.set(HConstants.ZOOKEEPER_QUORUM, MiniZooKeeperCluster.HOST); try (ZKConnectionRegistry otherRegistry = new ZKConnectionRegistry(otherConf)) { ReadOnlyZKClient zk2 = otherRegistry.getZKClient(); assertNotSame("Using a different configuration / quorum should result in different " <START> + "backing zk connection.", zk1, zk2); <END> assertNotEquals( "Using a different configrution / quorum should be reflected in the zk connection.", zk1.getConnectString(), zk2.getConnectString()); } } finally { LOG.info("DONE!"); } }</code><technical_language>I recall mentioned times operator end of a line I changed formatter config do this, prefer operator start of a line? fine both, want do want, is important</technical_language>

Target:
public void testIndependentZKConnections() throws IOException { try (ReadOnlyZKClient zk1 = REGISTRY.getZKClient()) { Configuration otherConf = new Configuration(TEST_UTIL.getConfiguration()); otherConf.set(HConstants.ZOOKEEPER_QUORUM, MiniZooKeeperCluster.HOST); try (ZKConnectionRegistry otherRegistry = new ZKConnectionRegistry(otherConf)) { ReadOnlyZKClient zk2 = otherRegistry.getZKClient(); assertNotSame("Using a different configuration / quorum should result in " + "different backing zk connection.", zk1, zk2); assertNotEquals( "Using a different configrution / quorum should be reflected in the zk connection.", zk1.getConnectString(), zk2.getConnectString()); } } finally { LOG.info("DONE!"); } }
Source:
<code>public void execute(Version version) { <START> logger.info("Executing Mica upgrade to version 3.3.0"); <END> setupDatasetOrders(); republishStudiesWithInvalidContent(); }</code><technical_language>3.3.0</technical_language>

Target:
public void execute(Version version) { logger.info("Executing Mica upgrade to version 3.1.0"); setupDatasetOrders(); republishStudiesWithInvalidContent(); }
Source:
<code>public void setUp() { MockitoAnnotations.initMocks(this); fakeTransport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return mockLowLevelRequest; } }; initializer = new RetryHttpInitializer(mockCredential, "foo-user-agent", <START> HttpRequest.DEFAULT_NUMBER_OF_RETRIES, 20 * 1000, 20 * 1000, ImmutableMap <END> .of("headerkey", "headervalue")); initializer.setSleeperOverride(mockSleeper); requestFactory = fakeTransport.createRequestFactory(initializer); }</code><technical_language>This formatted</technical_language>

Target:
public void setUp() { MockitoAnnotations.initMocks(this); fakeTransport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return mockLowLevelRequest; } }; initializer = new RetryHttpInitializer( mockCredential, "foo-user-agent", HttpRequest.DEFAULT_NUMBER_OF_RETRIES, 20_000, 20_000, ImmutableMap.of("header-key", "header=value")); initializer.setSleeperOverride(mockSleeper); requestFactory = fakeTransport.createRequestFactory(initializer); }
Source:
<code>public Visitable defaultVisit(Visitable node) throws StandardException { DMLStatementNode rsn; if ((explain || LOG.isDebugEnabled()) && node instanceof DMLStatementNode && (((DMLStatementNode) node).getResultSetNode()) != null) { rsn = (DMLStatementNode) node; List<QueryTreeNode> orderedNodes = new ArrayList<>(); rsn.buildTree(orderedNodes,0); Map<String, Collection<QueryTreeNode>> m=planMap.get(); m.put(query,orderedNodes); if (LOG.isDebugEnabled()){ DataSetProcessorType currentType = rsn.getLanguageConnectionContext().getDataSetProcessorType(); currentType = currentType.combine(rsn.getCompilerContext().getDataSetProcessorType()); <START> currentType = currentType.combine(determineSpark(orderedNodes)); <END> Iterator<String> nodes = planToIterator(orderedNodes, currentType); StringBuilder sb = new StringBuilder(); while (nodes.hasNext()) sb.append(nodes.next()).append("\n"); LOG.info(String.format("Plan nodes for query <<\n\t%s\n>>%s\n", query,sb.toString())); } } explain = false; return node; }</code><technical_language>Do need line 97? I dataSetProcessorType obtained rsn.getCompilerContext().getDataSetProcessorType() is final decision, is passed activation, need node in orderedNodes</technical_language>

Target:
public Visitable defaultVisit(Visitable node) throws StandardException { DMLStatementNode rsn; if ((explain || LOG.isDebugEnabled()) && node instanceof DMLStatementNode && (((DMLStatementNode) node).getResultSetNode()) != null) { rsn = (DMLStatementNode) node; List<QueryTreeNode> orderedNodes = new ArrayList<>(); rsn.buildTree(orderedNodes,0); Map<String, Collection<QueryTreeNode>> m=planMap.get(); m.put(query,orderedNodes); if (LOG.isDebugEnabled()){ DataSetProcessorType currentType = rsn.getCompilerContext().getDataSetProcessorType(); Iterator<String> nodes = planToIterator(orderedNodes, currentType); StringBuilder sb = new StringBuilder(); while (nodes.hasNext()) sb.append(nodes.next()).append("\n"); LOG.info(String.format("Plan nodes for query <<\n\t%s\n>>%s\n", query,sb.toString())); } } explain = false; return node; }
Source:
<code>Optional<MetricPusher> create(MetricPusherCreator metricPusherCreator, Map<String, String> parameters) { Supplier<MetricPusher> metricPusherSupplier = () -> { try { return metricPusherCreator.create(parameters.get(METRIC_PUSHER_ADDRESS)); } catch (Exception e) { logger.error("MetricPusher creation failed."); <START> e.printStackTrace(); <END> return null; } }; return create(metricPusherSupplier); }</code><technical_language>Again, weird logging. I get rid of e.printStackTrace() entries exception part of error logging logger</technical_language>

Target:
Optional<MetricPusher> create(MetricPusherCreator metricPusherCreator, Map<String, String> parameters) { Supplier<MetricPusher> metricPusherSupplier = () -> { try { return metricPusherCreator.create(parameters.get(METRIC_PUSHER_ADDRESS)); } catch (Exception e) { logger.error("MetricPusher creation failed.", e); return null; } }; return create(metricPusherSupplier); }
Source:
<code>public JSONObject toJSONObject() { JSONObject mainObj = new JSONObject(); try { mainObj.put("androidNotificationId", androidNotificationId); if (groupedNotifications != null) { JSONArray payloadJsonArray = new JSONArray(); for (OSNotification notification : groupedNotifications) payloadJsonArray.put(notification.toJSONObject()); mainObj.put("groupedNotifications", payloadJsonArray); } <START> JSONObject payload = new JSONObject(); <END> payload.put("notificationID", notificationId); payload.put("title", title); payload.put("body", body); payload.put("smallIcon", smallIcon); payload.put("largeIcon", largeIcon); payload.put("bigPicture", bigPicture); payload.put("smallIconAccentColor", smallIconAccentColor); payload.put("launchURL", launchURL); payload.put("sound", sound); payload.put("ledColor", ledColor); payload.put("lockScreenVisibility", lockScreenVisibility); payload.put("groupKey", groupKey); payload.put("groupMessage", groupMessage); payload.put("fromProjectNumber", fromProjectNumber); payload.put("collapseId", collapseId); payload.put("priority", priority); if (additionalData != null) payload.put("additionalData", additionalData); if (actionButtons != null) { JSONArray actionButtonJsonArray = new JSONArray(); for (ActionButton actionButton : actionButtons) { actionButtonJsonArray.put(actionButton.toJSONObject()); } payload.put("actionButtons", actionButtonJsonArray); } payload.put("rawPayload", rawPayload); mainObj.put("payload", payload); } catch(JSONException e) { e.printStackTrace(); } return mainObj; }</code><technical_language>Remove payload, properties mainObj</technical_language>

Target:
public JSONObject toJSONObject() { JSONObject mainObj = new JSONObject(); try { mainObj.put("androidNotificationId", androidNotificationId); if (groupedNotifications != null) { JSONArray payloadJsonArray = new JSONArray(); for (OSNotification notification : groupedNotifications) payloadJsonArray.put(notification.toJSONObject()); mainObj.put("groupedNotifications", payloadJsonArray); } mainObj.put("notificationId", notificationId); mainObj.put("title", title); mainObj.put("body", body); mainObj.put("smallIcon", smallIcon); mainObj.put("largeIcon", largeIcon); mainObj.put("bigPicture", bigPicture); mainObj.put("smallIconAccentColor", smallIconAccentColor); mainObj.put("launchURL", launchURL); mainObj.put("sound", sound); mainObj.put("ledColor", ledColor); mainObj.put("lockScreenVisibility", lockScreenVisibility); mainObj.put("groupKey", groupKey); mainObj.put("groupMessage", groupMessage); mainObj.put("fromProjectNumber", fromProjectNumber); mainObj.put("collapseId", collapseId); mainObj.put("priority", priority); if (additionalData != null) mainObj.put("additionalData", additionalData); if (actionButtons != null) { JSONArray actionButtonJsonArray = new JSONArray(); for (ActionButton actionButton : actionButtons) { actionButtonJsonArray.put(actionButton.toJSONObject()); } mainObj.put("actionButtons", actionButtonJsonArray); } mainObj.put("rawPayload", rawPayload); } catch(JSONException e) { e.printStackTrace(); } return mainObj; }
Source:
<code>private String readBlob(RevCommit commit, String string) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { TreeWalk tw = TreeWalk.forPath(db, string, commit.getTree()); if (tw == null) return null; <START> ObjectReader or = db.getObjectDatabase().newReader(); <END> ObjectId bId = tw.getObjectId(0); if (bId == null) return null; ObjectLoader ol = or.open(bId); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ol.copyTo(bos); or.release(); return new String(bos.toByteArray(), "UTF-8"); }</code><technical_language>this moved down, this skipped if bId == null</technical_language>

Target:
private String readBlob(RevCommit commit, String string) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { TreeWalk tw = TreeWalk.forPath(db, string, commit.getTree()); if (tw == null) return null; ObjectId bId = tw.getObjectId(0); if (bId == null) return null; ObjectReader or = db.getObjectDatabase().newReader(); ObjectLoader ol = or.open(bId); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ol.copyTo(bos); or.release(); return new String(bos.toByteArray(), "UTF-8"); }
Source:
<code>public Trace getTrace(String tenantId, String id) { Trace ret = null; List<Trace> fragments = getFragmentsForTraceId(tenantId, id); if (!fragments.isEmpty()) { <START> ret = fragments.stream().filter(f -> f.getTraceId().equals(id)).findFirst().get(); <END> for (int i=0; ret != null && i < ret.getNodes().size(); i++) { Node node = ret.getNodes().get(i); processConnectedNode(fragments, ret, node, new StringBuilder(ret.getFragmentId()).append(':').append(i)); } } if (msgLog.isTraceEnabled()) { msgLog.tracef("Get trace with id[%s] is: %s", id, ret); } if (ret == null && spanService != null) { ret = spanService.getTrace(tenantId, id); } return ret; }</code><technical_language>please move this List<Trace> fragments = getFragmentsForTraceId(tenantId, id); ret definition. change if ret != null remove ret != null for statement</technical_language>

Target:
public Trace getTrace(String tenantId, String id) { List<Trace> fragments = getFragmentsForTraceId(tenantId, id); Trace ret = fragments.stream().filter(f -> f.getTraceId().equals(id)).findFirst().orElse(null); if (ret != null) { for (int i=0; i < ret.getNodes().size(); i++) { Node node = ret.getNodes().get(i); processConnectedNode(fragments, ret, node, new StringBuilder(ret.getFragmentId()).append(':').append(i)); } } else if (spanService != null) { ret = spanService.getTrace(tenantId, id); } if (msgLog.isTraceEnabled()) { msgLog.tracef("Get trace with id[%s] is: %s", id, ret); } return ret; }
Source:
<code><START> static CqlClient create( <END> TaggedMetricRegistry taggedMetricRegistry, Supplier<CqlSession> cqlSessionSupplier, int preparedStatementCacheSize) { CqlSession cqlSession = cqlSessionSupplier.get(); CachingStatementPreparer cachingStatementPreparer = CachingStatementPreparer.create( key -> cqlSession.prepare(key.formatQueryString()), taggedMetricRegistry, preparedStatementCacheSize); return new CqlClientImpl(cqlSession, cachingStatementPreparer); }</code><technical_language>nit: annotation @VisibleForTesting for this kind of broadening for tests</technical_language>

Target:
private static CqlClient create( TaggedMetricRegistry taggedMetricRegistry, Supplier<CqlSession> cqlSessionSupplier, int preparedStatementCacheSize) { CqlSession cqlSession = cqlSessionSupplier.get(); CachingStatementPreparer cachingStatementPreparer = CachingStatementPreparer.create( key -> cqlSession.prepare(key.formatQueryString()), taggedMetricRegistry, preparedStatementCacheSize); return new CqlClientImpl(cqlSession, cachingStatementPreparer); }
Source:
<code>protected boolean shouldUpdateBroadcast(Broadcast broadcast) { return broadcast.getTransmissionEndTime() <START> .isAfter(DateTime.now().minusDays(MAX_BROADCAST_AGE_IN_DAYS_TO_UPDATE)); <END> }</code><technical_language>a clock here</technical_language>

Target:
protected boolean shouldUpdateBroadcast(Broadcast broadcast) { return broadcast.getTransmissionEndTime() .isAfter(clock.now().minus(MAX_BROADCAST_AGE_TO_UPDATE)); }
Source:
<code>public void sendJobCompletionEvent(final JobCompletionEventArgs args) throws IOException { final QueryString qs = new QueryString( <START> API_VERSION, "3.0-preview.1", <END> "publisherId", "jenkins", "channelId", args.getServerKey()); final URI requestUri = UriHelper.join( collectionUri, "_apis", "public", "hooks", "externalEvents", qs); final JSONObject json = JSONObject.fromObject(args.getPayload()); final NameValuePair[] headers = new NameValuePair[3]; headers[0] = new NameValuePair("X-Event-Key", "job:completion"); headers[1] = new NameValuePair("X-Jenkins-Signature", args.getPayloadSignature()); headers[2] = new NameValuePair("X-Jenkins-ServerKey", args.getServerKey()); request(Void.class, HttpMethod.POST, requestUri, json, headers); }</code><technical_language>{ "id": "e0e0a1c9-beeb-4fb7-a8c8-b18e3161a50e", "area": "hooks", "resourceName": "externalEvents", "routeTemplate": "_apis/public/{area}/{resource}", "resourceVersion": 1, "minVersion": "2.0", "maxVersion": "4.0", "releasedVersion": "3.2" },</technical_language>

Target:
public void sendJobCompletionEvent(final JobCompletionEventArgs args) throws IOException { final QueryString qs = new QueryString( API_VERSION, "3.2", "publisherId", "jenkins", "channelId", args.getServerKey()); final URI requestUri = UriHelper.join( collectionUri, "_apis", "public", "hooks", "externalEvents", qs); final JSONObject json = JSONObject.fromObject(args.getPayload()); final NameValuePair[] headers = new NameValuePair[3]; headers[0] = new NameValuePair("X-Event-Key", "job:completion"); headers[1] = new NameValuePair("X-Jenkins-Signature", args.getPayloadSignature()); headers[2] = new NameValuePair("X-Jenkins-ServerKey", args.getServerKey()); request(Void.class, HttpMethod.POST, requestUri, json, headers); }
Source:
<code>public void run() { while (execute) { try { long startTs = System.currentTimeMillis(); if ((isPollable && !isPolled) || !isPollable) { pollRecords(ps); } long endTs = System.currentTimeMillis(); long ioTime = endTs - startTs; long sleepTime = pollInterval - ioTime; <START> LOG.debug("pollInterval = " + pollInterval + " I/O time = " + ioTime + " sleepTime = " + sleepTime); <END> Thread.sleep(sleepTime > 0 ? sleepTime : 0); } catch (Exception ex) { cause.set(ex); execute = false; } } }</code><technical_language>{} syntax for log message, string evaluated if log level is enabled</technical_language>

Target:
public void run() { while (execute) { try { long startTs = System.currentTimeMillis(); if ((isPollable && !isPolled) || !isPollable) { pollRecords(ps); } long endTs = System.currentTimeMillis(); long ioTime = endTs - startTs; long sleepTime = pollInterval - ioTime; LOG.debug("pollInterval = , I/O time = , sleepTime = {}", pollInterval, ioTime, sleepTime); Thread.sleep(sleepTime > 0 ? sleepTime : 0); } catch (Exception ex) { cause.set(ex); execute = false; } } }
Source:
<code>public Optional<PatchLineComment> get(ReviewDb db, ChangeNotes notes, PatchLineComment.Key key) throws OrmException { if (!migration.readComments()) { <START> return Optional.of(db.patchComments().get(key)); <END> } for (PatchLineComment c : byChange(db, notes)) { if (key.equals(c.getKey())) { return Optional.of(c); } } return Optional.absent(); }</code><technical_language>get returns null if found. of() accept null. This fail NPE database systems, return absent() notedb</technical_language>

Target:
public Optional<PatchLineComment> get(ReviewDb db, ChangeNotes notes, PatchLineComment.Key key) throws OrmException { if (!migration.readComments()) { return Optional.fromNullable(db.patchComments().get(key)); } for (PatchLineComment c : byChange(db, notes)) { if (key.equals(c.getKey())) { return Optional.of(c); } } return Optional.absent(); }
Source:
<code>public void updateSearchResultSet( String outputName, DimensionSelector selector, SearchQuerySpec searchQuerySpec, int limit, final Object2IntRBTreeMap<SearchHit> set ) { if (selector == null) { return; } if (selector.nameLookupPossibleInAdvance() <START> && selector.getValueCardinality() == 1 <END> && selector.lookupName(0) == null) { return; } final IndexedInts vals = selector.getRow(); for (int i = 0; i < vals.size(); ++i) { final String dimVal = selector.lookupName(vals.get(i)); if (searchQuerySpec.accept(dimVal)) { set.addTo(new SearchHit(outputName, Strings.nullToEmpty(dimVal)), 1); if (set.size() >= limit) { return; } } } }</code><technical_language>Please extract this utility function "isNullSelector"</technical_language>

Target:
public void updateSearchResultSet( String outputName, DimensionSelector selector, SearchQuerySpec searchQuerySpec, int limit, final Object2IntRBTreeMap<SearchHit> set ) { if (selector != null && !isNilSelector(selector)) { final IndexedInts vals = selector.getRow(); for (int i = 0; i < vals.size(); ++i) { final String dimVal = selector.lookupName(vals.get(i)); if (searchQuerySpec.accept(dimVal)) { set.addTo(new SearchHit(outputName, Strings.nullToEmpty(dimVal)), 1); if (set.size() >= limit) { return; } } } } }
Source:
<code>public static void main(String[] args) { KeyVaultBackupClient backupClient = new KeyVaultBackupClientBuilder() .vaultUrl("https://{YOUR_VAULT_NAME}.vault.azure.net") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); String keyName = "<key-name>"; String blobStorageUrl = "<blob-storage-url>"; String sasToken = "<sas-token>"; String folderName = "<folder-name>"; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = backupClient.beginSelectiveRestore(keyName, blobStorageUrl, sasToken, folderName); <START> } <END></code><technical_language>wait for it, for consistency other examples if else</technical_language>

Target:
public static void main(String[] args) { KeyVaultBackupClient backupClient = new KeyVaultBackupClientBuilder() .vaultUrl("https://{YOUR_VAULT_NAME}.vault.azure.net") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); String keyName = "<key-name>"; String backupFolderUrl = "<backup-folder-url>"; String sasToken = "<sas-token>"; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = backupClient.beginSelectiveRestore(keyName, backupFolderUrl, sasToken); restorePoller.waitForCompletion(); }
Source:
<code>public Set<Guid> getDisksNotInPreviousCheckpoint() { List<DiskImage> checkpointDisks = vmCheckpointDao.getDisksByCheckpointId(getParameters().getVmBackup().getFromCheckpointId()); Set<Guid> vmCheckpointDisksIds = checkpointDisks .stream() .map(DiskImage::getId) .collect(Collectors.toCollection(HashSet::new)); return getDiskIds().stream() <START> .distinct() <END> .filter(diskId -> !vmCheckpointDisksIds.contains(diskId)) .collect(Collectors.toSet()); }</code><technical_language>Redundant, HashSet allow duplicates</technical_language>

Target:
public Set<Guid> getDisksNotInPreviousCheckpoint() { List<DiskImage> checkpointDisks = vmCheckpointDao.getDisksByCheckpointId(getParameters().getVmBackup().getFromCheckpointId()); Set<Guid> vmCheckpointDisksIds = checkpointDisks .stream() .map(DiskImage::getId) .collect(Collectors.toCollection(HashSet::new)); return getDiskIds().stream() .filter(diskId -> !vmCheckpointDisksIds.contains(diskId)) .collect(Collectors.toSet()); }