auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void locksShouldBeReapedAndLeaseShouldBeInvalidatedAfterReapPeriod() { AsyncResult<HeldLocks> result = new AsyncResult<>(); AsyncResult<Leased<LockToken>> asyncResult = heldLocksCollection.getExistingOrAcquire(REQUEST_ID, () -> result); result.complete(heldLocksForId(REQUEST_ID)); Lease lease = asyncResult.get().lease(); <START> setTimeStatic(clock.get().plus(LockLeaseContract.SERVER_LEASE_TIMEOUT).plus(Duration.ofNanos(1))); <END> assertThat(lease.isValid(leaderClock.time())).isFalse(); assertUnlocked(REQUEST_ID); }</code><technical_language>setTime</technical_language>

Target:
public void locksShouldBeReapedAndLeaseShouldBeInvalidatedAfterReapPeriod() { setTime(123); AsyncResult<HeldLocks> result = new AsyncResult<>(); AsyncResult<Leased<LockToken>> asyncResult = heldLocksCollection.getExistingOrAcquire(REQUEST_ID, () -> result); result.complete(heldLocksForId(REQUEST_ID)); Lease lease = asyncResult.get().lease(); advance(LockLeaseContract.SERVER_LEASE_TIMEOUT.plus(Duration.ofNanos(1))); assertThat(lease.isValid(leaderClock.time())).isFalse(); assertUnlocked(REQUEST_ID); }
Source:
<code>Node processUnaryExpression(UnaryExpressionTree exprNode) { int type = transformUnaryTokenType(exprNode.operator.type); Node operand = transform(exprNode.operand); if (type == Token.NEG && operand.isNumber()) { operand.setDouble(-operand.getDouble()); return operand; } else { if (type == Token.DELPROP && !(operand.isGetProp() || operand.isGetElem() || operand.isName())) { String msg = "Invalid delete operand. Only properties can be deleted."; errorReporter.error( msg, sourceName, operand.getLineno(), 0); <START> } else if ((type == Token.INC || type == Token.DEC) <END> && !operand.isValidAssignmentTarget()) { String msg = type == Token.INC ? "Invalid prefix increment operand." : "Invalid prefix decrement operand."; errorReporter.error( msg, sourceName, operand.getLineno(), operand.getCharno()); } return newNode(type, operand); } }</code><technical_language>snippets pretty similar. factor out a separate method avoid duplication</technical_language>

Target:
Node processUnaryExpression(UnaryExpressionTree exprNode) { int type = transformUnaryTokenType(exprNode.operator.type); Node operand = transform(exprNode.operand); if (type == Token.NEG && operand.isNumber()) { operand.setDouble(-operand.getDouble()); return operand; } else { if (type == Token.DELPROP && !(operand.isGetProp() || operand.isGetElem() || operand.isName())) { String msg = "Invalid delete operand. Only properties can be deleted."; errorReporter.error( msg, sourceName, operand.getLineno(), 0); } else if (type == Token.INC || type == Token.DEC) { return createIncrDecrNode(type, false, operand); } return newNode(type, operand); } }
Source:
<code>void send(ControlMessage message, SystemStream systemStream, MessageCollector collector) { SystemStreamMetadata metadata = metadataCache.getSystemStreamMetadata(systemStream, true); int partitionCount = metadata.getSystemStreamPartitionMetadata().size(); LOG.info(String.format("Broadcast %s message from task %s to %s with %s partition", MessageType.of(message).name(), message.getTaskName(), systemStream, partitionCount)); for (int i = 0; i < partitionCount; i++) { <START> OutgoingMessageEnvelope envelopeOut = new OutgoingMessageEnvelope(systemStream, i, "", message); <END> collector.send(envelopeOut); } }</code><technical_language>minor: nice define Void/null key for control messages in ControlMessage.getDefaultKey(), or, defining OutgoingControlMessageEnvelope(systemStream, partitionId, controlMessage) here</technical_language>

Target:
void send(ControlMessage message, SystemStream systemStream, MessageCollector collector) { SystemStreamMetadata metadata = metadataCache.getSystemStreamMetadata(systemStream, true); int partitionCount = metadata.getSystemStreamPartitionMetadata().size(); LOG.info(String.format("Broadcast %s message from task %s to %s with %s partition", MessageType.of(message).name(), message.getTaskName(), systemStream, partitionCount)); for (int i = 0; i < partitionCount; i++) { OutgoingMessageEnvelope envelopeOut = new OutgoingMessageEnvelope(systemStream, i, null, message); collector.send(envelopeOut); } }
Source:
<code>public void setup() throws Exception { <START> getCatalogBundle().setDownloadRetryDelayInSeconds(1); getCatalogBundle().setupCaching(false); <END> urlResourceReaderConfigurator = getUrlResourceReaderConfigurator(); server = new SecureStubServer(Integer.parseInt(RESTITO_STUB_SERVER_PORT.getPort())).run(); server.start(); cswServer.reset(); }</code><technical_language>moved beforeExam()</technical_language>

Target:
public void setup() throws Exception { urlResourceReaderConfigurator = getUrlResourceReaderConfigurator(); server = new SecureStubServer(Integer.parseInt(RESTITO_STUB_SERVER_PORT.getPort())).run(); server.start(); cswServer.reset(); }
Source:
<code>public void run() { for (Queue queue : getLocalQueues()) { if (!queue.isInternalQueue() && QueueManagerImpl.isAutoDelete(queue) && QueueManagerImpl.consumerCountCheck(queue) && QueueManagerImpl.delayCheck(queue) && QueueManagerImpl.messageCountCheck(queue) && queueWasUsed(queue)) { QueueManagerImpl.performAutoDeleteQueue(server, queue); } } Set<SimpleString> addresses = addressManager.getAddresses(); for (SimpleString address : addresses) { AddressInfo addressInfo = getAddressInfo(address); AddressSettings settings = addressSettingsRepository.getMatch(address.toString()); try { if (settings.isAutoDeleteAddresses() && addressInfo != null && addressInfo.isAutoCreated() && !isAddressBound(address) && addressInfo.getBindingRemovedTimestamp() != -1 && (System.currentTimeMillis() - addressInfo.getBindingRemovedTimestamp() >= settings.getAutoDeleteAddressesDelay())) { if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("deleting auto-created address \"" + address + ".\""); } server.removeAddressInfo(address, null); } } catch (ActiveMQAddressDoesNotExistException e) { <START> ActiveMQServerLogger.LOGGER.debug(e.getMessage(), e); <END> } catch (ActiveMQShutdownException e) { ActiveMQServerLogger.LOGGER.debug(e.getMessage(), e); } catch (Exception e) { ActiveMQServerLogger.LOGGER.errorRemovingAutoCreatedQueue(e, address); } } }</code><technical_language>for Debug, please declare a log PostOfficeimpl, log.debug(e.getMessage, e); Also, leak address / Reaper? hiding a bug rug eatin exception debug</technical_language>

