auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void updateStatus(final String itemName, final ISYBindingConfig config) { <START> if (this.logger.isDebugEnabled()) { <END> this.logger.debug("updateStatus({},{}) is called!", itemName, config); } if (this.insteonClient != null && this.insteonClient.isISYReady()) { try { UDNode node = this.insteonClient.getNodes().get( config.getAddress()); if (node == null) { node = this.insteonClient.getGroups().get( config.getAddress()); } if (node != null) { Object value = this.insteonClient.getCurrValue(node, config .getControlCommand().name()); UDControl control = new UDControl(); control.name = config.getControlCommand().name(); onModelChanged(control, value, node); } } catch (Exception ex) { this.logger.error("Failed to update status of " + itemName, ex); } } else { if (this.logger.isInfoEnabled()) { this.logger.info("ISY is not ready yet"); } } }</code><technical_language>need for if clause</technical_language>

Target:
private void updateStatus(final String itemName, final ISYBindingConfig config) { this.logger.debug("updateStatus({},{}) is called!", itemName, config); if (this.insteonClient != null && this.insteonClient.isISYReady()) { try { UDNode node = this.insteonClient.getNodes().get( config.getAddress()); if (node == null) { node = this.insteonClient.getGroups().get( config.getAddress()); } if (node != null) { Object value = this.insteonClient.getCurrValue(node, config .getControlCommand().name()); UDControl control = new UDControl(); control.name = config.getControlCommand().name(); onModelChanged(control, value, node); } } catch (Exception ex) { this.logger.error("Failed to update status of '{}' ", itemName, ex); } } else { this.logger.info("ISY is not ready yet"); } }
Source:
<code>public void shouldThrowTimeoutExceptionWithCompletionStage() throws Exception { <START> Duration timeoutDuration = Duration.ofSeconds(1); <END> TimeLimiter timeLimiter = TimeLimiter.of(timeoutDuration); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); Supplier<CompletionStage<Integer>> supplier = () -> CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1500); } catch (InterruptedException e) { } return 0; }); CompletionStage<Integer> decorated = TimeLimiter.decorateCompletionStage(timeLimiter, scheduler, supplier).get(); Try<Integer> decoratedResult = Try.ofCallable(() -> decorated.toCompletableFuture().get()); assertThat(decoratedResult.isFailure()).isTrue(); assertThat(decoratedResult.getCause()).isInstanceOf(ExecutionException.class) .hasCauseExactlyInstanceOf(TimeoutException.class); }</code><technical_language>speed this test? reduce timeoutduration</technical_language>

Target:
public void shouldThrowTimeoutExceptionWithCompletionStage() throws Exception { Duration timeoutDuration = Duration.ofMillis(300); TimeLimiter timeLimiter = TimeLimiter.of(timeoutDuration); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); Supplier<CompletionStage<Integer>> supplier = () -> CompletableFuture.supplyAsync(() -> { try { Thread.sleep(500); } catch (InterruptedException e) { } return 0; }); CompletionStage<Integer> decorated = TimeLimiter.decorateCompletionStage(timeLimiter, scheduler, supplier).get(); Try<Integer> decoratedResult = Try.ofCallable(() -> decorated.toCompletableFuture().get()); assertThat(decoratedResult.isFailure()).isTrue(); assertThat(decoratedResult.getCause()).isInstanceOf(ExecutionException.class) .hasCauseExactlyInstanceOf(TimeoutException.class); }
Source:
<code>public void testAssetsToImport() throws Exception { final String PAGE_ID = "page"; final String DS_CSV = "ds.csv"; final String DS = "ds.dset"; final String DS_CONTENT = "TEST_CONTENT"; final String DS_NAME = "test_dataset"; final String PAGE = PAGE_ID + "/perspective_layout"; final String PAGE_PLUGIN = PAGE_ID + "/perspective_layout.plugin"; DataSetDef dataSetDef = mock(DataSetDef.class); when(dataSetDef.isPublic()).thenReturn(true); when(dataSetDef.getName()).thenReturn(DS_NAME); when(dataSetDefJSONMarshaller.fromJson(DS_CONTENT)).thenReturn(dataSetDef); createFile(datasetsFS, DS, DS_CONTENT); createFile(datasetsFS, DS_CSV, ""); createFile(perspectivesFS, PAGE, ""); createFile(perspectivesFS, PAGE_PLUGIN, ""); <START> ExportInfo assetsToExport = dataTransferServices.exportInfo(); <END> assertEquals(1, assetsToExport.getDatasetsDefinitions().size()); assertEquals(DS_NAME, assetsToExport.getDatasetsDefinitions().get(0).getName()); assertEquals(1, assetsToExport.getPages().size()); assertEquals(PAGE_ID, assetsToExport.getPages().get(0)); cleanFileSystems(); }</code><technical_language>suggestion ExportInfo exportInfo = dataTransferServices.exportInfo();</technical_language>

Target:
public void testAssetsToImport() throws Exception { final String PAGE_ID = "page"; final String DS_CSV = "ds.csv"; final String DS = "ds.dset"; final String DS_CONTENT = "TEST_CONTENT"; final String DS_NAME = "test_dataset"; final String PAGE = PAGE_ID + "/perspective_layout"; final String PAGE_PLUGIN = PAGE_ID + "/perspective_layout.plugin"; DataSetDef dataSetDef = mock(DataSetDef.class); when(dataSetDef.isPublic()).thenReturn(true); when(dataSetDef.getName()).thenReturn(DS_NAME); when(dataSetDefJSONMarshaller.fromJson(DS_CONTENT)).thenReturn(dataSetDef); createFile(datasetsFS, DS, DS_CONTENT); createFile(datasetsFS, DS_CSV, ""); createFile(perspectivesFS, PAGE, ""); createFile(perspectivesFS, PAGE_PLUGIN, ""); ExportInfo exportInfo = dataTransferServices.exportInfo(); assertEquals(1, exportInfo.getDatasetsDefinitions().size()); assertEquals(DS_NAME, exportInfo.getDatasetsDefinitions().get(0).getName()); assertEquals(1, exportInfo.getPages().size()); assertEquals(PAGE_ID, exportInfo.getPages().get(0)); cleanFileSystems(); }
Source:
<code>public StateItem(RGB stateColor, String stateString) { fStyleMap = new HashMap<>(); fReadOnlyStyleMap = Collections.unmodifiableMap(fStyleMap); fStyleMap.put(ITimeEventStyleStrings.fillStyle(), ITimeEventStyleStrings.solidColorFillStyle()); <START> fStyleMap.put(ITimeEventStyleStrings.fillColor(), stateColor); <END> fStyleMap.put(ITimeEventStyleStrings.label(), stateString); }</code><technical_language>Yes, I prefer API other patch. I guess leave for now, other patch in soonish</technical_language>

