auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<String, Object> visualize( ControlFlowGraph cfg, Block entry, @Nullable Analysis<V, S, T> analysis) { <START> String stringGraph = visualizeGraph(cfg, entry, analysis).trim(); <END> Map<String, Object> res = new HashMap<>(); res.put("stringGraph", stringGraph); return res; }</code><technical_language>hard track trailing spaces coming output proper construction</technical_language>

Target:
public Map<String, Object> visualize( ControlFlowGraph cfg, Block entry, @Nullable Analysis<V, S, T> analysis) { String stringGraph = visualizeGraph(cfg, entry, analysis); Map<String, Object> res = new HashMap<>(); res.put("stringGraph", stringGraph); return res; }
Source:
<code>private void doBatchWork(BatchBackend backend) throws InterruptedException { <START> ExecutorService executor = Executors.newFixedThreadPool( batchIndexingThreads, "BatchIndexingWorkspace" ); <END> for ( Class<?> type : rootEntities ) { executor.execute( new BatchIndexingWorkspace( searchFactoryImplementor, sessionFactory, type, objectLoadingThreads, collectionLoadingThreads, cacheMode, objectLoadingBatchSize, endAllSignal, monitor, backend, objectsLimit, idFetchSize ) ); } executor.shutdown(); endAllSignal.await(); }</code><technical_language>extra-defensive apply a Math.min( batchIndexingThreads, rootEntities.length) check for upper boundary of user parameter</technical_language>

Target:
private void doBatchWork(BatchBackend backend) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool( typesToIndexInParallel, "BatchIndexingWorkspace" ); for ( Class<?> type : rootEntities ) { executor.execute( new BatchIndexingWorkspace( searchFactoryImplementor, sessionFactory, type, objectLoadingThreads, collectionLoadingThreads, cacheMode, objectLoadingBatchSize, endAllSignal, monitor, backend, objectsLimit, idFetchSize ) ); } executor.shutdown(); endAllSignal.await(); }
Source:
<code>public void activate() { VDS vds = null; boolean cpuFlagsChanged = false; try { if (log.isDebugEnabled()) { log.debugFormat( "ResourceManager::activateVds - trying to activate host {0} , meanwhile setting status to Unassigned meanwhile", getVdsId()); } vds = DbFacade.getInstance().getVdsDAO().get(getVdsId()); RefObject<Boolean> tempRefObject = new RefObject<Boolean>(cpuFlagsChanged); VDSStatus newStatus = refreshCapabilities(tempRefObject, vds); if (log.isDebugEnabled()) { log.debugFormat( "ResourceManager::activateVds - success to refreshCapabilities for host {0} , new status will be {1} ", getVdsId(), newStatus); } cpuFlagsChanged = tempRefObject.argvalue; } catch (java.lang.Exception e) { log.infoFormat("ResourceManager::activateVds - failed to get VDS = {0} capabilities with error: {1}.", getVdsId(), e.getMessage()); log.infoFormat("ResourceManager::activateVds - failed to activate VDS = {0}", getVdsId()); } finally { if (vds != null) { <START> UpdateDynamicData(vds.getDynamicData()); <END> if (servicePolicy.checkCpuFlags()) { ResourceManager.getInstance().getEventListener().processOnCpuFlagsChange(vds.getId()); } ResourceManager.getInstance().getEventListener().handleVdsVersion(vds.getId()); } } }</code><technical_language>CPU flags relevant for virt, in general flow</technical_language>

Target:
public void activate() { VDS vds = null; boolean cpuFlagsChanged = false; try { if (log.isDebugEnabled()) { log.debugFormat( "ResourceManager::activateVds - trying to activate host {0} , meanwhile setting status to Unassigned meanwhile", getVdsId()); } vds = DbFacade.getInstance().getVdsDAO().get(getVdsId()); RefObject<Boolean> tempRefObject = new RefObject<Boolean>(cpuFlagsChanged); VDSStatus newStatus = refreshCapabilities(tempRefObject, vds); if (log.isDebugEnabled()) { log.debugFormat( "ResourceManager::activateVds - success to refreshCapabilities for host {0} , new status will be {1} ", getVdsId(), newStatus); } cpuFlagsChanged = tempRefObject.argvalue; } catch (java.lang.Exception e) { log.infoFormat("ResourceManager::activateVds - failed to get VDS = {0} capabilities with error: {1}.", getVdsId(), e.getMessage()); log.infoFormat("ResourceManager::activateVds - failed to activate VDS = {0}", getVdsId()); } finally { if (vds != null) { UpdateDynamicData(vds.getDynamicData()); if (monitoringStrategy.shouldTestSpecialHardwareCapabilities()) { ResourceManager.getInstance().getEventListener().processOnCpuFlagsChange(vds.getId()); } ResourceManager.getInstance().getEventListener().handleVdsVersion(vds.getId()); } } }
Source:
<code>public String toString() { return toStringHelper(this) <START> .add("path", relativeUri) <END> .add("start", start) .add("end", end) .add("fileSize", fileSize) .toString(); }</code><technical_language>convert string here</technical_language>

Target:
public String toString() { return toStringHelper(this) .add("relativeUri", new String(relativeUri, UTF_8)) .add("start", start) .add("end", end) .add("fileSize", fileSize) .toString(); }
Source:
<code>public static Package buildPackageFromTemplate() { try { ClassLoader classLoader = PackageExtension.class.getClassLoader(); <START> File file = new File(classLoader.getResource(DATAPAAKCAGE_TEMPLATE_FILE).getFile()); <END> return new Package(FileUtils.readFileToString(file), false); } catch (ValidationException e) { logger.error("validation failed", ExceptionUtils.getStackTrace(e)); } catch (DataPackageException e) { logger.error("DataPackage Exception", ExceptionUtils.getStackTrace(e)); } catch (IOException e) { logger.error("IOException when build package from template", ExceptionUtils.getStackTrace(e)); } return null; }</code><technical_language>typo in DATAPAAKCAGE</technical_language>

Target:
public static Package buildPackageFromTemplate() { try { ClassLoader classLoader = PackageExtension.class.getClassLoader(); File file = new File(classLoader.getResource(DATAPACKAGE_TEMPLATE_FILE).getFile()); return new Package(FileUtils.readFileToString(file), false); } catch (ValidationException e) { logger.error("validation failed", ExceptionUtils.getStackTrace(e)); } catch (DataPackageException e) { logger.error("DataPackage Exception", ExceptionUtils.getStackTrace(e)); } catch (IOException e) { logger.error("IOException when build package from template", ExceptionUtils.getStackTrace(e)); } return null; }
Source:
<code>private void dispose() { fContextService.removeDebugContextListener(this); <START> fgServices.remove(fWindow); <END> fCommandUpdates.clear(); fWindow = null; }</code><technical_language>this misses synchronized block. problem, change fix too</technical_language>