Target:
public void run() { for (Queue queue : getLocalQueues()) { if (!queue.isInternalQueue() && QueueManagerImpl.isAutoDelete(queue) && QueueManagerImpl.consumerCountCheck(queue) && QueueManagerImpl.delayCheck(queue) && QueueManagerImpl.messageCountCheck(queue) && queueWasUsed(queue)) { QueueManagerImpl.performAutoDeleteQueue(server, queue); } } Set<SimpleString> addresses = addressManager.getAddresses(); for (SimpleString address : addresses) { AddressInfo addressInfo = getAddressInfo(address); AddressSettings settings = addressSettingsRepository.getMatch(address.toString()); try { if (settings.isAutoDeleteAddresses() && addressInfo != null && addressInfo.isAutoCreated() && !isAddressBound(address) && addressInfo.getBindingRemovedTimestamp() != -1 && (System.currentTimeMillis() - addressInfo.getBindingRemovedTimestamp() >= settings.getAutoDeleteAddressesDelay())) { if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("deleting auto-created address \"" + address + ".\""); } server.removeAddressInfo(address, null); } } catch (ActiveMQShutdownException e) { logger.debug(e.getMessage(), e); } catch (Exception e) { if (e instanceof ActiveMQAddressDoesNotExistException && getAddressInfo(address) == null) { logger.debug(e.getMessage(), e); } else { ActiveMQServerLogger.LOGGER.errorRemovingAutoCreatedQueue(e, address); } } } }
Source:
<code>public int hashCode() { if (hash != null) return hash; int h = 0; <START> h = computeHash(h, family); <END> h = computeHash(h, qualifier); hash = h; return h; }</code><technical_language>This is a good hash function. ... is eclipse generates, simpler stronger: public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(family); result = prime * result + Arrays.hashCode(qualifier); return result; }</technical_language>

Target:
public int hashCode() { if (hash != null) return hash; final int prime = 31; int h = 1; h = prime * h + Arrays.hashCode(family); h = prime * h + Arrays.hashCode(qualifier); hash = h; return h; }
Source:
<code>public static void calculateKAnonymity() throws Exception { String projectId = "your-project-id"; String datasetId = "your-bigquery-dataset-id"; String tableId = "your-bigquery-table-id"; String topicId = "pub-sub-topic"; String subscriptionId = "pub-sub-subscription"; <START> List<String> quasiIdColumns = Arrays.asList("name", "age", "zip_code", "..."); <END> calculateKAnonymity( projectId, datasetId, tableId, topicId, subscriptionId, quasiIdColumns); }</code><technical_language>inline - required for testing</technical_language>

Target:
public static void calculateKAnonymity() throws Exception { String projectId = "your-project-id"; String datasetId = "your-bigquery-dataset-id"; String tableId = "your-bigquery-table-id"; String topicId = "pub-sub-topic"; String subscriptionId = "pub-sub-subscription"; calculateKAnonymity(projectId, datasetId, tableId, topicId, subscriptionId); }
Source:
<code>public void openInTerminalTestByHotKey() { seleniumWebDriver.navigate().refresh(); projectExplorer.waitProjectExplorer(); projectExplorer.waitAndSelectItem(PROJECT_NAME); seleniumWebDriverHelper.sendKeys(Keys.chord(ALT, SHIFT, F12)); terminal.waitNumberTerminalTab(2); String terminalWorkDir = terminal.getVisibleTextFromTerminal(); <START> Assert.assertTrue(terminalWorkDir.trim().endsWith(PROJECT_NAME + "$")); <END> }</code><technical_language>Similar <LINK_0></technical_language>

Target:
public void openInTerminalTestByHotKey() { seleniumWebDriver.navigate().refresh(); projectExplorer.waitProjectExplorer(); projectExplorer.waitAndSelectItem(PROJECT_NAME); seleniumWebDriverHelper.sendKeys(Keys.chord(ALT, SHIFT, F12)); terminal.waitNumberTerminalTab(2); terminal.waitExpectedTextIntoTerminal(PROJECT_NAME + "$"); }
Source:
<code>public void shouldGetSvgFromTextAsStream() { ByteArrayOutputStream outs = new ByteArrayOutputStream(); QRCode.from("www.example.org").svg(outs); byte[] data = outs.toByteArray(); assertThat(data).isNotEmpty(); <START> assertThat(data.length).isGreaterThan(0); <END> assertThat(data).startsWith("<?xml".getBytes()); }</code><technical_language>condition isNotEmpty handle it</technical_language>

Target:
public void shouldGetSvgFromTextAsStream() { ByteArrayOutputStream outs = new ByteArrayOutputStream(); QRCode.from("www.example.org").svg(outs); byte[] data = outs.toByteArray(); assertThat(data).isNotEmpty(); assertThat(data).startsWith("<?xml".getBytes()); assertThat(data).endsWith("</svg\n>\n".getBytes()); }
Source:
<code>public @ResponseBody void setMessageAsViewed(HttpSession session, @RequestParam(value = "messageId") int messageId) { if (session.getAttribute("member") == null) return; MessageDao messageDao = new MessageDao(); Message message = messageDao.getMessageById(messageId); message.setViewed(true); messageDao.save(message); MemberDao memberDao = new MemberDao(); Member member = (Member) session.getAttribute("member"); session.setAttribute("message", null); <START> session.setAttribute("member", memberDao.getMemberById(member.getId())); <END> }</code><technical_language>this set</technical_language>

