auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void snapshotOnVersionChange() throws IOException { String previous = getPreviousVersionString(); String next = FBUtilities.getReleaseVersionString(); RateLimiter snapshotRateLimiter = RateLimiter.create(DatabaseDescriptor.getSnapshotLinksPerSecond() == 0 ? Double.MAX_VALUE : DatabaseDescriptor.getSnapshotLinksPerSecond()); if (!previous.equals(NULL_VERSION.toString()) && !previous.equals(next)) { logger.info("Detected version upgrade from to {}, snapshotting system keyspaces", previous, next); String snapshotName = Keyspace.getTimestampedSnapshotName(format("upgrade-%s-%s", previous, next)); for (String keyspace : SchemaConstants.LOCAL_SYSTEM_KEYSPACE_NAMES) <START> Keyspace.open(keyspace).snapshot(snapshotName, null, false, snapshotRateLimiter); <END> } }</code><technical_language>system keyspace do a snapshot rate limiter ? System keyspace sstables. for example, if set rate 2 this affect speed of setup for snapshotOnVersionChange , data keyspace's snapshot speed of 2 is want</technical_language>

Target:
public static void snapshotOnVersionChange() throws IOException { String previous = getPreviousVersionString(); String next = FBUtilities.getReleaseVersionString(); if (!previous.equals(NULL_VERSION.toString()) && !previous.equals(next)) { logger.info("Detected version upgrade from to {}, snapshotting system keyspaces", previous, next); String snapshotName = Keyspace.getTimestampedSnapshotName(format("upgrade-%s-%s", previous, next)); for (String keyspace : SchemaConstants.LOCAL_SYSTEM_KEYSPACE_NAMES) Keyspace.open(keyspace).snapshot(snapshotName, null, false, null); } }
Source:
<code>public boolean execute() throws Exception { String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); QName varName = new QName("archive", "active-archive"); SrampArchive archive = (SrampArchive) getContext().getVariable(varName); if (archive == null) { print(Messages.i18n.format("NO_ARCHIVE_OPEN")); return false; <START> } else if (archivePathArg.endsWith(File.separator)) { <END> print(Messages.i18n.format("Archive.Path.Arg.should.not.contain.slash.end")); return false; } else { boolean success = archive.removeEntry(archivePathArg); if (success) { print(Messages.i18n.format("RemoveEntry.EntryDeleted")); } else { print(Messages.i18n.format("RemoveEntry.NoEntryFound", archivePathArg)); } } return true; }</code><technical_language>Share 'validateArchivePath' method</technical_language>

