auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void setDebugContext(ISelection s) { ICommandControlDMContext context = null; fMultiple = false; if (s instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) s; if (ss.size() > 0) { @SuppressWarnings("rawtypes") Iterator i = ss.iterator(); context = getCommandControlContext(i.next()); while (i.hasNext()) <START> if (getCommandControlContext(i.next()) != context) { <END> context = null; fMultiple = true; break; } } } setDebugContext(context); }</code><technical_language>equals() compare contexts. dealing null, check first</technical_language>

Target:
private void setDebugContext(ISelection s) { ICommandControlDMContext context = null; fMultiple = false; if (s instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) s; if (ss.size() > 0) { @SuppressWarnings("rawtypes") Iterator i = ss.iterator(); context = getCommandControlContext(i.next()); while (i.hasNext()) { ICommandControlDMContext nextContext = getCommandControlContext(i.next()); if (nextContext == null && context != null || nextContext != null && context == null || nextContext != null && context != null && !nextContext.equals(context)) { context = null; fMultiple = true; break; } } } } setDebugContext(context); }
Source:
<code>private ExtMap processAuthzResult(ExtMap outMap, String operation) { if (outMap.<Integer> get(Base.InvokeKeys.RESULT) != Base.InvokeResult.SUCCESS) { throw new RuntimeException(String.format("Base.InvokeResult code is: %1$s. Invocation of %2$s failed", outMap.<Integer> get(Base.InvokeKeys.RESULT), operation)); } <START> logger.info(String.format("Successful invocation of %1$s", operation)); <END> if (outMap.<Integer> get(Authz.InvokeKeys.STATUS) != Authz.Status.SUCCESS) { throw new RuntimeException(String.format("Authz.Status code is: %1$s", outMap.<Integer> get(Authz.InvokeKeys.STATUS))); } logger.debug("PrincipalRecord: {}", outMap.get(Authz.InvokeKeys.PRINCIPAL_RECORD)); return outMap.get(Authz.InvokeKeys.PRINCIPAL_RECORD); }</code><technical_language>please {}</technical_language>

Target:
private ExtMap processAuthzResult(ExtMap outMap, String operation) { if (outMap.<Integer> get(Base.InvokeKeys.RESULT) != Base.InvokeResult.SUCCESS) { throw new RuntimeException(String.format("Base.InvokeResult code is: %1$s. Invocation of %2$s failed", outMap.<Integer> get(Base.InvokeKeys.RESULT), operation)); } log.info("Successful invocation of {}", operation); if (outMap.<Integer> get(Authz.InvokeKeys.STATUS) != Authz.Status.SUCCESS) { throw new RuntimeException(String.format("Authz.Status code is: %1$s", outMap.<Integer> get(Authz.InvokeKeys.STATUS))); } log.debug("PrincipalRecord: {}", outMap.get(Authz.InvokeKeys.PRINCIPAL_RECORD)); return outMap.get(Authz.InvokeKeys.PRINCIPAL_RECORD); }
Source:
<code>protected void setSystemProperty(String key, String newValue) { String originValue = System.getProperty(key); originSystemProps.put(key, originValue); <START> System.setProperty(key, newValue); <END> }</code><technical_language>@since 9.3 originSystemProps.put(key, System.setProperty(key, newValue));</technical_language>

Target:
protected void setSystemProperty(String key, String newValue) { originSystemProps.put(key, System.setProperty(key, newValue)); }
Source:
<code>public QueueStats apply(HttpResponse from) { QueueStats rawQueueStats = json.apply(from); if (rawQueueStats.getMessagesStats().getTotal() == 0) { return rawQueueStats; } else { Aged oldestWithHref = rawQueueStats.getMessagesStats().getOldest().get(); Aged oldestWithId = oldestWithHref.toBuilder() .id(ParseMessages.getMessageId(oldestWithHref.getId())) .build(); Aged newestWithHref = rawQueueStats.getMessagesStats().getNewest().get(); Aged newestWithId = newestWithHref.toBuilder() .id(ParseMessages.getMessageId(newestWithHref.getId())) <START> .build(); <END> MessagesStats messagesStatsWithIds = rawQueueStats.getMessagesStats().toBuilder() .oldest(oldestWithId) .newest(newestWithId) .build(); QueueStats queueStatsWithIds = rawQueueStats.toBuilder().messageStats(messagesStatsWithIds).build(); return queueStatsWithIds; } }</code><technical_language>Extract injectable function AgedWithHrefToId</technical_language>

