auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SyncResult getStatus(Stack stack, Set<InstanceMetaData> checkableInstances) { try { Set<InstanceMetaData> notTermiatedStackInstances = stack.getAllInstanceMetaDataList().stream() .filter(Predicate.not(InstanceMetaData::isTerminated)) .collect(Collectors.toSet()); Pair<List<DetailedStackStatus>, String> statusCheckPair = checkStatus(stack, checkableInstances); List<DetailedStackStatus> responses = statusCheckPair.getFirst(); DetailedStackStatus status; String postFix = ""; <START> Boolean result = false; <END> if (responses.isEmpty()) { status = DetailedStackStatus.UNREACHABLE; postFix = "Freeipa is unreachable, "; } else { DetailedStackStatus first = responses.get(0); if (responses.stream().allMatch(Predicate.isEqual(first)) && responses.size() == notTermiatedStackInstances.size()) { status = first; if (first.equals(DetailedStackStatus.AVAILABLE)) { result = true; } } else { status = DetailedStackStatus.UNHEALTHY; postFix = "Freeipa is unhealthy, "; } } return new SyncResult(postFix + statusCheckPair.getSecond(), status, result); } catch (Exception e) { LOGGER.info("Error occurred during status fetch: " + e.getMessage(), e); return new SyncResult("Freeipa is unreachable, because error occurred: " + e.getMessage(), DetailedStackStatus.UNREACHABLE, false); } }</code><technical_language>purpose of this result? name a boolean confused. I usage of SyncResult#getResult drop</technical_language>

Target:
public SyncResult getStatus(Stack stack, Set<InstanceMetaData> checkableInstances) { try { if (checkableInstances.isEmpty()) { throw new UnsupportedOperationException("There are no instances of FreeIPA to check the status of"); } Set<InstanceMetaData> notTermiatedStackInstances = stack.getAllInstanceMetaDataList().stream() .filter(Predicate.not(InstanceMetaData::isTerminated)) .collect(Collectors.toSet()); Pair<List<DetailedStackStatus>, String> statusCheckPair = checkStatus(stack, checkableInstances); List<DetailedStackStatus> responses = statusCheckPair.getFirst(); DetailedStackStatus status; if (areAllStatusTheSame(responses) && !hasMissingStatus(responses, notTermiatedStackInstances)) { status = responses.get(0); } else { status = DetailedStackStatus.UNHEALTHY; } return new SyncResult("FreeIpa is " + status + ", " + statusCheckPair.getSecond(), status); } catch (Exception e) { LOGGER.info("Error occurred during status fetch: " + e.getMessage(), e); return new SyncResult("FreeIpa is unreachable, because error occurred: " + e.getMessage(), DetailedStackStatus.UNREACHABLE); } }
Source:
<code>public void testUpdatedDbGeneration() { int size = 3 * ITEMS_COUNT_PER_UPDATE + 10; List<Guid> vmGuids = generateGuidList(size); List<Guid> templatesGuids = generateGuidList(size); List<Guid> removedGuids = Collections.emptyList(); addVms(vmGuids, 2, VMStatus.Down, ImageStatus.OK); addTemplates(templatesGuids, 2, VmTemplateStatus.OK, ImageStatus.OK); initTestForPool(pool1.getId(), vmGuids, templatesGuids, removedGuids); doReturn(2L).when(vmStaticDAO).getDbGeneration(any(Guid.class)); updater.ovfUpdate_timer(); <START> verify(updater, never()).performOvfUpdate(any(Guid.class), any(Map.class)); <END> verify(updater, never()).executeRemoveVmInSpm(any(Guid.class), any(Guid.class), any(Guid.class)); List<Guid> idsThatNeededToBeUpdated = new LinkedList<Guid>(vmGuids); idsThatNeededToBeUpdated.addAll(templatesGuids); verifyCorrectOvfDataUpdaterRun(pool1.getId(), Collections.<Guid> emptyList(), removedGuids); }</code><technical_language>s/any(Map.class)/anyMap()/</technical_language>

Target:
public void testUpdatedDbGeneration() { int size = 3 * ITEMS_COUNT_PER_UPDATE + 10; List<Guid> vmGuids = generateGuidList(size); List<Guid> templatesGuids = generateGuidList(size); List<Guid> removedGuids = Collections.emptyList(); addVms(vmGuids, 2, VMStatus.Down, ImageStatus.OK); addTemplates(templatesGuids, 2, VmTemplateStatus.OK, ImageStatus.OK); initTestForPool(pool1.getId(), vmGuids, templatesGuids, removedGuids); doReturn(2L).when(vmStaticDAO).getDbGeneration(any(Guid.class)); updater.ovfUpdate_timer(); verify(updater, never()).performOvfUpdate(any(Guid.class), anyMap()); verify(updater, never()).executeRemoveVmInSpm(any(Guid.class), any(Guid.class), any(Guid.class)); List<Guid> idsThatNeededToBeUpdated = new LinkedList<Guid>(vmGuids); idsThatNeededToBeUpdated.addAll(templatesGuids); verifyCorrectOvfDataUpdaterRun(pool1.getId(), Collections.<Guid> emptyList(), removedGuids); }
Source:
<code><START> ImapStore getStore() { <END> return store; }</code><technical_language>is this necessary</technical_language>

Target:
private ImapStore getStore() { return store; }
Source:
<code>private Pair<Double, Double> totalCost(final int numWorker, final int numDataBlocks, final int numModelBlocks, final int availableEvaluators, final List<EvaluatorSummary> workers, final List<EvaluatorSummary> servers) { final double workerThroughputSum = workers.subList(0, numWorker).stream() .mapToDouble(worker -> worker.throughput) .sum(); final double compCost = numDataBlocks / workerThroughputSum; final int numServers = availableEvaluators - numWorker; final double serverThroughputSum = servers.subList(0, numServers).stream() .mapToDouble(server -> server.throughput) .sum(); final double commCost = numModelBlocks / serverThroughputSum * numWorker * numMiniBatchPerItr; final double totalCost = compCost + commCost; LOG.log(Level.INFO, "Estimated Cost: (server, worker) = ({0}, {1}), totalCost = {2}, " + <START> "(compCost, commCost) = ({3}, {4})", <END> new Object[] {numServers, numWorker, totalCost, compCost, commCost}); return new Pair<>(compCost, commCost); }</code><technical_language>this log string follow JSON format for consistency</technical_language>