Target:
public StateItem(RGB stateColor, String stateString) { int stateColorInt = stateColor.red << 24 | stateColor.green << 16 | stateColor.blue << 8 | 0xff; fStyleMap = new HashMap<>(); fReadOnlyStyleMap = Collections.unmodifiableMap(fStyleMap); fStyleMap.put(ITimeEventStyleStrings.fillStyle(), ITimeEventStyleStrings.solidColorFillStyle()); fStyleMap.put(ITimeEventStyleStrings.fillColor(), stateColorInt); fStyleMap.put(ITimeEventStyleStrings.label(), stateString); }
Source:
<code>private static boolean validateRemote(String node, String target, String name, CommandLine cmd) throws InterruptedException { System.out.format("Validating %s environment on %s...%n", target, node); if (!CommonUtils.isAddressReachable(node, 22)) { System.err.format("Unable to reach ssh port 22 on node %s.%n", node); return false; } String argStr = String.join(" ", cmd.getArgs()); <START> String homeDir = InstancedConfiguration.defaults().get(PropertyKey.HOME); <END> String remoteCommand = String.format( "%s/bin/alluxio validateEnv %s %s %s", homeDir, target, name == null ? "" : name, argStr); String localCommand = String.format( "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand); String[] command = {"bash", "-c", localCommand}; try { ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); builder.redirectOutput(ProcessBuilder.Redirect.INHERIT); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); Process process = builder.start(); process.waitFor(); return process.exitValue() == 0; } catch (IOException e) { System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage()); return false; } }</code><technical_language>pass in conf object</technical_language>

Target:
private static boolean validateRemote(String node, String target, String name, CommandLine cmd) throws InterruptedException { System.out.format("Validating %s environment on %s...%n", target, node); if (!CommonUtils.isAddressReachable(node, 22)) { System.err.format("Unable to reach ssh port 22 on node %s.%n", node); return false; } String argStr = String.join(" ", cmd.getArgs()); String homeDir = CONF.get(PropertyKey.HOME); String remoteCommand = String.format( "%s/bin/alluxio validateEnv %s %s %s", homeDir, target, name == null ? "" : name, argStr); String localCommand = String.format( "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand); String[] command = {"bash", "-c", localCommand}; try { ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); builder.redirectOutput(ProcessBuilder.Redirect.INHERIT); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); Process process = builder.start(); process.waitFor(); return process.exitValue() == 0; } catch (IOException e) { System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage()); return false; } }
Source:
<code>public OperatorImplGraph(StreamGraphImpl streamGraph, Config config, TaskContext context, Clock clock) { this.clock = clock; TaskContextImpl taskContext = (TaskContextImpl) context; Map<SystemStream, Integer> producerTaskCounts = hasIntermediateStreams(streamGraph) ? getProducerTaskCountForIntermediateStreams(getStreamToConsumerTasks(taskContext.getJobModel()), getIntermediateToInputStreams(streamGraph)) : Collections.EMPTY_MAP; producerTaskCounts.forEach((stream, count) -> { LOG.info("{} has producer tasks.", stream, count); }); <START> taskContext.registerObject(EndOfStreamStates.class.getName(), <END> new EndOfStreamStates(context.getSystemStreamPartitions(), producerTaskCounts)); taskContext.registerObject(WatermarkStates.class.getName(), new WatermarkStates(context.getSystemStreamPartitions(), producerTaskCounts)); streamGraph.getInputOperators().forEach((streamSpec, inputOpSpec) -> { SystemStream systemStream = new SystemStream(streamSpec.getSystemName(), streamSpec.getPhysicalName()); InputOperatorImpl inputOperatorImpl = (InputOperatorImpl) createAndRegisterOperatorImpl(null, inputOpSpec, config, context); this.inputOperators.put(systemStream, inputOperatorImpl); }); }</code><technical_language>EOS states watermark states in taskContext potentially shared multiple threads in async model? nice thread-safe</technical_language>

Target:
public OperatorImplGraph(StreamGraphImpl streamGraph, Config config, TaskContext context, Clock clock) { this.clock = clock; TaskContextImpl taskContext = (TaskContextImpl) context; Map<SystemStream, Integer> producerTaskCounts = hasIntermediateStreams(streamGraph) ? getProducerTaskCountForIntermediateStreams(getStreamToConsumerTasks(taskContext.getJobModel()), getIntermediateToInputStreamsMap(streamGraph)) : Collections.EMPTY_MAP; producerTaskCounts.forEach((stream, count) -> { LOG.info("{} has producer tasks.", stream, count); }); taskContext.registerObject(EndOfStreamStates.class.getName(), new EndOfStreamStates(context.getSystemStreamPartitions(), producerTaskCounts)); taskContext.registerObject(WatermarkStates.class.getName(), new WatermarkStates(context.getSystemStreamPartitions(), producerTaskCounts)); streamGraph.getInputOperators().forEach((streamSpec, inputOpSpec) -> { SystemStream systemStream = new SystemStream(streamSpec.getSystemName(), streamSpec.getPhysicalName()); InputOperatorImpl inputOperatorImpl = (InputOperatorImpl) createAndRegisterOperatorImpl(null, inputOpSpec, systemStream, config, context); this.inputOperators.put(systemStream, inputOperatorImpl); }); }
Source:
<code><START> public void tearDownDocker() { <END> tdc.killAndRemoveContainer(); }</code><technical_language>is this method executed</technical_language>

Target:
public void tearDownDocker() throws Exception { client.killAndRemoveContainer(); }
Source:
<code>public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor pm) throws CoreException { preExecute(pm); IProject[] validProjects = ProjectUtil .getValidOpenProjects(repository); pm.beginTask(NLS.bind( CoreText.BranchOperation_performingBranch, target), 1); CheckoutCommand co = new Git(repository).checkout(); co.setName(target); try { co.call(); } catch (JGitInternalException e) { <START> if(e.getCause() instanceof CheckoutConflictException) { <END> return; } else { throw new CoreException(Activator.error(e.getMessage(), e)); } } catch (GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } finally { BranchOperation.this.result = co.getResult(); } if (result.getStatus() == Status.NONDELETED) retryDelete(result.getUndeletedList()); pm.worked(1); ProjectUtil.refreshValidProjects(validProjects, delete, new SubProgressMonitor(pm, 1)); pm.worked(1); postExecute(pm); pm.done(); } }; ResourcesPlugin.getWorkspace().run(action, monitor); }</code><technical_language>style nit: curly braces single line blocks CheckoutConflictException wrapped internal exception. check JGit throw API exception org.eclipse.jgit.api.errors.CheckoutConflictException instead</technical_language>

Target:
public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor pm) throws CoreException { preExecute(pm); IProject[] validProjects = ProjectUtil .getValidOpenProjects(repository); pm.beginTask(NLS.bind( CoreText.BranchOperation_performingBranch, target), 1); CheckoutCommand co = new Git(repository).checkout(); co.setName(target); try { co.call(); } catch (JGitInternalException e) { if (e.getCause() instanceof CheckoutConflictException) return; else throw new CoreException(Activator.error(e.getMessage(), e)); } catch (GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } finally { BranchOperation.this.result = co.getResult(); } if (result.getStatus() == Status.NONDELETED) retryDelete(result.getUndeletedList()); pm.worked(1); ProjectUtil.refreshValidProjects(validProjects, delete, new SubProgressMonitor(pm, 1)); pm.worked(1); postExecute(pm); pm.done(); } }; ResourcesPlugin.getWorkspace().run(action, monitor); }
Source:
<code>public Optional<ServiceInstance> getLocalInstance(String serviceName) { return Optional.ofNullable(serviceInstances.values().stream() .filter(ServiceInstance::isLocal) .filter(serviceInstance -> serviceInstance.serviceName().equals(serviceName)) .findFirst() <START> .orElse(null)); <END> }</code><technical_language>findFirst return optional, need create nullable put null in orElse</technical_language>

