auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public final void onMessage(M message, MessageCollector collector, TaskCoordinator coordinator) { this.numMessage.inc(); long startNs = this.highResClock.nanoTime(); Collection<RM> results = handleMessage(message, collector, coordinator); long endNs = this.highResClock.nanoTime(); this.handleMessageNs.update(endNs - startNs); results.forEach(rm -> this.registeredOperators.forEach(op -> op.onMessage(rm, collector, coordinator))); InitableFunction transformFn = getOperatorSpec().getTransformFn(); <START> if (transformFn != null && transformFn instanceof WatermarkFunction) { <END> long outputWm = ((WatermarkFunction) transformFn).getOutputWatermark(); if (outputWatermark < outputWm) { outputWatermark = outputWm; this.registeredOperators.forEach(op -> op.onWatermark(outputWatermark, collector, coordinator)); } } }</code><technical_language>condition is redundant second</technical_language>

Target:
public final void onMessage(M message, MessageCollector collector, TaskCoordinator coordinator) { this.numMessage.inc(); long startNs = this.highResClock.nanoTime(); Collection<RM> results = handleMessage(message, collector, coordinator); long endNs = this.highResClock.nanoTime(); this.handleMessageNs.update(endNs - startNs); results.forEach(rm -> this.registeredOperators.forEach(op -> op.onMessage(rm, collector, coordinator))); WatermarkFunction watermarkFn = getOperatorSpec().getWatermarkFn(); if (watermarkFn != null) { Long outputWm = watermarkFn.getOutputWatermark(); propagateWatermark(outputWm, collector, coordinator); } }
Source:
<code><START> public Optional<RefundTransactionsForPayment> getRefundsForPayment(Long gatewayAccountId, String paymentExternalId) { <END> var uri = UriBuilder .fromPath(ledgerUrl) .path(format("/v1/transaction/%s/transaction", paymentExternalId)) .queryParam("gateway_account_id", gatewayAccountId); Response response = getResponse(uri); if (response.getStatus() == SC_OK) { return Optional.of(response.readEntity(RefundTransactionsForPayment.class)); } return Optional.empty(); }</code><technical_language>discussed change interface this method give impression validly return empty result? Potentially code read clearer if returned a RefundTransactionsForPayment error for other case</technical_language>

Target:
public RefundTransactionsForPayment getRefundsForPayment(Long gatewayAccountId, String paymentExternalId) { var uri = UriBuilder .fromPath(ledgerUrl) .path(format("/v1/transaction/%s/transaction", paymentExternalId)) .queryParam("gateway_account_id", gatewayAccountId); Response response = getResponse(uri); if (response.getStatus() == SC_OK) { try { return response.readEntity(RefundTransactionsForPayment.class); } catch (ProcessingException exception) { logger.error("Error processing response from ledger for payment refunds: {}", kv(GATEWAY_ACCOUNT_ID, gatewayAccountId), kv(PAYMENT_EXTERNAL_ID, paymentExternalId)); throw new LedgerException(exception); } } else { logger.error("Received non-success status code for get refunds for payment from Ledger: {}, {}", kv(GATEWAY_ACCOUNT_ID, gatewayAccountId), kv(PAYMENT_EXTERNAL_ID, paymentExternalId)); throw new GetRefundsForPaymentException(response); } }
Source:
<code>public static boolean isUrlEncoded(String in) { if (!URL_VALID_PATTERN.matcher(in).matches()) { return false; } int percentIdx = 0; while ((percentIdx = in.indexOf('%', percentIdx)) != -1) { if (percentIdx + 2 >= in.length()) { return false; } if (!isHexadecimal(in.charAt(percentIdx + 1)) || !isHexadecimal(in.charAt(percentIdx + 2))) { <START> System.err.println("% is followed by non-alphanumeric " + in.substring(percentIdx, percentIdx + 2)); <END> return false; } percentIdx += 2; } return true; }</code><technical_language>Remove -- spam System.err. Optionally introduce a logger instead</technical_language>

Target:
public static boolean isUrlEncoded(String in) { if (!URL_VALID_PATTERN.matcher(in).matches()) { return false; } int percentIdx = 0; while ((percentIdx = in.indexOf('%', percentIdx)) != -1) { if (percentIdx + 2 >= in.length()) { return false; } if (!isHexadecimal(in.charAt(percentIdx + 1)) || !isHexadecimal(in.charAt(percentIdx + 2))) { return false; } percentIdx += 2; } return true; }
Source:
<code>public boolean performOk() { DocCommentOwnerManager.getInstance() .setWorkspaceCommentOwner(fDocCommentOwnerComposite.getSelectedDocCommentOwner()); <START> fDocCommentOwnerComposite.performOk(null); <END> return super.performOk(); }</code><technical_language>Invoking null argument is evil, please provide another method arguments if sense</technical_language>

Target:
public boolean performOk() { DocCommentOwnerManager.getInstance() .setWorkspaceCommentOwner(fDocCommentOwnerComposite.getSelectedDocCommentOwner()); fDocCommentOwnerComposite.performOk(); return super.performOk(); }
Source:
<code>public Map<IntermediateDataSetID, PersistedIntermediateResultDescriptor> getPersistedIntermediateResult() { if (!JobStatus.FINISHED.equals(state)) { return null; } <START> final List<IntermediateDataSetID> persistedIntermediateDataSetIds = getPersistedIntermediateDataSetID(); <END> Map<IntermediateDataSetID, PersistedIntermediateResultDescriptor> persistedIntermediateResults = new HashMap<>(persistedIntermediateDataSetIds.size()); for (IntermediateDataSetID intermediateDataSetID : persistedIntermediateDataSetIds) { PersistedIntermediateResultDescriptor intermediateResultDescriptor = getPersistedIntermediateResultDescriptor(intermediateDataSetID); persistedIntermediateResults.put(intermediateDataSetID, intermediateResultDescriptor); } return persistedIntermediateResults; }</code><technical_language>logic a complicated. iterating entrySet of IntermediateResult handle Id partitions array in another method simpler</technical_language>