Target:
public QueueStats apply(HttpResponse from) { QueueStats rawQueueStats = json.apply(from); if (rawQueueStats.getMessagesStats().getTotal() == 0) { return rawQueueStats; } else { Aged oldestWithHref = rawQueueStats.getMessagesStats().getOldest().get(); Aged oldestWithId = oldestWithHref.toBuilder() .id(TO_MESSAGE_ID.apply(oldestWithHref.getId())) .build(); Aged newestWithHref = rawQueueStats.getMessagesStats().getNewest().get(); Aged newestWithId = newestWithHref.toBuilder() .id(TO_MESSAGE_ID.apply(newestWithHref.getId())) .build(); MessagesStats messagesStatsWithIds = rawQueueStats.getMessagesStats().toBuilder() .oldest(oldestWithId) .newest(newestWithId) .build(); QueueStats queueStatsWithIds = rawQueueStats.toBuilder().messageStats(messagesStatsWithIds).build(); return queueStatsWithIds; } }
Source:
<code>private Receipt generateReceipt(@NonNull List<Distance> distancesThisDay) { if (distancesThisDay.isEmpty()) { throw new IllegalArgumentException("distancesThisDay must not be empty"); } final Distance distance0 = distancesThisDay.get(0); final ReceiptBuilderFactory factory = new ReceiptBuilderFactory(-1); final ArrayList<String> names = new ArrayList<>(); final ArrayList<String> comments = new ArrayList<>(); for (int i = 0; i < distancesThisDay.size(); i++) { final Distance distance = distancesThisDay.get(i); if (!names.contains(distance.getLocation())) { names.add(distance.getLocation()); } if (!TextUtils.isEmpty(distance.getComment()) && !comments.contains(distance.getComment())) { comments.add(distance.getComment()); } } if (names.isEmpty()) { factory.setName(context.getString(R.string.distance)); } else { factory.setName(TextUtils.join("; ", names)); } if (!comments.isEmpty()) { factory.setComment(TextUtils.join("; ", comments)); } factory.setTrip(distance0.getTrip()); factory.setDate(distance0.getDate()); factory.setFile(null); <START> factory.setImgHash(""); <END> factory.setIsReimbursable(true); factory.setTimeZone(distance0.getTimeZone()); factory.setCategory(new CategoryBuilderFactory().setName(context.getString(R.string.distance)).build()); factory.setCurrency(distance0.getTrip().getTripCurrency()); factory.setPrice(new PriceBuilderFactory().setPriceables(distancesThisDay, distance0.getTrip().getTripCurrency()).build()); return factory.build(); }</code><technical_language>set null instead (to align optional</technical_language>

Target:
private Receipt generateReceipt(@NonNull List<Distance> distancesThisDay) { if (distancesThisDay.isEmpty()) { throw new IllegalArgumentException("distancesThisDay must not be empty"); } final Distance distance0 = distancesThisDay.get(0); final ReceiptBuilderFactory factory = new ReceiptBuilderFactory(-1); final ArrayList<String> names = new ArrayList<>(); final ArrayList<String> comments = new ArrayList<>(); for (int i = 0; i < distancesThisDay.size(); i++) { final Distance distance = distancesThisDay.get(i); if (!names.contains(distance.getLocation())) { names.add(distance.getLocation()); } if (!TextUtils.isEmpty(distance.getComment()) && !comments.contains(distance.getComment())) { comments.add(distance.getComment()); } } if (names.isEmpty()) { factory.setName(context.getString(R.string.distance)); } else { factory.setName(TextUtils.join("; ", names)); } if (!comments.isEmpty()) { factory.setComment(TextUtils.join("; ", comments)); } factory.setTrip(distance0.getTrip()); factory.setDate(distance0.getDate()); factory.setFile(null); factory.setIsReimbursable(true); factory.setTimeZone(distance0.getTimeZone()); factory.setCategory(new CategoryBuilderFactory().setName(context.getString(R.string.distance)).build()); factory.setCurrency(distance0.getTrip().getTripCurrency()); factory.setPrice(new PriceBuilderFactory().setPriceables(distancesThisDay, distance0.getTrip().getTripCurrency()).build()); return factory.build(); }
Source:
<code>public Optional<Argument> build(Type type, Object value, StatementContext ctx) { <START> if (value instanceof Map) { <END> return Optional.of((i, p, cx) -> p.setObject(i, toString((Map<String, ?>) value), Types.OTHER)); } return Optional.empty(); }</code><technical_language>base this decision full type signature instanceof: if (Map.class.isAssignableFrom(GenericTypes.getErasedType(type)) && String.class == GenericTypes.resolveType(Map.class.getTypeParameters()[0], type) && String.class == GenericTypes.resolveType(Map.class.getTypeParameters()[1], type)) { factory able bind null correct SQL type</technical_language>

Target:
public Optional<Argument> build(Type type, Object value, StatementContext ctx) { if (Map.class.isAssignableFrom(GenericTypes.getErasedType(type))) { return Optional.of((i, p, cx) -> p.setObject(i, value)); } return Optional.empty(); }
Source:
<code>public static String getResponseBody(HttpResponse response) throws IDPTokenManagerException { String responseBody = null; HttpEntity entity = null; String message; try { entity = response.getEntity(); responseBody = getResponseBodyContent(entity); } catch (ParseException e) { message = "Invalid response."; throw new IDPTokenManagerException(message, e); } catch (IOException e) { if (entity != null) { try { entity.consumeContent(); } catch (IOException ex) { <START> message = "HTTP Response failure."; <END> throw new IDPTokenManagerException(message, e); } } } return responseBody; }</code><technical_language>Here, assigning log message a variable called "message" is redundant, I believe. Instead, pass message Exception instance</technical_language>

Target:
public static String getResponseBody(HttpResponse response) throws IDPTokenManagerException { String responseBody = null; HttpEntity entity = null; try { entity = response.getEntity(); responseBody = getResponseBodyContent(entity); } catch (ParseException e) { throw new IDPTokenManagerException("Invalid response.", e); } catch (IOException e) { if (entity != null) { try { entity.consumeContent(); } catch (IOException ex) { throw new IDPTokenManagerException("HTTP Response failure.", e); } } } return responseBody; }
Source:
<code>public String getValidityInfoForAllowedName(String fieldName, int maxLength, String value) { Assumption.assertTrue("Non-null value expected for " + fieldName, value != null); if (value.isEmpty()) { return getPopulatedErrorMessage(SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE, value, fieldName, REASON_EMPTY, maxLength); } if (isUntrimmed(value)) { return WHITESPACE_ONLY_OR_EXTRA_WHITESPACE_ERROR_MESSAGE.replace("${fieldName}", fieldName); } String sanitizedValue = SanitizationHelper.sanitizeForHtml(value); if (value.length() > maxLength) { return getPopulatedErrorMessage(SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE, sanitizedValue, fieldName, REASON_TOO_LONG, maxLength); } if (!Character.isLetterOrDigit(value.codePointAt(0))) { <START> boolean isStartWithBraces = value.charAt(0) == '{' && value.contains("}"); <END> if (!isStartWithBraces) { return getPopulatedErrorMessage(INVALID_NAME_ERROR_MESSAGE, sanitizedValue, fieldName, REASON_START_WITH_NON_ALPHANUMERIC_CHAR); } if (!StringHelper.isMatching(value.substring(1), REGEX_NAME)) { return getPopulatedErrorMessage(INVALID_NAME_ERROR_MESSAGE, sanitizedValue, fieldName, REASON_CONTAINS_INVALID_CHAR); } return ""; } if (!StringHelper.isMatching(value, REGEX_NAME)) { return getPopulatedErrorMessage(INVALID_NAME_ERROR_MESSAGE, sanitizedValue, fieldName, REASON_CONTAINS_INVALID_CHAR); } return ""; }</code><technical_language>prefixing is feels weird</technical_language>

Target:
public String getValidityInfoForAllowedName(String fieldName, int maxLength, String value) { Assumption.assertTrue("Non-null value expected for " + fieldName, value != null); if (value.isEmpty()) { return getPopulatedErrorMessage(SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE, value, fieldName, REASON_EMPTY, maxLength); } if (isUntrimmed(value)) { return WHITESPACE_ONLY_OR_EXTRA_WHITESPACE_ERROR_MESSAGE.replace("${fieldName}", fieldName); } String sanitizedValue = SanitizationHelper.sanitizeForHtml(value); if (value.length() > maxLength) { return getPopulatedErrorMessage(SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE, sanitizedValue, fieldName, REASON_TOO_LONG, maxLength); } if (!Character.isLetterOrDigit(value.codePointAt(0))) { boolean hasStartingBrace = value.charAt(0) == '{' && value.contains("}"); if (!hasStartingBrace) { return getPopulatedErrorMessage(INVALID_NAME_ERROR_MESSAGE, sanitizedValue, fieldName, REASON_START_WITH_NON_ALPHANUMERIC_CHAR); } if (!StringHelper.isMatching(value.substring(1), REGEX_NAME)) { return getPopulatedErrorMessage(INVALID_NAME_ERROR_MESSAGE, sanitizedValue, fieldName, REASON_CONTAINS_INVALID_CHAR); } return ""; } if (!StringHelper.isMatching(value, REGEX_NAME)) { return getPopulatedErrorMessage(INVALID_NAME_ERROR_MESSAGE, sanitizedValue, fieldName, REASON_CONTAINS_INVALID_CHAR); } return ""; }
Source:
<code>public void processMessage(final ObjectMessage message) { LOGGER.info("Processing public lighting get status request message"); String correlationUid = null; String messageType = null; String organisationIdentification = null; String deviceIdentification = null; GetDataRequest dataRequest = null; try { correlationUid = message.getJMSCorrelationID(); messageType = message.getJMSType(); organisationIdentification = message.getStringProperty(Constants.ORGANISATION_IDENTIFICATION); deviceIdentification = message.getStringProperty(Constants.DEVICE_IDENTIFICATION); <START> if (message.getObject() != null && message.getObject() instanceof GetDataRequest) { <END> dataRequest = (GetDataRequest) message.getObject(); } } catch (final JMSException e) { LOGGER.error("UNRECOVERABLE ERROR, unable to read ObjectMessage instance, giving up.", e); LOGGER.debug("correlationUid: {}", correlationUid); LOGGER.debug("messageType: {}", messageType); LOGGER.debug("organisationIdentification: {}", organisationIdentification); LOGGER.debug("deviceIdentification: {}", deviceIdentification); return; } try { LOGGER.info("Calling application service function: {}", messageType); this.adHocManagementService.getData(organisationIdentification, deviceIdentification, correlationUid, messageType, dataRequest); } catch (final Exception e) { this.handleError(e, correlationUid, organisationIdentification, deviceIdentification, messageType); } }</code><technical_language>null check removed, instanceof check well</technical_language>

Target:
public void processMessage(final ObjectMessage message) { LOGGER.info("Processing public lighting get status request message"); String correlationUid = null; String messageType = null; String organisationIdentification = null; String deviceIdentification = null; GetDataRequest dataRequest = null; try { correlationUid = message.getJMSCorrelationID(); messageType = message.getJMSType(); organisationIdentification = message.getStringProperty(Constants.ORGANISATION_IDENTIFICATION); deviceIdentification = message.getStringProperty(Constants.DEVICE_IDENTIFICATION); if (message.getObject() instanceof GetDataRequest) { dataRequest = (GetDataRequest) message.getObject(); } } catch (final JMSException e) { LOGGER.error("UNRECOVERABLE ERROR, unable to read ObjectMessage instance, giving up.", e); LOGGER.debug("correlationUid: {}", correlationUid); LOGGER.debug("messageType: {}", messageType); LOGGER.debug("organisationIdentification: {}", organisationIdentification); LOGGER.debug("deviceIdentification: {}", deviceIdentification); return; } try { LOGGER.info("Calling application service function: {}", messageType); this.adHocManagementService.getData(organisationIdentification, deviceIdentification, correlationUid, messageType, dataRequest); } catch (final Exception e) { this.handleError(e, correlationUid, organisationIdentification, deviceIdentification, messageType); } }
Source:
<code>public boolean supportsEventType(ResolvableType eventType) { if (this.eventTypes == null) { return true; } for (ResolvableType type : this.eventTypes) { if (type.isAssignableFrom(eventType)) { return true; } } <START> if (PayloadApplicationEvent.class.isAssignableFrom(eventType.getRawClass())) { <END> if (eventType.hasUnresolvableGenerics()) { return true; } ResolvableType payloadType = eventType.as(PayloadApplicationEvent.class).getGeneric(); for (ResolvableType type : this.eventTypes) { if (type.isAssignableFrom(payloadType)) { return true; } } } return false; }</code><technical_language>Needs a null check. getRawClass() return null</technical_language>

Target:
public boolean supportsEventType(ResolvableType eventType) { if (this.eventTypes == null) { return true; } for (ResolvableType type : this.eventTypes) { if (type.isAssignableFrom(eventType)) { return true; } } if (eventType.getRawClass() != null && PayloadApplicationEvent.class.isAssignableFrom(eventType.getRawClass())) { if (eventType.hasUnresolvableGenerics()) { return true; } ResolvableType payloadType = eventType.as(PayloadApplicationEvent.class).getGeneric(); for (ResolvableType type : this.eventTypes) { if (type.isAssignableFrom(payloadType)) { return true; } } } return false; }
Source:
<code>public static <T extends Widget> T serializeAndDeserialize( T instance ) throws Exception { byte[] bytes = serialize( instance ); T result = ( T )deserialize( bytes ); <START> Object adapter = result.getDisplay().getAdapter( IDisplayAdapter.class ); <END> IDisplayAdapter displayAdapter = ( IDisplayAdapter )adapter; displayAdapter.attachThread(); return result; }</code><technical_language>getAdapter() a generic interface, is need type cast anymore</technical_language>

Target:
public static <T> T serializeAndDeserialize( T instance ) throws Exception { byte[] bytes = serialize( instance ); return ( T )deserialize( bytes ); }
Source:
<code>public static String getPermissionStringValue(PermissionSet permissionSet) { if (permissionSet != null) { <START> int mask = permissionSet.getMask(); <END> switch (mask) { case READ_META_MASK: return READMETA; case COUNT_MASK: return COUNT; case READ_MASK: return READ; case WRITE_MASK: return WRITE; case WRITEMETA_MASK: return WRITEMETA; default: throw new IllegalArgumentException(format("Unexpected mask '%d'", mask)); } } return null; }</code><technical_language>Return Optional<String> for methods return null</technical_language>

Target:
public static String getPermissionStringValue(PermissionSet permissionSet) { if (permissionSet != null) { int mask = permissionSet.getMask(); switch (mask) { case READ_META_MASK: return READMETA; case COUNT_MASK: return COUNT; case READ_MASK: return READ; case WRITE_MASK: return WRITE; case WRITEMETA_MASK: return WRITEMETA; default: throw new IllegalArgumentException(format(UNEXPECTED_MASK_MESSAGE, mask)); } } return null; }
Source:
<code>public PointSensitivityBuilder rateSensitivity( PricingEnvironment env, OvernightCompoundedRateObservation observation, LocalDate startDate, LocalDate endDate) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>More informative message</technical_language>

Target:
public PointSensitivityBuilder rateSensitivity( PricingEnvironment env, OvernightCompoundedRateObservation observation, LocalDate startDate, LocalDate endDate) { throw new UnsupportedOperationException("Rate sensitivity for OvernightIndex not currently supported"); }
Source:
<code>public static Schema addFieldToSchema(Schema schema, String addFieldKey) { List<Schema.Field> newFields = new ArrayList<>(); <START> for (Schema.Field field : schema.getFields()) { <END> newFields.add(field); } Schema.Field newField = Schema.Field.of(addFieldKey, Schema.of(Schema.Type.STRING)); newFields.add(newField); return Schema.recordOf(schema.getRecordName(), newFields); }</code><technical_language>replace this newFields = new ArrayList<>(schema.getFields().size() + 1); newField.addAll(schema.getFields());</technical_language>

Target:
public static Schema addFieldToSchema(Schema schema, String addFieldKey) { List<Schema.Field> newFields = new ArrayList<>(schema.getFields().size() + 1); newFields.addAll(schema.getFields()); Schema.Field newField = Schema.Field.of(addFieldKey, Schema.of(Schema.Type.STRING)); newFields.add(newField); return Schema.recordOf(schema.getRecordName(), newFields); }
Source:
<code>public VolumeList startCreateVolume(OmVolumeArgs args) throws IOException { try { <START> if(isAclEnabled) { <END> checkAcls(ResourceType.VOLUME, StoreType.OZONE, ACLType.CREATE, args.getVolume(), null, null); } VolumeList volumeList = volumeManager.createVolume(args); return volumeList; } catch (Exception ex) { throw ex; } }</code><technical_language>Nitpick: need space if ( This needs fixed in multiple places</technical_language>

Target:
public VolumeList startCreateVolume(OmVolumeArgs args) throws IOException { if(isAclEnabled) { checkAcls(ResourceType.VOLUME, StoreType.OZONE, ACLType.CREATE, args.getVolume(), null, null); } VolumeList volumeList = volumeManager.createVolume(args); return volumeList; }
Source:
<code>public void addTab(final DialogTab tab) { tabContainer.add(tab); tab.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { switchTab(tab); } }); tab.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { <START> if (32 == event.getNativeKeyCode()) { <END> switchTab(tab); } } }); if (tabContainer.getWidgetCount() == 1) { switchTab(tab); } }</code><technical_language>please extract this magic number a named constant</technical_language>