Target:
private void dispose() { fContextService.removeDebugContextListener(this); synchronized (fgServices) { fgServices.remove(fWindow); } fCommandUpdates.clear(); fWindow = null; }
Source:
<code>public void shutdown() { <START> Optional.ofNullable(heartbeatScheduler.get()).ifPresent(Scheduler::stop); <END> }</code><technical_language>big is chance heartbeatScheduler AtomicReference returns null? cover for logging throwing exception</technical_language>

Target:
public void shutdown() { heartbeatMonitor().shutdown(); }
Source:
<code>public CloseableSpliterator<E> spliterator() { <START> return null; <END> }</code><technical_language>Closeables class implement this</technical_language>

Target:
public CloseableSpliterator<E> spliterator() { return Closeables.spliterator(set.spliterator()); }
Source:
<code>protected void executeCommand() { <START> GlusterVolumeEntity volume = getGlusterVolumeDao().getById(volumeId); <END> VDSReturnValue retVal = runVdsCommand(VDSCommandType.CreateGlusterVolumeSnapshot, new GlusterVolumeCreateSnapshotVDSParameters(upServer.getId(), volume.getName(), snapshot.getSnapshotName(), snapshot.getDescription(), force)); setSucceeded(retVal.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_SNAPSHOT_CREATE_FAILED, retVal.getVdsError().getMessage()); } else { GlusterVolumeSnapshotEntity createdSnapshot = getParameters().getSnapshot(); createdSnapshot.setSnapshotId(((GlusterVolumeSnapshotEntity) retVal.getReturnValue()).getSnapshotId()); createdSnapshot.setCreatedAt(new Date()); createdSnapshot.setStatus(GlusterSnapshotStatus.STARTED); getDbFacade().getGlusterVolumeSnapshotDao().save(createdSnapshot); } }</code><technical_language>getGlusterVolume() super class</technical_language>