Target:
public boolean execute() throws Exception { super.initialize(); String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); if (!validate(archivePathArg)) { return false; } else { boolean success = archive.removeEntry(archivePathArg); if (success) { print(Messages.i18n.format("RemoveEntry.EntryDeleted")); } else { print(Messages.i18n.format("RemoveEntry.NoEntryFound", archivePathArg)); } } return true; }
Source:
<code>public void serialEvent(SerialPortEvent portEvent) { try { <START> logger.debug("Received serial port event " + portEvent.toString() + ":" + portEvent.getEventType()); <END> logger.trace("RXTX library CPU load workaround, sleep forever"); Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { logger.warn("Unable to notify", e); } }</code><technical_language>parameterized logging instead of string concatenation, this method generating garbage objects call</technical_language>

Target:
public void serialEvent(SerialPortEvent portEvent) { try { logger.debug("Received serial port event '{}':'{}'", portEvent.toString(), portEvent.getEventType()); logger.trace("RXTX library CPU load workaround, sleep forever"); Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { logger.warn("Unable to notify", e); } }
Source:
<code><START> public void cleanup() throws IdGenerationException { <END> return; }</code><technical_language>if add this interface. implementations need generate data ids in this method. removing this instead throwing a RuntimeException implementations DataIdFactory</technical_language>

Target:
public void cleanup() { return; }
Source:
<code>public Boolean forAll(Collection<Object> collection, LambdaValue lambda) { Boolean result = Boolean.TRUE; if (collection != null && lambda == null) { result = Boolean.FALSE; } else { <START> for (Object input : collection) { <END> try { if (!Boolean.TRUE.equals(lambda.eval(new Object[] {input }))) { result = Boolean.FALSE; break; } } catch (Exception e) { result = Boolean.FALSE; break; } } } return result; }</code><technical_language>potential NPE above</technical_language>

Target:
public Boolean forAll(Collection<Object> collection, LambdaValue lambda) { Boolean result = Boolean.TRUE; if (collection == null || lambda == null) { result = Boolean.FALSE; } else { for (Object input : collection) { try { if (!Boolean.TRUE.equals(lambda.eval(new Object[] {input }))) { result = Boolean.FALSE; break; } } catch (Exception e) { result = Boolean.FALSE; break; } } } return result; }
Source:
<code>private void onButtonClick() { if (isSensorAvailable) { Intent intent = new Intent(getContext(), BearingActivity.class); waitingForDataRegistry.waitForData(getFormEntryPrompt().getIndex()); ((Activity) getContext()).startActivityForResult(intent, RequestCodes.BEARING_CAPTURE); } else { <START> binding.bearingButton.setEnabled(false); <END> ToastUtils.showLongToast(R.string.bearing_lack_of_sensors); binding.answerText.setBackground(textBackground); binding.answerText.setFocusable(true); binding.answerText.setFocusableInTouchMode(true); binding.answerText.requestFocus(); } }</code><technical_language>I mixing I showing toast i middle of other stuff. begging end</technical_language>

Target:
private void onButtonClick() { if (areSensorsAvailable()) { Intent intent = new Intent(getContext(), BearingActivity.class); ((Activity) getContext()).startActivityForResult(intent, RequestCodes.BEARING_CAPTURE); waitingForDataRegistry.waitForData(getFormEntryPrompt().getIndex()); } else { ToastUtils.showLongToast(R.string.bearing_lack_of_sensors); binding.bearingButton.setEnabled(false); binding.answerText.setBackground(new EditText(getContext()).getBackground()); binding.answerText.setFocusable(true); binding.answerText.setFocusableInTouchMode(true); binding.answerText.requestFocus(); } }
Source:
<code>public static void main(String[] args) throws Exception { Nd4j.setDataType(DataBuffer.Type.FLOAT); Cifar cf = new Cifar(); CifarDataSetIterator cifar = new CifarDataSetIterator(batchSize, numSamples, new int[] {height, width, channels}, preProcessCifar, true); CifarDataSetIterator cifarEval = new CifarDataSetIterator(batchSize, 10000, new int[] {height, width, channels}, preProcessCifar, false); MultiLayerNetwork model = cf.trainModelByCifarWithNet(); UIServer uiServer = UIServer.getInstance(); <START> StatsStorage statsStorage = new InMemoryStatsStorage(); <END> uiServer.attach(statsStorage); model.setListeners(new StatsListener( statsStorage), new ScoreIterationListener(freIterations), new EvaluativeListener(cifarEval, 1000)); labelStr = String.join(",", cifar.getLabels().toArray(new String[cifar.getLabels().size()])); model.fit(cifar, epochs); cf.testModelByUnkownImage(model); cf.saveModel(model, "trainModelByCifarWithAlexNet_model.json"); }</code><technical_language>Switch FileStatsStorage due overhead/memory</technical_language>

Target:
public static void main(String[] args) throws Exception { Cifar cf = new Cifar(); Cifar10DataSetIterator cifar = new Cifar10DataSetIterator(batchSize, new int[]{height, width}, DataSetType.TRAIN, null, seed); Cifar10DataSetIterator cifarEval = new Cifar10DataSetIterator(batchSize, new int[]{height, width}, DataSetType.TEST, null, seed); MultiLayerNetwork model = cf.getModel(); UIServer uiServer = UIServer.getInstance(); StatsStorage statsStorage = new FileStatsStorage(new File(System.getProperty("java.io.tmpdir"), "ui-stats.dl4j")); uiServer.attach(statsStorage); model.setListeners(new StatsListener( statsStorage), new ScoreIterationListener(50), new EvaluativeListener(cifarEval, 1, InvocationType.EPOCH_END)); model.fit(cifar, epochs); log.info("Saving model..."); model.save(new File(System.getProperty("java.io.tmpdir"), "cifarmodel.dl4j.zip"), true); System.exit(0); }
Source:
<code>private void resolve(Resource resource, IProgressMonitor monitor) { <START> SubMonitor progress = SubMonitor.convert(monitor); <END> resource.eSetDeliver(false); final List<EObject> roots = ((InternalEList<EObject>)resource.getContents()).basicList(); final Iterator<EObject> resourceContent = roots.iterator(); resource.getContents().clear(); SubMonitor subMonitor = progress.newChild(roots.size()); while (resourceContent.hasNext()) { final EObject eObject = resourceContent.next(); resolveCrossReferences(eObject); final TreeIterator<EObject> childContent = basicEAllContents(eObject); SubMonitor childMonitor = subMonitor.newChild(0); while (childContent.hasNext()) { progress.setWorkRemaining(10000); final EObject child = childContent.next(); if (child.eIsProxy()) { final URI proxyURI = ((InternalEObject)child).eProxyURI(); getResource(proxyURI.trimFragment(), false); } else { resolveCrossReferences(child); } childMonitor.worked(1); } subMonitor.worked(1); } resource.getContents().addAll(roots); }</code><technical_language>size this</technical_language>

Target:
private void resolve(Resource resource, IProgressMonitor monitor) { resource.eSetDeliver(false); final List<EObject> roots = ((InternalEList<EObject>)resource.getContents()).basicList(); final Iterator<EObject> resourceContent = roots.iterator(); resource.getContents().clear(); SubMonitor subMonitor = SubMonitor.convert(monitor, roots.size()); while (resourceContent.hasNext()) { final EObject eObject = resourceContent.next(); resolveCrossReferences(eObject); final TreeIterator<EObject> childContent = basicEAllContents(eObject); SubMonitor childMonitor = subMonitor.newChild(1); while (childContent.hasNext()) { childMonitor.setWorkRemaining(10000); final EObject child = childContent.next(); if (child.eIsProxy()) { final URI proxyURI = ((InternalEObject)child).eProxyURI(); getResource(proxyURI.trimFragment(), false); } else { resolveCrossReferences(child); } childMonitor.worked(1); } } resource.getContents().addAll(roots); }
Source:
<code>private static void insertConcurrent(CqlSession session) throws InterruptedException { PreparedStatement pst = session.prepare( insertInto("examples", "tbl_sample_kv") .value("id", bindMarker("id")) .value("value", bindMarker("value")) .build()); AtomicInteger insertsCounter = new AtomicInteger(); Set<String> threads = new ConcurrentSkipListSet<>(); ExecutorService executor = Executors.newFixedThreadPool(CONCURRENCY_LEVEL); for (int i = 0; i < TOTAL_NUMBER_OF_INSERTS; i++) { SEMAPHORE.acquire(); final int counter = i; <START> CompletableFuture.supplyAsync( <END> () -> { insertsCounter.incrementAndGet(); threads.add(Thread.currentThread().getName()); ResultSet executeRequest; try { executeRequest = session.execute( pst.bind().setUuid("id", UUID.randomUUID()).setInt("value", counter)); } finally { REQUEST_LATCH.countDown(); SEMAPHORE.release(); } return executeRequest; }, executor); } REQUEST_LATCH.await(); System.out.println( String.format( "Finished executing %s queries with a concurrency level of %s.", insertsCounter.get(), threads.size())); executor.shutdown(); }</code><technical_language>I easier follow if executor.submit. Also, need return executeRequest, resulting future anyways</technical_language>

Target:
private static void insertConcurrent(CqlSession session) throws InterruptedException { PreparedStatement pst = session.prepare( insertInto("examples", "tbl_sample_kv") .value("id", bindMarker("id")) .value("value", bindMarker("value")) .build()); AtomicInteger insertsCounter = new AtomicInteger(); ExecutorService executor = Executors.newFixedThreadPool(CONCURRENCY_LEVEL); for (int i = 0; i < TOTAL_NUMBER_OF_INSERTS; i++) { SEMAPHORE.acquire(); final int counter = i; executor.submit( () -> { try { session.execute(pst.bind().setUuid("id", UUID.randomUUID()).setInt("value", counter)); insertsCounter.incrementAndGet(); } catch (Throwable t) { t.printStackTrace(); } finally { REQUEST_LATCH.countDown(); SEMAPHORE.release(); } }); } REQUEST_LATCH.await(); System.out.println( String.format( "Finished executing %s queries with a concurrency level of %s.", insertsCounter.get(), CONCURRENCY_LEVEL)); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); }
Source:
<code>public CompletionStage<Void> putAllAsync(@Nonnull K key, @Nonnull Collection<? extends V> value) { checkTrueUnsupportedOperation(isClusterVersionGreaterOrEqual(Versions.V4_1), MINIMUM_VERSION_ERROR_4_1); InternalCompletableFuture<Void> future = new InternalCompletableFuture<>(); Map<Data, Data> dataMap = new HashMap<>(); Collection<Data> dataCollection = CollectionUtil .objectToDataCollection(value, getNodeEngine().getSerializationService()); <START> dataMap.put(toData(key), toData(dataCollection)); <END> putAllInternal(dataMap, future); return future; }</code><technical_language>suggestion dataMap.put(toData(key), toData(new DataCollection(dataCollection)));</technical_language>

Target:
public CompletionStage<Void> putAllAsync(@Nonnull K key, @Nonnull Collection<? extends V> value) { checkTrueUnsupportedOperation(isClusterVersionGreaterOrEqual(Versions.V4_1), MINIMUM_VERSION_ERROR_4_1); InternalCompletableFuture<Void> future = new InternalCompletableFuture<>(); Map<Data, Data> dataMap = new HashMap<>(); Collection<Data> dataCollection = CollectionUtil .objectToDataCollection(value, getNodeEngine().getSerializationService()); dataMap.put(toData(key), toData(new DataCollection(dataCollection))); putAllInternal(dataMap, future); return future; }
Source:
<code>@Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); <START> } <END></code><technical_language>assert type also</technical_language>

