auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public T next() throws InterruptedException { <START> WAIT_LOOP: for (;;) { <END> long now = TimeService.currentTimeMillis(); int myOffset = offset; INVOCATIONS_LOOP: for (int i = 0; i < numOperations; ++i) { int operationIndex = (i + myOffset) % numOperations; long myInterval = intervals[operationIndex]; long currentInterval = now / myInterval; long lastInterval; boolean set = false; do { lastInterval = lastIntervals.get(operationIndex); } while (currentInterval > lastInterval && !(set = lastIntervals.compareAndSet(operationIndex, lastInterval, currentInterval))); if (set) { int frequency = invocations[operationIndex]; todoInvocations.set(operationIndex, frequency - 1); synchronized (this) { this.notifyAll(); } } else { int todos; do { todos = todoInvocations.get(operationIndex); if (todos <= 0) continue INVOCATIONS_LOOP; } while (!todoInvocations.compareAndSet(operationIndex, todos, todos - 1)); } offset++; return operations[operationIndex]; } synchronized (this) { for (int i = 0; i < todoInvocations.length(); ++i) { if (todoInvocations.get(i) != 0) { continue WAIT_LOOP; } } this.wait(1); } } }</code><technical_language>adding a timeout here</technical_language>

Target:
public T next() throws InterruptedException { WAIT_LOOP: for (;;) { long now = TimeService.currentTimeMillis(); int myOffset = offset; INVOCATIONS_LOOP: for (int i = 0; i < operations.length; ++i) { int operationIndex = (i + myOffset) % operations.length; long myInterval = intervals[operationIndex]; long currentInterval = now / myInterval; long lastInterval; boolean hasSetLastInterval = false; do { lastInterval = lastIntervals.get(operationIndex); } while (currentInterval > lastInterval && !(hasSetLastInterval = lastIntervals.compareAndSet(operationIndex, lastInterval, currentInterval))); if (hasSetLastInterval) { int frequency = invocations[operationIndex]; todoInvocations.set(operationIndex, frequency - 1); synchronized (this) { this.notifyAll(); } } else { int todos; do { todos = todoInvocations.get(operationIndex); if (todos <= 0) continue INVOCATIONS_LOOP; } while (!todoInvocations.compareAndSet(operationIndex, todos, todos - 1)); } offset++; return operations[operationIndex]; } synchronized (this) { for (int i = 0; i < todoInvocations.length(); ++i) { if (todoInvocations.get(i) != 0) { continue WAIT_LOOP; } } this.wait(1); } } }
Source:
<code><START> public static void queryTwins() throws IOException, InterruptedException { <END> System.out.println("QUERY DIGITAL TWINS"); final CountDownLatch queryLatch = new CountDownLatch(1); System.out.println("Making a twin query and iterating over the results."); client.query("SELECT * FROM digitaltwins") .doOnNext(queryResult -> System.out.println("Query result: " + queryResult)) .doOnError(throwable -> System.err.println("Query error: " + throwable)) .doOnTerminate(queryLatch::countDown) .subscribe(); queryLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS); System.out.println("Making a twin query, with query-charge header extraction."); final CountDownLatch queryWithChargeLatch = new CountDownLatch(1); client.query("SELECT * FROM digitaltwins", BasicDigitalTwin.class) .byPage() .doOnNext(page -> { System.out.println("Query charge: " + getQueryCharge(page)); page.getValue() .forEach(item -> System.out.println("Found digital twin: " + item.getId())); }) .doOnError(throwable -> System.err.println("Query error: " + throwable)) .doOnTerminate(queryLatch::countDown) .subscribe(); queryWithChargeLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS); }</code><technical_language>IOExceptions thrown? I of client methods declaring it</technical_language>

Target:
public static void queryTwins() throws InterruptedException { ConsoleLogger.printHeader("QUERY DIGITAL TWINS"); final CountDownLatch queryLatch = new CountDownLatch(1); ConsoleLogger.printHeader("Making a twin query and iterating over the results."); client.query("SELECT * FROM digitaltwins") .doOnNext(queryResult -> ConsoleLogger.printHeader("Query result: " + queryResult)) .doOnError(throwable -> ConsoleLogger.printFatal("Query error: " + throwable)) .doOnTerminate(queryLatch::countDown) .subscribe(); queryLatch.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS); ConsoleLogger.printHeader("Making a twin query, with query-charge header extraction."); final CountDownLatch queryWithChargeLatch = new CountDownLatch(1); client.query("SELECT * FROM digitaltwins", BasicDigitalTwin.class) .byPage() .doOnNext(page -> { ConsoleLogger.printHeader("Query charge: " + getQueryCharge(page)); page.getValue() .forEach(item -> ConsoleLogger.printHeader("Found digital twin: " + item.getId())); }) .doOnError(throwable -> ConsoleLogger.printFatal("Query error: " + throwable)) .doOnTerminate(queryLatch::countDown) .subscribe(); queryWithChargeLatch.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS); }
Source:
<code>public int getKala(float kalamees) { Integer result = null; try { result = (Integer) handler.invoke(this, ProxySampleInterface_ReturnsBasic.class.getMethod("getKala", new Class[] {Float.TYPE}), new Object[] {new Float(kalamees)}); } catch (ClassCastException e) { throw e; } catch (NoSuchMethodException e) { } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Throwable e) { throw new UndeclaredThrowableException(e); } <START> if (result != null) { <END> return result; } else { return 0; } }</code><technical_language>This defensive also, a sample in a test. If underlying method handler invocation returns expected return null, check for null NPE happen</technical_language>