Target:
public @ResponseBody void setMessageAsViewed( HttpSession session, @RequestParam(value = "messageId") int messageId) { if (session.getAttribute("member") == null) return; MessageDao messageDao = new MessageDao(); Message message = messageDao.getById(messageId); message.setViewed(true); messageDao.merge(message); MemberDao memberDao = new MemberDao(); Member member = (Member) session.getAttribute("member"); session.setAttribute("message", null); session.setAttribute("member", memberDao.getMemberById(member.getId())); }
Source:
<code>public void disconnect(boolean wait) { for (int i = 0; i < clients.length; i++) { clients[i].disconnect(); <START> if (null != clientsV3) { <END> clientsV3[i].disconnect(); } } }</code><technical_language>suggestion if (clients != clientsV3) {</technical_language>

Target:
public void disconnect(boolean wait) { for (int i = 0; i < clients.length; i++) { clients[i].disconnect(); if (clients != clientsV3Enforced) { clientsV3Enforced[i].disconnect(); } } }
Source:
<code>public void testCustomAttributes() { <START> Collection<String> attributes = fixture.listCustomAttributes(); <END> assertEquals(0, attributes.size()); String attrib = fixture.getCustomAttribute("bozo"); assertNull(attrib); }</code><technical_language>Set<String> now, matter..</technical_language>

Target:
public void testCustomAttributes() { Set<String> attributes = fixture.listCustomAttributes(); assertEquals(0, attributes.size()); String attrib = fixture.getCustomAttribute("bozo"); assertNull(attrib); }
Source:
<code><START> public static synchronized Configuration GetConfiguration(Map storm_conf) { <END> Configuration.setConfiguration(null); String orig_loginConfigurationFile = System.getProperty("java.security.auth.login.config"); String loginConfigurationFile = (String)storm_conf.get("java.security.auth.login.config"); if (loginConfigurationFile==null) loginConfigurationFile = orig_loginConfigurationFile; Configuration login_conf = null; if ((loginConfigurationFile != null) && (loginConfigurationFile.length()>0)) { System.setProperty("java.security.auth.login.config", loginConfigurationFile); login_conf = Configuration.getConfiguration(); if (orig_loginConfigurationFile!=null) System.setProperty("java.security.auth.login.config", orig_loginConfigurationFile); } return login_conf; }</code><technical_language>is this method synchronized? also, side effects (setting properties whatnot)? more sense put this initialization code in main method of nimbus (and possibly supervisor and/or worker necessary)</technical_language>

Target:
public static Configuration GetConfiguration(Map storm_conf) { Configuration login_conf = null; String loginConfigurationFile = (String)storm_conf.get("java.security.auth.login.config"); if ((loginConfigurationFile != null) && (loginConfigurationFile.length()>0)) { try { URI config_uri = new File(loginConfigurationFile).toURI(); login_conf = Configuration.getInstance("JavaLoginConfig", new URIParameter(config_uri)); } catch (NoSuchAlgorithmException ex1) { if (ex1.getCause() instanceof FileNotFoundException) throw new RuntimeException("configuration file "+loginConfigurationFile+" could not be found"); else throw new RuntimeException(ex1); } catch (Exception ex2) { throw new RuntimeException(ex2); } } return login_conf; }
Source:
<code>public static Block stGeometries(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { OGCGeometry geometry = deserialize(input); if (geometry.isEmpty()) { return null; } <START> BlockBuilder blockBuilder; <END> GeometryType type = GeometryType.getForEsriGeometryType(geometry.geometryType()); if (!type.isMultitype()) { blockBuilder = GEOMETRY.createBlockBuilder(null, 1); GEOMETRY.writeSlice(blockBuilder, serialize(geometry)); return blockBuilder.build(); } OGCGeometryCollection collection = (OGCGeometryCollection) geometry; blockBuilder = GEOMETRY.createBlockBuilder(null, collection.numGeometries()); for (int i = 0; i < collection.numGeometries(); i++) { GEOMETRY.writeSlice(blockBuilder, serialize(collection.geometryN(i))); } return blockBuilder.build(); }</code><technical_language>declare this variable is ready</technical_language>

Target:
public static Block stGeometries(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { OGCGeometry geometry = deserialize(input); if (geometry.isEmpty()) { return null; } GeometryType type = GeometryType.getForEsriGeometryType(geometry.geometryType()); if (!type.isMultitype()) { BlockBuilder blockBuilder = GEOMETRY.createBlockBuilder(null, 1); GEOMETRY.writeSlice(blockBuilder, serialize(geometry)); return blockBuilder.build(); } OGCGeometryCollection collection = (OGCGeometryCollection) geometry; BlockBuilder blockBuilder = GEOMETRY.createBlockBuilder(null, collection.numGeometries()); for (int i = 0; i < collection.numGeometries(); i++) { GEOMETRY.writeSlice(blockBuilder, serialize(collection.geometryN(i))); } return blockBuilder.build(); }
Source:
<code>private Optional<Edge> getConstructorEdge(Node pNode) { assert pNode != null && isInConstructorCall(pNode); for(Edge edge : aDiagram.edges()) { if ( pNode.getClass() == CallNode.class && edge.getEnd() == pNode && edge.getClass() == ConstructorEdge.class ) <START> { <END> return Optional.of(edge); } } return Optional.empty(); }</code><technical_language>I pNode.getClass() in loop, move return empty is condition is true</technical_language>

Target:
private Optional<Edge> getConstructorEdge(Node pNode) { assert pNode != null && isConstructorExecution(pNode); if( pNode.getClass() == CallNode.class ) { return Optional.empty(); } for(Edge edge : aDiagram.edges()) { if ( edge.getEnd() == pNode && edge.getClass() == ConstructorEdge.class ) { return Optional.of(edge); } } return Optional.empty(); }
Source:
<code>public boolean isProfileAuthorized(final WebContext context, final U profile) throws RequiresHttpAction { if (profile != null && !(profile instanceof AnonymousProfile)) { return true; } else { if (this.redirectionUrl != null) { throw RequiresHttpAction.redirect("user should be authenticated", context, this.redirectionUrl); } else { return false; <START> } <END> } }</code><technical_language>block is repeated. extract this bit out</technical_language>

Target:
public boolean isProfileAuthorized(final WebContext context, final U profile) throws RequiresHttpAction { return profile != null && !(profile instanceof AnonymousProfile); }
Source:
<code>public void tearDown(final ManagementClient managementClient, final String containerId) { try { <START> applyUpdate(managementClient.getControllerClient(), Util.getUndefineAttributeOperation(remotingConnectorAddress, "sasl-authentication-factory"), false); <END> } catch (Exception e) { throw new RuntimeException(e); } applyRemoveAllowReload(managementClient.getControllerClient(), ejbDomainAddress, false); try { ServerReload.reloadIfRequired(managementClient); } catch (Exception e) { throw new RuntimeException(e); } applyRemoveAllowReload(managementClient.getControllerClient(), saslAuthenticationAddress, false); }</code><technical_language>guess is this needs read cache in setup undefine set original here. guess is is right in cases -Delytron is used, failures in elytron job</technical_language>

Target:
public void tearDown(final ManagementClient managementClient, final String containerId) { try { ModelNode restoreSaslOperation; if (saslAuthenticationFactoryValue != null) { restoreSaslOperation = Util.getWriteAttributeOperation(remotingConnectorAddress, "sasl-authentication-factory", saslAuthenticationFactoryValue); } else { restoreSaslOperation = Util.getUndefineAttributeOperation(remotingConnectorAddress, "sasl-authentication-factory"); } applyUpdate(managementClient.getControllerClient(), restoreSaslOperation, false); } catch (Exception e) { throw new RuntimeException(e); } applyRemoveAllowReload(managementClient.getControllerClient(), ejbDomainAddress, false); try { ServerReload.reloadIfRequired(managementClient); } catch (Exception e) { throw new RuntimeException(e); } applyRemoveAllowReload(managementClient.getControllerClient(), saslAuthenticationAddress, false); }
Source:
<code>public void setUp() throws Exception { createProjectWithNfcAndSetVariable(PROJECT_NAME); numDetectedTags.setValue(0); nfcBrickPosition = 0; setVariableIDPosition = 1; setVariableMessagePosition = 2; baseActivityTestRule.launchActivity(null); <START> checkIfSpinnerOnBrickAtPositionShowsString(R.id.set_variable_spinner, setVariableIDPosition, READ_TAG_ID); <END> checkIfSpinnerOnBrickAtPositionShowsString(R.id.set_variable_spinner, setVariableMessagePosition, READ_TAG_MESSAGE); }</code><technical_language>is this necessary in set up? wouldnt sufficient if this done in layout test</technical_language>

Target:
public void setUp() throws Exception { createProjectWithNfcAndSetVariable(); baseActivityTestRule.launchActivity(null); }
Source:
<code>void handleActionResult(final VdcActionType actionType, final VdcActionParametersBase parameters, final VdcReturnValueBase result, final IFrontendActionAsyncCallback callback, final Object state, final boolean showErrorDialog) { logger.log(Level.FINER, "Retrieved action result from RunAction."); FrontendActionAsyncResult f = new FrontendActionAsyncResult(actionType, parameters, result, state); boolean failedOnCanDoAction = !result.getCanDoAction(); if (failedOnCanDoAction) { result.setCanDoActionMessages((ArrayList<String>) translateError(result)); } else if (showErrorDialog && result.getIsSyncronious() && !result.getSucceeded()) { runActionExecutionFailed(actionType, result.getFault()); } callback.executed(f); if (failedOnCanDoAction && (getEventsHandler() != null) && (getEventsHandler().isRaiseErrorModalPanel(actionType, result.getFault()))) { <START> if (result.getCanDoActionMessages().isEmpty()) { <END> failureEventHandler(result.getDescription(), "No Message"); } else { failureEventHandler(result.getDescription(), result.getCanDoActionMessages()); } } }</code><technical_language>need a translation call in case of getCanDoActionMessages() a single message? This code drops right failure event handler. previous code translate first</technical_language>

Target:
void handleActionResult(final VdcActionType actionType, final VdcActionParametersBase parameters, final VdcReturnValueBase result, final IFrontendActionAsyncCallback callback, final Object state, final boolean showErrorDialog) { logger.log(Level.FINER, "Retrieved action result from RunAction."); FrontendActionAsyncResult f = new FrontendActionAsyncResult(actionType, parameters, result, state); boolean failedOnCanDoAction = !result.getCanDoAction(); if (failedOnCanDoAction) { result.setCanDoActionMessages((ArrayList<String>) translateError(result)); } else if (showErrorDialog && result.getIsSyncronious() && !result.getSucceeded()) { runActionExecutionFailed(actionType, result.getFault()); } callback.executed(f); if (failedOnCanDoAction && (getEventsHandler() != null) && (getEventsHandler().isRaiseErrorModalPanel(actionType, result.getFault()))) { ArrayList<String> messages = result.getCanDoActionMessages(); failureEventHandler(result.getDescription(), messages.isEmpty() ? Collections.singletonList(getConstants().noCanDoActionMessage()) : messages); } }
Source:
<code><START> public void testInit() throws Exception { <END> final List<DefinitionSetService> definitionSetServices = new LinkedList<>(); final DefinitionSetService definitionSetService1 = mock(DefinitionSetService.class); final DefinitionSetService definitionSetService2 = mock(DefinitionSetService.class); definitionSetServices.add(definitionSetService1); definitionSetServices.add(definitionSetService2); when(definitionSetServiceInstances.iterator()).thenReturn(definitionSetServices.iterator()); doAnswer(invocation -> { final Consumer consumer = invocation.getArgumentAt(0, Consumer.class); Iterator var2 = definitionSetServiceInstances.iterator(); while (var2.hasNext()) { Object t = var2.next(); consumer.accept(t); } return null; }).when(definitionSetServiceInstances).forEach(any(Consumer.class)); tested.init(); assertEquals(tested.definitionSetServices.size(), definitionSetServices.size()); tested.definitionSetServices.containsAll(definitionSetServices); }</code><technical_language>Exception is thrown</technical_language>

Target:
public void testInit() { final List<DefinitionSetService> definitionSetServices = new LinkedList<>(); final DefinitionSetService definitionSetService1 = mock(DefinitionSetService.class); final DefinitionSetService definitionSetService2 = mock(DefinitionSetService.class); definitionSetServices.add(definitionSetService1); definitionSetServices.add(definitionSetService2); when(definitionSetServiceInstances.iterator()).thenReturn(definitionSetServices.iterator()); doAnswer(invocation -> { final Consumer consumer = invocation.getArgumentAt(0, Consumer.class); Iterator var2 = definitionSetServiceInstances.iterator(); while (var2.hasNext()) { Object t = var2.next(); consumer.accept(t); } return null; }).when(definitionSetServiceInstances).forEach(any(Consumer.class)); tested.init(); assertEquals(tested.definitionSetServices.size(), definitionSetServices.size()); tested.definitionSetServices.containsAll(definitionSetServices); }
Source:
<code>public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof SwitchItem || item instanceof StringItem)) { throw new BindingConfigParseException("item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() <START> + "', only Switch- and StringItems are allowed - please check your *.items configuration"); <END> } }</code><technical_language>Restore original. apply other similar throws</technical_language>

Target:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof SwitchItem || item instanceof StringItem)) { throw new BindingConfigParseException("item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', only Switch-, Dimmer- and StringItems are allowed - please check your *.items configuration"); } }
Source:
<code>public void execute() throws MetaClassNotFoundException, FeatureNotFoundException { final EObject currentTarget = this.getContext().getCurrentTarget(); Object value = RuntimeLoggerManager.INSTANCE.decorate(interpreter).evaluate(currentTarget, this.let, ToolPackage.eINSTANCE.getLet_ValueExpression()); String variableName = Optional.ofNullable(this.let.getVariableName()).orElse(""); if (!variableName.isEmpty()) { <START> if ("self".equals(variableName) && value instanceof EObject) { context.setNextPushEObject((EObject) value); <END> } else { ICommandTask childTask = new InterpretedExpressionVariableTask(context, extPackage, InterpretedExpressionVariableTask.KIND_SET, variableName, value, interpreter); childTask.execute(); } } }</code><technical_language>want allow this</technical_language>