Target:
public Optional<ServiceInstance> getLocalInstance(String serviceName) { return serviceInstances.values().stream() .filter(ServiceInstance::isLocal) .filter(serviceInstance -> serviceInstance.serviceName().equals(serviceName)) .findFirst(); }
Source:
<code>public Integer performTask() throws Throwable { String elUrl = WikipediaApp.getInstance().getSslFailCount() < 2 ? EVENTLOG_URL : EVENTLOG_URL.replace("https", "http"); String dataURL = Uri.parse(elUrl) .buildUpon().query(data.toString()) .build().toString(); <START> Log.d(Funnel.ANALYTICS_TAG, "hitting " + dataURL); <END> return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); }</code><technical_language>If, instead of "dataURL," output "data", parameters of event line, nicely formatted</technical_language>

Target:
public Integer performTask() throws Throwable { String elUrl = WikipediaApp.getInstance().getSslFailCount() < 2 ? EVENTLOG_URL : EVENTLOG_URL.replace("https", "http"); String dataURL = Uri.parse(elUrl) .buildUpon().query(data.toString()) .build().toString(); return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); }
Source:
<code>public boolean hasTextMaxAngle() throws MBFormatException { return parse.isPropertyDefined(layout, "text-max-angle"); <START> } <END></code><technical_language>group this getTextMaxAngle is defined, easier find related methods? Also, this need public? if is protected private</technical_language>

Target:
private boolean hasTextMaxAngle() throws MBFormatException { return parse.isPropertyDefined(layout, "text-max-angle"); }
Source:
<code>private Response.ResponseBuilder calculateContentDisposition( Response.ResponseBuilder response, IAsyncReportState state ) { String extension = MimeHelper.getExtension( state.getMimeType() ); String path = state.getPath(); <START> String fileName = path.substring( path.lastIndexOf( "/" ) + 1, path.lastIndexOf( "." ) ); <END> if ( fileName == null || fileName.isEmpty() ) { fileName = "content"; } String disposition = "inline; filename*=UTF-8''" + RepositoryPathEncoder .encode( RepositoryPathEncoder.encodeRepositoryPath( fileName + extension ) ); response.header( "Content-Disposition", disposition ); response.header( "Content-Description", fileName ); return response; }</code><technical_language>Please this code safe. path a "/" "." character. If want a safe option for that, IOUtils#getFileName IOUtils#stripFileExtension libbase. contains necessary checks handle -1 index returned "lastIndexOf" in case search string is found</technical_language>

