auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void setUsernameInRequest() { Http.Session session = Http.Context.current().session(); String email = session.get(ConstantsManager.COOKIE_EMAIL_FIELD_NAME); START Controller.request().setUsername(email); END } `Http.Context.current().request().setUsername(email);` Tu pourras donc aussi enlever le import de Controller

Target:
private void setUsernameInRequest() { Http.Session session = Http.Context.current().session(); String email = session.get(ConstantsManager.COOKIE_EMAIL_FIELD_NAME); Http.Context.current().request().setUsername(email); }
Source:
private boolean useProtocolV2() { START return Objects.equals(transferConfig.protocolVersion, END ProtocolVersion.V2) && clientRequestedV2; } Optional: Can be written as ProtocolVersion.V2.equals(transferConfig.protocolVersion), since we know that ProtocolVersion.V2 is never null.

Target:
private boolean useProtocolV2() { return ProtocolVersion.V2.equals(transferConfig.protocolVersion) && clientRequestedV2; }
Source:
private synchronized int purgeExpiredRecallRequests(long expirationTime, int purgeSize) { int n = new TapeRecallCatalog().purgeCatalog(expirationTime, purgeSize); if (n == 0) { START log.trace("No entries have been purged from tape_recall table"); END } else { log.info("{} entries have been purged from tape_recall table", n); } return n; } I would remove the if an always log the number of entries removed, which can be 0

Target:
private synchronized int purgeExpiredRecallRequests(long expirationTime, int purgeSize) { return new TapeRecallCatalog().purgeCatalog(expirationTime, purgeSize); }
Source:
public A value() { START return supplier != null ? supplier.f() : null; END } should just be `return supplier.f()`. In FJ we do not special on case `null` imput value: protecting each input parameter against null would litter the code with garbage, maybe also impact perf and, in this case, hide root issue by propagating a null value. Only dedicated APIs like `Option.fromNull` explicitly deal with `null`.

Target:
public final A value() { return supplier.f(); }
Source:
START @Override public void onDestroyView() { END super.onDestroyView(); if (disposable != null) { disposable.dispose(); } } Please move the annotation to its own line

Target:
public void onDestroyView() { super.onDestroyView(); if (disposable != null) { disposable.dispose(); } }
Source:
void generateParameterValueSet(ActivationClassBuilder acb) throws StandardException { Vector parameterList = getCompilerContext().getParameterList(); int numberOfParameters = (parameterList == null) ? 0 : parameterList.size(); START if (numberOfParameters < 0) END return; ParameterNode.generateParameterValueSet (acb, numberOfParameters, parameterList); } Why? It seems that this cannot happen

Target:
void generateParameterValueSet(ActivationClassBuilder acb) throws StandardException { Vector parameterList = getCompilerContext().getParameterList(); int numberOfParameters = (parameterList == null) ? 0 : parameterList.size(); ParameterNode.generateParameterValueSet (acb, numberOfParameters, parameterList); }
Source:
public Boolean getXD_JMX_ENABLED() { START return (jmxEnabled != null && jmxEnabled) ? jmxEnabled : null; END } seems odd to return null here even if it had been explicitly set to FALSE

