auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void startRuntime() { String tempDir = AppConstants.getInstance().getString("log.dir", null); START v8 = V8.createV8Runtime("J2V8Javascript", tempDir); END } Setting the alias and temp directory can be quite important. Perhaps make this an optional argument? So you can overwrite the alias when needed (i.e. to improve performance). Right now all instances will be cached under the same name.

Target:
public void startRuntime() { v8 = V8.createV8Runtime(); }
Source:
public GWCConfig getConfig() { START if (gsEnvironment != null && gsEnvironment.isStale()) { END syncEnvironment(); } return gwcConfigPersister.getConfig(); } This bloc of code is repeated many times, should be centralized in a single method.

Target:
public GWCConfig getConfig() { return gwcConfigPersister.getConfig(); }
Source:
private BlackboardArtifact createDownloadArtifact(AbstractFile zoneFile, ZoneIdentifierInfo zoneInfo) { Collection<BlackboardAttribute> bbattributes = createDownloadAttributes( null, null, zoneInfo.getURL(), null, START (zoneInfo.getURL() != null ? NetworkUtils.extractDomain(zoneInfo.getURL()) : ""), END null); return addArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_DOWNLOAD, zoneFile, bbattributes); } again, maybe StringUtils.defaultString()

Target:
private BlackboardArtifact createDownloadArtifact(AbstractFile zoneFile, ZoneIdentifierInfo zoneInfo) { Collection<BlackboardAttribute> bbattributes = createDownloadAttributes( null, null, zoneInfo.getURL(), null, (zoneInfo.getURL() != null ? NetworkUtils.extractDomain(zoneInfo.getURL()) : ""), null); return addArtifact(TSK_WEB_DOWNLOAD, zoneFile, bbattributes); }
Source:
public IncrementalScoreDirector(IncrementalScoreDirectorFactory scoreDirectorFactory, boolean constraintMatchEnabledPreference, IncrementalScoreCalculator<Solution_> incrementalScoreCalculator) { super(scoreDirectorFactory, constraintMatchEnabledPreference); if (constraintMatchEnabledPreference && !(incrementalScoreCalculator instanceof ConstraintMatchAwareIncrementalScoreCalculator)) { throw new IllegalStateException("The score calculator " + incrementalScoreCalculator + " must implement " + ConstraintMatchAwareIncrementalScoreCalculator.class.getSimpleName() + " when constraintMatchEnabledPreference is true."); START } END this.incrementalScoreCalculator = incrementalScoreCalculator; } I fear we won't be able to add this fail fast (although I always like any proposal to add more fail fasts :)). The other fail fasts added in the PR are fine.

Target:
public IncrementalScoreDirector(IncrementalScoreDirectorFactory scoreDirectorFactory, boolean constraintMatchEnabledPreference, IncrementalScoreCalculator<Solution_> incrementalScoreCalculator) { super(scoreDirectorFactory, constraintMatchEnabledPreference); this.incrementalScoreCalculator = incrementalScoreCalculator; }
Source:
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); START return; END } } no need for the return statement.

Target:
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); } }
Source:
protected void before() throws Throwable { START if (session == null) { END throw new IllegalStateException("Session was not initialized"); } session.execute(String.format("CREATE KEYSPACE %s WITH durable_writes = false AND " + "replication = {'class': 'SimpleStrategy', 'replication_factor' : 1};", keyspaceName)); session.execute(String.format("USE %s;", keyspaceName)); } Change to `Assert.state(session != null, "Session was not initialized");`

Target:
protected void before() throws Throwable { Assert.state(session != null, "Session was not initialized"); session.execute(String.format("CREATE KEYSPACE %s WITH durable_writes = false AND " + "replication = {'class': 'SimpleStrategy', 'replication_factor' : 1};", keyspaceName)); session.execute(String.format("USE %s;", keyspaceName)); }
Source:
private void lockImageInDb() { final DiskImage diskImage = getDiskImage(); TransactionSupport.executeInNewTransaction(() -> { getCompensationContext().snapshotEntityStatus(diskImage.getImage()); START diskImage.setImageStatus(ImageStatus.LOCKED); END ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.LOCKED); getCompensationContext().stateChanged(); return null; }); } Not needed, the next statement handles it in the DB, do we really care if we have the status changed in the instance?

Target:
private void lockImageInDb() { final DiskImage diskImage = getDiskImage(); TransactionSupport.executeInNewTransaction(() -> { getCompensationContext().snapshotEntityStatus(diskImage.getImage()); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.LOCKED); getCompensationContext().stateChanged(); return null; }); }
Source:
public synchronized void close() { try { Closer closer = Closer.create(); if (mJournalOutputStream != null) { closer.register(mJournalOutputStream); } closer.register(mGarbageCollector); closer.close(); } catch (IOException e) { START LOG.warn("Failed to close UfsJournalLogWriter with error: {}.", e.getMessage()); END } mClosed = true; } What's the motivation for swallowing this exception, and is it really only a warning? Also, could we use `closeQuietly` (or an improved version if we want the logging)?

