auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public DataInputNavigableJsonAdapter(BufferObjectDataInput input, int initialOffset) { this.input = input; this.initialOffset = initialOffset; START } END Do we need to set the input position to the initial offset?

Target:
public DataInputNavigableJsonAdapter(BufferObjectDataInput input, int initialOffset) { this.input = input; this.input.position(initialOffset); this.initialOffset = initialOffset; }
Source:
protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree argument = mit.arguments().get(1); Type type = argument.symbolType(); START if (type.isUnknown()) { END return; } if (ExpressionsHelper.isNotSerializable(argument)) { String andParameters = JUtils.isParametrized(type) ? " and its parameters" : ""; reportIssue(argument, "Make \"" + type + "\"" + andParameters + " serializable or don't store it in the session."); } } So it means that an argument with unknown type is considered as not serializable? Should we consider making the unknown check inside `isNotSerializable` and provide the same behavior for all rules using it? I'm saying this since the other rule (S2118) using `isNotSerializable` is also reporting an arguable issue with a similar message if we run it against an unknown type. > Make the "!Unknown!" class "Serializable" or don't write it.

Target:
protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree argument = mit.arguments().get(1); Type type = argument.symbolType(); if (ExpressionsHelper.isNotSerializable(argument)) { String andParameters = JUtils.isParametrized(type) ? " and its parameters" : ""; reportIssue(argument, "Make \"" + type.name() + "\"" + andParameters + " serializable or don't store it in the session."); } }
Source:
public Predicate createPredicateAndJoin(String filterString, Root<T> root) { LogicalOperatorRulesLexer lexer = new LogicalOperatorRulesLexer(new ANTLRInputStream(filterString)); LogicalOperatorRulesParser parser = new LogicalOperatorRulesParser(new CommonTokenStream(lexer)); parser.addErrorListener(new OsiamAntlrErrorListener()); ParseTree tree = parser.parse(); EvalVisitor<T> visitor = new EvalVisitor<>(this, root); START return (Predicate) visitor.visit(tree); END } Is this cast still necessary?

Target:
public Predicate createPredicateAndJoin(String filterString, Root<T> root) { LogicalOperatorRulesLexer lexer = new LogicalOperatorRulesLexer(new ANTLRInputStream(filterString)); LogicalOperatorRulesParser parser = new LogicalOperatorRulesParser(new CommonTokenStream(lexer)); parser.addErrorListener(new OsiamAntlrErrorListener()); ParseTree tree = parser.parse(); EvalVisitor<T> visitor = new EvalVisitor<>(this, root); return visitor.visit(tree); }
Source:
START public Privilege[] getSupportedPrivileges(String path) throws PathNotFoundException, RepositoryException { END return privileges.listOfSupported(); } Remove the exceptions, since they're never thrown from the method.

Target:
public Privilege[] getSupportedPrivileges(String path) { return privileges.listOfSupported(); }
Source:
protected AbstractSessionPresenter(final SessionManager sessionManager, final SessionPresenter.View view, final Optional<? extends ToolbarFactory<S>> toolbarFactory, final Optional<PaletteWidgetFactory<DefinitionSetPalette, ?>> paletteFactory, final NotificationsObserver notificationsObserver) { this.sessionManager = sessionManager; START this.toolbarFactory = toolbarFactory.orElse(null); END this.paletteFactory = paletteFactory.orElse(null); this.notificationsObserver = notificationsObserver; this.view = view; this.hasToolbar = true; this.hasPalette = true; } I'd have thought preserving the use of ```Optional``` in the class's implementation would be nicer than just using ```Optional``` on the constructor and then reverting to ```null``` _inside_ the class.

Target:
protected AbstractSessionPresenter(final SessionManager sessionManager, final SessionPresenter.View view, final Optional<? extends ToolbarFactory<S>> toolbarFactory, final Optional<PaletteWidgetFactory<DefinitionSetPalette, ?>> paletteFactory, final NotificationsObserver notificationsObserver) { this.sessionManager = sessionManager; this.toolbarFactory = (Optional<ToolbarFactory<S>>) toolbarFactory; this.paletteFactory = paletteFactory; this.notificationsObserver = notificationsObserver; this.view = view; this.hasToolbar = true; this.hasPalette = true; }
Source:
START public void prepareToNewMarker() { END drawerLayout.closeDrawers(); setLongClickListener(true); setToastMarkerInfo(); } czy to musi byc publiczne?

Target:
private void prepareToNewMarker() { drawerLayout.closeDrawers(); setLongClickListener(); setToastMarkerInfo(); }
Source:
START private MVCCEntry wrapMvccEntryForPut(InvocationContext ctx, Object key, CacheEntry cacheEntry, Metadata providedMetadata, boolean skipRead) { END if (cacheEntry instanceof MVCCEntry) { MVCCEntry mvccEntry = (MVCCEntry) cacheEntry; updateMetadata(mvccEntry, providedMetadata); return mvccEntry; } return wrapInternalCacheEntryForPut(ctx, key, (InternalCacheEntry) cacheEntry, providedMetadata, true); } The skipRead parameter isn't used.

Target:
private MVCCEntry wrapMvccEntryForPut(InvocationContext ctx, Object key, CacheEntry cacheEntry, Metadata providedMetadata, boolean skipRead) { if (cacheEntry instanceof MVCCEntry) { MVCCEntry mvccEntry = (MVCCEntry) cacheEntry; updateMetadata(mvccEntry, providedMetadata); return mvccEntry; } return wrapInternalCacheEntryForPut(ctx, key, (InternalCacheEntry) cacheEntry, providedMetadata, skipRead); }
Source:
public SERVICE_FAILURE_ACTIONS getFailureActions() { Pointer buffer = queryServiceConfig2(Winsvc.SERVICE_CONFIG_FAILURE_ACTIONS); SERVICE_FAILURE_ACTIONS result = new SERVICE_FAILURE_ACTIONS(buffer); START result.read(); END return result; } You should make the `read()` call part of the `SERVICE_FAILURE_ACTIONS(Pointer)` constructor.

