auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Guid getStoragePoolId() { START return getDbFacade().getStoragePoolDao().getAllForStorageDomain(getStorageDomainId()).get(0).getId(); END } Might throw an IndexOutOfBound if no the storage domain is not attached to any storage pool

Target:
protected Guid getStoragePoolId() { return getParameters().getStoragePoolId(); }
Source:
START private Integer prerequirementImgResource(String group) { END if (group.equalsIgnoreCase(AssignmentPrerequirement.RANK.toString())) { return R.drawable.rank_prerequirement; } else if (group.equalsIgnoreCase(AssignmentPrerequirement.MISSION.toString())) { return R.drawable.group_prerequirement; } else { return R.drawable.empty; } } Why returning Integer instead of plain int?

Target:
private int prerequirementImgResource(String group) { if (group.equalsIgnoreCase(AssignmentPrerequirement.RANK.toString())) { return R.drawable.rank_prerequirement; } else if (group.equalsIgnoreCase(AssignmentPrerequirement.MISSION.toString())) { return R.drawable.group_prerequirement; } else { return R.drawable.empty; } }
Source:
public Iterator<ImageTypeSpecifier> getImageTypes(int pImageIndex) throws IOException { checkBounds(pImageIndex); // TODO: Better implementation, include INT_RGB types for 3BYTE_BGR and 4BYTE_ABGR for INT_ARGB START return Collections.singletonList(getRawImageType(pImageIndex)).iterator(); END } The TODO above the changed line indicates the reason for using a multi value list here... But of course, we could change this until we actually return multiple values.

Target:
public Iterator<ImageTypeSpecifier> getImageTypes(int pImageIndex) throws IOException { checkBounds(pImageIndex); // TODO: Better implementation, include INT_RGB types for 3BYTE_BGR and 4BYTE_ABGR for INT_ARGB return Arrays.asList(getRawImageType(pImageIndex)).iterator(); }
Source:
START public void resetPositions(int positionCount) END { positions = ensureCapacity(positions, positionCount); this.positionCount = 0; } For better readability i would sort the methods in the way they are used `resetPositions` -> `addPosition` -> `appendData` -> `flush`. Please also order the private methods accordingly: Method that uses a private method - > private method

Target:
private void resetPositions(int positionCount) { positions = ensureCapacity(positions, positionCount); this.positionCount = 0; }
Source:
public static SelectorHandler getHandler(final String selectorStr) { if (!selectorStr.isEmpty()) START for (final Entry<String, SelectorHandler> handler : selectorHandlers.subMap(selectorStr, true, selectorStr.substring(0, 1), true).entrySet()) END if (selectorStr.startsWith(handler.getKey())) return handler.getValue(); return vanillaHandler; } Why `selectorStr.substring(0, 1)`

Target:
public static SelectorHandler getHandler(final String selectorStr) { if (!selectorStr.isEmpty()) { for (final Entry<String, SelectorHandler> handler : selectorHandlers.subMap(selectorStr, true, selectorStr.substring(0, 1), true).entrySet()) { if (selectorStr.startsWith(handler.getKey())) { return handler.getValue(); } } } return vanillaHandler; }
Source:
public synchronized void close() { if (closed) { return; } closed = true; START if (parentMemoryContext != null) { END parentMemoryContext.updateBytes(-usedBytes); } usedBytes = 0; } This `if` is redundant. Question for you, @nezihyigitbasi: Do you see IntelliJ "warning"s for this? If not, you should turn those on.

Target:
public synchronized void close() { if (closed) { return; } closed = true; parentMemoryContext.updateBytes(-usedBytes); usedBytes = 0; }
Source:
START public Map<K, V> getEntries() { END return (Map<K, V>) entries; } Change seems unneeded. And actually the unchecked can be removed as well.

Target:
public Map<? extends K, ? extends V> getEntries() { return entries; }
Source:
public void testDefaultConfig() throws Exception { Files.write(springTestFile.toPath(), "modification".getBytes(), StandardOpenOption.SYNC); // Adding few millis to avoid fleaky tests // The file hasher could sometimes evaluate these two changes as duplicate, as the second modification of file could be done before hashing is done Thread.sleep(50); Files.write(springTestFile.toPath(), "modification 2".getBytes(), StandardOpenOption.SYNC); MockEndpoint mock = getMockEndpoint("mock:springTest"); START mock.setExpectedCount(1); // The same with testCustomHasher, that second MODIFY event is discarded END mock.setResultWaitTime(1000); mock.assertIsSatisfied(); } Why are you changing expectation, when no related production code changed? There should be really two events (`modification` and `modification 2`) Please note that this test is platform dependent. We are targetting to Linux and CI reports no issues or flakes with this test. Which OS are you running tests? Last CI build is here: https://builds.apache.org/view/C/view/Apache%20Camel/job/Camel/job/master/1533/consoleFull

Target:
public void testDefaultConfig() throws Exception { Files.write(springTestFile.toPath(), "modification".getBytes(), StandardOpenOption.SYNC); // Adding few millis to avoid fleaky tests // The file hasher could sometimes evaluate these two changes as duplicate, as the second modification of file could be done before hashing is done Thread.sleep(50); Files.write(springTestFile.toPath(), "modification 2".getBytes(), StandardOpenOption.SYNC); MockEndpoint mock = getMockEndpoint("mock:springTest"); mock.setExpectedCount(2); // two MODIFY events mock.setResultWaitTime(1000); mock.assertIsSatisfied(); }
Source:
private boolean startsOrEndsWithWhitespace(String value) { boolean startsOrEndsWithWhitespace = false; START if (value != null && StringUtils.isNotBlank(value)) { END int lastIndex = value.length() - 1; if (Character.isSpaceChar(value.charAt(0))) { startsOrEndsWithWhitespace = true; } else if (Character.isSpaceChar(value.charAt(lastIndex))) { startsOrEndsWithWhitespace = true; } } else { startsOrEndsWithWhitespace = false; } return startsOrEndsWithWhitespace; } Isn't isNotBlank already checking for null?

Target:
private boolean startsOrEndsWithWhitespace(String value) { return (StringUtils.isNotBlank(value) && (Character.isSpaceChar(value.charAt(0)) || Character.isSpaceChar(value.charAt(value.length() -1)))); }
Source:
private void updateData(OCShare share) { // Update DB with the response share.setPath(mPath); START if (mPath.endsWith(FileUtils.PATH_SEPARATOR)) { END share.setIsFolder(true); } else { share.setIsFolder(false); } share.setPermissions(READ_ONLY); getStorageManager().saveShare(share); // Update OCFile with data from share: ShareByLink and publicLink OCFile file = getStorageManager().getFileByPath(mPath); if (file!=null) { file.setShareWithSharee(true); // TODO - this should be done by the FileContentProvider, as part of getStorageManager().saveShare(share) getStorageManager().saveFile(file); } } This Block can be shortened to `share.setIsFolder(mPath.endsWith(FileUtils.PATH_SEPARATOR))`

Target:
private void updateData(OCShare share) { // Update DB with the response share.setPath(mPath); share.setIsFolder(mPath.endsWith(FileUtils.PATH_SEPARATOR)); share.setPermissions(READ_ONLY); getStorageManager().saveShare(share); // Update OCFile with data from share: ShareByLink and publicLink OCFile file = getStorageManager().getFileByPath(mPath); if (file!=null) { file.setShareWithSharee(true); // TODO - this should be done by the FileContentProvider, as part of getStorageManager().saveShare(share) getStorageManager().saveFile(file); } }
Source:
protected void startMasters(boolean isLeader) { try { connectToUFS(); mRegistry.start(isLeader); } catch (IOException e) { START LOG.error("Failed to start master.", e); END throw Throwables.propagate(e); } } does the propagated exception not get logged? This looks like it would result in logging the same thing twice

Target:
protected void startMasters(boolean isLeader) { try { connectToUFS(); mRegistry.start(isLeader); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
START public BugzillaRestRepositoryConnectorUi() { END connector = BugzillaRestConnector.getDefault() == null ? new BugzillaRestConnector() : BugzillaRestConnector.getDefault(); } The default constructor should assign "null" to connector.

Target:
public BugzillaRestRepositoryConnectorUi() { this.connector = BugzillaRestConnector.getDefault() == null ? new BugzillaRestConnector() : BugzillaRestConnector.getDefault(); }
Source:
public static ListStatusPOptions getListStatusOptions() { START FileSystemMasterCommonPOptions commonOptions = END getCommonOptions().toBuilder().setTtl(Configuration.getMs(PropertyKey.USER_FILE_LOAD_TTL)) .setTtlAction(GrpcUtils.toProto( Configuration.getEnum(PropertyKey.USER_FILE_LOAD_TTL_ACTION, TtlAction.class))) .build(); return ListStatusPOptions.newBuilder().setCommonOptions(commonOptions) .setLoadMetadataType(GrpcUtils.toProto(Configuration .getEnum(PropertyKey.USER_FILE_METADATA_LOAD_TYPE, LoadMetadataType.class))) .build(); } helper for setting common options?

Target:
public static ListStatusPOptions getListStatusOptions() { return ListStatusPOptions.newBuilder() .setCommonOptions(getCommonOptions().toBuilder() .setTtl(Configuration.getMs(PropertyKey.USER_FILE_LOAD_TTL)) .setTtlAction(GrpcUtils.toProto( Configuration.getEnum(PropertyKey.USER_FILE_LOAD_TTL_ACTION, TtlAction.class)))) .setLoadMetadataType(GrpcUtils.toProto(Configuration .getEnum(PropertyKey.USER_FILE_METADATA_LOAD_TYPE, LoadMetadataType.class))) .build(); }
Source:
Node(final String name, final NodeProcessor nodeProcessor, final Dag dag) { requireNonNull(nodeProcessor, "The nodeProcessor parameter can't be null."); this.nodeProcessor = nodeProcessor; requireNonNull(name, "The name of the node can't be null"); this.name = name; START requireNonNull(name, "The dag of the node can't be null"); END this.dag = dag; } small typo - I think `name` is supposed to be `dag`, right?

Target:
Node(final String name, final NodeProcessor nodeProcessor, final Dag dag) { requireNonNull(nodeProcessor, "The nodeProcessor parameter can't be null."); this.nodeProcessor = nodeProcessor; requireNonNull(name, "The name of the node can't be null"); this.name = name; requireNonNull(dag, "The dag of the node can't be null"); this.dag = dag; }
Source:
public String getTooltip(MergeMode mode) { String tooltip; switch (mode) { case LEFT_TO_RIGHT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.right.tooltip"); //$NON-NLS-1$ break; case RIGHT_TO_LEFT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.left.tooltip"); //$NON-NLS-1$ break; case ACCEPT: tooltip = EMFCompareDiagramEditMessages.getString("accept.change.tooltip"); //$NON-NLS-1$ break; case REJECT: tooltip = EMFCompareDiagramEditMessages.getString("reject.change.tooltip"); //$NON-NLS-1$ break; default: START throw new IllegalStateException(); END } return tooltip; } Here it's not the state of this class that's invalid, it's the given parameter. The relevant exception in such a case is IllegalArgumentException

Target:
public String getTooltip(MergeMode mode) throws IllegalArgumentException { String tooltip; switch (mode) { case LEFT_TO_RIGHT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.right.tooltip"); //$NON-NLS-1$ break; case RIGHT_TO_LEFT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.left.tooltip"); //$NON-NLS-1$ break; case ACCEPT: tooltip = EMFCompareDiagramEditMessages.getString("accept.change.tooltip"); //$NON-NLS-1$ break; case REJECT: tooltip = EMFCompareDiagramEditMessages.getString("reject.change.tooltip"); //$NON-NLS-1$ break; default: throw new IllegalArgumentException(); } return tooltip; }
Source:
START public TriggeredBuildSelector(boolean fallbackToLastSuccessful, UpstreamFilterStrategy upstreamFilterStrategy, boolean allowUpstreamDependencies) { END this.fallbackToLastSuccessful = fallbackToLastSuccessful ? Boolean.TRUE : null; this.upstreamFilterStrategy = upstreamFilterStrategy; this.allowUpstreamDependencies = allowUpstreamDependencies ? Boolean.TRUE : null; } Please add an overloaded constructor to keep comparibility (like `TriggerredBuildSelector(boolean)`).

Target:
public TriggeredBuildSelector(boolean fallbackToLastSuccessful, UpstreamFilterStrategy upstreamFilterStrategy, boolean allowUpstreamDependencies) { this.fallbackToLastSuccessful = fallbackToLastSuccessful ? Boolean.TRUE : null; this.upstreamFilterStrategy = upstreamFilterStrategy; this.allowUpstreamDependencies = allowUpstreamDependencies; }
Source:
public static Result deleteUser(Long userId) { if (User.findByLoginId(session().get("loginId")).isSiteManager()){ START if (!Project.isOnlyManager(userId)) { END User.find.byId(userId).delete(); } else { flash(Constants.WARNING, "site.userList.deleteAlert"); } } else { flash(Constants.WARNING, "auth.unauthorized.waringMessage"); } return redirect(routes.SiteApp.userList(0, null)); } 사소한 거긴 하지만 if (not a) { ... } not not a { ... } 가 되지 않도록 if 순서를 변경해 주세요.

Target:
public static Result deleteUser(Long userId) { if (User.findByLoginId(session().get("loginId")).isSiteManager()){ if (Project.isOnlyManager(userId)) { flash(Constants.WARNING, "site.userList.deleteAlert"); } else { User.find.byId(userId).delete(); } } else { flash(Constants.WARNING, "auth.unauthorized.waringMessage"); } return redirect(routes.SiteApp.userList(0, null)); }
Source:
public Attachment(@NonNull Uri uri, @NonNull String contentType, long date, @Nullable String fileName) { START if (date < 0) { END throw new AssertionError("uri, content type, and date must all be specified"); } this.uri = uri; this.fileName = fileName; this.contentType = contentType; this.date = date; } I know these are annotated nonnull, but since this is an assertion let's leave it in

Target:
public Attachment(@NonNull Uri uri, @NonNull String contentType, long date, @Nullable String fileName) { if (uri == null || contentType == null || date < 0) { throw new AssertionError("uri, content type, and date must all be specified"); } this.uri = uri; this.fileName = fileName; this.contentType = contentType; this.date = date; }
Source:
private List<VoldemortService> createServices() { List<VoldemortService> services = new ArrayList<VoldemortService>(); CoordinatorProxyService coordinator = new CoordinatorProxyService(config, storeClientConfigs); START services.add(coordinator); END if(config.isAdminServiceEnabled()) { services.add(new CoordinatorAdminService(config, storeClientConfigs)); } return ImmutableList.copyOf(services); } Just this will work too : services.add(new CoordinatorProxyService(config, storeClientConfigs)); You can save a line by not declaring a coordinator object.

Target:
private List<VoldemortService> createServices() { List<VoldemortService> services = new ArrayList<VoldemortService>(); services.add(new CoordinatorProxyService(config, storeClientConfigs)); if(config.isAdminServiceEnabled()) { services.add(new CoordinatorAdminService(config, storeClientConfigs)); } return ImmutableList.copyOf(services); }
Source:
public void afterBegin() throws EJBException, RemoteException { START log.info("afterBegin called"); END checker.setSynchronizedBegin(); } log.trace

Target:
public void afterBegin() throws EJBException, RemoteException { log.trace("afterBegin called"); checker.setSynchronizedBegin(); }
Source:
private boolean checkPagingSpec(PagingSpec pagingSpec, boolean descending) { for (Integer value : pagingSpec.getPagingIdentifiers().values()) { START if (descending ^ value < 0) { END return false; } } return pagingSpec.getThreshold() >= 0; } This is a part of the java spec I'm not as familiar with. Is this doing `((descending ? 1 : 0) ^ value) < 0` or `descending ^ (value < 0)`?

Target:
private boolean checkPagingSpec(PagingSpec pagingSpec, boolean descending) { for (Integer value : pagingSpec.getPagingIdentifiers().values()) { if (descending ^ (value < 0)) { return false; } } return pagingSpec.getThreshold() >= 0; }
Source:
private void init(Jdbi db) { START db.registerArrayType(SqlArrayTypeFactory.of(UserId.class, "int", UserId::getId)); END db.registerColumnMapper(new UserIdColumnMapper()); } Can we unroll this to use the new `Configurable` method instead?

Target:
private void init(Jdbi db) { db.registerArrayType(UserId.class, "int", UserId::getId); db.registerColumnMapper(new UserIdColumnMapper()); }
Source:
protected boolean updateBrickServerName(GlusterBrickEntity brick, boolean addCanDoActionMessage) { VdsStatic server = getVdsStaticDao().get(brick.getServerId()); START if ((server == null || !server.getvds_group_id().equals(getVdsGroupId())) && addCanDoActionMessage) { END addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_BRICK_SERVER_ID); return false; } brick.setServerName(server.gethost_name()); return true; } shouldn't it return false even if addCanDoActionMessage=false? from the name of the parameter it sounds like only the message is not needed but still give the correct return value

Target:
protected boolean updateBrickServerName(GlusterBrickEntity brick, boolean addCanDoActionMessage) { VdsStatic server = getVdsStaticDao().get(brick.getServerId()); if ((server == null || !server.getvds_group_id().equals(getVdsGroupId()))) { if (addCanDoActionMessage) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_BRICK_SERVER_ID); } return false; } brick.setServerName(server.gethost_name()); return true; }
Source:
START public static END @NonNull String getSpanName(String attributeName) { return attributeName.substring(0, attributeName.lastIndexOf('/')); } private

Target:
private static @NonNull String getSpanName(String attributeName) { return attributeName.substring(0, attributeName.lastIndexOf('/')); }
Source:
private static boolean containsAll(String text, final Collection<String> items) { final String _text = text.toLowerCase(); return items.stream() START .allMatch((String it) -> { END return _text.contains(it); }); } Why do you need to type parameter ?

Target:
private static boolean containsAll(String text, final Collection<String> items) { final String _text = text.toLowerCase(); return items.stream() .allMatch(it -> { return _text.contains(it); }); }
Source:
private void recursiveDelete(Path file) throws IOException { Files.walkFileTree(file, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; START } else { throw e; } END } }); } This doesn't really need to be in an else clause. It might be more readable to invert the logic of this block, i.e.: if (e != null) { throw e; } Files.delete(dir); return FileVisitResult.CONTINUE;

Target:
private void recursiveDelete(Path file) throws IOException { Files.walkFileTree(file, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e != null) { throw e; } Files.delete(dir); return FileVisitResult.CONTINUE; } }); }
Source:
public Optional<Object> nextMarker() { if (totalCount < pageSize) return Optional.absent(); START if (pageNumber < (totalCount / pageSize)) { END return Optional.of(toPaginationOptions(pageNumber + 1)); } return Optional.absent(); } Does the `pageNumber` start at 1 or 0? If it starts at one, this conditional could be wrong: pageNumber=1, totalCount=7,pageSize=5 would return false, but there is still a next page.

Target:
public Optional<Object> nextMarker() { if (totalCount < pageSize) return Optional.absent(); if ((float) pageNumber < ((float) totalCount / (float) pageSize)) { return Optional.of(toPaginationOptions(pageNumber + 1)); } return Optional.absent(); }
Source:
public void testInvalidUser(AuthenticationFlowContext context, UserModel user) { START if (user == null || user.getServiceAccountClientLink() != null) { END dummyHash(context); context.getEvent().error(Errors.USER_NOT_FOUND); Response challengeResponse = challenge(context, getDefaultChallengeMessage(context)); context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse); } } Is it really necessary to add this check here? Doesn't the AuthenticationProcessor prevent the login request from reaching this point?