Target:
private Response.ResponseBuilder calculateContentDisposition( Response.ResponseBuilder response, IAsyncReportState state ) { org.pentaho.reporting.libraries.base.util.IOUtils utils = org.pentaho.reporting.libraries .base.util.IOUtils.getInstance(); String extension = MimeHelper.getExtension( state.getMimeType() ); String path = state.getPath(); String reportExtension = utils.stripFileExtension( path ); String fileName = utils.getFileName( path ); if ( fileName == null || fileName.isEmpty() ) { fileName = "content"; } String disposition = "inline; filename*=UTF-8''" + RepositoryPathEncoder .encode( RepositoryPathEncoder.encodeRepositoryPath( fileName + extension ) ); response.header( "Content-Disposition", disposition ); response.header( "Content-Description", fileName + reportExtension ); return response; }
Source:
<code>public void testVisitDWithin() throws Exception { <START> getRootJsonFilterNode("spatial-distance-ops", "DWithin.json").accept(visitor); <END> forElement(visitor.getResult()) .withBinding(FilterType.class) .forElement(FilterType::getSpatialOps) .withBinding(DistanceBufferType.class) .verifyExpressionOrAny(DistanceBufferType::getExpressionOrAny) .withData("anyGeo", "WKT()"); }</code><technical_language>This blow DWithin.json exist. I suspect this is build failed</technical_language>

Target:
public void testVisitDWithin() throws Exception { getRootJsonFilterNode("spatial-distance-ops", "DWithin.json").accept(visitor); forElement(visitor.getResult()) .withBinding(FilterType.class) .forElement(FilterType::getSpatialOps) .withBinding(DistanceBufferType.class) .verifyDistanceBuffer() .withDistance(123.45) .withData("anyGeo", "WKT()"); }
Source:
<code>protected Direction columnDirection(ResultSet rs) throws SQLException { Direction columnDir = getColumnDirection(rs); if (columnDir == null) { <START> throw new SQLException("Invalid column/parameter type"); <END> } return columnDir; }</code><technical_language>I column name in exception message in some of earlier drafts. OK way</technical_language>

Target:
protected Direction columnDirection(ResultSet rs) throws SQLException { return requireNonNull(getColumnDirection(rs), "Invalid type for column/parameter " + getColumnName(rs)); }
Source:
<code>public QuantityType<Time> getDuration() { if (start == null || end == null) { return null; } if (start.after(end)) { return new QuantityType<Time>(0, SmartHomeUnits.MINUTE); } long diff = end.getTimeInMillis() - start.getTimeInMillis(); <START> return new QuantityType<Time>(diff / 60000, SmartHomeUnits.MINUTE); <END> }</code><technical_language>get rid of magic number 60000 QuantityType for ms minutes conversion: java long diff = end.getTimeInMillis() - start.getTimeInMillis(); QuantityType<Time> millis = new QuantityType<>(diff, MetricPrefix.MILLI(SmartHomeUnits.SECOND)); return millis.toUnit(SmartHomeUnits.MINUTE);</technical_language>

Target:
public QuantityType<Time> getDuration() { if (start == null || end == null) { return null; } if (start.after(end)) { return new QuantityType<Time>(0, SmartHomeUnits.MINUTE); } return new QuantityType<Time>(end.getTimeInMillis() - start.getTimeInMillis(), MILLI(SmartHomeUnits.SECOND)) .toUnit(SmartHomeUnits.MINUTE); }
Source:
<code>public ContainerInfo getMatchingContainer(final long sizeRequired, String owner, Pipeline pipeline) { try { NavigableSet<ContainerID> containerIDs = pipelineManager.getContainersInPipeline(pipeline.getId()); <START> if (containerIDs == null) { <END> LOG.error("Container list is null for pipeline=", pipeline.getId()); return null; } containerIDs = getContainersForOwner(containerIDs, owner); if (containerIDs.size() < numContainerPerOwnerInPipeline) { synchronized (pipeline) { containerIDs = getContainersForOwner( pipelineManager.getContainersInPipeline(pipeline.getId()), owner); if (containerIDs.size() < numContainerPerOwnerInPipeline) { ContainerInfo containerInfo = containerStateManager.allocateContainer(pipelineManager, owner, pipeline); addContainerToDB(containerInfo); containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); return containerInfo; } } } ContainerInfo containerInfo = containerStateManager.getMatchingContainer(sizeRequired, owner, pipeline.getId(), containerIDs); if (containerInfo == null) { synchronized (pipeline) { containerInfo = containerStateManager.allocateContainer(pipelineManager, owner, pipeline); addContainerToDB(containerInfo); containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); } } else { containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); } return containerInfo; } catch (Exception e) { LOG.warn("Container allocation failed for pipeline={} requiredSize={} {}", pipeline, sizeRequired, e); return null; } }</code><technical_language>This check removed. pipelineManager.getContainersInPipeline(pipeline.getId()) return null</technical_language>

Target:
public ContainerInfo getMatchingContainer(final long sizeRequired, String owner, Pipeline pipeline) { try { NavigableSet<ContainerID> containerIDs = pipelineManager.getContainersInPipeline(pipeline.getId()); containerIDs = getContainersForOwner(containerIDs, owner); if (containerIDs.size() < numContainerPerOwnerInPipeline) { synchronized (pipeline) { containerIDs = getContainersForOwner( pipelineManager.getContainersInPipeline(pipeline.getId()), owner); if (containerIDs.size() < numContainerPerOwnerInPipeline) { ContainerInfo containerInfo = containerStateManager.allocateContainer(pipelineManager, owner, pipeline); addContainerToDB(containerInfo); containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); return containerInfo; } } } ContainerInfo containerInfo = containerStateManager.getMatchingContainer(sizeRequired, owner, pipeline.getId(), containerIDs); if (containerInfo == null) { synchronized (pipeline) { containerInfo = containerStateManager.allocateContainer(pipelineManager, owner, pipeline); addContainerToDB(containerInfo); } } containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); return containerInfo; } catch (Exception e) { LOG.warn("Container allocation failed for pipeline={} requiredSize={} {}", pipeline, sizeRequired, e); return null; } }
Source:
<code>public void testSetup() { ZkClient zkClient = new ZkClient(testZkConnectionString, ZkConfig.DEFAULT_SESSION_TIMEOUT_MS, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS); <START> ZkJobCoordinatorMetrics metrics = new ZkJobCoordinatorMetrics(new MetricsRegistryMap()); <END> this.zkUtils = new ZkUtils(new ZkKeyBuilder("group1"), zkClient, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS, metrics); ZkClient zkClient1 = new ZkClient(testZkConnectionString, ZkConfig.DEFAULT_SESSION_TIMEOUT_MS, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS); this.zkUtils1 = new ZkUtils(new ZkKeyBuilder("group1"), zkClient1, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS, metrics); }</code><technical_language>new NoOpMetricsRegistry() if assert metrics</technical_language>