Target:
public void execute() throws MetaClassNotFoundException, FeatureNotFoundException { final EObject currentTarget = this.getContext().getCurrentTarget(); Object value = RuntimeLoggerManager.INSTANCE.decorate(interpreter).evaluate(currentTarget, this.let, ToolPackage.eINSTANCE.getLet_ValueExpression()); String variableName = Optional.ofNullable(this.let.getVariableName()).orElse(""); if (!variableName.isEmpty()) { if ("self".equals(variableName) && value instanceof EObject) { context.setNextPushEObject((EObject) value); for (ICommandTask childTask : this.getChildrenTasks()) { childTask.execute(); } } else { ICommandTask setVariableChildTask = new InterpretedExpressionVariableTask(context, extPackage, InterpretedExpressionVariableTask.KIND_SET, variableName, value, interpreter); this.getChildrenTasks().add(setVariableChildTask); this.let.getSubModelOperations().stream().map(childModelOperation -> { return new ExecuteToolOperationTask(extPackage, currentTarget, context.getRepresentation(), childModelOperation, uiCallback); }).forEach(this.getChildrenTasks()::add); ICommandTask unsetVariableChildTask = new InterpretedExpressionVariableTask(context, extPackage, InterpretedExpressionVariableTask.KIND_UNSET, variableName, value, interpreter); this.getChildrenTasks().add(unsetVariableChildTask); for (ICommandTask childTask : this.getChildrenTasks()) { childTask.execute(); } } } }
Source:
<code>protected AdsFandomObject loadPage(String pageName, String pageType) { String pageUrl; String queryString = Configuration.getQS(); <START> Boolean isF2 = queryString.matches(".*f2(?=\\=|&|$|\\n).*"); <END> PageObjectLogging.log("queryString", queryString, true); PageObjectLogging.log("isF2", isF2.toString(), true); if(isF2) { pageUrl = urlBuilder.getF2Url(pageName, pageType); } else { switch (pageType) { case PAGE_TYPE_HUB: pageUrl = urlBuilder.getUrlForFandomHub(pageName); break; case PAGE_TYPE_ARTICLE: default: pageUrl = urlBuilder.getUrlForFandomPage(pageName); break; } } return new AdsFandomObject(driver, pageUrl); }</code><technical_language>I bet evil request in world</technical_language>