Target:
public void addTab(final DialogTab tab) { tabContainer.add(tab); tab.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { switchTab(tab); } }); tab.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { if (SPACE_KEY_CODE == event.getNativeKeyCode()) { switchTab(tab); } } }); if (tabContainer.getWidgetCount() == 1) { switchTab(tab); } }
Source:
<code>private void setupFieldList() { final String selectField = translate(GuidedDecisionTableErraiConstants.FieldPageView_SelectField); fieldsList.clear(); fieldsList.addItem("-- " + selectField + " --", ""); <START> page.forEachFactField(fieldName -> fieldsList.addItem(fieldName)); <END> fieldsList.setSelectedIndex(getCurrentIndexFromList(getCurrentValue(), fieldsList)); }</code><technical_language>a "unwinding" I code OK</technical_language>

Target:
public void setupFieldList() { final String selectField = translate(GuidedDecisionTableErraiConstants.FieldPageView_SelectField); fieldsList.clear(); fieldsList.addItem("-- " + selectField + " --", ""); }
Source:
<code><START> public void testDoubleBufferedBlockResettableIterator() throws Exception <END> { final BlockResettableMutableObjectIterator<Record> iterator = new BlockResettableMutableObjectIterator<Record>(this.memman, this.reader, this.serializer, 2, memOwner); iterator.open(); int lower = 0; int upper = 0; do { lower = upper; upper = lower; Record target = new Record(); while ((target = iterator.next(target)) != null) { int val = target.getField(0, IntValue.class).getValue(); Assert.assertEquals(upper++, val); } for (int i = 0; i < 5; ++i) { iterator.reset(); target = new Record(); int count = 0; while ((target = iterator.next(target)) != null) { int val = target.getField(0, IntValue.class).getValue(); Assert.assertEquals(lower + (count++), val); } Assert.assertEquals(upper - lower, count); } } while (iterator.nextBlock()); Assert.assertEquals(NUM_VALUES, upper); iterator.close(); }</code><technical_language>correctly fails in case of exception</technical_language>

