auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static Process getProcess(IngesterName name) { Environment environment; try { environment = Environment.valueOf(TelescopeConfiguration.ENVIRONMENT); } catch (IllegalArgumentException e) { //add stage as the default environment, which is better than crashing START log.error("Could not find a telescope environment with the given name, name={}. Falling back to STAGE.", TelescopeConfiguration.ENVIRONMENT); END e.printStackTrace(); environment = Environment.STAGE; } return Process.create(name.getIngesterKey(), name.getIngesterName(), environment); } this shouldn't be necessary and if people aren't watching the logs carefully enough this could cause an ingest to stage without someone realising

Target:
private static Process getProcess(IngesterName name) { Environment environment; try { environment = Environment.valueOf(ENVIRONMENT); } catch (IllegalArgumentException e) { //add stage as the default environment, which is better than crashing environment = Environment.STAGE; log.error( "Could not find a telescope environment with the given name, name={}. Falling back to STAGE.", ENVIRONMENT, e ); } return Process.create(name.getIngesterKey(), name.getIngesterName(), environment); }
Source:
private String extractBaseIdFromUri(Channel channel) { return channel.getUri() START .replace(uriPrefix, "") END .trim(); } could the URI ever have a trailing '/' or similar cruft?

Target:
String extractBaseIdFromUri(Channel channel) { return channel.getUri() .replace(uriPrefix, "") .trim(); }
Source:
private Optional<Channel> updateChannelWithAdvertisedDates( Channel channel, DateTime advertiseFromDate, DateTime advertiseToDate ) { if (advertiseFromDate != null && advertiseFromDate.getMillis() > 0) { channel.setAdvertiseFrom(advertiseFromDate); } else { channel.setAdvertiseFrom(null); } if (advertiseToDate != null && advertiseToDate.getMillis() > 0) { channel.setAdvertiseTo(advertiseToDate); } else { channel.setAdvertiseTo(null); } channelWriter.createOrUpdate(channel); START return Optional.of(channel); END } why bother re-wrapping this to be returned, when it's not passed to this method as an Optional, so it must always be present?

Target:
private Channel updateChannelWithAdvertisedDates( Channel channel, DateTime advertiseFromDate, DateTime advertiseToDate ) { if (advertiseFromDate != null && advertiseFromDate.getMillis() > 0) { channel.setAdvertiseFrom(advertiseFromDate); } else { channel.setAdvertiseFrom(null); } if (advertiseToDate != null && advertiseToDate.getMillis() > 0) { channel.setAdvertiseTo(advertiseToDate); } else { channel.setAdvertiseTo(null); } channelWriter.createOrUpdate(channel); return channel; }
Source:
private void removeStaleAliasesFromChannel( Set<Long> channelIdsThatHaveAliasesAdded, Iterable<Channel> channels ) { for (Channel channel : channels) { if(!channelIdsThatHaveAliasesAdded.contains(channel.getId())) { channel.setAliases( channel.getAliases() .stream() START .filter(alias -> !alias.getNamespace().equals(aliasNamespace)) END .collect(Collectors.toList()) ); } channelWriter.createOrUpdate(channel); } } should this use Objects.equals JIC null safety is required?

Target:
private void removeStaleAliasesFromChannel( Set<Long> channelIdsThatHaveAliasesAdded, Iterable<Channel> channels ) { for (Channel channel : channels) { if(!channelIdsThatHaveAliasesAdded.contains(channel.getId())) { channel.setAliases( channel.getAliases() .stream() .filter(alias -> !alias.getNamespace().equals(aliasNamespace)) .collect(Collectors.toList()) ); channelWriter.createOrUpdate(channel); } } }
Source:
private boolean titlesEqual(String subjectTitle, String candidateTitle) { START return false && subjectTitle.equals(candidateTitle); END } wouldn't false and something always be false?

Target:
private boolean titlesEqual(String subjectTitle, String candidateTitle) { return subjectTitle.equals(candidateTitle); }
Source:
public void scheduleUpdater() { ExecutorService executorService = Executors.newFixedThreadPool(STARTUP_THREAD_COUNT); Set<ScheduledTask> jobsAtStartup = Sets.newHashSet(); if (Boolean.parseBoolean(updaterEnabled) && Boolean.parseBoolean(channelEquivEnabled)) { log.info("Channel equivalence enabled"); addEquivalenceJobs(jobsAtStartup); } START for (ScheduledTask scheduledTask : jobsAtStartup) { END executorService.submit(scheduledTask); } } can this be streamed?

Target:
public void scheduleUpdater() { ExecutorService executorService = Executors.newFixedThreadPool(STARTUP_THREAD_COUNT); Set<ScheduledTask> jobsAtStartup = Sets.newHashSet(); if (Boolean.parseBoolean(updaterEnabled) && Boolean.parseBoolean(channelEquivEnabled)) { log.info("Channel equivalence enabled"); addEquivalenceJobs(jobsAtStartup); } jobsAtStartup.forEach(executorService::submit); }
Source:
private ItunesEpfFileUpdater( String username, String password, String feedPath, String localFilesPath, S3Client s3Client ) { this.username = checkNotNull(username); this.password = checkNotNull(password); this.feedPath = checkNotNull(feedPath); this.localFilesPath = checkNotNull(localFilesPath); START this.s3client = s3Client; END } `checkNotNull`

Target:
private ItunesEpfFileUpdater( String username, String password, String feedPath, String localFilesPath, S3Client s3Client ) { this.username = checkNotNull(username); this.password = checkNotNull(password); this.feedPath = checkNotNull(feedPath); this.localFilesPath = checkNotNull(localFilesPath); this.s3client = checkNotNull(s3Client); }
Source:
START public EquivGraphController(LookupEntryStore lookupStore) { END this.lookupStore = checkNotNull(lookupStore); this.codec = SubstitutionTableNumberCodec.lowerCaseOnly(); } convert to private constructor and a static create method

Target:
private EquivGraphController(LookupEntryStore lookupStore) { this.lookupStore = checkNotNull(lookupStore); this.codec = SubstitutionTableNumberCodec.lowerCaseOnly(); }
Source:
START public ExclusionListFilter(Iterable<String> excludedUris, Iterable<String> excludedIds) { END this.excludedUris = ImmutableSet.copyOf(excludedUris); this.excludedIds = ImmutableSet.copyOf(excludedIds); this.codec = SubstitutionTableNumberCodec.lowerCaseOnly(); } convert to private constructor and a static create method

Target:
private ExclusionListFilter(Iterable<String> excludedUris, Iterable<String> excludedIds) { this.excludedUris = ImmutableSet.copyOf(excludedUris); this.excludedIds = ImmutableSet.copyOf(excludedIds); this.codec = SubstitutionTableNumberCodec.lowerCaseOnly(); }
Source:
START public EquivalenceGenerators( END Iterable<? extends EquivalenceGenerator<T>> generators, Set<String> excludedUris, Set<String> excludedIds ) { this.generators = ImmutableList.copyOf(generators); this.excludedUris = excludedUris; this.excludedIds = excludedIds; this.codec = SubstitutionTableNumberCodec.lowerCaseOnly(); } convert to private constructor and a static create method

Target:
private EquivalenceGenerators( Iterable<? extends EquivalenceGenerator<T>> generators, Set<String> excludedUris, Set<String> excludedIds ) { this.generators = ImmutableList.copyOf(generators); this.excludedUris = excludedUris; this.excludedIds = excludedIds; this.codec = SubstitutionTableNumberCodec.lowerCaseOnly(); }
Source:
public void generatorCreatesCandidatesForNonExcludedUri() { Item item = new Item(); START item.setId(12345678L); END item.setCanonicalUri("notexcluded"); generators.generate(item, resultDescription); verify(generator).generate(item, resultDescription); } I'd write some explicit tests for your ID list instead of adding id's into the uri tests. It's quick and a lot clearer what you're testing. Also, decoding the string representation of an ID to a long and using that variable in the tests would be a lot clearer to show which ID matches.

Target:
public void generatorCreatesCandidatesForNonExcludedUri() { Item item = new Item(); item.setCanonicalUri("notexcluded"); generators.generate(item, resultDescription); verify(generator).generate(item, resultDescription); }
Source:
private ContentWriteController contentWriteController() { return ContentWriteController.create( configFetcher, contentWriteExecutor, lookupBackedContentIdGenerator, contentWriteMessageSender, contentModelOutputter(), lookupStore, contentResolver, contentWriter, new EquivalenceBreaker( contentResolver, entryStore, lookupWriter ), START new OldContentDeactivator( END new MongoContentLister( mongo, new MongoContentResolver(mongo, lookupStore) ), contentWriter, contentResolver ) ); } If any of these classes are part of the `atlas` repo let's change them to have static factory methods as per the code style

Target:
private ContentWriteController contentWriteController() { return ContentWriteController.create( configFetcher, contentWriteExecutor, lookupBackedContentIdGenerator, contentWriteMessageSender, contentModelOutputter(), lookupStore, contentResolver, contentWriter, EquivalenceBreaker.create( contentResolver, entryStore, lookupWriter ), OldContentDeactivator.create( new MongoContentLister( mongo, new MongoContentResolver(mongo, lookupStore) ), contentWriter, contentResolver ) ); }
Source:
private ContentWriteController contentWriteController() { return ContentWriteController.create( configFetcher, contentWriteExecutor, lookupBackedContentIdGenerator, contentWriteMessageSender, contentModelOutputter(), lookupStore, contentResolver, contentWriter, new EquivalenceBreaker( contentResolver, entryStore, lookupWriter ), oldContentDeactivator, START configFetcher END ); } already passed in

Target:
private ContentWriteController contentWriteController() { return ContentWriteController.create( configFetcher, contentWriteExecutor, lookupBackedContentIdGenerator, contentWriteMessageSender, contentModelOutputter(), lookupStore, contentResolver, contentWriter, new EquivalenceBreaker( contentResolver, entryStore, lookupWriter ), oldContentDeactivator ); }
Source:
public void testConvertsPcOdToBrandIosUri() { map.put("dc:relation.programmeId", "338672-002"); START Assert.assertThat( END C4AtomApi.iOsUriFromPcUri("http://www.channel4.com/programmes/come-dine-with-me/on-demand/338672-002", map), is("all4://views/brands?brand=come-dine-with-me&programme=338672-002")); } Needs a static import.

Target:
public void testConvertsPcOdToBrandIosUri() { map.put("dc:relation.programmeId", "338672-002"); assertThat( C4AtomApi.iOsUriFromPcUri("http://www.channel4.com/programmes/come-dine-with-me/on-demand/338672-002", map), is("all4://views/brands?brand=come-dine-with-me&programme=338672-002")); }
Source:
private ChannelWriteController channelWriteController() { START return new ChannelWriteController( END configFetcher, channelStore, new DefaultGsonModelReader(), new ChannelModelTransformer( v4ChannelCodec(), new ImageModelTranslator() ) ); } Code style. Use static factory methods or builders for all classes. Constructors should be private

Target:
ChannelWriteController channelWriteController() { return ChannelWriteController.create( configFetcher, channelStore, DefaultGsonModelReader.create(), ChannelModelTransformer.create( v4ChannelCodec(), ImageModelTranslator.create() ) ); }
Source:
private Iterable<NitroItemSource<Episode>> toItemSources(Iterable<Episode> episodes) throws GlycerinException, NitroException { return new PaginatedNitroItemSources( episodes, START NITRO_BATCH_SIZE, END pageSize, executor, glycerin ); } This used to be an unused member inside it, is this actually used now or just left here?

Target:
private Iterable<NitroItemSource<Episode>> toItemSources(Iterable<Episode> episodes) throws GlycerinException, NitroException { return new PaginatedNitroItemSources( episodes, pageSize, executor, glycerin ); }
Source:
public boolean hasNext() { START if (episodes.hasNext()) { END return true; } return false; } Again, just return the boolean value.

Target:
public boolean hasNext() { return episodes.hasNext(); }
Source:
public List<Clip> getClips(String pid, String uri) { PidReference pidReference = new PidReference(); pidReference.setPid(pid); pidReference.setHref(uri); List<Clip> clips; try { START clips = clipsAdapter.clipsFor(pidReference); END } catch (NitroException e) { throw Throwables.propagate(e); } return clips; } Could simplify to `try { return clipsAdapter.clipsFor(pidReference); ...`

Target:
public List<Clip> getClips(String pid, String uri) { PidReference pidReference = new PidReference(); pidReference.setPid(pid); pidReference.setHref(uri); try { return clipsAdapter.clipsFor(pidReference); } catch (NitroException e) { throw Throwables.propagate(e); } }
Source:
private void setTags(ProgData progData, Content content) { Set<String> tagsFromGenres = paTagMap.map(content.getGenres()); START if (!tagsFromGenres.isEmpty()) { END content.setTags(tagsFromGenres); } } Why do we need this guard?

Target:
private void setTags(ProgData progData, Content content) { Set<String> tagsFromGenres = paTagMap.map(content.getGenres()); content.setTags(tagsFromGenres); }
Source:
protected boolean subjectAndCandidateMatch(Item subject, Item candidate) { ImmutableSet<String> aliasesOfCandidateBroadcasts = FluentIterable.from(candidate.flattenBroadcasts()) .transformAndConcat(BROADCAST_TO_ALIAS_STRING_ITERABLE) .toSet(); ImmutableSet<String> aliasesOfSubjectBroadcasts = FluentIterable.from(subject.flattenBroadcasts()) .transformAndConcat(BROADCAST_TO_ALIAS_STRING_ITERABLE) .toSet(); if (!Sets.intersection(aliasesOfCandidateBroadcasts, aliasesOfSubjectBroadcasts).isEmpty()) { return true; } START return false; END } you could eliminate the `if` here, and just do: `return !Sets.intersection(aliasesOfCandidateBroadcasts, aliasesOfSubjectBroadcasts).isEmpty();`

Target:
protected boolean subjectAndCandidateMatch(Item subject, Item candidate) { ImmutableSet<String> aliasesOfCandidateBroadcasts = FluentIterable.from(candidate.flattenBroadcasts()) .transformAndConcat(BROADCAST_TO_ALIAS_STRING_ITERABLE) .toSet(); ImmutableSet<String> aliasesOfSubjectBroadcasts = FluentIterable.from(subject.flattenBroadcasts()) .transformAndConcat(BROADCAST_TO_ALIAS_STRING_ITERABLE) .toSet(); return !Sets.intersection(aliasesOfCandidateBroadcasts, aliasesOfSubjectBroadcasts).isEmpty(); }
Source:
public C4AtomEntryVersionExtractor(Optional<Platform> platform, C4LocationPolicyIds locationPolicyIds, boolean createIosBrandLocations) { this.platform = checkNotNull(platform); this.locationPolicyIds = checkNotNull(locationPolicyIds); START this.createIosBrandLocations = checkNotNull(createIosBrandLocations); END } it's a primitive

Target:
public C4AtomEntryVersionExtractor(Optional<Platform> platform, C4LocationPolicyIds locationPolicyIds, boolean createIosBrandLocations) { this.platform = checkNotNull(platform); this.locationPolicyIds = checkNotNull(locationPolicyIds); this.createIosBrandLocations = createIosBrandLocations; }
Source:
public void handle(EquivalenceResult<T> result) { try { START sender.sendMessage(messageFrom(result));; END } catch (Exception e) { log.error("Failed to send equiv update message: " + result.subject(), e); } } double semi-colon

Target:
public void handle(EquivalenceResult<T> result) { try { sender.sendMessage(messageFrom(result)); } catch (Exception e) { log.error("Failed to send equiv update message: " + result.subject(), e); } }
Source:
public BaseContentPopulator(Optional<RoviProgramLine> program, Iterable<RoviProgramDescriptionLine> descriptions, ContentResolver contentResolver) { checkArgument(!isDelete(program), "It's not possible to populate from a program delete action"); checkNotNull(descriptions); checkNotNull(contentResolver); START this.optionalProgram = program; END this.descriptions = descriptions; this.contentResolver = contentResolver; } `checkNotNull`?

Target:
public BaseContentPopulator(Optional<RoviProgramLine> program, Iterable<RoviProgramDescriptionLine> descriptions, ContentResolver contentResolver) { checkArgument(!isDelete(program), "It's not possible to populate from a program delete action"); this.optionalProgram = checkNotNull(program); this.descriptions = checkNotNull(descriptions); this.contentResolver = checkNotNull(contentResolver); }
Source:
public ContentBuffer(ContentResolver contentResolver, ContentWriter contentWriter, ItemsPeopleWriter peopleWriter) { START this.resolver = Preconditions.checkNotNull(contentResolver); END this.writer = Preconditions.checkNotNull(contentWriter); this.peopleWriter = Preconditions.checkNotNull(peopleWriter); } static import?

Target:
public ContentBuffer(ContentResolver contentResolver, ContentWriter contentWriter, ItemsPeopleWriter peopleWriter) { this.resolver = checkNotNull(contentResolver); this.writer = checkNotNull(contentWriter); this.peopleWriter = checkNotNull(peopleWriter); }
Source:
START private boolean isUserRoleChanged(User posted, User existing) { END return posted.getRole().equals(existing.getRole()); } isn't this `isUserRoleNotChanged`?

Target:
private boolean isUserRoleChanged(User posted, User existing) { return !posted.getRole().equals(existing.getRole()); }
Source:
private XMLReader createReader() { try { JAXBContext context; START context = JAXBContext.newInstance("org.atlasapi.remotesite.pa.features.bindings"); END Unmarshaller unmarshaller = context.createUnmarshaller(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(unmarshaller.getUnmarshallerHandler()); unmarshaller.setListener(featuresProcessingListener()); return reader; } catch (Exception e) { throw new RuntimeException(e); } } minor thing... why is this broken into two lines?

Target:
private XMLReader createReader() { try { JAXBContext context = JAXBContext.newInstance("org.atlasapi.remotesite.pa.features.bindings"); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(unmarshaller.getUnmarshallerHandler()); unmarshaller.setListener(featuresProcessingListener()); return reader; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private boolean hasBrandSummary(ProgData progData) { if (Strings.isNullOrEmpty(progData.getSeriesSummary())) { return false; } START return true; END } if ([boolean condition]) return boolean... REALLY? in other news, you could just do return !Strings.isNullOrEmpty(progData.getSeriesSummary());

Target:
private boolean hasBrandSummary(ProgData progData) { return !Strings.isNullOrEmpty(progData.getSeriesSummary()); }
Source:
private boolean hasSeriesSummary(ProgData progData) { if (progData.getSeason() != null && !Strings.isNullOrEmpty(progData.getSeason().getSeasonSummary())) { return true; } START return false; END } Another instance of returning boolean on the result of a boolean check. THIS IS BAD.

Target:
private boolean hasSeriesSummary(ProgData progData) { return (progData.getSeason() != null && !Strings.isNullOrEmpty(progData.getSeason().getSeasonSummary())); }
Source:
public void write(ByteBuffer buffer) { buffer.putLong(offset); START buffer.rewind(); END } why rewind?

Target:
public void write(ByteBuffer buffer) { buffer.putLong(offset); }
Source:
public FetchedDataChunk(ByteBufferMessageSet messages, PartitionTopicInfo topicInfo, long fetchOffset) { START super(); END this.messages = messages; this.topicInfo = topicInfo; this.fetchOffset = fetchOffset; } remove

Target:
public FetchedDataChunk(ByteBufferMessageSet messages, PartitionTopicInfo topicInfo, long fetchOffset) { this.messages = messages; this.topicInfo = topicInfo; this.fetchOffset = fetchOffset; }
Source:
public Void visit(Boolean inTailPosition, FieldGet fieldGet) { START fieldGet.getObjectExpr().acceptVisitor(this, inTailPosition); END return null; } The recursive call should pass "false" because we have to get a field from any result

Target:
public Void visit(Boolean inTailPosition, FieldGet fieldGet) { fieldGet.getObjectExpr().acceptVisitor(this, false); return null; }
Source:
public ASTNode() { this((FileLocation)null); START location = null; END } This duplicates the initialization of location in the other constructor that's called in the previous line

Target:
public ASTNode() { this((FileLocation)null); }
Source:
START public boolean containsResource() { END return this.hasResource; } Declare this abstract or with a default implementation, then override in subclasses. VarDeclaration always contains a resource; ValDeclaration contains one depending on it's type; TypeDeclaration never contains a resource.

Target:
public boolean containsResource() { return false; }
Source:
START public void setHasResource(boolean hasResource) { END this.hasResource = hasResource; } This should be private, as we don't want the resource attribute to be set externally.

Target:
private void setHasResource(boolean hasResource) { this.hasResource = hasResource; }
Source:
START public Set<String> getFreeVariables() { END // Get free variables in the sub-expressions. Set<String> freeVars = toReplace.getFreeVariables(); freeVars.addAll(inExpr.getFreeVariables()); // Remove the name that just became bound. freeVars.remove(varName); return freeVars; } Technically bind has exactly the free variables that are in the "toReplace" part. The inExpr can use varName, and nothing else.

Target:
public Set<String> getFreeVariables() { return toReplace.getFreeVariables(); }
Source:
public Set<String> getFreeVariables() { // Get all free variables in the body of the method. Set<String> freeVars = body.getFreeVariables(); // Remove variables that became bound in this method's scope. START freeVars.remove(this.getName()); END for (FormalArg farg : formalArgs) { freeVars.remove(farg.getName()); } return freeVars; } Actually the name of the definition is not bound in the body --- at the level of the Core IL, recursive calls must be of the form "this.mymethod(...)" not just "mymethod(...)" [there is a sugar that makes this work at the source level but it goes away in translation to the core]

Target:
public Set<String> getFreeVariables() { // Get all free variables in the body of the method. Set<String> freeVars = body.getFreeVariables(); // Remove variables that became bound in this method's scope. for (FormalArg farg : formalArgs) { freeVars.remove(farg.getName()); } return freeVars; }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if(obj == null) { return false; } if(this.getClass() != obj.getClass()) { return false; } try { StringLiteral other = (StringLiteral) obj; START return this.equals(other); END } catch(ClassCastException e) { return false; } } Instead of this, check if the String values are equal.

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if(obj == null) { return false; } if(this.getClass() != obj.getClass()) { return false; } try { StringLiteral other = (StringLiteral) obj; return this.getValue().equals(other.getValue()); } catch(ClassCastException e) { return false; } }
Source:
private boolean indexIsOutOfRange(List<Element> elements) { START return elements.size() <= 0 || elementIndex >= elements.size(); END } Could use `elements.isEmpty()` instead of checking size `<= 0`.

Target:
private boolean indexIsOutOfRange(List<Element> elements) { return elements.isEmpty() || elementIndex >= elements.size(); }
Source:
public ZestLoopState<String> deepCopy() { ZestLoopStateFile copy = new ZestLoopStateFile(); if(this.convertedState==null){ START System.err.println("this converted state is null? "); END } copy.convertedState = (ZestLoopStateString) this.convertedState .deepCopy(); return copy; } We shouldnt use System.out.println / System.out.err.println anywhere apart from the CmdLine.java or ZestPrinter.java. If its an indication of a serious problem then throw an exception :)

Target:
public ZestLoopState<String> deepCopy() { ZestLoopStateFile copy = new ZestLoopStateFile(); copy.convertedState = (ZestLoopStateString) this.convertedState .deepCopy(); return copy; }
Source:
public boolean isTrue(ZestResponse response) { START boolean toReturn = true; END for (ZestExpressionElement con : getChildrenCondition()) { toReturn = toReturn && con.evaluate(response);// compute AND for each child if(!toReturn) break;//lazy evaluation } return toReturn; } Again, I'd default to false - I think 'nothing' makes more sense as false...

Target:
public boolean isTrue(ZestResponse response) { if(getChildrenCondition().isEmpty()) return false; boolean toReturn = true; for (ZestExpressionElement con : getChildrenCondition()) { toReturn = toReturn && con.evaluate(response);// compute AND for each child if(!toReturn) break;//lazy evaluation } return toReturn; }
Source:
public ZestExpressionURL deepCopy() { ZestExpressionURL copy = new ZestExpressionURL(); List<String> copyIncludeRegex = new ArrayList<>(includeRegexes); List<String> copyExcludeRegex = new ArrayList<>(excludeRegexes); List<Pattern> copyIncludePatterns = new ArrayList<>(includePatterns); START List<Pattern> copyExcludePatterns = new ArrayList<>(excludePatterns); END copy.excludePatterns = copyExcludePatterns; copy.includePatterns = copyIncludePatterns; copy.includeRegexes = copyIncludeRegex; copy.excludeRegexes = copyExcludeRegex; return copy; } Dont these all need to be deepCopy'ed?

Target:
public ZestExpressionURL deepCopy() { ZestExpressionURL copy = new ZestExpressionURL(); List<String> copyIncludeRegex = new ArrayList<>(includeRegexes); List<String> copyExcludeRegex = new ArrayList<>(excludeRegexes); copy.includeRegexes = copyIncludeRegex; copy.excludeRegexes = copyExcludeRegex; return copy; }
Source:
private String getGMTOffsetString(long millis) { long absmillis = (millis < 0) ? -millis : millis; int minutes = (int) ((absmillis / (1000 * 60)) % 60); int hours = (int) ((absmillis / (1000 * 60 * 60)) % 24); START return String.format("(GMT%c%02d:%02d) ", millis >= 0 ? '+' : '-', hours, minutes) END } And I just copy / pasted :innocent:

Target:
private String getGMTOffsetString(long millis) { long absmillis = (millis < 0) ? -millis : millis; int minutes = (int) ((absmillis / (1000 * 60)) % 60); int hours = (int) ((absmillis / (1000 * 60 * 60)) % 24); return String.format("(GMT%c%02d:%02d) ", millis >= 0 ? '+' : '-', hours, minutes); }
Source:
public TasksView(String authority, ContentProviderClient client) { START super(new BaseView<TaskContract.Tasks>(client, TaskContract.Properties.getContentUri(authority))); END } This creates a `Properties` table. Copy'n'paste? ;-)

Target:
public TasksView(String authority, ContentProviderClient client) { super(new BaseView<TaskContract.Tasks>(client, TaskContract.Tasks.getContentUri(authority))); }
Source:
public void testAddingFlag() { START assertTrue(containsFlag( END new Toggled(Notification.DEFAULT_SOUND, true, new NoSignal()).value(), Notification.DEFAULT_SOUND)); assertFalse(containsFlag( new Toggled(Notification.DEFAULT_SOUND, false, new NoSignal()).value(), Notification.DEFAULT_SOUND)); } don't use `containsFlag` here, instead test the expected outcome like so ```java assertThat(new Toggled(Notification.DEFAULT_SOUND, true, new NoSignal()).value(), is(new NoSignal().value() | Notification.DEFAULT_SOUND)); assertThat(new Toggled(Notification.DEFAULT_SOUND, false, new NoSignal()).value(), is(new NoSignal().value())); ```

Target:
public void testAddingFlag() { assertThat(new Toggled(Notification.DEFAULT_SOUND, true, new NoSignal()).value(), is(new NoSignal().value() | Notification.DEFAULT_SOUND)); assertThat(new Toggled(Notification.DEFAULT_SOUND, false, new NoSignal()).value(), is(new NoSignal().value())); }
Source:
protected double convertDuration(double duration) { START return duration / durationFactor; LOG.error("Exception thrown from {}#report. Exception was suppressed.", ScheduledReporter.this.getClass().getSimpleName(), ex); END } Accidental copy & paste error?

Target:
protected double convertDuration(double duration) { return duration / durationFactor; }
Source:
public String getStatementName(StatementContext statementContext) { final String rawSql = statementContext.getRawSql(); START if (rawSql == null || rawSql.length() == 0) { END return "sql.empty"; } return null; } `rawSql.isEmpty()` ?

Target:
public String getStatementName(StatementContext statementContext) { final String rawSql = statementContext.getRawSql(); return rawSql == null || rawSql.isEmpty() ? "sql.empty" : null; }
Source:
private int traverse(Deque<Chunk> traversedChunksDeque) { Chunk currentChunk; activeChunkLock.lock(); try { currentChunk = activeChunk; } finally { activeChunkLock.unlock(); } int valuesSize = 0; while (true) { valuesSize += currentChunk.cursor - currentChunk.startIndex; if (traversedChunksDeque != null) { traversedChunksDeque.addLast(currentChunk); } if (currentChunk.tailChunk == null) { break; } START currentChunk = currentChunk.tailChunk; END } return valuesSize; } Reading mutable fields without synchronization. ```trim``` and ```put``` do mutation of: - cursor - startIndex - tailChunk So result can be totaly wrong, even negative.

Target:
private int traverse(Deque<Chunk> traversedChunksDeque) { Chunk currentChunk = activeChunk; int valuesSize = 0; while (true) { valuesSize += currentChunk.cursor - currentChunk.startIndex; if (traversedChunksDeque != null) { traversedChunksDeque.addLast(currentChunk); } if (currentChunk.tailChunk == null) { break; } currentChunk = currentChunk.tailChunk; } return valuesSize; }
Source:
public void close() throws IOException { datagramChannel.socket().close(); START datagramChannel = null; END } I think it's better to dereference the channel in a finally block in case the socket failed to close.

Target:
public void close() throws IOException { try { datagramChannel.socket().close(); } finally { datagramChannel = null; } }
Source:
START public synchronized static MetricRegistry setDefault(String name) { END if (defaultRegistryName == null) { final MetricRegistry registry = getOrCreate(name); defaultRegistryName = name; return registry; } throw new IllegalStateException("Default metric registry name is already set."); } Should there be another method for instances when you already have the MetricRegistry? I am using Dropwizard where a metrics registry is created by the framework and I would like to make that instance the default. As proposed: ``` java SharedMetricRegistries.add("default", bootstrap.getMetricRegistry()); SharedMetricRegistries.setDefault("default"); ``` With the overloaded setDefault method. ``` java SharedMetricRegistries.setDefault("default", bootstrap.getMetricRegistry()); ```

Target:
public synchronized static MetricRegistry setDefault(String name) { final MetricRegistry registry = getOrCreate(name); return setDefault(name, registry); }
Source:
public void add(Entry entry) { START if (queue.size() >= maxSize) { END queue.poll(); } queue.add(entry); } IMO while would be better here

Target:
public void add(Entry entry) { while (queue.size() >= maxSize) { queue.poll(); } queue.add(entry); }
Source:
protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit) { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet())); START this(registry, name, filter, rateUnit, durationUnit, executor); END } Build fails with `ScheduledReporter.java:[72,21] call to this must be first statement in constructor`, this should fix it: ``` java this(registry, name, filter, rateUnit, durationUnit, Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet()))); ```

Target:
protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit) { this(registry, name, filter, rateUnit, durationUnit, Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet()))); }
Source:
private <T> Collection<? extends Callable<T>> instrument(Collection<? extends Callable<T>> tasks) { START List<InstrumentedCallable<T>> instrumented = new ArrayList<InstrumentedCallable<T>>(); END for (Callable<T> task : tasks) { instrumented.add(new InstrumentedCallable(task)); } return instrumented; } Make this `final` and since we know how many tasks we're dealing with, make sure we're creating a list with the right capacity.

Target:
private <T> Collection<? extends Callable<T>> instrument(Collection<? extends Callable<T>> tasks) { final List<InstrumentedCallable<T>> instrumented = new ArrayList<InstrumentedCallable<T>>(tasks.size()); for (Callable<T> task : tasks) { instrumented.add(new InstrumentedCallable(task)); } return instrumented; }
Source:
public void run() { running.inc(); START Timer.Context context = duration.time(); END try { task.run(); } finally { context.stop(); running.dec(); completed.mark(); } } Make this final.

Target:
public void run() { running.inc(); final Timer.Context context = duration.time(); try { task.run(); } finally { context.stop(); running.dec(); completed.mark(); } }
Source:
public T call() throws Exception { running.inc(); START Timer.Context context = duration.time(); END try { return callable.call(); } finally { context.stop(); running.dec(); completed.mark(); } } Make this final.

Target:
public T call() throws Exception { running.inc(); final Timer.Context context = duration.time(); try { return callable.call(); } finally { context.stop(); running.dec(); completed.mark(); } }
Source:
public InstrumentedHandler(MetricRegistry registry, Handler underlying) { START this(registry, underlying, underlying.getClass().getName()); END } This should be `name(underlying.getClass())`.

Target:
public InstrumentedHandler(MetricRegistry registry, Handler underlying) { this(registry, underlying, name(underlying.getClass())); }
Source:
public static OsAppCredentials anonymous() { START return new OsAppCredentials(nativeCreate(TYPE_ANONYMOUS), Credentials.IdentityProvider.ANONYMOUS); END } I think it would be cleaner if `Credentials.IdentityProvider.ANONYMOUS` was defined in the factory constructor of `AppCredentials`. `OsAppCredentials` is there to map to the underlying type, but us making a shortcut is not the responsibility of the Os class but our own `AppCredentials`. The same everywhere else.

Target:
public static OsAppCredentials anonymous() { return new OsAppCredentials(nativeCreate(TYPE_ANONYMOUS)); }
Source:
START public void setVersion(long version) { END OsObjectStore.setSchemaVersion(sharedRealm, version); } Having this public feels problematic. What classes need to call this that don't live in `io.realm` ?

Target:
void setVersion(long version) { OsObjectStore.setSchemaVersion(sharedRealm, version); }
Source:
START public Task<MongoCursor<ResultT>> iterator() { END return dispatcher.dispatchTask(() -> new MongoCursor<>(getCollection().iterator(), dispatcher) ); } Is it intended that calling this multiple times should trigger multiple remote operations? Maybe I am still a bit confused with the various _collection/iterable_ terms.

Target:
public Task<MongoCursor<ResultT>> iterator() { return dispatcher.dispatchTask(() -> new MongoCursor<>(getCollection().iterator()) ); }
Source:
public void setUp() { app = new TestRealmApp(); START RealmUser user = SyncTestUtils.Companion.createTestUser(app); END config = configFactory.createSyncConfigurationBuilder(user).build(); } You can annotate `createTestUser` with `@JvmStatic` and call it as a static method ```Kotlin RealmUser user = SyncTestUtils.createTestUser(app); ```

Target:
public void setUp() { app = new TestRealmApp(); RealmUser user = SyncTestUtils.createTestUser(app); config = configFactory.createSyncConfigurationBuilder(user).build(); }
Source:
public void queryFrozenRealmAcrossThreads() throws InterruptedException { final Realm frozenRealm = createDataForFrozenRealm(DATA_SIZE); Thread t = new Thread(() -> { RealmResults<AllTypes> results = frozenRealm.where(AllTypes.class).findAll(); assertEquals(DATA_SIZE, results.size()); }); t.start(); t.join(); START frozenRealm.close(); END } you're already closing it in the `tearDown`

Target:
public void queryFrozenRealmAcrossThreads() throws InterruptedException { final Realm frozenRealm = createDataForFrozenRealm(DATA_SIZE); Thread t = new Thread(() -> { RealmResults<AllTypes> results = frozenRealm.where(AllTypes.class).findAll(); assertEquals(DATA_SIZE, results.size()); }); t.start(); t.join(); }
Source:
START public void addReference(NativeObject referent) { END new NativeObjectReference(this, referent, referenceQueue); } why public?

Target:
void addReference(NativeObject referent) { new NativeObjectReference(this, referent, referenceQueue); }
Source:
START public long getTablePtr() { END return table.getNativePtr(); } why public? you can still call it from JNI even if it's private

Target:
private long getTablePtr() { return table.getNativePtr(); }
Source:
public int getCount() { START return cities == null ? 0 : cities.size(); END } This can never be null given the code in `setData` above?

Target:
public int getCount() { return cities.size(); }
Source:
private void setupViews() { backgroundJobStartStop = findViewById(R.id.backgroundJobStartStop); backgroundJobStartStop.setOnClickListener(new View.OnClickListener() { @Override START public void onClick(View v) { END if (!backgroundTask.isStarted()) { backgroundTask.start(); } else { backgroundTask.stop(); } updateJobButton(); } }); } We support Java 8 in the examples, so feel free to use lamdas.

Target:
private void setupViews() { backgroundJobStartStop = findViewById(R.id.backgroundJobStartStop); backgroundJobStartStop.setOnClickListener(v -> { if (!backgroundTask.isStarted()) { backgroundTask.start(); } else { backgroundTask.stop(); } updateJobButton(); }); }
Source:
private static X509Certificate buildCertificateFromPEM(String pem) throws IOException, CertificateException { InputStream stream = new ByteArrayInputStream(pem.getBytes("UTF-8")); X509Certificate x509Certificate = (X509Certificate) CERTIFICATE_FACTORY.generateCertificate(stream); START stream.close(); END return x509Certificate; } This will not be closed if CertificateException is thrown?

Target:
private static X509Certificate buildCertificateFromPEM(String pem) throws IOException, CertificateException { InputStream stream = null; try { stream = new ByteArrayInputStream(pem.getBytes("UTF-8")); return (X509Certificate) CERTIFICATE_FACTORY.generateCertificate(stream); } finally { if (stream != null) { stream.close(); } } }
Source:
public String getDisplayFileName() { if (displayName == null) { if(name != null) { if (version != null) { return name + ":" + version; } else { return name; } } else { return this.fileName; START } END } return this.displayName; } Minor suggestion/subjective: could get rid of the nesting here using something like: ```java if (displayName != null) { return displayName; } if (name == null) { return fileName; } if (version == null) { return name; } return name + ":" + version; ```

Target:
public String getDisplayFileName() { if (displayName != null) { return displayName; } if (name == null) { return fileName; } if (version == null) { return name; } return name + ":" + version; }
Source:
private static boolean isPositiveInteger(final String str) { if (str == null || str.isEmpty()) { return false; } // numbers/versions with leading zeros should not be treated as numbers // (e.g. when comparing "01" <-> "1") START if (str.charAt(0) == '0') { END return false; } for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; } This would treat '0' as a string. We need to add a `&& str.length() > 1`

Target:
static boolean isPositiveInteger(final String str) { if (str == null || str.isEmpty()) { return false; } // numbers with leading zeros should not be treated as numbers // (e.g. when comparing "01" <-> "1") if (str.charAt(0) == '0' && str.length() > 1) { return false; } for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; }
Source:
public Object getTransactionId() { START return tx != null ? tx.getId() : null; END } Transaction is mandatory. What kind of error we show in case a transaction is not present? If it's not clear enough we can improve it. Anyway, this would be a separate issue

Target:
public Object getTransactionId() { return tx.getId(); }
Source:
private void lookupDatabase() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", config.getNativeClientResource() ); mongoDb = (MongoDatabase) jndiService.locate( config.getNativeClientResource() ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( config.getNativeClientResource() ); } // clear resources START this.jndiService = null; END } Not critical but I find it counter intuitive that the lookup method also does the clear, can we move it at the end of the start method?

Target:
private void lookupDatabase() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", config.getNativeClientResource() ); mongoDb = (MongoDatabase) jndiService.locate( config.getNativeClientResource() ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( config.getNativeClientResource() ); } }
Source:
private void lookupClient() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", configuration.getNativeClientResource() ); Driver driver = (Driver) jndiService.locate( configuration.getNativeClientResource() ); this.client = new BoltNeo4jClient( driver ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( configuration.getNativeClientResource() ); } // clear resources START this.jndiService = null; END } Not critical but I find it counter intuitive that the lookup method also does the clear, can we move it at the end of the start method?

Target:
private void lookupClient() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", configuration.getNativeClientResource() ); Driver driver = (Driver) jndiService.locate( configuration.getNativeClientResource() ); this.client = new BoltNeo4jClient( driver ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( configuration.getNativeClientResource() ); } }
Source:
public void before() throws Exception { // Synchronize on the static field to defend against concurrent launches, // e.g. the usage as JUnit Rule concurrently with the usage as global test listener in Surefire. synchronized ( running ) { if ( running.compareAndSet( false, true ) ) { START RemoteHotRodServerHelper.beforeRun(); END StandaloneCommandBuilder builder = StandaloneCommandBuilder .of( "target/infinispan-server" ); builder .setServerReadOnlyConfiguration( DEFAULT_CONFIG_PATH ); if ( portOffset != 0 ) { builder.addJavaOption( "-Djboss.socket.binding.port-offset=" + portOffset ); } Launcher launcher = Launcher.of( builder ); hotRodServer = launcher.inherit().launch(); waitForRunning(); } } } this class is also used in integration tests module, where the server is in a different file system position

Target:
public void before() throws Exception { // Synchronize on the static field to defend against concurrent launches, // e.g. the usage as JUnit Rule concurrently with the usage as global test listener in Surefire. synchronized ( running ) { if ( running.compareAndSet( false, true ) ) { StandaloneCommandBuilder builder = StandaloneCommandBuilder .of( "target/infinispan-server" ); builder .setServerReadOnlyConfiguration( DEFAULT_CONFIG_PATH ); if ( portOffset != 0 ) { builder.addJavaOption( "-Djboss.socket.binding.port-offset=" + portOffset ); } Launcher launcher = Launcher.of( builder ); //This will launch the server w/o redirecting stdin and stdout, as that would corrupt Surefire's own streams when running via Maven. //Might want to use launcher.inherit().launch instead if you need to debug server bootstrap. hotRodServer = launcher.launch(); waitForRunning(); } } }
Source:
public void tearDown() { try { if ( !em.getTransaction().isActive() ) { em.getTransaction().begin(); START } END Family found = em.find( Family.class, family.getName() ); if ( found != null ) { em.remove( found ); } em.getTransaction().commit(); } finally { em.close(); } } Wondering if we should fix that or the test itself as it's not a good example of how things should be done. But maybe we have all our tests like that and it's not worth fixing.

Target:
public void tearDown() { try { em.getTransaction().begin(); Family found = em.find( Family.class, family.getName() ); if ( found != null ) { em.remove( found ); } em.getTransaction().commit(); } finally { em.close(); } }
Source:
private void initEnumValues() { if ( enumValues == null ) { Class<Enum<?>> returnedClass = coreEnumType.returnedClass(); START this.enumValues = returnedClass.getEnumConstants(); END if ( enumValues == null ) { throw new NullPointerException( "Failed to init enumValues" ); } } } I can't see a difference between the 2 codes. But either is OK to me.

Target:
private void initEnumValues() { if ( enumValues == null ) { Class<? extends Enum<?>> returnedClass = coreEnumType.returnedClass(); this.enumValues = returnedClass.getEnumConstants(); if ( enumValues == null ) { throw new NullPointerException( "Failed to init enumValues" ); } } }
Source:
public List getResultList() { START log.info( "I am called!" ); END if ( isResultSet() ) { return resultList; } return null; } Remember to remove this

Target:
public List getResultList() { if ( isResultSet() ) { return resultList; } return null; }
Source:
public Rule Reserved() { START return FirstOf( Aggregate(), Find(), FindOne(), FindAndModify(), Insert(), Remove(), Update(), Count() ); END // TODO There are many more query types than what we support. } Let's add it at the end instead of at the beginning. It's less common than the other operations.

Target:
public Rule Reserved() { return FirstOf( Find(), FindOne(), FindAndModify(), Insert(), Remove(), Update(), Count(), Aggregate() ); // TODO There are many more query types than what we support. }
Source:
public UniqueConstraintDetails(Label label, String property) { START super(); END this.label = label; this.property = property; } Maybe remove the useless `super()`?

Target:
public UniqueConstraintDetails(Label label, String property) { this.label = label; this.property = property; }
Source:
private Object readProperty(Node otherNode, String targetColumnName) { Object value = null; START otherNode.getAllProperties(); END if ( otherNode.hasProperty( targetColumnName ) ) { value = otherNode.getProperty( targetColumnName ); } return value; } The returned value is not used.

Target:
private Object readProperty(Node otherNode, String targetColumnName) { Object value = null; if ( otherNode.hasProperty( targetColumnName ) ) { value = otherNode.getProperty( targetColumnName ); } return value; }
Source:
public void testSlice() { START System.out.println( "slice" ); END String[] strings = new String[]{ "1", "2", "3" }; int begin = 0; int length = 2; String[] expResult = new String[]{ "1", "2" }; String[] result = ArrayHelper.slice( strings, begin, length ); assertArrayEquals( expResult, result ); } Can you remove the System.out.? They are unecessary

Target:
public void testSlice() { String[] strings = new String[]{ "1", "2", "3" }; int begin = 0; int length = 2; String[] expResult = new String[]{ "1", "2" }; String[] result = ArrayHelper.slice( strings, begin, length ); assertArrayEquals( expResult, result ); }
Source:
public Rule Reserved() { return FirstOf( START Sequence( Find(), builder.setOperation( Operation.FIND ) ), END Sequence( Count(), builder.setOperation( Operation.COUNT ) ) ); //TODO there is many more than `find` an `count` but as this time we only support `find` and `count` } `builder.setOperation()` is already invoked by `Operation()`. I don't think we need to do it here, too?

Target:
public Rule Reserved() { return FirstOf( Find(), Count() ); //TODO there is many more than `find` an `count` but as this time we only support `find` and `count` }
Source:
public void storeAssociation(EntityKey key, Association document) { byte[] associationId = associationId( key ); connection.del( associationId ); for ( Object row : document.getRows() ) { START connection.rpush( associationId, serializationStrategy.serialize( row ) ); END } } So this does not use JSON? Or am I missing something. Also I think it'd make sense to use the "transaction" semantics to write all rows of one association in one go?

Target:
private void storeAssociation(EntityKey key, Association document) { byte[] associationId = associationId( key ); connection.del( associationId ); for ( Object row : document.getRows() ) { connection.rpush( associationId, serializationStrategy.serialize( row ) ); } }