auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public TestResult run(@Context UriInfo uriInfo) throws Exception { <START> Map<String, String> queryParameters = getMap(uriInfo.getQueryParameters()); <END> String projectPath = queryParameters.get("projectPath"); String absoluteProjectPath = ResourcesPlugin.getPathToWorkspace() + projectPath; queryParameters.put("absoluteProjectPath", absoluteProjectPath); System.out.println(projectManager); System.out.println(absoluteProjectPath); System.out.println(projectPath); String projectType = ""; if (projectManager != null) { projectType = projectManager.getProject(projectPath).getType(); System.out.println(projectType); } String testFramework = queryParameters.get("testFramework"); System.out.println(queryParameters.toString()); TestRunner runner = frameworkRegistry.getTestRunner(testFramework); if (runner == null) { throw new Exception("No test frameworks found: " + testFramework); } System.out.println(runner); TestResult result = frameworkRegistry.getTestRunner(testFramework).execute(queryParameters, classpathRegistry.getTestClasspathProvider(projectType)); System.out.println(result); return result; }</code><technical_language>Please declare query parameters explicitly</technical_language>

Target:
public TestResult run(@Context UriInfo uriInfo) throws Exception { Map<String, String> queryParameters = getMap(uriInfo.getQueryParameters()); String projectPath = queryParameters.get("projectPath"); String absoluteProjectPath = ResourcesPlugin.getPathToWorkspace() + projectPath; queryParameters.put("absoluteProjectPath", absoluteProjectPath); String projectType = ""; if (projectManager != null) { projectType = projectManager.getProject(projectPath).getType(); } String testFramework = queryParameters.get("testFramework"); TestRunner runner = frameworkRegistry.getTestRunner(testFramework); if (runner == null) { throw new Exception("No test frameworks found: " + testFramework); } TestResult result = frameworkRegistry.getTestRunner(testFramework).execute(queryParameters, classpathRegistry.getTestClasspathProvider(projectType)); return result; }
Source:
<code>private String getVariableLabel(VariableMetadata variableMetadata) { if (variableMetadata.getName().startsWith(CASE_VARIABLE_PREFIX)) { return translationService.getValue(CASE_VARIABLE_LABEL_PREFIX) + " " + <START> variableMetadata.getName().substring(CASE_VARIABLE_PREFIX.length(), variableMetadata.getName().length()); <END> } else { return variableMetadata.getName(); } }</code><technical_language>variableMetadata.getName().length() invocation is redundant</technical_language>

Target:
private String getVariableLabel(VariableMetadata variableMetadata) { if (variableMetadata.getName().startsWith(CASE_VARIABLE_PREFIX)) { return translationService.getValue(CASE_VARIABLE_LABEL_PREFIX) + " " + variableMetadata.getName().substring(CASE_VARIABLE_PREFIX.length()); } else { return variableMetadata.getName(); } }
Source:
<code>protected void executeCommand() { if <START> (isOperationAllowed()) <END> { List<Cluster> clusters = getClustersWithOvsSwitchType(getNetwork().getId()); checkValidDefaultProvider(clusters); List<Cluster> clustersWithOVS = getClustersWithValidDefaultProvider(clusters); createListOfClustersByProvider(clustersWithOVS); List<Guid> providerIds = new ArrayList<>(listOfClustersByProvider.keySet()); IntStream.range(0, providerIds.size()) .forEach(i -> runAutodefineForOneProvider(providerIds.get(i), i)); } setSucceeded(true); }</code><technical_language>I move decision if command triggered initiator in this command a validation</technical_language>

Target:
protected void executeCommand() { List<Cluster> clusters = getClustersWithOvsSwitchType(getNetwork().getId()); checkValidDefaultProvider(clusters); List<Cluster> clustersWithOVS = getClustersWithValidDefaultProvider(clusters); createListOfClustersByProvider(clustersWithOVS); List<Guid> providerIds = new ArrayList<>(listOfClustersByProvider.keySet()); IntStream.range(0, providerIds.size()) .forEach(i -> runAutodefineForOneProvider(providerIds.get(i), i)); setSucceeded(true); }
Source:
<code>protected void runCommand(Runnable runnable) { while (true) { try { runnable.run(); break; } catch (CacheException e) { Throwable innerThrowable = e; do { <START> if (innerThrowable instanceof SuspectException) { <END> log.trace("Ignoring suspect exception and retrying operation for ClusterRegistry."); continue; } } while ((innerThrowable = innerThrowable.getCause()) != null); throw e; } } }</code><technical_language>I this is wrong solve this: a SuspectException handled swallowed transport code. If we, and, worse, users, defensively code SuspectExceptions is a usability problem</technical_language>

Target:
protected void runCommand(Runnable runnable) { while (true) { try { runnable.run(); break; } catch (CacheException e) { if (SuspectException.isSuspectExceptionInChain(e)) { log.trace("Ignoring suspect exception and retrying operation for ClusterRegistry."); } else { throw e; } } } }
Source:
<code>protected Map<String, GroupInfo> createGroupInfos() { if(!CONNECT_TIME_SAVED) { return Collections.emptyMap(); } HashMap<String, GroupInfo> groupInfos = new HashMap<>(); <START> groupInfos.put("aggregate_rpt_pct2", END> createPercentileGroupInfo("aggregate_rpt_pct2", 95, String.format( PERCENTILE_FORMAT, Integer.valueOf(95)))); return groupInfos; }</code><technical_language>define a constant</technical_language>

Target:
protected Map<String, GroupInfo> createGroupInfos() { if(!CONNECT_TIME_SAVED) { return Collections.emptyMap(); } ConnectTimeValueSelector valueSelector = new ConnectTimeValueSelector(false); NameSeriesSelector seriesSelector = new NameSeriesSelector(); HashMap<String, GroupInfo> groupInfos = new HashMap<>(); groupInfos.put(PERCENTILE_PROPERTY, createPercentileGroupInfo(PERCENTILE_PROPERTY, 95, String.format( PERCENTILE_FORMAT, Integer.valueOf(95)),valueSelector,seriesSelector)); return groupInfos; }
Source:
<code>public Map<String, String> getMetadata() { <START> return Collections.unmodifiableMap(metadata); <END> }</code><technical_language>cases people changing/removing breadcrumb metadata in a callback? case mind is intent extras EventReceiver</technical_language>