Target:
public void testInvalidUser(AuthenticationFlowContext context, UserModel user) { if (user == null) { dummyHash(context); context.getEvent().error(Errors.USER_NOT_FOUND); Response challengeResponse = challenge(context, getDefaultChallengeMessage(context)); context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse); } }
Source:
public boolean validateChecksum() { if (StringUtils.isNotBlank(checksum)) { try { return DigestHelper.check(checksum, new FileInputStream(downloadedFilePath)); } catch (IOException e) { START throw new CloudRuntimeException("could not check sum for file: " + downloadedFilePath); END } catch (NoSuchAlgorithmException e) { throw new CloudRuntimeException("Unknown checksum algorithm: " + checksum, e); } } return true; } missing second argument to view the actual exception message/stack trace: `file: " + downloadedFilePath, e)`

Target:
public boolean validateChecksum() { if (StringUtils.isNotBlank(checksum)) { try { return DigestHelper.check(checksum, new FileInputStream(downloadedFilePath)); } catch (IOException e) { throw new CloudRuntimeException("could not check sum for file: " + downloadedFilePath,e); } catch (NoSuchAlgorithmException e) { throw new CloudRuntimeException("Unknown checksum algorithm: " + checksum, e); } } return true; }
Source:
public RegistrationUpdateEvent(String address, List<RegistrationInfo> registrations) { this.address = address; if (registrations == null || registrations.isEmpty()) { this.registrations = Collections.emptyList(); } else { START this.registrations = Collections.unmodifiableList(registrations); END } } can we avoid using `unmodifiableList` and have the cluster manager trust the list will be not modified ?

