auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void announceSegment(DataSegment segment) throws IOException { Map.Entry<String, Integer> zNode = (zNodes.entrySet().isEmpty()) ? null : zNodes.entrySet().iterator().next(); final String path = (zNode == null) ? makeServedSegmentPath(new DateTime().toString()) : zNode.getKey(); Set<DataSegment> zkSegments = segmentReader.read(path); zkSegments.add(segment); if (zkSegments.size() >= config.getSegmentsPerNode()) { zNodes.remove(path); } else { zNodes.put(path, zkSegments.size()); } segmentLookup.put(segment.getIdentifier(), path); log.info("Announcing segment[%s] to path[%s]", segment.getIdentifier(), path); byte[] bytes = jsonMapper.writeValueAsBytes(zkSegments); if (bytes.length > config.getMaxNumBytes()) { throw new ISE("byte size %,d exceeds %,d", bytes.length, config.getMaxNumBytes()); } announcer.update(path, bytes); }

Target:
public void announceSegment(DataSegment segment) throws IOException { int newBytesLen = jsonMapper.writeValueAsBytes(segment).length; if (newBytesLen > config.getMaxNumBytes()) { throw new ISE("byte size %,d exceeds %,d", newBytesLen, config.getMaxNumBytes()); } if (availableZNodes.isEmpty()) { SegmentZNode availableZNode = new SegmentZNode(makeServedSegmentPath(new DateTime().toString())); availableZNode.addSegment(segment); log.info("Announcing segment[%s] at path[%s]", segment.getIdentifier(), availableZNode.getPath()); announcer.announce(availableZNode.getPath(), availableZNode.getBytes()); segmentLookup.put(segment, availableZNode); availableZNodes.add(availableZNode); } else { Iterator<SegmentZNode> iter = availableZNodes.iterator(); boolean done = false; while (iter.hasNext() && !done) { SegmentZNode availableZNode = iter.next(); if (availableZNode.getBytes().length + newBytesLen < config.getMaxNumBytes()) { availableZNode.addSegment(segment); log.info("Announcing segment[%s] at path[%s]", segment.getIdentifier(), availableZNode.getPath()); announcer.update(availableZNode.getPath(), availableZNode.getBytes()); segmentLookup.put(segment, availableZNode); if (availableZNode.getCount() >= config.getSegmentsPerNode()) { availableZNodes.remove(availableZNode); } done = true; } } } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { final IPageManager pageManager = getPageManager(event); if (pageManager == null) { return null; } List<EObject> selectedProperties = getCurrentSelectionAdaptedToType(event, EObject.class); if (selectedProperties == null) { return null; } final List<EObject> pagesToOpen = new LinkedList<>(); List<EObject> pagesToSelect = new LinkedList<>(); for (EObject selected : selectedProperties) { if (!canOpenByPolicy(selected)) { continue; } if (!pageManager.isOpen(selected) || isDuplicateDiagramAllowed) { pagesToOpen.add(selected); } else { pagesToSelect.add(selected); } } if (!pagesToOpen.isEmpty()) { for (EObject page : pagesToOpen) { pageManager.openPage(page); } } for (EObject page : pagesToSelect) { pageManager.selectPage(page); } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { final IPageManager pageManager = getPageManager(event); if (pageManager == null) { return null; } List<EObject> selectedProperties = getCurrentSelectionAdaptedToType(event, EObject.class); if (selectedProperties == null) { return null; } final List<EObject> pagesToOpen = new LinkedList<EObject>(); List<EObject> pagesToSelect = new LinkedList<EObject>(); for (EObject selected : selectedProperties) { if (!canOpenByPolicy(selected)) { continue; } if (!pageManager.isOpen(selected) || isDuplicateDiagramAllowed) { pagesToOpen.add(selected); } else { pagesToSelect.add(selected); } } if (!pagesToOpen.isEmpty()) { for (EObject page : pagesToOpen) { pageManager.openPage(page); } } for (EObject page : pagesToSelect) { pageManager.selectPage(page); } return null; }
Source:
public void testReservedSkippableBeforeStreamIdentifier() throws Exception { ByteBuf in = Unpooled.wrappedBuffer(new byte[] { -0x7f, 0x06, 0x00, 0x00, 's', 'n', 'e', 't', 't', 'y' }); assertFalse(channel.writeInbound(in)); }

Target:
public void testReservedSkippableBeforeStreamIdentifier() throws Exception { ByteBuf in = Unpooled.wrappedBuffer(new byte[] { -0x7f, 0x06, 0x00, 0x00, 's', 'n', 'e', 't', 't', 'y' }); channel.writeInbound(in); }
Source:
public void testStorageAndRetrieval() { final String dataToStore = "This a string intended for testing!"; ImmutableStorageProvider swarm = ImmutableStorageProviderFactory .getStorageProvider(ImmutableStorageProviderFactory.AvailableImmutableStorages.TEST, null); assertNotNull(swarm); try { swarm .store(dataToStore.getBytes(Charset.defaultCharset())) .thenCompose((hash)-> { LOGGER.debug("retrieved hash is: {}", hash); return swarm.retrieve(hash); }) .thenAccept((bytes)-> { try { String receivedMsg = IOUtils.toString(bytes, Charset.defaultCharset().name()); LOGGER.debug("retrieved msg is: {}", receivedMsg); assertEquals(dataToStore, receivedMsg); } catch (IOException e) { e.printStackTrace(); } }) .get(); } catch ( InterruptedException | ExecutionException ignored) { } }

Target:
public void testStorageAndRetrieval() throws ExecutionException, InterruptedException { final String dataToStore = "This a string intended for testing!"; ImmutableStorageProvider swarm = ImmutableStorageProviderFactory .getStorageProvider(ImmutableStorageProviderFactory.AvailableImmutableStorages.TEST, null); assertNotNull(swarm); swarm .store(new ByteArrayInputStream(dataToStore.getBytes(StandardCharsets.UTF_8))) .thenCompose((hash) -> { LOGGER.debug("retrieved hash is: {}", hash); return swarm.retrieve(hash); }) .thenAccept((bytes) -> { try { String receivedMsg = IOUtils.toString(bytes, StandardCharsets.UTF_8); LOGGER.debug("retrieved msg is: {}", receivedMsg); assertEquals(dataToStore, receivedMsg); } catch (IOException e) { throw new CompletionException(e); } }) .get(); }
Source:
public void onWorldAttachCapabilities(AttachCapabilitiesEvent<World> evt) { if (evt.getObject().isRemote) { return; } ICubicWorldServer world = (ICubicWorldServer) evt.getObject(); WorldSavedCubicChunksData savedData = (WorldSavedCubicChunksData) evt.getObject().getMapStorage().getOrLoadData(WorldSavedCubicChunksData.class, "cubicChunksData"); boolean forcedCubicChunks = ((ICubicWorldSettings)world.getWorldInfo()).isCubic(); if (!(evt.getObject().getWorldType() instanceof ICubicWorldType) && savedData == null && !forcedCubicChunks) { return; } if (shouldSkipWorld((World) world)) { CubicChunks.LOGGER.info("Skipping world " + evt.getObject() + " with type " + evt.getObject().getWorldType() + " due to potential " + "compatibility issues"); return; } CubicChunks.LOGGER.info("Initializing world " + evt.getObject() + " with type " + evt.getObject().getWorldType()); IntRange generationRange = new IntRange(0, ((ICubicWorldProvider) world.getProvider()).getOriginalActualHeight()); WorldType type = evt.getObject().getWorldType(); if (type instanceof ICubicWorldType) { generationRange = ((ICubicWorldType) type).calculateGenerationHeightRange((WorldServer) world); } if (savedData == null) { savedData = new WorldSavedCubicChunksData("heightBounds"); } int minHeight = savedData.minHeight; int maxHeight = savedData.maxHeight; world.initCubicWorldServer(new IntRange(minHeight, maxHeight), generationRange); savedData.markDirty(); evt.getObject().getMapStorage().setData("heightBounds", savedData); evt.getObject().getMapStorage().saveAllData(); }

Target:
public void onWorldAttachCapabilities(AttachCapabilitiesEvent<World> evt) { if (evt.getObject().isRemote) { return; } ICubicWorldServer world = (ICubicWorldServer) evt.getObject(); WorldSavedCubicChunksData savedData = (WorldSavedCubicChunksData) evt.getObject().getMapStorage().getOrLoadData(WorldSavedCubicChunksData.class, "cubicChunksData"); boolean forcedCubicChunks = ((ICubicWorldSettings)world.getWorldInfo()).isCubic(); if (!(evt.getObject().getWorldType() instanceof ICubicWorldType) && savedData == null && !forcedCubicChunks) { return; } if (shouldSkipWorld((World) world)) { CubicChunks.LOGGER.info("Skipping world " + evt.getObject() + " with type " + evt.getObject().getWorldType() + " due to potential " + "compatibility issues"); return; } CubicChunks.LOGGER.info("Initializing world " + evt.getObject() + " with type " + evt.getObject().getWorldType()); IntRange generationRange = new IntRange(0, ((ICubicWorldProvider) world.getProvider()).getOriginalActualHeight()); WorldType type = evt.getObject().getWorldType(); if (type instanceof ICubicWorldType) { generationRange = ((ICubicWorldType) type).calculateGenerationHeightRange((WorldServer) world); } if (savedData == null) { savedData = new WorldSavedCubicChunksData("cubicChunksData"); } int minHeight = savedData.minHeight; int maxHeight = savedData.maxHeight; world.initCubicWorldServer(new IntRange(minHeight, maxHeight), generationRange); savedData.markDirty(); evt.getObject().getMapStorage().setData("cubicChunksData", savedData); evt.getObject().getMapStorage().saveAllData(); }
Source:
public void testAddMavenDescriptorSetToTrue() throws Exception { File basedir = getBasedir("projects/addMavenDescriptorSetToTrue"); File platform = new File("src/test/resources/eclipse"); List<MavenProject> projects = getSortedProjects(basedir, platform); MavenProject project = getProject(projects, "addMavenDescriptorSetToTrue"); PackageFeatureMojo mojo = (PackageFeatureMojo) lookupMojo("package-feature", project.getFile()); setVariableValueToObject(mojo, "project", project); setVariableValueToObject(mojo, "session", newMavenSession(project, projects)); setVariableValueToObject(mojo, "finalName", "feature"); mojo.execute(); ZipFile zip = new ZipFile(new File(basedir, "target/feature.jar")); ZipEntry entry = zip.getEntry("META-INF/maven"); assertNotNull("There must be a 'META-INF/maven/' entry in the feature.jar!", entry); zip.close(); }

Target:
public void testAddMavenDescriptorSetToTrue() throws Exception { File basedir = getBasedir("projects/addMavenDescriptor/featureForcedToTrue"); File platform = new File("src/test/resources/eclipse"); List<MavenProject> projects = getSortedProjects(basedir, platform); MavenProject project = getProject(projects, "featureForcedToTrue"); PackageFeatureMojo mojo = (PackageFeatureMojo) lookupMojo("package-feature", project.getFile()); setVariableValueToObject(mojo, "project", project); setVariableValueToObject(mojo, "session", newMavenSession(project, projects)); mojo.execute(); ZipFile zip = new ZipFile(new File(basedir, "target/featureForcedToTrue.jar")); try { ZipEntry entry = zip.getEntry("META-INF/maven"); assertNotNull("There must be a 'META-INF/maven/' entry in the feature.jar!", entry); } finally { zip.close(); } }
Source:
private Set<AccountGroup.Id> queryForGroups(final DirContext ctx, final String username, LdapQuery.Result account) throws NamingException, AccountException { if (account == null) { account = findAccount(ctx, username); } final Set<AccountGroup.Id> actual = new HashSet<AccountGroup.Id>(); NamingEnumeration groups = account.getAll(accountMemberField).getAll(); while (groups.hasMore()) { final String dn = String.valueOf(groups.next()); if (!groupNames.containsKey(dn)) { groupNames.put(dn, groupsFor(ctx, dn)); } for (String cn : groupNames.get(dn)) { AccountGroup group = groupCache.lookup(cn); if (null != group && isLdapGroup(group)) { actual.add(group.getId()); } } } if (actual.isEmpty()) { return Collections.emptySet(); } else { return Collections.unmodifiableSet(actual); } }

Target:
private Set<AccountGroup.Id> queryForGroups(final DirContext ctx, final String username, LdapQuery.Result account) throws NamingException, AccountException { if (account == null) { account = findAccount(ctx, username); } final HashMap<String, String> params = new HashMap<String, String>(); params.put(USERNAME, username); if (groupNeedsAccount) { for (final String name : groupMemberQueryList.get(0).getParameters()) { params.put(name, account.get(name)); } } final Set<AccountGroup.Id> actual = new HashSet<AccountGroup.Id>(); for (LdapQuery groupMemberQuery : groupMemberQueryList) { for (LdapQuery.Result r : groupMemberQuery.query(ctx, params)) { final String name = r.get(groupName); final AccountGroup group = groupCache.lookup(name); if (group != null && isLdapGroup(group)) { actual.add(group.getId()); } } } NamingEnumeration groups = account.getAll(accountMemberField).getAll(); while (groups.hasMore()) { final String dn = (String) groups.next(); for (String cn : groupsFor(ctx, dn)) { AccountGroup group = groupCache.lookup(cn); if (null != group && isLdapGroup(group)) { actual.add(group.getId()); } } } if (actual.isEmpty()) { return Collections.emptySet(); } else { return Collections.unmodifiableSet(actual); } }
Source:
protected void executeVmCommand() { addCustomValue("InterfaceType", (VmInterfaceType.forValue(getInterface().getType()).getDescription()).toString()); boolean succeeded = false; boolean macAddedToPool = false; final MacPoolManagerStrategy macPool = getMacPoolForVm(); try { if (isVnicProfileChanged(oldIface, getInterface())) { Network newNetwork = NetworkHelper.getNetworkByVnicProfileId(getInterface().getVnicProfileId()); Network oldNetwork = NetworkHelper.getNetworkByVnicProfileId(oldIface.getVnicProfileId()); if (ObjectUtils.notEqual(oldNetwork, newNetwork)) { new ExternalNetworkManager(oldIface).deallocateIfExternal(); } } if (macShouldBeChanged) { macAddedToPool = addMacToPool(getMacAddress(), macPool); } if (mustChangeAddress(oldIface.getType(), getInterface().getType())) { getVmDeviceDao().clearDeviceAddress(getInterface().getId()); } getInterface().setSpeed(VmInterfaceType.forValue(getInterface().getType()).getSpeed()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(oldIface); getVmNicDao().update(getInterface()); getCompensationContext().stateChanged(); return null; } }); succeeded = updateHost(); } finally { setSucceeded(succeeded); if (macAddedToPool) { if (succeeded) { macPool.freeMac(oldIface.getMacAddress()); } else { macPool.freeMac(getMacAddress()); } } } }