Target:
@Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); }
Source:
<code>public ThrottledStorageComponent(StorageComponent delegate, MeterRegistry registry, int minConcurrency, int maxConcurrency, int maxQueueSize) { this.delegate = Objects.requireNonNull(delegate); Limit limit = Gradient2Limit.newBuilder() .minLimit(minConcurrency) .initialLimit(minConcurrency) .maxConcurrency(maxConcurrency) .queueSize(0) .build(); this.limiter = new Builder().limit(limit).build(); this.executor = new ThreadPoolExecutor(limit.getLimit(), limit.getLimit(), 0, TimeUnit.DAYS, createQueue(maxQueueSize), new ThottledThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); limit.notifyOnChange(new ThreadPoolExecutorResizer(executor)); <START> if (registry != null) { <END> ActuateThrottleMetrics metrics = new ActuateThrottleMetrics(registry); metrics.bind(executor); metrics.bind(limiter); } }</code><technical_language>do expect this null</technical_language>

Target:
public ThrottledStorageComponent(StorageComponent delegate, MeterRegistry registry, int minConcurrency, int maxConcurrency, int maxQueueSize) { this.delegate = Objects.requireNonNull(delegate); Limit limit = Gradient2Limit.newBuilder() .minLimit(minConcurrency) .initialLimit( minConcurrency) .maxConcurrency(maxConcurrency) .queueSize(0) .build(); this.limiter = new Builder().limit(limit).build(); this.executor = new ThreadPoolExecutor(limit.getLimit(), limit.getLimit(), 0, TimeUnit.DAYS, createQueue(maxQueueSize), new ThottledThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); limit.notifyOnChange(new ThreadPoolExecutorResizer(executor)); ActuateThrottleMetrics metrics = new ActuateThrottleMetrics(registry); metrics.bind(executor); metrics.bind(limiter); }
Source:
<code>public void close() throws IOException { <START> super.close(); <END> if (delegate != null) { delegate.close(); } }</code><technical_language>need call super.close</technical_language>

Target:
public void close() throws IOException { if (delegate != null) { delegate.close(); } }
Source:
<code>public void teleport(Location location, String successMessage, String failMessage) { PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location)) .thenApply(success -> { if (success) { if (successMessage != null && !successMessage.isEmpty()) { MessagingUtil.sendStringToChat(this, successMessage); } } else { if (failMessage != null && !failMessage.isEmpty()) { printError(failMessage); <START> } <END> } return success; }); }</code><technical_language>I this needs changed? need add null/isEmpty checks here, MessagingUtil.sendStringToChat</technical_language>

Target:
public void teleport(Location location, String successMessage, String failMessage) { PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location)) .thenApply(success -> { if (success) { if (!successMessage.isEmpty()) { MessagingUtil.sendStringToChat(this, successMessage); } } else { printError(failMessage); } return success; }); }
Source:
<code>public static boolean initialize(Context context) { CrashReporter.context = context; preferences = PreferenceManager.getDefaultSharedPreferences(context); setIsCrashReportEnabled(BuildConfig.CRASHLYTICS_CRASH_REPORT_ENABLED); <START> isCrashlyticsInitialized = false; <END> if (isAnonymousReportEnabled() && isCrashReportEnabled) { Fabric.with(context, new Crashlytics()); Log.d(TAG, "INITIALIZED!"); isCrashlyticsInitialized = true; return true; } Log.d(TAG, "INITIALIZATION FAILED! [ Anonymous Report : " + isAnonymousReportEnabled() + " Crash Report : " + isCrashReportEnabled + " ]"); isCrashlyticsInitialized = false; return false; }</code><technical_language>Please remove, isCrashlyticsInitialized is set in this method true false</technical_language>