Target:
public Map<IntermediateDataSetID, PersistedIntermediateResultDescriptor> getPersistedIntermediateResult() { if (!JobStatus.FINISHED.equals(state)) { return null; } Map<IntermediateDataSetID, PersistedIntermediateResultDescriptor> intermediateResultInfos = new HashMap<>(); intermediateResults.forEach(((intermediateDataSetID, intermediateResult) -> { if (!intermediateResult.getResultType().isPersistent()) { return; } intermediateResultInfos.put(intermediateDataSetID, getPersistedIntermediateResultDescriptor(intermediateResult)); })); return intermediateResultInfos; }
Source:
<code><START> public void flushToFileWriter(ColumnDescriptor path, ParquetFileWriter writer) throws IOException { <END> ColumnChunkPageWriter pageWriter = writers.get(path); pageWriter.writeToFileWriter(writer); }</code><technical_language>If mistaken, visibility of this method restricted package private</technical_language>

Target:
void flushToFileWriter(ColumnDescriptor path, ParquetFileWriter writer) throws IOException { ColumnChunkPageWriter pageWriter = writers.get(path); pageWriter.writeToFileWriter(writer); }
Source:
<code>public void setJobRegistry(JobRegistry jobRegistry) { this.jobRegistry = jobRegistry; if (stepRegistry == null && jobRegistry instanceof StepRegistry) { setStepRegistry((StepRegistry) jobRegistry); <START> } <END> }</code><technical_language>JobRegistry internal component - direction this functionality blog post this Jira issue sense a class citizen</technical_language>

Target:
public void setJobRegistry(JobRegistry jobRegistry) { this.jobRegistry = jobRegistry; }
Source:
<code><START> private PasswordBasedEncryptionUtil(Cipher cipher, AlgorithmParameters algorithmParameters, Alphabet alphabet) { <END> this.cipher = cipher; this.alphabet = alphabet; this.algorithmParameters = algorithmParameters; }</code><technical_language>time a constructor method is private called a nested enclosing class, compiler produce a "fake" member package-private access calls private member. this process awry. members package-private in place instead of private</technical_language>

Target:
PasswordBasedEncryptionUtil(Cipher cipher, AlgorithmParameters algorithmParameters, Alphabet alphabet) { this.cipher = cipher; this.alphabet = alphabet; this.algorithmParameters = algorithmParameters; }
Source:
<code>public boolean equals(Object obj) { if (!(obj instanceof GlusterVolumeSizeInfo)) { return false; } GlusterVolumeSizeInfo sizeInfo = (GlusterVolumeSizeInfo)obj; <START> if (!(volumeId.equals(sizeInfo.getVolumeName()))) { <END> return false; } if (!(volumeId.equals(sizeInfo.getVolumeId()))) { return false; } if (totalSize != sizeInfo.getTotalSize()) { return false; } if (freeSize != sizeInfo.getFreeSize()) { return false; } if (usedSize != sizeInfo.getUsedSize()) { return false; } return true; }</code><technical_language>miss correcting this below</technical_language>

Target:
public boolean equals(Object obj) { if (!(obj instanceof GlusterVolumeSizeInfo)) { return false; } GlusterVolumeSizeInfo sizeInfo = (GlusterVolumeSizeInfo) obj; if (!ObjectUtils.objectsEqual(volumeId, sizeInfo.getVolumeId())) { return false; } if (!ObjectUtils.objectsEqual(updatedAt, sizeInfo.getUpdatedAt())) { return false; } if (!ObjectUtils.objectsEqual(totalSize, sizeInfo.getTotalSize())) { return false; } if (!ObjectUtils.objectsEqual(freeSize, sizeInfo.getFreeSize())) { return false; } if (!ObjectUtils.objectsEqual(usedSize, sizeInfo.getUsedSize())) { return false; } return true; }
Source:
<code>public void testFileAsStringSimpleFile() throws IOException { <START> File tempFile = File.createTempFile("UtilsTestTempFlie", ".tmp"); <END> try { String testContent = "Test Content"; Files.write(tempFile.toPath(), testContent.getBytes()); assertEquals(testContent, Utils.readFileAsString(tempFile.getPath())); } finally { Files.deleteIfExists(tempFile.toPath()); } }</code><technical_language>reason TestUtils.tempFile</technical_language>

Target:
public void testFileAsStringSimpleFile() throws IOException { File tempFile = TestUtils.tempFile(); try { String testContent = "Test Content"; Files.write(tempFile.toPath(), testContent.getBytes()); assertEquals(testContent, Utils.readFileAsString(tempFile.getPath())); } finally { Files.deleteIfExists(tempFile.toPath()); } }
Source:
<code>public static UVCDialog newInstance() { final UVCDialog dialog = new UVCDialog(); final Bundle args = new Bundle(); <START> dialog.setArguments(args); <END> return dialog; }</code><technical_language>@guiseco Bundle args for here, arguments is added it</technical_language>