Target:
public Map<String, String> getMetadata() { return metadata; }
Source:
<code>public String set(String key, String value) { String command = "set"; registry.distributionSummary(TelemetryHelper.payloadSizeId(idPrefix, command)).record(payloadSize(value)); try { <START> return registry.timer(timerId(idPrefix, command)).record(() -> <END> delegated.set(key, value) ); } catch (Exception e) { registry.counter(allErrorId(idPrefix)).increment(); registry.counter(errorId(idPrefix, command)).increment(); throw new InstrumentedJedisException("could not execute delegate function", e); } }</code><technical_language>PercentileTimer (<LINK_0> please, enables name,redis.command.set,:eq,(,50,95,99,),:percentiles in atlas</technical_language>

Target:
public String set(String key, String value) { String command = "set"; registry.distributionSummary(TelemetryHelper.payloadSizeId(registry, poolName, command)).record(payloadSize(value)); try { return registry.timer(timerId(registry, poolName, command)).record(() -> delegated.set(key, value) ); } catch (Exception e) { registry.counter(allErrorId(registry, poolName)).increment(); registry.counter(errorId(registry, poolName, command)).increment(); throw new InstrumentedJedisException("could not execute delegate function", e); } }
Source:
<code>public void emitTuples() { if (currentWindowId <= idempotentStorageManager.getLargestRecoveryWindow()) { return; } int count = consumer.messageSize(); if (maxTuplesPerWindow > 0) { count = Math.min(count, maxTuplesPerWindow - emitCount); } if (count > 0) { if ((emitCount > 0) && ((maxMsgSizePerWindow - emitMsgSize) < consumer.peekMessage().msg.size())) { return; } <START> } <END> int numEmitted = 0; for (int i = 0; i < count; i++) { KafkaConsumer.KafkaMessage message = consumer.pollMessage(); if(offsetStats.containsKey(message.kafkaPart) && message.offSet <= offsetStats.get(message.kafkaPart)) continue; emitTuple(message.msg); ++numEmitted; emitMsgSize += message.msg.size(); offsetStats.put(message.kafkaPart, message.offSet); MutablePair<Long, Integer> offsetAndCount = currentWindowRecoveryState.get(message.kafkaPart); if(offsetAndCount == null) { currentWindowRecoveryState.put(message.kafkaPart, new MutablePair<Long, Integer>(message.offSet, 1)); } else { offsetAndCount.setRight(offsetAndCount.right+1); } message = consumer.peekMessage(); if (message != null) { if ((maxMsgSizePerWindow - emitMsgSize) < message.msg.size()) { break; } } } emitCount += numEmitted; }</code><technical_language>replace variable "i" numEmitted in for loop</technical_language>

Target:
public void emitTuples() { if (currentWindowId <= idempotentStorageManager.getLargestRecoveryWindow()) { return; } int count = consumer.messageSize() + ((pendingMessage != null) ? 1 : 0); if (maxTuplesPerWindow > 0) { count = Math.min(count, maxTuplesPerWindow - emitCount); } KafkaConsumer.KafkaMessage message = null; for (int i = 0; i < count; i++) { if (pendingMessage != null) { message = pendingMessage; pendingMessage = null; } else { message = consumer.pollMessage(); } if ((emitCount > 0) && ((maxTotalMsgSizePerWindow - emitTotalMsgSize) < message.msg.size())) { pendingMessage = message; break; } emitTuple(message.msg); emitCount++; emitTotalMsgSize += message.msg.size(); offsetStats.put(message.kafkaPart, message.offSet); MutablePair<Long, Integer> offsetAndCount = currentWindowRecoveryState.get(message.kafkaPart); if(offsetAndCount == null) { currentWindowRecoveryState.put(message.kafkaPart, new MutablePair<Long, Integer>(message.offSet, 1)); } else { offsetAndCount.setRight(offsetAndCount.right+1); } } }
Source:
<code>public void onValueSelected(final String modelName) { <START> if (NONE.equals(modelName)) { <END> scenario.setModelName(null); } else { scenario.setModelName(modelName); } }</code><technical_language>Objects.equals(NONE, modelName) more safe</technical_language>

Target:
public void onValueSelected(final String modelName) { if (Objects.equals(NONE, modelName)) { scenario.setModelName(null); } else { scenario.setModelName(modelName); } }
Source:
<code>public static DelayedAction create(ActionDelay delay, Action action) { <START> if (action.getType().isStop()) { <END> throw new IllegalArgumentException("Action type cannot be stop"); } return new DelayedAction(delay.getDelay(TimeUnit.NANOSECONDS), action, r -> { Action nextAction = action.getCallback().apply(r); if (action.getType().isStop()) { return createStop(nextAction); } return create(delay.getCallback().apply(r), nextAction); }); }</code><technical_language>action stop</technical_language>

Target:
public static DelayedAction create(ActionDelay delay, Action action) { if (action.getType().isStop()) { throw new IllegalArgumentException("Action type cannot be stop"); } return new DelayedAction(delay.getDelay(TimeUnit.NANOSECONDS), action, r -> { Action nextAction = action.getCallback().apply(r); if (nextAction.getType().isStop()) { return createStop(nextAction); } return create(delay.getCallback().apply(r), nextAction); }); }
Source:
<code>public CompletedCheckpointStore createCheckpointStore( JobID jobID, int maxNumberOfCheckpointsToRetain, ClassLoader userClassLoader) throws Exception { final String configMapName = getConfigMapNameFunction.apply(jobID); <START> return createCompletedCheckpointStore( <END> configuration, kubeClient, executor, configMapName, lockIdentity, maxNumberOfCheckpointsToRetain); }</code><technical_language>nit: I a bit static method imports harder this method from. I is put class name of method is easily visible</technical_language>

Target:
public CompletedCheckpointStore createCheckpointStore( JobID jobID, int maxNumberOfCheckpointsToRetain, ClassLoader userClassLoader) throws Exception { final String configMapName = getConfigMapNameFunction.apply(jobID); return KubernetesUtils.createCompletedCheckpointStore( configuration, kubeClient, executor, configMapName, lockIdentity, maxNumberOfCheckpointsToRetain); }
Source:
<code>public void prepare(String name) { String testDir = TestingUtil.tmpDirectory(name); Util.recursiveFileRemove(testDir); rootDir = new File(testDir); confDir = new File(rootDir, Server.DEFAULT_SERVER_CONFIG); if (!confDir.mkdirs()) { throw new RuntimeException("Failed to create server configuration directory " + confDir); } URL configurationFileURL = getClass().getClassLoader().getResource(configuration.configurationFile()); <START> if(new File(configuration.configurationFile()).isAbsolute()) { <END> configurationFileURL = Exceptions.unchecked(() -> new File(configuration.configurationFile()).toURI().toURL()); } if (configurationFileURL == null) { throw new RuntimeException("Cannot find test configuration file: " + configuration.configurationFile()); } Path configurationFilePath; try { configurationFilePath = Paths.get(configurationFileURL.toURI()); Util.recursiveDirectoryCopy(configurationFilePath.getParent(), confDir.toPath()); } catch (Exception e) { throw new RuntimeException(e); } createUserFile("default", true); createKeyStores(); }</code><technical_language>suggestion if (new File(configuration.configurationFile()).isAbsolute()) {</technical_language>

Target:
public void prepare(String name) { String testDir = TestingUtil.tmpDirectory(name); Util.recursiveFileRemove(testDir); rootDir = new File(testDir); confDir = new File(rootDir, Server.DEFAULT_SERVER_CONFIG); if (!confDir.mkdirs()) { throw new RuntimeException("Failed to create server configuration directory " + confDir); } URL configurationFileURL; if (new File(configuration.configurationFile()).isAbsolute()) { configurationFileURL = Exceptions.unchecked(() -> new File(configuration.configurationFile()).toURI().toURL()); } else { configurationFileURL = getClass().getClassLoader().getResource(configuration.configurationFile()); } if (configurationFileURL == null) { throw new RuntimeException("Cannot find test configuration file: " + configuration.configurationFile()); } Path configurationFilePath; try { configurationFilePath = Paths.get(configurationFileURL.toURI()); Util.recursiveDirectoryCopy(configurationFilePath.getParent(), confDir.toPath()); } catch (Exception e) { throw new RuntimeException(e); } createUserFile("default", true); createKeyStores(); }
Source:
<code>private void testDownload(String urlString, IProgressMonitor monitor) { try { <START> IPath foundationCoreStateLocation = FoundationCorePlugin.getDefault().getStateLocation(); <END> URL url = new URL(urlString); URLTransportUtility util = new URLTransportUtility(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IStatus s = util.download("displayName", urlString, baos, monitor); assertTrue(s.isOK()); String stringFromDownload = baos.toString(); assertNotNull(stringFromDownload); assertNotNull(stringFromDownload); } catch(MalformedURLException murle) { fail("Bad url: " + urlString); } }</code><technical_language>this is for - remove</technical_language>

Target:
private void testDownload(String urlString, IProgressMonitor monitor) { URLTransportUtility util = new URLTransportUtility(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IStatus s = util.download("displayName", urlString, baos, monitor); assertTrue(s.isOK()); String stringFromDownload = baos.toString(); assertNotNull(stringFromDownload); assertNotNull(stringFromDownload); }
Source:
<code>public static Optional<License> parse(String base64) { try { String data = new String(Base64.decodeBase64(base64.trim().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); Properties props = new Properties(); props.load(new StringReader(data)); Collection<String> plugins = Arrays.asList(StringUtils.split(props.getProperty(PLUGINS_KEY), ',')); String editionKey = props.getProperty(EDITION_KEY); if (editionKey != null && !plugins.isEmpty()) { return Optional.of(new License(editionKey, plugins, base64)); } } catch (Exception e) { } return Optional.empty(); <START> <END> }</code><technical_language>please provide a DEBUG log (same reason below)</technical_language>

Target:
public static Optional<License> parse(String base64) { try { String data = new String(Base64.decodeBase64(base64.trim().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); Properties props = new Properties(); props.load(new StringReader(data)); Collection<String> plugins = Arrays.asList(StringUtils.split(props.getProperty(PLUGINS_KEY), ',')); String editionKey = props.getProperty(EDITION_KEY); if (editionKey != null && !plugins.isEmpty()) { return Optional.of(new License(editionKey, plugins, base64)); } else { LOG.debug("Failed to parse license: no edition key and/or no plugin found"); } } catch (Exception e) { LOG.debug("Failed to parse license", e); } return Optional.empty(); }
Source:
<code>public LocalFileDirectTaskLogger(LogFilePrefix prefix, String taskName) throws IOException { String dateDir = LogFiles.formatDataDir(prefix); String attemptDir = LogFiles.formatSessionAttemptDir(prefix); Path dir = getPrefixDir(dateDir, attemptDir); Files.createDirectories(dir); String temporaryFileName = LogFiles.formatPlainTextFileName(taskName, Instant.now(), agentId.toString()); this.temporaryPath = dir.resolve(temporaryFileName); this.temporaryOutput = Files.newOutputStream(temporaryPath, CREATE, APPEND); String conclusiveFileName = LogFiles.formatFileName(taskName, Instant.now(), agentId.toString()); this.conclusivePath = dir.resolve(conclusiveFileName); <START> } <END></code><technical_language>This behaviour optional</technical_language>

Target:
public LocalFileDirectTaskLogger(LogFilePrefix prefix, String taskName) throws IOException { String dateDir = LogFiles.formatDataDir(prefix); String attemptDir = LogFiles.formatSessionAttemptDir(prefix); Path dir = getPrefixDir(dateDir, attemptDir); Files.createDirectories(dir); String fileName = LogFiles.formatFileName(taskName, Instant.now(), agentId.toString()); this.path = dir.resolve(fileName); String temporaryFileName = LogFiles.formatPlainTextFileName(taskName, Instant.now(), agentId.toString()); this.temporaryPath = dir.resolve(temporaryFileName); if (realtimeFollow) { this.output = Files.newOutputStream(temporaryPath, CREATE, APPEND); } else { this.output = new GZIPOutputStream(Files.newOutputStream(path, CREATE, APPEND), 16*1024); } }
Source:
<code><START> public List<String> getJudgmentTypes() { <END> return judgmentTypes; }</code><technical_language>List<JudgmentType>?</technical_language>

Target:
public Set<JudgmentType> getJudgmentTypes() { if (judgmentTypes == null) { return new HashSet<JudgmentType>(); } else { return judgmentTypes; } }
Source:
<code>public void store(String tenantId, List<Span> spans, Function<Span, String> cacheKeyEntrySupplier) throws CacheException { if (cacheContainer != null) { spansCache.startBatch(); } for (Span span : spans) { log.debugf("Store span [%s]" + span); spansCache.put(cacheKeyEntrySupplier.apply(span), span, 1, TimeUnit.MINUTES); if (span.getTraceId() != null) { Set<Span> trace = traceCache.get(span.getTraceId()); if (trace == null) { trace = new HashSet<>(); <START> traceCache.put(span.getTraceId(), trace); <END> } trace.add(span); } } if (cacheContainer != null) { spansCache.endBatch(true); } }</code><technical_language>Need 'put' in cache, trace set updated - put result in cached object written disk distributed remote node if change cache type</technical_language>

Target:
public void store(String tenantId, List<Span> spans, Function<Span, String> cacheKeyEntrySupplier) throws CacheException { if (cacheContainer != null) { spansCache.startBatch(); } for (Span span : spans) { log.debugf("Store span [%s]" + span); spansCache.put(cacheKeyEntrySupplier.apply(span), span, 1, TimeUnit.MINUTES); if (span.getTraceId() != null) { Set<Span> trace = traceCache.get(span.getTraceId()); if (trace == null) { trace = new HashSet<>(); } trace.add(span); traceCache.put(span.getTraceId(), trace); } } if (cacheContainer != null) { spansCache.endBatch(true); } }
Source:
<code>private boolean sendResponse(Object result) { if (RESPONSE_FLAG.compareAndSet(this, Boolean.FALSE, Boolean.TRUE)) { try { <START> if (result instanceof Throwable) { <END> result = new ErrorResponse((Throwable) result, op.getCallId(), op.isUrgent()); } op.sendResponse(result); } catch (HazelcastSerializationException e) { op.sendResponse(new ErrorResponse(e, op.getCallId(), op.isUrgent())); } return true; } return false; }</code><technical_language>op.sendResponse(...) handle this? afaik takes care of creating correct response object</technical_language>

Target:
private boolean sendResponse(Object result) { if (RESPONSE_FLAG.compareAndSet(this, Boolean.FALSE, Boolean.TRUE)) { try { op.sendResponse(result); } catch (HazelcastSerializationException e) { op.sendResponse(e); } return true; } return false; }
Source:
<code>public void testChangeHeaderAfterWritingHeader() { final File bcfOutputFile = VariantBaseTest.createTempFile("testWriteAndReadVCF.", ".bcf"); Tribble.indexFile(bcfOutputFile).deleteOnExit(); Set<VCFHeaderLine> metaData = new HashSet<VCFHeaderLine>(); Set<String> additionalColumns = new HashSet<String>(); final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary(); final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict); final VariantContextWriter writer2 = new VariantContextWriterBuilder() .setOutputFile(bcfOutputFile).setReferenceDictionary(sequenceDict) .setOptions(EnumSet.of(Options.INDEX_ON_THE_FLY)) .build(); writer2.writeHeader(header); writer2.setVCFHeader(header); <START> writer2.add(createVC(header)); <END> writer2.close(); }</code><technical_language>This call is unnecessary for test - exception thrown in previous stmt</technical_language>

Target:
public void testChangeHeaderAfterWritingHeader() throws IOException { final File bcfOutputFile = File.createTempFile("testWriteAndReadVCF.", ".bcf", tempDir); bcfOutputFile.deleteOnExit(); final VCFHeader header = createFakeHeader(); try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(bcfOutputFile).setReferenceDictionary(header.getSequenceDictionary()) .unsetOption(Options.INDEX_ON_THE_FLY) .build()) { writer.writeHeader(header); writer.setVCFHeader(header); } }
Source:
<code>public void testGetExternalResourcesWithConfigKeyNotSpecifiedOrEmpty() { final Configuration config = new Configuration(); final String resourceConfigKey = ""; config.set(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, RESOURCE_LIST); <START> config.setLong(ExternalResourceOptions.keyWithResourceNameAndSuffix(RESOURCE_NAME_1, ExternalResourceOptions.EXTERNAL_RESOURCE_AMOUNT_SUFFIX), RESOURCE_AMOUNT_1); <END> config.setLong(ExternalResourceOptions.keyWithResourceNameAndSuffix(RESOURCE_NAME_2, ExternalResourceOptions.EXTERNAL_RESOURCE_AMOUNT_SUFFIX), RESOURCE_AMOUNT_2); config.setString(ExternalResourceOptions.keyWithResourceNameAndSuffix(RESOURCE_NAME_1, SUFFIX), resourceConfigKey); final Map<String, Long> configMap = ExternalResourceUtils.getExternalResources(config, SUFFIX); assertThat(configMap.entrySet(), is(empty())); }</code><technical_language>introduce dedicated names for ExternalResourceOptions.keyWithResourceNameAndSuffix(RESOURCE_NAME_1, ExternalResourceOptions.EXTERNAL_RESOURCE_AMOUNT_SUFFIX). For example, ExternalResourceOptions.getAmountConfigOptionForResource(RESOURCE_NAME_1). For ExternalResourceOptions.keyWithResourceNameAndSuffix(RESOURCE_NAME_1, SUFFIX) introduce ExternalResourceOptions.getSystemConfigKeyConfigOptionForResource(RESOURCE_NAME_1, SUFFIX)</technical_language>

Target:
public void testGetExternalResourcesWithConfigKeyNotSpecifiedOrEmpty() { final Configuration config = new Configuration(); final String resourceConfigKey = ""; config.set(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, RESOURCE_LIST); config.setLong(ExternalResourceOptions.getAmountConfigOptionForResource(RESOURCE_NAME_1), RESOURCE_AMOUNT_1); config.setLong(ExternalResourceOptions.getAmountConfigOptionForResource(RESOURCE_NAME_2), RESOURCE_AMOUNT_2); config.setString(ExternalResourceOptions.getSystemConfigKeyConfigOptionForResource(RESOURCE_NAME_1, SUFFIX), resourceConfigKey); final Map<String, Long> configMap = ExternalResourceUtils.getExternalResources(config, SUFFIX); assertThat(configMap.entrySet(), is(empty())); }
Source:
<code>public void shouldUpdateProcessesAssignedToTemplate() throws Exception { Template template = new ServiceManager().getTemplateService().getById(1); <START> System.out.println(template.getDocket().getId() + " " + template.getRuleset().getId()); <END> for (Process process : template.getProcesses()) { assertNotEquals("Template and Process have assigned the same docket!", template.getDocket(), process.getDocket()); assertNotEquals("Template and Process have assigned the same ruleset!", template.getRuleset(), process.getRuleset()); } Updater updater = new Updater(template); updater.updateProcessesAssignedToTemplate(); for (Process process : template.getProcesses()) { assertEquals("Template and Process have assigned different docket!", template.getDocket(), process.getDocket()); assertEquals("Template and Process have assigned different ruleset!", template.getRuleset(), process.getRuleset()); } }</code><technical_language>Is this line needed</technical_language>

Target:
public void shouldUpdateProcessesAssignedToTemplate() throws Exception { Template template = new ServiceManager().getTemplateService().getById(1); for (Process process : template.getProcesses()) { assertNotEquals("Template and Process have assigned the same docket!", template.getDocket(), process.getDocket()); assertNotEquals("Template and Process have assigned the same ruleset!", template.getRuleset(), process.getRuleset()); } Updater updater = new Updater(template); updater.updateProcessesAssignedToTemplate(); for (Process process : template.getProcesses()) { assertEquals("Template and Process have assigned different docket!", template.getDocket(), process.getDocket()); assertEquals("Template and Process have assigned different ruleset!", template.getRuleset(), process.getRuleset()); } }
Source:
<code>public void execute(IProgressMonitor m) throws CoreException { SubMonitor progress = SubMonitor.convert(m, CoreText.DisconnectProviderOperation_disconnecting, <START> projectList.size() * 2); <END> for (IProject p : projectList) { if (GitTraceLocation.CORE.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.CORE.getLocation(), "disconnect " + p.getName()); unmarkTeamPrivate(p); RepositoryProvider.unmap(p); progress.worked(1); p.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); } }</code><technical_language>Remove * 2</technical_language>

Target:
public void execute(IProgressMonitor m) throws CoreException { SubMonitor progress = SubMonitor.convert(m, CoreText.DisconnectProviderOperation_disconnecting, projectList.size()); for (IProject p : projectList) { if (GitTraceLocation.CORE.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.CORE.getLocation(), "disconnect " + p.getName()); } unmarkTeamPrivate(p); RepositoryProvider.unmap(p); p.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); } }
Source:
<code>public static Map<Integer, Map<Integer, Long>> getUpdateCountersSnapshot( IgniteEx ign, Set<Integer> grpIds ) { Map<Integer, Map<Integer, Long>> partsWithCountersPerGrp = new HashMap<>(); for (Integer grpId : grpIds) { CacheGroupContext grpCtx = ign.context().cache().cacheGroup(grpId); if (grpCtx == null) throw new GridNotIdleException("Group not found: " + grpId + "." + " Possible reasons: rebalance in progress or concurrent cache destroy."); GridDhtPartitionTopology top = grpCtx.topology(); Map<Integer, Long> partsWithCounters = partsWithCountersPerGrp.computeIfAbsent(grpId, k -> new HashMap<>()); for (GridDhtLocalPartition part : top.currentLocalPartitions()) { if (part.state() != GridDhtPartitionState.OWNING) continue; if (!part.dataStore().partUpdateCounter().sequential()) <START> throw new GridNotIdleException("Cluster not idle. Probably due to continues rebalance"); <END> partsWithCounters.put(part.id(), part.updateCounter()); } } return partsWithCountersPerGrp; }</code><technical_language>Due lost updates (should happen normal circumstances) counter sequential if grid is idle. compare counter check</technical_language>

Target:
public static Map<Integer, Map<Integer, PartitionUpdateCounter>> getUpdateCountersSnapshot( IgniteEx ign, Set<Integer> grpIds ) { Map<Integer, Map<Integer, PartitionUpdateCounter>> partsWithCountersPerGrp = new HashMap<>(); for (Integer grpId : grpIds) { CacheGroupContext grpCtx = ign.context().cache().cacheGroup(grpId); if (grpCtx == null) throw new GridNotIdleException("Group not found: " + grpId + "." + " Possible reasons: rebalance in progress or concurrent cache destroy."); GridDhtPartitionTopology top = grpCtx.topology(); Map<Integer, PartitionUpdateCounter> partsWithCounters = partsWithCountersPerGrp.computeIfAbsent(grpId, k -> new HashMap<>()); for (GridDhtLocalPartition part : top.currentLocalPartitions()) { if (part.state() != GridDhtPartitionState.OWNING) continue; @Nullable PartitionUpdateCounter updCntr = part.dataStore().partUpdateCounter(); partsWithCounters.put(part.id(), updCntr == null ? null : updCntr.copy()); } } return partsWithCountersPerGrp; }
Source:
<code>public Iterable<VirtualMachine> listNodesByIds(final Iterable<String> ids) { return Iterables.filter(listNodes(), new Predicate<VirtualMachine>() { @Override public boolean apply(VirtualMachine vm) { return Iterables.contains(ids, vm.getId()); } <START> }); <END> }</code><technical_language>..and again? ;-)</technical_language>