Target:
public static boolean initialize(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); if (isReportingEnabled()) { Crashlytics crashlyticsKit = new Crashlytics.Builder() .core(new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()) .build(); Fabric.with(context, crashlyticsKit); Log.d(TAG, "INITIALIZED!"); return true; } Log.d(TAG, "INITIALIZATION FAILED! [ Anonymous Report : " + isAnonymousReportEnabled() + " Crash Report : " + isCrashReportEnabled + " ]"); return false; }
Source:
<code>public void handle(final ArtifactEvent event) { final Repository repository = getRepository(event); <START> if (!RepositoryLayoutEnum.MAVEN_2.getLayout().equals(repository.getLayout())) <END> { return; } if (event.getType() != ArtifactEventTypeEnum.EVENT_ARTIFACT_FILE_STORED.getType()) { return; } try { mavenIndexGroupRepositoryComponent.updateGroupsContaining(event.getStorageId(), event.getRepositoryId(), event.getPath()); } catch (final IOException e) { logger.error("Unable to update parent group repositories indexes of file " + event.getPath() + " of repository " + event.getRepositoryId(), e); } }</code><technical_language>Please, avoid RepositoryLayoutEnum.MAVEN_2.getLayout(), thinking of removing this (you check #437 for more details). possible, please Maven2LayoutProvider.ALIAS instead...? Thanks! I know, tricky remove this enum in places Repository for default layout</technical_language>

Target:
public void handle(final ArtifactEvent event) { final Repository repository = getRepository(event); if (!Maven2LayoutProvider.ALIAS.equals(repository.getLayout())) { return; } if (event.getType() != ArtifactEventTypeEnum.EVENT_ARTIFACT_FILE_STORED.getType()) { return; } try { mavenIndexGroupRepositoryComponent.updateGroupsContaining(event.getStorageId(), event.getRepositoryId(), event.getPath()); } catch (final IOException e) { logger.error("Unable to update parent group repositories indexes of file " + event.getPath() + " of repository " + event.getRepositoryId(), e); } }
Source:
<code>private void onLoginClick() { if (!PrefUtils.isSignedIn(this)) { mDrawerLayout.closeDrawer(Gravity.LEFT); <START> if (getGoogleApiClient().isConnected()) { <END> disconnectGoogleApiClient(); } PrefUtils.setSignedIn(this); createConnectedGoogleApiClient(); } }</code><technical_language>need methods below. need do is call these. PrefUtils.setSignedIn(GdgNavDrawerActivity.this); recreateGoogleApiClientIfNeeded(); getGoogleApiClient().connect();</technical_language>

Target:
private void onLoginClick() { if (!PrefUtils.isSignedIn(this)) { mDrawerLayout.closeDrawer(Gravity.LEFT); PrefUtils.setSignedIn(GdgNavDrawerActivity.this); recreateGoogleApiClientIfNeeded(); getGoogleApiClient().connect(); } }
Source:
<code>private Supplier<List<CassandraHealthMetricMeasurement>> getCassandraHealthMetricMeasurements() { return () -> cassandraHealthMetrics.get().stream().map(metric -> ImmutableCassandraHealthMetricMeasurement.builder() <START> .currentValue(cassandraMetricClient.getMetric( <END> metric.type(), metric.name(), metric.attribute(), metric.additionalParams())) .lowerLimit(metric.lowerLimit()) .upperLimit(metric.upperLimit()) .build()) .collect(Collectors.toList()); }</code><technical_language>looked Cassandra metric client code - is this a remote call</technical_language>

Target:
private Supplier<Collection<? extends CassandraHealthMetricMeasurement>> getCassandraHealthMetricMeasurements() { return cassandraHealthMetrics::getCassandraHealthMetricMeasurements; }
Source:
<code>public void restore() { <START> for (Context context : contexts) { <END> try { context.restore(); } catch (Exception e) { EmbeddedLogger.ROOT_LOGGER.failedToRestoreContext(e, context); } } }</code><technical_language>restoration in reverse order of activation? restore activated context</technical_language>

Target:
public void restore() { for (int i = (contexts.size() - 1); i >= 0; i--) { final Context context = contexts.get(i); try { context.restore(); } catch (Exception e) { EmbeddedLogger.ROOT_LOGGER.failedToRestoreContext(e, context); } } }
Source:
<code>public Integer invoke(File base, VirtualChannel channel) throws IOException { if (!base.exists()) { return 0; } assert target.channel == null; final File dest = new File(target.remote); final AtomicInteger count = new AtomicInteger(); scanner.scan(base, reading(new FileVisitor() { private boolean exceptionEncountered; @Override public void visit(File f, String relativePath) throws IOException { if (f.isFile()) { File target = new File(dest, relativePath); mkdirsE(target.getParentFile()); Path targetPath = fileToPath(writing(target)); if(!exceptionEncountered) { try { Files.copy(fileToPath(f), targetPath, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { exceptionEncountered = true; } } <START> if(exceptionEncountered) { <END> Files.copy(fileToPath(f), targetPath, StandardCopyOption.REPLACE_EXISTING); } count.incrementAndGet(); } } @Override public boolean understandsSymlink() { return true; } @Override public void visitSymlink(File link, String target, String relativePath) throws IOException { try { mkdirsE(new File(dest, relativePath).getParentFile()); writing(new File(dest, target)); Util.createSymlink(dest, target, relativePath, TaskListener.NULL); } catch (InterruptedException x) { throw new IOException(x); } count.incrementAndGet(); } })); return count.get(); }</code><technical_language>else</technical_language>

Target:
public Integer invoke(File base, VirtualChannel channel) throws IOException { if (!base.exists()) { return 0; } assert target.channel == null; final File dest = new File(target.remote); final AtomicInteger count = new AtomicInteger(); scanner.scan(base, reading(new FileVisitor() { private boolean exceptionEncountered; private boolean logMessageShown; @Override public void visit(File f, String relativePath) throws IOException { if (f.isFile()) { File target = new File(dest, relativePath); mkdirsE(target.getParentFile()); Path targetPath = fileToPath(writing(target)); exceptionEncountered = exceptionEncountered || !tryCopyWithAttributes(f, targetPath); if (exceptionEncountered) { Files.copy(fileToPath(f), targetPath, StandardCopyOption.REPLACE_EXISTING); if (!logMessageShown) { LOGGER.log(Level.INFO, "JENKINS-52325: Jenkins failed to retain attributes when copying to {0}, so proceeding without attributes.", dest.getAbsolutePath()); logMessageShown = true; } } count.incrementAndGet(); } } private boolean tryCopyWithAttributes(File f, Path targetPath) { try { Files.copy(fileToPath(f), targetPath, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { LOGGER.log(Level.FINE, "Unable to copy: {0}", e.getMessage()); return false; } return true; } @Override public boolean understandsSymlink() { return true; } @Override public void visitSymlink(File link, String target, String relativePath) throws IOException { try { mkdirsE(new File(dest, relativePath).getParentFile()); writing(new File(dest, target)); Util.createSymlink(dest, target, relativePath, TaskListener.NULL); } catch (InterruptedException x) { throw new IOException(x); } count.incrementAndGet(); } })); return count.get(); }
Source:
<code>protected void configure() { bind(TSOChannelHandler.class).in(Singleton.class); bind(TSOStateManager.class).to(TSOStateManagerImpl.class).in(Singleton.class); <START> if (config.getTimestampTypeEnum() == TIMESTAMP_TYPE.WORLD_TIME) { <END> bind(TimestampOracle.class).to(CurrentTimestampOracleImpl.class).in(Singleton.class); } else { bind(TimestampOracle.class).to(TimestampOracleImpl.class).in(Singleton.class); } bind(Panicker.class).to(SystemExitPanicker.class).in(Singleton.class); install(new BatchPoolModule(config)); install(new DisruptorModule(config)); }</code><technical_language>switch</technical_language>

Target:
protected void configure() { bind(TSOChannelHandler.class).in(Singleton.class); bind(TSOStateManager.class).to(TSOStateManagerImpl.class).in(Singleton.class); if (config.getTimestampTypeEnum() == TIMESTAMP_TYPE.WORLD_TIME) { bind(TimestampOracle.class).to(WorldClockOracleImpl.class).in(Singleton.class); } else { bind(TimestampOracle.class).to(TimestampOracleImpl.class).in(Singleton.class); } bind(Panicker.class).to(SystemExitPanicker.class).in(Singleton.class); install(new BatchPoolModule(config)); install(new DisruptorModule(config)); }
Source:
<code>private int calculateNextBatchSize() { int positionCount = currentPage.getPositionCount(); int totalEntries = 0; for (int i = currentPosition; i < positionCount; i++) { int currentEntry = maxEntries[i]; <START> if (totalEntries + currentEntry >= MAX_ROWS_PER_BLOCK) { <END> currentBatchTotalEntries = (i == currentPosition ? currentEntry : totalEntries); return Math.max(i - currentPosition, 1); } totalEntries += currentEntry; } currentBatchTotalEntries = totalEntries; return positionCount - currentPosition; }</code><technical_language>This code is a cryptic. - a batch size exceed MAX_ROWS_PER_BLOCK grabs a single input row. rewritten this: private int calculateNextBatchSize() { int positionCount = currentPage.getPositionCount(); int totalEntries = 0; int totalPositions = 0; for (int i = currentPosition; i < positionCount; i++) { int currentEntry = maxEntries[i]; if (totalEntries + currentEntry >= MAX_ROWS_PER_BLOCK) { break; } totalEntries += currentEntry; totalPositions++; } // grab a single position if (totalPositions == 0) { currentBatchTotalEntries = maxEntries[currentPosition]; return 1; } currentBatchTotalEntries = totalEntries; return totalPositions; } * please is correct, i test</technical_language>

Target:
private int calculateNextBatchSize() { int positionCount = currentPage.getPositionCount(); int totalLengths = 0; int position = currentPosition; while (position < positionCount) { int length = maxLengths[position]; if (totalLengths + length >= MAX_ROWS_PER_BLOCK) { break; } totalLengths += length; position++; } if (position == currentPosition) { currentBatchTotalLength = maxLengths[currentPosition]; return 1; } currentBatchTotalLength = totalLengths; return position - currentPosition; }
Source:
<code>public boolean getCertifiedProductHasAdditionalSoftware(Long certifiedProductId) { Query query = entityManager.createNativeQuery( "select count(cr.certification_result_id) " + "from " + SCHEMA_NAME + ".certification_result cr " + " inner join " + SCHEMA_NAME + ".certification_result_additional_software cras" + " on cr.certification_result_id = cras.certification_result_id " + "where cr.certified_product_id = :certifiedProductId " <START> + "and (NOT cras.deleted = true)"); <END> query.setParameter("certifiedProductId", certifiedProductId); BigInteger count = (BigInteger) query.getSingleResult(); return count.intValue() > 0; }</code><technical_language>compare this true? suggestion + "and cras.deleted");</technical_language>

Target:
public boolean getCertifiedProductHasAdditionalSoftware(Long certifiedProductId) { Query query = entityManager.createNativeQuery( "select count(cr.certification_result_id) " + "from " + SCHEMA_NAME + ".certification_result cr " + " inner join " + SCHEMA_NAME + ".certification_result_additional_software cras" + " on cr.certification_result_id = cras.certification_result_id " + "where cr.certified_product_id = :certifiedProductId " + "and NOT cras.deleted"); query.setParameter("certifiedProductId", certifiedProductId); BigInteger count = (BigInteger) query.getSingleResult(); return count.intValue() > 0; }
Source:
<code>public MetadataValueList getPermissionFilteredMetadata(Context context, M obj) { List<MetadataValue> metadata = obj.getMetadata(); try { if (context != null && authorizeService.isAdmin(context)) { return new MetadataValueList(metadata); } for (MetadataValue mv : metadata) { MetadataField metadataField = mv.getMetadataField(); if (metadataExposureService .isHidden(context, metadataField.getMetadataSchema().getName(), metadataField.getElement(), metadataField.getQualifier())) { metadata.remove(mv); } } } catch (SQLException e) { <START> log.error(e); <END> } return new MetadataValueList(metadata); }</code><technical_language>tiny thing, I prefer log more descriptive error messages. For example, this like: log.error("Error filtering metadata based permissions", e);</technical_language>

Target:
public MetadataValueList getPermissionFilteredMetadata(Context context, M obj) { List<MetadataValue> metadata = obj.getMetadata(); try { if (context != null && authorizeService.isAdmin(context)) { return new MetadataValueList(metadata); } for (MetadataValue mv : metadata) { MetadataField metadataField = mv.getMetadataField(); if (metadataExposureService .isHidden(context, metadataField.getMetadataSchema().getName(), metadataField.getElement(), metadataField.getQualifier())) { metadata.remove(mv); } } } catch (SQLException e) { log.error("Error filtering metadata based on permissions", e); } return new MetadataValueList(metadata); }
Source:
<code>public void findEvents(final DeviceMessageMetadata deviceMessageMetadata, final FindEventsRequestDataList findEventsQueryMessageDataContainer) throws FunctionalException { LOGGER.info("findEvents for organisationIdentification: for deviceIdentification: {}", deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification()); final SmartMeter smartMeter = this.domainHelperService .findSmartMeter(deviceMessageMetadata.getDeviceIdentification()); <START> LOGGER.info("Sending request message to core."); <END> final RequestMessage requestMessage = new RequestMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), smartMeter.getIpAddress(), this.managementMapper.map(findEventsQueryMessageDataContainer, FindEventsRequestList.class)); this.osgpCoreRequestMessageSender.send(requestMessage, deviceMessageMetadata.getMessageType(), deviceMessageMetadata.getMessagePriority(), deviceMessageMetadata.getScheduleTime()); }</code><technical_language>I agree sonar</technical_language>

Target:
public void findEvents(final DeviceMessageMetadata deviceMessageMetadata, final FindEventsRequestDataList findEventsQueryMessageDataContainer) throws FunctionalException { LOGGER.info("findEvents for organisationIdentification: for deviceIdentification: {}", deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification()); final SmartMeter smartMeter = this.domainHelperService .findSmartMeter(deviceMessageMetadata.getDeviceIdentification()); LOGGER.info(SENDING_REQUEST_MESSAGE_TO_CORE_LOG_MSG); final RequestMessage requestMessage = new RequestMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), smartMeter.getIpAddress(), this.managementMapper.map(findEventsQueryMessageDataContainer, FindEventsRequestList.class)); this.osgpCoreRequestMessageSender.send(requestMessage, deviceMessageMetadata.getMessageType(), deviceMessageMetadata.getMessagePriority(), deviceMessageMetadata.getScheduleTime()); }
Source:
<code>public void logOut() { L.d("Logging out"); AccountUtil.removeAccount(); <START> WikipediaApp.getInstance().getBus().post(new LoginLogoutEvent()); <END> ServiceFactory.get(getWikiSite()).getCsrfToken() .subscribeOn(Schedulers.io()) .flatMap(response -> ServiceFactory.get(getWikiSite()).postLogout(response.query().csrfToken()).subscribeOn(Schedulers.io())) .doFinally(() -> SharedPreferenceCookieManager.getInstance().clearAllCookies()) .subscribe(response -> L.d("Logout complete."), L::e); }</code><technical_language>do need a Bus event update Nav tab view? Please loginLogoutClick() in MainActivity</technical_language>

Target:
public void logOut() { L.d("Logging out"); AccountUtil.removeAccount(); ServiceFactory.get(getWikiSite()).getCsrfToken() .subscribeOn(Schedulers.io()) .flatMap(response -> ServiceFactory.get(getWikiSite()).postLogout(response.query().csrfToken()).subscribeOn(Schedulers.io())) .doFinally(() -> SharedPreferenceCookieManager.getInstance().clearAllCookies()) .subscribe(response -> L.d("Logout complete."), L::e); }
Source:
<code>static Hashtable<String, String> getEnv(String dnsServerAddress) { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); <START> if(dnsServerAddress != null && !dnsServerAddress.equals("")) { <END> env.put("java.naming.provider.url", "dns://" + dnsServerAddress); } return env; }</code><technical_language>dnsServerAddress.isEmpty()</technical_language>