Target:
public static UVCDialog newInstance() { final UVCDialog dialog = new UVCDialog(); return dialog; }
Source:
<code>private static <O> KeyVaultLongRunningOperation transformToLongRunningOperation(O operation) { if (operation instanceof RestoreOperation) { RestoreOperation restoreOperation = (RestoreOperation) operation; return new KeyVaultRestoreOperation(restoreOperation.getStatus(), restoreOperation.getStatusDetails(), createKeyVaultErrorFromError(restoreOperation.getError()), restoreOperation.getJobId(), restoreOperation.getStartTime(), restoreOperation.getEndTime()); } else if (operation instanceof SelectiveKeyRestoreOperation) { SelectiveKeyRestoreOperation selectiveKeyRestoreOperation = (SelectiveKeyRestoreOperation) operation; return new KeyVaultRestoreOperation(selectiveKeyRestoreOperation.getStatus(), selectiveKeyRestoreOperation.getStatusDetails(), createKeyVaultErrorFromError(selectiveKeyRestoreOperation.getError()), selectiveKeyRestoreOperation.getJobId(), selectiveKeyRestoreOperation.getStartTime(), selectiveKeyRestoreOperation.getEndTime()); } else if (operation instanceof FullBackupOperation) { FullBackupOperation fullBackupOperation = (FullBackupOperation) operation; return new KeyVaultBackupOperation(fullBackupOperation.getStatus(), fullBackupOperation.getStatusDetails(), createKeyVaultErrorFromError(fullBackupOperation.getError()), fullBackupOperation.getJobId(), fullBackupOperation.getStartTime(), fullBackupOperation.getEndTime(), fullBackupOperation.getAzureStorageBlobContainerUri()); } else { <START> throw new UnsupportedOperationException("Operation type not supported"); <END> } }</code><technical_language>nit: Is show name of type here? exception type is UnsupportedOperationException, string add additional information</technical_language>

Target:
private static <O> KeyVaultLongRunningOperation transformToLongRunningOperation(O operation) { if (operation instanceof RestoreOperation) { RestoreOperation restoreOperation = (RestoreOperation) operation; return new KeyVaultRestoreOperation(restoreOperation.getStatus(), restoreOperation.getStatusDetails(), createKeyVaultErrorFromError(restoreOperation.getError()), restoreOperation.getJobId(), restoreOperation.getStartTime(), restoreOperation.getEndTime()); } else if (operation instanceof SelectiveKeyRestoreOperation) { SelectiveKeyRestoreOperation selectiveKeyRestoreOperation = (SelectiveKeyRestoreOperation) operation; return new KeyVaultRestoreOperation(selectiveKeyRestoreOperation.getStatus(), selectiveKeyRestoreOperation.getStatusDetails(), createKeyVaultErrorFromError(selectiveKeyRestoreOperation.getError()), selectiveKeyRestoreOperation.getJobId(), selectiveKeyRestoreOperation.getStartTime(), selectiveKeyRestoreOperation.getEndTime()); } else if (operation instanceof FullBackupOperation) { FullBackupOperation fullBackupOperation = (FullBackupOperation) operation; return new KeyVaultBackupOperation(fullBackupOperation.getStatus(), fullBackupOperation.getStatusDetails(), createKeyVaultErrorFromError(fullBackupOperation.getError()), fullBackupOperation.getJobId(), fullBackupOperation.getStartTime(), fullBackupOperation.getEndTime(), fullBackupOperation.getAzureStorageBlobContainerUri()); } else { throw new UnsupportedOperationException(); } }
Source:
<code><START> List<DirectoryCleaner.DeletionMeta> perWorkerDirCleanup(long size) { <END> return workerLogs.getAllWorkerDirs().stream() .map(Unchecked.function(dir -> directoryCleaner.deleteOldestWhileTooLarge(Collections.singletonList(dir), size, true, null))) .collect(toList()); }</code><technical_language>If DeletionMeta is DirectoryCleaner, I belongs in file</technical_language>

Target:
List<DeletionMeta> perWorkerDirCleanup(long size) { return workerLogs.getAllWorkerDirs().stream() .map(Unchecked.function(dir -> directoryCleaner.deleteOldestWhileTooLarge(Collections.singletonList(dir), size, true, null))) .collect(toList()); }
Source:
<code>private static CompletableFuture<Exception> publishItem( final Producer<String, String> producer, final String topicId, final BatchItem item, final HystrixKafkaCircuitBreaker circuitBreaker) throws EventPublishingException { try { final CompletableFuture<Exception> result = new CompletableFuture<>(); final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( topicId, toKafkaPartition(item.getPartition()), item.getPartition(), item.getEvent().toString()); circuitBreaker.markStart(); producer.send(kafkaRecord, ((metadata, exception) -> { if (null != exception) { LOG.warn("Failed to publish to kafka topic {}", topicId, exception); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); if (hasKafkaConnectionException(exception)) { circuitBreaker.markFailure(); } else { circuitBreaker.markSuccessfully(); } result.complete(exception); } else { item.updateStatusAndDetail(EventPublishingStatus.SUBMITTED, ""); circuitBreaker.markSuccessfully(); result.complete(null); } })); return result; <START> } catch (final RuntimeException e) { <END> circuitBreaker.markSuccessfully(); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } }</code><technical_language>call circuitBreaker in this case</technical_language>

Target:
private static CompletableFuture<Exception> publishItem( final Producer<String, String> producer, final String topicId, final BatchItem item, final HystrixKafkaCircuitBreaker circuitBreaker) throws EventPublishingException { try { final CompletableFuture<Exception> result = new CompletableFuture<>(); final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( topicId, KafkaCursor.toKafkaPartition(item.getPartition()), item.getPartition(), item.getEvent().toString()); circuitBreaker.markStart(); producer.send(kafkaRecord, ((metadata, exception) -> { if (null != exception) { LOG.warn("Failed to publish to kafka topic {}", topicId, exception); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); if (hasKafkaConnectionException(exception)) { circuitBreaker.markFailure(); } else { circuitBreaker.markSuccessfully(); } result.complete(exception); } else { item.updateStatusAndDetail(EventPublishingStatus.SUBMITTED, ""); circuitBreaker.markSuccessfully(); result.complete(null); } })); return result; } catch (final InterruptException e) { Thread.currentThread().interrupt(); circuitBreaker.markSuccessfully(); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } catch (final RuntimeException e) { circuitBreaker.markSuccessfully(); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } }
Source:
<code>public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { <START> return null; <END> }</code><technical_language>this is a correct behavior for a missing feature leave default implementation in a case getTicker is a basic functionality I implement time in weekend</technical_language>

