auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Set<PersistentResource> getRelation(String relation, List<String> ids, Optional<FilterExpression> filter, Optional<Sorting> sorting, Optional<Pagination> pagination) { FilterExpression filterExpression; Class<?> entityType = dictionary.getParameterizedType(getResourceClass(), relation); Set<PersistentResource> newResources = new LinkedHashSet<>(); if (entityType == null) { throw new InvalidAttributeException(relation, type); } else { if (!ids.isEmpty()) { String typeAlias = dictionary.getJsonAliasFor(entityType); newResources = requestScope.getNewPersistentResources().stream() .filter(resource -> typeAlias.equals(resource.getType()) && ids.contains(resource.getUUID().orElse(""))) .collect(Collectors.toSet()); FilterExpression idExpression = buildIdFilterExpression(ids, entityType); filterExpression = filter .map(fe -> (FilterExpression) new AndFilterExpression(idExpression, fe)) .orElse(idExpression); } else { filterExpression = filter.orElse(null); } } Set<PersistentResource> existingResources = filter(ReadPermission.class, (Set) getRelationChecked(relation, Optional.ofNullable(filterExpression), sorting, pagination)); Set<PersistentResource> allResources = Sets.union(newResources, existingResources); Set<String> allExpectedIds = allResources.stream() .map(resource -> (String) resource.getUUID().orElseGet(resource::getId)) .collect(Collectors.toSet()); Set<String> missedIds = Sets.difference(new HashSet<>(ids), allExpectedIds); if (!missedIds.isEmpty()) { throw new EntityForbiddenException(); } return allResources; }

Target:
public Set<PersistentResource> getRelation(String relation, List<String> ids, Optional<FilterExpression> filter, Optional<Sorting> sorting, Optional<Pagination> pagination) { FilterExpression filterExpression; Class<?> entityType = dictionary.getParameterizedType(getResourceClass(), relation); Set<PersistentResource> newResources = new LinkedHashSet<>(); if (entityType == null) { throw new InvalidAttributeException(relation, type); } else { if (!ids.isEmpty()) { String typeAlias = dictionary.getJsonAliasFor(entityType); newResources = requestScope.getNewPersistentResources().stream() .filter(resource -> typeAlias.equals(resource.getType()) && ids.contains(resource.getUUID().orElse(""))) .collect(Collectors.toSet()); FilterExpression idExpression = buildIdFilterExpression(ids, entityType); filterExpression = filter .map(fe -> (FilterExpression) new AndFilterExpression(idExpression, fe)) .orElse(idExpression); } else { filterExpression = filter.orElse(null); } } Set<PersistentResource> existingResources = filter(ReadPermission.class, (Set) getRelationChecked(relation, Optional.ofNullable(filterExpression), sorting, pagination)); Set<PersistentResource> allResources = Sets.union(newResources, existingResources); Set<String> allExpectedIds = allResources.stream() .map(resource -> (String) resource.getUUID().orElseGet(resource::getId)) .collect(Collectors.toSet()); Set<String> missedIds = Sets.difference(new HashSet<>(ids), allExpectedIds); if (!missedIds.isEmpty()) { throw new ForbiddenEntityException(); } return allResources; }
Source:
public TableSnapshotResultIterator(Configuration configuration, Scan scan, ScanMetricsHolder scanMetricsHolder) throws IOException { this.configuration = configuration; this.currentRegion = -1; this.scan = scan; this.scanMetricsHolder = scanMetricsHolder; this.scanIterator = UNINITIALIZED_SCANNER; this.restoreDir = new Path(new Path(configuration.get(PhoenixConfigurationUtil.RESTORE_DIR_KEY)), UUID.randomUUID().toString()); this.snapshotName = configuration.get( PhoenixConfigurationUtil.SNAPSHOT_NAME_KEY); this.rootDir = FSUtils.getRootDir(configuration); this.fs = rootDir.getFileSystem(configuration); init(); }

Target:
public TableSnapshotResultIterator(Configuration configuration, Scan scan, ScanMetricsHolder scanMetricsHolder) throws IOException { this.configuration = configuration; this.currentRegion = -1; this.scan = scan; this.scanMetricsHolder = scanMetricsHolder; this.scanIterator = UNINITIALIZED_SCANNER; this.restoreDir = new Path(configuration.get(PhoenixConfigurationUtil.RESTORE_DIR_KEY), UUID.randomUUID().toString()); this.snapshotName = configuration.get( PhoenixConfigurationUtil.SNAPSHOT_NAME_KEY); this.rootDir = FSUtils.getRootDir(configuration); this.fs = rootDir.getFileSystem(configuration); init(); }
Source:
public BasicClusterDataCache(String clusterName) { _propertyDataChangedMap = new ConcurrentHashMap<>(); _externalViewCache = new ExternalViewCache(clusterName); _clusterName = clusterName; DEFAULT_CONTEXT_PROVIDER = AbstractDataCache.createDefaultControlContextProvider(clusterName); _liveInstancePropertyCache = new PropertyCache<>(DEFAULT_CONTEXT_PROVIDER, LIVE_INSTANCE, new PropertyCache.PropertyCacheKeyFuncs<LiveInstance>() { @Override public PropertyKey getRootKey(HelixDataAccessor accessor) { return accessor.keyBuilder().liveInstances(); } @Override public PropertyKey getObjPropertyKey(HelixDataAccessor accessor, String objName) { return accessor.keyBuilder().liveInstance(objName); } @Override public String getObjName(LiveInstance obj) { return obj.getInstanceName(); } }, true); _instanceConfigPropertyCache = new PropertyCache<>(DEFAULT_CONTEXT_PROVIDER, INSTANCE_CONFIG, new PropertyCache.PropertyCacheKeyFuncs<InstanceConfig>() { @Override public PropertyKey getRootKey(HelixDataAccessor accessor) { return accessor.keyBuilder().instanceConfigs(); } @Override public PropertyKey getObjPropertyKey(HelixDataAccessor accessor, String objName) { return accessor.keyBuilder().instanceConfig(objName); } @Override public String getObjName(InstanceConfig obj) { return obj.getInstanceName(); } }, true); }