Target:
public synchronized void close() throws IOException { Closer closer = Closer.create(); if (mJournalOutputStream != null) { closer.register(mJournalOutputStream); } closer.register(mGarbageCollector); closer.close(); mClosed = true; }
Source:
public void testFooPing() { // change logging level, does NOT work START Logger logger = Logger.getLogger(JMXMethodExecutor.class.getName()); END Level originalLevel = logger.getLevel(); logger.setLevel(Level.OFF); // Initialize weld, Foo bean is used in observer new Weld().initialize(); logger.setLevel(originalLevel); } The logging actually happens on the "client" side. So we'll need to setup the log level there, maybe using `@BeforeClass` and `@AfterClass`? I tried to move this code to the `AbstractShutdownHookTest.deploy()` method and it seemed to work.

Target:
public void testFooPing() { // Initialize weld, Foo bean is used in observer new Weld().initialize(); }
Source:
public void searchForProcesses() throws Exception { desktopPage.searchInSearchField("process"); int numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("proc"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("möhö"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be no process found",0,numberOfResults); START END } One empty line too much.

Target:
public void searchForProcesses() throws Exception { desktopPage.searchInSearchField("process"); int numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("proc"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); //TODO: selenium is too fast here and counts results from previous search searchResultPage.searchInSearchField("möhö"); numberOfResults = searchResultPage.getNumberOfResults(); //assertEquals("There should be no process found",0,numberOfResults); }
Source:
public AS7ManagementDetails(IServer server) { START this(server, new HashMap<String,Object>()); END } new HashMap<String,Object>(0) or Collections.<String, Object>emptyMap() if immutable

Target:
public AS7ManagementDetails(IServer server) { this(server, new HashMap<String,Object>(0)); }
Source:
public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { final CommandResult<RuleViolation> results = allow(context); if (!results.getType().equals(CommandResult.Type.ERROR)) { START final org.kie.workbench.common.stunner.core.graph.Graph graph = getGraph(context); END graph.addNode(candidate); getMutableIndex(context).addNode(candidate); } return results; } Do we need FQCN?

Target:
public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { final CommandResult<RuleViolation> results = allow(context); if (!results.getType().equals(CommandResult.Type.ERROR)) { final Graph graph = getGraph(context); graph.addNode(candidate); getMutableIndex(context).addNode(candidate); } return results; }
Source:
START private static void dataTableHeaderMayOnlyContainVariableNames(ASTNode stat) throws InvalidSpecCompileException { END throw new InvalidSpecCompileException(stat, "Header of data table may only contain variable names"); } might be better to return the exception so that you can directly see that it exits in the code `throw dataTableHeaderMayOnlyContainVariableNames(column.get(0));`

Target:
private static InvalidSpecCompileException dataTableHeaderMayOnlyContainVariableNames(ASTNode stat) { return new InvalidSpecCompileException(stat, "Header of data table may only contain variable names"); }
Source:
public static <T> MutableMessageBuilder<T> fromMessage(Message<T> message) { Assert.notNull(message, "message must not be null"); if (message instanceof CloneableMessage) { logger.warn("For CloneableMessages consider to use regular MessageBuilder. " + "Otherwise custom Message context may be lost."); START } END return new MutableMessageBuilder<T>(message); } If we move the logic to the builder factories, this would not be needed.

Target:
public static <T> MutableMessageBuilder<T> fromMessage(Message<T> message) { Assert.notNull(message, "message must not be null"); return new MutableMessageBuilder<T>(message); }
Source:
public Image getColumnImage(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return getIncomingChangesImage(); case 1: try { START return getReviewStateImage(Integer.parseInt(reviewContainer.getCr())); END } catch (Exception e) { break; } case 2: try { return getVerifiedStateImage(Integer.parseInt(reviewContainer.getV())); } catch (Exception e) { break; } } return null; } This implies you're expecting that "Code Review" and "Verified" below to always be integers (otherwise, you break silently so you must be.) I think this seems to have an underlying implication that the data type for both getters really should be "Integer". You can always convert an integer to a string safely but this isn't true for parsing some arbitrary string IMO. Thoughts?

Target:
public Image getColumnImage(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return getIncomingChangesImage(); case 1: return getReviewStateImage(reviewContainer.getCr()); case 2: return getVerifiedStateImage(reviewContainer.getV()); } return null; }
Source:
START WorkerErrantRecordReporter workerErrantRecordReporter() { END return workerErrantRecordReporter; } let's add `protected` here to be symmetric to what other fields that are accessed by the context have as scope

Target:
protected WorkerErrantRecordReporter workerErrantRecordReporter() { return workerErrantRecordReporter; }
Source:
public static VmInterfaceType getDefaultNicType(Collection<VmInterfaceType> items) { START return items.contains(VmInterfaceType.pv) ? VmInterfaceType.pv : items.iterator().next(); END } According to logic in BaseEditVmInterfaceModel: nicTypes = nicTypes == null ? new ArrayList<VmInterfaceType>() : nicTypes; the items are expected to be an empty ArrayList. In that case the items.iterator().next() would fail on NoSuchElementException.

Target:
public static VmInterfaceType getDefaultNicType(Collection<VmInterfaceType> items) { if (items == null || items.isEmpty()) { return null; } else if (items.contains(VmInterfaceType.pv)) { return VmInterfaceType.pv; } else { return items.iterator().next(); } }
Source:
public CompletionStage<Void> removeRecoveryInformationFromCluster(Collection<Address> where, long internalId) { if (rpcManager != null) { TxCompletionNotificationCommand ftc = commandFactory.buildTxCompletionNotificationCommand(internalId); CompletionStage<Void> stage = sendTxCompletionNotification(where, ftc); START return stage.thenRun(() -> removeRecoveryInformation(internalId)); END } else { removeRecoveryInformation(internalId); return CompletableFutures.completedNull(); } } Don't need to wait for the tx completion responses before removing the local info here either, although since removing the local info is expensive you could still send the command first.

Target:
public CompletionStage<Void> removeRecoveryInformationFromCluster(Collection<Address> where, long internalId) { if (rpcManager != null) { TxCompletionNotificationCommand ftc = commandFactory.buildTxCompletionNotificationCommand(internalId); CompletionStage<Void> stage = sendTxCompletionNotification(where, ftc); removeRecoveryInformation(internalId); return stage; } else { removeRecoveryInformation(internalId); return CompletableFutures.completedNull(); } }
Source:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() >= 1) { throw new IAE("Function[%s] needs 0 argument", name()); } START return ExprEval.of(Math.PI); END } Could be extracted to a `private static final` constant.

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() >= 1) { throw new IAE("Function[%s] needs 0 argument", name()); } return ExprEval.of(PI); }
Source:
public static List<CPListElement> getExistingEntries(IJavaProject project) throws JavaModelException { ArrayList<CPListElement> newClassPath= new ArrayList<>(); for (IClasspathEntry START curr : END project.getRawClasspath()) { newClassPath.add(CPListElement.createFromExisting(curr, project)); } return newClassPath; } rename to entry