Target:
protected void executeVmCommand() { addCustomValue("InterfaceType", (VmInterfaceType.forValue(getInterface().getType()).getDescription()).toString()); boolean succeeded = false; boolean macAddedToPool = false; try { if (isVnicProfileChanged(oldIface, getInterface())) { Network newNetwork = NetworkHelper.getNetworkByVnicProfileId(getInterface().getVnicProfileId()); Network oldNetwork = NetworkHelper.getNetworkByVnicProfileId(oldIface.getVnicProfileId()); if (ObjectUtils.notEqual(oldNetwork, newNetwork)) { new ExternalNetworkManager(oldIface).deallocateIfExternal(); } } if (macShouldBeChanged) { macAddedToPool = addMacToPool(getMacAddress()); } if (mustChangeAddress(oldIface.getType(), getInterface().getType())) { getVmDeviceDao().clearDeviceAddress(getInterface().getId()); } getInterface().setSpeed(VmInterfaceType.forValue(getInterface().getType()).getSpeed()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(oldIface); getVmNicDao().update(getInterface()); getCompensationContext().stateChanged(); return null; } }); succeeded = updateHost(); } finally { setSucceeded(succeeded); if (macAddedToPool) { if (succeeded) { getMacPool().freeMac(oldIface.getMacAddress()); } else { getMacPool().freeMac(getMacAddress()); } } } }
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, ctx -> { PyFunctionDefTree pyFunctionDefTree = ((PyFunctionDefTree) ctx.syntaxNode()); if (!shouldCheckFunctionDeclaration(pyFunctionDefTree)) { return; } PyNameTree functionNameTree = pyFunctionDefTree.name(); String name = functionNameTree.name(); if (!pattern().matcher(name).matches()) { String message = String.format(MESSAGE, typeName(), name, this.format); ctx.addIssue(functionNameTree, message); } }); }

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, ctx -> { PyFunctionDefTree pyFunctionDefTree = (PyFunctionDefTree) ctx.syntaxNode(); if (!shouldCheckFunctionDeclaration(pyFunctionDefTree)) { return; } PyNameTree functionNameTree = pyFunctionDefTree.name(); String name = functionNameTree.name(); if (!pattern().matcher(name).matches()) { String message = String.format(MESSAGE, typeName(), name, this.format); ctx.addIssue(functionNameTree, message); } }); }
Source:
final TychoRepositoryIndex createArtifactsIndex(File location) { return FileBasedTychoRepositoryIndex.createArtifactsIndex(location, new NoopFileLockService(), new NoopMavenLogger()); }