Target:
public void testDoubleBufferedBlockResettableIterator() throws Exception { try { final BlockResettableMutableObjectIterator<Record> iterator = new BlockResettableMutableObjectIterator<Record>(this.memman, this.reader, this.serializer, 2, memOwner); iterator.open(); int lower = 0; int upper = 0; do { lower = upper; upper = lower; Record target = new Record(); while ((target = iterator.next(target)) != null) { int val = target.getField(0, IntValue.class).getValue(); Assert.assertEquals(upper++, val); } for (int i = 0; i < 5; ++i) { iterator.reset(); target = new Record(); int count = 0; while ((target = iterator.next(target)) != null) { int val = target.getField(0, IntValue.class).getValue(); Assert.assertEquals(lower + (count++), val); } Assert.assertEquals(upper - lower, count); } } while (iterator.nextBlock()); Assert.assertEquals(NUM_VALUES, upper); iterator.close(); } catch (Exception ex) { Assert.fail("Test encountered an exception: " + ex.getMessage()); } }
Source:
<code>public static CloseableHttpResponse executeHTTPRequest(HttpRequestBase method, HttpClient httpClient) throws IOException, ArtifactSynchronizerException { CloseableHttpResponse httpResponse = null; int retryCount = 0; boolean retry; do { try { httpResponse = (CloseableHttpResponse) httpClient.execute(method); retry = false; } catch (IOException ex) { retryCount++; if (retryCount < retries) { retry = true; log.warn("Failed retrieving from remote endpoint: " + ex.getMessage() + ". Retrying after " + timeoutInSeconds + " seconds."); try { Thread.sleep(timeoutInSeconds * 1000); } catch (InterruptedException e) { } } else { throw ex; } } } while (retry); if (httpResponse.getStatusLine().getStatusCode() == 200) { return httpResponse; } else { httpResponse.close(); String errorMessage = EntityUtils.toString(httpResponse.getEntity(), APIConstants.DigestAuthConstants.CHARSET); <START> throw new ArtifactSynchronizerException(errorMessage + "Eevnthub status code is:" <END> + httpResponse.getStatusLine().getStatusCode()); } }</code><technical_language>Typo add a space</technical_language>