Target:
static Hashtable<String, String> getEnv(String dnsServerAddress) { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); if(dnsServerAddress != null && !dnsServerAddress.isEmpty()) { env.put("java.naming.provider.url", "dns://" + dnsServerAddress); } return env; }
Source:
<code>public List<Path> getPaths() { <START> return subPaths; <END> }</code><technical_language>Wrap in Collections.unmodifiableList return ImmutableList</technical_language>

Target:
public List<Path> getPaths() { return Collections.unmodifiableList(subPaths); }
Source:
<code>public ReferencedEnvelope getBounds(Filter filter) { try { GranuleSource source = reader.getGranules(reader.getGridCoverageNames()[0], true); Query query = new Query(null, filter); <START> if (filter != null) { <END> query.setFilter(filter); } FeatureCollection featureCollection = source.getGranules(query); return featureCollection.getBounds(); } catch (Exception exception) { throw new RuntimeException("Failed to collect bounds", exception); } }</code><technical_language>sure, if provide filter in constructor do need do set</technical_language>

Target:
public ReferencedEnvelope getBounds(Filter filter) { try { GranuleSource source = reader.getGranules(reader.getGridCoverageNames()[0], true); Query query = new Query(); if (filter != null) { query.setFilter(filter); } FeatureCollection featureCollection = source.getGranules(query); return featureCollection.getBounds(); } catch (Exception exception) { throw new RuntimeException("Failed to collect bounds", exception); } }
Source:
<code>private List<ServiceReference<?>> getApplicationContextReferences(BundleContext bundleContext) throws InvalidSyntaxException { List<ServiceReference<?>> references = new ArrayList<>(); if (bundleContext != null) { references.addAll(bundleContext.getServiceReferences( <START> ConfigurableApplicationContext.class, <END> String.format(BUNDLE_SYMBOLIC_NAME_FILTER, MDS_ENTITIES_SYMBOLIC_NAME) )); } return references; }</code><technical_language>ConfigurableApplicationContext, ApplicationContext</technical_language>