Target:
public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { throw new NotImplementedException(); }
Source:
<code>private void initFragments() { if (null == contributionsListFragment) { contributionsListFragment = new ContributionsListFragment(); } contributionsListFragment.setCallback(new Callback() { @Override public void retryUpload(Contribution contribution) { ContributionsFragment.this.retryUpload(contribution); } @Override public void deleteUpload(Contribution contribution) { contributionsPresenter.deleteUpload(contribution); } @Override public void openMediaDetail(int position) { showDetail(position); } @Override public int getNumberOfContributions() { return numberOfContributions; } @Override public Contribution getContributionForPosition(int position) { <START> Contribution contribution = (Contribution) contributionsPresenter.getItemAtPosition(position); <END> return contribution; } @Override public int findItemPositionWithId(String id) { return contributionsPresenter.getChildPositionWithId(id); } }); if(null==mediaDetailPagerFragment){ mediaDetailPagerFragment=new MediaDetailPagerFragment(); } }</code><technical_language>Is this needed</technical_language>

Target:
private void initFragments() { if (null == contributionsListFragment) { contributionsListFragment = new ContributionsListFragment(); } contributionsListFragment.setCallback(new Callback() { @Override public void retryUpload(Contribution contribution) { ContributionsFragment.this.retryUpload(contribution); } @Override public void deleteUpload(Contribution contribution) { contributionsPresenter.deleteUpload(contribution); } @Override public void openMediaDetail(int position) { showDetail(position); } @Override public int getNumberOfContributions() { return numberOfContributions; } @Override public Contribution getContributionForPosition(int position) { return (Contribution) contributionsPresenter.getItemAtPosition(position); } @Override public int findItemPositionWithId(String id) { return contributionsPresenter.getChildPositionWithId(id); } }); if(null==mediaDetailPagerFragment){ mediaDetailPagerFragment=new MediaDetailPagerFragment(); } }
Source:
<code>void send(ControlMessage message, SystemStream systemStream, MessageCollector collector) { <START> Integer partitionCount = partitions.get(systemStream); <END> if (partitionCount == null) { SystemStreamMetadata metadata = metadataCache.getSystemStreamMetadata(systemStream, true); partitionCount = metadata.getSystemStreamPartitionMetadata().size(); partitions.put(systemStream, partitionCount); } LOG.debug(String.format("Broadcast %s message from task %s to %s with %s partition", MessageType.of(message).name(), message.getTaskName(), systemStream, partitionCount)); for (int i = 0; i < partitionCount; i++) { OutgoingMessageEnvelope envelopeOut = new OutgoingMessageEnvelope(systemStream, i, null, message); collector.send(envelopeOut); } }</code><technical_language>Simplify this .putIfAbsent / computeIfAbsent</technical_language>

Target:
void send(ControlMessage message, SystemStream systemStream, MessageCollector collector) { Integer partitionCount = PARTITION_COUNT_CACHE.computeIfAbsent(systemStream, ss -> { SystemStreamMetadata metadata = metadataCache.getSystemStreamMetadata(ss, true); if (metadata == null) { throw new SamzaException("Unable to find metadata for stream " + systemStream); } return metadata.getSystemStreamPartitionMetadata().size(); }); LOG.debug(String.format("Broadcast %s message from task %s to %s with %s partition", MessageType.of(message).name(), message.getTaskName(), systemStream, partitionCount)); for (int i = 0; i < partitionCount; i++) { OutgoingMessageEnvelope envelopeOut = new OutgoingMessageEnvelope(systemStream, i, null, message); collector.send(envelopeOut); } }
Source:
<code>private boolean validateImagesAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; if (!validateImageAvailability(image, imageGroupId)) { if (getParameters().isAllowPartialImport()) { log.warn("Disk image '{}/{}' doesn't exist on any of its storage domains. " + "Ignoring since <START> the force flag <END> in on", imageGroupId, image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } else { return failValidation(EngineMessage.TEMPLATE_IMAGE_NOT_EXIST); } } } return true; }</code><technical_language>Change "the allow partial"</technical_language>

Target:
private boolean validateImagesAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; if (!validateImageAvailability(image, imageGroupId)) { if (!getParameters().isAllowPartialImport()) { return failValidation(EngineMessage.TEMPLATE_IMAGE_NOT_EXIST); } log.warn("Disk image '{}/{}' doesn't exist on any of its storage domains. " + "Ignoring since the 'Allow Partial' flag in on", imageGroupId, image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } } return true; }
Source:
<code>public Subscriber<? super T> call(final Subscriber<? super Boolean> child) { final SingleDelayedProducer<Boolean> producer = new SingleDelayedProducer<Boolean>(child); Subscriber<T> s = new Subscriber<T>() { boolean hasElements; boolean done; @Override public void onNext(T t) { hasElements = true; boolean result; try { result = predicate.call(t); } catch (Throwable e) { Exceptions.throwOrReport(e, this, t); return; } if (result && !done) { done = true; producer.setValue(!returnOnEmpty); unsubscribe(); } } @Override public void onError(Throwable e) { if (!done) { done = true; child.onError(e); <START> } <END> } @Override public void onCompleted() { if (!done) { done = true; if (hasElements) { producer.setValue(false); } else { producer.setValue(returnOnEmpty); } } } }; child.add(s); child.setProducer(producer); return s; }</code><technical_language>Call RxJavaHooks.onError exception is lost</technical_language>

Target:
public Subscriber<? super T> call(final Subscriber<? super Boolean> child) { final SingleDelayedProducer<Boolean> producer = new SingleDelayedProducer<Boolean>(child); Subscriber<T> s = new Subscriber<T>() { boolean hasElements; boolean done; @Override public void onNext(T t) { if (done) { return; } hasElements = true; boolean result; try { result = predicate.call(t); } catch (Throwable e) { Exceptions.throwOrReport(e, this, t); return; } if (result) { done = true; producer.setValue(!returnOnEmpty); unsubscribe(); } } @Override public void onError(Throwable e) { if (!done) { done = true; child.onError(e); } else { RxJavaHooks.onError(e); } } @Override public void onCompleted() { if (!done) { done = true; if (hasElements) { producer.setValue(false); } else { producer.setValue(returnOnEmpty); } } } }; child.add(s); child.setProducer(producer); return s; }
Source:
<code>public void validate() { <START> if (!containsMacro("port") && port < 0) { <END> throw new IllegalArgumentException("Port cannot be negative"); } }</code><technical_language>calling validate runtime. containsMacro("port") true check port if negative not</technical_language>