Target:
final TychoRepositoryIndex createArtifactsIndex(File location) { return FileBasedTychoRepositoryIndex.createArtifactsIndex(location, new NoopFileLockService(), mock(MavenLogger.class)); }
Source:
public boolean execute(final String activeContextId, final EventHandler<AvroElasticMemoryMessage> callback) { final ActiveContext activeContext = activeContexts.remove(activeContextId); final boolean isSuccess; if (activeContext == null) { LOG.log(Level.WARNING, "Trying to remove active context {0}, which is not found", activeContextId); isSuccess = false; } else { deletedWorkerSet.add(activeContextId); final RunningTask runningTask = contextIdToRunningTasks.get(activeContextId); runningTask.close(); activeContext.close(); final int remainingNumWorkers = runningWorkerContextCount.decrementAndGet(); LOG.log(Level.FINE, "Worker has been deleted successfully. Remaining workers: {0}", remainingNumWorkers); isSuccess = true; } sendCallback(activeContextId, callback, isSuccess); return isSuccess; }

Target:
public boolean execute(final String activeContextId, final EventHandler<AvroElasticMemoryMessage> callback) { final ActiveContext activeContext = activeContexts.remove(activeContextId); final boolean isSuccess; if (activeContext == null) { LOG.log(Level.WARNING, "Trying to remove active context {0}, which is not found", activeContextId); isSuccess = false; } else { deletedWorkerSet.add(activeContextId); final RunningTask runningTask = contextIdToRunningTasks.remove(activeContextId); runningTask.close(); activeContext.close(); final int remainingNumWorkers = runningWorkerContextCount.decrementAndGet(); LOG.log(Level.FINE, "Worker has been deleted successfully. Remaining workers: {0}", remainingNumWorkers); isSuccess = true; } sendCallback(activeContextId, callback, isSuccess); return isSuccess; }
Source:
public void test() throws IOException, InterruptedException, ExecutionException { XContentBuilder settings = jsonBuilder().startObject(); settings.startObject("analysis"); settings.startObject("analyzer"); settings.startObject("preserve"); settings.field("tokenizer", "whitespace"); settings.field("filter", "preserve_original_recorder", "lowercase", "preserve_original"); XContentBuilder mapping = jsonBuilder().startObject(); mapping.startObject("test").startObject("properties"); mapping.startObject("test"); mapping.field("type", "string"); mapping.field("analyzer", "preserve"); mapping.endObject(); assertAcked(prepareCreate("test").addMapping("test", mapping).setSettings(settings)); ensureGreen(); indexRandom(false, doc("all_lower", "hello world")); indexRandom(false, doc("mixed", "Hello World with more text")); refresh(); SearchResponse sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchQuery("test", "hello")).get(); assertHitCount(sr, 2); assertSearchHits(sr, "all_lower", "mixed"); sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchQuery("test", "Hello")).get(); assertHitCount(sr, 2); assertSearchHits(sr, "mixed", "all_lower"); }