Target:
public SERVICE_FAILURE_ACTIONS getFailureActions() { Pointer buffer = queryServiceConfig2(Winsvc.SERVICE_CONFIG_FAILURE_ACTIONS); SERVICE_FAILURE_ACTIONS result = new SERVICE_FAILURE_ACTIONS(buffer); return result; }
Source:
void fun(String strPath, String StrParent, String StrChild, String prefix, String suffix, java.net.URI uri) throws Exception { // Questionable: check what is done with this file new File(strPath); // Noncompliant new File(StrParent, StrChild); // Noncompliant {{Make sure this file handling is safe here.}} File parent = new File(uri); // Noncompliant new File(parent, StrChild); // compliant we rely on the fact that parent should be highlighted START File.createTempFile(prefix, suffix); // Noncompliant END } I would add the other createTempFile method to enforce the fact that we explicitly target this one only.

Target:
void fun(String strPath, String StrParent, String StrChild, String prefix, String suffix, java.net.URI uri) throws Exception { // Questionable: check what is done with this file new File(strPath); // Noncompliant new File(StrParent, StrChild); // Noncompliant {{Make sure this file handling is safe here.}} File parent = new File(uri); // Noncompliant new File(parent, StrChild); // compliant we rely on the fact that parent should be highlighted File.createTempFile(prefix, suffix); // Noncompliant File.createTempFile(prefix, suffix, parent); // compliant }
Source:
public ValidationResult vmNotHavingPciPassthroughDevices() { for (VM vm : vms) { if (getHostDeviceManager().checkVmNeedsPciDevices(vm.getId())) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_HAS_ATTACHED_PCI_HOST_DEVICES, START String.format("$VmName %s", vm.getName())); END } } return ValidationResult.VALID; } I see that VmName in not included in the error message.. not sure if the right thing to do is to include it in the message or not to set it here

Target:
public ValidationResult vmNotHavingPciPassthroughDevices() { for (VM vm : vms) { if (getHostDeviceManager().checkVmNeedsPciDevices(vm.getId())) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_HAS_ATTACHED_PCI_HOST_DEVICES); } } return ValidationResult.VALID; }
Source:
public void onError(Throwable e) { START e.printStackTrace(); END try { FileLfsServlet.sendError(response, HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage()); context.complete(); in.close(); } catch (IOException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } } did you want to log this exception ?

Target:
public void onError(Throwable e) { try { FileLfsServlet.sendError(response, HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage()); context.complete(); in.close(); } catch (IOException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } }
Source:
public String pop() { START String value = lines.remove(lines.lastKey()); END return value; } Return could be simplified: `return lines.remove(lines.lastKey());` :)

Target:
public String pop() { return lines.remove(lines.lastKey()); }
Source:
public void onDestroyView() { mapView.onDestroy(); mapboxMap = null; unbinder.unbind(); unbinder = null; START WikipediaApp.getInstance().getRefWatcher().watch(this); END super.onDestroyView(); } Shouldn't this be in onDestroy?

Target:
public void onDestroyView() { mapView.onDestroy(); mapboxMap = null; unbinder.unbind(); unbinder = null; super.onDestroyView(); }
Source:
private static SampleTissueProcessingDto asTissueProcessingSampleDto(SampleTissueProcessing from) { SampleTissueProcessingDto dto = null; START if (from.getClass() == SampleCVSlideImpl.class) { END dto = asCVSlideSampleDto((SampleCVSlide) from); } else if (from.getClass() == SampleLCMTubeImpl.class) { dto = asLCMTubeSampleDto((SampleLCMTube) from); } else { dto = new SampleTissueProcessingDto(); } return dto; } getClass comparison is required for Dtos because of the way their inheritance works (analyte is also a tissue and an identity for the purpose of including parent data), but instanceof should be used here (and typically for the non-dto models), and check vs. interfaces for flexibility. e.g. we could add another implementation of SampleCVSlide that this method should still work for, or we could subclass SampleCVSlideImpl (however unlikely)

Target:
private static SampleTissueProcessingDto asTissueProcessingSampleDto(SampleTissueProcessing from) { SampleTissueProcessingDto dto = null; if (from instanceof SampleCVSlideImpl) { dto = asCVSlideSampleDto((SampleCVSlide) from); } else if (from.getClass() == SampleLCMTubeImpl.class) { dto = asLCMTubeSampleDto((SampleLCMTube) from); } else { dto = new SampleTissueProcessingDto(); } return dto; }
Source:
public void testMakeTimeZone_NoOffsets() throws IOException { START END int[][] times = {}; int[][] offsets = {}; try { createZoneInfo(times, offsets); fail("Did not detect no transitions"); } catch (IllegalStateException expected) { // Expected this to happen } } Unnecessary new line here and below: why leave the first line blank? (unless there's a wrap in the signature, in which case it can help to differentiate between the signature and the body).

Target:
public void testMakeTimeZone_NoOffsets() throws Exception { int[][] times = {}; int[][] offsets = {}; try { createZoneInfo(times, offsets); fail("Did not detect no transitions"); } catch (IllegalStateException expected) { // Expected this to happen } }
Source:
DeploymentToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations, GroupNamingConvention.Factory namingConvention, OSImageToImage osImageToImage, RoleSizeToHardware roleSizeToHardware, Map<String, Credentials> credentialStore) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); this.locations = checkNotNull(locations, "locations"); this.osImageToImage = checkNotNull(osImageToImage, "osImageToImage"); this.roleSizeToHardware = checkNotNull(roleSizeToHardware, "roleSizeToHardware"); START this.credentialStore = checkNotNull(credentialStore, "credentialStore cannot be null"); END } Since the constructor is package private and only the Guice injector will be able to call it, you can remove all the null checks. The injector will already fail if any parameter is missing.

Target:
DeploymentToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations, GroupNamingConvention.Factory namingConvention, OSImageToImage osImageToImage, RoleSizeToHardware roleSizeToHardware, Map<String, Credentials> credentialStore) { this.nodeNamingConvention = namingConvention.createWithoutPrefix(); this.locations = locations; this.osImageToImage = osImageToImage; this.roleSizeToHardware = roleSizeToHardware; this.credentialStore = credentialStore; }
Source:
public AsyncContext startAsync() throws IllegalStateException { if (_asyncNotSupportedSource != null) throw new IllegalStateException("!asyncSupported: " + _asyncNotSupportedSource); HttpChannelState state = getHttpChannelState(); if (_async == null) _async = new AsyncContextState(state); START AsyncContextEvent event = new AsyncContextEvent(_context, _async, state, this, this, getResponse(), false); END state.startAsync(event); return _async; } I wonder if you shouldn't keep the old constructor here, and not use an extra boolean argument.