Target:
public static List<CPListElement> getExistingEntries(IJavaProject project) throws JavaModelException { ArrayList<CPListElement> newClassPath= new ArrayList<>(); for (IClasspathEntry entry : project.getRawClasspath()) { newClassPath.add(CPListElement.createFromExisting(entry, project)); } return newClassPath; }
Source:
public final List<A> minus(final Equal<A> eq, final List<A> xs) { return this.removeAll(compose(Monoid.disjunctionMonoid.sumLeft(), xs.mapM(Function.<A, A, Boolean>curry(eq.eq())))); START } END Hmm, I am suprised this is the case. I am using Intellij 14.0.2. Yourself?

Target:
public final List<A> minus(final Equal<A> eq, final List<A> xs) { return removeAll(compose(Monoid.disjunctionMonoid.sumLeft(), xs.mapM(curry(eq.eq())))); }
Source:
public Builder withDefaultHint(QueryEvaluationHint engineDefaultHints) { this.engineDefaultHints = engineDefaultHints; START this.defaultBackendFactory = engineDefaultHints.getQueryBackendFactory(); END return this; } This is not a good way to set up things. If both defaultHint and defaultBackend is set, the end result depends on the order... Either some checking (and possibly logging) is required here, or we should define a clear priority between the settings, and the build method should ensure that.

Target:
public Builder withDefaultHint(QueryEvaluationHint engineDefaultHints) { this.engineDefaultHints = engineDefaultHints; return this; }
Source:
public Integer getIdle() { HikariPool pool = getHikariPool(); if (Objects.nonNull(pool)) { return pool.getIdleConnections(); } START return super.getIdle(); END } I don't think calling super is what I'd do here

Target:
public Integer getIdle() { HikariPool pool = getHikariPool(); if (Objects.nonNull(pool)) { return pool.getIdleConnections(); } return null; }
Source:
ElasticsearchTableDescriptionProvider(ElasticsearchConnectorConfig config, JsonCodec<ElasticsearchTableDescription> codec) { requireNonNull(config, "config is null"); requireNonNull(codec, "codec is null"); START checkArgument(config.getScrollTimeout().toMillis() >= 10, "scrollTimeout must be at least 10 ms"); END checkArgument(config.getRequestTimeout().toMillis() >= 10, "requestTimeout must be at least 10 ms"); tableDefinitions = createTableDescriptions(config, codec); } Let's remove these `checkArgument`s as these are not critical checks & we will probably forget to remove these when `MinDuration` gets fixed.

Target:
ElasticsearchTableDescriptionProvider(ElasticsearchConnectorConfig config, JsonCodec<ElasticsearchTableDescription> codec) { requireNonNull(config, "config is null"); requireNonNull(codec, "codec is null"); tableDefinitions = createTableDescriptions(config, codec); }
Source:
public void dispose() { START if (fRegisterInProvider) { unregisterActions(); } END fSelectionProvider = null; fFindDeclarationsAction = null; fFindDeclarationsInProjectAction = null; fFindDeclarationsInHierarchyAction = null; fFindDeclarationsInWorkingSetAction = null; updateGlobalActionHandlers(); super.dispose(); } What if fSelectionProvider is null? NPE will be thrown.

Target:
public void dispose() { unregisterActions(); fSelectionProvider = null; fFindDeclarationsAction = null; fFindDeclarationsInProjectAction = null; fFindDeclarationsInHierarchyAction = null; fFindDeclarationsInWorkingSetAction = null; updateGlobalActionHandlers(); super.dispose(); }
Source:
public void addError(Throwable error) { if (error == null) { throw new NullPointerException("Error cannot be null"); } if (error instanceof AssumptionViolatedException) { AssertionError e = new AssertionError(error.getMessage()); e.initCause(error); START error = e; END } errors.add(error); } Minor thing: I'm generally not happy with reassigning method parameters.

Target:
public void addError(Throwable error) { if (error == null) { throw new NullPointerException("Error cannot be null"); } if (error instanceof AssumptionViolatedException) { AssertionError e = new AssertionError(error.getMessage()); e.initCause(error); errors.add(e); } else { errors.add(error); } }
Source:
protected void handleIdle() { START if (streams.isEmpty()) { END return; } super.handleIdle(); } Shouldn't the test be synchronized as in `Http1xClientConnection.java`?

Target:
protected void handleIdle() { synchronized (this) { if (streams.isEmpty()) { return; } } super.handleIdle(); }
Source:
public String get(String key) { START Map<String, String> Map = inheritableThreadLocal.get(); END if ((Map != null) && (key != null)) { return Map.get(key); } else { return null; } } I know this was pre-existing, but the variable is capitalized Map, but should be just map.