Target:
public Iterable<VirtualMachine> listNodesByIds(final Iterable<String> ids) { return filter(listNodes(), new Predicate<VirtualMachine>() { @Override public boolean apply(VirtualMachine vm) { return contains(ids, vm.getId()); } }); }
Source:
<code>public double getMinWeight( double distance ) { <START> return 0.001 * distance; <END> }</code><technical_language>This is correct. needs a good approximation A\* working fast correct. If is small A\* slow, if is bigger a single in real world route results incorrect</technical_language>

Target:
public double getMinWeight( double distance ) { return 0.1 * distance; }
Source:
<code>public Response doImport(Action action) { <START> validateParameters(action, "cluster.id|name", "storageDomain.id|name"); <END> Guid destStorageDomainId = getDestStorageDomainId(action); ImportVmParameters params = new ImportVmParameters(getEntity(), parent.getStorageDomainId(), destStorageDomainId, parent.getDataCenterId(destStorageDomainId), getClusterId(action)); params.setImageToDestinationDomainMap(getDiskToDestinationMap(action)); params.setForceOverride(action.isSetExclusive() ? action.isExclusive() : false); if (action.isSetVm() && action.getVm().isSetSnapshots() && action.getVm().getSnapshots().isSetCollapseSnapshots()) { params.setCopyCollapse(action.getVm().getSnapshots().isCollapseSnapshots()); } if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if(action.isSetVm() && action.getVm().isSetName()) { params.getVm().setName(action.getVm().getName()); } } return doAction(VdcActionType.ImportVm, params, action); }</code><technical_language>making storage_domain mandatory? - this break api, import() default logic SD</technical_language>