Target:
private Pair<Double, Double> totalCost(final int numWorker, final int numDataBlocks, final int numModelBlocks, final int availableEvaluators, final List<EvaluatorSummary> workers, final List<EvaluatorSummary> servers) { final double workerThroughputSum = workers.subList(0, numWorker).stream() .mapToDouble(worker -> worker.throughput) .sum(); final double compCost = numDataBlocks / workerThroughputSum; final int numServer = availableEvaluators - numWorker; final double serverThroughputSum = servers.subList(0, numServer).stream() .mapToDouble(server -> server.throughput) .sum(); final double commCost = numModelBlocks / serverThroughputSum * numWorker * numMiniBatchPerItr; final double totalCost = compCost + commCost; final String costInfo = String.format("{\"numServer\": %d, \"numWorker\": %d, \"totalCost\": %f, " + "\"compCost\": %f, \"commCost\": %f}", numServer, numWorker, totalCost, compCost, commCost); LOG.log(Level.INFO, "CostInfo {0} {1}", new Object[]{System.currentTimeMillis(), costInfo}); return new Pair<>(compCost, commCost); }
Source:
<code>private boolean indexIsOutOfRange(List<Element> elements) { <START> return elements.size() <= 0 || elementIndex >= elements.size(); <END> }</code><technical_language>elements.isEmpty() instead of checking size <= 0</technical_language>

Target:
private boolean indexIsOutOfRange(List<Element> elements) { return elements.isEmpty() || elementIndex >= elements.size(); }
Source:
<code>private void assertRequest(final String testCaseNameRequest, final String testCaseXml, final String testSuiteXml) { final WsdlTestCase wsdlTestcase = (WsdlTestCase) this.testCase; final String xml = wsdlTestcase.getConfig().toString(); final boolean flag1 = xml.indexOf(testCaseNameRequest) > 0; final boolean flag2 = xml.indexOf(testCaseXml) > 0; final boolean flag3 = xml.indexOf(testSuiteXml) > 0; try <START> {if (!flag1 || !flag2 || !flag3) { <END> } } catch (NullPointerException npe) { System.out.println(npe.getMessage() + " thrown!"); } }</code><technical_language>Format this code please</technical_language>

Target:
private void assertRequest(final String testCaseNameRequest, final String testCaseXml, final String testSuiteXml) { final WsdlTestCase wsdlTestcase = (WsdlTestCase) this.testCase; final String xml = wsdlTestcase.getConfig().toString(); final boolean flag1 = xml.indexOf(testCaseNameRequest) > 0; final boolean flag2 = xml.indexOf(testCaseXml) > 0; final boolean flag3 = xml.indexOf(testSuiteXml) > 0; if (!flag1 || !flag2 || !flag3) { } }
Source:
<code>public void testMultipleProviderTypesFound() throws Exception { TestFrameworkProvider anotherProvider = new TestFrameworkProvider() { @Override public boolean isEnabled(List<ClasspathEntry> testBundleClassPath, Properties surefireProperties) { return true; } @Override public Version getVersion() { return new Version("1.0"); } @Override public String getType() { return "another_test_fwk"; } @Override public String getSurefireProviderClassName() { return "a.nother.test.framework.Provider"; } @Override public List<Dependency> getRequiredBundles() { return emptyList(); } @Override public Properties <START> getProviderSpecifcProperties() <END> { return null; } }; PlexusContainer container = getContainer(); container.addComponent(anotherProvider, TestFrameworkProvider.class, "another_test_fwk"); ProviderHelper providerSelector = container.lookup(ProviderHelper.class); try { providerSelector.selectProvider(classPath("org.junit:4.8.1"), new Properties(), null); fail(); } catch (MojoExecutionException e) { } finally { container.release(anotherProvider); } }</code><technical_language>"Specifc" - typo</technical_language>

Target:
public void testMultipleProviderTypesFound() throws Exception { TestFrameworkProvider anotherProvider = new TestFrameworkProvider() { @Override public boolean isEnabled(List<ClasspathEntry> testBundleClassPath, Properties surefireProperties) { return true; } @Override public Version getVersion() { return new Version("1.0"); } @Override public String getType() { return "another_test_fwk"; } @Override public String getSurefireProviderClassName() { return "a.nother.test.framework.Provider"; } @Override public List<Dependency> getRequiredBundles() { return emptyList(); } @Override public Properties getProviderSpecificProperties() { return null; } }; PlexusContainer container = getContainer(); container.addComponent(anotherProvider, TestFrameworkProvider.class, "another_test_fwk"); ProviderHelper providerSelector = container.lookup(ProviderHelper.class); try { providerSelector.selectProvider(classPath("org.junit:4.8.1"), new Properties(), null); fail(); } catch (MojoExecutionException e) { } finally { container.release(anotherProvider); } }
Source:
<code>private static Collection<PlayerTypes.Type> gatherPlayerTypes() { return Stream.concat( StreamSupport.stream(ServiceLoader.load(AiProvider.class).spliterator(), false) .map(PlayerTypes.AiType::new), <START> PlayerTypes.getBuiltInPlayerTypes().stream()) <END> .collect(Collectors.toList()); }</code><technical_language>I hoping explicit list of player types here. surprised 'flow field' is part of built-in, built-in means</technical_language>

Target:
private static Collection<PlayerTypes.Type> gatherPlayerTypes() { return Stream.concat( PlayerTypes.getBuiltInPlayerTypes().stream(), StreamSupport.stream(ServiceLoader.load(AiProvider.class).spliterator(), false) .map(PlayerTypes.AiType::new)) .filter(HeadedGameRunner::filterBetaPlayerType) .collect(Collectors.toList()); }
Source:
<code>public boolean onAddBlockEvent(WorldServer.ServerBlockEventList list, Object obj, BlockPos pos, Block blockIn, int eventId, int eventParam) { if (blockIn instanceof BlockPistonBase) { final IBlockState blockstate = this.getBlockState(pos); EnumFacing direction = (EnumFacing) blockstate.getValue(BlockDirectional.FACING); BlockPistonStructureHelper movedBlocks = new BlockPistonStructureHelper(this$, pos, direction, eventId == 0); List<BlockPos> blocks = new ArrayList<BlockPos>(); blocks.addAll(movedBlocks.getBlocksToDestroy()); blocks.addAll(movedBlocks.getBlocksToMove()); List<Location<org.spongepowered.api.world.World>> locations = new ArrayList<Location<org.spongepowered.api.world.World>>(); for (BlockPos block : blocks) { <START> locations.add(new Location<>((org.spongepowered.api.world.World) this$, block.getX(), block.getY(), block.getZ())); <END> } if (SpongeCommonEventFactory.handleChangeBlockEventPre(this, pos, locations)) { return false; } } else { if (SpongeCommonEventFactory.handleChangeBlockEventPre(this, pos)) { return false; } } if (CauseTracker.ENABLED) { final CauseTracker causeTracker = this.getCauseTracker(); final PhaseData currentPhase = causeTracker.getCurrentPhaseData(); final IPhaseState phaseState = currentPhase.state; if (phaseState.getPhase().ignoresBlockEvent(phaseState)) { return list.add((BlockEventData) obj); } final BlockEventData blockEventData = (BlockEventData) obj; final PhaseContext context = currentPhase.context; IMixinBlockEventData blockEvent = (IMixinBlockEventData) blockEventData; phaseState.getPhase().addNotifierToBlockEvent(phaseState, context, causeTracker, pos, blockEvent); } return list.add((BlockEventData) obj); }</code><technical_language>filtering block positions added, multiple duplications of locations added</technical_language>