Target:
protected void executeCommand() { GlusterVolumeEntity volume = getGlusterVolume(); VDSReturnValue retVal = runVdsCommand(VDSCommandType.CreateGlusterVolumeSnapshot, new GlusterVolumeCreateSnapshotVDSParameters(upServer.getId(), volume.getName(), snapshot.getSnapshotName(), snapshot.getDescription(), force)); setSucceeded(retVal.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_SNAPSHOT_CREATE_FAILED, retVal.getVdsError().getMessage()); } else { GlusterVolumeSnapshotEntity createdSnapshot = getParameters().getSnapshot(); createdSnapshot.setSnapshotId((Guid) retVal.getReturnValue()); createdSnapshot.setStatus(GlusterSnapshotStatus.STARTED); getDbFacade().getGlusterVolumeSnapshotDao().save(createdSnapshot); } }
Source:
<code>private void init(Context context) { ((WordPress) context.getApplicationContext()).component().inject(this); if (!isInEditMode()) { mToken = mAccountStore.getAccessToken(); mReaderChromeClient = new ReaderWebChromeClient(this); this.setWebChromeClient(mReaderChromeClient); this.setWebViewClient(new ReaderWebViewClient(this)); this.getSettings().setUserAgentString(WordPress.getUserAgent()); final float fontScale = getResources().getConfiguration().fontScale; if (((int) (fontScale * 10000)) != 10000) { <START> this.getSettings().setDefaultFontSize((int) (this.getSettings().getDefaultFontSize() * fontScale)); <END> this.getSettings().setDefaultFixedFontSize( (int) (this.getSettings().getDefaultFixedFontSize() * fontScale)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().setAcceptThirdPartyCookies(this, true); } } }</code><technical_language>remove if branch here? adjusts content font size APIs 19 font scale is 1</technical_language>

Target:
private void init(Context context) { ((WordPress) context.getApplicationContext()).component().inject(this); if (!isInEditMode()) { mToken = mAccountStore.getAccessToken(); mReaderChromeClient = new ReaderWebChromeClient(this); this.setWebChromeClient(mReaderChromeClient); this.setWebViewClient(new ReaderWebViewClient(this)); this.getSettings().setUserAgentString(WordPress.getUserAgent()); CookieManager.getInstance().setAcceptThirdPartyCookies(this, true); } }
Source:
<code>private static RequestHeaders buildDefaultHeaders() { <START> final Multimap<String, String> headers = TreeMultimap.create(); <END> headers.put("Naming-Convention", "s3"); return new RequestHeadersImpl(headers); }</code><technical_language>RequestHeaders class, responsible for creating storage needs, consumer of it. Move TreeMultimap creation RequestHeaders class, new header insertion method</technical_language>

Target:
private static RequestHeaders buildDefaultHeaders() { final RequestHeaders requestHeaders = new RequestHeadersImpl(); requestHeaders.put("Naming-Convention", "s3"); return requestHeaders; }
Source:
<code>default void check() { File storageFile = new File(storagePath()); if (storageFile.exists()) { Preconditions.checkState( storageFile.isDirectory(), "Storage path has to point to a directory", SafeArg.of("path", storagePath())); } <START> Preconditions.checkState(!Paths.get(storagePath()).isAbsolute(), "Storage path must be relative"); <END> }</code><technical_language>nit: suggest including a SafeArg indicating of storagePath is</technical_language>

Target:
default void check() { Preconditions.checkState( !Paths.get(storagePath()).isAbsolute(), "Storage path must be relative", SafeArg.of("storagePath", storagePath())); File storageFile = new File(System.getProperty("user.dir"), storagePath()); if (storageFile.exists()) { Preconditions.checkState( storageFile.isDirectory(), "Storage path has to point to a directory", SafeArg.of("path", storagePath())); } }
Source:
<code>private void fillBuffer() throws IOException { String prefix; if (firstIteratorElement) { prefix = "["; firstIteratorElement = false; } else { prefix = ","; } String entity = iterator.hasNext() ? iterator.next() : ""; String postfix = ""; if (!iterator.hasNext()) { postfix = "]"; } try { closeJSONStream(); <START> jsonElementStream = IOUtils.toInputStream(prefix + entity + postfix, StandardCharsets.UTF_8.name()); <END> } catch (IOException e) { } }</code><technical_language>a separate try-catch-block for closeJSONStream method call? If close fails is do (and IMHO) this is reason ignore silently. If IOUtils.toInputStream fails, catched is a failure caller needs know</technical_language>

Target:
private void fillBuffer() { String prefix; if (firstIteratorElement) { prefix = "["; firstIteratorElement = false; } else { prefix = ","; } String entity = iterator.hasNext() ? iterator.next() : ""; String postfix = ""; if (!iterator.hasNext()) { postfix = "]"; } IOUtils.closeQuietly(jsonElementStream); try { jsonElementStream = IOUtils.toInputStream(prefix + entity + postfix, StandardCharsets.UTF_8.name()); } catch (IOException e) { } }
Source:
<code>public void whenCompletesEventually() throws Exception { final String response = "someresponse"; InternalCompletableFuture<String> f = localOperationService.invokeOnPartition(new OffloadingOperation(op -> new Offload(op) { @Override public void start() { <START> new Thread() { <END> @Override public void run() { sleepSeconds(5); offloadedOperation().sendResponse(response); } }.start(); } })); assertCompletesEventually(f); assertEquals(response, f.get()); }</code><technical_language>minor: converted new Thread(() -> { sleepSeconds(5); offloadedOperation().sendResponse(response); }).start();</technical_language>

Target:
public void whenCompletesEventually() throws Exception { final String response = "someresponse"; InternalCompletableFuture<String> f = localOperationService.invokeOnPartition(new OffloadingOperation(op -> new Offload(op) { @Override public void start() { new Thread(() -> { sleepSeconds(5); offloadedOperation().sendResponse(response); }).start(); } })); assertCompletesEventually(f); assertEquals(response, f.get()); }
Source:
<code><START> public String toString() <END> { return StringUtils.format( "JdbcExtractionNamespace = { connectorConfig = { %s }, table = %s, filter = %s, keyColumn = %s, valueColumn = %s, tsColumn = %s, pollPeriod = %s}", connectorConfig.toString(), table, filter, keyColumn, valueColumn, tsColumn, pollPeriod ); }</code><technical_language>Please re-generate toString IntelliJ</technical_language>

Target:
public String toString() { return "JdbcExtractionNamespace{" + "connectorConfig=" + connectorConfig + ", table='" + table + '\'' + ", keyColumn='" + keyColumn + '\'' + ", valueColumn='" + valueColumn + '\'' + ", tsColumn='" + tsColumn + '\'' + ", filter='" + filter + '\'' + ", pollPeriod=" + pollPeriod + '}'; }
Source:
<code>public MixinEmitter(ClassVisitor v, String className, Class[] classes, int[] route) { super(v); begin_class(Constants.V1_2, Constants.ACC_PUBLIC, className, MIXIN, TypeUtils.getTypes(getInterfaces(classes)), Constants.SOURCE_FILE); EmitUtils.null_constructor(this); EmitUtils.factory_method(this, NEW_INSTANCE); declare_field(Constants.ACC_PRIVATE, FIELD_NAME, Constants.TYPE_OBJECT_ARRAY, null); CodeEmitter e = begin_method(Constants.ACC_PUBLIC, CSTRUCT_OBJECT_ARRAY, null); e.load_this(); e.super_invoke_constructor(); e.load_this(); e.load_arg(0); e.putfield(FIELD_NAME); e.return_value(); e.end_method(); Set unique = new HashSet(); for (int i = 0; i < classes.length; i++) { Method[] methods = getMethods(classes[i]); for (int j = 0; j < methods.length; j++) { if (unique.add(MethodWrapper.create(methods[j]))) { MethodInfo method = ReflectUtils.getMethodInfo(methods[j]); <START> int access = Constants.ACC_PUBLIC; <END> if ((method.getModifiers() & Constants.ACC_VARARGS) == Constants.ACC_VARARGS) { access |= Constants.ACC_VARARGS; } e = EmitUtils.begin_method(this, method, access); e.load_this(); e.getfield(FIELD_NAME); e.aaload((route != null) ? route[i] : i); e.checkcast(method.getClassInfo().getType()); e.load_args(); e.invoke(method); e.return_value(); e.end_method(); } } } end_class(); }</code><technical_language>rename 'access' 'modifiers' & throughout</technical_language>

Target:
public MixinEmitter(ClassVisitor v, String className, Class[] classes, int[] route) { super(v); begin_class(Constants.V1_2, Constants.ACC_PUBLIC, className, MIXIN, TypeUtils.getTypes(getInterfaces(classes)), Constants.SOURCE_FILE); EmitUtils.null_constructor(this); EmitUtils.factory_method(this, NEW_INSTANCE); declare_field(Constants.ACC_PRIVATE, FIELD_NAME, Constants.TYPE_OBJECT_ARRAY, null); CodeEmitter e = begin_method(Constants.ACC_PUBLIC, CSTRUCT_OBJECT_ARRAY, null); e.load_this(); e.super_invoke_constructor(); e.load_this(); e.load_arg(0); e.putfield(FIELD_NAME); e.return_value(); e.end_method(); Set unique = new HashSet(); for (int i = 0; i < classes.length; i++) { Method[] methods = getMethods(classes[i]); for (int j = 0; j < methods.length; j++) { if (unique.add(MethodWrapper.create(methods[j]))) { MethodInfo method = ReflectUtils.getMethodInfo(methods[j]); int modifiers = Constants.ACC_PUBLIC; if ((method.getModifiers() & Constants.ACC_VARARGS) == Constants.ACC_VARARGS) { modifiers |= Constants.ACC_VARARGS; } e = EmitUtils.begin_method(this, method, modifiers); e.load_this(); e.getfield(FIELD_NAME); e.aaload((route != null) ? route[i] : i); e.checkcast(method.getClassInfo().getType()); e.load_args(); e.invoke(method); e.return_value(); e.end_method(); } } } end_class(); }
Source:
<code>public void resultPageUrlShouldContainSearchQueryName() { String searchPhrase = "searchPhrase"; String duckDuckUrl = "<LINK_0>"; chromium.sendCommand("Page.navigate", ImmutableMap.of("url", duckDuckUrl)); chromium.sendCommand("Input.insertText", ImmutableMap.of("text", searchPhrase)); <START> chromium.sendCommand("Input.dispatchKeyEvent", sendEnterKeyEventParams()); <END> response = chromium.sendCommandAndGetResponse("Page.getNavigationHistory", ImmutableMap.of()); assertIsPhrasePresentInTheResultsPageUrl(searchPhrase); }</code><technical_language>of lines start getChromiumApi().sendCommand(</technical_language>

Target:
public void resultPageUrlShouldContainSearchQueryName() { String searchPhrase = "searchPhrase"; String duckDuckUrl = "<LINK_0>"; getChromiumApi().sendCommand("Page.navigate", ImmutableMap.of("url", duckDuckUrl)); getChromiumApi().sendCommand("Input.insertText", ImmutableMap.of("text", searchPhrase)); getChromiumApi().sendCommand("Input.dispatchKeyEvent", sendEnterKeyEventParams()); response = getChromiumApi().sendCommandAndGetResponse("Page.getNavigationHistory", ImmutableMap.of()); assertIsPhrasePresentInTheResultsPageUrl(searchPhrase); }
Source:
<code>public void testZipIterableWithDelay() { TestScheduler scheduler = new TestScheduler(); Observable<Integer> o = Observable.just(1, 2).zipWith(Arrays.asList(1), new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer v1, Integer v2) { return v1; } }).delay(500, TimeUnit.MILLISECONDS, scheduler); TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>(); o.subscribe(subscriber); <START> scheduler.advanceTimeBy(1000, TimeUnit.DAYS.MILLISECONDS); <END> subscriber.assertValue(1); subscriber.assertNoErrors(); subscriber.assertCompleted(); }</code><technical_language>DAYS is unnecessary here</technical_language>