Target:
private List<ServiceReference<ApplicationContext>> getApplicationContextReferences(BundleContext bundleContext) throws InvalidSyntaxException { List<ServiceReference<ApplicationContext>> references = new ArrayList<>(); if (bundleContext != null) { references.addAll(bundleContext.getServiceReferences( ApplicationContext.class, String.format(BUNDLE_SYMBOLIC_NAME_FILTER, MDS_ENTITIES_SYMBOLIC_NAME) )); } return references; }
Source:
<code>public String streamExecutionLog(String streamName) { <START> return restTemplate.getForObject(logsLink.expand(streamName, null).getHref(), String.class); <END> }</code><technical_language>this existing stream applications deployed? I if explicit streams/logs/{streamName} endpoint for this</technical_language>

Target:
public String streamExecutionLog(String streamName) { return restTemplate.getForObject(logsLink.expand(streamName).getHref(), String.class); }
Source:
<code>public void acquireAllNodes() { this.readLock.lock(); try { logger.info("Starting node acquisition. Acquired nodes=" + getNumberOfAcquiredNodesWithLock() + ", Handled nodes=" + getNumberOfHandledNodesWithLock()); if (getNumberOfAcquiredNodesWithLock() < getNumberOfHandledNodesWithLock()) { int differenceBetweenHandledAndAcquiredNodes = getDifferenceBetweenNumberOfHandledAndAcquiredNodesWithLock(); logger.info("Starting " + differenceBetweenHandledAndAcquiredNodes + " nodes"); <START> startNodes(differenceBetweenHandledAndAcquiredNodes); <END> } } catch (RuntimeException e) { logger.error("Could not start nodes of local infrastructure " + this.nodeSource.getName(), e); } finally { this.readLock.unlock(); } }</code><technical_language>compute difference in if condition</technical_language>

