auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldNotSetRemovalTime_HistoricProcessInstancePermissionsDisabled() { testRule.getProcessEngineConfiguration() .setEnableHistoricInstancePermissions(false); String processInstanceId = testRule.process().call().userTask().deploy().start(); Authorization authorization = authorizationService.createNewAuthorization(Authorization.AUTH_TYPE_GRANT); authorization.setResource(Resources.HISTORIC_PROCESS_INSTANCE); authorization.setResourceId(processInstanceId); authorization.setUserId("foo"); authorizationService.saveAuthorization(authorization); testRule.updateHistoryTimeToLive("rootProcess", 5); HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery().rootProcessInstances(); testRule.syncExec( historyService.setRemovalTimeToHistoricProcessInstances() .calculatedRemovalTime() .byQuery(query) .hierarchical() .executeAsync() ); authorization = authorizationService.createAuthorizationQuery() .resourceType(Resources.HISTORIC_PROCESS_INSTANCE) .singleResult(); assertThat(authorization.getRemovalTime()).isNull(); <START> testRule.clearAuthorization(); <END> }</code><technical_language>@After method clears authorizations if assert statement fails</technical_language>

Target:
public void shouldNotSetRemovalTime_HistoricProcessInstancePermissionsDisabled() { testRule.getProcessEngineConfiguration() .setEnableHistoricInstancePermissions(false); String processInstanceId = testRule.process().call().userTask().deploy().start(); Authorization authorization = authorizationService.createNewAuthorization(Authorization.AUTH_TYPE_GRANT); authorization.setResource(Resources.HISTORIC_PROCESS_INSTANCE); authorization.setResourceId(processInstanceId); authorization.setUserId("foo"); authorizationService.saveAuthorization(authorization); testRule.updateHistoryTimeToLive("rootProcess", 5); HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery().rootProcessInstances(); testRule.syncExec( historyService.setRemovalTimeToHistoricProcessInstances() .calculatedRemovalTime() .byQuery(query) .hierarchical() .executeAsync() ); authorization = authorizationService.createAuthorizationQuery() .resourceType(Resources.HISTORIC_PROCESS_INSTANCE) .singleResult(); assertThat(authorization.getRemovalTime()).isNull(); }
Source:
<code>private boolean isNetworkStack(long accountId, long instanceId) { Instance instance = objectManager.findAny(Instance.class, INSTANCE.ID, instanceId); <START> List<? extends Service> services = instanceDao.findServicesFor(instance); <END> if(services.size() > 0) { List<Service> network_services = objectManager.find(Service.class, SERVICE.ACCOUNT_ID, accountId, SERVICE.REMOVED, null, SERVICE.STACK_ID, services.get(0).getStackId(), SERVICE.KIND, ServiceConstants.KIND_NETWORK_DRIVER_SERVICE); if(network_services.size() > 0) { return true; } } return false; }</code><technical_language>if change this method in instanceDao accept instanceid (I bet instanceid is get in db query anyway). This load instance line 132</technical_language>

Target:
private boolean isNetworkStack(long accountId, long instanceId) { List<? extends Service> services = instanceDao.findServicesForInstanceId(instanceId); if(services.size() > 0) { if(services.get(0).getKind().equals(ServiceConstants.KIND_NETWORK_DRIVER_SERVICE)) { return true; } List<Service> network_services = objectManager.find(Service.class, SERVICE.ACCOUNT_ID, accountId, SERVICE.REMOVED, null, SERVICE.STACK_ID, services.get(0).getStackId(), SERVICE.KIND, ServiceConstants.KIND_NETWORK_DRIVER_SERVICE); if(network_services.size() > 0) { return true; } } return false; }
Source:
<code>public void validateDatastreamsUpdate(List<Datastream> datastreams) throws DatastreamValidationException { <START> _log.info("About to validate datastremas update: " + datastreams); <END> try { List<String> connectorTypes = datastreams.stream().map(Datastream::getConnectorName).distinct().collect(Collectors.toList()); if (connectorTypes.size() != 1) { throw new DatastreamValidationException( "Expecting exactly one type of connectors for datastreams update: " + connectorTypes); } String connectorName = connectorTypes.get(0); ConnectorInfo connectorInfo = _connectors.get(connectorName); if (connectorInfo == null) { throw new DatastreamValidationException("Invalid connector: " + connectorName); } connectorInfo.getConnector() .validateUpdateDatastreams(datastreams, _datastreamCache.getAllDatastreams() .stream() .filter(d -> d.getConnectorName().equals(connectorName)) .collect(Collectors.toList())); } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(MODULE, "validateDatastreamsUpdate", NUM_ERRORS, 1); throw e; } }</code><technical_language>nit: _log.info("About validate datastremas update: ", datastreams);</technical_language>

Target:
public void validateDatastreamsUpdate(List<Datastream> datastreams) throws DatastreamValidationException { _log.info("About to validate datastreams update: " + datastreams); try { List<String> connectorTypes = datastreams.stream().map(Datastream::getConnectorName).distinct().collect(Collectors.toList()); if (connectorTypes.size() != 1) { throw new DatastreamValidationException( "Expecting exactly one type of connectors for datastreams update: " + connectorTypes); } String connectorName = connectorTypes.get(0); ConnectorInfo connectorInfo = _connectors.get(connectorName); if (connectorInfo == null) { throw new DatastreamValidationException("Invalid connector: " + connectorName); } connectorInfo.getConnector() .validateUpdateDatastreams(datastreams, _datastreamCache.getAllDatastreams() .stream() .filter(d -> d.getConnectorName().equals(connectorName)) .collect(Collectors.toList())); } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(MODULE, "validateDatastreamsUpdate", NUM_ERRORS, 1); throw e; } }
Source:
<code>private void registerLeaderElectionService(TimeLockServerConfiguration configuration) { remoteServers = getRemoteServerPaths(configuration); LeaderConfig leaderConfig = getLeaderConfig(configuration); Set<String> paxosSubresourceUris = PaxosTimeLockUriUtils.getLeaderPaxosUris(remoteServers); Leaders.LocalPaxosServices localPaxosServices = Leaders.createInstrumentedLocalServices( leaderConfig, ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteServers) .remoteAcceptorUris(paxosSubresourceUris) .remoteLearnerUris(paxosSubresourceUris) .build(), <START> "paxos-leader-election-service"); <END> leaderElectionService = localPaxosServices.leaderElectionService(); environment.jersey().register(localPaxosServices.pingableLeader()); environment.jersey().register(new LeadershipResource( localPaxosServices.ourAcceptor(), localPaxosServices.ourLearner())); }</code><technical_language>UserAgents.fromClass(getClass()) for userAgent include version</technical_language>