Target:
protected AdsFandomObject loadPage(String pageName, String pageType) { String pageUrl; Boolean isF2 = isF2(); if(isF2) { pageUrl = urlBuilder.getF2Url(pageName, pageType); } else { switch (pageType) { case PAGE_TYPE_HUB: pageUrl = urlBuilder.getUrlForFandomHub(pageName); break; case PAGE_TYPE_ARTICLE: default: pageUrl = urlBuilder.getUrlForFandomPage(pageName); break; } } return new AdsFandomObject(driver, pageUrl); }
Source:
<code>public void testCreate3desSubKey() throws Exception { byte[] input1 = CodePointIterator.ofString("FFFFFFFFFFFFFF").hexDecode().drain(); byte[] output1 = create3desSubKey(input1, 0); <START> assertEquals("FEFEFEFEFEFEFEFE".toLowerCase(Locale.ENGLISH), ByteIterator.ofBytes(output1).hexEncode().drainToString()); <END> byte[] input2 = CodePointIterator.ofString("d7c920cf2564cec39c570490f7ea").hexDecode().drain(); byte[] output2 = create3desSubKey(input2, 0); assertEquals("D6E54919F22A929D".toLowerCase(Locale.ENGLISH), ByteIterator.ofBytes(output2).hexEncode().drainToString()); byte[] input3 = CodePointIterator.ofString("d7c920cf2564cec39c570490f7ea").hexDecode().drain(); byte[] output3 = create3desSubKey(input3, 7); assertEquals("C2CE15E04986DFD5".toLowerCase(Locale.ENGLISH), ByteIterator.ofBytes(output3).hexEncode().drainToString()); }</code><technical_language>I Locale.ROOT is generally preferred for these</technical_language>