Target:
public static CloseableHttpResponse executeHTTPRequest(HttpRequestBase method, HttpClient httpClient) throws IOException, ArtifactSynchronizerException { CloseableHttpResponse httpResponse = null; int retryCount = 0; boolean retry; do { try { httpResponse = (CloseableHttpResponse) httpClient.execute(method); retry = false; } catch (IOException ex) { retryCount++; if (retryCount < retries) { retry = true; log.warn("Failed retrieving from remote endpoint: " + ex.getMessage() + ". Retrying after " + timeoutInSeconds + " seconds."); try { Thread.sleep(timeoutInSeconds * 1000); } catch (InterruptedException e) { } } else { throw ex; } } } while (retry); if (httpResponse.getStatusLine().getStatusCode() == 200) { return httpResponse; } else { httpResponse.close(); String errorMessage = EntityUtils.toString(httpResponse.getEntity(), APIConstants.DigestAuthConstants.CHARSET); throw new ArtifactSynchronizerException(errorMessage + "Event-Hub status code is : " + httpResponse.getStatusLine().getStatusCode()); } }
Source:
<code>private static void clearPrefixedSystemProperties(String prefix, Map<String, String> targetPropertyMap) { for (Object <START> element : <END> System.getProperties().keySet()) { String propertyName = (String) element; if (propertyName.startsWith(prefix) && !targetPropertyMap.containsKey(propertyName)) { targetPropertyMap.put(propertyName, null); } } }</code><technical_language>rename key</technical_language>

Target:
private static void clearPrefixedSystemProperties(String prefix, Map<String, String> targetPropertyMap) { for (Object key : System.getProperties().keySet()) { String propertyName = (String) key; if (propertyName.startsWith(prefix) && !targetPropertyMap.containsKey(propertyName)) { targetPropertyMap.put(propertyName, null); } } }
Source:
<code>public void testBandMergeWithNodata() throws FileNotFoundException, IOException { double noDataValue = -10000d; Range nodata = RangeFactory.create(noDataValue, noDataValue); double[] background = new double[] {noDataValue}; RenderedImage twoBands = null; PlanarImage pi = PlanarImage.wrapRenderedImage(imageWithNodata2); pi.setProperty("GC_NODATA", new NoDataContainer(nodata)); ImageWorker worker = <START> new ImageWorker() <END> .setNoData(nodata) .setBackground(background) .mosaic( new RenderedImage[] {pi}, MosaicDescriptor.MOSAIC_TYPE_OVERLAY, null, null, new double[][] {{-32768}}, null); twoBands = worker.addBand(worker.getRenderedImage(), false).getRenderedImage(); RenderedImage singleBand = new ImageWorker(twoBands).retainBands(1).getRenderedImage(); RenderedImage threeBands = new ImageWorker(twoBands).addBand(singleBand, false).getRenderedImage(); double[] threeSamples = new double[3]; threeBands.getData().getPixel(18, 18, threeSamples); for (double sample : threeSamples) { assertEquals(noDataValue, sample, 1E-6); } }</code><technical_language>mosaic in test? code changes not</technical_language>

Target:
public void testBandMergeWithNodata() throws FileNotFoundException, IOException { double noDataValue = -10000d; Range nodata = RangeFactory.create(noDataValue, noDataValue); double[] background = new double[] {noDataValue}; RenderedImage twoBands = null; PlanarImage pi = PlanarImage.wrapRenderedImage(imageWithNodata2); pi.setProperty("GC_NODATA", new NoDataContainer(nodata)); ImageWorker worker = new ImageWorker(pi).setNoData(nodata).setBackground(background); twoBands = worker.addBand(worker.getRenderedImage(), false).getRenderedImage(); RenderedImage oneBand = new ImageWorker(twoBands).retainBands(1).getRenderedImage(); RenderedImage threeBands = new ImageWorker(twoBands).addBand(oneBand, false).getRenderedImage(); double[] threeSamples = new double[3]; threeBands.getData().getPixel(18, 18, threeSamples); for (double sample : threeSamples) { assertEquals(noDataValue, sample, 1E-6); } }
Source:
<code>public void invalidate(final boolean direct) { if (direct) { <START> layoutState = LAYOUT_REDO; <END> } else if (layoutState != LAYOUT_REDO) { layoutState = LAYOUT_PROPAGATE; } if (getParent() instanceof AbstractBlockBox) { ((AbstractBlockBox) getParent()).invalidate(false); } }</code><technical_language>If needed anymore, delete ;-)</technical_language>

Target:
public void invalidate(final boolean direct) { if (direct) { layoutState = LAYOUT_REDO; } else { layoutState = LAYOUT_PROPAGATE; } if (getParent() instanceof AbstractBlockBox) { ((AbstractBlockBox) getParent()).invalidate(false); } }
Source:
<code>private void getRowCount(){ JsonNode jn = ((DatabaseClientImpl) client).getServices() .getResource(null, "internal/viewinfo", null, params, new JacksonHandle()) <START> .get(); <END> long batchCount = (this.rowCount/this.batchSize); this.bucketSize = (Long.MAX_VALUE/batchCount); }</code><technical_language>of rowCount in calculation current line 248 is obtained internal/viewinfo request. This method get of tableID rowCount properties JsonNode assign private fields of RowBatcherImpl</technical_language>