Target:
public int getKala(float kalamees) { Integer result = null; try { result = (Integer) handler.invoke(this, ProxySampleInterface_ReturnsBasic.class.getMethod("getKala", new Class[] {Float.TYPE}), new Object[] {new Float(kalamees)}); } catch (ClassCastException e) { throw e; } catch (NoSuchMethodException e) { } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Throwable e) { throw new UndeclaredThrowableException(e); } return result.intValue(); }
Source:
<code>public void apply(OnlineCommandContext ctx) throws Exception { if (ctx.options.isDomain) { throw new CommandFailedException("AddModule command isn't supported in domain mode"); } StringBuilder cmd = new StringBuilder("module add"); cmd.append(" --name=" + moduleName); cmd.append(" --slot=" + slot); cmd.append(" --resource-delimiter=" + resourceDelimiter); if (moduleXml != null) cmd.append(" --module-xml=" + moduleXml); if (mainClass != null) cmd.append(" --main-class=" + mainClass); Joiner joiner = Joiner.on(','); if (!resources.isEmpty()) { <START> cmd.append(" --resources=" + joiner.join(resources)); <END> } if (!dependencies.isEmpty()) { cmd.append(" --dependencies=" + joiner.join(dependencies)); } if (!properties.isEmpty()) { cmd.append(" --properties=" + joiner.join(properties)); } ctx.client.executeCli(cmd.toString()); }</code><technical_language>if path resource contains spaces (and/or quotes)? PatchingConversions class. some kind of a builder for local CLI operations encapsulate that, for time being, solve manually</technical_language>

Target:
public void apply(OnlineCommandContext ctx) throws Exception { if (ctx.options.isDomain) { throw new CommandFailedException("AddModule command isn't supported in domain mode"); } StringBuilder cmd = new StringBuilder("module add"); cmd.append(" --name=" + moduleName); cmd.append(" --slot=" + slot); if (moduleXml != null) cmd.append(" --module-xml=" + moduleXml); if (mainClass != null) cmd.append(" --main-class=" + mainClass); Joiner resourcesJoiner = Joiner.on(File.pathSeparatorChar); if (ctx.serverVersion.greaterThanOrEqualTo(ManagementVersion.VERSION_2_0_0)) { cmd.append(" --resource-delimiter=" + resourceDelimiter); resourcesJoiner = Joiner.on(resourceDelimiter); } if (!resources.isEmpty()) { cmd.append(" --resources=" + resourcesJoiner.join(resources).replaceAll(" ", "\\\\ ")); } Joiner defaultJoiner = Joiner.on(","); if (!dependencies.isEmpty()) { cmd.append(" --dependencies=" + defaultJoiner.join(dependencies)); } if (!properties.isEmpty()) { cmd.append(" --properties=" + defaultJoiner.join(properties)); } ctx.client.executeCli(cmd.toString()); }
Source:
<code>public List<LogicalDevice> getLogicalDevices() { <START> return logicalDevices; <END> }</code><technical_language>add "this" qualifier</technical_language>

Target:
public List<LogicalDevice> getLogicalDevices() { return this.logicalDevices; }
Source:
<code>public CompletionStage<Metadata> refreshSchema( String keyspace, boolean evenIfDisabled, boolean flushNow) { boolean isRefreshedKeyspace = keyspace == null || refreshedKeyspaces.isEmpty() || refreshedKeyspaces.contains(keyspace); CompletableFuture<Metadata> future = new CompletableFuture<>(); if (isRefreshedKeyspace && (evenIfDisabled || isSchemaEnabled())) { RunOrSchedule.on(adminExecutor, () -> singleThreaded.acceptSchemaRequest(future, flushNow)); } else { <START> future.complete(metadata); <END> singleThreaded.firstSchemaRefreshFuture.complete(null); } return future; }</code><technical_language>I this answers of previous questions, if schema is enabled programmatically overrides config completely (even if config changes?)</technical_language>

Target:
public CompletionStage<Metadata> refreshSchema( String keyspace, boolean evenIfDisabled, boolean flushNow) { CompletableFuture<Metadata> future = new CompletableFuture<>(); RunOrSchedule.on( adminExecutor, () -> singleThreaded.refreshSchema(keyspace, evenIfDisabled, flushNow, future)); return future; }
Source:
<code><START> public void setMetadata(String id, String value) { <END> esClient.prepareIndex(MetadataIndexDefinition.INDEX_TYPE_METADATA) .setId(id) .setSource(MetadataIndexDefinition.FIELD_VALUE, value) .setRefreshPolicy(REFRESH_IMMEDIATE) .get(); }</code><technical_language>here: slightly prefer private</technical_language>

Target:
private void setMetadata(String id, String value) { esClient.prepareIndex(MetadataIndexDefinition.INDEX_TYPE_METADATA) .setId(id) .setSource(MetadataIndexDefinition.FIELD_VALUE, value) .setRefreshPolicy(REFRESH_IMMEDIATE) .get(); }
Source:
<code>public void setup() { metadata = getQueryRunner().getMetadata(); sqlParser = getQueryRunner().getSqlParser(); ConnectorId connectorId = getCurrentConnectorId(); nationTableHandle = new TableHandle( connectorId, new TpchTableHandle("nation", 1.0), TestingTransactionHandle.create(), <START> Optional.of(TestingHandle.INSTANCE)); <END> nationTableLayoutHandle = new TableLayoutHandle(connectorId, TestingTransactionHandle.create(), new TpchTableLayoutHandle((TpchTableHandle) nationTableHandle.getConnectorHandle(), TupleDomain.all())); }</code><technical_language>ditto :)</technical_language>

Target:
public void setup() { metadata = getQueryRunner().getMetadata(); sqlParser = getQueryRunner().getSqlParser(); TpchTableHandle nationTpchTableHandle = new TpchTableHandle("nation", 1.0); ConnectorId connectorId = getCurrentConnectorId(); nationTableHandle = new TableHandle( connectorId, nationTpchTableHandle, TestingTransactionHandle.create(), Optional.of(new TpchTableLayoutHandle(nationTpchTableHandle, TupleDomain.all()))); }
Source:
<code>public void shouldAddDefaultHeaders() throws Exception { systemEnvironment.setProperty("gocd.enable.hsts.header", "true"); filter.doFilter(request, response, chain); verify(response).isCommitted(); verify(response).setHeader("X-XSS-Protection", "1; mode=block"); verify(response).setHeader("X-Content-Type-Options", "nosniff"); verify(response).setHeader("X-Frame-Options", "SAMEORIGIN"); verify(response).setHeader("X-UA-Compatible", "chrome=1"); <START> verify(response).setHeader("Strict-Transport-Security", "31536000"); <END> }</code><technical_language>Is Strict-Transport-Security: 31536000 Strict-Transport-Security: max-age=31536000</technical_language>