Target:
public RegistrationUpdateEvent(String address, List<RegistrationInfo> registrations) { this.address = address; this.registrations = registrations == null ? Collections.emptyList() : registrations; }
Source:
public InvocationContext createInvocationContext(boolean isWrite, int keyCount) { if (keyCount == 1) { START SingleKeyNonTxInvocationContext result = END new SingleKeyNonTxInvocationContext(true, keyEq); return result; } else if (keyCount > 0) { NonTxInvocationContext ctx = new NonTxInvocationContext(keyCount, true, keyEq); return ctx; } return createInvocationContext(null); } I would remove the variables and do `return new SingleKeyNonTxInvocationContext(true, keyEq);` the same thing can be applied to other methods

Target:
public InvocationContext createInvocationContext(boolean isWrite, int keyCount) { if (keyCount == 1) { return new SingleKeyNonTxInvocationContext(true, keyEq); } else if (keyCount > 0) { return new NonTxInvocationContext(keyCount, true, keyEq); } return createInvocationContext(null); }
Source:
private boolean isRealWorklog(final EveritWorklog worklog) { boolean isRealWorklog = true; if (issuesRegex != null) { START for (final Pattern issuePattern : issuesRegex) { END final boolean issueMatches = issuePattern.matcher(worklog.getIssue()).matches(); // if match not count in summary if (issueMatches) { isRealWorklog = false; break; } } } return isRealWorklog; } Remove all of the unnecessary final modifier from the local variables from all of the modified classes.

Target:
private boolean isRealWorklog(final EveritWorklog worklog) { boolean isRealWorklog = true; if (issuesRegex != null) { for (Pattern issuePattern : issuesRegex) { boolean issueMatches = issuePattern.matcher(worklog.getIssue()).matches(); // if match not count in summary if (issueMatches) { isRealWorklog = false; break; } } } return isRealWorklog; }
Source:
public void removed(IExtension[] extensions) { for (IExtension extension : extensions) { CustomLayoutAlgorithmProvider layoutAlgorithmProvider = extensionToLayoutAlgorithmProvider.get(extension); if (layoutAlgorithmProvider != null) { List<CustomLayoutAlgorithm> customLayoutAlgorithms = layoutAlgorithmProvider.getCustomLayoutAlgorithms(); for (CustomLayoutAlgorithm customLayoutAlgorithm : customLayoutAlgorithms) { layoutProviderRegistry.remove(customLayoutAlgorithm.getId()); } } START extensionToLayoutAlgorithmProvider.put(extension, END null); } } remove instead?

Target:
public void removed(IExtension[] extensions) { for (IExtension extension : extensions) { CustomLayoutAlgorithmProvider layoutAlgorithmProvider = extensionToLayoutAlgorithmProvider.get(extension); if (layoutAlgorithmProvider != null) { List<CustomLayoutAlgorithm> customLayoutAlgorithms = layoutAlgorithmProvider.getCustomLayoutAlgorithms(); for (CustomLayoutAlgorithm customLayoutAlgorithm : customLayoutAlgorithms) { layoutProviderRegistry.remove(customLayoutAlgorithm.getId()); } } extensionToLayoutAlgorithmProvider.remove(extension); } }
Source:
public void increment( int typeId ) { if ( typeId >= counts.length ) { START counts = Arrays.copyOf( counts, max( counts.length * 2, typeId ) ); END } counts[typeId]++; if ( typeId > highestTypeId ) { highestTypeId = typeId; } } This needs to be `typeId + 1`, since the parameter here is the _length_, while `typeId` is elsewhere used as an _index_.

Target:
public void increment( int typeId ) { if ( typeId >= counts.length ) { counts = Arrays.copyOf( counts, max( counts.length * 2, typeId + 1 ) ); } counts[typeId]++; if ( typeId > highestTypeId ) { highestTypeId = typeId; } }
Source:
private static void delete(List<ReceiveCommand> cmds, List<ReceiveCommand> createCmds) { for (ReceiveCommand c : createCmds) { ObjectId id = c.getNewId(); String START n = END c.getRefName(); cmds.add(new ReceiveCommand(id, ObjectId.zeroId(), n)); } } s/n/name/ n is always an index

Target:
private static void delete(List<ReceiveCommand> cmds, List<ReceiveCommand> createCmds) { for (ReceiveCommand cmd : createCmds) { ObjectId id = cmd.getNewId(); String name = cmd.getRefName(); cmds.add(new ReceiveCommand(id, ObjectId.zeroId(), name)); } }
Source:
public RefreshLocalVisitor(IProgressMonitor monitor) { this.monitor = START SubMonitor.convert(monitor, END TOTAL_WORK); workspace = (Workspace) ResourcesPlugin.getWorkspace(); resourceChanged = false; String msg = Messages.resources_errorMultiRefresh; errors = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_LOCAL, msg, null); } Use the one-argument version of convert, since the second argument passed in here is never used.

Target:
public RefreshLocalVisitor(IProgressMonitor monitor) { this.monitor = SubMonitor.convert(monitor); workspace = (Workspace) ResourcesPlugin.getWorkspace(); resourceChanged = false; String msg = Messages.resources_errorMultiRefresh; errors = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_LOCAL, msg, null); }
Source:
private ConfigurationImpl() { this.validationBootstrapParameters = new ValidationBootstrapParameters(); this.defaultResourceBundleLocator = new PlatformResourceBundleLocator( ResourceBundleMessageInterpolator.USER_VALIDATION_MESSAGES ); this.defaultTraversableResolver = new DefaultTraversableResolver(); this.defaultConstraintValidatorFactory = new ConstraintValidatorFactoryImpl(); if ( Version.getJavaRelease() >= 8 ) { START this.defaultParameterNameProvider = new Java8DefaultParameterNameProvider(); END } else { this.defaultParameterNameProvider = new DefaultParameterNameProvider(); } this.defaultMessageInterpolator = new ResourceBundleMessageInterpolator( defaultResourceBundleLocator ); } Should we really use it by default? I agree this would be nice (and we surely will do it as of BV 1.2) but for now the spec [describes](http://beanvalidation.org/1.1/spec/#constraintdeclarationvalidationprocess-methodlevelconstraints-definingparameterconstraints-namingparameters) "arg0", "arg1" etc. as the default names. I feel we should stick to this for now.

Target:
private ConfigurationImpl() { this.validationBootstrapParameters = new ValidationBootstrapParameters(); this.defaultResourceBundleLocator = new PlatformResourceBundleLocator( ResourceBundleMessageInterpolator.USER_VALIDATION_MESSAGES ); this.defaultTraversableResolver = new DefaultTraversableResolver(); this.defaultConstraintValidatorFactory = new ConstraintValidatorFactoryImpl(); this.defaultParameterNameProvider = new DefaultParameterNameProvider(); this.defaultMessageInterpolator = new ResourceBundleMessageInterpolator( defaultResourceBundleLocator ); }
Source:
public void testNull_Event() { XDRResponseEventType eventA = new XDRResponseEventType(); START XDREventType eventB = new XDREventType(); END eventA = null; eventB = null; assertNull(xdrTransformHelper.transformXDRResponseToCheckPolicy(eventA)); assertNull(xdrTransformHelper.transformXDRToCheckPolicy(eventB)); } Do we need to declare object and then assign to null? Just remove them

Target:
public void testNull_Event() { assertNull(xdrTransformHelper.transformXDRResponseToCheckPolicy(null)); assertNull(xdrTransformHelper.transformXDRToCheckPolicy(null)); }
Source:
public void testJNDIBindingsNoAppName() throws Exception { START boolean passed = false; END Context ctx = getInitialContext(HOST, PORT); Hello ejb = (Hello) ctx.lookup("ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello"); Assert.assertNotNull("Null object returned for local business interface lookup in the ejb namespace", ejb); Assert.assertTrue("Expected JNDI binding message not found", LoggingUtil.hasLogMessage(managementClient, TEST_HANDLER_NAME, "ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello")); } Cruft, It doesn't matter, but this is an unused variable.

Target:
public void testJNDIBindingsNoAppName() throws Exception { Context ctx = getInitialContext(HOST, PORT); Hello ejb = (Hello) ctx.lookup("ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello"); Assert.assertNotNull("Null object returned for local business interface lookup in the ejb namespace", ejb); Assert.assertTrue("Expected JNDI binding message not found", LoggingUtil.hasLogMessage(managementClient, TEST_HANDLER_NAME, "ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello")); }
Source:
public CrossesListDescriptionSheetParser(final T importedList, final UserDataManager userDataManager) { this.importedList = importedList; this.doParseDetails = true; this.doParseConditions = true; this.doParseFactors = true; this.doParseVariates = true; this.userDataManager = userDataManager; this.descriptionSheetIndex = 0; START ; END } remove

Target:
public CrossesListDescriptionSheetParser(final T importedList, final UserDataManager userDataManager) { this.importedList = importedList; this.doParseDetails = true; this.doParseConditions = true; this.doParseFactors = true; this.doParseVariates = true; this.userDataManager = userDataManager; this.descriptionSheetIndex = 0; }
Source:
public VolumeClassification getVolumeClassification() { if (volumeClassification == null) { if START (active) END { return VolumeClassification.Volume; } return VolumeClassification.Snapshot; } return volumeClassification; } please change to ternary

Target:
public VolumeClassification getVolumeClassification() { if (volumeClassification == null) { return (active ? VolumeClassification.Volume : VolumeClassification.Snapshot); } return volumeClassification; }
Source:
public void registerSonarQubeVersion_publishes_version_on_first_call() { ClusterProperties clusterProperties = new ClusterProperties(newClusterSettings()); try (HazelcastCluster hzCluster = HazelcastCluster.builder(clusterProperties).build()) { hzCluster.registerSonarQubeVersion("1.0.0.0"); HazelcastInstance hzInstance = createHazelcastClient(hzCluster); assertThat(hzInstance.getAtomicReference(SONARQUBE_VERSION).get()) .isNotNull() .isInstanceOf(String.class) START .isEqualTo("1.0.0.0"); END } } no need for isNotNull nor isInstanceOf(String.class). They are both implicit with .isEqualTo("1.0.0.0")

Target:
public void registerSonarQubeVersion_publishes_version_on_first_call() { ClusterProperties clusterProperties = new ClusterProperties(newClusterSettings()); try (HazelcastCluster hzCluster = HazelcastCluster.create(clusterProperties)) { hzCluster.registerSonarQubeVersion("1.0.0.0"); HazelcastInstance hzInstance = createHazelcastClient(hzCluster); assertThat(hzInstance.getAtomicReference(SONARQUBE_VERSION).get()).isEqualTo("1.0.0.0"); } }
Source:
public String[] getColumnTexts(@NonNull ITimeGraphEntry entry) { String[] texts = new START String[fColumns.length]; END for (int i = 0; i < fColumns.length; i++) { texts[i] = fLabelProvider.getColumnText(entry, i); } return texts; } Null pointer...

Target:
public String[] getColumnTexts(@NonNull ITimeGraphEntry entry) { String[] texts = null; if (fColumns != null) { texts = new String[fColumns.length]; for (int i = 0; i < fColumns.length; i++) { texts[i] = fLabelProvider.getColumnText(entry, i); } } else { texts = new String[1]; texts[0] = entry.getName(); } return texts; }
Source:
protected Pageview() { START } END private

Target:
private Pageview() { }
Source:
public TreeFillingConfigurationDialog(final Shell parentShell, final TreeFillingConfiguration treefillingConfiguration, final List<ILabelProviderConfiguration> existingLabelProvidersConfiguration, final List<PasteEObjectConfiguration> existingPasteConfigurations) { super(parentShell); this.modifiedTreefillingConfiguration = EcoreUtil.copy(treefillingConfiguration); this.existingLabelProviderConfigurations = existingLabelProvidersConfiguration; this.existingPasteConfigurations = existingPasteConfigurations; START setTitle(org.eclipse.papyrus.customization.nattableconfiguration.messages.Messages.TreeFillingConfigurationDialog_treeFillingConfigurationDialogName); END } import the class Messages ?

Target:
public TreeFillingConfigurationDialog(final Shell parentShell, final TreeFillingConfiguration treefillingConfiguration, final List<ILabelProviderConfiguration> existingLabelProvidersConfiguration, final List<PasteEObjectConfiguration> existingPasteConfigurations) { super(parentShell); this.modifiedTreefillingConfiguration = EcoreUtil.copy(treefillingConfiguration); this.existingLabelProviderConfigurations = existingLabelProvidersConfiguration; this.existingPasteConfigurations = existingPasteConfigurations; setTitle(Messages.TreeFillingConfigurationDialog_treeFillingConfigurationDialogName); }
Source:
public void execute(final Talks talks) throws IOException { int idx = this.index(talks); for (final Talk talk : talks.active()) { START final int current = idx + 1; END talk.modify( new Directives() .xpath("/talk/request") .attr("index", Integer.toString(current)) ); idx = current; } } `current` is redundant, just use `idx`

Target:
public void execute(final Talks talks) throws IOException { int idx = this.index(talks); for (final Talk talk : talks.active()) { idx += 1; talk.modify( new Directives() .xpath("/talk/request") .attr("index", Integer.toString(idx)) ); } }
Source:
public long getSafePointDrId() { // Acquire lock to avoid seeing bad data while another thread is in truncate() START synchronized (m_map) { END assert (!m_map.isEmpty()); return end(m_map.asRanges().iterator().next()); } } Looks good to me, but worth to protect `getFirstDrId()` and `getLastDrId()` too, they'll throw `NoSuchElementException` also if `m_map` is empty.

Target:
public long getSafePointDrId() { assert (!m_map.isEmpty()); return end(m_map.asRanges().iterator().next()); }
Source:
public void setUp() throws Exception { createProjectWithNfcAndSetVariable(PROJECT_NAME); numDetectedTags.setValue(0); nfcBrickPosition = 0; setVariableIDPosition = 1; setVariableMessagePosition = 2; baseActivityTestRule.launchActivity(null); START checkIfSpinnerOnBrickAtPositionShowsString(R.id.set_variable_spinner, setVariableIDPosition, READ_TAG_ID); END checkIfSpinnerOnBrickAtPositionShowsString(R.id.set_variable_spinner, setVariableMessagePosition, READ_TAG_MESSAGE); } is this necessary in the set up? wouldnt it be sufficient if this would be done once in the layout test?

Target:
public void setUp() throws Exception { createProjectWithNfcAndSetVariable(); baseActivityTestRule.launchActivity(null); }
Source:
public ListRequest list() { return new ListRequest() { @Override public List<ProjectInfo> get() throws RestApiException { START return ProjectsImpl.this.list(this); END } }; } I don't think ProjectsImpl.this is necessary, it would only be necessary if the method call were get(this) which conflicts with the method name in the anonymous class.

Target:
public ListRequest list() { return new ListRequest() { @Override public List<ProjectInfo> get() throws RestApiException { return list(this); } }; }
Source:
START public void validateEnums(WatchDog entity) { END EnumValidator.validateEnum(WatchdogAction.class, entity.getAction(), true); EnumValidator.validateEnum(WatchdogModel.class, entity.getModel(), false); } potential NPE, entity can be NULL

Target:
public void validateEnums(WatchDog entity) { if (entity != null) { EnumValidator.validateEnum(WatchdogAction.class, entity.getAction(), true); EnumValidator.validateEnum(WatchdogModel.class, entity.getModel(), true); } }
Source:
void error(ZuulException e) { RequestContext.getCurrentContext().setThrowable(e); zuulRunner.error(); START LOG.error(e.getMessage(), e); END } My preference would be to remove `e.printStackTrace()` altogether and let the 'error' filters determine if they want to log the error.

Target:
void error(ZuulException e) { RequestContext.getCurrentContext().setThrowable(e); zuulRunner.error(); }
Source:
private List<String> defaultIncludedModuleNamesForUnnamedModule() { if (fJavaElements != null) { List<IPackageFragmentRoot> roots= new ArrayList<>(); for (IJavaElement START fJavaElement : END fJavaElements) { if (fJavaElement instanceof IPackageFragmentRoot) { roots.add((IPackageFragmentRoot) fJavaElement); } } return JavaCore.defaultRootModules(roots); } return Collections.emptyList(); } rename to element

Target:
private List<String> defaultIncludedModuleNamesForUnnamedModule() { if (fJavaElements != null) { List<IPackageFragmentRoot> roots= new ArrayList<>(); for (IJavaElement element : fJavaElements) { if (element instanceof IPackageFragmentRoot) { roots.add((IPackageFragmentRoot) element); } } return JavaCore.defaultRootModules(roots); } return Collections.emptyList(); }
Source:
START public ResponseEntity<?> disable(@RequestBody List<Long> printerIds) throws IOException { END return setState(printerIds, false); } `@ResponseStatus(HttpStatus.NO_RESPONSE)`, void return type Same for `/enable`

Target:
public void disable(@RequestBody List<Long> printerIds) throws IOException { setState(printerIds, false); }
Source:
public double getFilterMinSelectivityEstimateFactor() { START return options.getOption(FILTER_MIN_SELECTIVITY_ESTIMATE_FACTOR.getOptionName()).float_val; END } Make the option validators above typed: `public static final FloatValidator FILTER_MIN_SELECTIVITY_ESTIMATE_FACTOR ...` and change this line to: `return options.getOption(FILTER_MIN_SELECTIVITY_ESTIMATE_FACTOR);` Same for the other option.

Target:
public double getFilterMinSelectivityEstimateFactor() { return options.getOption(FILTER_MIN_SELECTIVITY_ESTIMATE_FACTOR); }
Source:
public JavaOutputProcessor(PrettyPrinter printer) { START this.printer = printer; END this.environment = printer.getEnvironment(); } why did you need to copy the env? it is accessible via getFactory().getEnv().

Target:
public JavaOutputProcessor(PrettyPrinter printer) { this.printer = printer; }
Source:
public BucketFunction getBucketFunction( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle, List<Type> partitionChannelTypes, int bucketCount) { HivePartitioningHandle handle = (HivePartitioningHandle) partitioningHandle; BucketFunctionType bucketFunctionType = handle.getBucketFunctionType(); switch (bucketFunctionType) { case HIVE_COMPATIBLE: return createHiveCompatibleBucketFunction(bucketCount, handle.getHiveTypes().get()); case PRESTO_NATIVE: return createPrestoNativeBucketFunction(bucketCount, handle.getTypes().get()); default: START throw new IllegalStateException("Unsupported bucket function type " + bucketFunctionType); END } } nit `IllegalArgumentException`

Target:
public BucketFunction getBucketFunction( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle, List<Type> partitionChannelTypes, int bucketCount) { HivePartitioningHandle handle = (HivePartitioningHandle) partitioningHandle; BucketFunctionType bucketFunctionType = handle.getBucketFunctionType(); switch (bucketFunctionType) { case HIVE_COMPATIBLE: return createHiveCompatibleBucketFunction(bucketCount, handle.getHiveTypes().get()); case PRESTO_NATIVE: return createPrestoNativeBucketFunction(bucketCount, handle.getTypes().get()); default: throw new IllegalArgumentException("Unsupported bucket function type " + bucketFunctionType); } }
Source:
public void writePacketData(RailcraftOutputStream data) throws IOException { super.writePacketData(data); START tankManager.writePacketData(data); END data.writeBoolean(boiler.isBurning()); } This is only required in things that render the FluidStack in a TESR.

Target:
public void writePacketData(RailcraftOutputStream data) throws IOException { super.writePacketData(data); // tankManager.writePacketData(data); data.writeBoolean(boiler.isBurning()); }
Source:
protected void setValue(final int rowIndex, final int columnIndex, final Date value) { DTCellValue52 dtCellValue52 = table52.getData() .get(rowIndex) .get(columnIndex); dtCellValue52 .setDateValue(value); try { updateManager.update(table52, getUpdates(rowIndex, columnIndex)); START } catch (UpdateException e) { END e.printStackTrace(); } } This _smells_ bad.. what was your reasoning to catch `UpdateException`?

Target:
protected void setValue(final int rowIndex, final int columnIndex, final Date value) { DTCellValue52 dtCellValue52 = table52.getData() .get(rowIndex) .get(columnIndex); dtCellValue52 .setDateValue(value); updateManager.update(table52, getUpdates(rowIndex, columnIndex)); }
Source:
private TreeMap<Event, List<EntryDTO>> buildEventEntryDTOMap(List<EntryDTO> entryDTOS) { return entryDTOS.stream().collect(Collectors.groupingBy(EntryDTO::getEvent, START () -> new TreeMap<>(Comparator.comparing(Event::getExternalId).thenComparing(Event::getWhenOccured)), Collectors.toList())); END } ```suggestion () -> new TreeMap<>(Comparator.comparing(Event::getWhenOccured).thenComparing(Event::getExternalId)), Collectors.toList())); ```

Target:
private TreeMap<Event, List<EntryDTO>> buildEventEntryDTOMap(List<EntryDTO> entryDTOS) { return entryDTOS.stream().collect(Collectors.groupingBy(EntryDTO::getEvent, () -> new TreeMap<>(Comparator.comparing(Event::getWhenOccured).thenComparing(Event::getExternalId)), Collectors.toList())); }
Source:
START public void verifyTableProperty(String propertyName, int propertyValue) { END waitForElementByElement(table); Assertion.assertEquals(table.getAttribute(propertyName), Integer.toString(propertyValue)); PageObjectLogging.log( "verifyTableProperty", "table has correct " + propertyName + " property", true ); } 1. set this method to private, 2. create helpers for each property

Target:
private void verifyTableProperty(String propertyName, int propertyValue) { waitForElementByElement(table); Assertion.assertEquals(table.getAttribute(propertyName), Integer.toString(propertyValue)); PageObjectLogging.log( "verifyTableProperty", "table has correct " + propertyName + " property", true ); }
Source:
public ColumnMetadata_v4(String[] name, PrimitiveType.PrimitiveTypeName primitiveType, Object minValue, Object maxValue, Long nulls) { START this.name = name; END this.minValue = minValue; this.maxValue = maxValue; this.nulls = nulls; this.primitiveType = primitiveType; } Please post the examples of content for new metadata cache files to the Jira description

Target:
public ColumnMetadata_v4(String[] name, PrimitiveType.PrimitiveTypeName primitiveType, Object minValue, Object maxValue, Long nulls) { super(name, primitiveType, minValue, maxValue, nulls); }
Source:
START @Override public END ReflogEntry getReverseEntry(int number) throws IOException { lock.lock(); try { LogCursor cursor = reftable.seekLog(refname); while (true) { if (!cursor.next() || number < 0) { return null; } if (number == 0) { return cursor.getReflogEntry(); } number--; } } finally { lock.unlock(); } } The @Override should go on a line on its own, like in getReverseEntries() and the same below.

Target:
public ReflogEntry getReverseEntry(int number) throws IOException { lock.lock(); try { LogCursor cursor = reftable.seekLog(refname); while (true) { if (!cursor.next() || number < 0) { return null; } if (number == 0) { return cursor.getReflogEntry(); } number--; } } finally { lock.unlock(); } }
Source:
public void testVersion0_98IsValid() throws Exception{ rootDir = Paths.get(getClass().getClassLoader().getResource("bags/v0_98/bag").toURI()); if (System.getProperty("os.name").contains("Windows")){ START Path bagitDir = rootDir.resolve(".bagit"); END Files.setAttribute(bagitDir, "dos:hidden", Boolean.TRUE); } Bag bag = reader.read(rootDir); sut.isValid(bag, true); } the .bagit folder does not have to be hidden. .bagit is our incubating next version of the bagit spec; it solves a lot of problems from the originial spec.

Target:
public void testVersion0_98IsValid() throws Exception{ rootDir = Paths.get(getClass().getClassLoader().getResource("bags/v0_98/bag").toURI()); Bag bag = reader.read(rootDir); sut.isValid(bag, true); }
Source:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { START final AbstractStatementVisitor visitor = new PreStatementVisitor(context); END syntaxNode.accept(visitor); return visitor.programState; } remove `final` modifiers everywhere.

Target:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { AbstractStatementVisitor visitor = new PreStatementVisitor(context); syntaxNode.accept(visitor); return visitor.programState; }
Source:
START ParameterMap getQueryParams(MuleEvent event) END { return resolveParams(event, HttpParamType.QUERY_PARAM); } This breaks compatibility.

Target:
public ParameterMap getQueryParams(MuleEvent event) { return resolveParams(event, HttpParamType.QUERY_PARAM); }
Source:
public Mutation(Mutation m) { m.serialize(); this.row = m.row; this.data = m.data; START this.size = new MutationSize(m.size.entries, m.size.sizeInBytes); END this.values = m.values; this.replicationSources = m.replicationSources; } maybe make a copy constructor for this case?

Target:
public Mutation(Mutation m) { m.serialize(); this.row = m.row; this.data = m.data; this.entries = m.entries; this.values = m.values; this.replicationSources = m.replicationSources; }
Source:
public DecoratedCache(AdvancedCache<K, V> delegate, ClassLoader classLoader) { START this(delegate, classLoader, null, null); END } The last `null` is interpreted as a null `Flag`, not as a null `Flag[]`, and is causing some NPEs in the test suite: http://ci.infinispan.org/viewLog.html?buildId=6702&buildTypeId=bt9

Target:
public DecoratedCache(AdvancedCache<K, V> delegate, ClassLoader classLoader) { this(delegate, classLoader, null); }
Source:
default Query getRemoveByQuery() { START if (isVersionedEntity()) { END return getQueryForVersion(); } return getByIdQuery(); } Ternary ? true : false. ;)

Target:
default Query getRemoveByQuery() { return isVersionedEntity() ? getQueryForVersion() : getByIdQuery(); }
Source:
START public void addError(String errorMessage, Element element) { END errors.add(new ProblemImpl(errorMessage, name, element)); } There are still a lot of calls to this method, resulting in errors that will not reference any BPMN element. From a quick look, many of those do have an element id that we could reference.

Target:
public void addError(String errorMessage, Element element) { errors.add(new ProblemImpl(errorMessage, element)); }