Target:
public AsyncContext startAsync() throws IllegalStateException { if (_asyncNotSupportedSource != null) throw new IllegalStateException("!asyncSupported: " + _asyncNotSupportedSource); HttpChannelState state = getHttpChannelState(); if (_async == null) _async = new AsyncContextState(state); AsyncContextEvent event = new AsyncContextEvent(_context, _async, state, this, this, getResponse()); state.startAsync(event); return _async; }
Source:
CompletableFuture<Void> getFailureOp(CommitData cd) { START return CompletableFuture.supplyAsync(() -> { END try { rollbackLocks(cd); } catch (Exception e) { throw new CompletionException(e); } return null; }, env.getSharedResources().getSyncCommitExecutor()); } After `throws Exception` is dropped from rollbackLocks, seems like this code should be : ```java CompletableFuture<Void> getFailureOp(CommitData cd) { return rollbackLocks(cd); } ```

Target:
CompletableFuture<Void> getFailureOp(CommitData cd) { return rollbackLocks(cd); }
Source:
private boolean isGuavaPrecondition(Symbol.MethodSymbol symbol) { return symbol.owner().type().is("com.google.common.base.Preconditions") START && ("checkNotNull".equals(symbol.name()) || "checkArgument".equals(symbol.name()) || "checkState".equals(symbol.name()) ); END } symbol.name() called 3 times? maybe worth a dedicated variable.

Target:
private boolean isGuavaPrecondition(Symbol.MethodSymbol symbol) { String name = symbol.name(); return symbol.owner().type().is("com.google.common.base.Preconditions") && ("checkNotNull".equals(name) || "checkArgument".equals(name) || "checkState".equals(name) ); }
Source:
public void loadTrace(ITmfTrace trace) { START cancelUpdate(); END super.loadTrace(trace); initializeDataProvider(); } We had that cancelUpdate() at the beginning of updateContent(). Now the UpdateThread doesn't get cancelled with TmfXYChartViewer.windowRangeUpdated() and TmfCommonXAxisChartViewer.setNbPoints().

Target:
public void loadTrace(ITmfTrace trace) { super.loadTrace(trace); initializeDataProvider(); }
Source:
public StringInputRowParser( @JsonProperty("parseSpec") ParseSpec parseSpec, @JsonProperty("encoding") String encoding ) { this.parseSpec = parseSpec; this.mapParser = new MapInputRowParser(parseSpec); this.parser = parseSpec.makeParser(); START parser.startFileFromBeginning(); END if (encoding != null) { this.charset = Charset.forName(encoding); } else { this.charset = DEFAULT_CHARSET; } } StringInputRowParser is used by parser options that aren't file-oriented (you can use it on streams etc) so this isn't a good place to put this. imo, this should replace `reset()` and be called in places that `reset()` is currently called (like FileIteratingFirehose). With one addition: it needs to be called before the very first file too.

Target:
public StringInputRowParser( @JsonProperty("parseSpec") ParseSpec parseSpec, @JsonProperty("encoding") String encoding ) { this.parseSpec = parseSpec; this.mapParser = new MapInputRowParser(parseSpec); this.parser = parseSpec.makeParser(); if (encoding != null) { this.charset = Charset.forName(encoding); } else { this.charset = DEFAULT_CHARSET; } }
Source:
public Object getNegotiatedProperty(String propName) { assertComplete(); switch (propName) { case Sasl.QOP: return selectedQop.getName(); case Sasl.MAX_BUFFER: return Integer.toString(actualMaxReceiveBuffer != 0 ? actualMaxReceiveBuffer : configuredMaxReceiveBuffer); case Sasl.RAW_SEND_SIZE: return Integer.toString(maxBuffer); } START return super.getNegotiatedProperty(propName); END } The superclass only repeats the assertComplete() call. I don't think this PR adds any value.

Target:
public Object getNegotiatedProperty(String propName) { assertComplete(); switch (propName) { case Sasl.QOP: return selectedQop.getName(); case Sasl.MAX_BUFFER: return Integer.toString(actualMaxReceiveBuffer != 0 ? actualMaxReceiveBuffer : configuredMaxReceiveBuffer); case Sasl.RAW_SEND_SIZE: return Integer.toString(maxBuffer); } return null; }
Source:
public static BooleanExpression asBoolean(boolean value) { START return asBoolean(Expressions.constant(value)); END } this is inside Expressions, so maybe just `asBoolean(constant(value))`, the same with the others