Target:
private void registerLeaderElectionService(TimeLockServerConfiguration configuration) { remoteServers = getRemoteServerPaths(configuration); LeaderConfig leaderConfig = getLeaderConfig(configuration); Set<String> paxosSubresourceUris = PaxosTimeLockUriUtils.getLeaderPaxosUris(remoteServers); Leaders.LocalPaxosServices localPaxosServices = Leaders.createInstrumentedLocalServices( leaderConfig, ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteServers) .remoteAcceptorUris(paxosSubresourceUris) .remoteLearnerUris(paxosSubresourceUris) .build(), "leader-election-service"); leaderElectionService = localPaxosServices.leaderElectionService(); environment.jersey().register(localPaxosServices.pingableLeader()); environment.jersey().register(new LeadershipResource( localPaxosServices.ourAcceptor(), localPaxosServices.ourLearner())); }
Source:
<code>private CollectionStream(String systemName, String streamName, Integer partitionCount) { this.streamName = streamName; this.streamConfig = new HashMap<>(); this.partitions = new HashMap<>(); this.systemName = systemName; <START> streamConfig.put(String.format(STREAM_TO_SYSTEM, this.streamName), systemName); <END> for (int i = 0; i < partitionCount; i++) { partitions.put(i, new ArrayList<>()); } }</code><technical_language>Consider constructors delegate other. For example, this line is repeated in of constructors</technical_language>

Target:
private CollectionStream(String systemName, String streamName, Integer partitionCount) { this(systemName, streamName); Preconditions.checkState(partitionCount > 0); initPartitions = new HashMap<>(); for (int i = 0; i < partitionCount; i++) { initPartitions.put(i, new ArrayList<>()); } }
Source:
<code><START> protected IDialogSettings <END> getDialogBoundsSettings() { IDialogSettings settings = DebugUIPlugin.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(SETTINGS_ID); if (section == null) { section = settings.addNewSection(SETTINGS_ID); } return section; }</code><technical_language>Do want this protected</technical_language>

Target:
private IDialogSettings getDialogBoundsSettings() { IDialogSettings settings = DebugUIPlugin.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(SETTINGS_ID); if (section == null) { section = settings.addNewSection(SETTINGS_ID); } return section; }
Source:
<code>public @ResponseBody JSONObj get(@PathVariable String wsName, @PathVariable Long id) throws Exception { ImportContext imp = findImport(id); JSONObj result = new JSONObj(); result.put("id", imp.getId()); JSONArr preimport = result.putArray("preimport"); JSONArr imported = result.putArray("imported"); JSONArr pending = result.putArray("pending"); JSONArr failed = result.putArray("failed"); JSONArr ignored = result.putArray("ignored"); for (ImportTask task : imp.getTasks()) { if (imp.getState() == ImportContext.State.PENDING) { preimport.add(task(task)); } else { <START> if (task.getState() == ImportTask.State.COMPLETE) { <END> imported.add(complete(task)); } else { switch(task.getState()) { case NO_BOUNDS: case NO_CRS: pending.add(pending(task)); break; case ERROR: failed.add(failed(task)); break; default: ignored.add(ignored(task)); } } } } return result; }</code><technical_language>This a single switch statement</technical_language>

Target:
public @ResponseBody JSONObj get(@PathVariable String wsName, @PathVariable Long id) throws Exception { ImportContext imp = findImport(id); JSONObj result = new JSONObj(); result.put("id", imp.getId()); JSONArr preimport = result.putArray("preimport"); JSONArr imported = result.putArray("imported"); JSONArr pending = result.putArray("pending"); JSONArr failed = result.putArray("failed"); JSONArr ignored = result.putArray("ignored"); for (ImportTask task : imp.getTasks()) { if (imp.getState() == ImportContext.State.PENDING) { preimport.add(task(task)); } else { switch(task.getState()) { case COMPLETE: imported.add(complete(task)); break; case NO_BOUNDS: case NO_CRS: pending.add(pending(task)); break; case ERROR: failed.add(failed(task)); break; default: ignored.add(ignored(task)); } } } return result; }
Source:
<code>default void checkCanSelectFromTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName) { <START> denySelectTable(tableName.toString()); <END> }</code><technical_language>This delegate checkCanSelectFromColumns. subclasses delete implementations of deprecated methods implementing column level checks</technical_language>

Target:
default void checkCanSelectFromTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName) { checkCanSelectFromColumns(transactionHandle, identity, tableName, emptySet()); }
Source:
<code>SignatureSignerContext signer() throws SignatureException; SignatureVerifierContext verifier(String kid) throws VerificationException; <START> SignatureVerifierContext verifier(ClientModel client, JWSInput input) throws VerificationException; <END> @Override default void close() { }</code><technical_language>Verifying signatures for clients added SignatureProvider. Instead a new ClientSignatureVerifierProvider introduced. This enable listing supported algorithms properly hard-coding lists</technical_language>

Target:
SignatureSignerContext signer() throws SignatureException; SignatureVerifierContext verifier(String kid) throws VerificationException; @Override default void close() { }
Source:
<code><START> public JavaTypeDefinition getVarargComponentType() { <END> return argTypes.get(argTypes.size() - 1).getComponentType(); }</code><technical_language>this needs a companion method isVararg() throw if vararg</technical_language>