Target:
public void testSetup() { ZkClient zkClient = new ZkClient(testZkConnectionString, ZkConfig.DEFAULT_SESSION_TIMEOUT_MS, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS); this.zkUtils = new ZkUtils(new ZkKeyBuilder("group1"), zkClient, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS, new ZkJobCoordinatorMetrics(new NoOpMetricsRegistry())); ZkClient zkClient1 = new ZkClient(testZkConnectionString, ZkConfig.DEFAULT_SESSION_TIMEOUT_MS, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS); this.zkUtils1 = new ZkUtils(new ZkKeyBuilder("group1"), zkClient1, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS, new ZkJobCoordinatorMetrics(new NoOpMetricsRegistry())); }
Source:
<code>protected TypedString(String name) { <START> this.name = ArgChecker.notNull(name, "name"); <END> }</code><technical_language>this check for empty strings too</technical_language>

Target:
protected TypedString(String name) { this.name = ArgChecker.notEmpty(name, "name"); }
Source:
<code>@Override public boolean isSampled(long ignoredTraceId) { long now = System.nanoTime(); long updateAt = nextReset.get(); long nanosUntilReset = -(now - updateAt); if (nanosUntilReset <= 0) { <START> if (nextReset.compareAndSet(updateAt, updateAt + NANOS_PER_SECOND)) usage.set(0); <END> return isSampled(ignoredTraceId); } int max = maxFunction.max(nanosUntilReset); int prev, next; do { prev = usage.get(); next = prev + 1; if (next > max) return false; } while (!usage.compareAndSet(prev, next)); return true; }</code><technical_language>hole I is adding updateAt, sampler is long lived sampling decisions in seconds......it sample 100% updateAt caught up. forked added + -(nanosUntilReset) in addition NANOS_PER_SECOND update updateAt. push for somebody's taste, cured 100% sampling in implementation</technical_language>

Target:
@Override public boolean isSampled(long ignoredTraceId) { long now = System.nanoTime(); long updateAt = nextReset.get(); long nanosUntilReset = -(now - updateAt); if (nanosUntilReset <= 0) { if (nextReset.compareAndSet(updateAt, now + NANOS_PER_SECOND)) usage.set(0); return isSampled(ignoredTraceId); } int max = maxFunction.max(nanosUntilReset); int prev, next; do { prev = usage.get(); next = prev + 1; if (next > max) return false; } while (!usage.compareAndSet(prev, next)); return true; }
Source:
<code>private boolean hasEntryPoint(final Pattern52 pattern) { <START> return pattern.getEntryPointName() != null && !pattern.getEntryPointName().trim().isEmpty(); <END> }</code><technical_language>org.drools.core.util.StringUtils for implementation</technical_language>

Target:
private boolean hasEntryPoint(final Pattern52 pattern) { return !StringUtils.isEmpty(pattern.getEntryPointName()); }
Source:
<code>public void updateUseHostCpuAvailability() { boolean clusterSupportsHostCpu = getCompatibilityVersion() != null; boolean nonMigratable = MigrationSupport.PINNED_TO_HOST == getModel().getMigrationMode().getSelectedItem(); boolean usingPpcArch = hostHasPpcArchitecture(); if (clusterSupportsHostCpu && nonMigratable && <START> !usingPpcArch) { <END> getModel().getHostCpu().setIsChangeable(true); } else { getModel().getHostCpu().setEntity(false); getModel().getHostCpu().setChangeProhibitionReason(constants.hosCPUUnavailable()); getModel().getHostCpu().setIsChangeable(false); } }</code><technical_language>inline it? a here, is this for readability</technical_language>

Target:
public void updateUseHostCpuAvailability() { boolean clusterSupportsHostCpu = getCompatibilityVersion() != null; boolean nonMigratable = MigrationSupport.PINNED_TO_HOST == getModel().getMigrationMode().getSelectedItem(); if (clusterSupportsHostCpu && nonMigratable && !clusterHasPpcArchitecture()) { getModel().getHostCpu().setIsChangeable(true); } else { getModel().getHostCpu().setEntity(false); getModel().getHostCpu().setChangeProhibitionReason(constants.hosCPUUnavailable()); getModel().getHostCpu().setIsChangeable(false); } }
Source:
<code>private void populate() { final VBox toolsPane = new VBox(); final Text title = new TextWithStyle(tr("Tools"), TITLE_CSS_CLASS); toolsPane.getStyleClass().add(CONFIGURATION_PANE_CSS_CLASS); toolsPane.getChildren().add(title); final TilePane toolsContentPane = new TilePane(); toolsContentPane.setPrefColumns(3); toolsContentPane.getStyleClass().add("grid"); Button runExecutable = new Button(tr("Run executable")); runExecutable.getStyleClass().addAll("toolButton", "runExecutable"); runExecutable.setOnMouseClicked(event -> { this.lockAll(); FileChooser fileChooser = new FileChooser(); <START> fileChooser.setTitle(tr("Choose executable…")); <END> File containerDir = new File(this.container.getPath()); if (containerDir.canRead()) { fileChooser.setInitialDirectory(containerDir); } File file = fileChooser.showOpenDialog(this.getContent().getScene().getWindow()); if (file != null) { containerEngineController.runInContainer(container, file.getAbsolutePath(), this::unlockAll, e -> Platform.runLater(() -> new ErrorMessage("Error", e).show())); } else { this.unlockAll(); } }); this.lockableElements.add(runExecutable); toolsContentPane.getChildren().add(runExecutable); toolsPane.getChildren().addAll(toolsContentPane); this.setContent(toolsPane); }</code><technical_language>3 dot symbol instead of 3 dots. please 3 dots consistent scripts a new issue for this topic I below</technical_language>

