auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); maybeThrowIfCommitOffsetsNotOwned(offsets); log.debug("Committing offsets: {}", offsets); offsets.forEach(this::updateLastSeenEpochIfNewer); coordinator.commitOffsetsAsync(new HashMap<>(offsets), callback); } catch (CommitFailedException e) { START log.error("Failed to commit offsets asynchronously because they do not belong to dynamically assigned partitions"); END callback.onComplete(offsets, e); } finally { release(); } } Just wondering, does this mean we did not used to check if all the offsets actually belonged to auto-assigned partitions? Or did we just straight throw the `CommitFailedException`? Is this a behavioral change?

Target:
public void commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); log.debug("Committing offsets: {}", offsets); offsets.forEach(this::updateLastSeenEpochIfNewer); coordinator.commitOffsetsAsync(new HashMap<>(offsets), callback); } finally { release(); } }
Source:
public void applyState(XSiteState[] chunk) throws Exception { if (trace) { log.tracef("Received state: %s", extractKeys(chunk)); } else if (debug) { START log.debugf("Received state: %s keys", chunk.length); END } if (transactionManager != null) { applyStateInTransaction(chunk); } else { applyStateInNonTransaction(chunk); } } The trace log doesn't allow you to easily see how many entries there are, so it's actually less informative than the debug log :) Long lines in the log can also be a PITA to deal with, I would suggest logging just the number of entries at debug level and a separate line for each processed/skipped entry.

Target:
public void applyState(XSiteState[] chunk) throws Exception { if (debug) { log.debugf("Received state: %s keys", chunk.length); } if (transactionManager != null) { applyStateInTransaction(chunk); } else { applyStateInNonTransaction(chunk); } }
Source:
protected CallbackTracker(RestRequest restRequest, String operationType, Histogram operationTimeTracker, Histogram callbackProcessingTimeTracker) { this.restRequest = restRequest; START this.operationType = operationType; END this.operationTimeTracker = operationTimeTracker; this.callbackProcessingTimeTracker = callbackProcessingTimeTracker; blobId = RestUtils.getOperationOrBlobIdFromUri(restRequest); } Can we define enums for operation type

Target:
CallbackTracker(RestRequest restRequest, String operationType, Histogram operationTimeTracker, Histogram callbackProcessingTimeTracker) { this.restRequest = restRequest; this.operationType = operationType; this.operationTimeTracker = operationTimeTracker; this.callbackProcessingTimeTracker = callbackProcessingTimeTracker; blobId = RestUtils.getOperationOrBlobIdFromUri(restRequest); }
Source:
public void dispose() { START app.getChildren().remove(windowModel); END coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); windowModel.getContext().deactivate(); windowModel.getContext().dispose(); ((Shell) windowModel.getWidget()).dispose(); } Can this move closer to the end of this method? The app remove can happen after the shell is disposed since it's TBR is already false.

Target:
public void dispose() { coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); windowModel.getContext().deactivate(); windowModel.getContext().dispose(); ((Shell) windowModel.getWidget()).dispose(); app.getChildren().remove(windowModel); }
Source:
public boolean isComplex() { if (metadata.getType().getMinorType() == MinorType.MAP || metadata.getType().getMinorType() == MinorType.UNION || metadata.getType().getMinorType() == MinorType.LIST) { return true; } START return false; END } Nit, but ``` return metadata.getType().getMinorType() == MinorType.MAP || metadata.getType().getMinorType() == MinorType.UNION || metadata.getType().getMinorType() == MinorType.LIST; ``` And below.

Target:
public boolean isComplex() { return metadata.getType().getMinorType() == MinorType.MAP || metadata.getType().getMinorType() == MinorType.UNION || metadata.getType().getMinorType() == MinorType.LIST; }
Source:
protected Builder() { super(ShipyardApi.class); id("shipyard") .name("Shipyard Remote Docker Management API") .identityName("<shipyard-service-key>") .credentialName("not used") .documentation(URI.create("http://shipyard-project.com/docs/api/")) .version("2.0.4") .defaultEndpoint("https://127.0.0.1:8080") .defaultProperties(ShipyardApiMetadata.defaultProperties()) .defaultModules(ImmutableSet.<Class<? extends Module>>of( START OkHttpCommandExecutorServiceModule.class, END ShipyardHttpApiModule.class)); } Remove this from this list. The preferred way is to install it as part of the `ShipyardHttpApiModule`, which has already been done.

Target:
protected Builder() { super(ShipyardApi.class); id("shipyard") .name("Shipyard Remote Docker Management API") .identityName("<shipyard-service-key>") .credentialName("not used") .documentation(URI.create("http://shipyard-project.com/docs/api/")) .version("2.0.4") .defaultEndpoint("https://127.0.0.1:8080") .defaultProperties(ShipyardApiMetadata.defaultProperties()) .defaultModules(ImmutableSet.<Class<? extends Module>>of( ShipyardHttpApiModule.class)); }
Source:
PrintWriter createErrorWriter() { return new PrintWriter( new OutputStreamWriter(System.err, START StandardCharsets.UTF_8)); END } optional: import UTF_8 static