Target:
private void getRowCount(){ JsonNode jn = ((DatabaseClientImpl) getPrimaryClient()).getServices() .getResource(null, "internal/viewinfo", null, params, new JacksonHandle()) .get(); long batchCount = (this.rowCount/super.getBatchSize()); this.bucketSize = (Long.MAX_VALUE/batchCount); }
Source:
<code>private void activateContextService() { <START> fActiveContexts.add(fContextService.activateContext(CONTEXT)); <END> }</code><technical_language>called focusGained mouseEnter, active contexts. one</technical_language>

Target:
private void activateContextService() { if(!fActiveContexts.isEmpty()) { deactivateContextService(); } fActiveContexts.add(fContextService.activateContext(CONTEXT)); }
Source:
<code>public SeekableByteChannel buildChannel(final String key) throws IOException { final Path objectPath = this.root.resolve(key); final Path parentPath = objectPath.getParent(); if (parentPath != null) { Files.createDirectories(FileUtils.resolveForSymbolic(parentPath)); } if (!FileUtils.isTransferablePath(objectPath)) { throw new UnrecoverableIOException(objectPath + " is not a regular file."); } try { <START> striped.get(key).lock(); <END> if (Files.notExists(objectPath)) { Files.createDirectories(objectPath.getParent()); return FileChannel.open( objectPath, StandardOpenOption.SPARSE, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW ); } } finally { striped.get(key).unlock(); } return FileChannel.open( objectPath, StandardOpenOption.WRITE ); }</code><technical_language>get lock instead of twice</technical_language>

Target:
public SeekableByteChannel buildChannel(final String key) throws IOException { final Path objectPath = this.root.resolve(key); final Path parentPath = objectPath.getParent(); if (parentPath != null) { Files.createDirectories(FileUtils.resolveForSymbolic(parentPath)); } if (!FileUtils.isTransferablePath(objectPath)) { throw new UnrecoverableIOException(objectPath + " is not a regular file."); } final Lock lock = striped.get(key); try { lock.lock(); if (Files.notExists(objectPath)) { Files.createDirectories(objectPath.getParent()); return FileChannel.open( objectPath, StandardOpenOption.SPARSE, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW ); } } finally { lock.unlock(); } return FileChannel.open( objectPath, StandardOpenOption.WRITE ); }
Source:
<code>private boolean updateVmLease() { if (Objects.equals(oldVm.getLeaseStorageDomainId(), newVmStatic.getLeaseStorageDomainId())) { return true; } if (getVm().isDown()) { if (!addVmLease(newVmStatic.getLeaseStorageDomainId(), newVmStatic.getId())){ return false; } removeVmLease(oldVm.getLeaseStorageDomainId(), oldVm.getId()); } else { if (oldVm.getLeaseStorageDomainId() != null) { runVdsCommand(VDSCommandType.HotUnplugLease, new LeaseVDSParameters(getVm().getRunOnVds(), oldVm.getId(), oldVm.getLeaseStorageDomainId())); <START> removeVmLease(oldVm.getLeaseStorageDomainId(), oldVm.getId()); <END> } else { VmLeaseParameters params = new VmLeaseParameters(getStoragePoolId(), newVmStatic.getLeaseStorageDomainId(), newVmStatic.getId()); params.setVdsId(getVm().getRunOnVds()); return runInternalAction(VdcActionType.HotPlugLease, params).getSucceeded(); } } return true; }</code><technical_language>consider adding a log failure</technical_language>

Target:
private boolean updateVmLease() { if (Objects.equals(oldVm.getLeaseStorageDomainId(), newVmStatic.getLeaseStorageDomainId())) { return true; } if (getVm().isDown()) { if (!addVmLease(newVmStatic.getLeaseStorageDomainId(), newVmStatic.getId())){ return false; } removeVmLease(oldVm.getLeaseStorageDomainId(), oldVm.getId()); } else { if (oldVm.getLeaseStorageDomainId() != null) { runVdsCommand(VDSCommandType.HotUnplugLease, new LeaseVDSParameters(getVm().getRunOnVds(), oldVm.getId(), oldVm.getLeaseStorageDomainId())); removeVmLease(oldVm.getLeaseStorageDomainId(), oldVm.getId()); } else { VmLeaseParameters params = new VmLeaseParameters(getStoragePoolId(), newVmStatic.getLeaseStorageDomainId(), newVmStatic.getId()); params.setVdsId(getVm().getRunOnVds()); params.setHotPlugLease(true); return runInternalAction(VdcActionType.AddVmLease, params).getSucceeded(); } } return true; }
Source:
<code>private void updateTable() { fTree.setItemCount(0); if (fTrace == null) { return; } ITmfTrace[] traces; if (fTrace instanceof TmfExperiment) { TmfExperiment experiment = (TmfExperiment) fTrace; traces = experiment.getTraces(); } else { traces = new ITmfTrace[] { fTrace }; } for (ITmfTrace trace : traces) { if (trace instanceof CtfTmfTrace) { TreeItem item = new TreeItem(fTree, SWT.NONE); item.setText(0, trace.getName()); CtfTmfTrace ctfTrace = (CtfTmfTrace) trace; for (String varName : ctfTrace.getEnvNames()) { TreeItem subItem = new TreeItem(item, SWT.NONE); subItem.setText(0, varName); subItem.setText(1, ctfTrace.getEnvValue(varName)); <START> } <END> } } for (TreeColumn column : fTree.getColumns()) { column.pack(); } }</code><technical_language>For pack effective column, avoid for user need expand trace items, I suggest set expanded state true for root items here</technical_language>