Target:
public JavaTypeDefinition getVarargComponentType() { if (!isVararg()) { throw new IllegalStateException("Method is not vararg: " + method.toString() + "!"); } return argTypes.get(argTypes.size() - 1).getComponentType(); }
Source:
<code>public void configure(Job job) throws IOException { final Configuration conf = job.getConfiguration(); final Kiji kiji = mTable.getKiji(); conf.set( KijiConfKeys.OUTPUT_KIJI_TABLE_URI, String.format("kiji://%s:%s/%s/%s", conf.get(HConstants.ZOOKEEPER_QUORUM), conf.getInt(HConstants.ZOOKEEPER_CLIENT_PORT, HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT), kiji.getName(), mTable.getName())); job.setOutputFormatClass(NullOutputFormat.class); <START> conf.set(KijiConfKeys.KIJI_TABLE_CONTEXT_CLASS, DirectKijiTableWriterContext.class.getName()); <END> job.setNumReduceTasks(mNumReduceTasks); conf.setBoolean("mapred.map.tasks.speculative.execution", false); }</code><technical_language>Configuration#setClass(...) here</technical_language>

Target:
public void configure(Job job) throws IOException { final Configuration conf = job.getConfiguration(); final Kiji kiji = mTable.getKiji(); conf.set( KijiConfKeys.OUTPUT_KIJI_TABLE_URI, String.format("kiji://%s:%s/%s/%s", conf.get(HConstants.ZOOKEEPER_QUORUM), conf.getInt(HConstants.ZOOKEEPER_CLIENT_PORT, HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT), kiji.getName(), mTable.getName())); job.setOutputFormatClass(NullOutputFormat.class); conf.setClass( KijiConfKeys.KIJI_TABLE_CONTEXT_CLASS, DirectKijiTableWriterContext.class, KijiTableContext.class); job.setNumReduceTasks(mNumReduceTasks); conf.setBoolean("mapred.map.tasks.speculative.execution", false); }
Source:
<code>private static int getUnsignedIntValue(String bits){ int value = 0; int i = 0; for (int j = bits.length() - 1; j >= 0; j--, i++) { if (bits.charAt(j) == '1') { <START> value += (int) Math.pow(2.0, (double) i); <END> } } return value; }</code><technical_language>shift operators here. Instead of java += (int) Math.pow(2.0, (double) i); java += 1 << i; left-shift operator is equivalent 2 n-th power (2 ^ i == 1 << i), advantage of requiring conversions floating-point back, avoids expensive operations happen Math.pow. left-shift operator is a single assembly instruction :)</technical_language>