Target:
public BasicClusterDataCache(String clusterName) { _propertyDataChangedMap = new ConcurrentHashMap<>(); _externalViewCache = new ExternalViewCache(clusterName); _clusterName = clusterName; _clusterEventId = AbstractDataCache.UNKNOWN_EVENT_ID; _liveInstancePropertyCache = new PropertyCache<>(this, LIVE_INSTANCE, new PropertyCache.PropertyCacheKeyFuncs<LiveInstance>() { @Override public PropertyKey getRootKey(HelixDataAccessor accessor) { return accessor.keyBuilder().liveInstances(); } @Override public PropertyKey getObjPropertyKey(HelixDataAccessor accessor, String objName) { return accessor.keyBuilder().liveInstance(objName); } @Override public String getObjName(LiveInstance obj) { return obj.getInstanceName(); } }, true); _instanceConfigPropertyCache = new PropertyCache<>(this, INSTANCE_CONFIG, new PropertyCache.PropertyCacheKeyFuncs<InstanceConfig>() { @Override public PropertyKey getRootKey(HelixDataAccessor accessor) { return accessor.keyBuilder().instanceConfigs(); } @Override public PropertyKey getObjPropertyKey(HelixDataAccessor accessor, String objName) { return accessor.keyBuilder().instanceConfig(objName); } @Override public String getObjName(InstanceConfig obj) { return obj.getInstanceName(); } }, true); }
Source:
public void helpBuildingEvent(EventBuilder eventBuilder) { eventBuilder.withSdkName(RavenEnvironment.SDK_NAME + ":android"); String release = tags.get(VERSION_NAME_TAG_KEY); if (!TextUtils.isEmpty(release)) { eventBuilder.withRelease(release); } for (String key : tags.keySet()) { eventBuilder.withTag(key, tags.get(key)); } }

Target:
public void helpBuildingEvent(EventBuilder eventBuilder) { eventBuilder.withSdkName(RavenEnvironment.SDK_NAME + ":android"); for (String key : tags.keySet()) { String value = tags.get(key); if (VERSION_NAME_TAG_KEY.equals(key)) { eventBuilder.withRelease(value); } eventBuilder.withTag(key, value); } }
Source:
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { File mdlRsrc = IgniteUtils.resolveIgnitePath(MODEL_PATH); if (mdlRsrc == null) throw new IllegalArgumentException("Resource not found [resource_path=" + MODEL_PATH + "]"); InfModelReader reader = new DirectoryInfModelReader(mdlRsrc.getPath()); InfModelParser<double[], Long> parser = new TensorFlowSavedModelInfModelParser<double[], Long>("serve") .withInput("Placeholder", doubles -> { float[][][] reshaped = new float[1][28][28]; for (int i = 0; i < doubles.length; i++) reshaped[0][i / 28][i % 28] = (float)doubles[i]; return Tensor.create(reshaped); }) .withOutput(Collections.singletonList("ArgMax"), collectedTensors -> { return collectedTensors.get("ArgMax").copyTo(new long[1])[0]; }); List<MnistUtils.MnistLabeledImage> images = MnistUtils.mnistAsListFromResource( MNIST_IMG_PATH, MNIST_LBL_PATH, new Random(0), 10000 ); long t0 = System.currentTimeMillis(); try (InfModel<double[], Future<Long>> threadedMdl = new ThreadedInfModelBuilder(8) .build(reader, parser)) { List<Future<?>> futures = new ArrayList<>(images.size()); for (MnistUtils.MnistLabeledImage image : images) futures.add(threadedMdl.predict(image.getPixels())); for (Future<?> f : futures) f.get(); } long t1 = System.currentTimeMillis(); System.out.println("Threaded model throughput: " + 1.0 * images.size() / ((t1 - t0) / 1000) + " req/sec"); }

Target:
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { File mdlRsrc = IgniteUtils.resolveIgnitePath(MODEL_PATH); if (mdlRsrc == null) throw new IllegalArgumentException("Resource not found [resource_path=" + MODEL_PATH + "]"); InfModelReader reader = new FileSystemInfModelReader(mdlRsrc.getPath()); InfModelParser<double[], Long> parser = new TensorFlowSavedModelInfModelParser<double[], Long>("serve") .withInput("Placeholder", doubles -> { float[][][] reshaped = new float[1][28][28]; for (int i = 0; i < doubles.length; i++) reshaped[0][i / 28][i % 28] = (float)doubles[i]; return Tensor.create(reshaped); }) .withOutput(Collections.singletonList("ArgMax"), collectedTensors -> { return collectedTensors.get("ArgMax").copyTo(new long[1])[0]; }); List<MnistUtils.MnistLabeledImage> images = MnistUtils.mnistAsListFromResource( MNIST_IMG_PATH, MNIST_LBL_PATH, new Random(0), 10000 ); long t0 = System.currentTimeMillis(); try (InfModel<double[], Future<Long>> threadedMdl = new ThreadedInfModelBuilder(8) .build(reader, parser)) { List<Future<?>> futures = new ArrayList<>(images.size()); for (MnistUtils.MnistLabeledImage image : images) futures.add(threadedMdl.predict(image.getPixels())); for (Future<?> f : futures) f.get(); } long t1 = System.currentTimeMillis(); System.out.println("Threaded model throughput: " + 1.0 * images.size() / ((t1 - t0) / 1000) + " req/sec"); }
Source:
public synchronized void register(ServiceEndPoint endPoint) { String uniqueId = buildUniqueId(endPoint); S service = _serviceFactory.create(endPoint); ServiceHandle<S> serviceHandle = new ServiceHandle<>(service, endPoint); Map<String, ServiceHandle<S>> instancesPerEndPointCopy = Maps.newHashMap(_instancesPerEndpoint); instancesPerEndPointCopy.put(uniqueId, serviceHandle); _instancesPerEndpoint = instancesPerEndPointCopy; }