Target:
PrintWriter createErrorWriter() { return new PrintWriter(new OutputStreamWriter(System.err, UTF_8)); }
Source:
public void selectAll(){ int numberOfFiles = mAdapter.getCount(); for(int i = 0; i < numberOfFiles; i++){ File file = (File) mAdapter.getItem(i); if (file != null) { /// Click on a directory START if (file.isDirectory()) { END } else { /// Click on a file getListView().setItemChecked(i, true); // notify the change to the container Activity mContainerActivity.onFileClick(file); } } } } If we are not doing anything when file is a directory, this check is not necessary.

Target:
public void selectAll(){ int numberOfFiles = mAdapter.getCount(); for(int i = 0; i < numberOfFiles; i++){ File file = (File) mAdapter.getItem(i); if (file != null) { if (!file.isDirectory()) { /// Click on a file getListView().setItemChecked(i, true); // notify the change to the container Activity mContainerActivity.onFileClick(file); } } } }
Source:
START public VersionNumber getNeededDependenciesMinimumJavaVersion() { END VersionNumber versionNumber = null; try { versionNumber = minimumJavaVersion == null ? null : new VersionNumber(minimumJavaVersion); } catch (NumberFormatException nfe) { logBadMinJavaVersion("'minimumJavaVersion' was specified for plugin ''{0}'' but unparseable (received {1})", this.name, minimumJavaVersion); } for (Plugin p: getNeededDependencies()) { VersionNumber v = p.getNeededDependenciesMinimumJavaVersion(); if (v == null) { continue; } if (versionNumber == null || v.isNewerThan(versionNumber)) { versionNumber = v; } } return versionNumber; } I tend to agree, but I used the existing naming pattern. So I think either we'd fix everything, or nothing to be consistent.

Target:
public VersionNumber getNeededDependenciesMinimumJavaVersion() { VersionNumber versionNumber = null; try { versionNumber = minimumJavaVersion == null ? null : new VersionNumber(minimumJavaVersion); } catch (NumberFormatException nfe) { logBadMinJavaVersion(); } for (Plugin p: getNeededDependencies()) { VersionNumber v = p.getNeededDependenciesMinimumJavaVersion(); if (v == null) { continue; } if (versionNumber == null || v.isNewerThan(versionNumber)) { versionNumber = v; } } return versionNumber; }
Source:
public void validate() { START throw new CacheConfigurationException("MODULE ERROR"); END } you could throw a ```RuntimeException``` to have a better simulation.

Target:
public void validate() { throw new RuntimeException("MODULE ERROR"); }
Source:
public void addPages() { addPage(fSelectPage); addPage(fSelectDirectories); addPage(fScanPage); addPage(fImportOptions); START END } remove empty line

Target:
public void addPages() { addPage(fSelectPage); addPage(fSelectDirectories); addPage(fScanPage); }
Source:
public CheckEditPartResized(SWTBotGefEditPart editPartBot) { START this.graphicalEditPart = (GraphicalEditPart) editPartBot.part(); this.initialSize = graphicalEditPart.getFigure().getBounds().getSize().getCopy(); END } You can replace by: this((GraphicalEditPart) editPartBot.part());

Target:
public CheckEditPartResized(SWTBotGefEditPart editPartBot) { this((GraphicalEditPart) editPartBot.part()); }
Source:
public static long getBaseSize(byte[] delta) { int p = 0; long baseLen = 0; int c, shift = 0; do { c = delta[p++] & 0xff; START baseLen |= ((c & 0x7f) << shift); END shift += 7; } while ((c & 0x80) != 0); return baseLen; } looks like this explicit cast was done to prevent overflow, hence I am not sure if it is safe to remove this cast same question for the other occurrences below

Target:
public static long getBaseSize(byte[] delta) { int p = 0; long baseLen = 0; int c, shift = 0; do { c = delta[p++] & 0xff; baseLen |= ((long) (c & 0x7f)) << shift; shift += 7; } while ((c & 0x80) != 0); return baseLen; }
Source:
public Result apply(N node, Captures captures, Context context) { Map<DereferenceExpression, VariableReferenceExpression> expressions = START getDereferenceSymbolMap(ExpressionExtractor.extractExpressionsNonRecursive(node), context, metadata, sqlParser); END if (expressions.isEmpty()) { return Result.empty(); } return Result.ofPlanNode(new ProjectNode(context.getIdAllocator().getNextId(), rewrite(context, node, HashBiMap.create(expressions)), identityAssignmentsAsSymbolReferences(node.getOutputVariables()))); } static import ExpressionExtractor.extractExpressionsNonRecursive

Target:
public Result apply(N node, Captures captures, Context context) { Map<DereferenceExpression, VariableReferenceExpression> expressions = getDereferenceSymbolMap(extractExpressionsNonRecursive(node), context, metadata, sqlParser); if (expressions.isEmpty()) { return Result.empty(); } return Result.ofPlanNode(new ProjectNode(context.getIdAllocator().getNextId(), rewrite(context, node, HashBiMap.create(expressions)), identityAssignmentsAsSymbolReferences(node.getOutputVariables()))); }
Source:
protected void onResume() { String action = getIntent().getAction(); if (action == null || !action.equals("Already created")) { // don't restart if action is present Intent intent = new Intent(this, AddBudgetActivity.class); startActivity(intent); finish(); } else { // remove the unique action so the next time onResume // call will force restart getIntent().setAction(null); } START super.onResume(); END } Move this call to the start of the method, since that's generally how it's done.

Target:
protected void onResume() { super.onResume(); String action = getIntent().getAction(); if (action == null || !action.equals("Already created")) { // don't restart if action is present Intent intent = new Intent(this, AddBudgetActivity.class); startActivity(intent); finish(); } else { // remove the unique action so the next time onResume // call will force restart getIntent().setAction(null); } }
Source:
public QuotaViolationException(MetricName metricName, double value, double bound) { START super(metricName + " violated quota."); END this.metricName = metricName; this.value = value; this.bound = bound; } I think we want to make the string computation lazy, but not lose info. We could do that by overriding `toString`.

Target:
public QuotaViolationException(MetricName metricName, double value, double bound) { this.metricName = metricName; this.value = value; this.bound = bound; }
Source:
public VViewModelProperties inherit() { final VDefaultViewModelProperties properties = VViewFactory.eINSTANCE.createDefaultViewModelProperties(); START properties.getInheritableProperties().addAll(getInheritableProperties().entrySet()); END return properties; } needs cloning

Target:
public VViewModelProperties inherit() { final VDefaultViewModelProperties properties = VViewFactory.eINSTANCE.createDefaultViewModelProperties(); for (final Entry<String, Object> entry : getInheritableProperties().entrySet()) { properties.getInheritableProperties().put(entry.getKey(), entry.getValue()); } return properties; }
Source:
START public static XmlDataProviderManager getInstance() { END if (INSTANCE == null) { INSTANCE = new XmlDataProviderManager(); } return INSTANCE; } sync

Target:
public static synchronized XmlDataProviderManager getInstance() { if (INSTANCE == null) { INSTANCE = new XmlDataProviderManager(); } return INSTANCE; }
Source:
private void handleFailure(Throwable t) { if (message.doCallbackOnFailure()) { MessageOut response = new MessageOut(MessagingService.Verb.INTERNAL_RESPONSE) .withParameter(ParameterType.FAILURE_RESPONSE, MessagingService.ONE_BYTE); if (t instanceof TombstoneOverwhelmingException) { START response = response.withParameter(ParameterType.FAILURE_REASON.FAILURE_REASON, Shorts.checkedCast(RequestFailureReason.READ_TOO_MANY_TOMBSTONES.code)); END } MessagingService.instance().sendReply(response, id, message.from); } } It's just a bug in the code that happens to compile and work (with a warning). I'll remove the extra one.

Target:
private void handleFailure(Throwable t) { if (message.doCallbackOnFailure()) { MessageOut response = new MessageOut(MessagingService.Verb.INTERNAL_RESPONSE) .withParameter(ParameterType.FAILURE_RESPONSE, MessagingService.ONE_BYTE); if (t instanceof TombstoneOverwhelmingException) { response = response.withParameter(ParameterType.FAILURE_REASON, Shorts.checkedCast(RequestFailureReason.READ_TOO_MANY_TOMBSTONES.code)); } MessagingService.instance().sendReply(response, id, message.from); } }
Source:
public Optional<UsernamePasswordCredentials> extract(WebContext context) { START final String username = context.getRequestParameter(this.usernameParameter); END final String password = context.getRequestParameter(this.passwordParameter); if (username == null || password == null) { return Optional.empty(); } return Optional.of(new UsernamePasswordCredentials(username, password)); } I'm surprised that getRequestParameter does not return an Optional :)

Target:
public Optional<UsernamePasswordCredentials> extract(WebContext context) { final Optional<String> username = context.getRequestParameter(this.usernameParameter); final Optional<String> password = context.getRequestParameter(this.passwordParameter); if (username.isPresent() && password.isPresent()) { return Optional.of( new UsernamePasswordCredentials(username.get(), password.get()) ); } return Optional.empty(); }
Source:
public void partHidden(IWorkbenchPartReference partRef) { START setActive(partRef, END false); } This causes now editor not to open (sometimes) on BP hit if the debug view is hidden - all in a single window. Open Java perspective, start debugging, close editor, hide view, resume after few times editor is not opened...

Target:
public void partHidden(IWorkbenchPartReference partRef) { }
Source:
public boolean isSelected() { START if (parent != null) { END return parent.isSelected(); } return selected; } again I don't think we should modify the generated methods. If we need to we should set this on merge.

Target:
public boolean isSelected() { return selected; }
Source:
START public A value() { END return trampoline().run(); } could be `final`.

Target:
public final A value() { return trampoline().run(); }
Source:
private RelationalSymbolicValue(Kind kind, SymbolicValue leftOp, SymbolicValue rightOp) { START super(leftOp, rightOp); END this.kind = kind; } operands can be directly initialized : this.leftOp = leftOp; and so only super() constructor is required.

Target:
private RelationalSymbolicValue(Kind kind, SymbolicValue leftOp, SymbolicValue rightOp) { this.kind = kind; this.leftOp = leftOp; this.rightOp = rightOp; }
Source:
private void mapNodes() { if (fNodesList == null) { fNodesMap = new HashMap<>(1); return; } // Create a map with capacity for all child nodes. fNodesMap = new HashMap<>(fNodesList.size() * 4 / 3); for (ModelDelta START element : END fNodesList) { mapNode( element ); } } please name all 4 loop vars either node or delta

Target:
private void mapNodes() { if (fNodesList == null) { fNodesMap = new HashMap<>(1); return; } // Create a map with capacity for all child nodes. fNodesMap = new HashMap<>(fNodesList.size() * 4 / 3); for (ModelDelta node : fNodesList) { mapNode( node ); } }
Source:
public File generateMultipleDockets(Collection<DocketData> docketData, URI xslFileUri) throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket_multipage.pdf"); FileOutputStream fileOutputStream = new FileOutputStream(file); START try { END exportDocket.startExport(docketData, fileOutputStream, new File(xslFileUri)); } catch (IOException e) { throw new IOException(e.getMessage()); } finally { fileOutputStream.flush(); fileOutputStream.close(); } return file; } Please use [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) statement instead of handling this manually.

Target:
public File generateMultipleDockets(Collection<DocketData> docketData, URI xslFileUri) throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket_multipage.pdf"); try (FileOutputStream fileOutputStream = new FileOutputStream(file)) { exportDocket.startExport(docketData, fileOutputStream, new File(xslFileUri)); } catch (IOException e) { throw new IOException(e.getMessage()); } return file; }
Source:
private ContentSource source(AbstractTreeIterator iterator) { START if (iterator instanceof WorkingTreeIterator) END return ContentSource.create((WorkingTreeIterator) iterator); return ContentSource.create(db.newObjectReader()); } style nit: missing braces

Target:
private ContentSource source(AbstractTreeIterator iterator) { if (iterator instanceof WorkingTreeIterator) { return ContentSource.create((WorkingTreeIterator) iterator); } return ContentSource.create(db.newObjectReader()); }
Source:
public void copy(IFileStore destination, int options, IProgressMonitor monitor) throws CoreException { SubMonitor START subMonitor = END SubMonitor.convert(monitor, 1); final IFileInfo sourceInfo = fetchInfo(EFS.NONE, null); if (sourceInfo.isDirectory()) { copyDirectory(sourceInfo, destination, options, subMonitor.split(1)); } else { copyFile(sourceInfo, destination, options, subMonitor.split(1)); } } No submonitor is needed in this method. The original monitor can be passed to mutually exclusive method calls as is.

Target:
public void copy(IFileStore destination, int options, IProgressMonitor monitor) throws CoreException { final IFileInfo sourceInfo = fetchInfo(EFS.NONE, null); if (sourceInfo.isDirectory()) { copyDirectory(sourceInfo, destination, options, monitor); } else { copyFile(sourceInfo, destination, options, monitor); } }
Source:
public void stopTransport() { if (transport != null && transportStatus == ComponentStatus.RUNNING) START transport.stop(); END transportStatus = ComponentStatus.TERMINATED; try { unregisterServerMBeans(); } catch (Exception e) { throw new CacheException(e); } } I think you meant to have brackets encapsulate the entire rest of the method?

Target:
public void stopTransport() { if (transport != null && transportStatus == ComponentStatus.RUNNING) { transport.stop(); transportStatus = ComponentStatus.TERMINATED; try { unregisterServerMBeans(); } catch (Exception e) { throw new CacheException(e); } } }
Source:
public void test43() throws Exception { ClassNode cls = getClassNode(TestCls.class); String code = cls.getCode().toString(); START assertThat(code, containsOne("continue;")); END } In this case jadx replace `continue` with `else` and I think this is correct change. Anyway, jadx don't have any information to restore such code. Or I miss something? P.S. Next time for complex code write `check` method to check that method logic not changed after transformations during decompilation (as example see [`TestSwitchWithFallThroughCase`](https://github.com/skylot/jadx/blob/e1f4955286f73a6ca4525fc27b11fd02106f7f08/jadx-core/src/test/java/jadx/tests/integration/switches/TestSwitchWithFallThroughCase.java#L44) test) because sometimes code changed heavily but logic is preserved and is hard to check such case with "eye".

Target:
public void test43() throws Exception { getClassNode(TestCls.class); }
Source:
public List<DocumentType> getSpecialDocumentTypes() { checkDirty(); START return specialDocumentTypes.values().stream().collect(Collectors.toList()); END } `Collections#unmodifiableList` could be better there.

Target:
public Set<String> getSpecialDocumentTypes() { checkDirty(); return specialDocumentTypes; }
Source:
public void postReport(String urlString, Report report, Map<String, String> headers) throws NetworkException, BadResponseException { try { START nullCheckLatch.await(20, TimeUnit.MILLISECONDS); END } catch (InterruptedException exception) { exception.printStackTrace(); } super.postReport(urlString, report, headers); } Is it worth extending this timeout? AFIACT it won't effect the correct working of the latch, but could prevent issues if the tests are running on an especially slow device/simulator.

Target:
public void postReport(String urlString, Report report, Map<String, String> headers) throws NetworkException, BadResponseException { try { nullCheckLatch.await(100, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { exception.printStackTrace(); } super.postReport(urlString, report, headers); }
Source:
START public static String END composeObjectId(AuditLogableBase logable, AuditLogType logType) { return composeObjectId(logable, logType, logable.getUserId()); } this method can be non-static and private - it isn't used outside of the class

Target:
private String composeObjectId(AuditLogableBase logable, AuditLogType logType) { return composeObjectId(logable, logType, logable.getUserId()); }
Source:
private void removeSessionImpl(String sessionId, int reason, String message, Object... msgArgs) { AcctUtils.reportRecords(reason, getPrincipalName(sessionId), (ExtMap) getData(sessionId, AUTH_RECORD_PARAMETER_NAME, false), (ExtMap) getData(sessionId, PRINCIPAL_RECORD_PARAMETER_NAME, false), message, msgArgs ); sessionInfoMap.remove(sessionId); START getDbFacade().getEngineSessionDao().removeBySessionId(sessionId); END } you can remove by seq... no?

Target:
private void removeSessionImpl(String sessionId, int reason, String message, Object... msgArgs) { AcctUtils.reportRecords(reason, getPrincipalName(sessionId), (ExtMap) getData(sessionId, AUTH_RECORD_PARAMETER_NAME, false), (ExtMap) getData(sessionId, PRINCIPAL_RECORD_PARAMETER_NAME, false), message, msgArgs ); getDbFacade().getEngineSessionDao().removeBySessionId(sessionId); sessionInfoMap.remove(sessionId); }
Source:
private int createHashCode() { int result = System.identityHashCode( scriptEvaluatorFactory ); result = 31 * result + System.identityHashCode( clockProvider ); START result = 31 * result + ( temporalValidationTolerance != null ? temporalValidationTolerance.hashCode() : 0 ); END result = 31 * result + System.identityHashCode( constraintValidatorPayload ); return result; } The `temporalValidationTolerance` cannot be null either (and you don't have the null check in the `equals()` method anyway). Will change.

Target:
private int createHashCode() { int result = System.identityHashCode( scriptEvaluatorFactory ); result = 31 * result + System.identityHashCode( clockProvider ); result = 31 * result + temporalValidationTolerance.hashCode(); result = 31 * result + System.identityHashCode( constraintValidatorPayload ); return result; }
Source:
public int getNumThreads() { int numThreadsConfigured = getNumThreadsConfigured(); if (numThreadsConfigured != DEFAULT_NUM_THREADS) { return numThreadsConfigured; } else { START return Runtime.getRuntime().availableProcessors() - 1; END } } I suspect this code is unused (or maybe lightly used) or else someone would have complained by now that it doesn't work when you only have one processor. It should be `max(1, Runtime.getRuntime().availableProcessors() - 1)`.

Target:
public int getNumThreads() { int numThreadsConfigured = getNumThreadsConfigured(); if (numThreadsConfigured != DEFAULT_NUM_THREADS) { return numThreadsConfigured; } else { return Math.max(Runtime.getRuntime().availableProcessors() - 1, 1); } }
Source:
START protected String generateSlug(Id id) { END return "app-" + idCodec.encode(id.toBigInteger()); } If it shouldn't be possible to store an Application without a slug then this abstract implementation should have control over it and not rely on an implementation calling this method.

Target:
private String generateSlug(Id id) { return "app-" + idCodec.encode(id.toBigInteger()); }
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { START setRetainInstance(true); END return new BottomSheetDialog(requireContext(), getTheme()); } Invoking `setRetainInstance(true)` on a fragment with UI is quite risky (we might/will leak all the views), do we really need it? Moreover, `SignupBottomSheetDialogFragment` currently holds a reference to the Activity, which will also leak after a configuration change. Wdyt?

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { return new BottomSheetDialog(requireContext(), getTheme()); }
Source:
public boolean onBlockStartBreak(ItemStack stack, BlockPos pos, EntityPlayer player) { START if(!ToolHelper.isBroken(stack) && this instanceof IAoeTool && ((IAoeTool) this).isAoeHarvestTool()) { END for(BlockPos extraPos : ((IAoeTool) this).getAOEBlocks(stack, player.worldObj, player, pos)) { breakBlock(stack, player, extraPos, pos); } } return super.onBlockStartBreak(stack, pos, player); } Redundant instanceof and casts

Target:
public boolean onBlockStartBreak(ItemStack stack, BlockPos pos, EntityPlayer player) { if(!ToolHelper.isBroken(stack) && this.isAoeHarvestTool()) { for(BlockPos extraPos : ((IAoeTool) this).getAOEBlocks(stack, player.worldObj, player, pos)) { breakBlock(stack, player, extraPos, pos); } } return super.onBlockStartBreak(stack, pos, player); }
Source:
START protected void setRefLogIdent(final PatchSetApproval submitAudit) { END if (submitAudit != null) { branchUpdate.setRefLogIdent(mArguments.identifiedUserFactory.create( submitAudit.getAccountId()).newRefLogIdent()); } } Should subclasses be allowed to override this method?

Target:
protected final void setRefLogIdent(final PatchSetApproval submitAudit) { if (submitAudit != null) { branchUpdate.setRefLogIdent(mArguments.identifiedUserFactory.create( submitAudit.getAccountId()).newRefLogIdent()); } }
Source:
public PipeRunResult doPipe(Message message, IPipeLineSession session) throws PipeRunException { START try { try (MessageOutputStream target=MessageOutputStream.getTargetStream(this, session, getNextPipe())) { try (OutputStream out = target.asStream()) { END pgpAction.run(message.asInputStream(), out); } return target.getPipeRunResult(); } } catch (Exception e) { throw new PipeRunException(this, "Exception was thrown during PGPPipe execution.", e); } } mag 1 try weg?

Target:
public PipeRunResult doPipe(Message message, IPipeLineSession session) throws PipeRunException { try (MessageOutputStream target=MessageOutputStream.getTargetStream(this, session, getNextPipe())) { try (OutputStream out = target.asStream()) { pgpAction.run(message.asInputStream(), out); } return target.getPipeRunResult(); } catch (Exception e) { throw new PipeRunException(this, "Exception was thrown during PGPPipe execution.", e); } }
Source:
public void saveRevisionData(Session session, Object revisionData) { session.save( revisionInfoEntityName, revisionData ); if ( revisionInfoNumberReader != null ) { START if ( revisionInfoNumberReader.getRevisionNumber( revisionData ).longValue() < 0 ) { END throw new AuditException( "Negative revision numbers are not allowed" ); } } sessionCacheCleaner.scheduleAuditDataRemoval( session, revisionData ); } it seems using `&&` is more in line with existing coding pattern, though minor.

Target:
public void saveRevisionData(Session session, Object revisionData) { session.save( revisionInfoEntityName, revisionData ); if ( revisionInfoNumberReader != null && revisionInfoNumberReader.getRevisionNumber( revisionData ).longValue() < 0 ) { throw new AuditException( "Negative revision numbers are not allowed" ); } sessionCacheCleaner.scheduleAuditDataRemoval( session, revisionData ); }
Source:
private static boolean isRootPrivate(Component root, Map<String, ComponentDto> existingDtosByKeys) { String rootKey = root.getKey(); ComponentDto rootDto = existingDtosByKeys.get(rootKey); if (rootDto == null) { if (Component.Type.VIEW == root.getType()) { START return NEW_VIEWS_SHOULD_BE_PRIVATE; END } throw new IllegalStateException(String.format("The project '%s' is not stored in the database, during a project analysis.", rootKey)); } return rootDto.isPrivate(); } Using `false` is enough here, without constant

Target:
private static boolean isRootPrivate(Component root, Map<String, ComponentDto> existingDtosByKeys) { String rootKey = root.getKey(); ComponentDto rootDto = existingDtosByKeys.get(rootKey); if (rootDto == null) { if (Component.Type.VIEW == root.getType()) { return false; } throw new IllegalStateException(String.format("The project '%s' is not stored in the database, during a project analysis.", rootKey)); } return rootDto.isPrivate(); }
Source:
START public void error(SAXParseException e) throws SAXException { END if (firstException == null) { firstException = e; messageBuffer = new StringBuilder(64); messageBuffer.append('\'').append(resourceId).append('\'').append("' validation error:"); } messageBuffer.append('\n').append(e.toString()); } I might be missing something, but it seems that this method doesn't throws a SAXException. Perhaps it should "throw e" at the end?

Target:
public void error(SAXParseException e) { if (firstException == null) { firstException = e; messageBuffer = new StringBuilder(64); messageBuffer.append('\'').append(resourceId).append('\'').append("' validation error:"); } messageBuffer.append('\n').append(e.toString()); }
Source:
public void onGoogleSignupFinished(String name, String email, String photoUrl, String username) { AnalyticsTracker.track(AnalyticsTracker.Stat.SIGNUP_SOCIAL_SUCCESS); START mLoginAnalyticsListener.trackAnalyticsSignIn(false); END if (mIsJetpackConnect) { ActivityLauncher.showSignupEpilogueForResult(this, name, email, photoUrl, username, false); } else { ActivityLauncher.showMainActivityAndSignupEpilogue(this, name, email, photoUrl, username); } setResult(Activity.RESULT_OK); finish(); } Shouldn't this be `trackAnalyticsSignIn(true)`? I believe the flag is meant to identify self-hosted vs WP.com logins, and WP.com signups should count as the latter.

Target:
public void onGoogleSignupFinished(String name, String email, String photoUrl, String username) { AnalyticsTracker.track(AnalyticsTracker.Stat.SIGNUP_SOCIAL_SUCCESS); if (mIsJetpackConnect) { ActivityLauncher.showSignupEpilogueForResult(this, name, email, photoUrl, username, false); } else { ActivityLauncher.showMainActivityAndSignupEpilogue(this, name, email, photoUrl, username); } setResult(Activity.RESULT_OK); finish(); }
Source:
protected void log(final Level level, final String msg, final Throwable t) { START this.logger.log(level, this.simpleName + " " + msg, t); END } warning: The static field AbstractProcessor.logger should be accessed in a static way.

Target:
protected void log(final Level level, final String msg, final Throwable t) { this.LOGGER.log(level, this.simpleName + " " + msg, t); }
Source:
START private short[] toShortArray(int[] ints) { END if (ints == null) { return null; } short[] shorts = new short[ints.length]; for (int i = 0; i < shorts.length; i++) { shorts[i] = toShort(ints[i]); } return shorts; } minor: make it static

Target:
private static short[] toShortArray(int[] ints) { if (ints == null) { return null; } short[] shorts = new short[ints.length]; for (int i = 0; i < shorts.length; i++) { shorts[i] = toShort(ints[i]); } return shorts; }
Source:
protected void onSuccess(List<Question> questions) { if (questions == null) { showAlert("GetQuestion", "質問がありません。"); } else { START for (Question q : questions) { END questionList.add(q); } } // スクロールを確認するため追加 for (int i = 0; i < 20; i++) questionList.add(new Question("タイトル" + i, "本文" + i, "作者" + i)); adapter.notifyDataSetChanged(); } ここは、`questionList.addAll(questions);`と書くとすっきりしますね。

Target:
protected void onSuccess(List<Question> questions) { if (questions == null) { showAlert("GetQuestion", "質問がありません。"); } else { adapter.clear(); // Robolectric does not implement addAll, // so we use add method and a loop instead for the time being. // https://github.com/pivotal/robolectric/issues/281 for (Question q : questions) { adapter.add(q); } adapter.notifyDataSetChanged(); } }
Source:
public AssociationOrderBy(String expression, String order) { columnName = expression.substring( 1, expression.length() - 1 ); START kind = ( "desc".equalsIgnoreCase( order ) ) ? Order.DESC : Order.ASC; END } Nit picking, but we don't need the extra brackets. Let's just keep: ``` kind = "desc".equalsIgnoreCase( order ) ? Order.DESC : Order.ASC; ```

Target:
public AssociationOrderBy(String expression, String order) { // extract column name from expression, such as "{columnName}" columnName = expression.substring( 1, expression.length() - 1 ); kind = "desc".equalsIgnoreCase( order ) ? Order.DESC : Order.ASC; }
Source:
public FloatSelectiveStreamReader( StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, boolean outputRequired, LocalMemoryContext systemMemoryContext) { this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null"); this.filter = filter.orElse(null); this.outputRequired = outputRequired; this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null"); this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic(); START this.nullsAllowed = this.filter == null || this.filter.testNull(); END } nulls should be allowed if filter is non-deterministic; consider adding a test that uses `array(real)` to test this `nullsAllowed = this.filter == null || nonDeterministicFilter || this.filter.testNull();`

Target:
public FloatSelectiveStreamReader( StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, boolean outputRequired, LocalMemoryContext systemMemoryContext) { this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null"); this.filter = filter.orElse(null); this.outputRequired = outputRequired; this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null"); this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic(); this.nullsAllowed = this.filter == null || nonDeterministicFilter || this.filter.testNull(); }
Source:
public void setProvidedProducts(Collection<Product> providedProducts) { this.providedProductDtos = null; if (providedProducts != null) { START this.providedProducts = new HashSet<>(providedProducts); END } } We need to clear the collection here if the inbound collection is null. Can probably just drop the entire thing down to single line: ``` this.providedProducts = providedProducts != null ? new HashSet<>(providedProducts) : null; ```

Target:
public void setProvidedProducts(Collection<Product> providedProducts) { this.providedProductDtos = null; if (providedProducts != null) { this.providedProducts = new HashSet<>(providedProducts); } else { this.providedProducts = new HashSet<>(); } }
Source:
public NetworkCommon(T parameters) { super(parameters); START this.setStoragePoolId(getNetwork().getDataCenterId()); END } The changes make this line relevant only for AddNetworkCommand. Please remove it and modify: AddNetworkCommand.getPermissionCheckSubjects() to use getNetwork() instead in a safe way. It can come as a follower patch.

Target:
public NetworkCommon(T parameters) { super(parameters); }
Source:
private Collection<File> transactionFiles( File dbLocation ) throws IOException { Collection<File> txFiles = new ArrayList<>(); START DirectoryStream<Path> dirStream = Files.newDirectoryStream( dbLocation.toPath(), "neostore.transaction.db.*" ); END dirStream.forEach( path -> txFiles.add( path.toFile() ) ); return txFiles; } you need to close this directory stream

Target:
private Collection<File> transactionFiles( File dbLocation ) throws IOException { Collection<File> txFiles = new ArrayList<>(); DirectoryStream<Path> dirStream = Files.newDirectoryStream( dbLocation.toPath(), "neostore.transaction.db.*" ); dirStream.forEach( path -> txFiles.add( path.toFile() ) ); dirStream.close(); return txFiles; }
Source:
private String getBundleVersion() { ClassLoader cl = getClass().getClassLoader(); if (cl instanceof URLClassLoader) { START URL url = ((URLClassLoader) cl).findResource(JarFile.MANIFEST_NAME); END try { Manifest manifest = new Manifest(url.openStream()); return manifest.getMainAttributes().getValue("Bundle-Version"); } catch (IOException e) { // do nothing - will return null } } return null; } url should be checked for null.

Target:
private String getBundleVersion() { ClassLoader cl = getClass().getClassLoader(); if (cl instanceof URLClassLoader) { URL url = ((URLClassLoader) cl).findResource(JarFile.MANIFEST_NAME); if (url != null) return getBundleVersion(url); } return null; }
Source:
protected void configure() { super.configure(); install(new OkHttpCommandExecutorServiceModule()); bind(new TypeLiteral<Supplier<SSLContext>>() { }).to(new TypeLiteral<SSLContextWithKeysSupplier>() { }); START bind(OkHttpClientSupplier.class).to(new TypeLiteral<DockerOkHttpClientSupplier>() {}); END } Do it simpler: ``` java bind(OkHttpClientSupplier.class).to(DockerOkHttpClientSupplier.class); ```

Target:
protected void configure() { super.configure(); install(new OkHttpCommandExecutorServiceModule()); bind(OkHttpClientSupplier.class).to(DockerOkHttpClientSupplier.class); }
Source:
public void setupEnvironment() { CorrelationIdTracker.clean(); DbUser user = mock(DbUser.class); when(engineSessionDao.remove(anyLong())).thenReturn(1); START mcr.mockConfigValue(ConfigValues.UserSessionTimeOutInterval, 30); END sessionDataContainer.setUser(session, user); } If this is done for every test case, why not just do in in the MockConfigRule's constructor in line 33?

Target:
public void setupEnvironment() { CorrelationIdTracker.clean(); DbUser user = mock(DbUser.class); when(engineSessionDao.remove(anyLong())).thenReturn(1); sessionDataContainer.setUser(session, user); }
Source:
public void clear() { commands.clear(); START ; END items.clear(); getView().clear(); } Useless statement.

Target:
public void clear() { commands.clear(); items.clear(); getView().clear(); }
Source:
public void setNearClip(float nearClipIn) { START nearClip = nearClipIn; END } I'd write: `this.nearClip = nearClip` And I'd use the same also in the following method. Or did you get a checkstyle warning about it?

Target:
public void setNearClip(float nearClipIn) { this.nearClip = nearClipIn; }
Source:
public void scheduleTask(TaskDefinition task) throws SchedulerException { boolean contains = false; START for (String taskDef : scheduledTasks) { END if (taskDef.equals(task.getName())) { contains = true; break; } } if (!contains) { scheduledTasks.add(task.getName()); } } Oh i see! If it is only used for testing purposes and hence in src/test, then you are correct to have it stay. 👍

Target:
public void scheduleTask(TaskDefinition task) throws SchedulerException { if (!scheduledTasks.contains(task)) { scheduledTasks.add(task); } }
Source:
public SafeHtml getValue() { START if (showUnderline) { END return templates.underlinedHeader(headerText); } return headerText; } I would use the showUnderline in the setter instead of the getter. Now each time getValue is called, it has to evaluate the template. If you do that in the setter, then the value is always the underlined version and the evaluation only happens once.

Target:
public SafeHtml getValue() { return headerText; }
Source:
private String resolveUrl(URI uri, String link) { String url = cfg.getString("gerrit", null, "canonicalWebUrl"); if (Strings.isNullOrEmpty(url)) { url = uri.toString(); } if (!url.endsWith("/")) { url += "/"; } START if (Strings.isNullOrEmpty(link)) { END url += "#" + link; } return url; } Should this be if (!Strings.isNullOrEmpty(link)) { ?

Target:
private String resolveUrl(URI uri, String link) { String url = cfg.getString("gerrit", null, "canonicalWebUrl"); if (Strings.isNullOrEmpty(url)) { url = uri.toString(); } if (!url.endsWith("/")) { url += "/"; } if (!Strings.isNullOrEmpty(link)) { url += "#" + link; } return url; }
Source:
public void onSkipInWrite(S item, Throwable t) { if(skipWriteDelegate != null && t instanceof Exception) { try { START skipWriteDelegate.onSkipWriteItem(Collections.<Object>singletonList(item), (Exception) t); END } catch (Exception e) { throw new BatchRuntimeException(e); } } } This actually isn't correct. The "item" in this case that is being passed to the JSR-352 SkipListener is actually all the items in the current chunk. Unlike Spring Batch, the JSR does not provide facilities to identify which item within a chunk caused the error. See section 9.2.7 of the spec for more detail

Target:
public void onSkipInWrite(S item, Throwable t) { if(skipWriteDelegate != null && t instanceof Exception) { try { /* * assuming this SkipListenerAdapter will only be called from JsrFaultTolerantChunkProcessor, * which calls onSkipInWrite() with the whole chunk (List) of items instead of single item */ skipWriteDelegate.onSkipWriteItem((List<Object>) item, (Exception) t); } catch (Exception e) { throw new BatchRuntimeException(e); } } }
Source:
private FileStatus[] listConstraintFilesInDBDir(FileSystem fs, Path dbDir) { try { START return fs.listStatus(new Path(dbDirs[0].getPath(), ReplicationSemanticAnalyzer.CONSTRAINTS_ROOT_DIR_NAME)); END } catch (FileNotFoundException e) { return new FileStatus[]{}; } catch (IOException e) { throw new RuntimeException(e); } } Shall use dbDir instead of dbDirs[0] array.

Target:
private FileStatus[] listConstraintFilesInDBDir(FileSystem fs, Path dbDir) { try { return fs.listStatus(new Path(dbDir, ReplicationSemanticAnalyzer.CONSTRAINTS_ROOT_DIR_NAME)); } catch (FileNotFoundException e) { return new FileStatus[]{}; } catch (IOException e) { throw new RuntimeException(e); } }
Source:
START public static boolean sqSupportsExternalIssues() { END return orchestrator.getServer().version().isGreaterThanOrEquals(7, 2); } Access can be private

Target:
private static boolean sqSupportsExternalIssues() { return orchestrator.getServer().version().isGreaterThanOrEquals(7, 2); }
Source:
public void START testMakeTimeZone_All() END throws IOException { ZoneInfoDB.TzData instance = ZoneInfoDB.getInstance(); String[] availableIDs = instance.getAvailableIDs(); Arrays.sort(availableIDs); for (String id : availableIDs) { BufferIterator bufferIterator = instance.getBufferIterator(id); // Create a ZoneInfo at the earliest possible time to allow us to use the // useDaylightTime() method to check whether it ever has or ever will support daylight // savings time. ZoneInfo zoneInfo = ZoneInfo.makeTimeZone(id, bufferIterator, Long.MIN_VALUE); assertNotNull("TimeZone " + id + " was not created", zoneInfo); assertEquals(id, zoneInfo.getID()); } } It will be interesting to see if this times out / runs out of memory on low spec devices. It's a good test, though.

Target:
public void testMakeTimeZone_All() throws Exception { ZoneInfoDB.TzData instance = ZoneInfoDB.getInstance(); String[] availableIDs = instance.getAvailableIDs(); Arrays.sort(availableIDs); for (String id : availableIDs) { BufferIterator bufferIterator = instance.getBufferIterator(id); // Create a ZoneInfo at the earliest possible time to allow us to use the // useDaylightTime() method to check whether it ever has or ever will support daylight // savings time. ZoneInfo zoneInfo = ZoneInfo.makeTimeZone(id, bufferIterator, Long.MIN_VALUE); assertNotNull("TimeZone " + id + " was not created", zoneInfo); assertEquals(id, zoneInfo.getID()); } }
Source:
START public Integer getDefaultAutoLimit() { END return defaultAutoLimit; } ```suggestion public int getDefaultAutoLimit() { ```

Target:
public int getDefaultAutoLimit() { return defaultAutoLimit; }
Source:
START public byte getFormatVersion() END { return formatVersion; } Can be package-private

Target:
byte getFormatVersion() { return formatVersion; }
Source:
public SubscribeRule(@JsonProperty("type") final Type type, @JsonProperty("all") final Boolean all, @JsonProperty("publisher") final String publisher, @JsonProperty("track") final String track, @JsonProperty("kind") final Kind kind, @JsonProperty("priority") final Priority priority) { this.type = type; this.all = all; this.kind = kind; this.priority = priority; START this.publisher = publisher; END this.track = track; } nit: ordering is different.

Target:
public SubscribeRule(@JsonProperty("type") final Type type, @JsonProperty("all") final Boolean all, @JsonProperty("publisher") final String publisher, @JsonProperty("track") final String track, @JsonProperty("kind") final Kind kind, @JsonProperty("priority") final Priority priority) { this.type = type; this.all = all; this.publisher = publisher; this.track = track; this.kind = kind; this.priority = priority; }
Source:
public Subcategory getSubcategory() { START return subcategories.get(0); END } Backward incompatible change: if there are no subcategories it used to return null, now it's throwing null pointer.

Target:
public Subcategory getSubcategory() { return subcategories.isEmpty() ? null : subcategories.get(0); }
Source:
public void load(LazyBlock lazyBlock) { if (block == null) { return; } START while (block instanceof LazyBlock) { END block = ((LazyBlock) block).getBlock(); } Block coercedBlock = coercer.apply(block); lazyBlock.setBlock(coercedBlock); // clear reference to loader to free resources, since load was successful block = null; } Use `if` here instead. We don't nest `LazyBlock`s

Target:
public void load(LazyBlock lazyBlock) { if (block == null) { return; } if (block instanceof LazyBlock) { block = ((LazyBlock) block).getBlock(); } Block coercedBlock = coercer.apply(block); lazyBlock.setBlock(coercedBlock); // clear reference to loader to free resources, since load was successful block = null; }
Source:
public final String dumpConfiguration() { if (this.properties.isEmpty()) return "No configuration settings stored"; @SuppressWarnings("rawtypes") Enumeration e = this.properties.propertyNames(); START String response = "TSD Configuration:\n"; END response += "File [" + this.config_location + "]\n"; while (e.hasMoreElements()) { String key = (String) e.nextElement(); response += "Key [" + key + "] Value [" + this.properties.getProperty(key) + "]\n"; } return response; } You want to cumulate in a `StringBuilder` here, not a plain `String`.

Target:
public final String dumpConfiguration() { if (this.properties.isEmpty()) return "No configuration settings stored"; StringBuilder response = new StringBuilder("TSD Configuration:\n"); response.append("File [" + this.config_location + "]\n"); for (Map.Entry<String, String> entry : this.properties.entrySet()) { response.append("Key [" + entry.getKey() + "] Value ["). append(entry.getValue() + "]\n"); } return response.toString(); }
Source:
public void cleanup() { try { START log.info("Start cleanup"); END DateTime latestTimeToKeep = DateTime.getNow().addDays( Config.<Integer>getValue(ConfigValues.AuditLogAgingThreshold) * -1); auditLogDao.removeAllBeforeDate(latestTimeToKeep); log.info("Finished cleanup"); } catch (Throwable t) { log.error("Exception in performing audit log cleanup: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); } } We should move that to debug in different patch (or remove at all), I see no value for that in INFO level

Target:
public void cleanup() { try { log.debug("Start cleanup"); DateTime latestTimeToKeep = DateTime.getNow().addDays( Config.<Integer>getValue(ConfigValues.AuditLogAgingThreshold) * -1); auditLogDao.removeAllBeforeDate(latestTimeToKeep); log.debug("Finished cleanup"); } catch (Throwable t) { log.error("Exception in performing audit log cleanup: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); } }