Target:
private static int getUnsignedIntValue(String bits){ int value = 0; int i = 0; for (int j = bits.length() - 1; j >= 0; j--, i++) { if (bits.charAt(j) == '1') { value += 1 << i; } } return value; }
Source:
<code>public void checkWebJavaPetclinicProjectCommands() { projectExplorer.openItemByPath(WEB_JAVA_PETCLINIC); consoles.executeCommandFromProcessesArea( "db", COMMON_GOAL, "show databases", "information_schema"); consoles.executeCommandFromProcessesArea( <START> "dev-machine", COMMON_GOAL, BUILD_COMMAND, BUILD_SUCCESS); <END> consoles.executeCommandFromProcessesArea( "dev-machine", BUILD_GOAL, BUILD_COMMAND_ITEM.getItem(WEB_JAVA_PETCLINIC), BUILD_SUCCESS); consoles.executeCommandFromProcessesArea( "dev-machine", RUN_GOAL, BUILD_AND_DEPLOY_COMMAND_ITEM.getItem(WEB_JAVA_PETCLINIC), "Server startup in"); consoles.checkWebElementVisibilityAtPreviewPage(By.xpath(" projectExplorer.invokeCommandWithContextMenu( RUN_GOAL, WEB_JAVA_PETCLINIC, STOP_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_PETCLINIC), "dev-machine"); consoles.selectProcessInProcessConsoleTreeByName("Terminal"); terminal.typeIntoTerminal("ps ax"); terminal.typeIntoTerminal(ENTER.toString()); terminal.waitExpectedTextNotPresentTerminal("$TOMCAT_HOME/bin/catalina.sh"); consoles.executeCommandFromProcessesArea( "dev-machine", DEBUG_GOAL, DEBUG_COMMAND_ITEM.getItem(WEB_JAVA_PETCLINIC), LISTENING_AT_ADDRESS_8000); }</code><technical_language>Defining "dev-machine" string a constant code clear, IMHO, allow avoid duplication</technical_language>

Target:
public void checkWebJavaPetclinicProjectCommands() { By textOnPreviewPage = By.xpath(" String tomcatIsRunning = "$TOMCAT_HOME/bin/catalina.sh"; projectExplorer.openItemByPath(WEB_JAVA_PROJECT); consoles.executeCommandFromProcessesArea( DB_MACHINE_NAME, COMMON_GOAL, "show databases", "information_schema"); consoles.executeCommandFromProcessesArea( DEV_MACHINE_NAME, COMMON_GOAL, BUILD_COMMAND, BUILD_SUCCESS); consoles.executeCommandFromProcessesArea( DEV_MACHINE_NAME, BUILD_GOAL, BUILD_COMMAND_ITEM.getItem(WEB_JAVA_PROJECT), BUILD_SUCCESS); consoles.executeCommandFromProcessesArea( DEV_MACHINE_NAME, RUN_GOAL, BUILD_AND_DEPLOY_COMMAND_ITEM.getItem(WEB_JAVA_PROJECT), "Server startup in"); consoles.checkWebElementVisibilityAtPreviewPage(textOnPreviewPage); projectExplorer.invokeCommandWithContextMenu( RUN_GOAL, WEB_JAVA_PROJECT, STOP_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_PROJECT), DEV_MACHINE_NAME); consoles.selectProcessInProcessConsoleTreeByName("Terminal"); terminal.typeIntoTerminal("ps ax"); terminal.typeIntoTerminal(ENTER.toString()); terminal.waitExpectedTextNotPresentTerminal(tomcatIsRunning); consoles.executeCommandFromProcessesArea( DEV_MACHINE_NAME, DEBUG_GOAL, DEBUG_COMMAND_ITEM.getItem(WEB_JAVA_PROJECT), LISTENING_AT_ADDRESS_8000); }
Source:
<code>public void processOnVmStop(Collection<Guid> vmIds) { for (final Guid vmId : vmIds) { <START> log.infoFormat("process VM {0} that went down", vmId); <END> ThreadPoolUtil.execute(new Runnable() { @Override public void run() { Backend.getInstance().runInternalAction(VdcActionType.ProcessDownVm, new IdParameters(vmId), ExecutionHandler.createInternalJobContext()); } }); } }</code><technical_language>do need this log? is a command a log for running a command, no</technical_language>

Target:
public void processOnVmStop(Collection<Guid> vmIds) { for (final Guid vmId : vmIds) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { Backend.getInstance().runInternalAction(VdcActionType.ProcessDownVm, new IdParameters(vmId)); } }); } }
Source:
<code>private void handleEvent(SiteNode parent, SiteNode node, EventType eventType) { switch (eventType) { case ADD: publishEvent(SiteMapEventPublisher.SITE_NODE_ADDED_EVENT, node); if (parent == getRoot()) { publishEvent(SiteMapEventPublisher.SITE_ADDED_EVENT, node); } break; case REMOVE: publishEvent(SiteMapEventPublisher.SITE_NODE_REMOVED_EVENT, node); if(parent == getRoot()) { publishEvent(SiteMapEventPublisher.SITE_REMOVED_EVENT, node); <START> System.out.println("Site - Remove"); <END> } } }</code><technical_language>This statement removed</technical_language>

Target:
private void handleEvent(SiteNode parent, SiteNode node, EventType eventType) { switch (eventType) { case ADD: publishEvent(SiteMapEventPublisher.SITE_NODE_ADDED_EVENT, node); if (parent == getRoot()) { publishEvent(SiteMapEventPublisher.SITE_ADDED_EVENT, node); } break; case REMOVE: publishEvent(SiteMapEventPublisher.SITE_NODE_REMOVED_EVENT, node); if(parent == getRoot()) { publishEvent(SiteMapEventPublisher.SITE_REMOVED_EVENT, node); } } }
Source:
<code>public static DumpWriter makePredicateDumpWriter(final DumpWriter successorWriter, final PredicatePageFilter filter) { return new ChainingDumpWriter(successorWriter) { boolean showThisPage = true; public void writeStartPage(Page page) throws IOException { showThisPage = filter.test(page); <START> if (showThisPage) <END> writer.writeStartPage(page); } public void writeEndPage() throws IOException { if (showThisPage) writer.writeEndPage(); } public void writeRevision(Revision revision) throws IOException { if (showThisPage) writer.writeRevision(revision); } }; }</code><technical_language>nitpick: if new a big fan of ifs curly</technical_language>

Target:
public static DumpWriter makePredicateDumpWriter(final DumpWriter successorWriter, final PredicatePageFilter filter) { return new ChainingDumpWriter(successorWriter) { boolean showThisPage = true; public void writeStartPage(Page page) throws IOException { showThisPage = filter.test(page); if (showThisPage) { writer.writeStartPage(page); } } public void writeEndPage() throws IOException { if (showThisPage) { writer.writeEndPage(); } } public void writeRevision(Revision revision) throws IOException { if (showThisPage) { writer.writeRevision(revision); } } }; }
Source:
<code>public MeasureSpecRenderer() { super("Android <START> MeasureSpec.toString"); <END> }</code><technical_language>need for .toString, "Android MeasureSpec" is enough I think. (also update commit message)</technical_language>

Target:
public MeasureSpecRenderer() { super("Android MeasureSpec"); }
Source:
<code>public void activate(ComponentContext context) { typeRegistry = new TypeRegistry(); <START> recomputeCallback = () -> typeRegistry.recomputeTypes(); <END> SchemaManagerImpl schemaManager = (SchemaManagerImpl)Framework.getService(SchemaManager.class); schemaManager.registerRecomputeCallback(recomputeCallback); }</code><technical_language>simply recomputeCallback = typeRegistry::recomputeTypes</technical_language>

Target:
public void activate(ComponentContext context) { typeRegistry = new TypeRegistry(); recomputeCallback = typeRegistry::recomputeTypes; SchemaManagerImpl schemaManager = (SchemaManagerImpl) Framework.getService(SchemaManager.class); schemaManager.registerRecomputeCallback(recomputeCallback); }
Source:
<code>public ActionResult execute() { String blobKey = getNonNullRequestParamValue(Const.ParamsNames.BLOB_KEY); <START> log.info("blob-key given: " + blobKey); <END> return new ImageResult(blobKey); }</code><technical_language>this done before, this is helpful. remove it</technical_language>

Target:
public ActionResult execute() { String blobKey = getNonNullRequestParamValue(Const.ParamsNames.BLOB_KEY); return new ImageResult(blobKey); }
Source:
<code>private void updateData(@NonNull TimeQueryFilter filters, IProgressMonitor monitor) { try (FlowScopeLog scope = new FlowScopeLogBuilder(LOGGER, Level.FINE, "CommonXLineChart:updateData", "numRequests=", fNumRequests).setParentScope(fScope).build()) { ITmfXYDataProvider dataProvider = fXYDataProvider[0]; if (dataProvider == null) { TraceCompassLogUtils.traceInstant(LOGGER, Level.WARNING, "Data provider for this viewer is not available"); return; } boolean isComplete = false; do { <START> try (FlowScopeLog scopeDp = new FlowScopeLogBuilder(LOGGER, Level.FINE, dataProvider.getClass().getName() + ":fetchXY").setParentScope(fScope).build()) { END> TmfModelResponse<ITmfCommonXAxisModel> response = dataProvider.fetchXY(filters, monitor); ITmfCommonXAxisModel model = response.getModel(); if (model != null) { updateDisplay(model, monitor); } ITmfResponse.Status status = response.getStatus(); if (status == ITmfResponse.Status.COMPLETED) { isComplete = true; } else if (status == ITmfResponse.Status.FAILED || status == ITmfResponse.Status.CANCELLED) { TraceCompassLogUtils.traceInstant(LOGGER, Level.WARNING, response.getStatusMessage()); isComplete = true; } else { try { Thread.sleep(BUILD_UPDATE_TIMEOUT); } catch (InterruptedException e) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, e.getMessage()); } } } } while (!isComplete); } }</code><technical_language>Asking blocking... this a scope a step</technical_language>