Target:
public void acquireAllNodes() { this.readLock.lock(); try { int numberOfHandledNodes = getNumberOfHandledNodesWithLock(); int numberOfAcquiredNodes = getNumberOfAcquiredNodesWithLock(); logger.info("Starting node acquisition. Acquired nodes=" + numberOfAcquiredNodes + ", Handled nodes=" + numberOfHandledNodes); if (numberOfAcquiredNodes < numberOfHandledNodes) { int differenceBetweenHandledAndAcquiredNodes = getDifferenceBetweenNumberOfHandledAndAcquiredNodesWithLock(); logger.info("Starting " + differenceBetweenHandledAndAcquiredNodes + " nodes"); startNodes(differenceBetweenHandledAndAcquiredNodes); } } catch (RuntimeException e) { logger.error("Could not start nodes of local infrastructure " + this.nodeSource.getName(), e); } finally { this.readLock.unlock(); } }
Source:
<code>void putEntry(String path, FileMode mode, ObjectLoader loader, ArchiveOutputStream out) throws IOException; } private static final Map<Format, Archiver> formats; static { Map<Format, Archiver> fmts = new EnumMap<Format, Archiver>(Format.class); fmts.put(Format.ZIP, new Archiver() { @Override public ArchiveOutputStream createArchiveOutputStream(OutputStream s) { <START> ArchiveStreamFactory factory = new ArchiveStreamFactory(); <END> try { return factory.createArchiveOutputStream( ArchiveStreamFactory.ZIP, s); } catch (ArchiveException e) { throw die("this can't happen: missing zip support"); } } @Override public void putEntry(String path, FileMode mode, ObjectLoader loader, ArchiveOutputStream out) throws IOException { final ZipArchiveEntry entry = new ZipArchiveEntry(path); if (mode == FileMode.REGULAR_FILE) ; else if (mode == FileMode.EXECUTABLE_FILE || mode == FileMode.SYMLINK) entry.setUnixMode(mode.getBits()); else warnArchiveEntryModeIgnored(path); entry.setSize(loader.getSize()); out.putArchiveEntry(entry); loader.copyTo(out); out.closeArchiveEntry(); } }); formats = fmts; }</code><technical_language>need a factory for factory things? I guess this is Java right</technical_language>

Target:
void putEntry(String path, FileMode mode, ObjectLoader loader, ArchiveOutputStream out) throws IOException; } private static final Map<Format, Archiver> formats; static { Map<Format, Archiver> fmts = new EnumMap<Format, Archiver>(Format.class); fmts.put(Format.ZIP, new Archiver() { @Override public ArchiveOutputStream createArchiveOutputStream(OutputStream s) { return new ZipArchiveOutputStream(s); } @Override public void putEntry(String path, FileMode mode, ObjectLoader loader, ArchiveOutputStream out) throws IOException { final ZipArchiveEntry entry = new ZipArchiveEntry(path); if (mode == FileMode.REGULAR_FILE) ; else if (mode == FileMode.EXECUTABLE_FILE || mode == FileMode.SYMLINK) entry.setUnixMode(mode.getBits()); else warnArchiveEntryModeIgnored(path); entry.setSize(loader.getSize()); out.putArchiveEntry(entry); loader.copyTo(out); out.closeArchiveEntry(); } }); formats = fmts; }
Source:
<code>public static void main(String[] args) { if (args.length != 3) printUsage(); try { Version version = parseVersionString(args[0]); if (version == null) { System.err.println( "Invalid version number format, must be \"x.y.z(-.*)?\""); System.exit(ExitCode.UNEXPECTED_ERROR.getValue()); } String rev = args[1]; if (rev == null || rev.trim().isEmpty()) { rev = "-1"; } else { rev = rev.trim(); } <START> generateFile(new File("../../../target/generated-sources/java"), version, rev, args[2]); <END> } catch (NumberFormatException e) { System.err.println( "All version-related parameters must be valid integers!"); throw e; } }</code><technical_language>is this path passed a parameter, this easier drive this code pom.xml</technical_language>