Target:
private void updateTable() { fTree.setItemCount(0); if (fTrace == null) { return; } ITmfTrace[] traces; if (fTrace instanceof TmfExperiment) { TmfExperiment experiment = (TmfExperiment) fTrace; traces = experiment.getTraces(); } else { traces = new ITmfTrace[] { fTrace }; } for (ITmfTrace trace : traces) { if (trace instanceof CtfTmfTrace) { TreeItem item = new TreeItem(fTree, SWT.NONE); item.setText(0, trace.getName()); CtfTmfTrace ctfTrace = (CtfTmfTrace) trace; for (String varName : ctfTrace.getEnvNames()) { TreeItem subItem = new TreeItem(item, SWT.NONE); subItem.setText(0, varName); subItem.setText(1, ctfTrace.getEnvValue(varName)); } } } for (TreeColumn column : fTree.getColumns()) { column.pack(); } for (int i = 0; i < fTree.getItemCount(); i++) { fTree.getItem(i).setExpanded(true); } }
Source:
<code><START> public static void preloadXmlAnalysesOutput(File xmlFile) { <END> if (!xmlValidate(xmlFile).isOK()) { return; } removeXmlOutput(xmlFile.getAbsolutePath()); try { Document doc = XmlUtils.getDocumentFromFile(xmlFile); for (OutputType outputType : OutputType.values()) { NodeList outputNodes = doc.getElementsByTagName(outputType.getXmlElem()); for (int i = 0; i < outputNodes.getLength(); i++) { Set<String> analysesId = new HashSet<>(); Element node = (Element) outputNodes.item(i); List<Element> headNodes = TmfXmlUtils.getChildElements(node, TmfXmlStrings.HEAD); if (headNodes.size() != 1) { return; } Element headElement = headNodes.get(0); List<Element> analysisNodes = TmfXmlUtils.getChildElements(headElement, TmfXmlStrings.ANALYSIS); for (Element analysis : analysisNodes) { String analysisId = analysis.getAttribute(TmfXmlStrings.ID); analysesId.add(analysisId); } String outputId = node.getAttribute(TmfXmlStrings.ID); List<Element> label = TmfXmlUtils.getChildElements(headNodes.get(0), TmfXmlStrings.LABEL); if (label.isEmpty()) { return; } Element labelElement = label.get(0); String outputLabel = labelElement.getAttribute(TmfXmlStrings.VALUE); XmlOutputElement output = new XmlOutputElement(xmlFile.getAbsolutePath(), outputType.getXmlElem(), outputId, outputLabel, analysesId); AddXmlOutput(output); } } } catch (ParserConfigurationException | SAXException | IOException e) { Activator.logError("Error opening XML file", e); } }</code><technical_language>this private called other utility methods, addXmlFiles (or load?) initOutput</technical_language>

Target:
public static void preloadXmlAnalysesOutput(File xmlFile) { if (!xmlValidate(xmlFile).isOK()) { return; } removeXmlOutput(xmlFile.getAbsolutePath()); try { Document doc = XmlUtils.getDocumentFromFile(xmlFile); for (OutputType outputType : OutputType.values()) { NodeList outputNodes = doc.getElementsByTagName(outputType.getXmlElem()); for (int i = 0; i < outputNodes.getLength(); i++) { Set<String> analysesId = new HashSet<>(); Element node = (Element) outputNodes.item(i); List<Element> headNodes = TmfXmlUtils.getChildElements(node, TmfXmlStrings.HEAD); if (headNodes.size() != 1) { return; } Element headElement = headNodes.get(0); List<Element> analysisNodes = TmfXmlUtils.getChildElements(headElement, TmfXmlStrings.ANALYSIS); for (Element analysis : analysisNodes) { String analysisId = analysis.getAttribute(TmfXmlStrings.ID); analysesId.add(analysisId); } String outputId = node.getAttribute(TmfXmlStrings.ID); List<Element> label = TmfXmlUtils.getChildElements(headNodes.get(0), TmfXmlStrings.LABEL); if (label.isEmpty()) { return; } Element labelElement = label.get(0); String outputLabel = labelElement.getAttribute(TmfXmlStrings.VALUE); XmlOutputElement output = new XmlOutputElement(xmlFile.getAbsolutePath(), outputType.getXmlElem(), outputId, outputLabel, analysesId); addXmlOutput(output); } } updateCachedOuputElements(); } catch (ParserConfigurationException | SAXException | IOException e) { Activator.logError("Error opening XML file", e); } }
Source:
<code>public GitRepository(URI repositoryUri, String branch, String cacheDirectoryPath, LocalRepository.Factory localRepositoryFactory, FileUtilities fileUtilities) { super(); this.fileUtilities = fileUtilities; this.repositoryUri = repositoryUri; this.branch = branch == null ? "master" : branch; this.localRepositoryFactory = localRepositoryFactory; this.localFolder = createRepositoryLocation(cacheDirectoryPath); <START> this.lockFile = new File(this.localFolder.getAbsolutePath() + "_lock"); <END> }</code><technical_language>file .lock for lock files</technical_language>

Target:
public GitRepository(URI repositoryUri, String branch, String cacheDirectoryPath, LocalRepository.Factory localRepositoryFactory, FileUtilities fileUtilities) { super(); this.fileUtilities = fileUtilities; this.repositoryUri = repositoryUri; this.branch = branch == null ? "master" : branch; this.localRepositoryFactory = localRepositoryFactory; this.localFolder = createRepositoryLocation(cacheDirectoryPath); this.lockFile = new File(this.localFolder.getAbsolutePath() + ".lock"); }
Source:
<code>public void execute(final Scenario scenario) throws Throwable { Timeout.timeout(new Timeout.Callback<Object>() { @Override public Object call() throws Throwable { backend.invoke(body, new Object[]{scenario}); return null; } }, timeout); <START> } <END></code><technical_language>worked == - glad gone</technical_language>

Target:
public void execute(final Scenario scenario) throws Throwable { Timeout.timeout(new Timeout.Callback<Object>() { @Override public Object call() throws Throwable { backend.invoke(body, new Object[]{scenario}); return null; } }, timeoutMillis); }
Source:
<code>public void clientVersion(final String version) { final String name = name(group, TYPE + "_meter_client_version", version); Meter m = clientVersionMeters.get(name); if (m == null) { m = registry.meter(name); <START> clientVersionMeters.put(name, m); <END> } m.mark(); }</code><technical_language>MetricRegistry maintains a ConcurrentHashMap for of registered metrics, examines call register.meter(name), feels do map-keeping here, is pretty try request a metric this name a meter</technical_language>

Target:
public void clientVersion(final String version) { final String name = name(group, TYPE + "_meter_client_version", version); registry.meter(name).mark(); }
Source:
<code>public boolean hasNext() { for (;;) { <START> if (currentChunk != null && currentChunk.hasNext()) { <END> return true; } else if (iteratorOverChunks.hasNext()) { currentChunk = nextChunk(); } else { return false; } } }</code><technical_language>else conditions dropped of return. decrease cognitive complexity</technical_language>