Target:
private void updateData(@NonNull TimeQueryFilter filters, IProgressMonitor monitor) { try (FlowScopeLog scope = new FlowScopeLogBuilder(LOGGER, Level.FINE, "CommonXLineChart:updateData", "numRequests=", fNumRequests).setParentScope(fScope).build()) { ITmfXYDataProvider dataProvider = fXYDataProvider[0]; if (dataProvider == null) { TraceCompassLogUtils.traceInstant(LOGGER, Level.WARNING, "Data provider for this viewer is not available"); return; } boolean isComplete = false; do { try (FlowScopeLog scopeDp = new FlowScopeLogBuilder(LOGGER, Level.FINER, dataProvider.getClass().getName() + ":fetchXY").setParentScope(fScope).build()) { TmfModelResponse<ITmfCommonXAxisModel> response = dataProvider.fetchXY(filters, monitor); ITmfCommonXAxisModel model = response.getModel(); if (model != null) { updateDisplay(model, monitor); } ITmfResponse.Status status = response.getStatus(); if (status == ITmfResponse.Status.COMPLETED) { isComplete = true; } else if (status == ITmfResponse.Status.FAILED || status == ITmfResponse.Status.CANCELLED) { TraceCompassLogUtils.traceInstant(LOGGER, Level.WARNING, response.getStatusMessage()); isComplete = true; } else { try { Thread.sleep(BUILD_UPDATE_TIMEOUT); } catch (InterruptedException e) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, e.getMessage()); } } } } while (!isComplete); } }
Source:
<code>public void call(final Subscriber<? super T> subscriber) { subscriber.setProducer(new Producer() { @Override public void request(long n) { if (selection.choice.get() != null) { selection.choice.get().requestMore(n); } for (Observable<? extends T> source : sources) { if (subscriber.isUnsubscribed()) { break; } if (selection.choice.get() != null) { break; } AmbSubscriber<T> ambSubscriber = new AmbSubscriber<T>(n, subscriber, selection); <START> selection.ambSubscribers.add(ambSubscriber); <END> subscriber.add(ambSubscriber); source.unsafeSubscribe(ambSubscriber); } } }); }</code><technical_language>race condition in unsubscribeOthers L366, unsubscribeOthers, selection.ambSubscribers a AmbSubscriber. I this is OK this AmbSubscriber receives a message, call unsubscribe</technical_language>

Target:
public void call(final Subscriber<? super T> subscriber) { subscriber.add(Subscriptions.create(new Action0() { @Override public void call() { if (selection.choice.get() != null) { selection.choice.get().unsubscribe(); } if(!selection.ambSubscribers.isEmpty()) { for (AmbSubscriber<T> other : selection.ambSubscribers) { other.unsubscribe(); } selection.ambSubscribers.clear(); } } })); subscriber.setProducer(new Producer() { @Override public void request(long n) { if (selection.choice.get() != null) { selection.choice.get().requestMore(n); } else { for (Observable<? extends T> source : sources) { if (subscriber.isUnsubscribed()) { break; } AmbSubscriber<T> ambSubscriber = new AmbSubscriber<T>(n, subscriber, selection); selection.ambSubscribers.add(ambSubscriber); if (selection.choice.get() != null) { selection.unsubscribeOthers(selection.choice.get()); break; } source.unsafeSubscribe(ambSubscriber); } } } }); }
Source:
<code>public void assertChangedResources(String[] expected) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (String file : expected) <START> assertTrue(changedResources.contains(root.findMember(file))); <END> assertTrue(changedResources.size() == expected.length); }</code><technical_language>Please assertThat, a message in case of failure: assertThat(changedResources, Matchers.hasItem(root.findMember(file)));</technical_language>

Target:
public void assertChangedResources(String[] expected) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (String file : expected) assertThat(changedResources, hasItem(root.findMember(file))); assertEquals(changedResources.size(), expected.length); }
Source:
<code>public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String binaryUri = (String) in.getHeader(FCREPO_URI); <START> String mimeType = (String) in.getHeader("MimeType"); <END> final ExecResult result = (ExecResult) in.getBody(); String derivativePath = new BufferedReader(new InputStreamReader(result.getStdout())) .lines().collect(Collectors.joining("\n")); InputStream binaryStream = new FileInputStream(derivativePath + ".PNG"); BinaryObject binary = repository.getBinary(PIDs.get(binaryUri)); FileObject parent = (FileObject) binary.getParent(); parent.addDerivative(slug, binaryStream, derivativePath, mimeType, PcdmUse.ThumbnailImage); log.info("Adding derivative for from {}", binaryUri, derivativePath); }</code><technical_language>this header classes a constant. a class of header constants similar FcrepoHeaders? Also, namespace property "CdrBinaryMimeType" (CdrBinaryPath, CdrBinaryChecksum) avoid conflicts. easier clean out of headers add if needed</technical_language>