Target:
public void shouldAddDefaultHeaders() throws Exception { systemEnvironment.setProperty("gocd.enable.hsts.header", "true"); filter.doFilter(request, response, chain); verify(response).isCommitted(); verify(response).setHeader("X-XSS-Protection", "1; mode=block"); verify(response).setHeader("X-Content-Type-Options", "nosniff"); verify(response).setHeader("X-Frame-Options", "SAMEORIGIN"); verify(response).setHeader("X-UA-Compatible", "chrome=1"); verify(response).setHeader("Strict-Transport-Security", "max-age=31536000"); }
Source:
<code>private static String[] getFolders() { File backupFolder = new File(BACKUP_FOLDER); String[] folders = backupFolder.list(); if (folders == null) { return new String[] {}; } List<String> listOfFolders = Arrays.asList(folders); <START> listOfFolders.sort(new Comparator<String>() { <END> @Override public int compare(String o1, String o2) { DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd HH.mm.ss"); try { Date firstDate = dateFormat.parse(o1); Date secondDate = dateFormat.parse(o2); return secondDate.compareTo(firstDate); } catch (ParseException e) { return 0; } } }); listOfFolders.toArray(folders); return folders; }</code><technical_language>this a lambda</technical_language>

Target:
private static String[] getFolders() { File backupFolder = new File(BACKUP_FOLDER); String[] folders = backupFolder.list(); if (folders == null) { return new String[] {}; } List<String> listOfFolders = Arrays.asList(folders); listOfFolders.sort((o1, o2) -> { DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd HH.mm.ss"); try { Date firstDate = dateFormat.parse(o1); Date secondDate = dateFormat.parse(o2); return secondDate.compareTo(firstDate); } catch (ParseException e) { return 0; } }); listOfFolders.toArray(folders); return folders; }
Source:
<code>public void testBasicDeletion() throws Exception { ifServerRespond = true; <START> initialize("9"); <END> ServerErrorCode[] serverErrorCodes = new ServerErrorCode[9]; Arrays.fill(serverErrorCodes, ServerErrorCode.No_Error); writeBlobRecordToServers(serverErrorCodes); future = router.deleteBlob(blobIdString, new ClientCallback()); future.get(); assertCloseCleanup(); }</code><technical_language>"9" a constant places</technical_language>

Target:
public void testBasicDeletion() throws Exception { ServerErrorCode[] serverErrorCodes = new ServerErrorCode[9]; Arrays.fill(serverErrorCodes, ServerErrorCode.No_Error); presetServerErrorCode(serverErrorCodes); future = router.deleteBlob(blobIdString, new ClientCallback()); future.get(); }
Source:
<code>public Optional<Message> next() { try { if (readQueue.isEmpty()) { ConsumerRecords<byte[], byte[]> records = consumer.poll(pollTimeout); try { for (ConsumerRecord<byte[], byte[]> record : records) { readQueue.add(convertToMessage(record)); } } catch (Exception ex) { logger.error("Failed to read message for subscription {}, readQueueSize {}, records {}", subscription.getQualifiedName(), readQueue.size(), records.count(), ex); } } return Optional.ofNullable(readQueue.poll()); } catch (InterruptException ex ) { <START> logger.debug("Interrupting kafka consumer...", ex); <END> Thread.currentThread().interrupt(); return Optional.empty(); } catch (KafkaException ex) { logger.error("Error while reading message for subscription {}", subscription.getQualifiedName(), ex); return Optional.empty(); } catch (Exception ex) { logger.error("Failed to read message for subscription {}, readQueueSize {}", subscription.getQualifiedName(), readQueue.size(), ex); return Optional.empty(); } }</code><technical_language>info level fine here. Also, message reflect reality more if "Kafka consumer thread interrupted", do think</technical_language>

Target:
public Optional<Message> next() { try { if (readQueue.isEmpty()) { ConsumerRecords<byte[], byte[]> records = consumer.poll(pollTimeout); try { for (ConsumerRecord<byte[], byte[]> record : records) { readQueue.add(convertToMessage(record)); } } catch (Exception ex) { logger.error("Failed to read message for subscription {}, readQueueSize {}, records {}", subscription.getQualifiedName(), readQueue.size(), records.count(), ex); } } return Optional.ofNullable(readQueue.poll()); } catch (InterruptException ex ) { logger.info("Kafka consumer thread interrupted", ex); Thread.currentThread().interrupt(); return Optional.empty(); } catch (KafkaException ex) { logger.error("Error while reading message for subscription {}", subscription.getQualifiedName(), ex); return Optional.empty(); } catch (Exception ex) { logger.error("Failed to read message for subscription {}, readQueueSize {}", subscription.getQualifiedName(), readQueue.size(), ex); return Optional.empty(); } }
Source:
<code>public static int getSmallImageGrade(Product product) { String nutritionGrade = null; if (product != null) { <START> nutritionGrade = product.getNutritionGradeFr() != null ? product.getNutritionGradeFr() : product.getNutritionGradeTag(); <END> } return getSmallImageGrade(nutritionGrade); }</code><technical_language>do prefer FR grade? reason? @teolemon @Varsha-29</technical_language>

Target:
public static int getSmallImageGrade(Product product) { if (product == null) { return getSmallImageGrade((String) null); } if (product.getNutritionGradeTag() != null) { return getSmallImageGrade(product.getNutritionGradeTag()); } else { return getSmallImageGrade(product.getNutritionGradeFr()); } }
Source:
<code>public Img< DoubleType > createOutput( final IterableInterval< T > input ) { final int numDimensions = input.numDimensions(); if ( input.numDimensions() != 2 ) { throw new IllegalArgumentException( <START> "Cannot compute Hough circle transform for non-2D images. Got " + numDimensions + "D image." ); } <END> maxRadius = Math.max( minRadius, maxRadius ); minRadius = Math.min( minRadius, maxRadius ); final long nRadiuses = ( maxRadius - minRadius ) / stepRadius + 1; final long[] dims = new long[ numDimensions + 1 ]; for ( int d = 0; d < numDimensions; d++ ) dims[ d ] = input.dimension( d ); dims[ numDimensions ] = nRadiuses; final Dimensions dimensions = FinalDimensions.wrap( dims ); final ImgFactory< DoubleType > factory = ops().create().imgFactory( dimensions ); final Img< DoubleType > votes = factory.create( dimensions, new DoubleType() ); return votes; }</code><technical_language>This needed of Contingent below</technical_language>

Target:
public Img<DoubleType> createOutput(final IterableInterval<T> input) { final long maxR = Math.max(minRadius, maxRadius); final long minR = Math.min(minRadius, maxRadius); maxRadius = maxR; minRadius = minR; final long nRadiuses = (maxRadius - minRadius) / stepRadius + 1; final int numDimensions = input.numDimensions(); final long[] dims = new long[numDimensions + 1]; for (int d = 0; d < numDimensions; d++) dims[d] = input.dimension(d); dims[numDimensions] = nRadiuses; final Dimensions dimensions = FinalDimensions.wrap(dims); final ImgFactory<DoubleType> factory = ops().create().imgFactory( dimensions); final Img<DoubleType> votes = factory.create(dimensions, new DoubleType()); return votes; }
Source:
<code>public void tearDown() throws Exception { InitialSQL ini = new InitialSQL(mConfig); ini.exe(); ProjectManager projectManager = new ProjectManager(); projectManager.deleteAllProject(); <START> <END> ini = null; mCP = null; mConfig = null; mControl = null; }</code><technical_language>loss set test mode false</technical_language>

Target:
public void tearDown() throws Exception { InitialSQL ini = new InitialSQL(mConfig); ini.exe(); ProjectManager projectManager = new ProjectManager(); projectManager.deleteAllProject(); mConfig.setTestMode(false); mConfig.save(); ini = null; mCP = null; mConfig = null; mControl = null; }
Source:
<code>protected List<MethodMatcher> getMethodInvocationMatchers() { return ImmutableList.of( MethodMatcher.create() <START> .typeDefinition(TypeCriteria.is("javax.crypto.Cipher")) <END> .name("getInstance") .withAnyParameters(), MethodMatcher.create() .typeDefinition(TypeCriteria.is("org.apache.commons.crypto.utils.Utils")) .name("getCipherInstance") .withAnyParameters()); }</code><technical_language>string overload TypeCriteria is exact match</technical_language>

Target:
protected List<MethodMatcher> getMethodInvocationMatchers() { return ImmutableList.of( MethodMatcher.create() .typeDefinition("javax.crypto.Cipher") .name("getInstance") .withAnyParameters(), MethodMatcher.create() .typeDefinition("org.apache.commons.crypto.utils.Utils") .name("getCipherInstance") .withAnyParameters()); }
Source:
<code>public void shoulReturnSameResourceVariant() throws Exception { String fileName = "Main.java"; File file = testRepo.createFile(iProject, fileName); testRepo.appendContentAndCommit(iProject, file, "class Main {}", "initial commit"); IFile mainJava = testRepo.getIFile(iProject, file); GitSynchronizeData data = new GitSynchronizeData(repo, Constants.HEAD, Constants.MASTER, false); GitSynchronizeDataSet dataSet = new GitSynchronizeDataSet(data); GitResourceVariantTree grvt = new GitRemoteResourceVariantTree(dataSet); IResourceVariant actual = grvt.getResourceVariant(mainJava); assertNotNull(actual); assertEquals(fileName, actual.getName()); InputStream actualIn = actual.getStorage(new NullProgressMonitor()) .getContents(); byte[] actualByte = new byte[actualIn.available()]; actualIn.read(actualByte); <START> InputStream expectedIn = mainJava.getContents(); <END> byte[] expectedByte = new byte[expectedIn.available()]; expectedIn.read(expectedByte); assertArrayEquals(expectedByte, actualByte); }</code><technical_language>This input stream is closed. This leads test errors project deleted in tearDown,</technical_language>

Target:
public void shoulReturnSameResourceVariant() throws Exception { String fileName = "Main.java"; File file = testRepo.createFile(iProject, fileName); testRepo.appendContentAndCommit(iProject, file, "class Main {}", "initial commit"); IFile mainJava = testRepo.getIFile(iProject, file); GitSynchronizeData data = new GitSynchronizeData(repo, Constants.HEAD, Constants.MASTER, false); GitSynchronizeDataSet dataSet = new GitSynchronizeDataSet(data); GitResourceVariantTree grvt = new GitRemoteResourceVariantTree(dataSet); IResourceVariant actual = grvt.getResourceVariant(mainJava); assertNotNull(actual); assertEquals(fileName, actual.getName()); InputStream actualIn = actual.getStorage(new NullProgressMonitor()) .getContents(); byte[] actualByte = getBytesAndCloseStream(actualIn); InputStream expectedIn = mainJava.getContents(); byte[] expectedByte = getBytesAndCloseStream(expectedIn); assertArrayEquals(expectedByte, actualByte); }
Source:
<code>public Task<Void> saveInBackground(final ProgressCallback uploadProgressCallback) { if (data != null && file != null) { throw new IllegalArgumentException("File and data can not be set at the same time"); } <START> <END> final Task<Void>.TaskCompletionSource cts = Task.create(); currentTasks.add(cts); return ParseUser.getCurrentSessionTokenAsync().onSuccessTask(new Continuation<String, Task<Void>>() { @Override public Task<Void> then(Task<String> task) throws Exception { final String sessionToken = task.getResult(); return saveAsync(sessionToken, uploadProgressCallback, cts.getTask()); } }).continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { cts.trySetResult(null); currentTasks.remove(cts); return task; } }); }</code><technical_language>Is this possible? circumstances</technical_language>

Target:
public Task<Void> saveInBackground(final ProgressCallback uploadProgressCallback) { final Task<Void>.TaskCompletionSource cts = Task.create(); currentTasks.add(cts); return ParseUser.getCurrentSessionTokenAsync().onSuccessTask(new Continuation<String, Task<Void>>() { @Override public Task<Void> then(Task<String> task) throws Exception { final String sessionToken = task.getResult(); return saveAsync(sessionToken, uploadProgressCallback, cts.getTask()); } }).continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { cts.trySetResult(null); currentTasks.remove(cts); return task; } }); }
Source:
<code><START> protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { <END> if (args.length == 3 && sender.isAuthorized("essentials.speed.others", ess)) { return getPlayers(server, sender); } else { return Collections.emptyList(); } }</code><technical_language>This tab method is a weird, suggest user entered 2 args already, making useless currently</technical_language>

Target:
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { if (args.length == 1) { return types; } else if (args.length == 2) { return speeds; } else if (args.length == 3 && sender.isAuthorized("essentials.speed.others", ess)) { return getPlayers(server, sender); } else { return Collections.emptyList(); } }
Source:
<code>public final BlobQuickQueryInputStream openInputStream(String expression, BlobQuickQuerySerialization input, BlobQuickQuerySerialization output, BlobRequestConditions requestConditions, ErrorReceiver<BlobQuickQueryError> nonFatalErrorReceiver, ProgressReceiver progressReceiver) { Flux<ByteBuffer> data = client.queryWithResponse(expression, input, output, requestConditions) .flatMapMany(ResponseBase::getValue); FluxInputStream fluxInputStream = new FluxInputStream(data, logger); <START> return new BlobQuickQueryInputStream(fluxInputStream, nonFatalErrorReceiver, progressReceiver); <END> }</code><technical_language>a progress receiver? Typically parallel operations</technical_language>

Target:
public final BlobQuickQueryInputStream openInputStream(String expression, BlobQuickQuerySerialization input, BlobQuickQuerySerialization output, BlobRequestConditions requestConditions, ErrorReceiver<BlobQuickQueryError> nonFatalErrorReceiver, ProgressReceiver progressReceiver) { Flux<ByteBuffer> data = client.queryWithResponse(expression, input, output, requestConditions) .flatMapMany(BlobQuickQueryAsyncResponse::getValue); FluxInputStream fluxInputStream = new FluxInputStream(data, logger); return new BlobQuickQueryInputStream(fluxInputStream, nonFatalErrorReceiver, progressReceiver); }
Source:
<code>private static void dumpThreads(String safeTestName, List<String> pids) { try { File jstackFile = new File(System.getProperty("java.home") + "/../bin/jstack"); if (!jstackFile.canExecute()) { jstackFile = new File(System.getProperty("java.home") + "/bin/jstack"); } LocalDateTime now = LocalDateTime.now(); if (jstackFile.canExecute() && !pids.isEmpty()) { for (String pid : pids) { File dumpFile = new File(String.format("threaddump-%1$s-%2$tY-%2$tm-%2$td-%3$s.log", safeTestName, now, pid)); System.out.printf("Dumping thread stacks of process %s to %s\n", pid, dumpFile.getAbsolutePath()); Process jstack = new ProcessBuilder() <START> .command(System.getProperty("java.home") + "/../bin/jstack", pid) <END> .redirectOutput(dumpFile) .start(); jstack.waitFor(10, SECONDS); } } else { File dumpFile = new File(String.format("threaddump-%1$s-%2$tY-%2$tm-%2$td.log", safeTestName, now)); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); try (PrintWriter writer = new PrintWriter(new FileWriter(dumpFile))) { writer.printf("%1$tF %1$tT\nTest thread dump:\n\n", now); ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true); for (ThreadInfo thread : threads) { dumpThread(writer, thread); } } } } catch (Exception e) { System.err.println("Error dumping threads:"); e.printStackTrace(System.err); } }</code><technical_language>Surely this jstackFile.getAbsolutePath()</technical_language>

Target:
private static void dumpThreads(String safeTestName, List<String> pids) { try { File jstackFile = new File(System.getProperty("java.home") + "/../bin/jstack"); if (!jstackFile.canExecute()) { jstackFile = new File(System.getProperty("java.home") + "/bin/jstack"); } LocalDateTime now = LocalDateTime.now(); if (jstackFile.canExecute() && !pids.isEmpty()) { for (String pid : pids) { File dumpFile = new File(String.format("threaddump-%1$s-%2$tY-%2$tm-%2$td-%3$s.log", safeTestName, now, pid)); System.out.printf("Dumping thread stacks of process %s to %s\n", pid, dumpFile.getAbsolutePath()); Process jstack = new ProcessBuilder() .command(jstackFile.getAbsolutePath(), pid) .redirectOutput(dumpFile) .start(); jstack.waitFor(10, SECONDS); } } else { File dumpFile = new File(String.format("threaddump-%1$s-%2$tY-%2$tm-%2$td.log", safeTestName, now)); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); try (PrintWriter writer = new PrintWriter(new FileWriter(dumpFile))) { writer.printf("%1$tF %1$tT\nTest thread dump:\n\n", now); ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true); for (ThreadInfo thread : threads) { dumpThread(writer, thread); } } } } catch (Exception e) { System.err.println("Error dumping threads:"); e.printStackTrace(System.err); } }
Source:
<code>public static void tearDown() throws Exception { List inputList = new ArrayList<>(); inputList.addAll(Arrays.asList(SessionVars.GROUPBY_MULTI_LEVEL_ENABLED.keyname())); <START> client.unsetSessionVariables(inputList); <END> }</code><technical_language>rewritten a simple Arrays.asList() call</technical_language>