Target:
public void test() throws IOException, InterruptedException, ExecutionException { XContentBuilder settings = jsonBuilder().startObject(); settings.startObject("analysis"); settings.startObject("analyzer"); settings.startObject("preserve"); settings.field("tokenizer", "whitespace"); settings.field("filter", "preserve_original_recorder", "lowercase", "preserve_original"); XContentBuilder mapping = jsonBuilder().startObject(); mapping.startObject("test").startObject("properties"); mapping.startObject("test"); mapping.field("type", "string"); mapping.field("analyzer", "preserve"); mapping.field("similarity", "bm25"); mapping.endObject(); assertAcked(prepareCreate("test").addMapping("test", mapping).setSettings(settings)); ensureGreen(); indexRandom(false, doc("all_lower", "hello world")); indexRandom(false, doc("mixed", "Hello World with more text")); refresh(); SearchResponse sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchQuery("test", "hello")).get(); assertOrderedSearchHits(sr, "all_lower", "mixed"); sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchPhraseQuery("test", "hello world")).get(); assertOrderedSearchHits(sr, "all_lower", "mixed"); sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchQuery("test", "Hello")).get(); assertOrderedSearchHits(sr, "mixed", "all_lower"); sr = client().prepareSearch("test").setTypes("test").setQuery(QueryBuilders.matchPhraseQuery("test", "Hello World").analyzer("whitespace")).get(); assertOrderedSearchHits(sr, "mixed"); }
Source:
public Response create(@ApiParam(value = "New user") UserDescriptor userDescriptor, @ApiParam(value = "Authentication token") @QueryParam("token") String token, @ApiParam(value = "User type") @QueryParam("temporary") @DefaultValue("false") Boolean isTemporary, @Context SecurityContext context) throws ForbiddenException, BadRequestException, UnauthorizedException, ConflictException, ServerException, NotFoundException { if (!context.isUserInRole("system/admin") && !userSelfCreationAllowed) { throw new ForbiddenException("Currently only admins can create accounts. Please contact our Admin Team for further info."); } final User user = context.isUserInRole("system/admin") ? fromEntity(userDescriptor) : fromToken(token); if (isValidUserName(user.getName())) { throw new BadRequestException("Username must contain only letters and digits"); } userManager.create(user, isTemporary); return status(CREATED).entity(injectLinks(toDescriptor(user), getServiceContext())).build(); }

Target:
public Response create(@ApiParam(value = "New user") UserDescriptor userDescriptor, @ApiParam(value = "Authentication token") @QueryParam("token") String token, @ApiParam(value = "User type") @QueryParam("temporary") @DefaultValue("false") Boolean isTemporary, @Context SecurityContext context) throws ForbiddenException, BadRequestException, UnauthorizedException, ConflictException, ServerException, NotFoundException { if (!context.isUserInRole("system/admin") && !userSelfCreationAllowed) { throw new ForbiddenException("Currently only admins can create accounts. Please contact our Admin Team for further info."); } final User user = context.isUserInRole("system/admin") ? fromEntity(userDescriptor) : fromToken(token); if (!isValidUserName(user.getName())) { throw new BadRequestException("Username must contain only letters and digits"); } userManager.create(user, isTemporary); return status(CREATED).entity(injectLinks(toDescriptor(user), getServiceContext())).build(); }
Source:
public static ObjectId computeChangeId(final ObjectId treeId, final ObjectId firstParentId, final PersonIdent author, final PersonIdent committer, final String message) throws IOException { StringBuilder b = new StringBuilder(); b.append("tree "); b.append(ObjectId.toString(treeId)); b.append("\n"); if (firstParentId != null) { b.append("parent "); b.append(ObjectId.toString(firstParentId)); b.append("\n"); } b.append("author "); b.append(author.toExternalString()); b.append("\n"); b.append("committer "); b.append(committer.toExternalString()); b.append("\n\n"); b.append(clean(message)); ObjectWriter w = new ObjectWriter(null); byte[] bytes = b.toString().getBytes(Constants.CHARACTER_ENCODING); ByteArrayInputStream is = new ByteArrayInputStream(bytes); ObjectId sha1 = w.computeObjectSha1(Constants.OBJ_COMMIT, bytes.length, is); return sha1; }