Target:
public void validate() { if (port < 0) { throw new IllegalArgumentException("Port cannot be negative"); } }
Source:
<code>private <R> R getUpcallResultInner(long timestamp, Object[] conflictObject) { if (TransactionalContext.isInTransaction()) { try { return (R) TransactionalContext.getCurrentContext() .getUpcallResult(this, timestamp, conflictObject); } catch (Exception e) { log.warn("UpcallResult[{}] Exception: {}", this, e); this.abortTransaction(e); } } if (underlyingObject.getUpcallResults().containsKey(timestamp)) { log.trace("Upcall[{}] Direct", this, timestamp); R ret = (R) underlyingObject.getUpcallResults().get(timestamp); underlyingObject.getUpcallResults().remove(timestamp); return ret == VersionLockedObject.NullValue.NULL_VALUE ? null : ret; } for (int x = 0; x < rt.getParameters().getTrimRetry(); x++) { try { return underlyingObject.update(o -> { o.syncObjectUnsafe(timestamp); if (o.getUpcallResults().containsKey(timestamp)) { log.trace("Upcall[{}] Sync'd", this, timestamp); R ret = (R) o.getUpcallResults().get(timestamp); o.getUpcallResults().remove(timestamp); return ret == VersionLockedObject.NullValue.NULL_VALUE ? null : ret; } throw new RuntimeException("Attempted to get the result " + "of an upcall@" + timestamp + " but we are @" + underlyingObject.getVersionUnsafe() + " and we don't have a copy"); }); } catch (TrimmedException ex) { <START> log.info("accessInner: Encountered trimmed address space " + <END> "while accessing version on attempt {}", timestamp, x); underlyingObject.update(o -> { o.resetUnsafe(); return null; }); } } throw new TrimmedUpcallException(timestamp); }</code><technical_language>accessInner -> getUpcallResultInner, this incorrectly copy-pasted</technical_language>

Target:
private <R> R getUpcallResultInner(long timestamp, Object[] conflictObject) { if (TransactionalContext.isInTransaction()) { try { return (R) TransactionalContext.getCurrentContext() .getUpcallResult(this, timestamp, conflictObject); } catch (Exception e) { log.warn("UpcallResult[{}] Exception: {}", this, e); this.abortTransaction(e); } } if (underlyingObject.getUpcallResults().containsKey(timestamp)) { log.trace("Upcall[{}] Direct", this, timestamp); R ret = (R) underlyingObject.getUpcallResults().get(timestamp); underlyingObject.getUpcallResults().remove(timestamp); return ret == VersionLockedObject.NullValue.NULL_VALUE ? null : ret; } for (int x = 0; x < rt.getParameters().getTrimRetry(); x++) { try { return underlyingObject.update(o -> { o.syncObjectUnsafe(timestamp); if (o.getUpcallResults().containsKey(timestamp)) { log.trace("Upcall[{}] Sync'd", this, timestamp); R ret = (R) o.getUpcallResults().get(timestamp); o.getUpcallResults().remove(timestamp); return ret == VersionLockedObject.NullValue.NULL_VALUE ? null : ret; } throw new RuntimeException("Attempted to get the result " + "of an upcall@" + timestamp + " but we are @" + underlyingObject.getVersionUnsafe() + " and we don't have a copy"); }); } catch (TrimmedException ex) { log.info("getUpcallResultInner: Encountered trimmed address space " + "while accessing version on attempt {}", timestamp, x); underlyingObject.update(o -> { o.resetUnsafe(); return null; }); } } throw new TrimmedUpcallException(timestamp); }
Source:
<code>public void onUnityAdsStart(String placementId) { if (mMediationRewardedAdCallback != null) { <START> mMediationRewardedAdCallback.onVideoStart(); <END> } }</code><technical_language>Is this a more place call mMediationRewardedAdCallback.reportAdImpression()</technical_language>

Target:
public void onUnityAdsStart(String placementId) { if (mMediationRewardedAdCallback != null) { mMediationRewardedAdCallback.reportAdImpression(); mMediationRewardedAdCallback.onVideoStart(); } }
Source:
<code>public static boolean isBranchNameValid(String name) { <START> if (name.isEmpty()) { <END> return false; } for (int i = 0; i < ILLEGAL_CHARS.length(); i++) { char illegalChar = ILLEGAL_CHARS.charAt(i); if (name.contains(String.valueOf(illegalChar))) { return false; } } return true; }</code><technical_language>Repository.isValidRefName(final String refName) check if a name is a valid branch name</technical_language>

Target:
public static boolean isBranchNameValid(String name) { return Repository.isValidRefName(name); }
Source:
<code>public void stop(long timeInNS, long inSize, long outSize, Exchange ex) { Message request = ex.getInMessage(); TimingContext timingContext = TimingContext.get(request); <START> if (timingContext == null) { <END> timingContext = startAndAttachTimingContext(request); } record(timingContext, ex); }</code><technical_language>flow nullable timingContext concerns a bit. happen, assuming does, record effectively zeroed samples (since start stop time equal), basically screw / mess metric. I suggest skip record call in this case, if could, provide sample (since time took, timeInNS), do think</technical_language>