Target:
public boolean onAddBlockEvent(WorldServer.ServerBlockEventList list, Object obj, BlockPos pos, Block blockIn, int eventId, int eventParam) { if ((blockIn instanceof BlockPistonBase && SpongeCommonEventFactory.handlePistonEvent(this, list, obj, pos, blockIn, eventId, eventParam)) || SpongeCommonEventFactory.callChangeBlockEventPre(this, pos, NamedCause.of(NamedCause.BLOCK_EVENT, this)).isCancelled()) { return false; } if (CauseTracker.ENABLED) { final CauseTracker causeTracker = this.getCauseTracker(); final PhaseData currentPhase = causeTracker.getCurrentPhaseData(); final IPhaseState phaseState = currentPhase.state; if (phaseState.getPhase().ignoresBlockEvent(phaseState)) { return list.add((BlockEventData) obj); } final BlockEventData blockEventData = (BlockEventData) obj; final PhaseContext context = currentPhase.context; IMixinBlockEventData blockEvent = (IMixinBlockEventData) blockEventData; phaseState.getPhase().addNotifierToBlockEvent(phaseState, context, causeTracker, pos, blockEvent); } return list.add((BlockEventData) obj); }
Source:
<code>public String renderNavigationMenu(HttpServletRequest request, String menuDefinition, String rendererClass, int minDepth, int maxDepth) throws Exception { <START> URL url = request.getServletContext().getResource(menuDefinition); <END> return renderNavigationMenu(url, request, rendererClass, minDepth, maxDepth); }</code><technical_language>Compilation error? Please check resubmit! [javac] /builddir/build/BUILD/spacewalk-java-git-3.c90b394/code/src/com/redhat/rhn/frontend/taglibs/helpers/RenderUtils.java:90: error: find symbol [javac] URL url = request.getServletContext().getResource(menuDefinition); [javac] ^ [javac] symbol: method getServletContext() [javac] location: variable request of type HttpServletRequest</technical_language>

Target:
public String renderNavigationMenu(HttpServletRequest request, String menuDefinition, String rendererClass, int minDepth, int maxDepth) throws Exception { URL url = request.getSession().getServletContext().getResource(menuDefinition); return renderNavigationMenu(url, request, rendererClass, minDepth, maxDepth); }
Source:
<code>public Receive createReceive() { return new ReceiveBuilder() .matchEquals(TICK, msg -> tick()) .matchEquals(REQUEST_FINISHED, msg -> { _nAvailableRequests += 1; tick(); }) .match(Task.class, task -> { if (_queue.size() < _bufferSize) { _queue.add(task); getSender().tell(new Status.Success(task), getSelf()); <START> recordCounter("buffer_size", _queue.size()); <END> recordCounter("submit/success", 1); tick(); } else { getSender().tell(new Status.Failure(BufferFull.getInstance()), getSelf()); recordCounter("submit/success", 0); } }) .match(SampleCounts.class, this::sampleCountsReceived) .build(); }</code><technical_language>This result in irregular publications of is effectively a gauge. This interpretation more difficult. If tick interval is reasonable, publish this there</technical_language>

Target:
public Receive createReceive() { return new ReceiveBuilder() .matchEquals(TICK, msg -> tick()) .matchEquals(REQUEST_FINISHED, msg -> { _nAvailableRequests += 1; tick(); }) .match(Task.class, task -> { if (_queue.size() < _bufferSize) { _queue.add(task); getSender().tell(new Status.Success(task), getSelf()); _maxRecentBufferSize.accumulateAndGet(_queue.size(), Math::max); recordCounter("submit/success", 1); tick(); } else { getSender().tell(new Status.Failure(BufferFull.getInstance()), getSelf()); recordCounter("submit/success", 0); } }) .match(SampleCounts.class, this::sampleCountsReceived) .build(); }
Source:
<code>public void onDestroyActionMode(ActionMode mode) { mCallbacks.onActionModeDestroyed(); mActionMode = null; if (getActivity() != null) { NotesActivity notesActivity = (NotesActivity) getActivity(); setActivateOnItemClick(DisplayUtils.isLargeScreenLandscape(notesActivity)); <START> if(mSelectedNoteId == null) notesActivity.showDetailPlaceholder(); <END> } }</code><technical_language>suggestion if (mSelectedNoteId == null) { notesActivity.showDetailPlaceholder(); } Some parts of codebase inline if statements. So, this code style for some files modules. if statements consistent multiline syntax. update this multiline too</technical_language>

Target:
public void onDestroyActionMode(ActionMode mode) { mCallbacks.onActionModeDestroyed(); mActionMode = null; if (getActivity() != null) { NotesActivity notesActivity = (NotesActivity) getActivity(); setActivateOnItemClick(DisplayUtils.isLargeScreenLandscape(notesActivity)); if (mSelectedNoteId == null) { notesActivity.showDetailPlaceholder(); } } new Handler().postDelayed( new Runnable() { @Override public void run() { requireActivity().getWindow().setStatusBarColor(getResources().getColor(android.R.color.transparent, requireActivity().getTheme())); } }, requireContext().getResources().getInteger(android.R.integer.config_longAnimTime) ); }
Source:
<code><START> private DataSource getDataSource(DBConfig dbConfig, DBPasswordExtractor dbPasswordExtractor) { <END> HikariConfig config = new HikariConfig(); config.setJdbcUrl(dbConfig.getUrl()); config.setUsername(dbConfig.getUser()); config.setPassword(dbPasswordExtractor.getDBPassword(dbConfig)); config.setDriverClassName(dbConfig.getDriver()); dbConfig.getPropertyMap().forEach((k, v) -> config.addDataSourceProperty(k, v)); return new HikariDataSource(config); }</code><technical_language>static</technical_language>