Target:
public Boolean getXD_JMX_ENABLED() { return jmxEnabled; }
Source:
private void validateTag(String xmlTag) { Conditions.checkNotNullOrEmpty(xmlTag, "xmlTag"); // resources can only have three tags: "resourceDoc", "applicationDocs" or "grammars" START boolean valid = false; END if (xmlTag.compareTo("resourceDoc") == 0) { valid = true; } else if (xmlTag.compareTo("applicationDocs") == 0) { valid = true; } else if (xmlTag.compareTo("grammars") == 0) { valid = true; } if (!valid) { throw new OseeArgumentException("Invalid resource document tag"); } } This looks like a C style equality check. Also, it does not account for case mismatches. Conside using if("resourceDoc".equalsIgnoreCase(xmlTag))... instead.

Target:
private void validateTag(String xmlTag) { Conditions.checkNotNullOrEmpty(xmlTag, "xmlTag"); // resources can only have three tags: "resourceDoc", "applicationDocs" or "grammars" boolean valid = false; if (xmlTag.equals("resourceDoc")) { valid = true; } else if (xmlTag.equals("applicationDocs")) { valid = true; } else if (xmlTag.equals("grammars")) { valid = true; } if (!valid) { throw new OseeArgumentException("Invalid resource document tag"); } }
Source:
public int compareTo(ModuleMetadata other) { START return this.getName().compareTo(other.getName()); END } Should include other properties to break ties here

Target:
public int compareTo(ModuleMetadata other) { return this.getId().compareTo(other.getId()); }
Source:
START private BlockingQueue<Runnable> newQueue(boolean needPrioritySort) { END return needPrioritySort ? new PriorityBlockingQueue<>() : new LinkedBlockingQueue<>(); } static

Target:
private static BlockingQueue<Runnable> newQueue(boolean needPrioritySort) { return needPrioritySort ? new PriorityBlockingQueue<>() : new LinkedBlockingQueue<>(); }
Source:
public void run() { START if (historyPage.getCurrentRepo() == null) END return; dialog = new GitHistoryRefFilterConfigurationDialog( historyPage.getSite().getWorkbenchWindow().getShell(), historyPage.getCurrentRepo(), historyPage.helper); if (dialog.open() == Window.OK) { historyPage.refresh(historyPage.selectedCommit()); } } missing braces

Target:
public void run() { if (historyPage.getCurrentRepo() == null) { return; } dialog = new GitHistoryRefFilterConfigurationDialog( historyPage.getSite().getWorkbenchWindow().getShell(), historyPage.getCurrentRepo(), historyPage.helper); if (dialog.open() == Window.OK) { historyPage.refresh(historyPage.selectedCommit()); } }
Source:
public String getAccumuloClasspath() { START return verifyNotNull(ADMIN_ACCUMULO_CLASSPATH_PROP, getString(ADMIN_ACCUMULO_CLASSPATH_PROP, ADMIN_ACCUMULO_CLASSPATH_DEFAULT)); END } Could this ever be null since `getString()` is passed a default?

Target:
public String getAccumuloClasspath() { return getString(ADMIN_ACCUMULO_CLASSPATH_PROP, ADMIN_ACCUMULO_CLASSPATH_DEFAULT); }
Source:
private AuthenticationException onError(JwtException e) { START if (logger.isDebugEnabled()) { END logger.debug("Authentication error for Jwt Token: " + e.getMessage()); } if (e instanceof BadJwtException) { return new InvalidBearerTokenException(e.getMessage(), e); } else { return new AuthenticationServiceException(e.getMessage(), e); } } I'm not seeing the added benefit of this one since `AuthenticationWebFilter` displays the same information. Is it necessary?

Target:
private AuthenticationException onError(JwtException e) { if (e instanceof BadJwtException) { return new InvalidBearerTokenException(e.getMessage(), e); } else { return new AuthenticationServiceException(e.getMessage(), e); } }
Source:
private void validateCallbackUrl(String callbackUrl) { try { new URL(callbackUrl); } catch (MalformedURLException e) { START throw new IllegalArgumentException("Callback URL must be valid if provided!"); END } } Maybe we could also pass the root cause when creating the new exception.

Target:
private void validateCallbackUrl(String callbackUrl) { try { new URL(callbackUrl); } catch (MalformedURLException e) { throw new IllegalArgumentException("Callback URL must be valid if provided!", e); } }
Source:
private boolean canViewInjectedVars(@Nonnull User user, @Nonnull Run<?,?> run) throws UsernameNotFoundException { SecurityContext initialContext = null; try { Authentication auth = user.impersonate(); initialContext = hudson.security.ACL.impersonate(auth); return EnvInjectPlugin.canViewInjectedVars(run); } finally { if (initialContext != null) { SecurityContextHolder.setContext(initialContext); } START } END } BTW can be written more concisely with an effectively final variable: ``` java Authentication auth = user.impersonate(); SecurityContext initialContext = ACL.impersonate(auth); try { return EnvInjectPlugin.canViewInjectedVars(run); } finally { SecurityContextHolder.setContext(initialContext); } ``` (There are also two newer overloads with closures, but neither are suitable for Java 8 lambdas.)

Target:
private boolean canViewInjectedVars(@Nonnull User user, @Nonnull Run<?,?> run) throws UsernameNotFoundException { SecurityContext initialContext = null; Authentication auth = user.impersonate(); initialContext = hudson.security.ACL.impersonate(auth); try { return EnvInjectPlugin.canViewInjectedVars(run); } finally { SecurityContextHolder.setContext(initialContext); } }
Source:
public void doPrefetch(int index, long relativeOffset, long size) { try { readOptions.get(index).doPrefetch(relativeOffset, size); } catch (Exception e) { START logger.error("Data Prefetch failed", e); END } } so why is this an error and not a warning? Since the system proceeds without giving up, I think it should be a warning

Target:
public void doPrefetch(int index, long relativeOffset, long size) throws IOException { readOptions.get(index).doPrefetch(relativeOffset, size); }
Source:
public void latchAwaitSeconds(int sec) throws InterruptedException { START System.out.println("AWAIT " + latch); END if (!latch.await(sec, TimeUnit.SECONDS)) { throw new RuntimeException("Await failed"); } } This should probably be removed

Target:
public void latchAwaitSeconds(int sec) throws InterruptedException { if (!latch.await(sec, TimeUnit.SECONDS)) { throw new RuntimeException("Await failed"); } }
Source:
START protected boolean canDoAction() { END if (!(validate(hostExists()) && validate(hostStatusValid()))){ return false; } return true; } you can simplify it with a single line by replacing the method's body with: return validate(hostExists()) && validate(hostStatusValid());

Target:
protected boolean canDoAction() { return validate(hostExists()) && validate(hostStatusValid()); }
Source:
public List<ID3v2ChapterFrameData> getChapters() { if (obseleteFormat) { START return Collections.emptyList(); END } return extractChapterFrameData(ID_CHAPTER); } Changing from returning null to returning an empty collection changes the SDK's interface, which might affect applications that are using it. I'd prefer not to make a breaking change unless it's absolutely neccessary.

Target:
public ArrayList<ID3v2ChapterFrameData> getChapters() { if (obseleteFormat) { return null; } return new ArrayList<>(extractChapterFrameData(ID_CHAPTER)); }
Source:
ImageEditorPanel(MainFrame mainFrame, BufferedImage image, String name) { this.image = image; this.name = name; setTransferHandler(new ImageTransferHandler(mainFrame)); checkImage(); setOpaque(false); setLayout(new BorderLayout()); loadSupport(); START buildImageViewer(); END buildStatusPanel(); } checkImage(); should be below buildStatusPanel(); loadSupport(); buildImageViewer(); buildStatusPanel(); checkImage();

Target:
ImageEditorPanel(MainFrame mainFrame, BufferedImage image, String name) { this.image = image; this.name = name; setTransferHandler(new ImageTransferHandler(mainFrame)); setOpaque(false); setLayout(new BorderLayout()); loadSupport(); buildImageViewer(); buildStatusPanel(); checkImage(); }
Source:
public void setIdentifiers(List<Identifier> identifiers) { START Identifiers = identifiers; END } Shouldn't this be this.variableName. This is a Potential Null pointer Exception.

Target:
public void setIdentifiers(List<Identifier> identifiers) { this.identifiers = identifiers; }
Source:
public String getActionClass( ) { return environmentVariables.get( actionClass ); START } END Seems like a lot of work just to verify that the json is valid. Perhaps there is some 3rd party utility to do that for us? Something to consider

Target:
public String getActionClass( ) { return actionClass; }
Source:
public void handleMessage(Message msg) { switch (msg.what) { case EVENT_QUALIFIED_NETWORKS_CHANGED: START synchronized (this) { END AsyncResult ar = (AsyncResult) msg.obj; List<QualifiedNetworks> networks = (List<QualifiedNetworks>) ar.result; updateAvailableNetworks(networks); } break; default: loge("Unexpected event " + msg.what); break; } } Why not use the synchronized in updateAvailableNetworks?

Target:
public void handleMessage(Message msg) { switch (msg.what) { case EVENT_QUALIFIED_NETWORKS_CHANGED: AsyncResult ar = (AsyncResult) msg.obj; List<QualifiedNetworks> networks = (List<QualifiedNetworks>) ar.result; updateAvailableNetworks(networks); break; default: loge("Unexpected event " + msg.what); break; } }
Source:
private void saveStateParamForIdpToRequestSession(String state, String idpOriginKey, HttpServletRequest request) { if (request != null) { request.getSession().setAttribute("xoauth-state-" + idpOriginKey, state); START } END } Is there any value to this null check? Even if it is null, this operation doesn't make any sense if we can't access the session.

Target:
private void saveStateParamForIdpToRequestSession(String state, String idpOriginKey, HttpServletRequest request) { request.getSession().setAttribute("xoauth-state-" + idpOriginKey, state); }
Source:
START private void logMeasureByResource(Resource resource, Measure measure) { END if (LOG.isDebugEnabled()) { Measure alreadySaved = MEASURES_BY_RESOURCE.get(resource); if (alreadySaved == null) { MEASURES_BY_RESOURCE.put(resource, measure); } else { LOG.debug("Measure already saved for resource {}", measure, resource); } } } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "logMeasureByResource" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/coding_rules#rule_key=squid%3AS2325)

Target:
private static void logMeasureByResource(Resource resource, Measure measure) { if (LOG.isDebugEnabled()) { Measure alreadySaved = MEASURES_BY_RESOURCE.get(resource); if (alreadySaved == null) { MEASURES_BY_RESOURCE.put(resource, measure); } else { LOG.debug("Measure already saved for resource {}", measure, resource); } } }
Source:
START private List<ProducerBatch> getChildrenProducerBatch() { END if (childrenProducerBatch == null) { return Collections.emptyList(); } return childrenProducerBatch; } If we could get rid of null check, `addChildrenProducerBatch` and `getChildrenProducerBatch` could be removed as well.

Target:
private synchronized List<ProducerBatch> getChildrenProducerBatch() { if (childrenProducerBatch == null) { return Collections.emptyList(); } return childrenProducerBatch; }
Source:
private String getSetting(String settingName) { SettingKey key = settingKeyDAO.findByName(settingName); if (key != null) { Setting setting = settingDAO.findByKey(key); if (setting != null) START return setting.getValue(); END } return null; } Use braces - see https://www.dwheeler.com/essays/apple-goto-fail.html

Target:
private String getSetting(String settingName) { SettingKey key = settingKeyDAO.findByName(settingName); if (key != null) { Setting setting = settingDAO.findByKey(key); if (setting != null) { return setting.getValue(); } } return null; }
Source:
public float getPrefHeight () { // Min of borders + text height or drawable height layout = new GlyphLayout(style.font, model.getValue().toString()); START return Float.max(style.background.getMinHeight(), END style.background.getTopHeight() + style.background.getBottomHeight() + layout.height); } `Float.max()` is since 1.8 so it won't work on Android and GWT. Use `Math.max()` instead.

Target:
public float getPrefHeight () { // Max of borders + text height or drawable height return Math.max(style.background.getMinHeight(), style.background.getTopHeight() + style.background.getBottomHeight() + layout.height); }
Source:
private void removeIncludeExcludeWithHandler() { new PushButton("Remove...").click(); START new WaitUntil(new ShellIsAvailable("Confirmation")); END new DefaultShell("Confirmation"); new PushButton("OK").click(); } no need for the wait, DefaultShell already has the wait inside

Target:
private void removeIncludeExcludeWithHandler() { new PushButton("Remove...").click(); new DefaultShell("Confirmation"); new PushButton("OK").click(); }
Source:
public synchronized void onClosedSource(String tableName, int partition) { boolean removed = m_dataSourcesClosing.remove(tableName, partition); if (exportLog.isDebugEnabled()) { if (removed) { exportLog.debug("Closed " + tableName + ", partition " + partition); } else { START exportLog.info("Closed untracked " + tableName + ", partition " + partition + " (ok on shutdown)"); END } } } This will only be logged if debug is enabled since it is in this block you might want to reorder if statements ``` if (!m_dataSourcesClosing.remove(tableName, partition)) <log info message> else if (log.isDebugEnabled()) <log closed message> ```

Target:
public synchronized void onClosedSource(String tableName, int partition) { boolean removed = m_dataSourcesClosing.remove(tableName, partition); if (exportLog.isDebugEnabled()) { if (removed) { exportLog.debug("Closed " + tableName + ", partition " + partition); } else { exportLog.debug("Closed untracked " + tableName + ", partition " + partition + " (ok on shutdown)"); } } }
Source:
public String getJBossDiscoveryDirectory() { // use commandline override -Djboss.discovery.directory.url String directory = System.getProperty(JBOSS_DISCOVERY_DIRECTORY, null); if (directory == null) { IPropertiesProvider pp = PropertiesHelper.getPropertiesProvider(); try { directory = pp.getValue(JBOSS_DISCOVERY_DIRECTORY, new NullProgressMonitor()); } catch (CoreException e) { START throw new RuntimeException(e); END } } return directory; } shouldn't there be a default so this never happens ?

Target:
public String getJBossDiscoveryDirectory() { // use commandline override -Djboss.discovery.directory.url String directory = System.getProperty(JBOSS_DISCOVERY_DIRECTORY, null); if (directory == null) { IPropertiesProvider pp = PropertiesHelper.getPropertiesProvider(); directory = pp.getValue(JBOSS_DISCOVERY_DIRECTORY); } return directory; }
Source:
public void setActive(boolean active) { START getImage().setActive(true == active); END } No need... getImage().setActive(active)

Target:
public void setActive(boolean active) { getImage().setActive(active); }
Source:
public MainDrawerHandler(WikiDrawerLayout slidingPane, Activity parentActivity) { this.slidingPane = slidingPane; this.parentActivity = parentActivity; START ButterKnife.bind(this.slidingPane); END setUpViews(); } What does this call do?

Target:
MainDrawerHandler(WikiDrawerLayout slidingPane, Activity parentActivity) { this.slidingPane = slidingPane; this.parentActivity = parentActivity; setUpViews(); }
Source:
public KeyStore loadKeyStore() throws IOException, GeneralSecurityException { KeyStore ks = keyStoreInstance(); START InputStream inputStream = null; END try { inputStream = new FileInputStream(new File(keyStorePath)); ks.load(inputStream, passwordStringToCharArray(keyStorePassword)); return ks; } finally { forceClose(inputStream); } } We can use try-with-resources now. I know this is only a refactoring but we can take this opportunity to clean up code

Target:
public KeyStore loadKeyStore() throws IOException, GeneralSecurityException { try (InputStream inputStream = new FileInputStream(new File(keyStorePath))) { KeyStore ks = keyStoreInstance(); ks.load(inputStream, passwordStringToCharArray(keyStorePassword)); return ks; } }
Source:
private List<GlusterVolumeEntity> getEligibleVolumesList(Set<GlusterVolumeEntity> upVolumesWithSuggestedCapacityAndNotInMasterCluster, Set<GlusterVolumeEntity> existingSessionSlaveVolumes) { List<GlusterVolumeEntity> eligibleVolumes = new ArrayList<GlusterVolumeEntity>(); START upVolumesWithSuggestedCapacityAndNotInMasterCluster.removeAll(existingSessionSlaveVolumes); END eligibleVolumes.addAll(upVolumesWithSuggestedCapacityAndNotInMasterCluster); return eligibleVolumes; } you could just return upVolumesWithSuggestedCapacityAndNotInMasterCluster here

Target:
private Set<GlusterVolumeEntity> getEligibleVolumesList(Set<GlusterVolumeEntity> upVolumesWithSuggestedCapacityAndNotInMasterCluster, Set<GlusterVolumeEntity> existingSessionSlaveVolumes) { upVolumesWithSuggestedCapacityAndNotInMasterCluster.removeAll(existingSessionSlaveVolumes); return upVolumesWithSuggestedCapacityAndNotInMasterCluster; }
Source:
public EclipseReferencePointManager() { referencePointToProjectMapper = START new ConcurrentHashMap<IReferencePoint, org.eclipse.core.resources.IProject>(); END } please use the Diamond Operator for initialization

Target:
public EclipseReferencePointManager() { referencePointToProjectMapper = new ConcurrentHashMap<>(); }
Source:
public void setSchedulerService(SchedulerService schedulerService) throws InitialisationException { this.schedulerService = schedulerService; START initialise(); END } this doesn't belong here

Target:
void setSchedulerService(SchedulerService schedulerService) { this.schedulerService = schedulerService; }
Source:
public void evictExpiredEntries(int expirationPercentage) { long now = Clock.currentTimeMillis(); int maxIterationCount = getMaxIterationCount(size(), expirationPercentage); int evictedCount = 0; int maxRetry = 3; int loop = 0; START while (true) { END evictedCount += evictExpiredInternal(maxIterationCount, now); if (evictedCount >= maxIterationCount) { break; } loop++; if (loop > maxRetry) { break; } } } `while (loop < maxRetry)` will get rid of the extra `if break` condition.

Target:
public void evictExpiredEntries(int expirationPercentage) { long now = Clock.currentTimeMillis(); int maxIterationCount = getMaxIterationCount(size(), expirationPercentage); int evictedCount = 0; int maxRetry = 3; int loop = 0; while (loop < maxRetry) { evictedCount += evictExpiredInternal(maxIterationCount, now); if (evictedCount >= maxIterationCount) { break; } loop++; } }
Source:
public static IJBoss7ManagerService findService(String runtimeType) { forceStart("org.jboss.ide.eclipse.as.core"); START forceStart("org.jboss.ide.eclipse.as.management.as71"); END forceStart("org.jboss.ide.eclipse.as.management.wildfly8"); try { return JBoss7ManagerUtil.getService(runtimeType); } catch(JBoss7ManangerException ise) { return null; } } Why forceStart call is required when org.jboss.ide.eclipse.as.management.as71 is declared as a dependency for test plugin?

Target:
public static IJBoss7ManagerService findService(String runtimeType) { try { return JBoss7ManagerUtil.getService(runtimeType); } catch(JBoss7ManangerException ise) { return null; } }
Source:
private List<Iterator<Entry<KeyType>>> getGroupersIterator(boolean sorted) { return groupers.stream() .map(grouper -> { synchronized (grouper) { return grouper.iterator(sorted); } START }).collect(Collectors.toList()); END } Should break line before dot

Target:
private List<Iterator<Entry<KeyType>>> getGroupersIterator(boolean sorted) { return groupers.stream() .map(grouper -> grouper.iterator(sorted)) .collect(Collectors.toList()); }
Source:
private void waitForAppToFinish() { workers.shutdown(); try { boolean finishedInTime = workers. awaitTermination(durationMs + APPLICATION_TIMEOUT_IN_MS, TimeUnit.MILLISECONDS); String livenessState = finishedInTime ? "Success" : "Fail"; Correctness.recordOperation("Liveness, " + livenessState, false); if (!finishedInTime) { START System.exit(0); END } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { taskProducer.shutdownNow(); checkpointer.shutdownNow(); } } Shouldn't you return an error code in this case?

Target:
private void waitForAppToFinish() { workers.shutdown(); try { boolean finishedInTime = workers. awaitTermination(durationMs + APPLICATION_TIMEOUT_IN_MS, TimeUnit.MILLISECONDS); String livenessState = finishedInTime ? "Success" : "Fail"; Correctness.recordOperation("Liveness, " + livenessState, false); if (!finishedInTime) { System.exit(1); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { taskProducer.shutdownNow(); checkpointer.shutdownNow(); } }
Source:
public Boolean scriptExists(final String sha1, final String key) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.scriptExists(sha1); } START }.run(1,key); END } I think .run(key) is more faster than this if we keep JedisClusterCommand.run(String or byte[]).

Target:
public Boolean scriptExists(final String sha1, final String key) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.scriptExists(sha1); } }.run(key); }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); START mSubscriptions = new Disposable[2]; END mRepository = (Repository) getArguments().getSerializable("repo"); mRef = getArguments().getString("ref"); } Maybe it would be better to use some sort of map? That way we would avoid potential out of bounds exceptions when someone adds new subscription but doesn't update that declaration.

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRepository = (Repository) getArguments().getSerializable("repo"); mRef = getArguments().getString("ref"); }
Source:
public void dispatchInvalidateOptionsMenu() { if (BuildConfig.DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]"); mActivity.getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL); START if (mMenu != null) { mMenu.invalidate(); } END } Either no brackets or put invalidate on its own line.

Target:
public void dispatchInvalidateOptionsMenu() { if (BuildConfig.DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]"); mActivity.getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL); if (mMenu != null) mMenu.invalidate(); }
Source:
public Collection<String> getSupportedCategories() { START return Collections.unmodifiableCollection(SUPPORTED_CATEGORIES); END } Since the categories never change, it would be better to make the value of `SUPPORTED_CATEGORIES` unmodifiable from the start.

Target:
public Collection<String> getSupportedCategories() { return SUPPORTED_CATEGORIES; }
Source:
public List<Runnable> shutdownNow() { shutdown = true; List<Runnable> runnableList = new LinkedList<>(); runnableList.addAll(executorService.shutdownNow()); runnableList.addAll(blockedTasks); START controllerThread.interrupt(); END return runnableList; } Shouldn't you interrupt the controller first?

Target:
public List<Runnable> shutdownNow() { shutdown = true; controllerThread.interrupt(); List<Runnable> runnableList = new LinkedList<>(); runnableList.addAll(executorService.shutdownNow()); runnableList.addAll(blockedTasks); return runnableList; }
Source:
public WorkQueue.Executor get() { CurrentUser user = userProvider.get(); START WorkQueue.Executor executor = queues.getInteractiveQueue(); END if (user.isBatchUser()) { executor = queues.getBatchQueue(); } return executor; } Style-nit: Don't assign then replace. Instead use a proper if-else: if (user.isBatchUser) { return queues.getBatchQueue(); } else { return queues.getInteractiveQueue(); }

Target:
public WorkQueue.Executor get() { WorkQueue.Executor executor; if (user.isBatchUser()) { executor = queues.getBatchQueue(); } else { executor = queues.getInteractiveQueue(); } return executor; }
Source:
final AppConfig getAppConfig(CascadeStrategy defaultStrategy) throws ConfigException { return DefaultAppConfig.builder() .withDefaultCascadingStrategy(defaultStrategy) START .withApplicationConfigName(DefaultAppConfig.DEFAULT_APP_CONFIG_NAME) END .build(); } Is there any reason to explicitly set to the default?

Target:
final AppConfig getAppConfig(CascadeStrategy defaultStrategy) throws ConfigException { return DefaultAppConfig.builder() .withDefaultCascadingStrategy(defaultStrategy) .build(); }
Source:
public static String moduleToJsonString(Module module) throws IOException { JsonFactory jsonFactory = createJsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer); jsonGenerator.useDefaultPrettyPrinter(); jsonGenerator.writeObject(module); START String result = writer.getBuffer().toString(); END return result; } ```suggestion return writer.getBuffer().toString(); ```

Target:
public static String moduleToJsonString(Module module) throws IOException { JsonFactory jsonFactory = createJsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer); jsonGenerator.useDefaultPrettyPrinter(); jsonGenerator.writeObject(module); return writer.getBuffer().toString(); }
Source:
private String createResults() { QueryResults queryResults = new QueryResults( "20160128_214710_00012_rk68b", server.url("/query.html?20160128_214710_00012_rk68b").uri(), null, null, ImmutableList.of(new Column("_col0", BigintType.BIGINT)), ImmutableList.of(ImmutableList.of(123)), StatementStats.builder().setState("FINISHED").build(), //new StatementStats("FINISHED", false, true, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null), null, null, START null, END null); return QUERY_RESULTS_CODEC.toJson(queryResults); } please squash this with first commit

Target:
private String createResults() { QueryResults queryResults = new QueryResults( "20160128_214710_00012_rk68b", server.url("/query.html?20160128_214710_00012_rk68b").uri(), null, null, ImmutableList.of(new Column("_col0", BigintType.BIGINT)), ImmutableList.of(ImmutableList.of(123)), StatementStats.builder().setState("FINISHED").build(), //new StatementStats("FINISHED", false, true, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null), null, ImmutableList.of(), null, null); return QUERY_RESULTS_CODEC.toJson(queryResults); }
Source:
START protected HashMap<String, Object> buildGitEnv(String url, END String username, String password, boolean mirror) { return new HashMap<String, Object>() {{ put("origin", url); put(SCHEME, GitRepository.SCHEME.toString()); put("replaceIfExists", true); put("username", username); put("password", password); put(MIRROR, mirror); }}; } Program to interface, not to implementation - please change return type to `Map<String, Object>`

Target:
protected Map<String, Object> buildGitEnv(String url, String username, String password, boolean mirror) { return new HashMap<String, Object>() {{ put("origin", url); put(SCHEME, GitRepository.SCHEME.toString()); put("replaceIfExists", true); put("username", username); put("password", password); put(MIRROR, mirror); }}; }
Source:
public void setDefinitions(List<Definition> definitions) { START this.m_definitions = definitions; END } this.m_

Target:
public void setDefinitions(List<Definition> definitions) { m_definitions = definitions; }
Source:
protected void cleanUp(UserAccount userAccount) { SalesforceAnalyticsManager.reset(userAccount); RestClient.clearCaches(userAccount); START UserAccountManager.getInstance().clearCachedCurrentUser(userAccount); END } We also need to clear the cache when user switching occurs.

Target:
protected void cleanUp(UserAccount userAccount) { SalesforceAnalyticsManager.reset(userAccount); RestClient.clearCaches(userAccount); UserAccountManager.getInstance().clearCachedCurrentUser(); }
Source:
protected static int parseFraction(String string, int sign, String text) { if (string == null || string.length() == 0) { return 0; } try { string = (string + "000000000").substring(0, 9); return Integer.parseInt(string) * sign; } catch (NumberFormatException | ArithmeticException e) { START throw (DateTimeParseException) new DateTimeParseException( END "Text cannot be parsed to a PeriodAndDuration: fraction", text, 0).initCause(e); } } I'm probably missing something, why not using the constructor taking a Throwable?

Target:
protected static int parseFraction(String string, int sign, String text) { if (string == null || string.length() == 0) { return 0; } try { string = (string + "000000000").substring(0, 9); return Integer.parseInt(string) * sign; } catch (NumberFormatException | ArithmeticException e) { throw new DateTimeParseException("Text cannot be parsed to a PeriodAndDuration: fraction", text, 0, e); } }
Source:
public IASTName[] getNames() { IASTName[] result = new IASTName[fQualifierPos + (fLastName == null ? 1 : 2)]; int idx = 0; START for (ICPPASTNameSpecifier nameSpecifier : getQualifier()) END if (nameSpecifier instanceof IASTName) result[idx++] = (IASTName) nameSpecifier; else throw new UnsupportedOperationException("Can't use getNames() on a " + //$NON-NLS-1$ "qualified name that includes a decltype-specifier. Use " + //$NON-NLS-1$ "getQualifier() and getLastName() instead"); //$NON-NLS-1$ if (fLastName != null) result[fQualifierPos + 1] = fLastName; return result; } Please always use curly braces in 'for' statements.

Target:
public IASTName[] getNames() { IASTName[] result = new IASTName[fQualifierPos + (fLastName == null ? 1 : 2)]; int idx = 0; for (ICPPASTNameSpecifier nameSpecifier : getQualifier()) { if (nameSpecifier instanceof IASTName) { result[idx++] = (IASTName) nameSpecifier; } else { throw new UnsupportedOperationException("Can't use getNames() on a " + //$NON-NLS-1$ "qualified name that includes a decltype-specifier. Use " + //$NON-NLS-1$ "getQualifier() and getLastName() instead"); //$NON-NLS-1$ } } if (fLastName != null) result[fQualifierPos + 1] = fLastName; return result; }
Source:
private String getConsoleModelErrorMessage(Object sender, ErrorCodeEventArgs e) { String translatedError = consoleErrorCodeTranslator.translateErrorCode(e.getErrorCode()); if (sender instanceof SpiceConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingSpiceMsg(translatedError); } else if (sender instanceof RdpConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingRdpMsg(translatedError); } START throw new IllegalArgumentException("Message recieved from an unknown model " + sender.getClass().getName()); //$NON-NLS-1$ END } who catches that? I'd return a message instead;

Target:
private String getConsoleModelErrorMessage(Object sender, ErrorCodeEventArgs e) { String translatedError = consoleErrorCodeTranslator.translateErrorCode(e.getErrorCode()); if (sender instanceof SpiceConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingSpiceMsg(translatedError); } else if (sender instanceof RdpConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingRdpMsg(translatedError); } return translatedError; }
Source:
public final void setExtendedExpiresOn(final Date extendedExpiresOn) { START this.mExtendedExpiresOn = extendedExpiresOn; END } > this [](start = 8, length = 4) no this. please

Target:
public final void setExtendedExpiresOn(final Date extendedExpiresOn) { mExtendedExpiresOn = extendedExpiresOn; }
Source:
public static void mkdir(final File d, boolean skipExisting) throws IOException { START if (skipExisting && d.exists() && d.isDirectory()) END return; if (!d.mkdir()) throw new IOException(MessageFormat.format( JGitText.get().mkDirFailed, d.getAbsolutePath())); } I would put this on the failure path: if (!d.mkdir()) { if (skipExisting && d.isDirectory()) return; throw new IOException(...); } Because odds are the caller wants to make a new directory and we can reasonably assume it doesn't exist yet. If it does, we'll fail on the mkdir and check its mode, if its a directory, we're fine, if its not, we fail.

Target:
public static void mkdir(final File d, boolean skipExisting) throws IOException { if (!d.mkdir()) { if (skipExisting && d.isDirectory()) return; throw new IOException(MessageFormat.format( JGitText.get().mkDirFailed, d.getAbsolutePath())); } }
Source:
protected void initDiskVmElement() { setDiskVmElement(new DiskVmElement(new START VmDeviceId(null, null))); END } IMHO can you a no-argument C'tor.

Target:
protected void initDiskVmElement() { setDiskVmElement(new DiskVmElement()); }
Source:
public void setHtmlTemplate(FreemarkerTemplate htmlTemplate) { START if (this.getUseFreemarkerTemplate()) END { set(LANDING_PAGE_HTML_TEMPLATE, htmlTemplate); } } better to remove if if statement, just set the value, the user of the entity can than use the getUseFreemarkerTemplate function to choose to use the template of not.

Target:
public void setHtmlTemplate(FreemarkerTemplate htmlTemplate) { set(LANDING_PAGE_HTML_TEMPLATE, htmlTemplate); }
Source:
public PhysicalOperation visitExchange(ExchangeNode node, LocalExecutionPlanContext context) { checkArgument(node.getScope() == LOCAL, "Only local exchanges are supported in the local planner"); if (node.getOrderingScheme().isPresent()) { return createLocalMerge(node, context); } else { return createLocalExchange(node, context); START } END } nit: it seems like we prefer to not put else after return elsewhere in the codebase

Target:
public PhysicalOperation visitExchange(ExchangeNode node, LocalExecutionPlanContext context) { checkArgument(node.getScope() == LOCAL, "Only local exchanges are supported in the local planner"); if (node.getOrderingScheme().isPresent()) { return createLocalMerge(node, context); } return createLocalExchange(node, context); }
Source:
public void onCreated(Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException { START for (Object event1 : events) { END CacheEntryEvent event = (CacheEntryEvent) event1; Assert.assertEquals(EventType.CREATED, event.getEventType()); this.created.incrementAndGet(); event.getKey(); event.getValue(); event.getSource(); } } This could be typed as CacheEntryEvent<? extends K, ? extends V> and the cast wouldn't be needed on the next line.

Target:
public void onCreated(Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException { for (CacheEntryEvent<? extends K, ? extends V> event : events) { Assert.assertEquals(EventType.CREATED, event.getEventType()); this.created.incrementAndGet(); } }
Source:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); //request code should be unique for each call for pending intent so we have taken requestcode //as keyId which is unique for each call as keyId is unique for each passphrase START long requestcode = keyId; END return PendingIntent.getBroadcast(context, (int)requestcode, intent, PendingIntent.FLAG_CANCEL_CURRENT); } this line is redundant, you can use keyId directly

Target:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); //request code should be unique for each call for pending intent so we have taken requestcode //as keyId which is unique for each call as keyId is unique for each passphrase return PendingIntent.getBroadcast(context, (int)keyId, intent, PendingIntent.FLAG_CANCEL_CURRENT); }
Source:
START public boolean hasTxLogs() throws RuntimeException END { File[] files = storeDir.listFiles( LogFiles.FILENAME_FILTER ); if ( files == null ) { throw new RuntimeException( "Files was null. Incorrect directory or I/O error?" ); } return files.length > 0; } Does it make sense to declare `throws RuntimeException`?

Target:
public boolean hasTxLogs() { File[] files = storeDir.listFiles( LogFiles.FILENAME_FILTER ); if ( files == null ) { throw new RuntimeException( "Files was null. Incorrect directory or I/O error?" ); } return files.length > 0; }
Source:
public void setTaskScheduler(TaskScheduler taskScheduler) { START setTaskScheduler(taskScheduler); END } ??? Does it work? Really it has to be `super.`. IDEA shows the recursion for me

Target:
public void setTaskScheduler(TaskScheduler taskScheduler) { super.setTaskScheduler(taskScheduler); }
Source:
START public Constant(Sort sort, String value) { END super(sort, null); this.value = value; } Oh right, I remember, the parser does some funky stuff internally with the Token and KList classes. Okay. I am persuaded that it makes sense to go this route for now. Please make sure it is clear that developers should never call this constructor from outside the parser kernel, then.

Target:
public Constant(Sort sort, String value) { super(sort, null); assert value != null; this.value = value; }
Source:
private void addCriteriaForFlows(final OnmsCriteria criteria, final Boolean hasFlows) { START if (hasFlows == null) { END return; } criteria.add(Restrictions.eq("node.hasFlows", hasFlows)); } This is a duplicated check, as this is only invoked after `command.hasFlows()` is true, so not required to invoke it again. If you absolutely want this check, I'd opt for ```java if (hasFlows != null) { ... } ``` as it is much easier to read.

Target:
private void addCriteriaForFlows(final OnmsCriteria criteria, final Boolean hasFlows) { criteria.add(Restrictions.eq("node.hasFlows", hasFlows)); }
Source:
public List<String> getJobsForAnExtension(final String extensionName) throws FalconException { List<ExtensionJobsBean> extensionJobs = metaStore.getJobsForAnExtension(extensionName); if (null != extensionJobs && !extensionJobs.isEmpty()){ List<String> extensionJobNames = new ArrayList<>(); for (ExtensionJobsBean extensionJobsBean: extensionJobs) { extensionJobNames.add(extensionJobsBean.getJobName()); } return extensionJobNames; START } else { END return null; } } It is always good to return an empty list instead. Avoids NPEs

Target:
public List<String> getJobsForAnExtension(final String extensionName) throws FalconException { List<ExtensionJobsBean> extensionJobs = metaStore.getJobsForAnExtension(extensionName); List<String> extensionJobNames = new ArrayList<>(); if (null != extensionJobs && !extensionJobs.isEmpty()) { for (ExtensionJobsBean extensionJobsBean : extensionJobs) { extensionJobNames.add(extensionJobsBean.getJobName()); } } return extensionJobNames; }
Source:
public void handleEvent(EventBundle events) { for (Event event : events) { START if (DOCUMENT_REMOVED.equals(event.getName())) { END DocumentEventContext context = (DocumentEventContext) event.getContext(); DocumentModel docModel = context.getSourceDocument(); if (DOCUMENT_ROUTE_DOCUMENT_TYPE.equals(docModel.getType())) { deleteOrphanTasks(context.getCoreSession(), docModel.getId()); } } } } This test is not needed since the event bundle is filtered regarding the events defined to trigger the listener in its descriptor.

Target:
public void handleEvent(EventBundle events) { for (Event event : events) { DocumentEventContext context = (DocumentEventContext) event.getContext(); DocumentModel docModel = context.getSourceDocument(); if (DOCUMENT_ROUTE_DOCUMENT_TYPE.equals(docModel.getType())) { deleteOrphanTasks(context.getCoreSession(), docModel.getId()); } } }
Source:
public Set<Order> getOrders() { if (orders == null) { START orders = new LinkedHashSet<Order>(); END } return orders; } Yes am assuming it should be a SortedSet and the ordering would be based on the sortWeight of the orders.

Target:
public List<Order> getOrders() { if (orders == null) { orders = new ArrayList<Order>(); } return orders; }
Source:
private void executeIdentifier(IdentifierTree tree) { Symbol symbol = tree.symbol(); SymbolicValue value = programState.getValue(symbol); if (value == null) { value = constraintManager.createSymbolicValue(tree); programState = programState.stackValue(value); learnIdentifierNullConstraints(tree, value); programState = programState.put(symbol, value); } else { programState = programState.stackValue(value); START programState = programState.put(symbol, value); END } } The call to `put` can be extracted from the `if-else` statement in order to remove the duplication.

Target:
private void executeIdentifier(IdentifierTree tree) { Symbol symbol = tree.symbol(); SymbolicValue value = programState.getValue(symbol); if (value == null) { value = constraintManager.createSymbolicValue(tree); programState = programState.stackValue(value); learnIdentifierNullConstraints(tree, value); } else { programState = programState.stackValue(value); } programState = programState.put(symbol, value); }
Source:
START public AutoRegisterModules(String END pluginName, PluginGuiceEnvironment env, JarFile jarFile, ClassLoader classLoader) { this.pluginName = pluginName; this.env = env; this.jarFile = jarFile; this.classLoader = classLoader; this.sshGen = env.hasSshModule() ? env.newSshModuleGenerator() : null; this.httpGen = env.hasHttpModule() ? env.newHttpModuleGenerator() : null; } Not needed in this change.

Target:
AutoRegisterModules(String pluginName, PluginGuiceEnvironment env, JarFile jarFile, ClassLoader classLoader) { this.pluginName = pluginName; this.env = env; this.jarFile = jarFile; this.classLoader = classLoader; this.sshGen = env.hasSshModule() ? env.newSshModuleGenerator() : null; this.httpGen = env.hasHttpModule() ? env.newHttpModuleGenerator() : null; }
Source:
public boolean checkIfJobHasTasks(Guid jobId) { List<Step> steps = step.getStepsByJobIdForVdsmAndGluster(jobId); START return steps.size() > 0; END } Please use: return !steps.isEmpty();

Target:
public boolean checkIfJobHasTasks(Guid jobId) { List<Step> steps = step.getStepsByJobIdForVdsmAndGluster(jobId); return !steps.isEmpty(); }
Source:
public String getUserNameForChannel(UUID channelId) throws UnauthenticatedException { START END try (LockResource clientsLockShared = new LockResource(mClientsLock.readLock())) { if (mChannels.containsKey(channelId)) { AuthenticatedChannelInfo clientInfo = mChannels.get(channelId); return mChannels.get(channelId).getUserName(); } else { throw new UnauthenticatedException( String.format("Client:%s needs to be authenticated", channelId.toString())); } } } nit: extra space

Target:
public String getUserNameForChannel(UUID channelId) throws UnauthenticatedException { if (mChannels.containsKey(channelId)) { AuthenticatedChannelInfo clientInfo = mChannels.get(channelId); return clientInfo.getUserName(); } else { throw new UnauthenticatedException( String.format("Client:%s needs to be authenticated", channelId.toString())); } }
Source:
public static boolean isValidSingleVersion( final String version ) { boolean result = true; if ( version == null || version.trim().length() < 1 ) { START result = false; END } try { SingleVersion singleVersion = new VersionParser( version ).single(); } catch ( final ParseException e ) { result = false; } catch ( final TokenMgrError e ) { result = false; } return result; } I'd just go ahead and return false here. The logic you have here doesn't prevent trying to parse when the input value is null or empty. And when you have that fixed, go ahead and merge at will. :smiley:

Target:
public static boolean isValidSingleVersion( final String version ) { boolean result = true; if ( version == null || version.trim().length() < 1 ) { return false; } try { SingleVersion singleVersion = new VersionParser( version ).single(); } catch ( final ParseException e ) { result = false; } catch ( final TokenMgrError e ) { result = false; } return result; }
Source:
public void handle(DataServerConnection connection, int rpcType, ByteBuf pBody, ByteBuf dBody, ResponseSender sender) throws RpcException { switch (rpcType) { case RpcType.REQ_RUNTIME_FILTER_VALUE : { handleRuntimeFilterRequest(pBody, dBody, sender); } START case RpcType.REQ_RECORD_BATCH_VALUE : { END handleRecordBatchRequest(pBody, dBody, sender); } default: throw new RpcException("Not yet supported."); } } `break` statement is missing here and below

Target:
public void handle(DataServerConnection connection, int rpcType, ByteBuf pBody, ByteBuf dBody, ResponseSender sender) throws RpcException { switch (rpcType) { case RpcType.REQ_RUNTIME_FILTER_VALUE : { handleRuntimeFilterRequest(pBody, dBody, sender); break; } case RpcType.REQ_RECORD_BATCH_VALUE : { handleRecordBatchRequest(pBody, dBody, sender); break; } default: throw new RpcException("Not yet supported."); } }
Source:
public Builder addModifiers(Modifier... modifiers) { START this.modifiers.addAll(Arrays.asList(modifiers)); END return this; } `Collections.addAll` saves the wrapper object... although we don't need to go full-on nit picky on allocations like we would something in a library.

Target:
public Builder addModifiers(Modifier... modifiers) { Collections.addAll(this.modifiers, modifiers); return this; }