Target:
public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String binaryUri = (String) in.getHeader(FCREPO_URI); String binaryMimeType = (String) in.getHeader(CdrBinaryMimeType); final ExecResult result = (ExecResult) in.getBody(); String derivativePath = new BufferedReader(new InputStreamReader(result.getStdout())) .lines().collect(Collectors.joining("\n")); InputStream binaryStream = new FileInputStream(derivativePath + "." + fileExtension); BinaryObject binary = repository.getBinary(PIDs.get(binaryUri)); FileObject parent = (FileObject) binary.getParent(); parent.addDerivative(slug, binaryStream, derivativePath, binaryMimeType, PcdmUse.ThumbnailImage); log.info("Adding derivative for from {}", binaryUri, derivativePath); }
Source:
<code>private void startFormEntry(AndroidSessionWrapper state) throws SessionUnavailableException { if (state.getFormRecordId() == -1) { if (CommCarePreferences.isIncompleteFormsEnabled() && <START> state.getSessionStateDescriptor().getSessionDescriptor().contains(SessionFrame.STATE_DATUM_VAL)) { <END> SessionStateDescriptor existing = state.searchForDuplicates(); if (existing != null) { createAskUseOldDialog(state, existing); return; } } state.commitStub(); } else { Logger.log("form-entry", "Somehow ended up starting form entry with old state?"); } FormRecord record = state.getFormRecord(); if (platform == null && CommCareApplication._().getCurrentApp() != null) { platform = CommCareApplication._().getCommCarePlatform(); } formEntry(platform.getFormContentUri(record.getFormNamespace()), record, CommCareActivity.getTitle(this, null)); }</code><technical_language>Agreed this logic. in searchForDuplicates code, though</technical_language>

Target:
private void startFormEntry(AndroidSessionWrapper state) throws SessionUnavailableException { if (state.getFormRecordId() == -1) { if (CommCarePreferences.isIncompleteFormsEnabled()) { SessionStateDescriptor existing = state.getExistingIncompleteCaseDescriptor(); if (existing != null) { createAskUseOldDialog(state, existing); return; } } state.commitStub(); } else { Logger.log("form-entry", "Somehow ended up starting form entry with old state?"); } FormRecord record = state.getFormRecord(); if (platform == null && CommCareApplication._().getCurrentApp() != null) { platform = CommCareApplication._().getCommCarePlatform(); } formEntry(platform.getFormContentUri(record.getFormNamespace()), record, CommCareActivity.getTitle(this, null)); }
Source:
<code>public void fail_to_update_custom_rule_when_empty_name() { RuleDefinitionDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")).getDefinition(); db.rules().insert(templateRule); RuleDefinitionDto customRule = RuleTesting.newCustomRule(templateRule); db.rules().insert(customRule); dbSession.commit(); RuleUpdate update = RuleUpdate.createForCustomRule(customRule.getKey()) .setName("") .setMarkdownDescription("New desc") .setOrganization(db.getDefaultOrganization()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("The name is missing"); <START> <END> underTest.update(dbSession, update, db.getDefaultOrganization(), userSessionRule); }</code><technical_language>easier review if refactoring ExpectedException done in another commit</technical_language>

Target:
public void fail_to_update_custom_rule_when_empty_name() { RuleDefinitionDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")).getDefinition(); db.rules().insert(templateRule); RuleDefinitionDto customRule = RuleTesting.newCustomRule(templateRule); db.rules().insert(customRule); dbSession.commit(); RuleUpdate update = createForCustomRule(customRule.getKey()) .setName("") .setMarkdownDescription("New desc") .setOrganization(db.getDefaultOrganization()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("The name is missing"); underTest.update(dbSession, update, db.getDefaultOrganization(), userSessionRule); }
Source:
<code>public Integer resolve(ITmfEvent event) { if (!(event instanceof CtfTmfEvent)) { return null; } int cpu = ((CtfTmfEvent) event).getCPU(); <START> if (cpu == -1) { <END> ITmfEventField content = event.getContent(); Long fieldValue = null; if (content != null) { fieldValue = content.getFieldValue(Long.class, CPU_ID); } return fieldValue == null ? null : fieldValue.intValue(); } return cpu; }</code><technical_language>If is CPU id, returns -1? null</technical_language>

Target:
public Integer resolve(ITmfEvent event) { if (!(event instanceof CtfTmfEvent)) { return null; } int cpu = ((CtfTmfEvent) event).getCPU(); if (cpu == IEventDefinition.UNKNOWN_CPU) { ITmfEventField content = event.getContent(); Long fieldValue = null; if (content != null) { fieldValue = content.getFieldValue(Long.class, CPU_ID); } return fieldValue == null ? null : fieldValue.intValue(); } return cpu; }
Source:
<code>private static int[] orderStreamReaders(Collection<Integer> columnIndices, Map<Integer, Integer> columnToScore, Set<Integer> filterFunctionInputs) { List<Integer> sortedColumnsByFilterScore = columnToScore.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) <START> .map(entry -> entry.getKey()) <END> .collect(Collectors.toList()); int[] order = new int[columnIndices.size()]; int i = 0; for (int columnIndex : sortedColumnsByFilterScore) { if (columnIndices.contains(columnIndex)) { order[i++] = columnIndex; } } for (int columnIndex : filterFunctionInputs) { if (columnIndices.contains(columnIndex) && !sortedColumnsByFilterScore.contains(columnIndex)) { order[i++] = columnIndex; } } for (int columnIndex : columnIndices) { if (!sortedColumnsByFilterScore.contains(columnIndex) && !filterFunctionInputs.contains(columnIndex)) { order[i++] = columnIndex; } } return order; }</code><technical_language>map(Map.Entry::getKey)</technical_language>

Target:
private static int[] orderStreamReaders(Collection<Integer> columnIndices, Map<Integer, Integer> columnToScore, Set<Integer> filterFunctionInputs) { List<Integer> sortedColumnsByFilterScore = columnToScore.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .collect(toImmutableList()); int[] order = new int[columnIndices.size()]; int i = 0; for (int columnIndex : sortedColumnsByFilterScore) { if (columnIndices.contains(columnIndex)) { order[i++] = columnIndex; } } for (int columnIndex : filterFunctionInputs) { if (columnIndices.contains(columnIndex) && !sortedColumnsByFilterScore.contains(columnIndex)) { order[i++] = columnIndex; } } for (int columnIndex : columnIndices) { if (!sortedColumnsByFilterScore.contains(columnIndex) && !filterFunctionInputs.contains(columnIndex)) { order[i++] = columnIndex; } } return order; }
Source:
<code>private OptionHandler findHandler(String name) { if (options == null) { options = Maps.newHashMap(); for (OptionHandler handler : parser.options) { if (handler.option instanceof NamedOptionDef) { NamedOptionDef def = (NamedOptionDef) handler.option; if (!def.isArgument()) { options.put(def.name(), handler); for (String alias : def.aliases()) { options.put(alias, handler); } } } } <START> return options.get(name); <END> } return options.get(name); }</code><technical_language>[optional] remove this line,</technical_language>

Target:
private OptionHandler findHandler(String name) { if (options == null) { options = index(parser.options); } return options.get(name); }
Source:
<code>protected Result pushDownDereferences(Context context, N targetNode, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { PlanNode source = getOnlyElement(targetNode.getSources()); <START> ImmutableMap<VariableReferenceExpression, RowExpression> <END> dereferencesMap = expressions.inverse().entrySet().stream().collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); ProjectNode projectNode = new ProjectNode( context.getIdAllocator().getNextId(), source, Assignments.builder().putAll(identityAssignmentsAsSymbolReferences(source.getOutputVariables())).putAll(dereferencesMap).build()); return Result.ofPlanNode(targetNode.replaceChildren(ImmutableList.of(projectNode))); }</code><technical_language>ImmutableMap -> Map - formatting Map<VariableReferenceExpression, RowExpression> dereferencesMap = expressions.inverse().entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); ProjectNode projectNode = new ProjectNode( context.getIdAllocator().getNextId(), source, Assignments.builder() .putAll(identityAssignmentsAsSymbolReferences(source.getOutputVariables())) .putAll(dereferencesMap) .build());</technical_language>