Target:
public void stop(long timeInNS, long inSize, long outSize, Exchange ex) { Message request = ex.getInMessage(); TimingContext timingContext = TimingContext.get(request); if (timingContext == null) { LOG.warning("Unable for record metric for exchange: " + ex); } else { record(timingContext, ex); } }
Source:
<code>public void checkStateChanged(CheckStateChangedEvent event) { CounterChartViewer counterChartViewer = fCounterChartViewer; if (counterChartViewer == null) { return; } if (getTrace() == null) { return; } ICheckable checkboxTree = event.getCheckable(); if (checkboxTree instanceof CheckboxTreeViewer) { @NonNull Set<@NonNull Integer> quarks = new TreeSet<>(); CheckboxTreeViewer checkboxTreeViewer = (CheckboxTreeViewer) checkboxTree; setSubtreeChecked(event.getElement(), event.getChecked()); <START> maintainCheckIntegrity(event.getElement()); <END> for (Object checkedElement : checkboxTreeViewer.getCheckedElements()) { if (checkedElement instanceof CounterTreeViewerEntry) { quarks.add(((CounterTreeViewerEntry) checkedElement).getQuark()); } } counterChartViewer.updateChart(quarks); } }</code><technical_language>I CheckboxTreeViewer's responsibility maintain check integrity of parents children. CounterView's responsibility is get checked leafs update chart</technical_language>

Target:
public void checkStateChanged(CheckStateChangedEvent event) { CounterChartViewer counterChartViewer = fCounterChartViewer; if (counterChartViewer == null) { return; } if (getTrace() == null) { return; } ICheckable checkboxTree = event.getCheckable(); if (checkboxTree instanceof CheckboxTreeViewer) { @NonNull Set<@NonNull Integer> quarks = new TreeSet<>(); fFilteredCheckboxTree.setSubtreeChecked(event.getElement(), event.getChecked()); for (Object checkedElement : fFilteredCheckboxTree.getCheckedElements()) { fFilteredCheckboxTree.maintainCheckIntegrity(checkedElement); if (checkedElement instanceof CounterTreeViewerEntry) { quarks.add(((CounterTreeViewerEntry) checkedElement).getQuark()); } } counterChartViewer.updateChart(quarks); } }
Source:
<code>public ConstructQueryMetadata readConstructQueryMetadata(SnapshotBase tx, String nodeId) { Optional<NodeType> type = NodeType.fromNodeId(nodeId); try { <START> checkArgument(type.isPresent() && type.get() == NodeType.CONSTRUCT); <END> LOG.debug("Retrieving Metadata from Cache: {}", nodeId); return (ConstructQueryMetadata) commonNodeMetadataCache.get(nodeId, new Callable<CommonNodeMetadata>() { @Override public CommonNodeMetadata call() throws Exception { LOG.debug("Seeking Metadata from Fluo Table: {}.", nodeId); return dao.readConstructQueryMetadata(tx, nodeId); } }); } catch (Exception e) { throw new RuntimeException("Unable to access ConstructQueryMetadata for nodeId: " + nodeId, e); } }</code><technical_language>catch checkArg()</technical_language>

Target:
public ConstructQueryMetadata readConstructQueryMetadata(SnapshotBase tx, String nodeId) { checkNotNull(nodeId); checkNotNull(tx); Optional<NodeType> type = NodeType.fromNodeId(nodeId); checkArgument(type.isPresent() && type.get() == NodeType.CONSTRUCT); try { LOG.debug("Retrieving Metadata from Cache: {}", nodeId); return (ConstructQueryMetadata) commonNodeMetadataCache.get(nodeId, () -> { LOG.debug("Seeking Metadata from Fluo Table: {}.", nodeId); return dao.readConstructQueryMetadata(tx, nodeId); }); } catch (Exception e) { throw new RuntimeException("Unable to access ConstructQueryMetadata for nodeId: " + nodeId, e); } }
Source:
<code><START> NaiEntity(String name, String encoding ,List<EapEntity> eaps) { <END> this.name = name; this.encoding = encoding; this.eaps = eaps; }</code><technical_language>format</technical_language>

Target:
NaiEntity(String name, String encoding, List<EapEntity> eaps) { this.name = name; this.encoding = encoding; this.eaps = ImmutableList.copyOf(eaps); }
Source:
<code>static Immutable of(Iterable<? extends Value<?>> values) { return Sponge.getRegistry().requireFactory(Factory.class).of(values); <START> } <END></code><technical_language>factory methods moved DataManipulator renamed. E.g. DataManipulator.immutableOf instead of DataManipulator.Immutable.of. IMO feels cleaner. applies mutable one</technical_language>

Target:
static Mutable of(Iterable<? extends Value<?>> values) { return Sponge.getRegistry().requireFactory(Mutable.Factory.class).of(values); }
Source:
<code>private void addNewTemplate(JSONObject model) { JSONObject newTemplate; int oldPosition = getArguments().getInt("position"); JSONArray templates = model.getJSONArray("tmpls"); JSONObject oldTemplate = templates.getJSONObject(oldPosition); newTemplate = Models.newTemplate(newCardName(templates)); newTemplate.put("qfmt", oldTemplate.get("qfmt")); newTemplate.put("afmt", oldTemplate.get("afmt")); if (templates.length() == 1) { flipQA(newTemplate); } int lastExistingOrd = templates.getJSONObject(templates.length() - 1).getInt("ord"); Timber.d("addNewTemplate() lastExistingOrd was %s", lastExistingOrd); <START> newTemplate.put("ord", lastExistingOrd + 1); <END> templates.put(newTemplate); mTemplateEditor.getTempModel().addNewTemplate(newTemplate); mTemplateEditor.selectTemplate(templates.length() - 1); }</code><technical_language>Out-of scope, for future discussion: This technically performs in-memory delete, modSchema is a database-centric action, if move this performing check, able avoid a full uploads if user cancels out of action</technical_language>