Target:
public static BooleanExpression asBoolean(boolean value) { return asBoolean(constant(value)); }
Source:
public void startPolicyEnforcement() throws IOException { if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Starting time based retention policy enforcement with retainMillis=" + m_retainMillis + " for PBD " + m_pbd.getNonce()); } m_reader = m_pbd.openForRead(CURSOR_NAME); START scheduleTaskFor(m_pbd.getNonce(), ()->deleteOldSegments(), 0); END } You can do `this::deleteOldSegments` for the callable. It is more efficient lambda form

Target:
public void startPolicyEnforcement() throws IOException { if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Starting time based retention policy enforcement with retainMillis=" + m_retainMillis + " for PBD " + m_pbd.getNonce()); } m_reader = m_pbd.openForRead(CURSOR_NAME); scheduleTaskFor(m_pbd.getNonce(), this::deleteOldSegments, 0); }
Source:
public void afterRun() throws Exception { if (recordStore.isWanReplicationEnabled()) { CacheRecord record = recordStore.getRecord(key); if (record != null) { publishWanUpdate(key, record); START } else { END publishWanRemove(key); } } super.afterRun(); } Do you need to guard against `null` here as well?

Target:
public void afterRun() throws Exception { if (recordStore == null) { return; } if (recordStore.isWanReplicationEnabled()) { CacheRecord record = recordStore.getRecord(key); if (record != null) { publishWanUpdate(key, record); } else { publishWanRemove(key); } } super.afterRun(); }
Source:
protected String getConfigRoot() { START return ClientConfigSections.HAZELCAST_CLIENT.name.toLowerCase(); END } `toLowerCase`

Target:
protected String getConfigRoot() { return ClientConfigSections.HAZELCAST_CLIENT.name; }
Source:
START public synchronized int getCapacity() { END return capacity; } Does this method have to be synchronized, considering that `capacity` is `final`?

Target:
public int getCapacity() { return capacity; }
Source:
private Set<IArtifactType> getAllArtTypes() { Set<IArtifactType> allArtTypes = new HashSet<>(); if (artifactTypes == null || !artifactTypes.isEmpty()) { START allArtTypes.addAll(artifactTypes); END } else { getArtifactTypesFromWorkItemTypes(); } return allArtTypes; } why add 'null' to allArtTypes?

Target:
private Set<IArtifactType> getAllArtTypes() { Set<IArtifactType> allArtTypes = new HashSet<>(); if (artifactTypes != null || !artifactTypes.isEmpty()) { allArtTypes.addAll(artifactTypes); } else { allArtTypes = getArtifactTypesFromWorkItemTypes(); } return allArtTypes; }
Source:
public void testContextListenerIsSet() throws Exception { try (WizardCommandController tester = testHarness.createWizardController(MyFirstWizard.class)) { tester.initialize(); Assert.assertTrue("Wizard is not on a valid state", tester.isValid()); Assert.assertTrue("Listener is not set", listener.isContextInitialized()); tester.execute(); START Assert.assertFalse("Listener is still set", listener.isContextInitialized()); END } } This should be moved outside the try block

Target:
public void testContextListenerIsSet() throws Exception { try (WizardCommandController tester = testHarness.createWizardController(MyFirstWizard.class)) { tester.initialize(); Assert.assertTrue("Wizard is not on a valid state", tester.isValid()); Assert.assertTrue("Listener is not set", listener.isContextInitialized()); tester.execute(); } Assert.assertFalse("Listener is still set", listener.isContextInitialized()); }
Source:
START private Later(F0<A> producer) { END this.memo = P.hardMemo(producer); } package private

Target:
Later(F0<A> producer) { this.memo = P.hardMemo(producer); }
Source:
private boolean isRunningFromCommandLine() { boolean runningFromCommandLine = false; // first look up all OptionProcessors and see if running from command line option is set Collection<? extends OptionProcessor> optionProcessors = Lookup.getDefault().lookupAll(OptionProcessor.class); Iterator<? extends OptionProcessor> optionsIterator = optionProcessors.iterator(); while (optionsIterator.hasNext()) { // find CommandLineOptionProcessor OptionProcessor processor = optionsIterator.next(); if (!(processor instanceof CommandLineOptionProcessor)) { continue; } // check if we are running from command line runningFromCommandLine = ((CommandLineOptionProcessor) processor).isRunFromCommandLine(); return runningFromCommandLine; } return false; START } END Codacy flagged this method for "Avoid using a branching statement as the last in a loop." I think that is a reasonable call by Codacy and the code would be easier to read if runningFromCommandLine was set to true in the loop, followed by a break, and a single method return of runningFromCommandLine on what is currently line 136. Alternatively, one could also do away with runningFromCommandLine and have a return true statement in the loop, but I think the first alternative may be a little easier to read and will make Codacy content.

Target:
private boolean isRunningFromCommandLine() { // first look up all OptionProcessors and see if running from command line option is set Collection<? extends OptionProcessor> optionProcessors = Lookup.getDefault().lookupAll(OptionProcessor.class); Iterator<? extends OptionProcessor> optionsIterator = optionProcessors.iterator(); while (optionsIterator.hasNext()) { // find CommandLineOptionProcessor OptionProcessor processor = optionsIterator.next(); if ((processor instanceof CommandLineOptionProcessor)) { // check if we are running from command line return ((CommandLineOptionProcessor) processor).isRunFromCommandLine(); } } return false; }
Source:
START public Boolean onReceivedHttpAuthRequest(CordovaWebView view, ICordovaHttpAuthHandler handler, String host, String realm) { END for (CordovaPlugin plugin : this.pluginMap.values()) { if (plugin != null && plugin.onReceivedHttpAuthRequest(view, handler, host, realm)) { return true; } } return false; } Unless you want this to be tri-state, then "Boolean" should be "boolean". I don't see the need for tristate, so go with "boolean"

Target:
public boolean onReceivedHttpAuthRequest(CordovaWebView view, ICordovaHttpAuthHandler handler, String host, String realm) { for (CordovaPlugin plugin : this.pluginMap.values()) { if (plugin != null && plugin.onReceivedHttpAuthRequest(view, handler, host, realm)) { return true; } } return false; }
Source:
private String createAndGetLockPath() throws InterruptedException, KeeperException { // Create locks if it does not exist START if (zk.exists(lockPath.toString(), false) == null) { END try { Util.mkdir(zk, lockPath.toString(), ZooDefs.Ids.OPEN_ACL_UNSAFE); } catch (CloudnameException e) { log.log( java.util.logging.Level.INFO, "CloudnameException while trying to get lock path " + absoluteLockPath, e); } } return lockPath + "/" + lockName; } lockPath is already String

Target:
private String createAndGetLockPath() throws InterruptedException, KeeperException { // Create locks if it does not exist if (zk.exists(lockPath, false) == null) { try { Util.mkdir(zk, lockPath, ZooDefs.Ids.OPEN_ACL_UNSAFE); } catch (CloudnameException e) { log.log( java.util.logging.Level.INFO, "CloudnameException while trying to get lock path " + absoluteLockPath, e); } } return lockPath + "/" + lockName; }
Source:
public Tuple getTuple(EntityKey key, TupleContext tupleContext) { Entity entity = getEntity( key, tupleContext.getOptionsContext() ); if ( entity != null ) { return new Tuple( new RedisTupleSnapshot( entity.getProperties() ) ); } START else if ( isInTheQueue( key, tupleContext ) ) { END // The key has not been inserted in the db but it is in the queue return new Tuple( new RedisTupleSnapshot( entity.getProperties() ) ); } else { return null; } } What I mean is, your dialect does not implement `BatchableGridDialect`, so items will never be put in to the operations queue.

Target:
public Tuple getTuple(EntityKey key, TupleContext tupleContext) { Entity entity = getEntity( key ); if ( entity != null ) { return new Tuple( new RedisTupleSnapshot( entity.getProperties() ) ); } else { return null; } }
Source:
public void invoke(ClientEvent event) { try { method.invoke(listener, event); } catch (InvocationTargetException e) { log.errorInvokingListener(method, listener, e.getTargetException()); throw log.exceptionInvokingListener( e.getClass().getName(), method, listener, e.getTargetException()); } catch (Exception e) { throw log.exceptionInvokingListener( START e.getClass().getName(), method, listener, e); END } } Isn't it enough to throw the logging exception instead of also logging locally ?

Target:
public void invoke(ClientEvent event) { try { method.invoke(listener, event); } catch (InvocationTargetException e) { throw log.exceptionInvokingListener( e.getClass().getName(), method, listener, e.getTargetException()); } catch (Exception e) { throw log.exceptionInvokingListener( e.getClass().getName(), method, listener, e); } }
Source:
ConfigFileConfigProvider(@JsonProperty("configFile") String configFile){ this.configFile = configFile; START loadProperties(); END } can you make loadProperties() take configFile location as an argument and remove the global variable configFile . It seems it is not really needed and reducing global state is good in general.

Target:
ConfigFileConfigProvider(@JsonProperty("configFile") String configFile){ loadProperties(configFile); }
Source:
public void addDataSource(long dataSourceObjectId) throws IngestStreamClosedException { // Do nothing START System.out.println("### DefaultAddImageTaskIngestStream - addDataSource " + dataSourceObjectId); END } No println's, please.

Target:
public void addDataSource(long dataSourceObjectId) throws IngestStreamClosedException { // Do nothing }
Source:
private void deleteEmptyStagingDirectories(List<DeclaredIntentionToWrite> declaredIntentionsToWrite) { for (DeclaredIntentionToWrite declaredIntentionToWrite : declaredIntentionsToWrite) { START Path path = declaredIntentionToWrite.getRootPath(); END if (declaredIntentionToWrite.isTemporaryTable()) { // for temporary table simply delete the entire directory deleteRecursivelyIfExists(declaredIntentionToWrite.getContext(), hdfsEnvironment, path); continue; } if (declaredIntentionToWrite.getMode() != WriteMode.STAGE_AND_MOVE_TO_TARGET_DIRECTORY) { continue; } recursiveDeleteFilesAndLog(declaredIntentionToWrite.getContext(), path, ImmutableList.of(), true, "staging directory cleanup"); } } I don't know if they should be put inside this method or not. Should temp table be considered as staging directories?

Target:
private void deleteEmptyStagingDirectories(List<DeclaredIntentionToWrite> declaredIntentionsToWrite) { for (DeclaredIntentionToWrite declaredIntentionToWrite : declaredIntentionsToWrite) { if (declaredIntentionToWrite.getMode() != WriteMode.STAGE_AND_MOVE_TO_TARGET_DIRECTORY) { continue; } Path path = declaredIntentionToWrite.getRootPath(); recursiveDeleteFilesAndLog(declaredIntentionToWrite.getContext(), path, ImmutableList.of(), true, "staging directory cleanup"); } }
Source:
public void edit() { if (getWindow() != null) { return; } START EditDiskProfileModel model = END new EditDiskProfileModel(this, getCompatibilityVersion(), (DiskProfile) getSelectedItem(), getEntity().getStoragePoolId()); setWindow(model); initProfileStorageDomains(model); } format

Target:
public void edit() { if (getWindow() != null) { return; } EditDiskProfileModel model = new EditDiskProfileModel(this, (DiskProfile) getSelectedItem(), getEntity().getStoragePoolId()); setWindow(model); initProfileStorageDomains(model); }
Source:
public void setUp() throws Exception { super.setUp(); gitDir = new File(project.getProject() .getLocationURI().getPath(), Constants.DOT_GIT); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); START testRepository.commit("initial commit"); END } Please remove that line. It changes the tests.

Target:
public void setUp() throws Exception { super.setUp(); gitDir = new File(project.getProject() .getLocationURI().getPath(), Constants.DOT_GIT); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); }
Source:
protected long getParentDid() { long deckID; START deckID = getCol().getDecks().selected(); END return deckID; } should look like this but without the declaration above - they should be on one line ```suggestion long deckID = getCol().getDecks().selected(); ```

Target:
protected long getParentDid() { long deckID = getCol().getDecks().selected(); return deckID; }
Source:
public static String getFileExtension(File file) throws Exception { START return FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase(); END } Actually this part does not throw any Exception. Just remove `throws Exception` and we should be good. Beware of spaces vs tabs. Prefer using spaces for indentation please.

Target:
public static String getFileExtension(File file) { return FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase(); }
Source:
public void shouldPurgeAnAutoGenerationOption() throws Exception { START assertNotNull(identifierSourceService.getAutoGenerationOption(Integer.parseInt(getUuid()))); END MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(identifierSourceService.getAutoGenerationOption(Integer.parseInt(getUuid()))); } You do not need to call Integer.parseInt(getUuid()) more than once in a method.

Target:
public void shouldPurgeAnAutoGenerationOption() throws Exception { assertNotNull(identifierSourceService.getAutoGenerationOption(getId())); MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(identifierSourceService.getAutoGenerationOption(getId())); }
Source:
START private void loadPerspectiveAndCheckLoadingTime(String perspectiveID, boolean headerIncluded) { END //long loadingStart = System.currentTimeMillis(); String standalonePerspectiveURL = getStandalonePerspectiveURL(perspectiveID, headerIncluded); driver.get(standalonePerspectiveURL); BusyPopup.waitForDisappearance(); ApplicationLoadingPopup.waitForDisappearance(PERSPECTIVE_LOADING_TIMEOUT); //double perspectiveLoadingTime = (System.currentTimeMillis() - loadingStart) / (double) 1000; //TODO: What is the acceptable loading time? Do we want to test this? //assertThat(perspectiveLoadingTime) // .as("It should take less than "+PERSPECTIVE_LOADING_TIMEOUT+" seconds to load the perspective " + perspectiveID + ".") // .isLessThan(PERSPECTIVE_LOADING_TIMEOUT); } Any chance we could make this test `@Parameterized`? To test 35 different perspectives from within one test case seems evil. Alternatively (as I'm sniffing potential problems with the annotation and Arquillian.), can we at least make the looped code its own function and put some logging around it, so that we know when was it that the test actually failed? Of course, we could also have a different method for each of the perspectives - which would be the "cleanest" solution in this situation. But I sort of see how that would be overkill.

Target:
private void loadPerspectiveAndCheckLoadingTime(String perspectiveID, boolean headerIncluded) { //long loadingStart = System.currentTimeMillis(); String standalonePerspectiveURL = getStandalonePerspectiveURL(perspectiveID, headerIncluded); driver.get(standalonePerspectiveURL); ApplicationLoadingPopup.waitForDisappearance(PERSPECTIVE_LOADING_TIMEOUT); BusyPopup.waitForDisappearance(); //double perspectiveLoadingTime = (System.currentTimeMillis() - loadingStart) / (double) 1000; //TODO: What is the acceptable loading time? Do we want to test this? //assertThat(perspectiveLoadingTime) // .as("It should take less than " + PERSPECTIVE_LOADING_TIMEOUT + " seconds to load the perspective " + perspectiveID + ".") // .isLessThan(PERSPECTIVE_LOADING_TIMEOUT); }
Source:
public default IVariableBinding[] getSyntheticOuterLocals() { return START null; END } THis should return empty array

Target:
public default IVariableBinding[] getSyntheticOuterLocals() { return new IVariableBinding[0]; }
Source:
protected void executeCommand() { AuthenticationProfile profile = sessionDataContainer.getProfile(getParameters().getSessionId()); if (profile == null) { setSucceeded(false); } else { sessionId = getParameters().getSessionId(); START sourceIp = sessionDataContainer.getSourceIp(getParameters().getSessionId()); END sessionDataContainer.setSessionValid(getParameters().getSessionId(), false); setSucceeded(true); } } Both should be initialized even for failures

Target:
protected void executeCommand() { AuthenticationProfile profile = sessionDataContainer.getProfile(getParameters().getSessionId()); sessionId = getParameters().getSessionId(); sourceIp = sessionDataContainer.getSourceIp(getParameters().getSessionId()); if (profile == null) { setSucceeded(false); } else { sessionDataContainer.setSessionValid(getParameters().getSessionId(), false); setSucceeded(true); } }
Source:
public static void updateNotification(Context context, MasterSecret masterSecret, long threadId) { if (TextSecurePreferences.isNotificationsEnabled(context)) { if (visibleThread == threadId) { DatabaseFactory.getThreadDatabase(context).setRead(threadId); sendInThreadNotification(context); } else { START updateNotification(context, masterSecret, true); END } } updateBadge(context); } Sure you shouldn't do this if the thread is visible? This way, the notification will not disappear when the thread is visible for some reason.

Target:
public static void updateNotification(Context context, MasterSecret masterSecret, long threadId) { if (!TextSecurePreferences.isNotificationsEnabled(context)) { return; } if (visibleThread == threadId) { DatabaseFactory.getThreadDatabase(context).setRead(threadId); sendInThreadNotification(context); } else { updateNotification(context, masterSecret, true); } }
Source:
protected void fillOptions(Map<Enum, String> options) { options.put(EnumModel.VAL1, START EnumModel.VAL1.toString()); END options.put(EnumModel.VAL2, EnumModel.VAL2.toString()); options.put(EnumModel.VAL3, EnumModel.VAL3.toString()); options.put(EnumModel.VAL4, EnumModel.VAL4.toString()); } not sure if makes sense, but instead of putting the `toString()` as values, I probably would use the Enum's `name() `method, as the `toString()` is usually been overridden...

Target:
protected void fillOptions(Map<Enum, String> options) { options.put(EnumModel.VAL1, EnumModel.VAL1.name()); options.put(EnumModel.VAL2, EnumModel.VAL2.name()); options.put(EnumModel.VAL3, EnumModel.VAL3.name()); options.put(EnumModel.VAL4, EnumModel.VAL4.name()); }
Source:
public boolean removeQueues(Queue... queues) { START removeQueues(Arrays.asList(queues) END .stream() .map(Queue::getName)); return super.removeQueues(queues); } The same `Arrays.stream()` can be applied here as well.

Target:
public boolean removeQueues(Queue... queues) { removeQueues(Arrays.stream(queues) .map(Queue::getName)); return super.removeQueues(queues); }
Source:
private static Object castIntegerToObect(int value, Type type) { if (type == INTEGER || type == TINYINT || type == BIGINT) { return (long) value; } if (type == VARCHAR) { START return value + ""; END } if (type == DOUBLE) { return (double) value; } throw new UnsupportedOperationException(); } String.valueOf()

Target:
private static Object castIntegerToObect(int value, Type type) { if (type == INTEGER || type == TINYINT || type == BIGINT) { return (long) value; } if (type == VARCHAR) { return String.valueOf(value); } if (type == DOUBLE) { return (double) value; } throw new UnsupportedOperationException(); }
Source:
public void testXmlConfig() throws IOException { EmbeddedCacheManager cm = new DefaultCacheManager("jpa-config.xml"); Cache<String, KeyValueEntity> specificCache = cm.getCache("specificCache"); validateConfig(specificCache); KeyValueEntity entity = new KeyValueEntity("k", "v"); specificCache.put(entity.getK(), entity); START cm.stop(); END } `stop()` should be in a finally block, or you could use `TestingUtil.withCacheManager()`.

Target:
public void testXmlConfig() throws IOException { EmbeddedCacheManager cm = null; try { cm = new DefaultCacheManager("jpa-config.xml"); Cache<String, KeyValueEntity> specificCache = cm.getCache("specificCache"); validateConfig(specificCache); KeyValueEntity entity = new KeyValueEntity("k", "v"); specificCache.put(entity.getK(), entity); } finally { if (cm != null) cm.stop(); } }
Source:
public boolean equals(Object o) { boolean equals = this == o || o instanceof START URIEditorInput && END getURI().equals(((URIEditorInput) o).getURI()); if (equals && o instanceof SessionEditorInput) { EObject input = getInput(false); if (input != null) { SessionEditorInput otherSessionEditorInput = (SessionEditorInput) o; return input.equals(otherSessionEditorInput.getInput(false)); } } return equals; } Shouldn't this be SessionEditorInput? Here equals() can return true for instances of different subclasses of URIEditorInput which point to the same URI. I have not checked, but maybe it happen could if have my aird opened at the same time inside a non-Sirius editor.

Target:
public boolean equals(Object o) { boolean equals = this == o || o instanceof SessionEditorInput && getURI().equals(((SessionEditorInput) o).getURI()); if (equals && o instanceof SessionEditorInput) { EObject input = getInput(false); if (input != null) { SessionEditorInput otherSessionEditorInput = (SessionEditorInput) o; return input.equals(otherSessionEditorInput.getInput(false)); } } return equals; }
Source:
private void loadChildEntities(LibraryDilution dilution) throws IOException { if (dilution.getLibrary() != null) { dilution.setLibrary(libraryDao.get(dilution.getLibrary().getId())); } if (dilution.getTargetedSequencing() != null) { dilution.setTargetedSequencing(targetedSequencingDao.get(dilution.getTargetedSequencing().getId())); } START dilution.setDilutionCreator(authorizationManager.getCurrentUsername()); END } This will cause creator to change on every update

Target:
private void loadChildEntities(LibraryDilution dilution) throws IOException { if (dilution.getLibrary() != null) { dilution.setLibrary(libraryDao.get(dilution.getLibrary().getId())); } if (dilution.getTargetedSequencing() != null) { dilution.setTargetedSequencing(targetedSequencingDao.get(dilution.getTargetedSequencing().getId())); } }
Source:
GdkColor getContextColor () { long /*int*/ fontHandle = fontHandle (); long /*int*/ context = OS.gtk_widget_get_style_context (fontHandle); GdkRGBA rgba = new GdkRGBA (); if (OS.GTK_VERSION < OS.VERSION(3, 18, 0)) { rgba = display.styleContextGetColor (context, OS.GTK_STATE_FLAG_NORMAL, rgba); } else { START int styleState = OS.gtk_widget_get_state_flags(handle); END rgba = display.styleContextGetColor (context, styleState, rgba); } return display.toGdkColor (rgba); } No need to have the styleState variable at all.

Target:
GdkColor getContextColor () { long /*int*/ fontHandle = fontHandle (); long /*int*/ context = OS.gtk_widget_get_style_context (fontHandle); int styleState = OS.gtk_widget_get_state_flags(handle); GdkRGBA rgba = new GdkRGBA (); rgba = display.styleContextGetColor (context, styleState, rgba); return display.toGdkColor (rgba); }
Source:
public Subquery parameter(String listId, Object... values) { if (values == null || values.length == 0 || values[0] == null) { return this; } where.setToNormal(); where.setToIntersection(); where.addParameter(listId, values); START return this; END } These 2 can be called just once.

Target:
public Subquery parameter(String listId, Object... values) { if (values == null || values.length == 0 || values[0] == null) { return this; } where.setToIntersection(); where.addParameter(listId, values); return this; }
Source:
public int hashCode() { START int result = (key ? 1 : 0); END result = 31 * result + (path != null ? path.hashCode() : 0); return result; } Minor : parentheses are not needed

Target:
public int hashCode() { int result = key ? 1 : 0; result = 31 * result + (path != null ? path.hashCode() : 0); return result; }
Source:
public boolean doSynchronousPing() { MerlinLog.d("Pinging : " + hostAddress); try { START int responseCode = responseCodeFetcher.from(hostAddress); END MerlinLog.d("Got response : " + responseCode); } catch (RequestException e) { if (e.causedByIO()) { return false; } throw e; } return true; } Is this only used for logging?

Target:
public boolean doSynchronousPing() { MerlinLog.d("Pinging : " + hostAddress); try { responseCodeFetcher.from(hostAddress); } catch (RequestException e) { if (e.causedByIO()) { return false; } throw e; } return true; }
Source:
public T hasThisElement(final Object val) { Assert.parametersNotNull("val", val); START return addCriteria(FilterOperator.ELEMENT_MATCH, val, not); END } Is that bug reported? If not, it should be so we can track that it's getting fixed. Also, ensure that the bug fix should be done in a separate commit from the new feature work for elemMatch (I didn't check).

Target:
public T hasThisElement(final Object val) { Assert.parametersNotNull("val", val); return addCriteria(FilterOperator.ELEMENT_MATCH, val, false); }
Source:
public Builder setSSHDirectory(final File sshDirectory) { this.sshDirectory = sshDirectory; START return this; END } Since this class overrides the ```equals``` method, it also needs to override the ```hashCode``` method. Let me know if you have any questions on this.

Target:
public Builder setSSHDirectory(final File sshDirectory) { Assert.assertNotNull(sshDirectory); this.sshDirectory = sshDirectory; return this; }
Source:
public List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Facility facility, Resource resource, User user, Member member) throws InternalErrorException, MemberResourceMismatchException { List<Attribute> attributes = new ArrayList<>(); for (Service service : services) { START getRequiredAttributes(sess, service, facility, resource, user, member); END } return attributes; } I believe you want to add result into the ``attributes`` list. Also, what if required attributes of passed services overlap? We probably should gather them into the set before returning as list.

Target:
public List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Facility facility, Resource resource, User user, Member member) throws MemberResourceMismatchException { Set<Attribute> attributes = new HashSet<>(); for (Service service : services) { attributes.addAll(getRequiredAttributes(sess, service, facility, resource, user, member)); } return new ArrayList<>(attributes); }
Source:
public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, final int offset, final int count) { START sendCommand(ZREVRANGEBYSCORE, key, toByteArray(min), toByteArray(max), LIMIT.raw, toByteArray(offset), END toByteArray(count), WITHSCORES.raw); } parameter sequence swapped: max, min is correct.

Target:
public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, final int offset, final int count) { sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), LIMIT.raw, toByteArray(offset), toByteArray(count), WITHSCORES.raw); }
Source:
public void write(int b) throws IOException { mSingleCharWrite[0] = (byte) b; START write(mSingleCharWrite, 0, 1); END } `write(mSingleCharWrite)`?

Target:
public void write(int b) throws IOException { mSingleCharWrite[0] = (byte) b; write(mSingleCharWrite); }
Source:
public void deallocateFlow(String flowId) throws FlowNotFoundException, ProvisionerException { try { String netId = getNetworkSelector().findNetworkForFlowId(flowId); START getNclController().deallocateFlow(netId, flowId); END } catch (Exception e) { throw new ProvisionerException(e); } } this method expects flowId, netId as parameters. Be careful with the order!

Target:
public void deallocateFlow(String flowId) throws FlowNotFoundException, ProvisionerException { try { String netId = getNetworkSelector().findNetworkForFlowId(flowId); getNclController().deallocateFlow(flowId, netId); } catch (Exception e) { throw new ProvisionerException(e); } }
Source:
private String _encode(String strVal) { try { return URLEncoder.encode(strVal, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { START return e.getMessage(); END } } Perhaps in this case the best is to just rethrow the exception as a RuntimeException

Target:
private String _encode(String strVal) { try { return URLEncoder.encode(strVal, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
public boolean contains(Object o) { START boolean contains = super.contains(o); END if (!contains && o != null) { MarshalledEntry<K, V> me = persistenceManager.loadFromAllStores(o, true); contains = me != null; } return contains; } if o is null, should no we just return false ?

Target:
public boolean contains(Object o) { boolean contains = false; if (o != null) { contains = super.contains(o); if (!contains) { MarshalledEntry<K, V> me = persistenceManager.loadFromAllStores(o, true); contains = me != null; } } return contains; }
Source:
public boolean provides(IOperation operation) { if (!(operation instanceof CreateDecoratorsOperation)) { return false; } IDecoratorTarget decoratorTarget = ((CreateDecoratorsOperation) operation).getDecoratorTarget(); START View view = decoratorTarget.getAdapter(View.class); END return view != null && DDiagramEditPart.MODEL_ID.equals(SiriusVisualIDRegistry.getModelID(view)); } The cast should not be removed to avoid compilation errors on Eclipse versions which do not have the generified getAdapter.

Target:
public boolean provides(IOperation operation) { if (!(operation instanceof CreateDecoratorsOperation)) { return false; } IDecoratorTarget decoratorTarget = ((CreateDecoratorsOperation) operation).getDecoratorTarget(); View view = (View) decoratorTarget.getAdapter(View.class); return view != null && DDiagramEditPart.MODEL_ID.equals(SiriusVisualIDRegistry.getModelID(view)); }
Source:
public void MercuryCuratedMainPageTest_006_CheckWrongCategoryAlert() { CuratedContentPageObject ccp = new CuratedContentPageObject(driver); wikiURL = urlBuilder.getUrlForWiki(MercuryWikis.MERCURY_CC); ccp.openMercuryArticleByNameWithNoCacheBuster(wikiURL, MercurySubpages.CC_MAIN_PAGE); MercuryAlertComponentObject mercuryAlert = new MercuryAlertComponentObject( driver, Mercury.AlertMessage.NOT_EXISTING_CATEGORY); START END String oldUrl = driver.getCurrentUrl(); ccp.clickOnCuratedContentElementByIndex(2); Assertion.assertTrue(mercuryAlert.isAlertMessageVisible()); ccp.waitForLoadingSpinnerToFinish(); Assertion.assertUrlEqualToCurrentUrl(driver, oldUrl); } remove extra line

Target:
public void MercuryCuratedMainPageTest_006_CheckWrongCategoryAlert() { CuratedContentPageObject ccp = new CuratedContentPageObject(driver); wikiURL = urlBuilder.getUrlForWiki(MercuryWikis.MERCURY_CC); ccp.openMercuryArticleByNameWithNoCacheBuster(wikiURL, MercurySubpages.CC_MAIN_PAGE); MercuryAlertComponentObject mercuryAlert = new MercuryAlertComponentObject( driver, MercuryAlertComponentObject.AlertMessage.NOT_EXISTING_CATEGORY); String oldUrl = driver.getCurrentUrl(); ccp.clickOnCuratedContentElementByIndex(2); Assertion.assertTrue(mercuryAlert.isAlertMessageVisible()); ccp.waitForLoadingSpinnerToFinish(); Assertion.assertUrlEqualToCurrentUrl(driver, oldUrl); }