Target:
public boolean hasNext() { for (;;) { if (currentChunk != null && currentChunk.hasNext()) { return true; } if (iteratorOverChunks.hasNext()) { currentChunk = nextChunk(); } else { return false; } } }
Source:
<code>void beforeReleaseWrite(FullPageId pageId, long ptr, boolean pageWalRec) throws IgniteCheckedException { <START> boolean walIsNotDisable = !walMgr.disabled(pageId.groupId()); <END> boolean pageRecOrAlwaysWriteFullPage = walMgr != null && (pageWalRec || walMgr.isAlwaysWriteFullPages()); if (pageRecOrAlwaysWriteFullPage && walIsNotDisable) walMgr.log(new PageSnapshot(pageId, ptr, pageSize(), realPageSize(pageId.groupId()))); }</code><technical_language>walMgr != null check missed. refactoring this code block null WAL manager executed</technical_language>

Target:
void beforeReleaseWrite(FullPageId pageId, long ptr, boolean pageWalRec) throws IgniteCheckedException { boolean walIsNotDisable = walMgr != null && !walMgr.disabled(pageId.groupId()); boolean pageRecOrAlwaysWriteFullPage = walMgr != null && (pageWalRec || walMgr.isAlwaysWriteFullPages()); if (pageRecOrAlwaysWriteFullPage && walIsNotDisable) walMgr.log(new PageSnapshot(pageId, ptr, pageSize(), realPageSize(pageId.groupId()))); }
Source:
<code>public void testStorageSpaceQuotaParam() { StorageSpaceQuotaParam sp = new StorageSpaceQuotaParam( StorageSpaceQuotaParam.DEFAULT); assertEquals(Long.valueOf(StorageSpaceQuotaParam.DEFAULT), sp.getValue()); sp = new StorageSpaceQuotaParam(100L); <START> assertEquals(new Long(100), sp.getValue()); <END> }</code><technical_language>"assertEquals(100L,"</technical_language>

Target:
public void testStorageSpaceQuotaParam() { StorageSpaceQuotaParam sp = new StorageSpaceQuotaParam( StorageSpaceQuotaParam.DEFAULT); assertEquals(Long.valueOf(StorageSpaceQuotaParam.DEFAULT), sp.getValue()); sp = new StorageSpaceQuotaParam(100L); assertEquals(100L, sp.getValue().longValue()); }
Source:
<code>public CqlQueryResponse executeCqlQuery(CqlRequest cqlRequest) throws UnsupportedQueryException, SourceUnavailableException, FederationException { QueryRequest request = cqlRequest.createQueryRequest(catalogFramework.getId(), filterBuilder); Stopwatch stopwatch = Stopwatch.createStarted(); List<QueryResponse> responses = Collections.synchronizedList(new ArrayList<>()); List<Result> results; if (cqlRequest.getCount() == 0) { results = retrieveHitCount(request, responses); } else { results = retrieveResults(cqlRequest, request, responses); } QueryResponse response = new QueryResponseImpl( request, results, true, responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getHits) .findFirst() .orElse(-1L), responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getProperties) .findFirst() .orElse(Collections.emptyMap()), responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getProcessingDetails) <START> .findFirst() <END> .orElse(Collections.EMPTY_SET)); stopwatch.stop(); return new CqlQueryResponse( cqlRequest.getId(), request, response, cqlRequest.getSourceResponseString(), stopwatch.elapsed(TimeUnit.MILLISECONDS), cqlRequest.isNormalize(), filterAdapter, actionRegistry, descriptors); }</code><technical_language>context, making fine finding rest? need collapse/reduce a single set</technical_language>

Target:
public CqlQueryResponse executeCqlQuery(CqlRequest cqlRequest) throws UnsupportedQueryException, SourceUnavailableException, FederationException { QueryRequest request = cqlRequest.createQueryRequest(catalogFramework.getId(), filterBuilder); Stopwatch stopwatch = Stopwatch.createStarted(); List<QueryResponse> responses = Collections.synchronizedList(new ArrayList<>()); List<Result> results; if (cqlRequest.getCount() == 0) { results = retrieveHitCount(request, responses); } else { results = retrieveResults(cqlRequest, request, responses); } QueryResponse response = new QueryResponseImpl( request, results, true, responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getHits) .findFirst() .orElse(-1L), responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getProperties) .findFirst() .orElse(Collections.emptyMap()), responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getProcessingDetails) .reduce( new HashSet<>(), (l, r) -> { l.addAll(r); return l; })); stopwatch.stop(); return new CqlQueryResponse( cqlRequest.getId(), request, response, cqlRequest.getSourceResponseString(), stopwatch.elapsed(TimeUnit.MILLISECONDS), cqlRequest.isNormalize(), filterAdapter, actionRegistry, descriptors); }
Source:
<code>public void handleNotification(StatisticsNotification notification) { long totalCount = 0; long totalTime = 0; for (StatisticId statId : notification) { StatisticDescriptor descriptor = statId.getStatisticDescriptor(); String name = descriptor.getName(); Number value; try { value = notification.getValue(statId); } catch (StatisticNotFoundException e) { value = 0; } log(name, value); if (name.equals(StatsKey.VM_GC_STATS_COLLECTIONS)) { totalCount += value.longValue(); } else if (name.equals(StatsKey.VM_GC_STATS_COLLECTION_TIME)) { totalTime += value.longValue(); } } collections = totalCount; collectionTime = totalTime; <START> } <END></code><technical_language>I a notification includes stats values changed. If correct, summing is _changed_ GC stats, _all_ of GC stats. This work if absolutely stat change sample. ValueMonitor.monitorStatistics(), builds notification updated stats. SampleCollector.sample(), adds a stats updated stats list if of stat changed previous sample</technical_language>

Target:
public void handleNotification(StatisticsNotification notification) { for (StatisticId statId : notification) { StatisticDescriptor descriptor = statId.getStatisticDescriptor(); String name = descriptor.getName(); Number value; try { value = notification.getValue(statId); } catch (StatisticNotFoundException e) { value = 0; } log(name, value); if (name.equals(StatsKey.VM_GC_STATS_COLLECTIONS)) { collections.put(statId.getStatistics().getUniqueId(), value); } else if (name.equals(StatsKey.VM_GC_STATS_COLLECTION_TIME)) { collectionTime.put(statId.getStatistics().getUniqueId(), value); } } }