Target:
private void populate() { final VBox toolsPane = new VBox(); final Text title = new TextWithStyle(tr("Tools"), TITLE_CSS_CLASS); toolsPane.getStyleClass().add(CONFIGURATION_PANE_CSS_CLASS); toolsPane.getChildren().add(title); final TilePane toolsContentPane = new TilePane(); toolsContentPane.setPrefColumns(3); toolsContentPane.getStyleClass().add("grid"); Button runExecutable = new Button(tr("Run executable")); runExecutable.getStyleClass().addAll("toolButton", "runExecutable"); runExecutable.setOnMouseClicked(event -> { this.lockAll(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(tr("Choose executable ...")); File containerDir = new File(this.container.getPath()); if (containerDir.canRead()) { fileChooser.setInitialDirectory(containerDir); } File file = fileChooser.showOpenDialog(this.getContent().getScene().getWindow()); if (file != null) { containerEngineController.runInContainer(container, file.getAbsolutePath(), this::unlockAll, e -> Platform.runLater(() -> new ErrorMessage("Error", e).show())); } else { this.unlockAll(); } }); this.lockableElements.add(runExecutable); toolsContentPane.getChildren().add(runExecutable); toolsPane.getChildren().addAll(toolsContentPane); this.setContent(toolsPane); }
Source:
<code>private int getNumOfPrestartedVmsInPool(VmPool pool) { <START> List<VM> vmsInPool = getVmDao().getAllForVmPool(pool.getVmPoolId()); END> return vmsInPool == null ? 0 : vmsInPool.stream() .filter(vm -> vm.isStartingOrUp() && vmPoolHandler.isPrestartedVmFree(vm.getId(), pool.isStateful(), null)) .collect(Collectors.counting()) .intValue(); }</code><technical_language>worth consider a query vms_monitoring_view (TODO)</technical_language>

Target:
private int getNumOfPrestartedVmsInPool(VmPool pool) { List<VM> vmsInPool = vmDao.getAllForVmPool(pool.getVmPoolId()); return vmsInPool == null ? 0 : vmsInPool.stream() .filter(vm -> vm.isStartingOrUp() && vmPoolHandler.isPrestartedVmFree(vm.getId(), pool.isStateful(), null)) .collect(Collectors.counting()) .intValue(); }
Source:
<code>public List<Role> getRoles(final RoleSearchDto roleSearchDto) { final List<Role> toReturn; try { final Criteria criteria = this.getSession().createCriteria(Role.class); if (roleSearchDto != null) { if (roleSearchDto.getRoleIds() != null && !roleSearchDto.getRoleIds().isEmpty()) { criteria.add(Restrictions.in("id", roleSearchDto.getRoleIds())); } if (roleSearchDto.getAssignable() != null) { criteria.add(Restrictions.eq("assignable", roleSearchDto.getAssignable())); } if (roleSearchDto.getRoleTypeId() != null) { criteria.createAlias("roleType", "roleType"); criteria.add(Restrictions.eq("roleType.id", roleSearchDto.getRoleTypeId())); } <START> if(roleSearchDto.getName() != null && StringUtils.isNotBlank(roleSearchDto.getName())) { <END> criteria.add(Restrictions.eq("name", roleSearchDto.getName())); } if(roleSearchDto.getDescription() != null && StringUtils.isNotBlank(roleSearchDto.getDescription())) { criteria.add(Restrictions.eq("description", roleSearchDto.getDescription())); } } criteria.addOrder(Order.asc("id")); toReturn = criteria.list(); } catch (final HibernateException e) { final String message = "Error with getRoles query from RoleDAO: " + e.getMessage(); RoleDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return toReturn; }</code><technical_language>isNotBlank checks for null</technical_language>

Target:
public List<Role> getRoles(final RoleSearchDto roleSearchDto) { final List<Role> toReturn; try { final Criteria criteria = this.getSession().createCriteria(Role.class); if (roleSearchDto != null) { if (roleSearchDto.getRoleIds() != null && !roleSearchDto.getRoleIds().isEmpty()) { criteria.add(Restrictions.in("id", roleSearchDto.getRoleIds())); } if (roleSearchDto.getAssignable() != null) { criteria.add(Restrictions.eq("assignable", roleSearchDto.getAssignable())); } if (roleSearchDto.getRoleTypeId() != null) { criteria.createAlias("roleType", "roleType"); criteria.add(Restrictions.eq("roleType.id", roleSearchDto.getRoleTypeId())); } if (StringUtils.isNotBlank(roleSearchDto.getName())) { criteria.add(Restrictions.eq("name", roleSearchDto.getName())); } } criteria.addOrder(Order.asc("id")); toReturn = criteria.list(); } catch (final HibernateException e) { final String message = "Error with getRoles query from RoleDAO: " + e.getMessage(); RoleDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return toReturn; }
Source:
<code>public void onNext(final RunningTask runningTask) { LOG.log(Level.INFO, "Task {0} is running", runningTask.getId()); <START> taskSelector.addRunningTask(runningTask); <END> }</code><technical_language>taskSelector.addRunningTask sounds a bit strange</technical_language>

Target:
public void onNext(final RunningTask runningTask) { LOG.log(Level.INFO, "Task {0} is running", runningTask.getId()); taskSelector.registerRunningTask(runningTask); }
Source:
<code>public SettingsDto(String host, String port, String user, String password, Properties additionalProperties, String logAddress, String logSubject, String logBody, String logPurgeEnable, String logPurgeTime, String logPurgeTimeMultiplier) { this.host = host; this.port = port; this.username = user; this.password = password; Map<String, String> props = new HashMap<>(); <START> for (Entry<Object, Object> entry : additionalProperties.entrySet()) { <END> props.put((String) entry.getKey(), (String) entry.getValue()); } this.additionalProperties = props; this.logAddress = logAddress; this.logSubject = logSubject; this.logBody = logBody; this.logPurgeEnable = logPurgeEnable; this.logPurgeTime = logPurgeTime; this.logPurgeTimeMultiplier = logPurgeTimeMultiplier; }</code><technical_language>NPE additionalProperties is null; refactor of constructors invoke more complex constructor set actual values</technical_language>

Target:
public SettingsDto(String host, String port, String user, String password, Properties additionalProperties, String logAddress, String logSubject, String logBody, String logPurgeEnable, String logPurgeTime, String logPurgeTimeMultiplier) { this(host, port, user, password, new HashMap<String, String>(), logAddress, logSubject, logBody, logPurgeEnable, logPurgeTime, logPurgeTimeMultiplier); if (additionalProperties != null) { for (Entry<Object, Object> entry : additionalProperties.entrySet()) { this.additionalProperties.put((String) entry.getKey(), (String) entry.getValue()); } } }
Source:
<code>public Response(int status, String reason, List<Header> headers, byte[] body) { if (status < 100) { throw new IllegalArgumentException("Invalid status code: " + status); } if (reason == null) { throw new IllegalArgumentException("Reason must not be null."); } if (headers == null) { throw new IllegalArgumentException("Headers must not be null."); } if (body == null) { <START> throw new IllegalArgumentException("Body must not be null."); <END> } this.body = body; this.status = status; this.reason = reason; this.headers = Collections.unmodifiableList(headers); }</code><technical_language>curious, support @HEAD</technical_language>

Target:
public Response(int status, String reason, List<Header> headers, byte[] body) { if (status < 200) { throw new IllegalArgumentException("Invalid status code: " + status); } if (reason == null) { throw new IllegalArgumentException("reason == null"); } if (headers == null) { throw new IllegalArgumentException("headers == null"); } this.status = status; this.reason = reason; this.headers = Collections.unmodifiableList(new ArrayList<Header>(headers)); this.body = body; }
Source:
<code>static double minSizeRequiredToRespectSpacing(final double spacing, final double firstRatio, final double secondRatio) { assert secondRatio >= firstRatio; <START> if (secondRatio - firstRatio == 0) { <END> return 0; } else { return (spacing) / (secondRatio - firstRatio); } }</code><technical_language>fuzzy equal</technical_language>

Target:
static double minSizeRequiredToRespectSpacing(final double spacing, final double firstRatio, final double secondRatio) { assert secondRatio >= firstRatio; if (DoubleMath.fuzzyEquals(firstRatio, secondRatio, EQUALITY_TOLERANCE)) { return 0; } else { return spacing / (secondRatio - firstRatio); } }
Source:
<code>public void setValue(final Boolean value, final boolean fireEvents) { <START> if (isAttached()) { <END> switchState(getElement(), value, true); } else { onChange(value, fireEvents); } }</code><technical_language>I revert changes below. implementation is correct here: - first, attaching DOM, fireEvents is account. original implementation is do want - second, original onChange(boolean value) implementation is called in: private native void switchInit(Element e) /*-{ $wnd.jQuery(e).bootstrapSwitch(); var = this; $wnd.jQuery(e).on('switchChange.bootstrapSwitch', function (em, state) { me.@org.gwtbootstrap3.extras.toggleswitch.client.ui.base.ToggleSwitchBase::onChange(Z)(state); }); }-*/; change event is fired user switch in GUI. call ValueChangeEvent.fireIfNotEqual, ValueChangeEvent.fire. Here, need is supposed compare new one. want set toggle switch's programmatically calling switchState(Element e, boolean value, boolean skip) method, control change event fired 3rd argument skip. original implementation (on left side) correct. do nothing</technical_language>

Target:
public void setValue(final Boolean value, final boolean fireEvents) { Boolean oldValue = getValue(); if (isAttached()) { switchState(getElement(), value, true); } else { element.setChecked(value); } if (fireEvents) { ValueChangeEvent.fireIfNotEqual(ToggleSwitchBase.this, oldValue, value); } }
Source:
<code>public void testNestedNonTerminals3() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, new Grammar.State.OrderingInfo(0), stiend, new Grammar.State.OrderingInfo(100)); Grammar.RegExState resx = new Grammar.RegExState(new Grammar.StateId("RegExStidx"), nt1, new Grammar.State.OrderingInfo(1), Pattern.compile("x")); Grammar.NonTerminalState nts = new Grammar.NonTerminalState(new Grammar.StateId("NT"), nt1, new Grammar.State.OrderingInfo(2), nt1, false); nt1.entryState.next.add(resx); nt1.entryState.next.add(nt1.exitState); resx.next.add(nts); nts.next.add(nt1.exitState); { Term result = new Parser(new ParseState("")).parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); assertEquals("EmtpyString check: ", expected, result); } { Term result = new Parser(new ParseState("xx")).parse(nt1, 0); Term expected = amb(klist(amb(klist(Token.kAppOf("K", "x"), amb(klist(Token.kAppOf("K", "x"), amb(KList.EMPTY))))))); assertEquals("x^n check: ", expected, result); } <START> assertEquals("Expected Nullable NTs", 1, NullabilityCheck.getReachableNullableNT(nt1).size()); <END> }</code><technical_language>Please assert nullable nonterminal is</technical_language>