Target:
private static DataSource getDataSource(DBConfig dbConfig, DBPasswordExtractor dbPasswordExtractor) { HikariConfig config = new HikariConfig(); config.setJdbcUrl(dbConfig.getUrl()); config.setUsername(dbConfig.getUser()); config.setPassword(dbPasswordExtractor.getDBPassword(dbConfig)); config.setDriverClassName(dbConfig.getDriver()); dbConfig.getPropertyMap().forEach((k, v) -> config.addDataSourceProperty(k, v)); return new HikariDataSource(config); }
Source:
<code>public void abortProcessInstances(List<Long> processInstanceIds) { <START> processInstanceIds.stream().forEach(processInstanceId -> { <END> try { abortProcessInstance(processInstanceId); } catch (ProcessInstanceNotFoundException processInstanceNotFoundException) { logger.warn(processInstanceNotFoundException.getMessage()); } }); }</code><technical_language>suggestion processInstanceIds.forEach(processInstanceId -> { dont need _.stream_ access _forEach_</technical_language>

Target:
public void abortProcessInstances(List<Long> processInstanceIds) { processInstanceIds.forEach(processInstanceId -> { try { abortProcessInstance(processInstanceId); } catch (ProcessInstanceNotFoundException ex) { logger.warn("Process instance with id " + processInstanceId + " was not found", ex); } }); }
Source:
<code>public List<ClientModel> getClients(RealmModel realm, Integer firstResult, Integer maxResults) { TypedQuery<String> query = em.createNamedQuery("getClientIdsByRealm", String.class); if (firstResult != null && firstResult > 0) { query.setFirstResult(firstResult); } if (maxResults != null && maxResults > 0) { query.setMaxResults(maxResults); } query.setParameter("realm", realm.getId()); List<String> clients = query.getResultList(); <START> if (clients.isEmpty()) return Collections.emptyList(); <END> List<ClientModel> list = new LinkedList<>(); for (String id : clients) { ClientModel client = session.realms().getClientById(id, realm); if (client != null) list.add(client); } return Collections.unmodifiableList(list); }</code><technical_language>Please unnecessary changes (Collections.EMPTY_LIST is perfectly valid)</technical_language>

Target:
public List<ClientModel> getClients(RealmModel realm, Integer firstResult, Integer maxResults) { TypedQuery<String> query = em.createNamedQuery("getClientIdsByRealm", String.class); if (firstResult != null && firstResult > 0) { query.setFirstResult(firstResult); } if (maxResults != null && maxResults > 0) { query.setMaxResults(maxResults); } query.setParameter("realm", realm.getId()); List<String> clients = query.getResultList(); if (clients.isEmpty()) return Collections.EMPTY_LIST; List<ClientModel> list = new LinkedList<>(); for (String id : clients) { ClientModel client = session.realms().getClientById(id, realm); if (client != null) list.add(client); } return Collections.unmodifiableList(list); }
Source:
<code>public void testBatchWithoutOngoingTMSuspension() throws Exception { Cache<String, String> cache = createCache("testBatchWithoutOngoingTMSuspension"); TransactionManager tm = TestingUtil.getTransactionManager(cache); assertEquals(MyDummyTransactionManager.class, tm.getClass()); assertNull(tm.getTransaction(), "Should have no ongoing txs"); cache.startBatch(); cache.put("k", "v"); assertNull(tm.getTransaction(), "Should have no ongoing txs"); cache.put("k2", "v2"); assertNull(getOnDifferentThread(cache, "k")); assertNull(getOnDifferentThread(cache, "k2")); try { tm.commit(); } catch (Exception e) { } assertNull(tm.getTransaction(), "Should have no ongoing txs"); assertNull(getOnDifferentThread(cache, "k")); assertNull(getOnDifferentThread(cache, "k2")); <START> cache.endBatch(true); END> assertEquals("v", getOnDifferentThread(cache, "k")); assertEquals("v2", getOnDifferentThread(cache, "k2")); }</code><technical_language>no-op</technical_language>

Target:
public void testBatchWithoutOngoingTMSuspension() throws Exception { Cache<String, String> cache = createCache("testBatchWithoutOngoingTMSuspension"); TransactionManager tm = TestingUtil.getTransactionManager(cache); assertEquals(MyDummyTransactionManager.class, tm.getClass()); assertNull("Should have no ongoing txs", tm.getTransaction()); cache.startBatch(); cache.put("k", "v"); assertNull("Should have no ongoing txs", tm.getTransaction()); cache.put("k2", "v2"); assertNull(getOnDifferentThread(cache, "k")); assertNull(getOnDifferentThread(cache, "k2")); try { tm.commit(); } catch (Exception e) { } assertNull("Should have no ongoing txs", tm.getTransaction()); assertNull(getOnDifferentThread(cache, "k")); assertNull(getOnDifferentThread(cache, "k2")); cache.endBatch(true); assertEquals("v", getOnDifferentThread(cache, "k")); assertEquals("v2", getOnDifferentThread(cache, "k2")); }
Source:
<code>public Builder(JLoadProfileUsers userGroup, JLoadProfileUsers... userGroups) { Objects.nonNull(userGroup); ArrayList<JLoadProfileUsers> groups = new ArrayList<>(); groups.add(userGroup); Collections.addAll(groups, userGroups); this.userGroups = groups; <START> this.tickInterval = 1000; <END> }</code><technical_language>a constant</technical_language>

Target:
public Builder(JLoadProfileUsers userGroup, JLoadProfileUsers... userGroups) { Objects.nonNull(userGroup); ArrayList<JLoadProfileUsers> groups = new ArrayList<>(); groups.add(userGroup); Collections.addAll(groups, userGroups); this.userGroups = groups; this.tickInterval = DEFAULT_TICK_INTERVAL; }
Source:
<code>private void initiatePersonasSearch(List<BlackboardAttribute> accountAttributesList) throws CentralRepoException { GridBagLayout gridBagLayout = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.FIRST_LINE_START; constraints.gridx = 0; constraints.gridy = 0; constraints.insets = new java.awt.Insets(TOP_INSET, 0, 0, 0); constraints.fill = GridBagConstraints.NONE; constraints.weightx = 0; javax.swing.Box.Filler filler1 = this.createFiller(5, 0); personasPanel.add(filler1, constraints); constraints.gridx++; javax.swing.JLabel primaryPersonaNameLabel = new javax.swing.JLabel(); primaryPersonaNameLabel.setText(Bundle.ContactArtifactViewer_persona_searching()); gridBagLayout.setConstraints(primaryPersonaNameLabel, constraints); personasPanel.add(primaryPersonaNameLabel); personasPanel.setLayout(gridBagLayout); <START> personasPanel.revalidate(); <END> ContactPersonaSearcherTask personaSearchTask = new ContactPersonaSearcherTask(accountAttributesList); personaSearchTask.execute(); }</code><technical_language>This a call repaint(),</technical_language>

Target:
private void initiatePersonasSearch(List<BlackboardAttribute> accountAttributesList) throws CentralRepoException { personasLabel.setVisible(true); GridBagLayout gridBagLayout = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.FIRST_LINE_START; constraints.gridx = 0; constraints.gridy = 0; constraints.insets = new java.awt.Insets(TOP_INSET, LEFT_INSET, 0, 0); constraints.fill = GridBagConstraints.NONE; constraints.weightx = 0; javax.swing.JLabel personaLabel = new javax.swing.JLabel(); personaLabel.setText(Bundle.ContactArtifactViewer_persona_label()); personaLabel.setFont(personaLabel.getFont().deriveFont(Font.BOLD, personaLabel.getFont().getSize())); gridBagLayout.setConstraints(personaLabel, constraints); personasPanel.add(personaLabel); constraints.gridy++; javax.swing.JLabel primaryPersonaNameLabel = new javax.swing.JLabel(); primaryPersonaNameLabel.setText(Bundle.ContactArtifactViewer_persona_searching()); gridBagLayout.setConstraints(primaryPersonaNameLabel, constraints); personasPanel.add(primaryPersonaNameLabel); personasPanel.setLayout(gridBagLayout); personasPanel.revalidate(); personasPanel.repaint(); ContactPersonaSearcherTask personaSearchTask = new ContactPersonaSearcherTask(accountAttributesList); personaSearchTask.execute(); }
Source:
<code>public void updateRegionsInTransitionMetrics() { long currentTime = System.currentTimeMillis(); int totalRITs = 0; int totalRITsOverThreshold = 0; long oldestRITTime = 0; Set<String> oldestRITHashesAndStates = Sets.newHashSet(); int ritThreshold = this.server.getConfiguration(). getInt(HConstants.METRICS_RIT_STUCK_WARNING_THRESHOLD, 60000); int counter = 0; for (RegionState state: regionStates.getRegionsInTransitionOrderedByDuration()) { totalRITs++; long ritTime = currentTime - state.getStamp(); if (ritTime > ritThreshold) { totalRITsOverThreshold++; } if (oldestRITTime < ritTime) { oldestRITTime = ritTime; } <START> if (counter < 500) { END> oldestRITHashesAndStates.add( state.getRegion().getRegionNameAsString() + ":" + state.getState().name() ); } counter += 1; } if (this.metricsAssignmentManager != null) { this.metricsAssignmentManager.updateRITOldestAge(oldestRITTime); this.metricsAssignmentManager.updateRITCount(totalRITs); this.metricsAssignmentManager.updateRITCountOverThreshold(totalRITsOverThreshold); LOG.debug("Oldest RIT hashes and states: " + oldestRITHashesAndStates.toString()); long time = EnvironmentEdgeManager.currentTime(); if ((time - ritThreshold / 2) >= this.lastRITHashMetricUpdate) { this.metricsAssignmentManager.updateRITHashesAndStates(oldestRITHashesAndStates); this.lastRITHashMetricUpdate = time; } } }</code><technical_language>500 high me. 20 enough? this a constant in file, if configurable</technical_language>

Target:
public void updateRegionsInTransitionMetrics() { long currentTime = System.currentTimeMillis(); int totalRITs = 0; int totalRITsOverThreshold = 0; long oldestRITTime = 0; Set<String> oldestRITHashesAndStates = Sets.newHashSet(); int ritThreshold = this.server.getConfiguration(). getInt(HConstants.METRICS_RIT_STUCK_WARNING_THRESHOLD, 60000); int counter = 0; for (RegionState state: regionStates.getRegionsInTransitionOrderedByTimestamp()) { totalRITs++; long ritTime = currentTime - state.getStamp(); if (ritTime > ritThreshold) { totalRITsOverThreshold++; } if (oldestRITTime < ritTime) { oldestRITTime = ritTime; } if ((counter < NUMBER_OF_RITS_TO_RECORD) && (ritTime > ritThreshold)) { oldestRITHashesAndStates.add( state.getRegion().getEncodedName() + ":" + state.getState().name() ); } counter += 1; } if (this.metricsAssignmentManager != null) { this.metricsAssignmentManager.updateRITOldestAge(oldestRITTime); this.metricsAssignmentManager.updateRITCount(totalRITs); this.metricsAssignmentManager.updateRITCountOverThreshold(totalRITsOverThreshold); this.metricsAssignmentManager.updateRITHashesAndStates(oldestRITHashesAndStates); this.lastRITHashMetricUpdate = currentTime; if (((currentTime - ritThreshold / 2) >= this.lastRITHashMetricUpdate) && oldestRITHashesAndStates.size() > 0) { LOG.debug("Oldest RIT hashes and states: " + oldestRITHashesAndStates.toString()); } } }
Source:
<code>public void run() { boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean(). getInputArguments().toString().indexOf("-agentlib:jdwp") > 0; SoapUIUpdateProvider updateProvider = SoapUIAutoUpdaterUtils.getProvider(); if (!isDebug && SoapUI.getSettings().getBoolean(VersionUpdateSettings.AUTO_CHECK_VERSION_UPDATE)) { updateProvider.start(); } addStandardPreferencesShortcutOnMac(); boolean isFirstLaunch = !DefaultSoapUICore.settingsFileExists(); Properties props = new Properties(); try { props.load(SoapUI.class.getResourceAsStream(SOAPUI_TITLE)); String brandedTitleExt = props.getProperty("soapui.app.title"); if (!StringUtils.isNullOrEmpty(brandedTitleExt)) { brandedTitleExt = " - " + brandedTitleExt; } else { brandedTitleExt = ""; } startSoapUI(mainArgs, "SoapUI " + SOAPUI_VERSION + " " + brandedTitleExt, new StandaloneSoapUICore(true)); if (getSettings().getBoolean(UISettings.SHOW_STARTUP_PAGE) && !isBrowserDisabled()) { SwingUtilities.invokeLater(new Runnable() { public void run() { showStarterPage(); } }); } <START> if (isFirstLaunch && SoapUI.usingGraphicalEnvironment()) { <END> if (!SoapUI.getSettings().getBoolean(SHOW_ENDPOINT_EXPLORER_ON_START, true)) { SwingUtilities.invokeLater(SoapUI::showEndpointExplorer); } } if (isCommandLine()) { Analytics.trackAction(SoapUIActions.PRODUCT_STARTED_FROM_CMD); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } }</code><technical_language>remove this code all? Endpoint Explorer is started SoapUI:1014</technical_language>

Target:
public void run() { boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean(). getInputArguments().toString().indexOf("-agentlib:jdwp") > 0; SoapUIUpdateProvider updateProvider = SoapUIAutoUpdaterUtils.getProvider(); if (!isDebug && SoapUI.getSettings().getBoolean(VersionUpdateSettings.AUTO_CHECK_VERSION_UPDATE)) { updateProvider.start(); } addStandardPreferencesShortcutOnMac(); Properties props = new Properties(); try { props.load(SoapUI.class.getResourceAsStream(SOAPUI_TITLE)); String brandedTitleExt = props.getProperty("soapui.app.title"); if (!StringUtils.isNullOrEmpty(brandedTitleExt)) { brandedTitleExt = " - " + brandedTitleExt; } else { brandedTitleExt = ""; } startSoapUI(mainArgs, "SoapUI " + SOAPUI_VERSION + " " + brandedTitleExt, new StandaloneSoapUICore(true)); if (getSettings().getBoolean(UISettings.SHOW_STARTUP_PAGE) && !isBrowserDisabled()) { SwingUtilities.invokeLater(new Runnable() { public void run() { showStarterPage(); } }); } if (isCommandLine()) { Analytics.trackAction(SoapUIActions.PRODUCT_STARTED_FROM_CMD); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
Source:
<code>public final Map<String, SiteStatus> globalStatus() { final Iterator<CacheXSiteAdminOperation> iterator = collectXSiteAdminOperation().iterator(); if (!iterator.hasNext()) { return Collections.emptyMap(); } Map<String, ContainerSiteStatusBuilder> siteStatusBuilderMap = new HashMap<>(); while (iterator.hasNext()) { CacheXSiteAdminOperation xsiteAdminOperation = iterator.next(); Map<String, SiteStatus> perCacheSiteStatus = xsiteAdminOperation.xSiteAdminOperations.clusterStatus(); <START> for (Map.Entry<String, SiteStatus> siteStatus : perCacheSiteStatus.entrySet()) { <END> String siteName = siteStatus.getKey(); SiteStatus status = siteStatus.getValue(); ContainerSiteStatusBuilder builder = siteStatusBuilderMap.get(siteName); if (builder == null) { builder = new ContainerSiteStatusBuilder(); siteStatusBuilderMap.put(siteName, builder); } builder.addCacheName(xsiteAdminOperation.cacheName, status); } } Map<String, SiteStatus> result = new HashMap<>(); for (Map.Entry<String, ContainerSiteStatusBuilder> builder : siteStatusBuilderMap.entrySet()) { result.put(builder.getKey(), builder.getValue().build()); } return result; }</code><technical_language>perCacheSiteStatus.forEach((siteName, status) -> { ... }); nicer read more compact</technical_language>

Target:
public final Map<String, SiteStatus> globalStatus() { final Iterator<CacheXSiteAdminOperation> iterator = collectXSiteAdminOperation().iterator(); if (!iterator.hasNext()) { return Collections.emptyMap(); } Map<String, ContainerSiteStatusBuilder> siteStatusBuilderMap = new HashMap<>(); while (iterator.hasNext()) { CacheXSiteAdminOperation xsiteAdminOperation = iterator.next(); xsiteAdminOperation.xSiteAdminOperations.clusterStatus().forEach((site, status) -> { ContainerSiteStatusBuilder builder = siteStatusBuilderMap.get(site); if (builder == null) { builder = new ContainerSiteStatusBuilder(); siteStatusBuilderMap.put(site, builder); } builder.addCacheName(xsiteAdminOperation.cacheName, status); }); } Map<String, SiteStatus> result = new HashMap<>(); siteStatusBuilderMap.forEach((site, builder) -> result.put(site, builder.build())); return result; }
Source:
<code>private static ExceptionSupplier<CredentialSource, ConfigXMLParseException> createCredentialStoreSupplier(final XMLLocation location, final String storeName, final String alias, final String clearText, final Map<String, ExceptionSupplier<CredentialStore, ConfigXMLParseException>> credentialStoresMap) { return () -> { if (storeName != null) { final ExceptionSupplier<CredentialStore, ConfigXMLParseException> supplier = credentialStoresMap.get(storeName); if (supplier == null) { throw xmlLog.xmlCredentialStoreNameNotDefined(location, storeName); } final CredentialStore credentialStore = supplier.get(); return new CredentialStoreCredentialSource(credentialStore, alias); } else if (clearText != null) { return new CredentialSource() { @Override public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { return SupportLevel.SUPPORTED; } @Override public <C extends Credential> C getCredential(Class<C> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { <START> return credentialType.cast(new PasswordCredential(ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, clearText.toCharArray()))); <END> } }; } else { throw xmlLog.xmlInvalidCredentialStoreRef(location); } }; }</code><technical_language>This a ClassCastException if (for some reason) user of this CredentialSource query some other credential type. A option is to: * Create PasswordCredential anonymous class avoid allocation pressure, * return passwordCredential.castAs(credentialType, algorithmName, parameterSpec); body, return null for unsupported requests spec</technical_language>

Target:
private static ExceptionSupplier<CredentialSource, ConfigXMLParseException> createCredentialStoreSupplier(final XMLLocation location, final String storeName, final String alias, final String clearText, final Map<String, ExceptionSupplier<CredentialStore, ConfigXMLParseException>> credentialStoresMap) { return () -> { if (storeName != null) { final ExceptionSupplier<CredentialStore, ConfigXMLParseException> supplier = credentialStoresMap.get(storeName); if (supplier == null) { throw xmlLog.xmlCredentialStoreNameNotDefined(location, storeName); } final CredentialStore credentialStore = supplier.get(); return new CredentialStoreCredentialSource(credentialStore, alias); } else if (clearText != null) { final PasswordCredential passwordCredential = new PasswordCredential(ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, clearText.toCharArray())); return IdentityCredentials.NONE.withCredential(passwordCredential); } else { throw xmlLog.xmlInvalidCredentialStoreRef(location); } }; }
Source:
<code><START> public SyslogReceivingChannelAdapterFactoryBean(Protocol protocol) { <END> this.protocol = protocol; }</code><technical_language>do a null check</technical_language>

Target:
public SyslogReceivingChannelAdapterFactoryBean(Protocol protocol) { Assert.notNull(protocol, "'protocol' cannot be null"); this.protocol = protocol; }
Source:
<code><START> public T getNullable() { <END> T value = this.value; if (this.resolved) { return value; } value = supplier.get(); this.value = value; this.resolved = true; return value; }</code><technical_language>sticking Optional orElse( ) pattern? Staying Java's names Optional idioms more flexibility a bit more familiar users</technical_language>

Target:
private T getNullable() { T value = this.value; if (this.resolved) { return value; } value = supplier.get(); this.value = value; this.resolved = true; return value; }
Source:
<code>public void testLoadString() throws Exception { if (! myFileIsBinary) { String ionText; try { ionText = PrivateUtils.utf8FileToString(myTestFile); } catch (IonException e) { <START> final CharBuffer buffer = CharBuffer.allocate(1204); <END> final CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder(); final FileReader fileReader = new FileReader(myTestFile); while(fileReader.read(buffer) != -1){ assert utf8Encoder.canEncode(buffer); } return; } try { @SuppressWarnings("unused") IonDatagram dg = loader().load(ionText); fail("Expected IonException"); } catch (IonException e) { } } }</code><technical_language>I meant *why* is this 1204</technical_language>

Target:
public void testLoadString() throws Exception { if (! myFileIsBinary) { String ionText; try { ionText = PrivateUtils.utf8FileToString(myTestFile); } catch (IonException e) { final CharBuffer buffer = CharBuffer.allocate(1024); final CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder(); final FileReader fileReader = new FileReader(myTestFile); while(fileReader.read(buffer) != -1){ assert utf8Encoder.canEncode(buffer); } return; } try { @SuppressWarnings("unused") IonDatagram dg = loader().load(ionText); fail("Expected IonException"); } catch (IonException e) { } } }
Source:
<code>public static void validateNotSingleJobInstance(String definition, Collection<String> jobInstances) { JobSpecification jobSpecification = null; try { JobParser parser = new JobParser(); jobSpecification = parser.parse(definition); } catch (Exception e) { <START> return; END> } if (jobSpecification.getJobReferences().size() == 1) { String jobName = jobSpecification.getJobReferences().get(0).getName(); if (jobInstances.contains(jobName)) { throw new IllegalStateException(String.format( "Job Instance specified %s must use transitions. Or just " + "launch the job instance directly", jobName)); } } }</code><technical_language>swallowing this</technical_language>

Target:
public static void validateNotSingleJobInstance(String definition, Collection<String> jobInstances) { JobSpecification jobSpecification = null; try { JobParser parser = new JobParser(); jobSpecification = parser.parse(definition); } catch (JobSpecificationException e) { return; } if (jobSpecification.getJobReferences().size() == 1) { String jobName = jobSpecification.getJobReferences().get(0).getName(); if (jobInstances.contains(jobName)) { throw new IllegalStateException(String.format( "Job Instance specified %s must use transitions. Or just " + "launch the job instance directly", jobName)); } } }
Source:
<code>public void tearDown() throws Exception { <START> System.setProperty("BUCKET", ""); <END> System.setProperty("CONNECTIONS", ""); System.setProperty("ENABLED", ""); System.setProperty("ALLOW_ENV_PARAMETRIZATION", ""); }</code><technical_language>This sets system property empty strings remove it. extra leave behind, [clearProperty](<LINK_0> instead</technical_language>

Target:
public void tearDown() throws Exception { System.clearProperty("BUCKET"); System.clearProperty("CONNECTIONS"); System.clearProperty("ENABLED"); System.clearProperty("ALLOW_ENV_PARAMETRIZATION"); }
Source:
<code>public void testConvertToInterleavedStorageCommand() { ConvertToInterleavedStorageCommand cmd = new ConvertToInterleavedStorageCommand(); <START> Assert.assertTrue(cmd.apply(bkFlags, new String[] { "" })); <END> }</code><technical_language>I verify command is executing expected. e.g. verify if methods called</technical_language>

Target:
public void testConvertToInterleavedStorageCommand() { ConvertToInterleavedStorageCommand cmd = new ConvertToInterleavedStorageCommand(); Assert.assertTrue(cmd.apply(bkFlags, new String[] { "" })); try { verifyNew(ServerConfiguration.class).withArguments(eq(conf)); verifyNew(LedgerDirsManager.class, times(2)) .withArguments(eq(conf), any(File[].class), any(DiskChecker.class)); verifyNew(DbLedgerStorage.class, times(1)).withNoArguments(); verifyNew(InterleavedLedgerStorage.class, times(1)).withNoArguments(); verify(dbStorage, times(1)).initialize(eq(conf), eq(null), any(LedgerDirsManager.class), any(LedgerDirsManager.class), eq(null), any(CheckpointSource.class), any(Checkpointer.class), eq(NullStatsLogger.INSTANCE), eq(PooledByteBufAllocator.DEFAULT)); verify(interleavedLedgerStorage, times(1)) .initialize(eq(conf), eq(null), any(LedgerDirsManager.class), any(LedgerDirsManager.class), eq(null), any(CheckpointSource.class), any(Checkpointer.class), eq(NullStatsLogger.INSTANCE), eq(PooledByteBufAllocator.DEFAULT)); verify(dbStorage, times(1)).getActiveLedgersInRange(anyLong(), anyLong()); verify(dbStorage, times(10)).readMasterKey(anyLong()); verify(interleavedLedgerStorage, times(10)).setMasterKey(anyLong(), any()); verify(dbStorage, times(10)).getLastEntryInLedger(anyLong()); verify(dbStorage, times(10)).getLocation(anyLong(), anyLong()); verify(dbStorage, times(1)).shutdown(); verify(interleavedLedgerCache, times(1)).flushLedger(true); verify(interleavedLedgerStorage, times(1)).flush(); verify(interleavedLedgerStorage, times(1)).shutdown(); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } }
Source:
<code>public T set(final int index, final T element) { try { return this.origin.set(index, element); } catch (final IndexOutOfBoundsException ex) { <START> throw new IllegalArgumentException(this.message, ex); <END> } }</code><technical_language>@Happy-Neko here, throw IndexOutOfBoundsException custom message</technical_language>

Target:
public T set(final int index, final T element) { try { return this.origin.set(index, element); } catch (final IndexOutOfBoundsException ex) { throw this.wrapException(ex); } }
Source:
<code>private static FunctionMetadata methodToFunctionMetadata(ScalarTranslationHeader header, Method method) { requireNonNull(header, "header is null"); SqlType annotatedReturnType = method.getAnnotation(SqlType.class); checkArgument(annotatedReturnType != null, format("Method [%s] is missing @SqlType annotation", method)); TypeSignature returnType = parseTypeSignature(annotatedReturnType.value(), ImmutableSet.of()); ImmutableList.Builder<TypeSignature> argumentTypes = new ImmutableList.Builder<>(); for (Parameter parameter : method.getParameters()) { Annotation[] annotations = parameter.getAnnotations(); SqlType type = Stream.of(annotations) .filter(SqlType.class::isInstance) .map(SqlType.class::cast) .findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Method [%s] is missing @SqlType annotation for parameter", method))); TypeSignature typeSignature = parseTypeSignature(type.value(), ImmutableSet.of()); argumentTypes.add(typeSignature); } if (header.getOperatorType().isPresent()) { return new FunctionMetadata(header.getOperatorType().get(), argumentTypes.build(), returnType, SCALAR, header.isDeterministic(), header.isCalledOnNullInput()); } <START> else { <END> return new FunctionMetadata(header.getName(), argumentTypes.build(), returnType, SCALAR, header.isDeterministic(), header.isCalledOnNullInput()); } }</code><technical_language>else { is redundant</technical_language>

Target:
private static FunctionMetadata methodToFunctionMetadata(ScalarTranslationHeader header, Method method) { requireNonNull(header, "header is null"); SqlType annotatedReturnType = method.getAnnotation(SqlType.class); checkArgument(annotatedReturnType != null, format("Method [%s] is missing @SqlType annotation", method)); TypeSignature returnType = parseTypeSignature(annotatedReturnType.value(), ImmutableSet.of()); ImmutableList.Builder<TypeSignature> argumentTypes = new ImmutableList.Builder<>(); for (Parameter parameter : method.getParameters()) { Annotation[] annotations = parameter.getAnnotations(); SqlType type = Stream.of(annotations) .filter(SqlType.class::isInstance) .map(SqlType.class::cast) .findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Method [%s] is missing @SqlType annotation for parameter", method))); TypeSignature typeSignature = parseTypeSignature(type.value(), ImmutableSet.of()); argumentTypes.add(typeSignature); } if (header.getOperatorType().isPresent()) { return new FunctionMetadata(header.getOperatorType().get(), argumentTypes.build(), returnType, SCALAR, header.isDeterministic(), header.isCalledOnNullInput()); } return new FunctionMetadata(header.getName(), argumentTypes.build(), returnType, SCALAR, header.isDeterministic(), header.isCalledOnNullInput()); }
Source:
<code>Pair<String, String> doWork(Map<String, String> statsWrappersJSON) throws IOException { StatsSnapshot partitionSnapshot = new StatsSnapshot(0L, new HashMap<String, StatsSnapshot>()); Map<String, Long> partitionTimestampMap = new HashMap<>(); StatsSnapshot rawPartitionSnapshot = new StatsSnapshot(0L, new HashMap<String, StatsSnapshot>()); for (Map.Entry<String, String> statsWrapperJSON : statsWrappersJSON.entrySet()) { if (statsWrapperJSON != null) { StatsWrapper snapshotWrapper = mapper.readValue(statsWrapperJSON.getValue(), StatsWrapper.class); StatsWrapper snapshotWrapperCopy = mapper.readValue(statsWrapperJSON.getValue(), StatsWrapper.class); combineRaw(rawPartitionSnapshot, snapshotWrapper); combine(partitionSnapshot, snapshotWrapperCopy, statsWrapperJSON.getKey(), partitionTimestampMap); } } <START> logger.info("Reduced raw snapshot {}", mapper.writeValueAsString(rawPartitionSnapshot)); <END> logger.info("Reduced snapshot {}", mapper.writeValueAsString(partitionSnapshot)); StatsSnapshot reducedRawSnapshot = reduce(rawPartitionSnapshot); StatsSnapshot reducedSnapshot = reduce(partitionSnapshot); return new Pair<>(mapper.writeValueAsString(reducedRawSnapshot), mapper.writeValueAsString(reducedSnapshot)); }</code><technical_language>non-reduced snapshots, right</technical_language>

Target:
Pair<String, String> doWork(Map<String, String> statsWrappersJSON) throws IOException { StatsSnapshot partitionSnapshot = new StatsSnapshot(0L, new HashMap<String, StatsSnapshot>()); Map<String, Long> partitionTimestampMap = new HashMap<>(); StatsSnapshot rawPartitionSnapshot = new StatsSnapshot(0L, new HashMap<String, StatsSnapshot>()); for (Map.Entry<String, String> statsWrapperJSON : statsWrappersJSON.entrySet()) { if (statsWrapperJSON != null) { StatsWrapper snapshotWrapper = mapper.readValue(statsWrapperJSON.getValue(), StatsWrapper.class); StatsWrapper snapshotWrapperCopy = mapper.readValue(statsWrapperJSON.getValue(), StatsWrapper.class); combineRaw(rawPartitionSnapshot, snapshotWrapper); combine(partitionSnapshot, snapshotWrapperCopy, statsWrapperJSON.getKey(), partitionTimestampMap); } } if (logger.isTraceEnabled()) { logger.trace("Combined raw snapshot {}", mapper.writeValueAsString(rawPartitionSnapshot)); logger.trace("Combined snapshot {}", mapper.writeValueAsString(partitionSnapshot)); } StatsSnapshot reducedRawSnapshot = reduce(rawPartitionSnapshot); StatsSnapshot reducedSnapshot = reduce(partitionSnapshot); if (logger.isTraceEnabled()) { logger.trace("Reduced raw snapshot {}", mapper.writeValueAsString(reducedRawSnapshot)); logger.trace("Reduced snapshot {}", mapper.writeValueAsString(reducedSnapshot)); } return new Pair<>(mapper.writeValueAsString(reducedRawSnapshot), mapper.writeValueAsString(reducedSnapshot)); }