Target:
public static ObjectId computeChangeId(final ObjectId treeId, final ObjectId firstParentId, final PersonIdent author, final PersonIdent committer, final String message) throws IOException { String cleanMessage = clean(message); if (cleanMessage.length() == 0) return null; StringBuilder b = new StringBuilder(); b.append("tree "); b.append(ObjectId.toString(treeId)); b.append("\n"); if (firstParentId != null) { b.append("parent "); b.append(ObjectId.toString(firstParentId)); b.append("\n"); } b.append("author "); b.append(author.toExternalString()); b.append("\n"); b.append("committer "); b.append(committer.toExternalString()); b.append("\n\n"); b.append(cleanMessage); ObjectWriter w = new ObjectWriter(null); byte[] bytes = b.toString().getBytes(Constants.CHARACTER_ENCODING); ByteArrayInputStream is = new ByteArrayInputStream(bytes); ObjectId sha1 = w.computeObjectSha1(Constants.OBJ_COMMIT, bytes.length, is); return sha1; }
Source:
public void saveCurrentWorkflow() { ConfigItem<WorkflowRepresentation> workflowRepresentation = new ConfigItem<WorkflowRepresentation>(); workflowRepresentation.setContent(getCurrentWorkflow()); try { getPersistence().persist(workflowRepresentation); } catch (InvalidConfigurationException e) { throw new RuntimeException(e); } catch (PersistenceException e) { throw new RuntimeException(e); } }