Target:
public void testNestedNonTerminals3() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, new Grammar.State.OrderingInfo(0), stiend, new Grammar.State.OrderingInfo(100)); Grammar.RegExState resx = new Grammar.RegExState(new Grammar.StateId("RegExStidx"), nt1, new Grammar.State.OrderingInfo(1), Pattern.compile("x")); Grammar.NonTerminalState nts = new Grammar.NonTerminalState(new Grammar.StateId("NT"), nt1, new Grammar.State.OrderingInfo(2), nt1, false); nt1.entryState.next.add(resx); nt1.entryState.next.add(nt1.exitState); resx.next.add(nts); nts.next.add(nt1.exitState); { Term result = new Parser(new ParseState("")).parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); Assert.assertEquals("EmtpyString check: ", expected, result); } { Term result = new Parser(new ParseState("xx")).parse(nt1, 0); Term expected = amb(klist(amb(klist(Token.kAppOf("K", "x"), amb(klist(Token.kAppOf("K", "x"), amb(KList.EMPTY))))))); Assert.assertEquals("x^n check: ", expected, result); } Assert.assertEquals("Expected Nullable NTs", nt1, NullabilityCheck.getReachableNullableNT(nt1).iterator().next()); }
Source:
<code>public void removeMember(Patient patient) { List<CohortMembership> memberToRemoveList = getMembers().stream() .filter(m -> m.getPatient() == patient).collect(Collectors.toList()); <START> memberToRemoveList.forEach(this::removeMembership); <END> }</code><technical_language>Remove member mark matching membership voided, need set voided, voidedBy, dateVoided voidReason, remove methods in Cohort CohortService optional reason argument</technical_language>