Target:
public static void tearDown() throws Exception { client.unsetSessionVariables(Arrays.asList(SessionVars.GROUPBY_MULTI_LEVEL_ENABLED.keyname())); }
Source:
<code>public boolean configureNetworkRulesVMSecondaryIP(final Connect conn, final String vmName, final String secIp, final String action) { if (!_canBridgeFirewall) { return false; } <START> final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); <END> cmd.add("network_rules_vmSecondaryIp"); cmd.add("--vmname", vmName); cmd.add("--nicsecips", secIp); cmd.add("--action", action); final String result = cmd.execute(); if (result != null) { return false; } return true; }</code><technical_language>Please consider adding overridden version of Script(String, int, Logger) constructor accepts Duration encapsulate this type conversion</technical_language>

Target:
public boolean configureNetworkRulesVMSecondaryIP(final Connect conn, final String vmName, final String secIp, final String action) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("network_rules_vmSecondaryIp"); cmd.add("--vmname", vmName); cmd.add("--nicsecips", secIp); cmd.add("--action", action); final String result = cmd.execute(); if (result != null) { return false; } return true; }
Source:
<code>public void setup() { hydrator = new HandlebarsHydrator(); testClass = new DynamicConfigValidator(CONFIG_PATH); try { testClass.readAndValidateConfigs(); } catch (IOException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>I this reverted</technical_language>

Target:
public void setup() throws IOException { hydrator = new HandlebarsHydrator(); testClass = new DynamicConfigValidator(CONFIG_PATH); testClass.readAndValidateConfigs(); }
Source:
<code>public void test() { String title = getViewTitle(); SWTBotView viewBot = fBot.viewByTitle(title); viewBot.show(); viewBot.setFocus(); TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(this, START_TIME)); fBot.waitUntil(ConditionHelpers.timeGraphIsReadyCondition((AbstractTimeGraphView) viewBot.getViewReference().getPart(false), new TmfTimeRange(START_TIME, START_TIME), START_TIME)); openDialog(viewBot); SWTBotShell shell = fBot.shell("Find"); SWTBot bot = shell.bot(); SWTBotButton findButton = bot.button("Fi&nd"); String text = getFindText(); testWrapSearch(text, bot, findButton, viewBot); testDirectionSearch(true, text, bot, findButton, viewBot); testCaseSensitive(text, bot, findButton); final @NonNull String ttext = text.split(SPACE)[0]; testWholeWord(ttext, bot, findButton); testRegEx(REGEX_PREFIX + ttext, bot, findButton); <START> testDirectionSearch(false, text, bot, findButton, viewBot); <END> }</code><technical_language>close find, re-open re-close please</technical_language>

Target:
public void test() { String title = getViewTitle(); SWTBotView viewBot = fBot.viewByTitle(title); viewBot.show(); viewBot.setFocus(); TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(this, START_TIME)); fBot.waitUntil(ConditionHelpers.timeGraphIsReadyCondition((AbstractTimeGraphView) viewBot.getViewReference().getPart(false), new TmfTimeRange(START_TIME, START_TIME), START_TIME)); openDialog(viewBot); SWTBot bot = getDialogBot(); SWTBotButton findButton = bot.button("Fi&nd"); String text = getFindText(); testWrapSearch(text, bot, findButton, viewBot); testDirectionSearch(true, text, bot, findButton, viewBot); testCaseSensitive(text, bot, findButton); final @NonNull String ttext = text.split(SPACE)[0]; testWholeWord(ttext, bot, findButton); testRegEx(REGEX_PREFIX + ttext, bot, findButton); testDirectionSearch(false, text, bot, findButton, viewBot); testOpenCloseDialog(viewBot); }
Source:
<code>public void sendVerificationmail(User user, String url) { String message = "Please click on the following link to complete your registration: <a href=\"" + url + "\">" + url + "</a><br /><br />If the link does not work, please copy the link and" + " paste it into your browser."; <START> sendMail(user.getUsername(), user.getProfile().getFirstName() + " " + user.getProfile().getLastName(), "Confirm your registration", message); <END> }</code><technical_language>Sille said: Please note this is possible, first- lastname set here</technical_language>