Target:
private void addNewTemplate(JSONObject model) { JSONObject newTemplate; int oldPosition = getArguments().getInt("position"); JSONArray templates = model.getJSONArray("tmpls"); JSONObject oldTemplate = templates.getJSONObject(oldPosition); newTemplate = Models.newTemplate(newCardName(templates)); newTemplate.put("qfmt", oldTemplate.get("qfmt")); newTemplate.put("afmt", oldTemplate.get("afmt")); if (templates.length() == 1) { flipQA(newTemplate); } int lastExistingOrd = templates.getJSONObject(templates.length() - 1).getInt("ord"); Timber.d("addNewTemplate() lastExistingOrd was %s", lastExistingOrd); newTemplate.put("ord", lastExistingOrd + 1); templates.put(newTemplate); mTemplateEditor.getTempModel().addNewTemplate(newTemplate); mTemplateEditor.mViewPager.getAdapter().notifyDataSetChanged(); mTemplateEditor.mViewPager.setCurrentItem(templates.length() - 1, mTemplateEditor.animationDisabled()); }
Source:
<code>public String validateFields() { if (Control.Mode.safe == Control.getSingleton().getMode()) { return Constant.messages.getString("ascan.custom.notSafe.error"); } <START> if (this.filterPanel != null) { <END> String fail = this.filterPanel.validateFields(); if (fail != null) { return fail; } } if (this.customPanels != null) { for (CustomScanPanel customPanel : this.customPanels) { String fail = customPanel.validateFields(); if (fail != null) { return fail; } } for (CustomScanPanel customPanel : this.customPanels) { Target target = customPanel.getTarget(); if (target != null && target.isValid()) { return null; } } } if (this.target == null || !this.target.isValid()) { return Constant.messages.getString("ascan.custom.nostart.error"); } switch (Control.getSingleton().getMode()) { case protect: List<StructuralNode> nodes = target.getStartNodes(); if (nodes != null) { for (StructuralNode node : nodes) { if (node instanceof StructuralSiteNode) { SiteNode siteNode = ((StructuralSiteNode) node).getSiteNode(); if (!siteNode.isIncludedInScope()) { return Constant.messages.getString( "ascan.custom.targetNotInScope.error", siteNode.getHierarchicNodeName()); } } } } break; default: } return null; }</code><technical_language>need check for null (we do check in save method NPE in end). Worth creating in constructor avoid these</technical_language>

Target:
public String validateFields() { if (Control.Mode.safe == Control.getSingleton().getMode()) { return Constant.messages.getString("ascan.custom.notSafe.error"); } String errorMessage = this.filterPanel.validateFields(); if (errorMessage != null) { return errorMessage; } if (this.customPanels != null) { for (CustomScanPanel customPanel : this.customPanels) { errorMessage = customPanel.validateFields(); if (errorMessage != null) { return errorMessage; } } for (CustomScanPanel customPanel : this.customPanels) { Target target = customPanel.getTarget(); if (target != null && target.isValid()) { return null; } } } if (this.target == null || !this.target.isValid()) { return Constant.messages.getString("ascan.custom.nostart.error"); } switch (Control.getSingleton().getMode()) { case protect: List<StructuralNode> nodes = target.getStartNodes(); if (nodes != null) { for (StructuralNode node : nodes) { if (node instanceof StructuralSiteNode) { SiteNode siteNode = ((StructuralSiteNode) node).getSiteNode(); if (!siteNode.isIncludedInScope()) { return Constant.messages.getString( "ascan.custom.targetNotInScope.error", siteNode.getHierarchicNodeName()); } } } } break; default: } return null; }
Source:
<code>public OSFileStore[] getFileStores() { Map<String, String> fstype = new HashMap<>(); try { List<String> mounts = FileUtil.readFile("/proc/self/mounts"); for (String mount : mounts) { String[] split = mount.split(" "); if (split.length < 6) { continue; } fstype.put(split[1].replaceAll("\\\\040", " "), split[2]); <START> } <END> } catch (IOException e) { LOG.error("Error reading /proc/self/mounts. Can't detect filetypes."); } List<OSFileStore> fsList = new ArrayList<>(); for (FileStore store : FileSystems.getDefault().getFileStores()) { String path = store.toString().replace(" (" + store.name() + ")", ""); if (path.startsWith("/proc") || path.startsWith("/sys") || path.startsWith("/run") || path.startsWith("/dev")) continue; String name = store.name(); if (path.equals("/")) name = "/"; String description = "Mount Point"; if (store.name().startsWith("/dev")) description = "Local Disk"; String type = "unknown"; if (fstype.containsKey(path)) { type = fstype.get(path); } try { fsList.add(new OSFileStore(name, description, type, store.getUsableSpace(), store.getTotalSpace())); } catch (IOException e) { LOG.trace("", e); continue; } } return fsList.toArray(new OSFileStore[fsList.size()]); }</code><technical_language>Check indentation/formatting settings. FYI Eclipse Sun Java Conventions</technical_language>

Target:
public OSFileStore[] getFileStores() { Map<String, String> fstype = new HashMap<>(); List<String> mounts = FileUtil.readFile("/proc/self/mounts"); for (String mount : mounts) { String[] split = mount.split(" "); if (split.length < 6) { continue; } fstype.put(split[1].replaceAll("\\\\040", " "), split[2]); } List<OSFileStore> fsList = new ArrayList<>(); for (FileStore store : FileSystems.getDefault().getFileStores()) { String path = store.toString().replace(" (" + store.name() + ")", ""); if (this.pseudofs.contains(store.name())) { if (store.name().equals("tmpfs")) { if (listElementStarts(this.tmpfsPaths, path)) { continue; } } else { continue; } } String name = store.name(); if (path.equals("/")) name = "/"; String description = "Mount Point"; if (store.name().startsWith("/dev")) description = "Local Disk"; String type = "unknown"; if (fstype.containsKey(path)) { type = fstype.get(path); } try { fsList.add(new OSFileStore(name, path, description, type, store.getUsableSpace(), store.getTotalSpace())); } catch (IOException e) { LOG.trace("", e); continue; } } return fsList.toArray(new OSFileStore[fsList.size()]); }
Source:
<code>private void saveHeartBeat(final List<WriteRequest> lastSeenWriteRequests) { final BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest(); int i = 0; <START> for (final List<WriteRequest> partition : Lists.partition(lastSeenWriteRequests, 25)) { <END> i++; final Map<String, List<WriteRequest>> map = Maps.newHashMap(); map.put(tableName, partition); batchWriteItemRequest.withRequestItems(map); try { final BatchWriteItemResult result = dynamoDBClient.batchWriteItem(batchWriteItemRequest); final Map<String, List<WriteRequest>> unprocessed = result.getUnprocessedItems(); if (unprocessed == null || unprocessed.isEmpty()) { continue; } final float ratio = unprocessed.size() / (float) partition.size() * 100.0f; LOGGER.info("Table : {}% ({} attempted, unprocessed)", tableName, Math.round(ratio), partition.size(), unprocessed.size()); }catch (AmazonClientException e) { LOGGER.error("Error persisting last seen device data: {}", e.getMessage()); } } LOGGER.error("Iterations: {}", i); }</code><technical_language>Magic constants..</technical_language>