Target:
public Response doImport(Action action) { validateParameters(action, "cluster.id|name"); Guid destStorageDomainId = getDestStorageDomainId(action); ImportVmParameters params = new ImportVmParameters(getEntity(), parent.getStorageDomainId(), destStorageDomainId, parent.getDataCenterId(destStorageDomainId), getClusterId(action)); params.setImageToDestinationDomainMap(getDiskToDestinationMap(action)); params.setForceOverride(action.isSetExclusive() ? action.isExclusive() : false); if (action.isSetVm() && action.getVm().isSetSnapshots() && action.getVm().getSnapshots().isSetCollapseSnapshots()) { params.setCopyCollapse(action.getVm().getSnapshots().isCollapseSnapshots()); } if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if(action.isSetVm() && action.getVm().isSetName()) { params.getVm().setName(action.getVm().getName()); } } return doAction(VdcActionType.ImportVm, params, action); }
Source:
<code>private void preserveOriginalFile(Path java) throws Exception { long expected = Files.getLastModifiedTime(java).toMillis(); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in); int errorCode = main.format("-replace", java.toAbsolutePath().toString()); <START> Assert.assertEquals("ErrorCode not 0: " + err + ": " + out, 0, errorCode); <END> long actual = Files.getLastModifiedTime(java).toMillis(); Assert.assertEquals("Last modified time changed: " + java, expected, actual); }</code><technical_language>Consider truth assertions for consistency rest of file: java assertThat(errorCode).named("Error Code").isEqualTo(0);</technical_language>