Target:
public synchronized void register(ServiceEndPoint endPoint) { checkNotNull(endPoint); Timer.Context context = _registerTimer.time(); doRegister(endPoint); ServiceHandle<S> evictedServiceHandle = _evictedList.getIfPresent(endPoint); if(evictedServiceHandle != null) { _evictedList.invalidate(endPoint); } context.stop(); }
Source:
private IJavaClassObject loadTheClasses(IJavaThread theThread) throws DebugException { if (loadedClass != null) { return loadedClass; } JDIDebugTarget debugTarget = ((JDIDebugTarget) theThread.getDebugTarget()); IJavaClassObject theMainClass = null; IJavaObject classloader = null; try { IJavaReferenceType surroundingClass = findType(this.enclosingTypeName, debugTarget); classloader = surroundingClass.getClassLoaderObject(); } catch (DebugException ex) { throw new DebugException(new Status(IStatus.ERROR, JDIDebugModel.getPluginIdentifier(), DebugException.REQUEST_FAILED, EvaluationMessages.RemoteEvaluationEngine_Evaluation_failed___unable_to_load_surrounding_class, null)); } for (Map.Entry<String, byte[]> entry : classFiles.entrySet()) { String className = entry.getKey(); IJavaReferenceType existingClass = tryLoadType(className, debugTarget); if (existingClass != null) { if (codeSnippetClassName.equals(className)) { theMainClass = existingClass.getClassObject(); } } else { IJavaArray byteArray = createClassBytes(theThread, debugTarget, entry); IJavaValue[] defineClassArgs = new IJavaValue[] { debugTarget.newValue(className.replaceAll("/", ".")), byteArray, debugTarget.newValue(0), debugTarget.newValue(entry.getValue().length), debugTarget.nullValue() }; IJavaClassObject theClass = (IJavaClassObject) classloader.sendMessage("defineClass", "(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;", defineClassArgs, theThread, false); if (codeSnippetClassName.equals(className)) { theMainClass = theClass; } } } return theMainClass; }

Target:
private IJavaClassObject loadTheClasses(IJavaThread theThread) throws DebugException { if (loadedClass != null) { return loadedClass; } JDIDebugTarget debugTarget = ((JDIDebugTarget) theThread.getDebugTarget()); IJavaClassObject theMainClass = null; IJavaObject classloader = null; IJavaReferenceType surroundingClass = findType(this.enclosingTypeName, debugTarget); classloader = surroundingClass.getClassLoaderObject(); for (Map.Entry<String, byte[]> entry : classFiles.entrySet()) { String className = entry.getKey(); IJavaReferenceType existingClass = tryLoadType(className, debugTarget); if (existingClass != null) { if (codeSnippetClassName.equals(className)) { theMainClass = existingClass.getClassObject(); } } else { IJavaArray byteArray = createClassBytes(theThread, debugTarget, entry); IJavaValue[] defineClassArgs = new IJavaValue[] { debugTarget.newValue(className.replaceAll("/", ".")), byteArray, debugTarget.newValue(0), debugTarget.newValue(entry.getValue().length), debugTarget.nullValue() }; IJavaClassObject theClass = (IJavaClassObject) classloader.sendMessage("defineClass", "(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;", defineClassArgs, theThread, false); if (codeSnippetClassName.equals(className)) { theMainClass = theClass; } } } return theMainClass; }
Source:
public IStatus openTraceFromPath(String projectRoot, String path, Shell shell, String tracetypeHint) throws CoreException { TraceTypeHelper traceTypeToSet = null; try { traceTypeToSet = TmfTraceTypeUIUtils.selectTraceType(path, null, tracetypeHint); } catch (TmfTraceImportException e) { MessageBox mb = new MessageBox(shell); mb.setMessage(e.getMessage()); mb.open(); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()); } IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectRoot); IFolder folder = project.getFolder(TmfTraceFolder.TRACE_FOLDER_NAME); String traceName = getTraceName(path, folder); if (traceExists(path, folder)) { return openTraceFromProject(projectRoot, traceName); } final IPath tracePath = folder.getFullPath().append(traceName); IResource linkedTrace = TmfImportHelper.createLink(folder, tracePath, traceName); if (linkedTrace == null || !linkedTrace.exists()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TmfOpenTraceHelper_LinkFailed); } if (traceTypeToSet == null) { return Status.OK_STATUS; } IStatus ret = TmfTraceTypeUIUtils.setTraceType(linkedTrace, traceTypeToSet); if (ret.isOK()) { ret = openTraceFromProject(projectRoot, traceName); } return ret; }

Target:
public IStatus openTraceFromPath(String projectRoot, String path, Shell shell, String tracetypeHint) throws CoreException { TraceTypeHelper traceTypeToSet = null; try { traceTypeToSet = TmfTraceTypeUIUtils.selectTraceType(path, null, tracetypeHint); } catch (TmfTraceImportException e) { MessageBox mb = new MessageBox(shell); mb.setMessage(e.getMessage()); mb.open(); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()); } IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectRoot); IFolder folder = project.getFolder(TmfTraceFolder.TRACE_FOLDER_NAME); String traceName = getTraceName(path, folder); if (traceExists(path, folder)) { return openTraceFromProject(projectRoot, traceName); } final IPath pathString = Path.fromOSString(path); IResource linkedTrace = TmfImportHelper.createLink(folder, pathString, traceName); if (linkedTrace == null || !linkedTrace.exists()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TmfOpenTraceHelper_LinkFailed); } if (traceTypeToSet == null) { return Status.OK_STATUS; } IStatus ret = TmfTraceTypeUIUtils.setTraceType(linkedTrace, traceTypeToSet); if (ret.isOK()) { ret = openTraceFromProject(projectRoot, traceName); } return ret; }
Source:
public OperationResult doOperationCallback() throws OperationException { final String pluginName; try { pluginName = daoHelper.getPaymentProviderPluginName(true); this.plugin = daoHelper.getPaymentPluginApi(); } catch (final PaymentApiException e) { throw convertToUnknownTransactionStatusAndErroredPaymentState(e); } if (paymentStateContext.shouldLockAccountAndDispatch()) { return doOperationCallbackWithDispatchAndAccountLock(pluginName); } else { try { return doSimpleOperationCallback(); } catch (final OperationException e) { throw convertToUnknownTransactionStatusAndErroredPaymentState(e); } } }

Target:
public OperationResult doOperationCallback() throws OperationException { try { this.paymentPluginApi = daoHelper.getPaymentPluginApi(); } catch (final PaymentApiException e) { throw convertToUnknownTransactionStatusAndErroredPaymentState(e); } if (paymentStateContext.shouldLockAccountAndDispatch()) { return doOperationCallbackWithDispatchAndAccountLock(daoHelper.getPluginName()); } else { try { return doSimpleOperationCallback(); } catch (final OperationException e) { throw convertToUnknownTransactionStatusAndErroredPaymentState(e); } } }
Source:
public Collection<Integer> selectNextChildren(RangeCondition<Long> rc) { OverlappingNode<?> node = getNode(); if (rc.min() < node.getNodeStart() || (node.isOnDisk() && rc.max() > node.getNodeEnd())) { throw new RangeException("Requesting children outside the node's range: " + rc.toString()); } node.takeReadLock(); try { List<Integer> childList = new ArrayList<>(); for (int i = 0; i < getNbChildren(); i++) { if (rc.intersects(fChildStart[i], fChildEnd[i])) { childList.add(getChild(i)); } } return childList; } finally { node.releaseReadLock(); } }