Target:
private void saveHeartBeat(final List<WriteRequest> lastSeenWriteRequests) { final BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest(); int i = 0; for (final List<WriteRequest> partition : Lists.partition(lastSeenWriteRequests, DYNAMO_BATCH_WRITE_LIMIT)) { i++; final Map<String, List<WriteRequest>> map = Maps.newHashMap(); map.put(tableName, partition); batchWriteItemRequest.withRequestItems(map); try { final BatchWriteItemResult result = dynamoDBClient.batchWriteItem(batchWriteItemRequest); final Map<String, List<WriteRequest>> unprocessed = result.getUnprocessedItems(); if (unprocessed == null || unprocessed.isEmpty()) { continue; } final float ratio = unprocessed.size() / (float) partition.size() * 100.0f; LOGGER.info("Table : {}% ({} attempted, unprocessed)", tableName, Math.round(ratio), partition.size(), unprocessed.size()); }catch (AmazonClientException e) { LOGGER.error("Error persisting last seen device data: {}", e.getMessage()); } } LOGGER.error("Iterations: {}", i); }
Source:
<code>private BrokerResponse processLiteralOnlyBrokerRequest(BrokerRequest brokerRequest, long compilationStartTimeNs, RequestStatistics requestStatistics) throws IllegalStateException { <START> System.out.println("brokerRequest = " + brokerRequest.toString()); <END> BrokerResponseNative brokerResponse = new BrokerResponseNative(); List<String> columnNames = new ArrayList<>(); List<DataSchema.ColumnDataType> columnTypes = new ArrayList<>(); List<Object> row = new ArrayList<>(); for (Expression e : brokerRequest.getPinotQuery().getSelectList()) { computeResultsForExpression(e, columnNames, columnTypes, row); } DataSchema dataSchema = new DataSchema(columnNames.toArray(new String[0]), columnTypes.toArray(new DataSchema.ColumnDataType[0])); List<Object[]> rows = new ArrayList<>(); rows.add(row.toArray()); ResultTable resultTable = new ResultTable(dataSchema, rows); brokerResponse.setResultTable(resultTable); long totalTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - compilationStartTimeNs); brokerResponse.setTimeUsedMs(totalTimeMs); requestStatistics.setQueryProcessingTime(totalTimeMs); requestStatistics.setStatistics(brokerResponse); return brokerResponse; }</code><technical_language>Remove this</technical_language>

Target:
private BrokerResponse processLiteralOnlyBrokerRequest(BrokerRequest brokerRequest, long compilationStartTimeNs, RequestStatistics requestStatistics) throws IllegalStateException { BrokerResponseNative brokerResponse = new BrokerResponseNative(); List<String> columnNames = new ArrayList<>(); List<DataSchema.ColumnDataType> columnTypes = new ArrayList<>(); List<Object> row = new ArrayList<>(); for (Expression e : brokerRequest.getPinotQuery().getSelectList()) { computeResultsForExpression(e, columnNames, columnTypes, row); } DataSchema dataSchema = new DataSchema(columnNames.toArray(new String[0]), columnTypes.toArray(new DataSchema.ColumnDataType[0])); List<Object[]> rows = new ArrayList<>(); rows.add(row.toArray()); ResultTable resultTable = new ResultTable(dataSchema, rows); brokerResponse.setResultTable(resultTable); long totalTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - compilationStartTimeNs); brokerResponse.setTimeUsedMs(totalTimeMs); requestStatistics.setQueryProcessingTime(totalTimeMs); requestStatistics.setStatistics(brokerResponse); return brokerResponse; }
Source:
<code>public LocationAware makeIndexableSourceFromStream(final InputStream inputStream) { <START> if (inputStream instanceof BlockCompressedInputStream) { <END> return new AsciiLineReaderIterator(new BlockCompressedAsciiLineReader((BlockCompressedInputStream) inputStream)); } else if (inputStream instanceof PositionalBufferedStream) { return new AsciiLineReaderIterator(new AsciiLineReader((PositionalBufferedStream)inputStream)); } else { return new AsciiLineReaderIterator(new AsciiLineReader(inputStream)); } }</code><technical_language>I propose deal this in a new static method AsciiLineReader.from(InputStream is) deprecate constructor. This safer for users of AsciiLineReader simplify code here</technical_language>

Target:
public LocationAware makeIndexableSourceFromStream(final InputStream inputStream) { return new AsciiLineReaderIterator(AsciiLineReader.from(inputStream)); }
Source:
<code>public boolean stop(Duration timeout) { log.debug("Stopping ..."); if (pools == null) { return true; } long failures = pools.parallelStream().filter(comp -> !comp.stop(timeout)).count(); log.debug(String.format("Stopped %d failure", failures)); <START> return failures == 0L; <END> }</code><technical_language>need for 0L, 0 is enough</technical_language>

Target:
public boolean stop(Duration timeout) { log.debug("Stopping ..."); if (pools == null) { return true; } long failures = pools.parallelStream().filter(comp -> !comp.stop(timeout)).count(); log.debug(String.format("Stopped %d failure", failures)); return failures == 0; }