Target:
private void preserveOriginalFile(Path java) throws Exception { long expected = Files.getLastModifiedTime(java).toMillis(); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in); int errorCode = main.format("-replace", java.toAbsolutePath().toString()); assertThat(errorCode).named("Error Code").isEqualTo(0); long actual = Files.getLastModifiedTime(java).toMillis(); assertThat(actual).named("Last modified time changed: " + java).isEqualTo(expected); }
Source:
<code>private ServiceResponse<?> validateContainerReleaseAndMode(String preffix, KieContainerResource container) { <START> if(container == null) { <END> return new ServiceResponse<>(ResponseType.FAILURE, preffix, "Release Id is null"); } return validateReleaseAndMode(preffix, container.getReleaseId()); }</code><technical_language>formatting.. format regions of selected code in intellij reformatting file if want avoid whitespace changes in code change</technical_language>

Target:
private <T> ServiceResponse<T> validateContainerReleaseAndMode(String preffix, KieContainerResource container) { if (container == null) { return new ServiceResponse<>(ResponseType.FAILURE, preffix + " Container is null"); } return validateReleaseAndMode(preffix, container.getReleaseId()); }
Source:
<code>public void onActivityStarted(Activity activity) { ConnectivityIndicator.start(mContext); <START> mCurrentActivity = activity; <END> }</code><technical_language>do need a reference activity here? This leak app. mEditState array instead</technical_language>