Target:
public Collection<Integer> selectNextChildren(RangeCondition<Long> rc) { OverlappingNode<?> node = getNode(); if (rc.min() < node.getNodeStart() || rc.max() > node.getNodeEnd()) { throw new RangeException("Requesting children outside the node's range: " + rc.toString()); } node.takeReadLock(); try { List<Integer> childList = new ArrayList<>(); for (int i = 0; i < getNbChildren(); i++) { if (rc.intersects(fChildStart[i], fChildEnd[i])) { childList.add(getChild(i)); } } return childList; } finally { node.releaseReadLock(); } }
Source:
public static boolean motionDuringSleepCheck(final int minMotionCount, final ImmutableList<TrackerMotion> trackerMotions, final Long fallAsleepTimestamp, final Long wakeUpTimestamp) { final float sleepDuration = (int) ((double) (wakeUpTimestamp - fallAsleepTimestamp) / 60000.0); final int requiredSleepDuration = 120; final int sleepWindowPadding = 30 * DateTimeConstants.MILLIS_PER_MINUTE; final int motionCount = getMotionCount(trackerMotions, fallAsleepTimestamp + sleepWindowPadding, wakeUpTimestamp - sleepWindowPadding); if (motionCount < minMotionCount && sleepDuration > requiredSleepDuration) { return false; } return true; }

Target:
public static boolean motionDuringSleepCheck(final int minMotionCount, final ImmutableList<TrackerMotion> trackerMotions, final Long fallAsleepTimestamp, final Long wakeUpTimestamp) { final float sleepDuration = (wakeUpTimestamp - fallAsleepTimestamp) / DateTimeConstants.MILLIS_PER_MINUTE; final int requiredSleepDuration = 120; final int sleepWindowPadding = 30 * DateTimeConstants.MILLIS_PER_MINUTE; final int motionCount = getMotionCount(trackerMotions, fallAsleepTimestamp + sleepWindowPadding, wakeUpTimestamp - sleepWindowPadding); if (motionCount < minMotionCount && sleepDuration > requiredSleepDuration) { return false; } return true; }
Source:
protected void update(final TransactionalEditingDomain domain, final Notification notification) { if (parentPropertySheetPage.isUpdateEnabled()) { Object notifier = notification.getNotifier(); if (notifier instanceof EObject && contentPage != null && contentPage.getControl() != null) { final Control control = contentPage.getControl(); control.getDisplay().syncExec(new Runnable() { public void run() { if (!control.isDisposed() && control.isVisible()) { if (!notification.getNewValue().equals(notification.getOldValue())) { refresh(); } } } }); } } }

Target:
protected void update(final TransactionalEditingDomain domain, final Notification notification) { if (parentPropertySheetPage.isUpdateEnabled()) { Object notifier = notification.getNotifier(); if (notifier instanceof EObject && contentPage != null && contentPage.getControl() != null) { final Control control = contentPage.getControl(); control.getDisplay().syncExec(new Runnable() { public void run() { if (!control.isDisposed() && control.isVisible()) { refresh(); } } }); } } }
Source:
public void init() { solrUrl = serverConfigurationService.getString("ses.solr.server", null); solrServer = new ConcurrentUpdateSolrServer(solrUrl, 1000, 1); Integer.parseInt(serverConfigurationService.getString("recent.days", "14")); }

Target:
public void init() { solrUrl = serverConfigurationService.getString("ses.solr.server", null); solrServer = new ConcurrentUpdateSolrServer(solrUrl, 1000, 1); }
Source:
public PropertiesPermissionLoader(Properties props) { Map<String, Permissions> b = Maps.newHashMap(); for (String key : props.stringPropertyNames()) { b.put(key, permissionsFromString(props.getProperty(key))); } if (!b.containsKey(ANONYMOUS_PERMISSIONS_KEY)) { b.put(ANONYMOUS_PERMISSIONS_KEY, new Permissions(new ArrayList<>())); } this.permissions = ImmutableMap.copyOf(b); }

Target:
public PropertiesPermissionLoader(Properties props) { Map<String, Permissions> b = Maps.newHashMap(); for (String key : props.stringPropertyNames()) { b.put(key, permissionsFromString(props.getProperty(key))); } if (!b.containsKey(ANONYMOUS_PERMISSIONS_KEY)) { b.put(ANONYMOUS_PERMISSIONS_KEY, new Permissions(Collections.emptyList())); } this.permissions = ImmutableMap.copyOf(b); }
Source:
public void testDiff() throws Exception { write(new File(db.getDirectory().getParent(), "test.txt"), "test"); File folder = new File(db.getDirectory().getParent(), "folder"); folder.mkdir(); write(new File(folder, "folder.txt"), "folder"); Git git = new Git(db); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); write(new File(folder, "folder.txt"), "folder change"); PatchIdDiffFormatter df = new PatchIdDiffFormatter(); df.setRepository(db); df.setPathFilter(PathFilter.create("folder")); DirCacheIterator oldTree = new DirCacheIterator(db.readDirCache()); FileTreeIterator newTree = new FileTreeIterator(db); df.format(oldTree, newTree); df.flush(); assertEquals("AnyObjectId[1ff64e0f9333e9b81967c3e8d7a81362b14d5441]", df.getCalulatedPatchId().toString()); }

Target:
public void testDiff() throws Exception { write(new File(db.getDirectory().getParent(), "test.txt"), "test"); File folder = new File(db.getDirectory().getParent(), "folder"); folder.mkdir(); write(new File(folder, "folder.txt"), "folder"); Git git = new Git(db); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); write(new File(folder, "folder.txt"), "folder change"); PatchIdDiffFormatter df = new PatchIdDiffFormatter(); df.setRepository(db); df.setPathFilter(PathFilter.create("folder")); DirCacheIterator oldTree = new DirCacheIterator(db.readDirCache()); FileTreeIterator newTree = new FileTreeIterator(db); df.format(oldTree, newTree); df.flush(); assertEquals("1ff64e0f9333e9b81967c3e8d7a81362b14d5441", df .getCalulatedPatchId().name()); }
Source:
public static void deactivateTenant(String tenantDomain) throws RestAPIException { TenantManager tenantManager = ServiceHolder.getTenantManager(); int tenantId; try { tenantId = tenantManager.getTenantId(tenantDomain); if (tenantId != -1) { try { TenantMgtUtil.deactivateTenant(tenantDomain, tenantManager, tenantId); } catch (Exception e) { String msg = "Error in deactivating Tenant :" + tenantDomain; log.error(msg, e); throw new RestAPIException(msg, e); } try { TenantMgtUtil.triggerTenantDeactivation(tenantId); } catch (StratosException e) { String msg = "Error in notifying tenant deactivate."; log.error(msg, e); throw new RestAPIException(msg, e); } } else { String msg = "The tenant with domain name: " + tenantDomain + " does not exist."; throw new RestAPIException(msg); } } catch (UserStoreException e) { String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain + "."; log.error(msg, e); throw new RestAPIException(msg, e); } }