Target:
public void sendVerificationmail(User user, String url) { String message = "Please click on the following link to complete your registration: <a href=\"" + url + "\">" + url + "</a><br /><br />If the link does not work, please copy the link and" + " paste it into your browser."; sendMail(user.getUsername(), formatRecipient(user), "Confirm your registration", message); }
Source:
<code>protected void processValidationSet(GroupDescription processedDescription, GroupDescription currentDescription, TransformationCache cache) { if (currentDescription.eIsSet(VALIDATIONSET_FEATURE)) { <START> if (processedDescription.getValidationSet() == null) { <END> GroupValidationSetDescription validationSet = PropertiesFactory.eINSTANCE.createGroupValidationSetDescription(); processedDescription.setValidationSet(validationSet); } List<SemanticValidationRule> newSemanticValidationRules = new ArrayList<>(); for (SemanticValidationRule rule : currentDescription.getValidationSet().getSemanticValidationRules()) { newSemanticValidationRules.add(EcoreUtil.copy(rule)); } newSemanticValidationRules.addAll(processedDescription.getValidationSet().getSemanticValidationRules()); processedDescription.getValidationSet().getSemanticValidationRules().clear(); processedDescription.getValidationSet().getSemanticValidationRules().addAll(newSemanticValidationRules); List<PropertyValidationRule> newPropertyValidationRules = new ArrayList<>(); for (PropertyValidationRule rule : currentDescription.getValidationSet().getPropertyValidationRules()) { newPropertyValidationRules.add(EcoreUtil.copy(rule)); } newPropertyValidationRules.addAll(processedDescription.getValidationSet().getPropertyValidationRules()); processedDescription.getValidationSet().getPropertyValidationRules().clear(); processedDescription.getValidationSet().getPropertyValidationRules().addAll(newPropertyValidationRules); } }</code><technical_language>java8-isation [optional][orElseGet]</technical_language>