Target:
public void onActivityStarted(Activity activity) { mCurrentActivity = new WeakReference<>(activity); }
Source:
<code>public boolean remove(Object o) { throw new UnsupportedOperationException("No <START> remove in <END> " + this.getClass().getName()); }</code><technical_language>remove(Object)</technical_language>

Target:
public boolean remove(Object o) { throw new UnsupportedOperationException("No remove(Object) in " + this.getClass().getName()); }
Source:
<code>public MockEJBStrategyRule(Map<BeanType, Object> beans) { <START> this(beans, new EnumMap<ContainerManagedResourceType,Object>(ContainerManagedResourceType.class));; <END> }</code><technical_language>extra semicolon end here</technical_language>

Target:
public MockEJBStrategyRule(Map<BeanType, Object> beans) { this(beans, new EnumMap<ContainerManagedResourceType,Object>(ContainerManagedResourceType.class)); }
Source:
<code>public MedicationRequest updateFHIRMedicationRequest(MedicationRequest medicationRequest, String uuid) { List<String> errors = new ArrayList<String>(); DrugOrder incomingDrugOrder = FHIRMedicationRequestUtil.generateDrugOrder(medicationRequest, errors); DrugOrder generatedDrugOrder = (DrugOrder) Context.getOrderService().getOrderByUuid(uuid); FHIRMedicationRequestUtil.copyObsAttributes(incomingDrugOrder, generatedDrugOrder, errors); if (generatedDrugOrder != null) { if (!errors.isEmpty()) { <START> String errorMessage = ErrorUtil.generateErrorMessage(errors, "The request cannot be processed due to the " + <END> "following issues \n"); throw new UnprocessableEntityException(errorMessage); } incomingDrugOrder = (DrugOrder) Context.getOrderService().saveOrder(generatedDrugOrder, null); return FHIRMedicationRequestUtil.generateMedicationRequest(incomingDrugOrder); } else { StrategyUtil.setIdIfNeeded(medicationRequest, uuid); return createFHIRMedicationRequest(medicationRequest); } }</code><technical_language>FHIRConstants.REQUEST_ISSUE_LIST here</technical_language>