Target:
public void removeMember(Patient patient) { List<CohortMembership> memberToRemoveList = getMembers().stream() .filter(m -> m.getPatient().getPatientId().equals(patient.getPatientId())).collect(Collectors.toList()); memberToRemoveList.forEach(m -> m.setEndDate(new Date())); }
Source:
<code><START> private boolean hasCharacteristic(int characteristics, int characteristic) { <END> return (characteristics & characteristic) == characteristic; }</code><technical_language>static</technical_language>

Target:
private static boolean hasCharacteristic(int characteristics, int characteristic) { return (characteristics & characteristic) == characteristic; }
Source:
<code>protected static Method getMethod(Class<?> clz, String name, Object value) throws NoSuchMethodException { Method method = null; try { method = getMethod(clz, name); } catch (NoSuchMethodException nsme) { <START> method = clz.getMethod("is" + name); <END> } return method; }</code><technical_language>method starts 'is' bool</technical_language>

Target:
protected static Method getMethod(Class<?> clz, String name, Object value) throws NoSuchMethodException { Method method = null; try { method = getMethod(clz, name); } catch (NoSuchMethodException nsme) { if (Boolean.class.equals(value.getClass())) { method = clz.getMethod("is" + name); } else { throw nsme; } } return method; }
Source:
<code>public List<String> getIndices(ElasticsearchTableDescription tableDescription) { if (tableDescription.getIndexExactMatch()) { return ImmutableList.of(tableDescription.getIndex()); } TransportClient client = clients.get(tableDescription.getClusterName()); <START> verify(client != null, "TransportClient should not be null"); <END> String[] indices = client.admin() .indices() .getIndex(new GetIndexRequest()) .actionGet(timeout.toMillis()) .getIndices(); return Arrays.stream(indices) .filter(index -> index.startsWith(tableDescription.getIndex())) .collect(toImmutableList()); }</code><technical_language>TransportClient is null</technical_language>

Target:
public List<String> getIndices(ElasticsearchTableDescription tableDescription) { if (tableDescription.getIndexExactMatch()) { return ImmutableList.of(tableDescription.getIndex()); } TransportClient client = clients.get(tableDescription.getClusterName()); verify(client != null, "client is null"); String[] indices = client.admin() .indices() .getIndex(new GetIndexRequest()) .actionGet(timeout.toMillis()) .getIndices(); return Arrays.stream(indices) .filter(index -> index.startsWith(tableDescription.getIndex())) .collect(toImmutableList()); }
Source:
<code>public void before() { commandUp = spy(new CommandUp()); reset(commandUp); <START> when(commandUp.execute()).thenReturn(mock(MesosCluster.class)); <END> commandDestroy = spy(new CommandDestroy()); reset(commandDestroy); doNothing().when(commandDestroy).execute(); commandInfo = spy(new CommandInfo()); reset(commandInfo); doNothing().when(commandInfo).execute(); commandState = spy(new CommandState()); reset(commandState); doNothing().when(commandState).execute(); commandInstall = spy(new CommandInstall()); reset(commandInstall); doNothing().when(commandInstall).execute(); main = new Main(); main.setCommandUp(commandUp); main.setCommandDestroy(commandDestroy); main.setCommandInfo(commandInfo); main.setCommandState(commandState); main.setCommandInstall(commandInstall); main.setCommandHelp(new CommandHelp()); }</code><technical_language>I mocks for introducing unit test for legacy code only, this line is wrong: commandUp.execute() is invoked result in passed when(). replaced doReturn(mock(MesosCluster.class)).when(commandUp).execute();</technical_language>

Target:
public void before() { outputStream = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(outputStream, true); commandUp = spy(new CommandUp()); doReturn(mock(MesosCluster.class)).when(commandUp).execute(); commandDestroy = spy(new CommandDestroy()); doNothing().when(commandDestroy).execute(); commandInfo = spy(new CommandInfo(ps)); doNothing().when(commandInfo).execute(); commandState = spy(new CommandState(ps)); doNothing().when(commandState).execute(); commandInstall = spy(new CommandInstall()); doNothing().when(commandInstall).execute(); main = new Main(); main.setOutput(ps); main.setCommandUp(commandUp); main.setCommandDestroy(commandDestroy); main.setCommandInfo(commandInfo); main.setCommandState(commandState); main.setCommandInstall(commandInstall); main.setCommandHelp(new CommandHelp()); }