Target:
public static void main(String[] args) { if (args.length != 4) printUsage(); try { Version version = parseVersionString(args[0]); if (version == null) { System.err.println( "Invalid version number format, must be \"x.y.z(-.*)?\""); System.exit(ExitCode.UNEXPECTED_ERROR.getValue()); } String rev = args[1]; if (rev == null || rev.trim().isEmpty()) { rev = "-1"; } else { rev = rev.trim(); } generateFile(new File(args[3]), version, rev, args[2]); } catch (NumberFormatException e) { System.err.println( "All version-related parameters must be valid integers!"); throw e; } }
Source:
<code><START> private Optional<Pair<ContainerPlacementMessage.StatusCode, String>> validatePlacementAction(ContainerPlacementRequestMessage requestMessage) { String errorMessagePrefix = String.format("ContainerPlacement request: %s is rejected due to", requestMessage); <END> Boolean invalidAction = false; String errorMessage = null; if (standbyContainerManager.isPresent()) { errorMessage = String.format("%s not supported for host standby enabled", errorMessagePrefix); invalidAction = true; } else if (hasActiveContainerPlacementAction(requestMessage.getProcessorId())) { return Optional.empty(); } else if (!samzaApplicationState.runningProcessors.containsKey(requestMessage.getProcessorId()) || samzaApplicationState.pendingProcessors.containsKey(requestMessage.getProcessorId())) { return Optional.empty(); } else if (dequeuedActionsCache.containsKey(requestMessage.getUuid())) { errorMessage = String.format("%s duplicate UUID of the request, please retry", errorMessagePrefix); invalidAction = true; } else if (Integer.parseInt(requestMessage.getProcessorId()) >= samzaApplicationState.processorCount.get() ) { errorMessage = String.format("%s invalid processor id", errorMessagePrefix); invalidAction = true; } if (invalidAction) { LOG.info(errorMessage); return Optional.of(new ImmutablePair<>(ContainerPlacementMessage.StatusCode.BAD_REQUEST, errorMessage)); } return Optional.of(new ImmutablePair<>(ContainerPlacementMessage.StatusCode.ACCEPTED, "Request is accepted")); }</code><technical_language>For a method is called validatePlacementAction a return of null/empty means action is valid? weird semantics</technical_language>

Target:
private Pair<ContainerPlacementMessage.StatusCode, String> validatePlacementAction(ContainerPlacementRequestMessage requestMessage) { String errorMessagePrefix = String.format("ContainerPlacement request: %s is rejected due to", requestMessage); Boolean invalidAction = false; String errorMessage = null; if (standbyContainerManager.isPresent()) { errorMessage = String.format("%s not supported for hot standby enabled", errorMessagePrefix); invalidAction = true; } else if (placementRequestsCache.containsKey(requestMessage.getUuid())) { errorMessage = String.format("%s duplicate UUID of the request, please retry", errorMessagePrefix); invalidAction = true; } else if (Integer.parseInt(requestMessage.getProcessorId()) >= samzaApplicationState.processorCount.get() ) { errorMessage = String.format("%s invalid processor id", errorMessagePrefix); invalidAction = true; } if (invalidAction) { LOG.info(errorMessage); return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.BAD_REQUEST, errorMessage); } return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.ACCEPTED, "Request is accepted"); }
Source:
<code>public boolean testPermission(CommandSource source) { <START> return source.hasPermission(this.permission); <END> }</code><technical_language>a null check for permissions here. Subject.testPermission(String) accept null permissions input</technical_language>

Target:
public boolean testPermission(CommandSource source) { return this.permission == null ? true : source.hasPermission(this.permission); }
Source:
<code>private synchronized void tryLog() { if (shouldLog()) { if (distributionNotUniform()) { logNotUniform(); } else { logUniform(); } <START> totalWrites.set(0); <END> lastLoggedTime = System.currentTimeMillis(); } }</code><technical_language>totalWrites -> writesSinceLastLog</technical_language>

Target:
private synchronized void tryLog() { if (shouldLog()) { if (distributionNotUniform()) { logNotUniform(); } else { logUniform(); } writesSinceLastLog.set(0); lastLoggedTime = System.currentTimeMillis(); } }
Source:
<code>private void tryInitializationLoop() { try { tryInitializeInternal(); <START> log.info("Initialized on the attempt in milliseconds", <END> SafeArg.of("className", getInitializingClassName()), SafeArg.of("numberOfAttempts", numberOfInitializationAttempts), SafeArg.of("initializationDuration", System.currentTimeMillis() - initializationStartTime)); } catch (Throwable throwable) { log.info("Failed to initialize on the attempt", SafeArg.of("className", getInitializingClassName()), SafeArg.of("numberOfAttempts", numberOfInitializationAttempts++), throwable); cleanUpOnInitFailure(); scheduleInitialization(); } }</code><technical_language>avoid put st/nd/rd/th attempt(s), put attempt (ditto below)</technical_language>

Target:
private void tryInitializationLoop() { try { tryInitializeInternal(); log.info("Initialized on the attempt in milliseconds", SafeArg.of("className", getInitializingClassName()), SafeArg.of("numberOfAttempts", numberOfInitializationAttempts), SafeArg.of("initializationDuration", System.currentTimeMillis() - initializationStartTime)); } catch (Throwable throwable) { log.info("Failed to initialize on the attempt {}", SafeArg.of("className", getInitializingClassName()), SafeArg.of("numberOfAttempts", numberOfInitializationAttempts++), throwable); cleanUpOnInitFailure(); scheduleInitialization(); } }