Target:
public static void deactivateTenant(String tenantDomain) throws RestAPIException { TenantManager tenantManager = ServiceHolder.getTenantManager(); int tenantId; try { tenantId = tenantManager.getTenantId(tenantDomain); if (tenantId != -1) { try { TenantMgtUtil.deactivateTenant(tenantDomain, tenantManager, tenantId); } catch (Exception e) { String msg = "Error in deactivating Tenant :" + tenantDomain; log.error(msg, e); throw new RestAPIException(msg, e); } try { TenantMgtUtil.triggerTenantDeactivation(tenantId); } catch (StratosException e) { String msg = "Error in notifying tenant deactivate."; log.error(msg, e); throw new RestAPIException(msg, e); } } else { String msg = "The tenant with domain name: " + tenantDomain + " does not exist."; throw new InvalidDomainException(msg); } } catch (UserStoreException e) { String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain + "."; log.error(msg, e); throw new RestAPIException(msg, e); } }
Source:
public void testRemoveAlias() throws IOException, TimeoutException, InterruptedException { final String aliasName = "my_alias_" + RandomStringUtils.randomNumeric(7); try { ops.invoke(ADD_ALIAS_OPERATION,credentialStoreAddress,Values.of(ALIAS,aliasName)).assertSuccess(); page.navigate(); page.getResourceManager().selectByName(CREDENTIAL_STORE_NAME); ResourceManager aliasManager = page.getConfig() .switchTo(ALIASES_TAB_LABEL) .getResourceManager(); aliasManager .removeResource(aliasName) .confirmAndDismissReloadRequiredMessage() .assertClosed(); Assert.assertFalse(aliasManager.isResourcePresent(aliasName)); ModelNodeResult aliases = ops.invoke(READ_ALIASES_OPERATION, credentialStoreAddress); aliases.assertSuccess(); Assert.assertFalse("Created alias should be present in model", aliases.stringListValue().contains(aliasName)); } finally { ops.invoke(REMOVE_ALIAS_OPERATION, credentialStoreAddress, Values.of(ALIAS, aliasName)); adminOps.reloadIfRequired(); } }

Target:
public void testRemoveAlias() throws IOException, TimeoutException, InterruptedException { final String aliasName = "my_alias_" + RandomStringUtils.randomNumeric(7); try { ops.invoke(ADD_ALIAS_OPERATION, credentialStoreAddress, Values.of(ALIAS, aliasName)).assertSuccess(); page.navigate(); page.getResourceManager().selectByName(CREDENTIAL_STORE_NAME); ResourceManager aliasManager = page.getConfig() .switchTo(ALIASES_TAB_LABEL) .getResourceManager(); aliasManager .removeResource(aliasName) .confirmAndDismissReloadRequiredMessage() .assertClosed(); Assert.assertFalse("Removed alias should not be present in table anymore", aliasManager.isResourcePresent(aliasName)); ModelNodeResult aliases = ops.invoke(READ_ALIASES_OPERATION, credentialStoreAddress); aliases.assertSuccess(); Assert.assertFalse("Removed alias should not be present in model anymore", aliases.stringListValue().contains(aliasName)); } finally { ops.invoke(REMOVE_ALIAS_OPERATION, credentialStoreAddress, Values.of(ALIAS, aliasName)); adminOps.reloadIfRequired(); } }
Source:
public void testAddMovePlanDependency() { final Plan plan = PlanImpl.newBuilder() .addTransferStep(NAMESPACE_PREFIX, new TransferStepImpl(EVAL_PREFIX + 1, EVAL_PREFIX + 0, new DataInfoImpl(1))) .addEvaluatorToAdd(NAMESPACE_PREFIX, EVAL_PREFIX + 0) .addTransferStep(NAMESPACE_PREFIX, new TransferStepImpl(EVAL_PREFIX + 2, EVAL_PREFIX + 0, new DataInfoImpl(1))) .addEvaluatorToAdd(NAMESPACE_PREFIX, EVAL_PREFIX + 3) .addTransferStep(NAMESPACE_PREFIX, new TransferStepImpl(EVAL_PREFIX + 1, EVAL_PREFIX + 3, new DataInfoImpl(1))) .addTransferStep(NAMESPACE_PREFIX, new TransferStepImpl(EVAL_PREFIX + 2, EVAL_PREFIX + 3, new DataInfoImpl(1))) .build(); final Set<EMOperation> firstOpsToExec = plan.getReadyOps(); assertEquals(2, firstOpsToExec.size()); EMOperation firstAdd = null; EMOperation secondAdd = null; for (final EMOperation operation : firstOpsToExec) { assertEquals(EMOperation.OpType.Add, operation.getOpType()); if (operation.getEvalId().get().equals(EVAL_PREFIX + 0)) { firstAdd = operation; } else { secondAdd = operation; } } assertNotNull(firstAdd); assertNotNull(secondAdd); final Set<EMOperation> nextOpsToExec = plan.onComplete(firstAdd); assertEquals(2, nextOpsToExec.size()); nextOpsToExec.addAll(plan.onComplete(secondAdd)); assertEquals(4, nextOpsToExec.size()); for (final EMOperation operation : nextOpsToExec) { assertEquals(EMOperation.OpType.Move, operation.getOpType()); assertTrue(plan.onComplete(operation).isEmpty()); } assertTrue(plan.getReadyOps().isEmpty()); }