Target:
public String get(String key) { Map<String, String> map = inheritableThreadLocal.get(); if ((map != null) && (key != null)) { return map.get(key); } else { return null; } }
Source:
public void containsConversion(Class<?> from, Class<?> to) { isNotNull(); boolean foundMatchingConversion = false; for ( GroupConversionDescriptor groupConversionDescriptor : actual ) { if ( groupConversionDescriptor.getFrom().equals( from ) && groupConversionDescriptor.getTo().equals( to ) ) { foundMatchingConversion = true; break; } } if ( !foundMatchingConversion ) { START fail( String.format( Locale.getDefault(), "<%s> does not contain a conversion from <%s> to <%s>.", actual, from, to ) ); END } } @marko-bekhta Is this still a left-over? I.e. are you planning to revert this change as per our discussion above? Same question for some more places where `Locale.getDefault()` is used now.

Target:
public void containsConversion(Class<?> from, Class<?> to) { isNotNull(); boolean foundMatchingConversion = false; for ( GroupConversionDescriptor groupConversionDescriptor : actual ) { if ( groupConversionDescriptor.getFrom().equals( from ) && groupConversionDescriptor.getTo().equals( to ) ) { foundMatchingConversion = true; break; } } if ( !foundMatchingConversion ) { fail( String.format( "<%s> does not contain a conversion from <%s> to <%s>.", actual, from, to ) ); } }
Source:
public synchronized void setTailSegment(long tailSegment) { dataStore.put(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT, tailSegment); // Set the epoch in the router as well. //TODO need to figure out if we can remove this redundancy START serverRouter.setServerEpoch(tailSegment); END } Copy paste error ?

Target:
public void setTailSegment(long tailSegment) { dataStore.put(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT, tailSegment); }
Source:
public void sleep(IInteger seconds) { try { START Thread.sleep(TimeUnit.SECONDS.toMillis(seconds.longValue())); END } catch (InterruptedException e) { } } FYI, `TimeUnit.SECONDS.sleep(seconds.longValue())`

Target:
public void sleep(IInteger seconds) { try { TimeUnit.SECONDS.sleep(seconds.longValue()); } catch (InterruptedException e) { } }
Source:
public void release() { START JdbcConnectionAccess connectionAccess = jdbcContext.getJdbcConnectionAccess(); END if( !( connectionAccess instanceof JdbcConnectionAccessProvidedConnectionImpl ) ) { throw new IllegalStateException( "DdlTransactionIsolatorProvidedConnectionImpl should always use a JdbcConnectionAccessProvidedConnectionImpl" ); } JdbcConnectionAccessProvidedConnectionImpl connectionAccessProvidedConnection = (JdbcConnectionAccessProvidedConnectionImpl) connectionAccess; try { connectionAccess.releaseConnection( null ); } catch (SQLException ignore) { LOG.unableToReleaseIsolatedConnection( ignore ); } } I see that `connectionAccessProvidedConnection` isn't used. Is the check on `connectionAccess` and the cast there just to make sure that the connection was provided?

Target:
public void release() { JdbcConnectionAccess connectionAccess = jdbcContext.getJdbcConnectionAccess(); if( !( connectionAccess instanceof JdbcConnectionAccessProvidedConnectionImpl ) ) { throw new IllegalStateException( "DdlTransactionIsolatorProvidedConnectionImpl should always use a JdbcConnectionAccessProvidedConnectionImpl" ); } try { // While passing the connection to the releaseConnection method might be suitable for other `JdbcConnectionAccess` implementations, // it has no meaning for JdbcConnectionAccessProvidedConnectionImpl because, in this case, the connection is wrapped // and we don't have access to it upon releasing via the DdlTransactionIsolatorProvidedConnectionImpl. connectionAccess.releaseConnection( null ); } catch (SQLException ignore) { LOG.unableToReleaseIsolatedConnection( ignore ); } }
Source:
public boolean isRead(Tip tip) { START return fReadList.contains(new Integer(tip.hashCode())); END } Integer.valueOf(...) instead.

Target:
public boolean isRead(Tip tip) { return fReadList.contains(Integer.valueOf(tip.hashCode())); }
Source:
public IContentProvider getContentProvider() { START if (useDynamic) END return dynamicProvider; return super.getContentProvider(); } Please use brackets, even for one-line blocks

Target:
public IContentProvider getContentProvider() { if (useDynamic) { return dynamicProvider; } return super.getContentProvider(); }
Source:
public BlobStore getById(Function<String, InputStream> configGetter, String storeId) { logger.debug("Looking blob store with id {}", storeId); try { HierarchicalConfiguration config = getConfiguration(configGetter); if (config != null) { return findStore(config, store -> StringUtils.equals(storeId, store.getString(CONFIG_KEY_ID))); } } catch (ConfigurationException e) { START logger.error("Error reading blob store configuration", e); END } return null; } Why are we swallowing the exception? Isn't this something the caller should know?

Target:
public BlobStore getById(Function<String, InputStream> configGetter, String storeId) throws ConfigurationException, IOException { logger.debug("Looking blob store with id {}", storeId); HierarchicalConfiguration config = getConfiguration(configGetter); if (config != null) { return findStore(config, store -> StringUtils.equals(storeId, store.getString(CONFIG_KEY_ID))); } return null; }
Source:
public void disconnect() { // Set the terminal control state to CLOSED. START fControl.setState(TerminalState.CLOSED); END } Add a null check, as the class may not be initialized just yet.

Target:
public void disconnect() { // Set the terminal control state to CLOSED. if (fControl != null) { fControl.setState(TerminalState.CLOSED); } }
Source:
public SymmetricHashJoin construct(final ConstructArgs args) { SymmetricHashJoin join = new SymmetricHashJoin( null, null, argColumns1, argColumns2, argSelect1, argSelect2, argSetSemanticsLeft, argSetSemanticsRight, argColumnNames); START join.setPullOrder(argOrder); END return join; } If this setter is only called here then it should be moved into the constructor.

Target:
public SymmetricHashJoin construct(final ConstructArgs args) { return new SymmetricHashJoin( null, null, argColumns1, argColumns2, argSelect1, argSelect2, argSetSemanticsLeft, argSetSemanticsRight, argColumnNames, argOrder); }
Source:
public String toString() { START return "VM [" + vmStatic.getvm_name() + "]"; END } you can use getName() instead of vmStatic.getvm_name()

Target:
public String toString() { return "VM [" + getName() + "]"; }
Source:
START DropDownMenu updateContextMenu(DropDownMenu menuBar, List<ActionButtonDefinition<T>> actions) { END return updateContextMenu(menuBar, actions, true); } public, protected, private?

Target:
private DropDownMenu updateContextMenu(DropDownMenu menuBar, List<ActionButtonDefinition<T>> actions) { return updateContextMenu(menuBar, actions, true); }
Source:
private static synchronized Session session() { final Properties properties = new Properties(); START final ConfigurationProperties conf = EmailDispatchConfiguration.getConfiguration(); END properties.put("mail.smtp.host", conf.mailSmtpHost()); properties.put("mail.smtp.name", conf.mailSmtpName()); properties.put("mail.smtp.port", conf.mailSmtpPort()); properties.put("mailSender.max.recipients", conf.mailSenderMaxRecipients()); SESSION = Session.getDefaultInstance(properties, null); return SESSION; } Don't spam final keywords in code that is not part of your changeset

Target:
private static synchronized Session session() { final Properties properties = new Properties(); ConfigurationProperties conf = EmailDispatchConfiguration.getConfiguration(); properties.put("mail.smtp.host", conf.mailSmtpHost()); properties.put("mail.smtp.name", conf.mailSmtpName()); properties.put("mail.smtp.port", conf.mailSmtpPort()); properties.put("mailSender.max.recipients", conf.mailSenderMaxRecipients()); SESSION = Session.getDefaultInstance(properties, null); return SESSION; }
Source:
public void testInterrupt() throws Exception { Pipelining<String> pipelining = new Pipelining<String>(1); pipelining.add(mock(ICompletableFuture.class)); TestThread t = new TestThread() { @Override public void doRun() throws Throwable { START pipelining.add(mock(ICompletableFuture.class)); END } }; t.start(); t.interrupt(); t.assertFailsEventually(InterruptedException.class); } You need to mark the pipelining as `final` as the code needs to be JDK6 compatible.

Target:
public void testInterrupt() throws Exception { final Pipelining<String> pipelining = new Pipelining<String>(1); pipelining.add(mock(ICompletableFuture.class)); TestThread t = new TestThread() { @Override public void doRun() throws Throwable { pipelining.add(mock(ICompletableFuture.class)); } }; t.start(); t.interrupt(); t.assertFailsEventually(InterruptedException.class); }
Source:
public void traceClosed(@Nullable TmfTraceClosedSignal signal) { cancelUpdate(); super.traceClosed(signal); setDataProvider(null); if (signal != null) { START fXYPresentationProvider.remove(signal.getTrace().getUUID()); END } } If the trace is an experiment, it has already been disposed and its UUID has changed (experiment no longer has any children, its UUID computed from an empty string).

Target:
public void traceClosed(@Nullable TmfTraceClosedSignal signal) { cancelUpdate(); super.traceClosed(signal); setDataProvider(null); if (signal != null) { fXYPresentationProvider.remove(signal.getTrace()); } }
Source:
private String author(int line) { PersonIdent author = START db.getMailmap().map(blame.getSourceAuthor(line)); END if (author == null) return ""; //$NON-NLS-1$ String name = showAuthorEmail ? author.getEmailAddress() : author .getName(); return name != null ? name : ""; //$NON-NLS-1$ } the other option is to do it on the commands exposing this information to the user only. I think internally we should stick to the original author/committer/tagger

Target:
private String author(int line) { PersonIdent author = blame.getSourceAuthor(line); if (author == null) return ""; //$NON-NLS-1$ String name = showAuthorEmail ? author.getEmailAddress() : author .getName(); return name != null ? name : ""; //$NON-NLS-1$ }
Source:
START public void deactivate() { END // retrieve the view and the element managed by the edit part View view = getView(); if (view == null) { return; } getDiagramEventBroker().removeNotificationListener(view, this); if (hostSemanticElement == null) { return; } // remove listeners to applied stereotyped for (EObject stereotypeApplication : hostSemanticElement.getStereotypeApplications()) { getDiagramEventBroker().removeNotificationListener(stereotypeApplication, this); } // remove notification on element getDiagramEventBroker().removeNotificationListener(hostSemanticElement, this); // removes the reference to the semantic element hostSemanticElement = null; } Avoid multiple returns.

Target:
public void deactivate() { // retrieve the view and the element managed by the edit part View view = getView(); if (view != null) { getDiagramEventBroker().removeNotificationListener(view, this); if (hostSemanticElement != null) { // remove listeners to applied stereotyped for (EObject stereotypeApplication : hostSemanticElement.getStereotypeApplications()) { getDiagramEventBroker().removeNotificationListener(stereotypeApplication, this); } // remove notification on element getDiagramEventBroker().removeNotificationListener(hostSemanticElement, this); // removes the reference to the semantic element hostSemanticElement = null; } } }
Source:
public DefaultSchedulerMessageSource(MuleContext muleContext, PeriodicScheduler scheduler, boolean disallowConcurrentExecution) { this.muleContext = muleContext; this.scheduler = scheduler; this.disallowConcurrentExecution = disallowConcurrentExecution; notificationFunctions = new LinkedList<>(); // Add message received notification notificationFunctions START .add((event, component) -> createConnectorMessageNotification(this, event, component.getLocation(), MESSAGE_RECEIVED)); END } isn't this the exact same notification that the FlowProcessMediator is already sending?

Target:
public DefaultSchedulerMessageSource(MuleContext muleContext, PeriodicScheduler scheduler, boolean disallowConcurrentExecution) { this.muleContext = muleContext; this.scheduler = scheduler; this.disallowConcurrentExecution = disallowConcurrentExecution; }
Source:
public void requestHandleWithNonHealthCheckRequestTest() throws IOException { START testNonHealthCheckRequest(HttpMethod.POST, "POST"); END testNonHealthCheckRequest(HttpMethod.GET, "GET"); testNonHealthCheckRequest(HttpMethod.GET, MockBlobStorageService.ECHO_REST_METHOD); testNonHealthCheckRequest(HttpMethod.DELETE, "DELETE"); } Don't understand this. Why aren't you doing `MockBlobStorageService.ECHO_REST_METHOD` for everything?

Target:
public void requestHandleWithNonHealthCheckRequestTest() throws IOException { testNonHealthCheckRequest(HttpMethod.POST, "POST"); testNonHealthCheckRequest(HttpMethod.GET, "GET"); testNonHealthCheckRequest(HttpMethod.DELETE, "DELETE"); }
Source:
public DockerTemplateOptions volumes(Map<String, String> volumes) { for (Map.Entry<String, String> entry : checkNotNull(volumes, "volumes").entrySet()) { checkNotNull(entry.getKey(), "host paths must not be null"); checkNotNull(entry.getValue(), "container paths must not be null"); START } END this.volumes = Optional.<Map<String, String>>of(ImmutableMap.copyOf(volumes)); return this; } In general for the whole PR, are these checks really needed? Guava's immutable collections don't allow null values so checking the null input in the map and list options here looks redundant?

Target:
public DockerTemplateOptions volumes(Map<String, String> volumes) { this.volumes = Optional.<Map<String, String>>of(ImmutableMap.copyOf(checkNotNull(volumes, "volumes"))); return this; }
Source:
private String getMethodCallback(JMethod method) { START if (isVoidMethod(method)) { END return "org.fusesource.restygwt.client.MethodCallback<java.lang.Void> callback"; } else if (method.getReturnType().isPrimitive() != null) { JPrimitiveType primitiveType = method.getReturnType().isPrimitive(); return "org.fusesource.restygwt.client.MethodCallback<" + primitiveType.getQualifiedBoxedSourceName() + "> callback"; } return "org.fusesource.restygwt.client.MethodCallback<" + method.getReturnType().getParameterizedQualifiedSourceName() + "> callback"; } Correct me if it's wrong, but I think the first block with "if (isVoidMethod(method)) {" is not needed anymore

Target:
private String getMethodCallback(JMethod method) { if (method.getReturnType().isPrimitive() != null) { JPrimitiveType primitiveType = method.getReturnType().isPrimitive(); return "org.fusesource.restygwt.client.MethodCallback<" + primitiveType.getQualifiedBoxedSourceName() + "> callback"; } return "org.fusesource.restygwt.client.MethodCallback<" + method.getReturnType().getParameterizedQualifiedSourceName() + "> callback"; }
Source:
protected GoogleApiClient createGoogleApiClient() { START return GoogleApiClientFactory.createWithoutSignIn(getApplicationContext()); END } I am not sure if it is a good practice to create GoogleApiClient with ApplicationContext. GoogleApiClient is really tied to the Activity. We are recreating it on every Activity. That's how it needs to be done. So I am not sure if this makes sense.

Target:
protected GoogleApiClient createGoogleApiClient() { return GoogleApiClientFactory.createWithoutSignIn(this); }
Source:
private boolean matchNamePattern(String value, String namePattern) { boolean match = true; START if (value != null && StringUtils.isNotBlank(value)) { END match = value.matches(namePattern); } return match; } Doesn't StringUtils.isNotBlank already compare for null?

Target:
private boolean matchNamePattern(String value, String namePattern) { boolean match = true; if (StringUtils.isNotBlank(value)) { match = value.matches(namePattern); } return match; }
Source:
public void setStatus(int sc, String sm) { START if (super.getStatus() == OK) { END super.setStatus(sc, sm); } status = sc; } I think this check should happen before applying the wrapper (i.e. if the current status code is 200 don't apply the wrapper, if it is not 200 don't let it be modified). Otherwise if there are multiple calls to setStatus the first one may work and the second will fail.

Target:
public void setStatus(int sc, String sm) { status = sc; }
Source:
public final GHIntArrayList reverse() { final int[] buffer = this.buffer; for (int start = 0, end = size() - 1; start < end; start++, end--) { // swap the values START int tmp = buffer[start]; END buffer[start] = buffer[end]; buffer[end] = tmp; } return this; } Maybe we should define the int outside of the for? Not sure if this gets optimized, but I introduced a "bug" with String once, so I became a bit cautious with these things.

Target:
public final GHIntArrayList reverse() { final int[] buffer = this.buffer; int tmp; for (int start = 0, end = size() - 1; start < end; start++, end--) { // swap the values tmp = buffer[start]; buffer[start] = buffer[end]; buffer[end] = tmp; } return this; }
Source:
public Collection<TreeNode> getTreeNodes(Diff diff) { final Collection<EStructuralFeature.Setting> settings = treeNodeToDiffCrossReferencer .getNonNavigableInverseReferences(diff, false); START final Set<TreeNode> nodes = new LinkedHashSet<TreeNode>(settings.size()); END for (EStructuralFeature.Setting setting : settings) { final EObject referencing = setting.getEObject(); if (referencing instanceof TreeNode) { nodes.add((TreeNode)referencing); } } return nodes; } Is a Set really necessary here? A treenode can wrap a single eobject so the same treenode will be returned only once by #getNonNavigableInverseReferences()

Target:
public Collection<TreeNode> getTreeNodes(Diff diff) { final Collection<EStructuralFeature.Setting> settings = treeNodeToDiffCrossReferencer .getNonNavigableInverseReferences(diff, false); final List<TreeNode> nodes = new ArrayList<TreeNode>(settings.size()); for (EStructuralFeature.Setting setting : settings) { final EObject referencing = setting.getEObject(); if (referencing instanceof TreeNode) { nodes.add((TreeNode)referencing); } } return nodes; }
Source:
public int lookupId(String name) { START if (value == null) { END return Strings.isNullOrEmpty(name) ? 0 : -1; } else { return value.equals(name) ? 0 : -1; } } This branch is not needed

Target:
public int lookupId(String name) { return value.equals(name) ? 0 : -1; }
Source:
START public String getAbsoluteFilePath(String relPath) { END Bundle bundle = Platform.getBundle(MulticoreVisualizerUIPlugin.PLUGIN_ID); URL fileURL = bundle.getEntry(relPath); File file = null; try { file = new File(FileLocator.resolve(fileURL).toURI()); } catch (URISyntaxException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return file.getAbsolutePath(); } private

Target:
private String getAbsoluteFilePath(String relPath) { Bundle bundle = Platform.getBundle(MulticoreVisualizerUIPlugin.PLUGIN_ID); URL fileURL = bundle.getEntry(relPath); File file = null; try { file = new File(FileLocator.resolve(fileURL).toURI()); } catch (URISyntaxException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return file.getAbsolutePath(); }
Source:
START private void timeoutEvent(TimeoutMap.Listener.Type type, String cid) { END switch (type) { case Remove: case Evict: correlationIds.remove(cid); break; case Put: default: correlationIds.add(cid); } dirty = true; } Can we avoid the switch as its not common practice and maybe people dont know about how it works and would think that remove and put does nothing in this example etc. Make the code understandable and maintainable for everyone.

Target:
private void timeoutEvent(TimeoutMap.Listener.Type type, String cid) { if (type == Put) { correlationIds.add(cid); } else if (type == Remove || type == Evict) { correlationIds.remove(cid); } dirty = true; }
Source:
public void setUp() throws Exception { createProject(); START baseActivityTestRule.launchActivity(null); END } please use baseActivityTestRule.launchActivity() (without the "null")

Target:
public void setUp() throws Exception { createProject(); baseActivityTestRule.launchActivity(); }
Source:
public void tearDown() { col.drop(); START client.close(); END } The closing is already done in the driver. No need to repeat it here.

Target:
public void tearDown() { col.drop(); }
Source:
private View makeSpaceView(int width, int height) { View view = new View(getActivity()); view.setLayoutParams(new ListView.LayoutParams(width, height)); view.setClickable(true); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dismiss(); } START return false; END } }); return view; } Shouldn't we return true?

Target:
private View makeSpaceView(int width, int height) { View view = new View(getActivity()); view.setLayoutParams(new ListView.LayoutParams(width, height)); view.setClickable(true); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dismiss(); } return true; } }); return view; }
Source:
public boolean needsInput() { // Since SetBuildOperator is always the last operator (no next operator that needs input from it), // we handle the unfinished work in this method instead of getOutput(). The Driver always // calls it in each iteration. if (unfinishedWork != null) { boolean done = processUnfinishedWork(); channelSetBuilder.updateMemoryReservation(); START if (!done) { return false; } END } return !finished; } fmt

Target:
public boolean needsInput() { // Since SetBuilderOperator doesn't produce any output, the getOutput() // method may never be called. We need to handle any unfinished work // before addInput() can be called again. return !finished && (unfinishedWork == null || processUnfinishedWork()); }
Source:
public void onLoad() { START offset = world.rand.nextInt(10); END } Add ````java super.onLoad(); ```` Just so that we don't have to worry about future additions to the parent's onLoad function not being called by this.

Target:
public void onLoad() { super.onLoad(); offset = world.rand.nextInt(10); }
Source:
protected Message<?> doPollForMessage(String groupIdKey) { START List<Message<?>> messages = jdbcTemplate.query(getQuery(Query.POLL_FROM_GROUP), new Object[] { groupIdKey, region, groupIdKey }, mapper); END Assert.isTrue(messages.size() == 0 || messages.size() == 1); if (messages.size() > 0){ return messages.get(0); } return null; } How about to use here `NamedParameterJdbcTemplate` as you've done in the `JdbcChannelMessageStore#doPollForMessage` ?

Target:
protected Message<?> doPollForMessage(String groupIdKey) { List<Message<?>> messages = jdbcTemplate.query(getQuery(Query.POLL_FROM_GROUP), new Object[] { groupIdKey, region, groupIdKey, region }, mapper); Assert.isTrue(messages.size() == 0 || messages.size() == 1); if (messages.size() > 0){ return messages.get(0); } return null; }
Source:
public static boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { Thread watcherThread = ThreadDeathWatcher.watcherThread; if (watcherThread != null) { watcherThread.join( START ObjectUtil.checkNotNull(unit, "unit").toMillis(timeout)); END return !watcherThread.isAlive(); } else { return true; } } move the null check as first action in the method to ensure we also throw if `watcherThread == null` and `unit` is null

Target:
public static boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { ObjectUtil.checkNotNull(unit, "unit"); Thread watcherThread = ThreadDeathWatcher.watcherThread; if (watcherThread != null) { watcherThread.join(unit.toMillis(timeout)); return !watcherThread.isAlive(); } else { return true; } }
Source:
public Builder toBuilder() { Builder builder = new Builder(type); builder.members.putAll(members); START for (Map.Entry<String, List<CodeBlock>> entry : builder.members.entrySet()) { END entry.setValue(new ArrayList<>(entry.getValue())); } return builder; } I think I'd have rather looped over the `members`' entry set to `put()` each entry into `builder.members` instead of using `putAll` and then replacing the entries' values.

Target:
public Builder toBuilder() { Builder builder = new Builder(type); for (Map.Entry<String, List<CodeBlock>> entry : members.entrySet()) { builder.members.put(entry.getKey(), new ArrayList<>(entry.getValue())); } return builder; }
Source:
public void closeJob(GeneralSecurityException gse) { START callback.onCompletion(new EncryptJobResult(null, null, null), gse); END } why isn't this `onCompletion(null, gse)`?

Target:
public void closeJob(GeneralSecurityException gse) { callback.onCompletion(null, gse); }
Source:
private ChangeInfo getChange(PushOneCommit.Result pr) throws IOException { return getChange(pr.getChangeId(), START ListChangesOption.DETAILED_LABELS); END } Nit: in another file you've imported ListChangesOption statically (for MESSAGES). Umport it statically here too?

Target:
private ChangeInfo getChange(PushOneCommit.Result pr) throws IOException { return getChange(pr.getChangeId(), DETAILED_LABELS); }
Source:
private void clearIfNeeded(Address lockHolder) { START if(!rpcManager.getMembers().contains(lockHolder)) { END final Directory directory = getDirectoryProvider().getDirectory(); log.warn("Forcing clear of index lock"); ((DirectoryExtensions) directory).forceUnlock(IndexWriter.WRITE_LOCK_NAME); } } Spacing

Target:
private void clearIfNeeded(Address lockHolder) { if (!rpcManager.getMembers().contains(lockHolder)) { final Directory directory = getDirectoryProvider().getDirectory(); log.debug("Forcing clear of index lock"); ((DirectoryExtensions) directory).forceUnlock(IndexWriter.WRITE_LOCK_NAME); } }
Source:
public Capable canUpload() { Capable result = projectControl.canPushToAtLeastOneRef(); if (result != Capable.OK) { return result; } START result = MagicBranch.checkMagicBranchRefs(repo, project); END return Capable.OK; } You ignore result here. You need to return result.

Target:
public Capable canUpload() { Capable result = projectControl.canPushToAtLeastOneRef(); if (result != Capable.OK) { return result; } return MagicBranch.checkMagicBranchRefs(repo, project); }
Source:
private int getColumnWidth(final Pattern52 pattern) { START if (pattern.getBoundName() == null || pattern.getBoundName().trim().isEmpty()) { END return 1; } else { return pattern.getChildColumns().size(); } } Maybe also here `StringUtils` but I am thinking if it is good idea to bring dependency for that class.

Target:
private int getColumnWidth(final Pattern52 pattern) { if (StringUtils.isEmpty(pattern.getBoundName())) { return 1; } else { return pattern.getChildColumns().size(); } }
Source:
public void onStart(ITestContext iTestContext) { getLifecycle().fire(new TestSuiteStartedEvent( getSuiteUid(iTestContext), iTestContext.getSuite().getName() ).withTitle( getCurrentSuiteTitle(iTestContext) ).withLabels( AllureModelUtils.createTestFrameworkLabel("TestNG"), START AllureModelUtils.createFeatureLabel(getCurrentSuiteTitle(iTestContext)) END )); } Could you please remove this line?

Target:
public void onStart(ITestContext iTestContext) { getLifecycle().fire(new TestSuiteStartedEvent( getSuiteUid(iTestContext), iTestContext.getSuite().getName() ).withTitle( getCurrentSuiteTitle(iTestContext) ).withLabels( AllureModelUtils.createTestFrameworkLabel("TestNG") )); }
Source:
public boolean supportsSorting(SortBy[] sortAttributes) { START if (super.supportsSorting(sortAttributes)) return true; END for (SortBy sort : sortAttributes) { if (!supportsPropertySorting(sort.getPropertyName())) return false; } return true; } Not sure about this one @taba90, even if the default implementation supports it we still want to override the default check no?

Target:
public boolean supportsSorting(SortBy[] sortAttributes) { for (SortBy sort : sortAttributes) { if (!supportsPropertySorting(sort.getPropertyName())) return false; } return true; }
Source:
public static boolean hasGitFolder(InputStream inputStream) throws IOException { TarArchiveInputStream tarInputStream = null; try { boolean gitFolderPresent = false; tarInputStream = new TarArchiveInputStream(new GzipCompressorInputStream(inputStream)); START for (TarArchiveEntry entry; (entry = tarInputStream.getNextTarEntry()) != null;) { END if (GIT_FOLDER_NAME.equals(entry.getName()) && entry.isDirectory()) { gitFolderPresent = true; break; } } return gitFolderPresent; } finally { StreamUtils.close(tarInputStream); } } yes but if you change the impl to something that would not always set it and forget about changing the initialization.... It's simply very good but simple practice: always initialize local variables, instance variable are automagically always in a sane state. I really dont see the point of removing the existing initializations. Spare some characters? And as said, it's a good practice to always initialize local variables to a defined state.

Target:
public static boolean hasGitFolder(InputStream inputStream) throws IOException { TarArchiveInputStream tarInputStream = null; try { boolean gitFolderPresent = false; tarInputStream = new TarArchiveInputStream(new GzipCompressorInputStream(inputStream)); for (TarArchiveEntry entry = null; (entry = tarInputStream.getNextTarEntry()) != null;) { if (GIT_FOLDER_NAME.equals(entry.getName()) && entry.isDirectory()) { gitFolderPresent = true; break; } } return gitFolderPresent; } finally { StreamUtils.close(tarInputStream); } }