Target:
public void testZipIterableWithDelay() { TestScheduler scheduler = new TestScheduler(); Observable<Integer> o = Observable.just(1, 2).zipWith(Arrays.asList(1), new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer v1, Integer v2) { return v1; } }).delay(500, TimeUnit.MILLISECONDS, scheduler); TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>(); o.subscribe(subscriber); scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); subscriber.assertValue(1); subscriber.assertNoErrors(); subscriber.assertCompleted(); }
Source:
<code>private void setRowSelection(IntegerUnion modelSelection) { IntegerUnion newSelection; if(tableSorter.isFiltered() || !tableSorter.getSortKeys().isEmpty()) { <START> IntegerUnion viewSelection = new IntegerUnion(); <END> for(Integer modelId : modelSelection) { int viewRowId = table.convertRowIndexToView(modelId); if(viewRowId!=-1) { viewSelection.add(viewRowId); } } newSelection = viewSelection; } else { newSelection = modelSelection; } setViewRowSelection(newSelection); }</code><technical_language>This intermediate variable is necessary</technical_language>

Target:
private void setRowSelection(IntegerUnion modelSelection) { IntegerUnion newSelection; if(tableSorter.isFiltered() || !tableSorter.getSortKeys().isEmpty()) { newSelection = new IntegerUnion(); for(Integer modelId : modelSelection) { int viewRowId = table.convertRowIndexToView(modelId); if(viewRowId!=-1) { newSelection.add(viewRowId); } } } else { newSelection = modelSelection; } setViewRowSelection(newSelection); }
Source:
<code>public List<NearbyLocation> getNearestCities(String location, int radiusInKm, int maxResults) throws ParseException, GeoEntryQueryException { Geometry geometry; try { geometry = WKT_READER_THREAD_LOCAL.get().read(location); } catch (org.locationtech.jts.io.ParseException e) { throw new GeoEntryQueryException("Could not parse location"); } double distanceInDegrees = radiusInKm / KM_PER_DEGREE; final Geometry originalGeometry = geometry; Geometry bufferedGeo = originalGeometry.buffer(distanceInDegrees, 14); String wkt = WKT_WRITER_THREAD_LOCAL.get().write(bufferedGeo); String q = String.format( "location_geo_index:\"Intersects( %s ) AND %s\"", ClientUtils.escapeQueryChars(wkt), CITY_SOLR_QUERY); SolrQuery solrQuery = new SolrQuery(q); solrQuery.setRows(Math.min(maxResults, MAX_RESULTS)); QueryResponse response; try { response = client.query(solrQuery, METHOD.POST); } catch (SolrServerException | IOException e) { <START> LOGGER.debug("Error executing query for nearest cities", e); <END> throw new GeoEntryQueryException("Error executing query", e); } return response .getResults() .stream() .map(result -> convert(result, originalGeometry)) .collect(Collectors.toList()); }</code><technical_language>Another log throw</technical_language>

Target:
public List<NearbyLocation> getNearestCities(String location, int radiusInKm, int maxResults) throws ParseException, GeoEntryQueryException { Geometry geometry; try { geometry = WKT_READER_THREAD_LOCAL.get().read(location); } catch (org.locationtech.jts.io.ParseException e) { throw new GeoEntryQueryException("Could not parse location"); } final Geometry originalGeometry = geometry; Geometry bufferedGeo = originalGeometry.buffer(convertKilometerToDegree(radiusInKm), 14); String wkt = WKT_WRITER_THREAD_LOCAL.get().write(bufferedGeo); String q = String.format( "%s_index:\"Intersects( %s ) AND %s\"", LOCATION, ClientUtils.escapeQueryChars(wkt), CITY_SOLR_QUERY); SolrQuery solrQuery = new SolrQuery(q); solrQuery.setRows(Math.min(maxResults, MAX_RESULTS)); QueryResponse response; try { response = client.query(solrQuery, METHOD.POST); } catch (SolrServerException | IOException e) { throw new GeoEntryQueryException("Error executing query for nearest cities", e); } return response .getResults() .stream() .map(result -> convert(result, originalGeometry)) .collect(Collectors.toList()); }
Source:
<code>public void skip(long items) throws IOException { while (items > 0) { if (used == numLiterals) { readValues(); } long consume = Math.min(items, numLiterals - used); used += consume; items -= consume; if (items != 0) { <START> currentRunOffset += (int) consume; <END> } } }</code><technical_language>Perhaps, change type of consume int Math.toIntExact</technical_language>

Target:
public void skip(long items) throws IOException { while (items > 0) { if (used == numLiterals) { readValues(); } long consume = Math.min(items, numLiterals - used); used += consume; items -= consume; if (items != 0) { currentRunOffset += toIntExact(consume); } } }
Source:
<code>public RtGithub( @NotNull(message = "token can't be NULL") final String token) { <START> this(URI.create(DEFAULT_GITHUB_HOST), token); <END> }</code><technical_language>@perfa RtGithub.DEFAULT_GITHUB_HOST</technical_language>