Target:
public void testAddMovePlanDependency() { final Plan plan = PlanImpl.newBuilder() .addTransferStep(NAMESPACE_PREFIX, new TransferStepImpl(EVAL_PREFIX + 1, EVAL_PREFIX + 0, new DataInfoImpl(1))) .addEvaluatorToAdd(NAMESPACE_PREFIX, EVAL_PREFIX + 0) .addTransferStep(NAMESPACE_PREFIX, new TransferStepImpl(EVAL_PREFIX + 2, EVAL_PREFIX + 0, new DataInfoImpl(1))) .addEvaluatorToAdd(NAMESPACE_PREFIX, EVAL_PREFIX + 3) .addTransferStep(NAMESPACE_PREFIX, new TransferStepImpl(EVAL_PREFIX + 1, EVAL_PREFIX + 3, new DataInfoImpl(1))) .addTransferStep(NAMESPACE_PREFIX, new TransferStepImpl(EVAL_PREFIX + 2, EVAL_PREFIX + 3, new DataInfoImpl(1))) .build(); final Set<EMOperation> firstOpsToExec = plan.getReadyOps(); assertEquals(2, firstOpsToExec.size()); EMOperation firstAdd = null; EMOperation secondAdd = null; for (final EMOperation operation : firstOpsToExec) { assertEquals(EMOperation.OpType.ADD, operation.getOpType()); if (operation.getEvalId().get().equals(EVAL_PREFIX + 0)) { firstAdd = operation; } else { secondAdd = operation; } } assertNotNull(firstAdd); assertNotNull(secondAdd); final Set<EMOperation> nextOpsToExec = plan.onComplete(firstAdd); assertEquals(2, nextOpsToExec.size()); nextOpsToExec.addAll(plan.onComplete(secondAdd)); assertEquals(4, nextOpsToExec.size()); for (final EMOperation operation : nextOpsToExec) { assertEquals(EMOperation.OpType.MOVE, operation.getOpType()); assertTrue(plan.onComplete(operation).isEmpty()); } assertTrue(plan.getReadyOps().isEmpty()); }
Source:
public InputStream getResourceAsStream(@Nonnull String name) { VPath path = new VPath(name, '/'); InputVFile vFile; try { vFile = vfs.getRootInputVDir().getInputVFile(path); return vFile.getInputStream(); } catch (WrongPermissionException | NotFileOrDirectoryException | NoSuchFileException e) { return null; } }

Target:
public InputStream getResourceAsStream(@Nonnull String name) { VPath path = new VPath(name, '/'); InputVFile vFile; try { vFile = vfs.getRootInputVDir().getInputVFile(path); return vFile.getInputStream(); } catch (WrongPermissionException e) { logger.log(Level.SEVERE, "Failed to open resource '" + name + "' from " + vfs.getLocation().getDescription(), e); return null; } catch (NotFileOrDirectoryException | NoSuchFileException e) { return null; } }
Source:
public void createTopic(Topic topic) { topicValidator.ensureCreatedTopicIsValid(topic); topicRepository.createTopic(topic); if (!multiDCAwareService.topicExists(topic)) { createTopicInBrokers(topic); } else { logger.info(String.format("Skipping creating topic %s on brokers, topic already exists", topic.getQualifiedName())); } }

Target:
public void createTopic(Topic topic) { topicValidator.ensureCreatedTopicIsValid(topic); topicRepository.createTopic(topic); if (!multiDCAwareService.topicExists(topic)) { createTopicInBrokers(topic); } else { logger.info("Skipping creation of topic on brokers, topic already exists", topic.getQualifiedName()); } }
Source:
public BlockingChannelConnectionPool(ConnectionPoolConfig config, MetricRegistry registry) { connections = new ConcurrentHashMap<String, BlockingChannelInfo>(); this.config = config; this.registry = registry; connectionCheckOutTime = registry.timer(MetricRegistry.name(BlockingChannelInfo.class, "connectionCheckOutTime")); connectionCheckInTime = registry.timer(MetricRegistry.name(BlockingChannelInfo.class, "connectionCheckInTime")); connectionDestroyTime = registry.timer(MetricRegistry.name(BlockingChannelInfo.class, "connectionDestroyTime")); numberOfConnections = new Gauge<Integer>() { @Override public Integer getValue() { return connections.size(); } }; registry.register(MetricRegistry.name(BlockingChannelInfo.class, "numberOfConnections"), numberOfConnections); }

Target:
public BlockingChannelConnectionPool(ConnectionPoolConfig config, MetricRegistry registry) { connections = new ConcurrentHashMap<String, BlockingChannelInfo>(); this.config = config; this.registry = registry; connectionCheckOutTime = registry.timer(MetricRegistry.name(BlockingChannelConnectionPool.class, "connectionCheckOutTime")); connectionCheckInTime = registry.timer(MetricRegistry.name(BlockingChannelConnectionPool.class, "connectionCheckInTime")); connectionDestroyTime = registry.timer(MetricRegistry.name(BlockingChannelConnectionPool.class, "connectionDestroyTime")); totalNumberOfNodesConnectedTo = new Gauge<Integer>() { @Override public Integer getValue() { int noOfNodesConnectedTo = 0; for (BlockingChannelInfo blockingChannelInfo : connections.values()) { if (blockingChannelInfo.getNumberOfConnections() > 0) { noOfNodesConnectedTo++; } } return noOfNodesConnectedTo; } }; registry.register(MetricRegistry.name(BlockingChannelConnectionPool.class, "totalNumberOfNodesConnectedTo"), totalNumberOfNodesConnectedTo); totalNumberOfConnections = new Gauge<Integer>() { @Override public Integer getValue() { int noOfConnections = 0; for (BlockingChannelInfo blockingChannelInfo : connections.values()) { noOfConnections += blockingChannelInfo.getNumberOfConnections(); } return noOfConnections; } }; registry.register(MetricRegistry.name(BlockingChannelConnectionPool.class, "totalNumberOfConnections"), totalNumberOfConnections); }
Source:
static void addService(final ServiceTarget serviceTarget) { ServiceBuilder<?> builder = serviceTarget.addService(ArquillianService.SERVICE_NAME); builder.setInstance(new ArquillianService( builder.requires(MBeanServerService.SERVICE_NAME), builder.provides(ArquillianService.SERVICE_NAME) )); builder.install(); }