Target:
private void processValidationSet(GroupDescription processedDescription, GroupDescription currentDescription, TransformationCache cache) { if (currentDescription.eIsSet(VALIDATIONSET_FEATURE)) { GroupValidationSetDescription validationSet = Optional.ofNullable(processedDescription.getValidationSet()).orElse(PropertiesFactory.eINSTANCE.createGroupValidationSetDescription()); processedDescription.setValidationSet(validationSet); List<SemanticValidationRule> newSemanticValidationRules = new ArrayList<>(); currentDescription.getValidationSet().getSemanticValidationRules().forEach(rule -> newSemanticValidationRules.add(EcoreUtil.copy(rule))); newSemanticValidationRules.addAll(processedDescription.getValidationSet().getSemanticValidationRules()); processedDescription.getValidationSet().getSemanticValidationRules().clear(); processedDescription.getValidationSet().getSemanticValidationRules().addAll(newSemanticValidationRules); List<PropertyValidationRule> newPropertyValidationRules = new ArrayList<>(); currentDescription.getValidationSet().getPropertyValidationRules().forEach(rule -> newPropertyValidationRules.add(EcoreUtil.copy(rule))); newPropertyValidationRules.addAll(processedDescription.getValidationSet().getPropertyValidationRules()); processedDescription.getValidationSet().getPropertyValidationRules().clear(); processedDescription.getValidationSet().getPropertyValidationRules().addAll(newPropertyValidationRules); } }
Source:
<code>private void addIndicationsRepresentation(final StringBuilder stringBuilder, final IndicationUrlBuilder indicationUrlBuilder, final List<FoundIndication> indications, final int indentLevel) { final int nextIndentLevel = indentLevel + ITEM_INCREMENT; if (useHtmlFormat) { stringBuilder.append("<ul>"); for (int i = 0, size = indications.size(); i < size; ++i) { final FoundIndication indication = indications.get(i); indicationUrlBuilder.setIndication(indication); final int indicationNumber = i + 1; addIndicationRepresentation(stringBuilder, indicationUrlBuilder, indication, indicationNumber, nextIndentLevel); } stringBuilder.append("</ul>"); } else { for (int i = 0, size = indications.size(); i < size; ++i) { final FoundIndication indication = indications.get(i); indicationUrlBuilder.setIndication(indication); final int indicationNumber = i + 1; addIndicationRepresentation(stringBuilder, indicationUrlBuilder, indication, indicationNumber, nextIndentLevel); } } <START> for (int i = 0, size = indications.size(); i < size; ++i) { <END> final FoundIndication indication = indications.get(i); } }</code><technical_language>is this for loop for</technical_language>