Target:
public void testCreate3desSubKey() throws Exception { byte[] input1 = CodePointIterator.ofString("FFFFFFFFFFFFFF").hexDecode().drain(); byte[] output1 = create3desSubKey(input1, 0); assertEquals("FEFEFEFEFEFEFEFE".toLowerCase(Locale.ROOT), ByteIterator.ofBytes(output1).hexEncode().drainToString()); byte[] input2 = CodePointIterator.ofString("d7c920cf2564cec39c570490f7ea").hexDecode().drain(); byte[] output2 = create3desSubKey(input2, 0); assertEquals("D6E54919F22A929D".toLowerCase(Locale.ROOT), ByteIterator.ofBytes(output2).hexEncode().drainToString()); byte[] input3 = CodePointIterator.ofString("d7c920cf2564cec39c570490f7ea").hexDecode().drain(); byte[] output3 = create3desSubKey(input3, 7); assertEquals("C2CE15E04986DFD5".toLowerCase(Locale.ROOT), ByteIterator.ofBytes(output3).hexEncode().drainToString()); }
Source:
<code><START> public Map<Long, Double> uniquenessDistribution(long histogramSize) <END> { Map<Long, Double> out = new TreeMap<>(); LongStream.rangeClosed(1, histogramSize).forEach(l -> out.put(l, 0D)); int size = minhash.size(); for (HyperLogLog hll : minhash.values()) { long bucket = Math.min(hll.cardinality(), histogramSize); out.merge(bucket, (double) 1 / size, Double::sum); } return out; }</code><technical_language>find a do this boxed types</technical_language>

Target:
public Long2DoubleMap uniquenessDistribution(long histogramSize) { Long2DoubleMap out = new Long2DoubleOpenHashMap(); PrimitiveIterator.OfLong iterator = LongStream.rangeClosed(1, histogramSize).iterator(); while (iterator.hasNext()) { out.put(iterator.nextLong(), 0D); } int size = minhash.size(); for (HyperLogLog hll : minhash.values()) { long bucket = Math.min(hll.cardinality(), histogramSize); out.merge(bucket, (double) 1 / size, Double::sum); } return out; }
Source:
<code>protected void runInContext() { try { s_logger.debug("HostOutOfBandManagementStatsCollector is running..."); List<OutOfBandManagementVO> outOfBandManagementHosts = outOfBandManagementDao.findAllByManagementServer(ManagementServerNode.getManagementServerId()); if (outOfBandManagementHosts == null) { return; } for (OutOfBandManagement outOfBandManagementHost : outOfBandManagementHosts) { Host host = _hostDao.findById(outOfBandManagementHost.getHostId()); if (host == null) { continue; } if (outOfBandManagementService.isOutOfBandManagementEnabled(host)) { outOfBandManagementService.submitBackgroundPowerSyncTask(host); } else { if (outOfBandManagementHost.getPowerState() != OutOfBandManagement.PowerState.Disabled) { <START> if (outOfBandManagementService.transitionPowerStateToDisabled(Collections.singletonList(host))) { <END> s_logger.debug("Out-of-band management was disabled in zone/cluster/host, disabled power state for host id:" + host.getId()); } } } } } catch (Throwable t) { s_logger.error("Error trying to retrieve host out-of-band management stats", t); } }</code><technical_language>Collapse if blocks a single else if line 447 improve readability</technical_language>