Target:
public static void addService(final ServiceTarget serviceTarget) { ServiceBuilder<?> builder = serviceTarget.addService(ArquillianService.SERVICE_NAME); builder.setInstance(new ArquillianService( builder.requires(MBeanServerService.SERVICE_NAME), builder.provides(ArquillianService.SERVICE_NAME) )); builder.install(); }
Source:
protected void rollbackStreamUnsafe(ISMRStream stream, long rollbackVersion) { if (stream.pos() <= rollbackVersion) { return; } List<SMREntry> entries = stream.current(); while (entries != null) { if (entries.stream().allMatch(x -> x.isUndoable())) { ListIterator<SMREntry> it = entries.listIterator(entries.size()); while (it.hasPrevious()) { applyUndoRecordUnsafe(it.previous()); } } else { Optional<SMREntry> entry = entries.stream().findFirst(); log.trace("rollbackStreamUnsafe: one or more stream entries in address @{} are not undoable. Undoable entries: {}/{}", stream.pos(), entries.stream().filter(x -> x.isUndoable()).collect(Collectors.toList()).size(), entries.size()); throw new NoRollbackException(entry, stream.pos(), rollbackVersion); } entries = stream.previous(); if (stream.pos() <= rollbackVersion) { return; } } throw new NoRollbackException(stream.pos(), rollbackVersion); }

Target:
protected void rollbackStreamUnsafe(ISMRStream stream, long rollbackVersion) { if (stream.pos() <= rollbackVersion) { return; } List<SMREntry> entries = stream.current(); while (entries != null) { if (entries.stream().allMatch(x -> x.isUndoable())) { ListIterator<SMREntry> it = entries.listIterator(entries.size()); while (it.hasPrevious()) { applyUndoRecordUnsafe(it.previous()); } } else { Optional<SMREntry> entry = entries.stream().findFirst(); if (log.isTraceEnabled()) { log.trace("rollbackStreamUnsafe: one or more stream entries in address @{} are not undoable. " + "Undoable entries: {}/{}", stream.pos(), entries.stream().filter(x -> x.isUndoable()).collect(Collectors.toList()).size(), entries.size()); } throw new NoRollbackException(entry, stream.pos(), rollbackVersion); } entries = stream.previous(); if (stream.pos() <= rollbackVersion) { return; } } throw new NoRollbackException(stream.pos(), rollbackVersion); }
Source:
private String getNDJSON(List<Entry> publishedEntries) { Gson gson = new GsonBuilder().create(); StringBuilder builder = new StringBuilder(); publishedEntries.forEach(entry -> { Map<String, Map<String, String>> index = new HashMap<>(); Map<String, String> internal = new HashMap<>(); internal.put("_id", String.valueOf(entry.getId())); internal.put("_type", entry instanceof Tool ? "tool" : "workflow"); index.put("index", internal); builder.append(gson.toJson(index)); builder.append('\n'); try { builder.append(MAPPER.writeValueAsString(dockstoreEntryToElasticSearchObject(entry))); } catch (IOException e) { throw new CustomWebApplicationException("Could not convert Dockstore entry to Elasticsearch object. ", HttpStatus.SC_INTERNAL_SERVER_ERROR); } builder.append('\n'); }); return builder.toString(); }

Target:
private String getNDJSON(List<Entry> publishedEntries) { Gson gson = new GsonBuilder().create(); StringBuilder builder = new StringBuilder(); publishedEntries.forEach(entry -> { Map<String, Map<String, String>> index = new HashMap<>(); Map<String, String> internal = new HashMap<>(); internal.put("_id", String.valueOf(entry.getId())); internal.put("_type", entry instanceof Tool ? "tool" : "workflow"); index.put("index", internal); builder.append(gson.toJson(index)); builder.append('\n'); try { builder.append(MAPPER.writeValueAsString(dockstoreEntryToElasticSearchObject(entry))); } catch (IOException e) { throw new CustomWebApplicationException(MAPPER_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR); } builder.append('\n'); }); return builder.toString(); }
Source:
public void shouldApplyForEachTupleInClusteredMode() throws Exception { String[] columnNames = { "foo", "bar", "baz" }; EntityKeyMetadata keyMetadata = new DefaultEntityKeyMetadata( "Foobar", columnNames ); Object[] values = { 123, "Hello", 456L }; EntityKey key = new EntityKey( keyMetadata, values ); Tuple tuple = dialect1.createTuple( key, emptyTupleContext() ); tuple.put( "foo", "bar" ); dialect1.insertOrUpdateTuple( key, tuple, emptyTupleContext() ); MyConsumer consumer = new MyConsumer(); dialect2.forEachTuple( consumer, null, keyMetadata ); assertThat( consumer.consumedTuple.get( "foo" ) ).isEqualTo( "bar" ); }

Target:
public void shouldApplyForEachTupleInClusteredMode() throws Exception { String[] columnNames = { "foo", "bar", "baz" }; EntityKeyMetadata keyMetadata = new DefaultEntityKeyMetadata( "Foobar", columnNames ); Object[] values = { 123, "Hello", 456L }; EntityKey key = new EntityKey( keyMetadata, values ); Tuple tuple = dialect1.createTuple( key, emptyTupleContext() ); tuple.put( "foo", "bar" ); dialect1.insertOrUpdateTuple( key, tuple, emptyTupleContext() ); MyConsumer consumer = new MyConsumer(); dialect2.forEachTuple( consumer, emptyTupleContext(), keyMetadata ); assertThat( consumer.consumedTuple.get( "foo" ) ).isEqualTo( "bar" ); }
Source:
protected final void layoutChildren() { double width = rectangle.getWidth(); double height = rectangle.getHeight(); double fontWidth = text.getLayoutBounds().getWidth(); text.setFont(Font.font("Oxygen Mono", (HORIZONTALSCALE) * width / fontWidth)); clip.setWidth(width); clip.setHeight(height); clip.setLayoutX(0); clip.setLayoutY(-height / 2); text.setLayoutX(width / 2 - text.getLayoutBounds().getWidth() / 2); text.setLayoutY(height / 2); }

Target:
protected final void layoutChildren() { double width = rectangle.getWidth(); double height = rectangle.getHeight(); double fontWidth = text.getLayoutBounds().getWidth(); text.setFont(Font.font(FONTNAME, (HORIZONTALSCALE) * width / fontWidth)); clip.setWidth(width); clip.setHeight(height); clip.setLayoutX(0); clip.setLayoutY(-height / 2); text.setLayoutX(width / 2 - text.getLayoutBounds().getWidth() / 2); text.setLayoutY(height / 2); }
Source:
public String toString() { return "version=" + VERSION + ";guid="+ guid.toString(); }