Target:
private void addIndicationsRepresentation(final StringBuilder stringBuilder, final IndicationUrlBuilder indicationUrlBuilder, final List<FoundIndication> indications, final int indentLevel) { final int nextIndentLevel = indentLevel + ITEM_INCREMENT; if (useHtmlFormat) { stringBuilder.append("<ul>"); for (int i = 0, size = indications.size(); i < size; ++i) { final FoundIndication indication = indications.get(i); indicationUrlBuilder.setIndication(indication); final int indicationNumber = i + 1; addIndicationRepresentation(stringBuilder, indicationUrlBuilder, indication, indicationNumber, nextIndentLevel); } stringBuilder.append("</ul>"); } else { for (int i = 0, size = indications.size(); i < size; ++i) { final FoundIndication indication = indications.get(i); indicationUrlBuilder.setIndication(indication); final int indicationNumber = i + 1; addIndicationRepresentation(stringBuilder, indicationUrlBuilder, indication, indicationNumber, nextIndentLevel); } } }
Source:
<code>private void blockUntilReady() { try { <START> readyForEvents.await(); <END> } catch (InterruptedException e) { } }</code><technical_language>problems for ManagementCacheListener apply here</technical_language>

Target:
private void blockUntilReady() { try { readyForEvents.await(); } catch (InterruptedException e) { Thread.interrupted(); throw new RuntimeException(e); } }
Source:
<code>public void setup() throws NoSuchFieldException, IllegalAccessException { <START> instanceCountField = OpenHelperManager.class.getDeclaredField("instanceCount"); <END> instanceCountField.setAccessible(true); setInstanceCountToZero(); controller = Robolectric.buildActivity(OrmLiteOnDestroyActivity_.class).create(); }</code><technical_language>Please FEST reflect fluent API</technical_language>

Target:
public void setup() throws NoSuchFieldException, IllegalAccessException { staticField("helper").ofType(OrmLiteSqliteOpenHelper.class).in(OpenHelperManager.class).set(null); staticField("helperClass").ofType(Class.class).in(OpenHelperManager.class).set(null); staticField("wasClosed").ofType(boolean.class).in(OpenHelperManager.class).set(false); instanceCountInvoker = staticField("instanceCount").ofType(int.class).in(OpenHelperManager.class); instanceCountInvoker.set(0); controller = Robolectric.buildActivity(OrmLiteOnDestroyActivity_.class).create(); }
Source:
<code>private ElementRecord getElement(String id) { try { return sxe.getDocumentRecord().getElementRecordById(id); } catch (MissingRecordException e) { <START> LOG.error("trying to set access an element that does NOT" <END> + " exist, the changes will be ignored.", e); return null; } }</code><technical_language>set do add id ? Currently this message is helpful if want debug issue id is silently swallowed. is id part contained in MissingRecordException</technical_language>