Target:
public MedicationRequest updateFHIRMedicationRequest(MedicationRequest medicationRequest, String uuid) { List<String> errors = new ArrayList<String>(); DrugOrder incomingDrugOrder = FHIRMedicationRequestUtil.generateDrugOrder(medicationRequest, errors); DrugOrder generatedDrugOrder = (DrugOrder) Context.getOrderService().getOrderByUuid(uuid); FHIRMedicationRequestUtil.copyObsAttributes(incomingDrugOrder, generatedDrugOrder, errors); if (generatedDrugOrder != null) { if (!errors.isEmpty()) { String errorMessage = ErrorUtil.generateErrorMessage(errors, FHIRConstants.REQUEST_ISSUE_LIST); throw new UnprocessableEntityException(errorMessage); } incomingDrugOrder = (DrugOrder) Context.getOrderService().saveOrder(generatedDrugOrder, null); return FHIRMedicationRequestUtil.generateMedicationRequest(incomingDrugOrder); } else { StrategyUtil.setIdIfNeeded(medicationRequest, uuid); return createFHIRMedicationRequest(medicationRequest); } }
Source:
<code>private void checkGps() { Timber.d("checking GPS"); if (!locationManager.isProviderEnabled()) { Timber.d("GPS is not enabled"); new AlertDialog.Builder(getActivity()) .setMessage(R.string.gps_disabled) .setCancelable(false) .setPositiveButton(R.string.enable_gps, (dialog, id) -> { Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); Timber.d("Loaded settings page"); startActivityForResult(callGPSSettingIntent, 1); }) .setNegativeButton(R.string.menu_cancel_upload, (dialog, id) -> { DialogUtil.showAlertDialog( getActivity(), null, getString(R.string.nearby_needs_gps), getString(R.string.enable_gps), getString(R.string.cancel), <START> new Runnable() { <END> @Override public void run() { Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); Timber.d("Loaded settings page"); startActivityForResult(callGPSSettingIntent, 1); } }, new Runnable() { @Override public void run() { ((MainActivity)getActivity()).viewPager.setCurrentItem(((MainActivity)getActivity()).CONTRIBUTIONS_TAB_POSITION); } }); dialog.cancel(); }) .create() .show(); } else { Timber.d("GPS is enabled"); checkLocationPermission(); } }</code><technical_language>lambda</technical_language>

Target:
private void checkGps() { Timber.d("checking GPS"); if (!locationManager.isProviderEnabled()) { Timber.d("GPS is not enabled"); new AlertDialog.Builder(getActivity()) .setMessage(R.string.gps_disabled) .setCancelable(false) .setPositiveButton(R.string.enable_gps, (dialog, id) -> { Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); Timber.d("Loaded settings page"); startActivityForResult(callGPSSettingIntent, 1); }) .setNegativeButton(R.string.menu_cancel_upload, (dialog, id) -> { DialogUtil.showAlertDialog( getActivity(), null, getString(R.string.nearby_needs_gps), getString(R.string.enable_gps), getString(R.string.cancel), () -> { Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); Timber.d("Loaded settings page"); startActivityForResult(callGPSSettingIntent, 1); }, () -> { ((MainActivity)getActivity()).viewPager.setCurrentItem(((MainActivity)getActivity()).CONTRIBUTIONS_TAB_POSITION); }); dialog.cancel(); }) .create() .show(); } else { Timber.d("GPS is enabled"); checkLocationPermission(); } }
Source:
<code>public void visitNode(AstNode node) { Symbol symbol = getContext().symbolTable().getSymbol(node); if (symbol != null && questionableFunctions.contains(symbol.qualifiedName())) { AstNode parent = node.getParent(); if (parent != null && parent.is(PythonGrammar.CALL_EXPR)) { <START> parent.getChildren(PythonGrammar.ARGLIST).forEach(this::checkArgument); <END> } } }</code><technical_language>Checking arguments raise FP a non-regexp argument. e.g. in regex.subf('pattern', 'replacement{1}{2}', 'input') check regexp arguments</technical_language>

Target:
public void visitNode(AstNode node) { Symbol symbol = getContext().symbolTable().getSymbol(node); if (symbol != null && questionableFunctions.contains(symbol.qualifiedName())) { AstNode parent = node.getParent(); if (parent != null && parent.is(PythonGrammar.CALL_EXPR)) { AstNode argListNode = parent.getFirstChild(PythonGrammar.ARGLIST); if (argListNode != null) { checkRegexArgument(argListNode.getChildren().get(REGEX_ARGUMENT)); } } } }
Source:
<code>private static Map<String, String> getHostToRackMap(String rackYamlFile) throws FileNotFoundException, YamlException { <START> YamlReader yamlReader = new YamlReader(new FileReader(rackYamlFile)); <END> Map rackHostsMap = (Map) yamlReader.read(); Map racks = (Map) rackHostsMap.get(RACKS_YAML_KEY_NAME); Map<String, String> hostToRackMap = new HashMap<>(); for (Map.Entry entry : (Set<Map.Entry>) racks.entrySet()) { Map rackInfoMap = (Map) entry.getValue(); String rackName = (String) entry.getKey(); if (rackInfoMap.containsKey(HOSTS_YAML_KEY_NAME)) { List<String> hostList = (List<String>) rackInfoMap.get(HOSTS_YAML_KEY_NAME); for (String host : hostList) { hostToRackMap.put(host, rackName); } } if (rackInfoMap.containsKey(HOST_GROUPS_YAML_KEY_NAME)) { List<Map> hostGroups = (List<Map>) rackInfoMap.get(HOST_GROUPS_YAML_KEY_NAME); for (Map hostGroup : hostGroups) { if (hostGroup.containsKey(HOSTS_YAML_KEY_NAME)) { List<String> hostList = (List<String>) hostGroup.get(HOSTS_YAML_KEY_NAME); for (String host : hostList) { hostToRackMap.put(host, rackName); } } } } } return hostToRackMap; }</code><technical_language>YamlReader closed some point</technical_language>