Target:
public String toString() { return serialize(this); }
Source:
public void validateColumnValue(ITableRow row, IFormField editor, boolean singleColValidation, T value) { if (row == null) { LOG.error("validateColumnValue called with row=null"); return; } if (isCellEditable(row)) { try { if (editor == null) { m_isValidating = true; editor = prepareEdit(row); if (editor instanceof IValueField<?>) { ((IValueField<T>) editor).setValue(value); } m_isValidating = false; } if (editor != null) { IProcessingStatus errorStatus = editor.getErrorStatus(); boolean editorValid = editor.isContentValid() && errorStatus == null; Cell cell = row.getCellForUpdate(this); if (!editorValid) { if (isDisplayable() && !isVisible()) { setVisible(true); } if (errorStatus != null) { cell.setErrorStatus(errorStatus); if (errorStatus instanceof ParsingFailedStatus) { cell.setText(((ParsingFailedStatus) errorStatus).getParseInputString()); } } else { cell.setErrorStatus(ScoutTexts.get("FormEmptyMandatoryFieldsMessage")); cell.setText(""); } } else { cell.clearErrorStatus(); decorateCellInternal(cell, row); ITable table = getTable(); if (table instanceof AbstractTable && singleColValidation) { ((AbstractTable) table).wasEverValid(row); } } } } catch (Throwable t) { LOG.error("validating " + getTable().getClass().getSimpleName() + " for new row for column " + getClass().getSimpleName(), t); } } }

Target:
public void validateColumnValue(ITableRow row, IFormField editor, boolean singleColValidation, T value) { if (row == null) { LOG.error("validateColumnValue called with row=null"); return; } if (isCellEditable(row)) { try { if (editor == null) { m_isValidating = true; editor = prepareEdit(row); if (editor instanceof IValueField<?>) { ((IValueField<T>) editor).setValue(value); } m_isValidating = false; } if (editor != null) { IProcessingStatus errorStatus = editor.getErrorStatus(); boolean editorValid = editor.isContentValid() && errorStatus == null; Cell cell = row.getCellForUpdate(this); if (!editorValid) { if (isDisplayable() && !isVisible()) { setVisible(true); } if (errorStatus != null) { cell.setErrorStatus(errorStatus); if (errorStatus instanceof ParsingFailedStatus) { cell.setText(((ParsingFailedStatus) errorStatus).getParseInputString()); } } else { cell.setErrorStatus(ScoutTexts.get("FormEmptyMandatoryFieldsMessage")); cell.setText(""); } } else { cell.clearErrorStatus(); cell.setValue(value); decorateCellInternal(cell, row); ITable table = getTable(); if (table instanceof AbstractTable && singleColValidation) { ((AbstractTable) table).wasEverValid(row); } } } } catch (Throwable t) { LOG.error("validating " + getTable().getClass().getSimpleName() + " for new row for column " + getClass().getSimpleName(), t); } } }
Source:
public Process exec(String command, int timeout) throws TransportException { final String ssh = SystemReader.getInstance().getenv("GIT_SSH"); final boolean putty = ssh.toLowerCase().contains("plink"); final List<String> args = new ArrayList<String>(); args.add(ssh); if (putty && !ssh.toLowerCase().contains("tortoiseplink")) args.add("-batch"); if (0 < getURI().getPort()) { args.add(putty ? "-P" : "-p"); args.add(String.valueOf(getURI().getPort())); } if (getURI().getUser() != null) args.add(getURI().getUser() + "@" + getURI().getHost()); else args.add(getURI().getHost()); args.add(command); final ProcessBuilder pb = new ProcessBuilder(); pb.command(args); if (local.getDirectory() != null) pb.environment().put(Constants.GIT_DIR_KEY, local.getDirectory().getPath()); try { return pb.start(); } catch (final IOException err) { throw new TransportException(err.getMessage(), err); } }

Target:
public Process exec(String command, int timeout) throws TransportException { String ssh = SystemReader.getInstance().getenv("GIT_SSH"); boolean putty = ssh.toLowerCase().contains("plink"); List<String> args = new ArrayList<String>(); args.add(ssh); if (putty && !ssh.toLowerCase().contains("tortoiseplink")) args.add("-batch"); if (0 < getURI().getPort()) { args.add(putty ? "-P" : "-p"); args.add(String.valueOf(getURI().getPort())); } if (getURI().getUser() != null) args.add(getURI().getUser() + "@" + getURI().getHost()); else args.add(getURI().getHost()); args.add(command); ProcessBuilder pb = new ProcessBuilder(); pb.command(args); if (local.getDirectory() != null) pb.environment().put(Constants.GIT_DIR_KEY, local.getDirectory().getPath()); try { return pb.start(); } catch (IOException err) { throw new TransportException(err.getMessage(), err); } }
Source:
protected long computeNext(long last) { long current = clock.currentTimeMicros(); return last >= current ? last + 1 : current; }

Target:
protected long computeNext(long last) { long currentTick = clock.currentTimeMicros(); if (last >= currentTick) { onDrift(currentTick, last); return last + 1; } return currentTick; }
Source:
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { int page = 0; boolean force = false; if (args.length > 0) { try { page = Integer.parseInt(args[0]); } catch (NumberFormatException ex) { if (args[0].equalsIgnoreCase("force") && ess.getUser(sender.getSender()).isAuthorized("essentials.balancetop.force")) { force = true; } } } if (!force && lock.readLock().tryLock()) { try { if (cacheage > System.currentTimeMillis() - CACHETIME) { outputCache(sender, page); return; } if (ess.getUserMap().getUniqueUsers() > MINUSERS) { sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); } } finally { lock.readLock().unlock(); } ess.runTaskAsynchronously(new Viewer(sender, page, force)); } else { if (ess.getUserMap().getUniqueUsers() > MINUSERS) { sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); } ess.runTaskAsynchronously(new Viewer(sender, page, force)); } }

Target:
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { int page = 0; boolean force = false; if (args.length > 0) { try { page = Integer.parseInt(args[0]); } catch (NumberFormatException ex) { if (args[0].equalsIgnoreCase("force")){ if (!(sender.getSender() instanceof Player)){ force = true; } else { Player player = (Player) sender.getSender(); if (ess.getUser(player).isAuthorized("essentials.balancetop.force")){ force = true; } else { sender.sendMessage(_("noAccessCommand")); return; } } } } } if (!force && lock.readLock().tryLock()) { try { if (cacheage > System.currentTimeMillis() - CACHETIME) { outputCache(sender, page); return; } if (ess.getUserMap().getUniqueUsers() > MINUSERS) { sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); } } finally { lock.readLock().unlock(); } ess.runTaskAsynchronously(new Viewer(sender, page, force)); } else { if (ess.getUserMap().getUniqueUsers() > MINUSERS) { sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); } ess.runTaskAsynchronously(new Viewer(sender, page, force)); } }