Target:
public RtGithub( @NotNull(message = "token can't be NULL") final String token) { this(URI.create(RtGithub.DEFAULT_HOST), token); }
Source:
<code>boolean requestCookie(HttpConnectionInterceptorContext context) { return requestCookie(context, sessionURL, sessionRequestBody, sessionRequestMimeType, "application/json", new OnExecuteCallable() { @Override public boolean call(HttpConnection connection) throws IOException { if (sessionHasStarted(connection.responseAsInputStream())) { return storeCookiesFromResponse(connection.getConnection()); } else { InputStream errorStream = connection.getConnection().getErrorStream(); <START> if (errorStream != null) { <END> try { IOUtils.copy(errorStream, NullOutputStream.NULL_OUTPUT_STREAM); } finally { IOUtils.closeQuietly(errorStream); } } return false; } } } ); }</code><technical_language>This block of code is this [line](<LINK_0> in [HttpConnection](<LINK_1> put this in a utils class reduce duplicate code</technical_language>

Target:
boolean requestCookie(HttpConnectionInterceptorContext context) { return requestCookie(context, sessionURL, sessionRequestBody, sessionRequestMimeType, "application/json", new OnExecuteCallable() { @Override public boolean call(HttpConnection connection) throws IOException { if (sessionHasStarted(connection.responseAsInputStream())) { return storeCookiesFromResponse(connection.getConnection()); } else { Utils.consumeAndCloseStream(connection.getConnection().getErrorStream ()); return false; } } } ); }
Source:
<code>private void sleepUntilNextRun(Optional<SweepOutcome> maybeOutcome) throws InterruptedException { <START> Duration sleepDuration = maybeOutcome.flatMap(outcome -> { <END> if (outcome == SweepOutcome.SUCCESS) { return Optional.of(Duration.ofMillis(sweepPauseMillis.get())); } else if (outcome == SweepOutcome.NOTHING_TO_SWEEP) { return Optional.of(getBackoffTimeWhenNothingToSweep()); } else { return Optional.empty(); } }).orElseGet(this::getBackoffTimeWhenSweepHasNotRun); sleepFor(sleepDuration); }</code><technical_language>nit: extract method</technical_language>

Target:
private void sleepUntilNextRun(Optional<SweepOutcome> maybeOutcome) throws InterruptedException { sleepFor(getSleepDuration(maybeOutcome)); }
Source:
<code>@Test public void iteratorThrowsIOException() throws IOException { QueueFile queueFile = newQueueFile(); queueFile.add(values[253]); queueFile.close(); final class BrokenRandomAccessFile extends RandomAccessFile { boolean fail = false; BrokenRandomAccessFile(File file, String mode) throws FileNotFoundException { super(file, mode); } @Override public void write(byte[] b, int off, int len) throws IOException { if (fail) { throw new IOException(); } super.write(b, off, len); } @Override public int read(byte[] b, int off, int len) throws IOException { if (fail) { throw new IOException(); } return super.read(b, off, len); } } BrokenRandomAccessFile braf = new BrokenRandomAccessFile(file, "rwd"); queueFile = newQueueFile(braf); Iterator<byte[]> iterator = queueFile.iterator(); braf.fail = true; try { iterator.next(); } catch (Throwable ioe) { assertThat(ioe).isInstanceOf(IOException.class); <START> } <END> braf.fail = false; iterator.next(); braf.fail = true; try { iterator.remove(); fail(); } catch (Throwable ioe) { assertThat(ioe).isInstanceOf(IOException.class); } }</code><technical_language>Missing fail(), catch IOE again</technical_language>

Target:
@Test public void iteratorThrowsIOException() throws IOException { QueueFile queueFile = newQueueFile(); queueFile.add(values[253]); queueFile.close(); final class BrokenRandomAccessFile extends RandomAccessFile { boolean fail = false; BrokenRandomAccessFile(File file, String mode) throws FileNotFoundException { super(file, mode); } @Override public void write(byte[] b, int off, int len) throws IOException { if (fail) { throw new IOException(); } super.write(b, off, len); } @Override public int read(byte[] b, int off, int len) throws IOException { if (fail) { throw new IOException(); } return super.read(b, off, len); } } BrokenRandomAccessFile braf = new BrokenRandomAccessFile(file, "rwd"); queueFile = newQueueFile(braf); Iterator<byte[]> iterator = queueFile.iterator(); braf.fail = true; try { iterator.next(); fail(); } catch (Exception ioe) { assertThat(ioe).isInstanceOf(IOException.class); } braf.fail = false; iterator.next(); braf.fail = true; try { iterator.remove(); fail(); } catch (Exception ioe) { assertThat(ioe).isInstanceOf(IOException.class); } }
Source:
<code>private void overrideParameters() { <START> boolean isTemplate = isTemplate(); <END> if (getParameters().getOperation() == ImageOperation.Copy) { getParameters().setUseCopyCollapse(true); getParameters().setAddImageDomainMapping(true); if (!isTemplate) { getParameters().setAddImageDomainMapping(false); Guid newId = Guid.newGuid(); Guid newGroupId = Guid.newGuid(); DiskImage image = getImage(); image.setId(newGroupId); image.setImageId(newId); image.setDiskAlias(getDiskAlias()); image.setStorageIds(new ArrayList<Guid>()); image.getStorageIds().add(getParameters().getStorageDomainId()); image.setQuotaId(getParameters().getQuotaId()); image.setDiskProfileId(getParameters().getDiskProfileId()); getParameters().setDestinationImageId(newId); getParameters().setImageGroupID(getParameters().getImageGroupID()); getParameters().setDestImageGroupId(newGroupId); } } else { getParameters().setUseCopyCollapse(false); } if (getParameters().getOperation() == ImageOperation.Move || isTemplate) { getParameters().setDestinationImageId(getImageId()); getParameters().setImageGroupID(getImageGroupId()); getParameters().setDestImageGroupId(getImageGroupId()); } getParameters().setVolumeFormat(getDiskImage().getVolumeFormat()); getParameters().setVolumeType(getDiskImage().getVolumeType()); getParameters().setCopyVolumeType(CopyVolumeType.SharedVol); getParameters().setParentCommand(getActionType()); getParameters().setParentParameters(getParameters()); getParameters().setDiskProfileId(getImage().getDiskProfileId()); }</code><technical_language>style: is pretty confusing calling variable name of method, I simply call method additional variable change variable name</technical_language>

Target:
private void overrideParameters() { if (getParameters().getOperation() == ImageOperation.Copy) { getParameters().setUseCopyCollapse(true); getParameters().setAddImageDomainMapping(true); if (!isTemplate()) { prepareCopyNotTemplate(); } } else { getParameters().setUseCopyCollapse(false); } if (getParameters().getOperation() == ImageOperation.Move || isTemplate()) { getParameters().setDestinationImageId(getImageId()); getParameters().setImageGroupID(getImageGroupId()); getParameters().setDestImageGroupId(getImageGroupId()); } getParameters().setVolumeFormat(getDiskImage().getVolumeFormat()); getParameters().setVolumeType(getDiskImage().getVolumeType()); getParameters().setCopyVolumeType(CopyVolumeType.SharedVol); getParameters().setParentCommand(getActionType()); getParameters().setParentParameters(getParameters()); getParameters().setDiskProfileId(getImage().getDiskProfileId()); }
Source:
<code>public static String CM_Get_Device_ID(int devInst) { int charToBytes = Boolean.getBoolean("w32.ascii") ? 1 : Native.WCHAR_SIZE; IntByReference pulLen = new IntByReference(); Cfgmgr32.INSTANCE.CM_Get_Device_ID_Size(pulLen, devInst, 0); int deviceIdLength = pulLen.getValue() + 1; Memory buffer = new Memory(deviceIdLength * charToBytes); <START> Cfgmgr32.INSTANCE.CM_Get_Device_ID(devInst, buffer, deviceIdLength, 0); <END> if (charToBytes == 1) { return buffer.getString(0); } else { return buffer.getWideString(0); } }</code><technical_language>Please check return of CM_Get_Device_ID. call sequence is correct, identifier increase in length call CM_Get_Device_ID_Size here. a call error raised</technical_language>

Target:
public static String CM_Get_Device_ID(int devInst) throws Cfgmgr32Exception { int charToBytes = Boolean.getBoolean("w32.ascii") ? 1 : Native.WCHAR_SIZE; IntByReference pulLen = new IntByReference(); int ret = Cfgmgr32.INSTANCE.CM_Get_Device_ID_Size(pulLen, devInst, 0); if (ret != Cfgmgr32.CR_SUCCESS) { throw new Cfgmgr32Exception(ret); } Memory buffer = new Memory((pulLen.getValue() + 1) * charToBytes); buffer.clear(); ret = Cfgmgr32.INSTANCE.CM_Get_Device_ID(devInst, buffer, pulLen.getValue(), 0); if (ret == Cfgmgr32.CR_BUFFER_SMALL) { ret = Cfgmgr32.INSTANCE.CM_Get_Device_ID_Size(pulLen, devInst, 0); if (ret != Cfgmgr32.CR_SUCCESS) { throw new Cfgmgr32Exception(ret); } buffer = new Memory((pulLen.getValue() + 1) * charToBytes); buffer.clear(); ret = Cfgmgr32.INSTANCE.CM_Get_Device_ID(devInst, buffer, pulLen.getValue(), 0); } if (ret != Cfgmgr32.CR_SUCCESS) { throw new Cfgmgr32Exception(ret); } if (charToBytes == 1) { return buffer.getString(0); } else { return buffer.getWideString(0); } }
Source:
<code>private void init() { getRootPane().registerKeyboardAction( action -> { setVisible(false); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), <START> JComponent.WHEN_IN_FOCUSED_WINDOW); <END> multiUserCasesPanel = new OpenMultiUserCasePanel(this); add(multiUserCasesPanel); pack(); setResizable(false); }</code><technical_language>Hitting ESC do for</technical_language>

Target:
private void init() { multiUserCasesPanel = new OpenMultiUserCasePanel(this); add(multiUserCasesPanel); pack(); setResizable(false); }
Source:
<code>public void startPlayback(PianoView pianoView) { playRunnables.clear(); long playLength = NoteLength.QUARTER.toMilliseconds(Project.DEFAULT_BEATS_PER_MINUTE); long currentTime = SystemClock.uptimeMillis(); for (GridRow row : gridRows) { for (int i = 0; i < row.getGridRowPositions().size(); i++) { int tactIndex = row.getGridRowPositions().keyAt(i); <START> long tactOffset = playLength * 4 * tactIndex; <END> List<GridRowPosition> gridRowPositions = row.getGridRowPositions().get(tactIndex); for (GridRowPosition position : gridRowPositions) { MidiRunnable runnable = new MidiRunnable(MidiSignals.NOTE_ON, row.getNoteName(), playLength - 10, handler, midiDriver, pianoView); handler.postAtTime(runnable, currentTime + tactOffset + playLength * position.getColumnStartIndex() + 10); playRunnables.add(runnable); } } } }</code><technical_language>I 4 TrackRowView.QUARTER_COUNT</technical_language>

Target:
public void startPlayback(PianoView pianoView) { playRunnables.clear(); long playLength = NoteLength.QUARTER.toMilliseconds(Project.DEFAULT_BEATS_PER_MINUTE); long currentTime = SystemClock.uptimeMillis(); for (GridRow row : gridRows) { for (int i = 0; i < row.getGridRowPositions().size(); i++) { int tactIndex = row.getGridRowPositions().keyAt(i); long tactOffset = playLength * TrackRowView.QUARTER_COUNT * tactIndex; List<GridRowPosition> gridRowPositions = row.getGridRowPositions().get(tactIndex); for (GridRowPosition position : gridRowPositions) { MidiRunnable runnable = new MidiRunnable(MidiSignals.NOTE_ON, row.getNoteName(), playLength - SOUND_OFFSET, handler, midiDriver, pianoView); handler.postAtTime(runnable, currentTime + tactOffset + playLength * position.getColumnStartIndex() + SOUND_OFFSET); playRunnables.add(runnable); } } } }
Source:
<code>public static OkHttpClient getOAuthBasedClient(@NonNull Context context) { OkHttpClient client = new OkHttpClient(); File cacheDirectory = new File(context.getFilesDir(), "http-cache"); if (!cacheDirectory.exists()) { cacheDirectory.mkdirs(); } <START> Cache cache = new com.squareup.okhttp.Cache(cacheDirectory, cacheSize); <END> client.setCache(cache); client.interceptors().add(new GzipRequestInterceptor()); client.interceptors().add(new OauthHeaderRequestInterceptor(context)); client.interceptors().add(new LoggingInterceptor()); return client; }</code><technical_language>com.squareup.okhttp namespace removed, imported Cache here</technical_language>

Target:
public static OkHttpClient getOAuthBasedClient(@NonNull Context context) { final OkHttpClient client = new OkHttpClient(); final File cacheDirectory = new File(context.getFilesDir(), "http-cache"); if (!cacheDirectory.exists()) { cacheDirectory.mkdirs(); } final Cache cache = new Cache(cacheDirectory, cacheSize); client.setCache(cache); client.interceptors().add(new GzipRequestInterceptor()); client.interceptors().add(new OauthHeaderRequestInterceptor(context)); client.interceptors().add(new LoggingInterceptor()); return client; }
Source:
<code>private static void processException(Exception e, SensorContext context, InputFile inputFile) { reportAnalysisError(e, context, inputFile); <START> throw new IllegalStateException("Unable to analyse file " + inputFile.uri(), e); <END> }</code><technical_language>Ok need rework PR, i for a log instead of throwing ISE here</technical_language>

Target:
private static void processException(Exception e, SensorContext context, InputFile inputFile) { reportAnalysisError(e, context, inputFile); LOG.error("Unable to analyse file " + inputFile.uri(), e); }
Source:
<code>public IMessage onMessage(MessageRequestBlockUpdate message, MessageContext ctx) { WorldServer world = ctx.getServerHandler().player.getServerWorld(); world.addScheduledTask(() -> { synchronized (EventHandler.requestedBlockUpdates) { if (world.isBlockLoaded(message.pos)) { int dim = world.provider.getDimension(); <START> EventHandler.requestedBlockUpdates.offer(new ImmutablePair<>(dim, message.pos)); <END> } } }); return null; }</code><technical_language>Alternatively consider a java.util.concurrent Queue for EventHandler.requestedBlockUpdates, callers need worry synchronized()</technical_language>

Target:
public IMessage onMessage(MessageRequestBlockUpdate message, MessageContext ctx) { WorldServer world = ctx.getServerHandler().player.getServerWorld(); world.addScheduledTask(() -> { if (world.isBlockLoaded(message.pos)) { int dim = world.provider.getDimension(); EventHandler.requestedBlockUpdates.offer(new ImmutablePair<>(dim, message.pos)); } }); return null; }
Source:
<code>public List<BrooklinMetricInfo> getMetricInfos() { _metrics.add(new BrooklinMeterInfo(buildMetricName(NUM_REBALANCES))); _metrics.add(new BrooklinMeterInfo(getDynamicMetricPrefixRegex() + NUM_ERRORS)); _metrics.add(new BrooklinMeterInfo(getDynamicMetricPrefixRegex() + NUM_RETRIES)); <START> _metrics.add(new BrooklinMeterInfo(buildMetricName(NUM_HEARTBEATS))); <END> return Collections.unmodifiableList(_metrics); }</code><technical_language>BrooklinCounterInfo, implemented a counter</technical_language>

Target:
public List<BrooklinMetricInfo> getMetricInfos() { _metrics.add(new BrooklinMeterInfo(buildMetricName(NUM_REBALANCES))); _metrics.add(new BrooklinMeterInfo(getDynamicMetricPrefixRegex() + NUM_ERRORS)); _metrics.add(new BrooklinMeterInfo(getDynamicMetricPrefixRegex() + NUM_RETRIES)); _metrics.add(new BrooklinCounterInfo(buildMetricName(NUM_HEARTBEATS))); return Collections.unmodifiableList(_metrics); }
Source:
<code>public UserAndPassword1_8 save(UserAndPassword1_8 user) { User openmrsUser = new User(); if (user.getUser().getUserId() == null) { openmrsUser = Context.getUserService().createUser(user.getUser(), user.getPassword()); } else { openmrsUser = Context.getUserService().saveUser(user.getUser()); Context.refreshAuthenticatedUser(); <START> if (openmrsUser.getId() != null && (Context.getAuthenticatedUser().getUuid().equals(openmrsUser.getUuid()))) { <END> Context.getUserService().changePassword(user.getOldPassword(), user.getPassword()); } else if (openmrsUser.getId() != null && StringUtils.isNotBlank(user.getPassword())) { Context.getUserService().changePassword(openmrsUser, user.getPassword()); } } return new UserAndPassword1_8(openmrsUser); }</code><technical_language>I expect logic if (Context.hasPrivilege(PrivilegeConstants.EDIT_USER_PASSWORDS)) { // call admin version } else { // call changeOwnPassword function }</technical_language>

Target:
public UserAndPassword1_8 save(UserAndPassword1_8 user) { User openmrsUser = new User(); if (user.getUser().getUserId() == null) { openmrsUser = Context.getUserService().createUser(user.getUser(), user.getPassword()); } else { openmrsUser = Context.getUserService().saveUser(user.getUser()); Context.refreshAuthenticatedUser(); } return new UserAndPassword1_8(openmrsUser); }
Source:
<code>public void testWriterWithJson() throws IOException { Mockito.when(sink.getContainsJson()).thenReturn(true); Mockito.when(writeOperation.getSink()).thenReturn(sink); writer = new CouchbaseWriter(writeOperation); CouchbaseConnection connection = Mockito.mock(CouchbaseConnection.class); Mockito.when(sink.getConnection()).thenReturn(connection); Mockito.when(sink.getContainsJson()).thenReturn(true); Schema schema = SchemaBuilder.builder().record("record").fields().requiredString("idFieldName").endRecord(); <START> IndexedRecord record = new GenericRecordBuilder(schema).set("idFieldName", 1).build(); <END> writer.open("random"); writer.write(record); Result result = writer.close(); Assert.assertEquals(1, result.totalCount); Mockito.verify(connection, Mockito.times(1)).insertJsonDocument(Mockito.anyString(), Mockito.any()); Mockito.verify(connection, Mockito.times(1)).increment(); Mockito.verify(connection, Mockito.times(1)).decrement(); }</code><technical_language>test test basic input, json string input column value, do adjust if i right</technical_language>

Target:
public void testWriterWithJson() throws IOException { CouchbaseConnection connection = Mockito.mock(CouchbaseConnection.class); Mockito.when(sink.getConnection()).thenReturn(connection); Mockito.when(sink.getContainsJson()).thenReturn(true); Mockito.when(writeOperation.getSink()).thenReturn(sink); writer = new CouchbaseWriter(writeOperation); Schema schema = SchemaBuilder.builder().record("record").fields().requiredString("idFieldName").endRecord(); IndexedRecord record = new GenericRecordBuilder(schema).set("idFieldName", 1).build(); writer.open("random"); writer.write(record); Result result = writer.close(); assertEquals(1, result.totalCount); Mockito.verify(connection, Mockito.times(1)).insertJsonDocument(Mockito.anyString(), Mockito.any()); Mockito.verify(connection, Mockito.times(1)).increment(); Mockito.verify(connection, Mockito.times(1)).decrement(); }
Source:
<code>public void selectLanguage(String lang) { wait.forElementVisible(wikiLanguageDropdown); wikiLanguageDropdown.click(); List<WebElement> langList = wikiLanguageList.findElements(By.cssSelector("li:not(.spacer)")); for (int i = 0; i < langList.size(); i++) { WebElement selectedLanguage = langList.get(i); String selectedLanguageText = selectedLanguage.getText(); <START> if (selectedLanguageText.contains(lang + ":")) { <END> wait.forElementClickable(selectedLanguage); selectedLanguage.click(); Assertion.assertEquals(languageSelectedIndicator.getText(), lang + "."); PageObjectLogging.log("selectLanguage", "selected " + selectedLanguageText + " language", true, driver); break; } } }</code><technical_language>move this string concatenation of loop concatenate iteration</technical_language>

Target:
public void selectLanguage(String lang) { wait.forElementClickable(wikiLanguageDropdown); wikiLanguageDropdown.click(); List<WebElement> langList = wikiLanguageList.findElements(By.cssSelector("li:not(.spacer)")); String langSelector = lang + ":"; for (int i = 0; i < langList.size(); i++) { WebElement selectedLanguage = langList.get(i); String selectedLanguageText = selectedLanguage.getText(); if (selectedLanguageText.contains(langSelector)) { wait.forElementClickable(selectedLanguage); selectedLanguage.click(); Assertion.assertEquals(languageSelectedIndicator.getText(), lang + "."); PageObjectLogging.log("selectLanguage", "selected " + selectedLanguageText + " language", true, driver); break; } } }
Source:
<code><START> public String getProjectName() { <END> return projectName; }</code><technical_language>[optional] return Project.NameKey</technical_language>

Target:
public String getProjectName() { return projectName != null ? projectName.get() : null; }
Source:
<code>public WebElement getPortletInRightTable(String name) { try { if (getPanel().findElements(By.xpath(" <START> return getPanel().findElement(By.xpath(" END> } else { return getPanel().findElement(By.xpath(" } } catch (NoSuchElementException ex) { return null; } }</code><technical_language>extract common part of 240 242</technical_language>

Target:
public WebElement getPortletInRightTable(String name) { try { if (getPanel().findElements(By.xpath(" return getRightPortletOnExactPosition(name, 2); } else { return getRightPortletOnExactPosition(name, 1); } } catch (NoSuchElementException ex) { return null; } }
Source:
<code>public String toString() { JSONStringer js = new JSONStringer(); try { js.object(); js.key("group").value(group); js.key("coordinatorip").value(coordinatorIp.toString()); js.key("zkinterface").value(zkInterface); js.key("internalinterface").value(internalInterface); js.key("internalport").value(internalPort); js.key("deadhosttimeout").value(deadHostTimeout); js.key("backwardstimeforgivenesswindow").value(backwardsTimeForgivenessWindow); js.key("networkThreads").value(networkThreads); <START> js.key("acceptor").value(acceptor); <END> js.endObject(); return js.toString(); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>more of keys constants</technical_language>

Target:
public String toString() { JSONStringer js = new JSONStringer(); try { js.object(); js.key(GROUP).value(group); js.key(COORDINATOR_IP).value(coordinatorIp.toString()); js.key(ZK_INTERFACE).value(zkInterface); js.key(INTERNAL_INTERFACE).value(internalInterface); js.key(INTERNAL_PORT).value(internalPort); js.key(DEAD_HOST_TIMEOUT).value(deadHostTimeout); js.key(BACKWARDS_TIME_FORGIVENESS_WINDOW).value(backwardsTimeForgivenessWindow); js.key(NETWORK_THREADS).value(networkThreads); js.key(ACCEPTOR).value(acceptor); js.endObject(); return js.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public void testStopJobExecution() throws Exception { String jobName = generateJobName(); executeJobCreate(jobName, JOB_WITH_STEP_EXECUTIONS); checkForJobInList(jobName, JOB_WITH_STEP_EXECUTIONS, true); triggerJobWithDelay(jobName, "5"); Thread.sleep(5000); Table table = (Table) executeCommand("job execution list").getResult(); assertTrue(!table.getRows().isEmpty()); String executionId = table.getRows().get(0).getValue(1); String executionStatus = table.getRows().get(0).getValue(5); assertTrue(executionStatus.equals("STARTING") || executionStatus.equals("STARTED")); executeCommand("job execution stop " + executionId); Thread.sleep(3000); table = (Table) executeCommand("job execution list").getResult(); int n = 0; <START> while (!"STOPPED".equals(executionStatus) && n++ < 100) { <END> for (TableRow tr : table.getRows()) { if (tr.getValue(1).equals(executionId)) { executionStatus = tr.getValue(5); if (!"STOPPED".equals(executionStatus)) { Thread.sleep(100); table = (Table) executeCommand("job execution list").getResult(); } break; } } } assertEquals("STOPPED", executionStatus); }</code><technical_language>Is this intended a tight spin? sleep occurs in nested if block leads a break; So, if block is entered this loop pause</technical_language>

Target:
public void testStopJobExecution() throws Exception { String jobName = generateJobName(); executeJobCreate(jobName, JOB_WITH_STEP_EXECUTIONS); checkForJobInList(jobName, JOB_WITH_STEP_EXECUTIONS, true); triggerJobWithDelay(jobName, "5"); Thread.sleep(5000); Table table = (Table) executeCommand("job execution list").getResult(); assertTrue(!table.getRows().isEmpty()); String executionId = table.getRows().get(0).getValue(1); String executionStatus = table.getRows().get(0).getValue(5); assertTrue(executionStatus.equals("STARTING") || executionStatus.equals("STARTED")); executeCommand("job execution stop " + executionId); Thread.sleep(3000); int n = 0; do { table = (Table) executeCommand("job execution list").getResult(); for (TableRow tr : table.getRows()) { if (tr.getValue(1).equals(executionId)) { executionStatus = tr.getValue(5); break; } } if (!"STOPPED".equals(executionStatus)) { Thread.sleep(100); } } while (!"STOPPED".equals(executionStatus) && n++ < 100); assertEquals("STOPPED", executionStatus); }