Target:
private ElementRecord getElement(String id) { try { return sxe.getDocumentRecord().getElementRecordById(id); } catch (MissingRecordException e) { LOG.error("trying to access an element that does NOT" + " exist, the changes will be ignored.", e); return null; } }
Source:
<code>public void setSubscriptions(List<String> subscriptions) { this.subscriptions.clear(); if(subscriptions == null) return; for(String currentSubscription: subscriptions) { <START> if (this.getNotifierName().equals(AlertService.SupportedNotifier.GUS.getName())) { <END> if (currentSubscription.length() < 10) throw new IllegalArgumentException("GUS subjectId is incorrect."); } else if (this.getNotifierName().equals(AlertService.SupportedNotifier.EMAIL.getName())) { if (!currentSubscription.matches(EMAILREGEX)) { String errorMessage = MessageFormat.format("Email Address is incorrect. {0}", currentSubscription); throw new IllegalArgumentException(errorMessage); } } } if (subscriptions != null && !subscriptions.isEmpty()) { this.subscriptions.addAll(subscriptions); } }</code><technical_language>I assume regex change is intentional part of fix, right? making a constant</technical_language>

Target:
public void setSubscriptions(List<String> subscriptions) { this.subscriptions.clear(); if(subscriptions == null) return; for(String currentSubscription: subscriptions) { if (this.getNotifierName().equals(AlertService.SupportedNotifier.GUS.getName())) { if (currentSubscription.length() < 10) throw new IllegalArgumentException("GUS subjectId is incorrect."); } else if (this.getNotifierName().equals(AlertService.SupportedNotifier.EMAIL.getName())) { if (!currentSubscription.matches(EMAILREGEX)) { String errorMessage = MessageFormat.format("Email Address {0} is not allowed according to Regex {1}.", currentSubscription, EMAILREGEX); throw new IllegalArgumentException(errorMessage); } } } if (subscriptions != null && !subscriptions.isEmpty()) { this.subscriptions.addAll(subscriptions); } }
Source:
<code>public <T> Collection<Binding<T>> bindConsumer(T input, String inputName) { String bindingTarget = this.channelBindingServiceProperties .getBindingDestination(inputName); String[] bindingTargets = StringUtils .commaDelimitedListToStringArray(bindingTarget); Collection<Binding<T>> bindings = new ArrayList<>(); Binder<T, ConsumerProperties, ?> binder = (Binder<T, ConsumerProperties, ?>) getBinder( inputName, input.getClass()); ConsumerProperties consumerProperties = this.channelBindingServiceProperties .getConsumerProperties(inputName); if (binder instanceof ExtendedPropertiesBinder) { Object extension = ((ExtendedPropertiesBinder) binder) .getExtendedConsumerProperties(inputName); ExtendedConsumerProperties extendedConsumerProperties = new ExtendedConsumerProperties( extension); BeanUtils.copyProperties(consumerProperties, extendedConsumerProperties); consumerProperties = extendedConsumerProperties; } validate(consumerProperties); for (String target : bindingTargets) { Binding<T> binding = binder.bindConsumer(target, channelBindingServiceProperties.getGroup(inputName), input, consumerProperties); bindings.add(binding); } bindings = Collections.unmodifiableCollection(bindings); this.consumerBindings.put(inputName, new ArrayList<Binding<?>>(bindings)); <START> return Collections.unmodifiableCollection(bindings); <END> }</code><technical_language>return bindings unmodifiable</technical_language>

Target:
public <T> Collection<Binding<T>> bindConsumer(T input, String inputName) { String bindingTarget = this.channelBindingServiceProperties .getBindingDestination(inputName); String[] bindingTargets = StringUtils .commaDelimitedListToStringArray(bindingTarget); Collection<Binding<T>> bindings = new ArrayList<>(); Binder<T, ConsumerProperties, ?> binder = (Binder<T, ConsumerProperties, ?>) getBinder( inputName, input.getClass()); ConsumerProperties consumerProperties = this.channelBindingServiceProperties .getConsumerProperties(inputName); if (binder instanceof ExtendedPropertiesBinder) { Object extension = ((ExtendedPropertiesBinder) binder) .getExtendedConsumerProperties(inputName); ExtendedConsumerProperties extendedConsumerProperties = new ExtendedConsumerProperties( extension); BeanUtils.copyProperties(consumerProperties, extendedConsumerProperties); consumerProperties = extendedConsumerProperties; } validate(consumerProperties); for (String target : bindingTargets) { Binding<T> binding = binder.bindConsumer(target, channelBindingServiceProperties.getGroup(inputName), input, consumerProperties); bindings.add(binding); } bindings = Collections.unmodifiableCollection(bindings); this.consumerBindings.put(inputName, new ArrayList<Binding<?>>(bindings)); return bindings; }
Source:
<code>public boolean exists(URI uri, Map<?, ?> options) { boolean exists = false; try { <START> IStorageProvider storageProvider = storageAccessor.getStorageProvider(getResourceFromURI(uri), <END> side); if (storageProvider != null) { exists = storageProvider.getStorage(new NullProgressMonitor()) != null; } else { exists = super.exists(uri, options); } } catch (CoreException e) { EMFCompareIDEUIPlugin.getDefault().log(IStatus.ERROR, e.getMessage()); } return exists; }</code><technical_language>normalize uri is done in other method, kind of URI receive here</technical_language>

Target:
public boolean exists(URI uri, Map<?, ?> options) { boolean exists = false; try { final URI normalizedUri = normalize(uri); IStorageProvider storageProvider = storageAccessor.getStorageProvider( getResourceFromURI(normalizedUri), side); if (storageProvider != null) { exists = storageProvider.getStorage(new NullProgressMonitor()) != null; } else { exists = super.exists(normalizedUri, options); } } catch (CoreException e) { EMFCompareIDEUIPlugin.getDefault().log(IStatus.ERROR, e.getMessage()); } return exists; }
Source:
<code>private boolean <START> isSupportedExternalType(ProviderNetwork <END> providerNetwork) { return BaseNetworkProviderProxy.FLAT_NETWORK.equals(providerNetwork.getProviderNetworkType()) || BaseNetworkProviderProxy.VLAN_NETWORK.equals(providerNetwork.getProviderNetworkType()); }</code><technical_language>I implemented in another ;-) , this is valid, too</technical_language>

Target:
private boolean isSupportedExternalType(ProviderNetwork providerNetwork) { return providerNetwork.isProviderNetworkFlat() || providerNetwork.isProviderNetworkVlan(); }