Target:
private static Map<String, String> getHostToRackMap(String rackYamlFile) throws IOException { YamlReader yamlReader = new YamlReader(new FileReader(rackYamlFile)); Map rackHostsMap; try { rackHostsMap = (Map) yamlReader.read(); } finally { yamlReader.close(); } Map racks = (Map) rackHostsMap.get(RACKS_YAML_KEY_NAME); Map<String, String> hostToRackMap = new HashMap<>(); for (Map.Entry entry : (Set<Map.Entry>) racks.entrySet()) { Map rackInfoMap = (Map) entry.getValue(); String rackName = (String) entry.getKey(); if (rackInfoMap.containsKey(HOSTS_YAML_KEY_NAME)) { List<String> hostList = (List<String>) rackInfoMap.get(HOSTS_YAML_KEY_NAME); for (String host : hostList) { hostToRackMap.put(host, rackName); } } if (rackInfoMap.containsKey(HOST_GROUPS_YAML_KEY_NAME)) { List<Map> hostGroups = (List<Map>) rackInfoMap.get(HOST_GROUPS_YAML_KEY_NAME); for (Map hostGroup : hostGroups) { if (hostGroup.containsKey(HOSTS_YAML_KEY_NAME)) { List<String> hostList = (List<String>) hostGroup.get(HOSTS_YAML_KEY_NAME); for (String host : hostList) { hostToRackMap.put(host, rackName); } } } } } return hostToRackMap; }
Source:
<code>private Iterable<ISegment> compactList(final long startTime, final Iterable<@NonNull ISegment> iterableToCompact) { return new Iterable<@NonNull ISegment>() { @Override public Iterator<ISegment> iterator() { return new Iterator<@NonNull ISegment>() { <START> private @Nullable ISegment last = null; <END> private @Nullable ISegment next = null; private Iterator<@NonNull ISegment> iterator = iterableToCompact.iterator(); @Override public @NonNull ISegment next() { if (hasNext()) { last = next; next = null; return Objects.requireNonNull(last); } throw new NoSuchElementException(); } @Override public boolean hasNext() { if (last == null) { if (iterator.hasNext()) { last = iterator.next(); if (last.getStart() >= startTime) { next = last; } } else { return false; } } ISegment prev = last; while (next == null && iterator.hasNext()) { ISegment tmp = iterator.next(); if (tmp.getStart() >= startTime && !overlaps(prev, tmp)) { next = tmp; } } return next != null; } }; } }; }</code><technical_language>fNext, fLast</technical_language>

Target:
private Iterable<ISegment> compactList(final long startTime, final Iterable<@NonNull ISegment> iterableToCompact) { return new Iterable<@NonNull ISegment>() { @Override public Iterator<ISegment> iterator() { return new Iterator<@NonNull ISegment>() { private @Nullable ISegment fLast = null; private @Nullable ISegment fNext = null; private Iterator<@NonNull ISegment> fIterator = iterableToCompact.iterator(); @Override public @NonNull ISegment next() { if (hasNext()) { fLast = fNext; fNext = null; return Objects.requireNonNull(fLast); } throw new NoSuchElementException(); } @Override public boolean hasNext() { if (fLast == null) { if (fIterator.hasNext()) { fLast = fIterator.next(); if (fLast.getStart() >= startTime) { fNext = fLast; } } else { return false; } } ISegment prev = fLast; while (fNext == null && fIterator.hasNext()) { ISegment tmp = fIterator.next(); if (tmp.getStart() >= startTime && !overlaps(prev, tmp)) { fNext = tmp; } } return fNext != null; } }; } }; }
Source:
<code>public TmfLocationArray(ITmfLocation[] locations, long[] ranks) { <START> assert(locations.length == ranks.length); <END> fLocations = Arrays.copyOf(locations, locations.length); fRanks = Arrays.copyOf(ranks, ranks.length); }</code><technical_language>want leave asserts in code? checking throwing IllegalArgumentException, similar, is better</technical_language>

Target:
public TmfLocationArray(ITmfLocation[] locations, long[] ranks) { fLocations = Arrays.copyOf(locations, locations.length); fRanks = Arrays.copyOf(ranks, ranks.length); }
Source:
<code>public void onEventMainThread(PostEvents.PostUploadCanceled event) { <START> if (isAdded() && mSite.getId() == event.localSiteId) { <END> loadPosts(LoadMode.FORCED); } }</code><technical_language>I understand mSite null, reading onCreate sequence this class is registered for FLuxC event listening _before_ mSite property is initialized in updateSiteOrFinishActivity(). While deserve analysis, for sake of this PR check mSite is null avoid a NPE</technical_language>

Target:
public void onEventMainThread(PostEvents.PostUploadCanceled event) { if (isAdded() && mSite != null && mSite.getId() == event.localSiteId) { loadPosts(LoadMode.FORCED); } }
Source:
<code>public void execute(TronObject object) { <START> FlagKeeper flagkeeper = (FlagKeeper) object; <END> if (flagkeeper != null) { Flag flag = flagkeeper.giveFlag(); if (flag != null) { List<SquareContainer> neighbours = this.getAllNeighboursOf(flagkeeper .getCurrentPosition()); neighbours.get(new Random().nextInt(neighbours.size())).addItem(flag); } } super.execute(object); }</code><technical_language>check if this done</technical_language>

Target:
public void execute(TronObject object) throws IllegalStateException { FlagKeeper flagkeeper = object.asFlagKeeper(); if (flagkeeper != null) { Flag flag = flagkeeper.giveFlag(); if (flag != null) { List<SquareContainer> neighbours = flagkeeper.getCurrentPosition() .getAllNeighbours(); if (neighbours.size() == 0) throw new IllegalStateException( " The flagkeeper's current square must have at least one neigbour."); neighbours.get(new Random().nextInt(neighbours.size())).addItem(flag); } } super.execute(object); }