Target:
protected void runInContext() { try { s_logger.debug("HostOutOfBandManagementStatsCollector is running..."); List<OutOfBandManagementVO> outOfBandManagementHosts = outOfBandManagementDao.findAllByManagementServer(ManagementServerNode.getManagementServerId()); if (outOfBandManagementHosts == null) { return; } for (OutOfBandManagement outOfBandManagementHost : outOfBandManagementHosts) { Host host = _hostDao.findById(outOfBandManagementHost.getHostId()); if (host == null) { continue; } if (outOfBandManagementService.isOutOfBandManagementEnabled(host)) { outOfBandManagementService.submitBackgroundPowerSyncTask(host); } else if (outOfBandManagementHost.getPowerState() != OutOfBandManagement.PowerState.Disabled) { if (outOfBandManagementService.transitionPowerStateToDisabled(Collections.singletonList(host))) { if (s_logger.isDebugEnabled()) { s_logger.debug("Out-of-band management was disabled in zone/cluster/host, disabled power state for host id:" + host.getId()); } } } } } catch (Throwable t) { s_logger.error("Error trying to retrieve host out-of-band management stats", t); } }
Source:
<code>protected void showLocationFilter() { final Collection<String> locations; if (getCollector() instanceof TargetPlatformClassContributionCollector) { locations = TargetPlatformClassContributionCollector.getInstance().getLocations(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { locations = TargetPlatformIconContributionCollector.getInstance().getLocations(); } else { return; } final HashSet<String> parentLocations = new HashSet<String>(); for (String location : locations) { if (location.endsWith(".jar")) { int index = location.lastIndexOf(File.separator); if (index >= 0) { location = location.substring(0, index); parentLocations.add(location); } } else { parentLocations.add(location); } } final ArrayList<String> sorted = new ArrayList<String>(parentLocations); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the location to filter on."); setTitle("Location Filter"); getShell().setText("Location Filter"); <START> setTitleImage(new Image(getShell().getDisplay(), getClass().getResourceAsStream("/icons/full/wizban/location_wiz.png"))); <END> return ret; } }; if (dlg.open() == Dialog.OK) { setFilterLocations((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }</code><technical_language>anonymous "new Image()" is a resource leak. Please some kind of resourcepool</technical_language>

Target:
protected void showLocationFilter() { final Collection<String> locations; if (getCollector() instanceof TargetPlatformClassContributionCollector) { locations = TargetPlatformClassContributionCollector.getInstance().getLocations(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { locations = TargetPlatformIconContributionCollector.getInstance().getLocations(); } else { return; } final HashSet<String> parentLocations = new HashSet<String>(); for (String location : locations) { if (location.endsWith(".jar")) { int index = location.lastIndexOf(File.separator); if (index >= 0) { location = location.substring(0, index); parentLocations.add(location); } } else { parentLocations.add(location); } } final ArrayList<String> sorted = new ArrayList<String>(parentLocations); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the location to filter on."); setTitle("Location Filter"); getShell().setText("Location Filter"); setTitleImage(imageCache.create("/icons/full/wizban/location_wiz.png")); return ret; } }; if (dlg.open() == Dialog.OK) { setFilterLocations((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }
Source:
<code>private void applyChanges(LibraryDilution target, LibraryDilution source) { target.setConcentration(source.getConcentration()); <START> if (!autoGenerateIdBarcodes) target.setIdentificationBarcode(source.getIdentificationBarcode()); <END> }</code><technical_language>if idBarcode generation is enabled, manually overrideable</technical_language>

Target:
private void applyChanges(LibraryDilution target, LibraryDilution source) { target.setConcentration(source.getConcentration()); target.setTargetedSequencing(source.getTargetedSequencing()); target.setIdentificationBarcode(source.getIdentificationBarcode()); }
Source:
<code>public void setUp() throws Exception { VARIANT.setIds(Collections.singleton("1_1000_A_C")); VARIANT.addSourceEntry(new VariantSourceEntry("FILE_ID", "STUDY_ID")); List<VariantEntity> variantEntities = Collections.singletonList(VARIANT); Region region = new Region("1", 500, 2000); given(variantEntityRepository.findByRegionsAndComplexFilters(eq(Collections.singletonList(region)), any(), any(), any())) .willReturn(variantEntities); given(variantEntityRepository.countByRegionsAndComplexFilters(eq(Collections.singletonList(region)), any())) <START> .willReturn(new Long(variantEntities.size())); <END> }</code><technical_language>is preferred Long.valueOf() new Long() for casts. In this case affect memory usage much, is common idiom, I recommend replacing it</technical_language>

Target:
public void setUp() throws Exception { variant = new VariantEntity("1", 1000, 1005, "A", "C"); variant.setIds(Collections.singleton("1_1000_A_C")); variant.addSourceEntry(new VariantSourceEntry("FILE_ID", "STUDY_ID")); List<VariantEntity> variantEntities = Collections.singletonList(variant); Region region = new Region("1", 500, 2000); given(variantEntityRepository.findByRegionsAndComplexFilters(eq(Collections.singletonList(region)), any(), any(), any())) .willReturn(variantEntities); given(variantEntityRepository.countByRegionsAndComplexFilters(eq(Collections.singletonList(region)), any())) .willReturn(Long.valueOf(variantEntities.size())); }
Source:
<code>private boolean isAnalyze(DispoAnnotationData annotation) { String type = annotation.getResolutionType(); <START> boolean toReturn = false; <END> if (type.equals("Modify_Code") || type.equals("Modify_Test") || type.equals("Modify_Reqt")) { toReturn = true; } return toReturn; }</code><technical_language>if strings elsewhere, create static constants share</technical_language>

Target:
private boolean isAnalyze(DispoAnnotationData annotation) { String type = annotation.getResolutionType(); boolean toReturn = false; if (type.equals(ANALYZE_CODE) || type.equals(ANALYZE_TEST) || type.equals(ANALYZE_REQT)) { toReturn = true; } return toReturn; }
Source:
<code>public String calculatePartition(final EventType eventType, final JSONObject event, final List<String> partitions) throws InvalidPartitionKeyFieldsException { final List<String> partitionKeyFields = eventType.getPartitionKeyFields(); if (partitionKeyFields.isEmpty()) { throw new RuntimeException("Applying " + this.getClass().getSimpleName() + " although event type " + "has no partition key fields configured."); } try { final JsonPathAccess traversableJsonEvent = new JsonPathAccess(event); final ArrayList<String> fieldValues = new ArrayList<>(); final int hashValue = partitionKeyFields.stream() .map(pkf -> EventCategory.DATA.equals(eventType.getCategory()) ? DATA_PATH_PREFIX + pkf : pkf) .map(Try.wrap(okf -> { final String fieldValue = traversableJsonEvent.get(okf).toString(); fieldValues.add(fieldValue); return stringHash.hashCode(fieldValue); })) .map(Try::getOrThrow) .mapToInt(hc -> hc) .sum(); int partitionIndex = abs(hashValue) % partitions.size(); partitionIndex = hashPartitioningCrutch.adjustPartitionIndex(partitionIndex, partitions.size()); <START> final List<String> sortedPartitions = partitions.stream().sorted().collect(Collectors.toList()); <END> final String partition = sortedPartitions.get(partitionIndex); LOG.info("[HASH_BUG] hash - values:{} -> hash:{} -> index:{} -> partition:{}; " + "partitions of '{}' [PNUM:{}]: {}", fieldValues, hashValue, partitionIndex, partition, eventType.getName(), partitions.size(), partitions.stream().collect(Collectors.joining(","))); return partition; } catch (NakadiRuntimeException e) { final Exception original = e.getException(); if (original instanceof InvalidPartitionKeyFieldsException) { throw (InvalidPartitionKeyFieldsException) original; } else { throw e; } } }</code><technical_language>Do find a of this sorting a collection call</technical_language>

Target:
public String calculatePartition(final EventType eventType, final JSONObject event, final List<String> partitions) throws InvalidPartitionKeyFieldsException { final List<String> partitionKeyFields = eventType.getPartitionKeyFields(); if (partitionKeyFields.isEmpty()) { throw new RuntimeException("Applying " + this.getClass().getSimpleName() + " although event type " + "has no partition key fields configured."); } try { final JsonPathAccess traversableJsonEvent = new JsonPathAccess(event); final int hashValue = partitionKeyFields.stream() .map(pkf -> EventCategory.DATA.equals(eventType.getCategory()) ? DATA_PATH_PREFIX + pkf : pkf) .map(Try.wrap(okf -> { final String fieldValue = traversableJsonEvent.get(okf).toString(); return stringHash.hashCode(fieldValue); })) .map(Try::getOrThrow) .mapToInt(hc -> hc) .sum(); int partitionIndex = abs(hashValue) % partitions.size(); partitionIndex = hashPartitioningCrutch.adjustPartitionIndex(partitionIndex, partitions.size()); final List<String> sortedPartitions = partitions.stream().sorted().collect(Collectors.toList()); return sortedPartitions.get(partitionIndex); } catch (NakadiRuntimeException e) { final Exception original = e.getException(); if (original instanceof InvalidPartitionKeyFieldsException) { throw (InvalidPartitionKeyFieldsException) original; } else { throw e; } } }
Source:
<code><START> public void shouldInvokePartitionerWhenSet() { <END> final int[] expectedKeys = new int[]{0, 1}; final StreamPartitioner<Integer, String> streamPartitionerMock = EasyMock.mock(StreamPartitioner.class); expect(streamPartitionerMock.partition(anyString(), eq(0), eq("X0"), anyInt())).andReturn(1).times(1); expect(streamPartitionerMock.partition(anyString(), eq(1), eq("X1"), anyInt())).andReturn(1).times(1); replay(streamPartitionerMock); final Repartitioned<Integer, String> repartitioned = Repartitioned .streamPartitioner(streamPartitionerMock) .withName("repartition"); final KStream<Integer, String> repartitionedStream = builder.<Integer, String>stream(inputTopic) .repartition(repartitioned); final MockProcessorSupplier<Integer, String> supplier = new MockProcessorSupplier<>(); repartitionedStream.process(supplier); try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) { final TestInputTopic<Integer, String> testInputTopic = driver.createInputTopic( inputTopic, new IntegerSerializer(), new StringSerializer() ); for (int i = 0; i < 2; i++) { testInputTopic.pipeInput(expectedKeys[i], "X" + expectedKeys[i], i + 10); } final MockProcessor<Integer, String> proc = supplier.theCapturedProcessor(); proc.checkAndClearProcessResult( new KeyValueTimestamp<>(0, "X0", 10), new KeyValueTimestamp<>(1, "X1", 11) ); } verify(streamPartitionerMock); }</code><technical_language>this test verifies</technical_language>

Target:
public void shouldInvokePartitionerWhenSet() { final int[] expectedKeys = new int[]{0, 1}; final StreamPartitioner<Integer, String> streamPartitionerMock = EasyMock.mock(StreamPartitioner.class); expect(streamPartitionerMock.partition(anyString(), eq(0), eq("X0"), anyInt())).andReturn(1).times(1); expect(streamPartitionerMock.partition(anyString(), eq(1), eq("X1"), anyInt())).andReturn(1).times(1); replay(streamPartitionerMock); final String repartitionOperationName = "test"; final Repartitioned<Integer, String> repartitioned = Repartitioned .streamPartitioner(streamPartitionerMock) .withName(repartitionOperationName); builder.<Integer, String>stream(inputTopic) .repartition(repartitioned); try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) { final TestInputTopic<Integer, String> testInputTopic = driver.createInputTopic(inputTopic, new IntegerSerializer(), new StringSerializer()); final String topicName = repartitionOutputTopic(props, repartitionOperationName); final TestOutputTopic<Integer, String> testOutputTopic = driver.createOutputTopic( topicName, new IntegerDeserializer(), new StringDeserializer() ); for (int i = 0; i < 2; i++) { testInputTopic.pipeInput(expectedKeys[i], "X" + expectedKeys[i], i + 10); } assertThat(testOutputTopic.readRecord(), equalTo(new TestRecord<>(0, "X0", Instant.ofEpochMilli(10)))); assertThat(testOutputTopic.readRecord(), equalTo(new TestRecord<>(1, "X1", Instant.ofEpochMilli(11)))); assertTrue(testOutputTopic.readRecordsToList().isEmpty()); } verify(streamPartitionerMock); }
Source:
<code>void addThreadMetrics(List<MetricFamilySamples> sampleFamilies) { List<MetricFamilySamples.Sample> threads = new ArrayList<MetricFamilySamples.Sample>(); threads.add( new MetricFamilySamples.Sample( "jvm_threads", <START> Arrays.asList("type"), <END> Arrays.asList("daemon"), threadBean.getDaemonThreadCount())); threads.add( new MetricFamilySamples.Sample( "jvm_threads", Arrays.asList("type"), Arrays.asList("nondaemon"), threadBean.getThreadCount() - threadBean.getDaemonThreadCount())); sampleFamilies.add( new MetricFamilySamples( "jvm_threads", Type.GAUGE, "Thread count of a JVM", threads)); List<MetricFamilySamples.Sample> peakThreads = new ArrayList<MetricFamilySamples.Sample>(); peakThreads.add( new MetricFamilySamples.Sample( "jvm_threads_peak", Arrays.asList("type"), Arrays.asList("peak"), threadBean.getPeakThreadCount())); sampleFamilies.add( new MetricFamilySamples( "jvm_threads_peak", Type.GAUGE, "Peak thread count of a JVM", peakThreads)); List<MetricFamilySamples.Sample> startedThreads = new ArrayList<MetricFamilySamples.Sample>(); startedThreads.add( new MetricFamilySamples.Sample( "jvm_threads_started", Arrays.asList("type"), Arrays.asList("started"), threadBean.getTotalStartedThreadCount())); sampleFamilies.add( new MetricFamilySamples( "jvm_threads", Type.GAUGE, "Started thread count of a JVM", startedThreads)); }</code><technical_language>Type is a bad label name, generic. suggest this a single gauge called jvm_daemon_threads</technical_language>

Target:
void addThreadMetrics(List<MetricFamilySamples> sampleFamilies) { sampleFamilies.add( new MetricFamilySamples( "jvm_threads_current", Type.GAUGE, "Current thread count of a JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_threads_current", EMPTY_LABEL, EMPTY_LABEL, threadBean.getThreadCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_threads_daemon", Type.GAUGE, "Daemon thread count of a JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_threads_daemon", EMPTY_LABEL, EMPTY_LABEL, threadBean.getDaemonThreadCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_peak_threads", Type.GAUGE, "Peak thread count of a JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_threads_peak", EMPTY_LABEL, EMPTY_LABEL, threadBean.getPeakThreadCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_threads_started_total", Type.COUNTER, "Started thread count of a JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_threads_started_total", EMPTY_LABEL, EMPTY_LABEL, threadBean.getTotalStartedThreadCount())))); }