Target:
public void saveCurrentWorkflow() throws PersistenceException { ConfigItem<WorkflowRepresentation> workflowRepresentation = new ConfigItem<WorkflowRepresentation>(); workflowRepresentation.setContent(getCurrentWorkflow()); try { LOGGER.debug("Saving workflow " + getCurrentWorkflow().getName()); getPersistence().persist(workflowRepresentation); } catch (InvalidConfigurationException e) { LOGGER.error("Invalid Configuration: " + e.getMessage()); throw new PersistenceException(e); } }
Source:
private long createTags(OseeConnection connection, Collection<IndexedResource> sources) throws OseeCoreException { SearchTagCollector tagCollector = new SearchTagCollector(); Set<Long> processed = new HashSet<Long>(); Map<Long, Collection<Long>> toStore = new HashMap<Long, Collection<Long>>(); for (IndexedResource source : sources) { long startItemTime = System.currentTimeMillis(); Long gamma = source.getGammaId(); if (processed.add(gamma)) { Set<Long> tags = new HashSet<Long>(); toStore.put(gamma, tags); tagCollector.setCurrentTag(gamma, tags); try { long typeUuid = source.getTypeUuid(); String taggerId = getTaggerIdByTypeUuid(typeUuid); if (taggingEngine.hasTagger(taggerId)) { Tagger tagger = taggingEngine.getTagger(taggerId); tagger.tagIt(source, tagCollector); if (isStorageAllowed(toStore)) { if (getLogger().isDebugEnabled()) { getLogger().debug("Stored a - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); } storeTags(connection, toStore); } } } catch (Exception ex) { } finally { long endItemTime = System.currentTimeMillis() - startItemTime; notifyOnIndexItemComplete(gamma, tags.size(), endItemTime); } } } if (!toStore.isEmpty()) { if (getLogger().isDebugEnabled()) { getLogger().debug("Stored b - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); } storeTags(connection, toStore); } return tagCollector.getTotalTags(); }

Target:
private long createTags(OseeConnection connection, Collection<IndexedResource> sources) throws OseeCoreException { SearchTagCollector tagCollector = new SearchTagCollector(); Set<Long> processed = new HashSet<Long>(); Map<Long, Collection<Long>> toStore = new HashMap<Long, Collection<Long>>(); for (IndexedResource source : sources) { long startItemTime = System.currentTimeMillis(); Long gamma = source.getGammaId(); if (processed.add(gamma)) { Set<Long> tags = new HashSet<Long>(); toStore.put(gamma, tags); tagCollector.setCurrentTag(gamma, tags); try { long typeUuid = source.getTypeUuid(); String taggerId = getTaggerIdByTypeUuid(typeUuid); if (taggingEngine.hasTagger(taggerId)) { Tagger tagger = taggingEngine.getTagger(taggerId); tagger.tagIt(source, tagCollector); if (isStorageAllowed(toStore)) { getLogger().debug("Stored a - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); storeTags(connection, toStore); } } else { getLogger().error("Field has no tagger provider and cannot be tagged - [Gamma: %s]", gamma); } } catch (Exception ex) { getLogger().error(ex, "Unable to tag - [%s]", gamma); } finally { long endItemTime = System.currentTimeMillis() - startItemTime; notifyOnIndexItemComplete(gamma, tags.size(), endItemTime); } } } if (!toStore.isEmpty()) { getLogger().debug("Stored b - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); storeTags(connection, toStore); } return tagCollector.getTotalTags(); }
Source:
protected long getParam(JSONObject params, String name, long defaultValue) { try { return params.getInt(name); } catch (Exception e) { return defaultValue; } }

Target:
protected long getParam(JSONObject params, String name, long defaultValue) { try { return params.getLong(name); } catch (Exception e) { return defaultValue; } }
Source:
public void advance(long amountToAdd, TemporalUnit unit) { now = now.plus(amountToAdd, unit); }

Target:
public Instant advance(long amountToAdd, TemporalUnit unit) { now = now.plus(amountToAdd, unit); return instant(); }
Source:
private void processDistributedObjectInfos(ClientMessage response) { ClientGetDistributedObjectsCodec.ResponseParameters resultParameters = ClientGetDistributedObjectsCodec.decodeResponse(response); Collection<? extends DistributedObject> distributedObjects = getLocalDistributedObjects(); Set<DistributedObjectInfo> localDistributedObjects = new HashSet<DistributedObjectInfo>(); for (DistributedObject localInfo : distributedObjects) { localDistributedObjects.add(new DistributedObjectInfo(localInfo.getServiceName(), localInfo.getName())); } Collection<DistributedObjectInfo> newDistributedObjectInfo = resultParameters.response; for (DistributedObjectInfo distributedObjectInfo : newDistributedObjectInfo) { localDistributedObjects.remove(distributedObjectInfo); getOrCreateProxy(distributedObjectInfo.getServiceName(), distributedObjectInfo.getName(), true); } for (DistributedObjectInfo distributedObjectInfo : localDistributedObjects) { destroyProxyLocally(distributedObjectInfo.getServiceName(), distributedObjectInfo.getName()); } }

Target:
private synchronized void processDistributedObjectInfos(ClientMessage response) { ClientGetDistributedObjectsCodec.ResponseParameters resultParameters = ClientGetDistributedObjectsCodec.decodeResponse(response); Collection<? extends DistributedObject> distributedObjects = getLocalDistributedObjects(); Set<DistributedObjectInfo> localDistributedObjects = new HashSet<DistributedObjectInfo>(); for (DistributedObject localInfo : distributedObjects) { localDistributedObjects.add(new DistributedObjectInfo(localInfo.getServiceName(), localInfo.getName())); } Collection<DistributedObjectInfo> newDistributedObjectInfo = resultParameters.response; for (DistributedObjectInfo distributedObjectInfo : newDistributedObjectInfo) { localDistributedObjects.remove(distributedObjectInfo); getOrCreateProxy(distributedObjectInfo.getServiceName(), distributedObjectInfo.getName(), false); } for (DistributedObjectInfo distributedObjectInfo : localDistributedObjects) { destroyProxyLocally(distributedObjectInfo.getServiceName(), distributedObjectInfo.getName()); } }
Source:
public void setWhiteListedRoutes(String s) { if (s != null && !s.equals("")) whiteListedRoutes = RouteMatcher.parse(s); else whiteListedRoutes = RouteMatcher.emptyMatcher(); }

Target:
public void setWhiteListedRoutes(String s) { if (!s.isEmpty()) { whiteListedRoutes = RouteMatcher.parse(s); } else { whiteListedRoutes = RouteMatcher.emptyMatcher(); } }
Source:
public void close() throws IOException { LOG.info("Processing remaining requests [docs = " + bulkDocs + ", length = " + bulkLength + ", total docs = " + indexedDocs + "]"); createNewBulk = false; commit(); LOG.info("Processing to finalize last execute"); createNewBulk = false; commit(); client.close(); if (node != null) { node.close(); } }

Target:
public void close() throws IOException { LOG.info("Processing remaining requests [docs = {}, length = {}, total docs = {}]" , bulkDocs, bulkLength, indexedDocs); createNewBulk = false; commit(); LOG.info("Processing to finalize last execute"); createNewBulk = false; commit(); client.close(); if (node != null) { node.close(); } }
Source:
public void handleRequest(HttpServerExchange exchange) throws Exception { logger.debug("Health check from {}", exchange.getSourceAddress().getHostString()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain; charset=utf-8"); if(shutdown) { exchange.setStatusCode(HTTP_UNAVAILABLE); exchange.getResponseSender().send("No p*ng for you, shutting down", StandardCharsets.UTF_8); logger.info("Return 503 on health check to indicate shutdown"); } else { exchange.getResponseSender().send("Pong", StandardCharsets.UTF_8); } }

Target:
public void handleRequest(HttpServerExchange exchange) throws Exception { logger.debug("Health check from {}", exchange.getSourceAddress().getHostString()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain; charset=utf-8"); if(shutdown) { exchange.setStatusCode(HTTP_UNAVAILABLE); exchange.getResponseSender().send("No p*ng for you, shutting down", StandardCharsets.UTF_8); logger.info("Return 503 on health check to indicate shutdown"); } else { exchange.getResponseSender().send("pong", StandardCharsets.UTF_8); } }
Source:
public static synchronized @NonNull SymbolProviderManager getInstance() { if (INSTANCE == null) { List<@NonNull SymbolProviderFactoryWrapper> providers = new ArrayList<>(); IConfigurationElement[] configElements = Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID); for (IConfigurationElement element : configElements) { if (ELEM_NAME_PROVIDER.equals(element.getName())) { try { Object extension = element.createExecutableExtension(ATTR_CLASS); int priority = 0; try { priority = Integer.parseInt(element.getAttribute(ATTR_PRIORITY)); } catch (NumberFormatException e) { } providers.add(new SymbolProviderFactoryWrapper((ISymbolProviderFactory) extension, priority)); } catch (CoreException | ClassCastException e) { Activator.getDefault().logError("Exception while loading extensions", e); } } } providers.sort(Comparator.<SymbolProviderFactoryWrapper> comparingLong(o -> o.priority).reversed()); } return INSTANCE; }

Target:
public static synchronized @NonNull SymbolProviderManager getInstance() { if (INSTANCE == null) { List<@NonNull SymbolProviderFactoryWrapper> providers = new ArrayList<>(); IConfigurationElement[] configElements = Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID); for (IConfigurationElement element : configElements) { if (ELEM_NAME_PROVIDER.equals(element.getName())) { try { Object extension = element.createExecutableExtension(ATTR_CLASS); int priority = 0; try { priority = Integer.parseInt(element.getAttribute(ATTR_PRIORITY)); } catch (NumberFormatException e) { } providers.add(new SymbolProviderFactoryWrapper((ISymbolProviderFactory) extension, priority)); } catch (CoreException | ClassCastException e) { Activator.getDefault().logError("Exception while loading extensions", e); } } } providers.sort(Comparator.<SymbolProviderFactoryWrapper> comparingLong(o -> o.priority).reversed()); INSTANCE = new SymbolProviderManager(providers); } return INSTANCE; }
Source:
public void onEvent(FormStatusEvent event) { if (isShowing() && event.getStatus().getFormDefinition().equals(form)) { try { editorArea.read(new StringReader(event.getStatus().getStatusHistory()), null); } catch (IOException e) { log.warn("failed to load history", e); } } }

Target:
public void onEvent(FormStatusEvent event) { if (isShowing() && event.getStatus().getFormDefinition().equals(form)) { try { Document doc = editorArea.getDocument(); String latestStatus = "\n" + event.getStatusString(); doc.insertString(doc.getLength(), latestStatus, null); } catch (BadLocationException e) { log.warn("failed to update history", e); } } }
Source:
private ArrayList<Long> generateSpinnerSpeeds() { long initialSpeed = 100; ArrayList<Long> speedList = new ArrayList<>(); speedList.add(-1l); for (int i = 1; i <= 10; i++) { speedList.add(initialSpeed * i); } return speedList; }

Target:
private ArrayList<Long> generateSpinnerSpeeds() { long initialSpeed = 100; ArrayList<Long> speedList = new ArrayList<>(); speedList.add(mExpandableAdapter.CUSTOM_ANIMATION_DURATION_NOT_SET); for (int i = 1; i <= 10; i++) { speedList.add(initialSpeed * i); } return speedList; }
Source:
public void throwsWhenIncorrectTypeInResponse() { assertThrows(AzureException.class, () -> { final Long eventHubName = 100L; final Date createdAtAsDate = new Date(1569275540L); final String[] partitionIds = new String[]{ "1", "foo", "bar", "baz" }; final Map<String, Object> values = new HashMap<>(); values.put(ManagementChannel.MANAGEMENT_ENTITY_NAME_KEY, eventHubName); values.put(ManagementChannel.MANAGEMENT_RESULT_CREATED_AT, createdAtAsDate); values.put(ManagementChannel.MANAGEMENT_RESULT_PARTITION_IDS, partitionIds); final AmqpValue amqpValue = new AmqpValue(values); final Message message = Proton.message(); message.setBody(amqpValue); serializer.deserialize(message, EventHubProperties.class); }); }

Target:
public void throwsWhenIncorrectTypeInResponse() { final Long eventHubName = 100L; final Date createdAtAsDate = new Date(1569275540L); final String[] partitionIds = new String[]{"1", "foo", "bar", "baz"}; final Map<String, Object> values = new HashMap<>(); values.put(ManagementChannel.MANAGEMENT_ENTITY_NAME_KEY, eventHubName); values.put(ManagementChannel.MANAGEMENT_RESULT_CREATED_AT, createdAtAsDate); values.put(ManagementChannel.MANAGEMENT_RESULT_PARTITION_IDS, partitionIds); final AmqpValue amqpValue = new AmqpValue(values); final Message message = Proton.message(); message.setBody(amqpValue); assertThrows(AzureException.class, () -> { serializer.deserialize(message, EventHubProperties.class); }); }
Source:
private boolean isRedo(Change newCh) { if (position < changes.size() - 1) { Change oldCh = changes.get(position + 1); boolean isEqual = oldCh.getChange().difference(newCh.getChange()).isEmpty(); boolean isOpposite = oldCh.isPositive() == newCh.isPositive(); return isEqual && isOpposite; } else { return false; } }

Target:
private boolean isRedo(Change newCh) { if (position < changes.size() - 1) { Change oldCh = changes.get(position + 1); boolean isEqual = oldCh.getChange().difference(newCh.getChange()).isEmpty(); boolean isSame = oldCh.isAddition() == newCh.isAddition(); return isEqual && isSame; } else { return false; } }
Source:
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Handler singleContext = _singleContext; if (singleContext != null) { singleContext.handle(target, baseRequest, request, response); return; } Mapping mapping = (Mapping)_handlers.get(); if (mapping == null && mapping.getHandlers().length == 0) return; HttpChannelState async = baseRequest.getHttpChannelState(); if (async.isAsync()) { ContextHandler context = async.getContextHandler(); if (context != null) { Handler branch = mapping._contextBranches.get(context); if (branch == null) context.handle(target, baseRequest, request, response); else branch.handle(target, baseRequest, request, response); return; } } if (target.startsWith("/")) { Trie<Map.Entry<String, Branch[]>> pathBranches = mapping._pathBranches; if (pathBranches == null) return; int limit = target.length() - 1; while (limit >= 0) { Map.Entry<String, Branch[]> branches = pathBranches.getBest(target, 1, limit); if (branches == null) break; int l = branches.getKey().length(); if (l == 1 || target.length() == l || target.charAt(l) == '/') { for (Branch branch : branches.getValue()) { branch.getHandler().handle(target, baseRequest, request, response); if (baseRequest.isHandled()) return; } } limit = l - 2; } } else { if (mapping.getHandlers() == null) return; for (int i = 0; i < mapping.getHandlers().length; i++) { mapping.getHandlers()[i].handle(target, baseRequest, request, response); if (baseRequest.isHandled()) return; } } }

Target:
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Mapping mapping = (Mapping)_handlers.get(); if (mapping == null) return; Handler[] handlers = mapping.getHandlers(); if (handlers == null || handlers.length == 0) return; if (handlers.length == 1) { handlers[0].handle(target, baseRequest, request, response); return; } HttpChannelState async = baseRequest.getHttpChannelState(); if (async.isAsync()) { ContextHandler context = async.getContextHandler(); if (context != null) { Handler branch = mapping._contextBranches.get(context); if (branch == null) context.handle(target, baseRequest, request, response); else branch.handle(target, baseRequest, request, response); return; } } if (target.startsWith("/")) { Trie<Map.Entry<String, Branch[]>> pathBranches = mapping._pathBranches; if (pathBranches == null) return; int limit = target.length() - 1; while (limit >= 0) { Map.Entry<String, Branch[]> branches = pathBranches.getBest(target, 1, limit); if (branches == null) break; int l = branches.getKey().length(); if (l == 1 || target.length() == l || target.charAt(l) == '/') { for (Branch branch : branches.getValue()) { branch.getHandler().handle(target, baseRequest, request, response); if (baseRequest.isHandled()) return; } } limit = l - 2; } } else { for (Handler handler : handlers) { handler.handle(target, baseRequest, request, response); if (baseRequest.isHandled()) return; } } }
Source:
private void cloneExistingGoalAsHistoryItem(UserAnonymized userAnonymizedEntity, Goal existingGoal) { Goal historyGoal = existingGoal.cloneAsHistoryItem(); existingGoal.setPreviousGoal(historyGoal); WeekActivity.getRepository().findByGoal(existingGoal).stream().forEach(a -> a.setGoal(historyGoal)); DayActivity.getRepository().findByGoal(existingGoal).stream().forEach(a -> a.setGoal(historyGoal)); }

Target:
private void cloneExistingGoalAsHistoryItem(UserAnonymized userAnonymizedEntity, Goal existingGoal) { Goal historyGoal = existingGoal.cloneAsHistoryItem(); existingGoal.setPreviousVersionOfThisGoal(historyGoal); WeekActivity.getRepository().findByGoal(existingGoal).stream().forEach(a -> a.setGoal(historyGoal)); DayActivity.getRepository().findByGoal(existingGoal).stream().forEach(a -> a.setGoal(historyGoal)); }
Source:
public abstract Object computeValue(Object row) throws HiveException; public abstract boolean isDistanceGreater(Object v1, Object v2, int amt); public abstract boolean isEqual(Object v1, Object v2); public abstract int computeStart(int rowIdx, PTFPartition p) throws HiveException; public abstract int computeEnd(int rowIdx, PTFPartition p) throws HiveException; public void handleCache(int rowIdx, PTFPartition p) throws HiveException { BoundaryCache cache = p.getBoundaryCache(); if (cache == null) { return; } if (rowIdx == 0) { cache.clear(); } if (cache.isComplete()) { return; } int cachePos = cache.approxCachePositionOf(rowIdx); if (cache.isEmpty()) { fillCacheUntilEndOrFull(rowIdx, p); } else if (cachePos > 50 && cachePos <= 75) { if (!start.isPreceding() && end.isFollowing()) { cache.evictHalf(); fillCacheUntilEndOrFull(rowIdx, p); } } else if (cachePos > 75 && cachePos <= 95) { if (start.isPreceding() && end.isFollowing()) { cache.evictHalf(); fillCacheUntilEndOrFull(rowIdx, p); } } else if (cachePos >= 95) { if (start.isPreceding() && !end.isFollowing()) { cache.evictHalf(); fillCacheUntilEndOrFull(rowIdx, p); } } }

Target:
public abstract Object computeValue(Object row) throws HiveException; public abstract boolean isDistanceGreater(Object v1, Object v2, int amt); public abstract boolean isEqual(Object v1, Object v2); public abstract int computeStart(int rowIdx, PTFPartition p) throws HiveException; public abstract int computeEnd(int rowIdx, PTFPartition p) throws HiveException; public void handleCache(int rowIdx, PTFPartition p) throws HiveException { BoundaryCache cache = p.getBoundaryCache(); if (cache == null) { return; } if (start.isUnbounded() && end.isUnbounded()) { return; } if (rowIdx == 0) { cache.clear(); } if (cache.isComplete()) { return; } if (cache.isEmpty()) { fillCacheUntilEndOrFull(rowIdx, p); return; } if (start.isPreceding()) { if (start.isUnbounded()) { if (end.isPreceding()) { Map.Entry<Integer, Object> maxEntry = cache.getMaxEntry(); if (maxEntry != null && maxEntry.getKey() <= rowIdx) { cache.evictOne(); } } else { checkIfCacheCanEvict(rowIdx, p, true); } } else { END is of FOLLOWING type: we should remove ranges preceding the current range beginning. Map.Entry<Integer, Object> maxEntry = cache.getMaxEntry(); if (maxEntry != null && maxEntry.getKey() <= rowIdx) { cache.evictOne(); } else if (end.isFollowing()) { int startIdx = computeStart(rowIdx, p); checkIfCacheCanEvict(startIdx - 1, p, true); } } } if (start.isCurrentRow()) { checkIfCacheCanEvict(rowIdx, p, false); } if (start.isFollowing()) { checkIfCacheCanEvict(rowIdx, p, true); } fillCacheUntilEndOrFull(rowIdx, p); }
Source:
private static List<TagObject> activeTagList(TagModel model) { List<TagObject> result = new ArrayList<>(); if (model.getSelection()) { result.add(from(model, false)); } for(TagModel child: model.getChildren()) { List<TagObject> activeChildTags = activeTagList(child); if (!activeChildTags.isEmpty()) { result.addAll(activeChildTags); } } return result; }

Target:
private static List<TagObject> activeTagList(TagModel model) { List<TagObject> result = new ArrayList<>(); if (model.getSelection()) { result.add(from(model, false)); } for (TagModel child : model.getChildren()) { result.addAll(activeTagList(child)); } return result; }
Source:
public void send(CommandSender sender) { sender.sendMessage(""); sender.sendMessage(ChatColor.GREEN + "===== Slimefun Lag Profiler ====="); sender.sendMessage(ChatColors.color("&6Total: &e" + NumberUtils.getAsMillis(totalElapsedTime))); sender.sendMessage(ChatColors.color("&6Performance: " + getPerformanceRating())); sender.sendMessage(ChatColors.color("&6Active Chunks: &e" + chunks.size())); sender.sendMessage(ChatColors.color("&6Active Blocks: &e" + totalTickedBlocks)); sender.sendMessage(""); summarizeTimings("Chunks", sender, entry -> { int count = profiler.getBlocksOfId(entry.getKey()); String time = NumberUtils.getAsMillis(entry.getValue()); if (count > 1) { String average = NumberUtils.getAsMillis(entry.getValue() / count); return entry.getKey() + " - " + count + "x (" + time + ", " + average + " avg/block)"; } else { return entry.getKey() + " - " + count + "x (" + time + ')'; } }, items.entrySet().stream()); sender.sendMessage(""); summarizeTimings("Blocks", sender, entry -> { int count = profiler.getBlocksInChunk(entry.getKey()); String time = NumberUtils.getAsMillis(entry.getValue()); return entry.getKey() + " - " + count + "x (" + time + ")"; }, chunks.entrySet().stream()); }

Target:
public void send(CommandSender sender) { sender.sendMessage(""); sender.sendMessage(ChatColor.GREEN + "===== Slimefun Lag Profiler ====="); sender.sendMessage(ChatColor.GOLD + "Total: " + ChatColor.YELLOW + NumberUtils.getAsMillis(totalElapsedTime)); sender.sendMessage(ChatColor.GOLD + "Performance: " + getPerformanceRating()); sender.sendMessage(ChatColor.GOLD + "Active Chunks: " + ChatColor.YELLOW + chunks.size()); sender.sendMessage(ChatColor.GOLD + "Active Blocks: " + ChatColor.YELLOW + totalTickedBlocks); sender.sendMessage(""); summarizeTimings("Blocks", sender, entry -> { int count = profiler.getBlocksOfId(entry.getKey()); String time = NumberUtils.getAsMillis(entry.getValue()); if (count > 1) { String average = NumberUtils.getAsMillis(entry.getValue() / count); return entry.getKey() + " - " + count + "x (" + time + ", " + average + " avg/block)"; } else { return entry.getKey() + " - " + count + "x (" + time + ')'; } }, items.entrySet().stream()); sender.sendMessage(""); summarizeTimings("Chunks", sender, entry -> { int count = profiler.getBlocksInChunk(entry.getKey()); String time = NumberUtils.getAsMillis(entry.getValue()); return entry.getKey() + " - " + count + "x (" + time + ")"; }, chunks.entrySet().stream()); }