Target:
protected Result pushDownDereferences(Context context, N targetNode, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { PlanNode source = getOnlyElement(targetNode.getSources()); Map<VariableReferenceExpression, RowExpression> dereferencesMap = expressions.inverse().entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); ProjectNode projectNode = new ProjectNode( context.getIdAllocator().getNextId(), source, Assignments.builder() .putAll(identityAssignmentsAsSymbolReferences(source.getOutputVariables())) .putAll(dereferencesMap) .build()); return Result.ofPlanNode(targetNode.replaceChildren(ImmutableList.of(projectNode))); }
Source:
<code>private void initReadCategory(final ReviewDb c, final SystemConfig sConfig) throws OrmException { final Transaction txn = c.beginTransaction(); final ApprovalCategory cat; final ArrayList<ApprovalCategoryValue> vals; cat = new ApprovalCategory(ApprovalCategory.READ, "Read Access"); cat.setPosition((short) -1); cat.setFunctionName(NoOpFunction.NAME); vals = new ArrayList<ApprovalCategoryValue>(); vals.add(value(cat, 2, "Upload permission")); vals.add(value(cat, 1, "Read access")); vals.add(value(cat, -1, "No access")); c.approvalCategories().insert(Collections.singleton(cat), txn); c.approvalCategoryValues().insert(vals, txn); txn.commit(); { final ProjectRight read = new ProjectRight(new ProjectRight.Key(DEFAULT_WILD_NAME, cat.getId(), sConfig.anonymousGroupId)); <START> read.setMaxValue((short) 1); <END> read.setMinValue((short) 1); c.projectRights().insert(Collections.singleton(read)); } { final ProjectRight read = new ProjectRight(new ProjectRight.Key(DEFAULT_WILD_NAME, cat.getId(), sConfig.adminGroupId)); read.setMaxValue((short) 1); read.setMinValue((short) 1); c.projectRights().insert(Collections.singleton(read)); } }</code><technical_language>This +2 right here. default a new server encourage read upload projects, encourage open source usage. :-)</technical_language>

Target:
private void initReadCategory(final ReviewDb c, final SystemConfig sConfig) throws OrmException { final Transaction txn = c.beginTransaction(); final ApprovalCategory cat; final ArrayList<ApprovalCategoryValue> vals; cat = new ApprovalCategory(ApprovalCategory.READ, "Read Access"); cat.setPosition((short) -1); cat.setFunctionName(NoOpFunction.NAME); vals = new ArrayList<ApprovalCategoryValue>(); vals.add(value(cat, 2, "Upload permission")); vals.add(value(cat, 1, "Read access")); vals.add(value(cat, -1, "No access")); c.approvalCategories().insert(Collections.singleton(cat), txn); c.approvalCategoryValues().insert(vals, txn); txn.commit(); { final ProjectRight read = new ProjectRight(new ProjectRight.Key(DEFAULT_WILD_NAME, cat.getId(), sConfig.anonymousGroupId)); read.setMaxValue((short) 2); read.setMinValue((short) 1); c.projectRights().insert(Collections.singleton(read)); } { final ProjectRight read = new ProjectRight(new ProjectRight.Key(DEFAULT_WILD_NAME, cat.getId(), sConfig.adminGroupId)); read.setMaxValue((short) 1); read.setMinValue((short) 1); c.projectRights().insert(Collections.singleton(read)); } }
Source:
<code>public final boolean evaluate(Object feature) { final Object object1 = eval(expression1, feature); final Object object2 = eval(expression2, feature); Collection<Object> collection1 = getCollection(object1); <START> Collection<Object> collection2 = getCollection(object2); <END> if (collection1 == null && collection2 == null) { return evaluateInternal(object1, object2); } Collection<Object> leftValues = collection1 instanceof Collection ? collection1 : Collections.<Object>singletonList(object1); Collection<Object> rightValues = collection2 instanceof Collection ? collection2 : Collections.<Object>singletonList(object2); int count = 0; for (Object value1 : leftValues) { for (Object value2 : rightValues) { boolean temp = evaluateInternal(value1, value2); if (temp) { count++; } switch (matchAction) { case ONE: if (count > 1) return false; break; case ALL: if (!temp) return false; break; case ANY: if (temp) return true; break; } } } switch (matchAction) { case ONE: return (count == 1); case ALL: return true; case ANY: return false; default: return false; } }</code><technical_language>I try stay this kind of logic (assuming is useful provided making methods cast). work? final Collection<Object> collection1 = expression1.evaulate( feature, Collection.class ) final Collection<Object> collection2 = expression2.evaulate( feature, Collection.class )</technical_language>

Target:
public final boolean evaluate(Object feature) { final Object object1 = eval(expression1, feature); final Object object2 = eval(expression2, feature); Collection<Object> collection1 = toCollection(object1); Collection<Object> collection2 = toCollection(object2); if (collection1 == null && collection2 == null) { return evaluateInternal(object1, object2); } Collection<Object> leftValues = collection1 instanceof Collection ? collection1 : Collections.<Object>singletonList(object1); Collection<Object> rightValues = collection2 instanceof Collection ? collection2 : Collections.<Object>singletonList(object2); int count = 0; for (Object value1 : leftValues) { for (Object value2 : rightValues) { boolean temp = evaluateInternal(value1, value2); if (temp) { count++; } switch (matchAction) { case ONE: if (count > 1) return false; break; case ALL: if (!temp) return false; break; case ANY: if (temp) return true; break; } } } switch (matchAction) { case ONE: return (count == 1); case ALL: return true; case ANY: return false; default: return false; } }
Source:
<code>private void loadProperties() { if (file != null && file.exists()) { try (InputStream in = new FileInputStream(file)) { properties.load(in); if (logger.isInfoEnabled()) { logger.info( String.format( <START> "Load registry store file %s, data: %s", file, properties <END> ) ); } } catch (IOException e) { logger.warn(e.getMessage(), e); } catch (Throwable e) { logger.warn(String.format("Failed to load registry store file %s", file), e); } } }</code><technical_language>I string concatination, info log level this called lot time string concatination performance String.format. Another place place I more of logging, if present file full path instead of file object</technical_language>

Target:
private void loadProperties() { if (file != null && file.exists()) { try (InputStream in = new FileInputStream(file)) { properties.load(in); if (logger.isInfoEnabled()) { logger.info("Load registry store file: " + file + ", data: " + properties); } } catch (IOException e) { logger.warn(e.getMessage(), e); } catch (Throwable e) { logger.warn(String.format("Failed to load registry store file %s", file), e); } } }
Source:
<code><START> public StandaloneJsPluginModule(String <END> pluginName, String fileName) { this.pluginName = pluginName; this.fileName = fileName; }</code><technical_language>package private access is acceptable class is private</technical_language>

Target:
StandaloneJsPluginModule(String pluginName, String fileName) { this.pluginName = pluginName; this.fileName = fileName; }
Source:
<code>protected void verifyRelNode(String expectedRelNodeStr, RelNode relNode) { String relNodeStr = RelOptUtil.toString(relNode); <START> System.out.println(relNodeStr); <END> relNodeStr = relNodeStr.replaceAll("\\s", ""); assertEquals(expectedRelNodeStr, relNodeStr); }</code><technical_language>Remove this line</technical_language>

Target:
protected void verifyRelNode(String expectedRelNodeStr, RelNode relNode) { String relNodeStr = RelOptUtil.toString(relNode); assertEquals(expectedRelNodeStr, relNodeStr); }
Source:
<code>private List<Serializable> getSerializableParamsOrFail(String nodeSourceName, Object[] params) { List<Serializable> serializableParams = null; if (params != null) { Object currentParam = null; try { serializableParams = new ArrayList<>(params.length); for (int i = 0; i < params.length; i++) { currentParam = params[i]; serializableParams.add(i, (Serializable) currentParam); } } catch (ClassCastException e) { throw new IllegalArgumentException("Parameter " + currentParam + " of defined node source " + <START> nodeSourceName + " is not Serializable"); <END> } } return serializableParams; }</code><technical_language>chain original exception</technical_language>

Target:
private List<Serializable> getSerializableParamsOrFail(String nodeSourceName, Object[] params) { List<Serializable> serializableParams = null; if (params != null) { Object currentParam = null; try { serializableParams = new ArrayList<>(params.length); for (int i = 0; i < params.length; i++) { currentParam = params[i]; serializableParams.add(i, (Serializable) currentParam); } } catch (ClassCastException e) { throw new IllegalArgumentException("Parameter " + currentParam + " of defined node source " + nodeSourceName + " is not Serializable", e); } } return serializableParams; }
Source:
<code>private String createActivatedEmailText(User user, String appName) { String firstName = user.getFirstName(); String lastName = user.getLastName(); if (firstName == null || firstName.isEmpty()) firstName = user.getUsername(); if (lastName == null || lastName.isEmpty()) lastName = null; StringBuilder builder = new StringBuilder(); builder.append("Dear "); builder.append(firstName); if (lastName != null) { builder.append(" "); builder.append(lastName); } builder.append(",\n\n"); builder.append("Your registration request for "); builder.append(appName); builder.append(" was approved.\n"); builder.append("Your account is now active.\n\n"); builder.append("Kind regards,\n\n"); <START> builder.append("MOLGENIS support"); <END> return builder.toString(); }</code><technical_language>"MOLGENIS support" a bit strange for party's hosting a molgenis instance..</technical_language>

Target:
private String createActivatedEmailText(User user, String appName) { String firstName = user.getFirstName(); String lastName = user.getLastName(); if (firstName == null || firstName.isEmpty()) firstName = user.getUsername(); if (lastName == null || lastName.isEmpty()) lastName = null; StringBuilder builder = new StringBuilder(); builder.append("Dear "); builder.append(firstName); if (lastName != null) { builder.append(" "); builder.append(lastName); } builder.append(",\n\n"); builder.append("Your registration request for "); builder.append(appName); builder.append(" was approved.\n"); builder.append("Your account is now active.\n\n"); builder.append("Kind regards,\n\n"); builder.append("Server administrator"); return builder.toString(); }