auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void saveSyntaxHighlighting(SensorContext context, List<HighlightingData> highlightingDataList, InputFile inputFile) { NewHighlighting highlighting = context.newHighlighting().onFile(inputFile); for (HighlightingData highlightingData : highlightingDataList) { START highlighting.highlight(highlightingData.startOffset(), highlightingData.endOffset(), highlightingData.highlightCode()); END } highlighting.save(); } ![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png 'Severity: MINOR') Remove this use of "highlight"; it is deprecated. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3ACallToDeprecatedMethod)

Target:
private static void saveSyntaxHighlighting(SensorContext context, List<HighlightingData> highlightingDataList, InputFile inputFile) { NewHighlighting highlighting = context.newHighlighting().onFile(inputFile); for (HighlightingData highlightingData : highlightingDataList) { highlighting.highlight(highlightingData.startOffset(), highlightingData.endOffset(), highlightingData.highlightCode()); } highlighting.save(); }
Source:
START private static boolean isFileBeginning(int line, int column, boolean hasBOM) { END if (line == 1) { return column > (hasBOM ? 1 : 0); } return true; } @pynicolas Are you sure about this method name? As I understand, it does the opposite

Target:
private static boolean isFileBeginning(int line, int column, boolean hasBOM) { if (line == 1) { return column <= (hasBOM ? 1 : 0); } return false; }
Source:
public List getExtensions() { return ImmutableList.of( PropertyDefinition.builder(XmlPlugin.FILE_SUFFIXES_KEY) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze.") .defaultValue(".xml") .category("XML") .onQualifiers(Qualifiers.PROJECT) .build(), Xml.class, XmlRulesDefinition.class, XmlSonarWayProfile.class, // Sensors XmlSensor.class, START LineCounter.class, END XmlCodeColorizerFormat.class); } @lindamartin I don't get how it works if LineCounter doesn't extend any interface (e.g. sensor)

Target:
public List getExtensions() { return ImmutableList.of( PropertyDefinition.builder(XmlPlugin.FILE_SUFFIXES_KEY) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze.") .defaultValue(".xml") .category("XML") .onQualifiers(Qualifiers.PROJECT) .build(), Xml.class, XmlRulesDefinition.class, XmlSonarWayProfile.class, // Sensors XmlSensor.class); }
Source:
START protected TraceeMessagePropertiesConverter(TraceeBackend backend, HttpHeaderTransport transportSerialization, String profile) { END this.backend = backend; this.transportSerialization = transportSerialization; this.profile = profile; } This constructor should be moved to package-scope. Then you're able to insert an mocked TraceeBackend in test-cases -- you could spy on backend-calls and use the `SimpleTraceeBackend.createNonLoggingAllPermittingBackend()`instead of the ThreadLocalBackend.

Target:
TraceeMessagePropertiesConverter(TraceeBackend backend, HttpHeaderTransport transportSerialization, String profile) { this.backend = backend; this.transportSerialization = transportSerialization; this.profile = profile; }
Source:
START public void addParentLevel(ParentKey parent) { END this.parentLevels.add(parent); parent.getKey().childLevels.add(this); } Speaking of access modifiers, this could probably be package private, as this should only be called when constructing the key graph.

Target:
void addParentLevel(ParentKey parent) { this.parentLevels.add(parent); parent.getKey().childLevels.add(this); }
Source:
START private Maybe<User> getUserByEmail(String userEmail) throws NoResultException { END User user; try { user = entityManagerProvider.get().createQuery( "SELECT u FROM User u " + "WHERE u.email = :email", User.class) .setParameter("email", userEmail) .getSingleResult(); return Maybe.of(user); } catch (NoResultException e) { return Maybe.notFound(); } } Use java.util.Optional here instead of Maybe. We use the Maybe type for results which could have *one* of the following states: visible, forbidden, non-existant,or deleted. Here the user is either present or not.

Target:
private Optional<User> getUserByEmail(String userEmail) { User user; try { user = entityManagerProvider.get().createQuery( "SELECT u FROM User u " + "WHERE u.email = :email", User.class) .setParameter("email", userEmail) .getSingleResult(); return Optional.of(user); } catch (NoResultException e) { return Optional.empty(); } }
Source:
START public Quantity(double value) { END this(value, UNKNOWN_UNITS); } Why is this constructor deprecated?

Target:
public Quantity(double value) { this.value = value; }
Source:
protected void onLoad() { super.onLoad(); Iterator<MatrixChildParametersAction> i = this.getActions(MatrixChildParametersAction.class).iterator(); START while(i.hasNext()) { END MatrixChildParametersAction a = i.next(); a.onLoad(this); } } Why using iterator and not the for each loop?

Target:
protected void onLoad() { super.onLoad(); for (MatrixChildParametersAction action : this.getActions(MatrixChildParametersAction.class)){ action.onLoad(this); } }
Source:
public MatrixBuild getMatrixBuild() START { END if( parent == null ) { try { parent = (MatrixBuild)Run.fromExternalizableId(parentId); } catch (Exception e) { parent = null; } } return parent; } Please, respect surrounding code style (`() {`).

Target:
public MatrixBuild getMatrixBuild() { if (parent == null && parentId != null) { try { parent = (MatrixBuild)Run.fromExternalizableId(parentId); } catch (Exception e) { parent = null; } } return parent; }
Source:
public void delete() throws IOException { super.delete(); for(MatrixRun run : getExactRuns()) { START if (run.getWhyKeepLog() != null) continue; END run.delete(); } } I would expect that `MatrixBuild.getWhyKeepLog` would return non-null in this case, so that the whole thing is kept as a unit.

Target:
public void delete() throws IOException { super.delete(); for(MatrixRun run : getExactRuns()) { run.delete(); } }
Source:
START public Iterable<String> getKeysToRemove() { END return KEYS_TO_REMOVE; } Make this protected (and in the `@Overriden`)

Target:
protected Iterable<String> getKeysToRemove() { return KEYS_TO_REMOVE; }
Source:
public Maybe<Channel> fromKey(String key) { for (Channel channel : channels.get()) { START if (Objects.nonNull(channel.getKey()) && channel.getKey().equals(key)) { END return Maybe.just(channel); } } return Maybe.nothing(); } I'd just do `if (Objects.equals(channel.get(), key)) {` then it does all the null checking for you. `Objects.nonNull` is only really useful where a function is required (e.g. stream.filter) as all it does is add an extra method call that the jit then has to decide whether to inline or not (as compared to `obj != null').

Target:
public Maybe<Channel> fromKey(String key) { for (Channel channel : channels.get()) { if (Objects.equals(channel.getKey(), key)) { return Maybe.just(channel); } } return Maybe.nothing(); }
Source:
private void decodeDistribution(DBObject dbObject, Described entity) { entity.setDistributions(TranslatorUtils.toIterable(dbObject, START DISTRIBUTION_KEY, new Function<DBObject, Distribution>() { END @Override public Distribution apply(DBObject input) { return distributionTranslator.fromDBObject(input, new Distribution()); } }).or(ImmutableSet.<Distribution>of())); } lambda

Target:
private void decodeDistribution(DBObject dbObject, Described entity) { entity.setDistributions(TranslatorUtils.toIterable(dbObject, DISTRIBUTION_KEY, input -> distributionTranslator.fromDBObject(input) ).or(ImmutableSet.<Distribution>of())); }
Source:
public QueueingOrganisationStore(MessageSender<EntityUpdatedMessage> sender, OrganisationStore delegate) { this.delegate = checkNotNull(delegate); this.sender = checkNotNull(sender); clock = new SystemClock(); START entityIdCodec = SubstitutionTableNumberCodec.lowerCaseOnly(); END } Inconsistent use of `this`.

Target:
public QueueingOrganisationStore(MessageSender<EntityUpdatedMessage> sender, OrganisationStore delegate) { this(checkNotNull(sender), checkNotNull(delegate), new SystemClock(), SubstitutionTableNumberCodec.lowerCaseOnly()); }
Source:
START protected String generateApiKey() { END return new UUIDGenerator().generate(); } Can this be private?

Target:
private String generateApiKey() { return new UUIDGenerator().generate(); }
Source:
private MessageBuffer getNextBuffer() throws IOException { MessageBuffer next = in.next(); if (next == null) { throw new MessageInsufficientBufferException(); } START totalReadBytes += buffer.size(); END return next; } Check if `buffer` is not null.

Target:
private MessageBuffer getNextBuffer() throws IOException { MessageBuffer next = in.next(); if (next == null) { throw new MessageInsufficientBufferException(); } assert (buffer != null); totalReadBytes += buffer.size(); return next; }
Source:
public Value getOrNilValue(int index) { START if (array.length < index && index >= 0) { END return array[index]; } return ImmutableNilValueImpl.get(); } This condition seems to be backwards. I think it should be `index < array.length`

Target:
public Value getOrNilValue(int index) { if (index < array.length && index >= 0) { return array[index]; } return ImmutableNilValueImpl.get(); }
Source:
public void reset(OutputStream out) throws IOException { START this.out = out; END } This should have been: ``` this.out.close(); ```

Target:
public void reset(OutputStream out) throws IOException { this.out.close(); this.out = out; }
Source:
public ArrayBufferInput(byte[] arr, int offset, int length) { this.buffer = MessageBuffer.wrap(checkNotNull(arr, "input array is null")).slice(offset, length); START checkArgument(length <= arr.length); END this.length = length; } We need to check `offset + length <= arr.length`?

Target:
public ArrayBufferInput(byte[] arr, int offset, int length) { checkArgument(offset + length <= arr.length); this.buffer = MessageBuffer.wrap(checkNotNull(arr, "input array is null")).slice(offset, length); }
Source:
START public boolean skipValue() throws IOException { END // NOTE: This implementation must be as efficient as possible int remainingValues = 1; while(remainingValues > 0) { MessageFormat f = getNextFormat(); if(f == MessageFormat.EOF) return false; remainingValues += f.skip(this); remainingValues--; } return true; } Does this method just check if it can skip? If so, "canSkipValue()" or something is a better method name?

Target:
public boolean skipValue() throws IOException { // NOTE: This implementation must be as efficient as possible int remainingValues = 1; while(remainingValues > 0) { MessageFormat f = getNextFormat(); remainingValues += f.skip(this); remainingValues--; } return true; }
Source:
public String toString() { START return String.format("double@0x%x=%s", Pointer.nativeValue(getPointer()), Double.toString(getValue())); END } The explicit call to `Double#toString` is not necessary, String#format can directly be invoked with a primitive boolean

Target:
public String toString() { return String.format("double@0x%x=%s", Pointer.nativeValue(getPointer()), getValue()); }
Source:
public String toString() { START return String.format("float@0x%x=%s", Pointer.nativeValue(getPointer()), Float.toString(getValue())); END } See DoubleByReference

Target:
public String toString() { return String.format("float@0x%x=%s", Pointer.nativeValue(getPointer()), getValue()); }
Source:
START public byte getValueIfPresent(PointerType key, PointerByReference value) { END return INSTANCE.CFDictionaryGetValueIfPresent(this, key, value); } Would it make sense to convert the return of `CFDictionaryGetValueIfPresent` directly to a boolean?

Target:
public boolean getValueIfPresent(PointerType key, PointerByReference value) { return INSTANCE.CFDictionaryGetValueIfPresent(this, key, value) > 0; }
Source:
public void testGetCurrentThread() { HANDLE h = Kernel32.INSTANCE.GetCurrentThread(); assertNotNull("No current thread handle", h); START assertFalse("Null current thread handle", h.getPointer().equals(Pointer.NULL)); END } Please make this ```java assertNotNull("Null current thread handle", h.getValue()); ``` Your version will raise a `NullPointerException` in the failure case. I consider `Pointer.NULL` a very bad idea - it gives the illusion as if it were an object, in fact it is `null`. If you want to keep your version, it needs to be: ```java assertFalse("Null current thread handle", h.getPointer() == Pointer.NULL); ```

Target:
public void testGetCurrentThread() { HANDLE h = Kernel32.INSTANCE.GetCurrentThread(); assertNotNull("No current thread handle", h); assertNotNull("Null current thread handle", h.getPointer()); }
Source:
public static boolean registryValueExists(HKEY root, String key, String value) { START return registryValueExists(root, key, value, WinNT.REG_NONE); END } Please don't use `WinNT.REG_NONE` for this use-case. `WinNT.REG_NONE` is a type, not an access level. There is no "NONE" access level for the registry. I would just use 0 here. I would not invent a constant.

Target:
public static boolean registryValueExists(HKEY root, String key, String value) { return registryValueExists(root, key, value, 0); }
Source:
private String _evtGetExtendedStatus(String query) { EVT_HANDLE handle = null; String result; try { handle = Wevtapi.INSTANCE.EvtQuery(null, "Application", query, Winevt.EVT_QUERY_FLAGS.EvtQueryChannelPath); result = WevtapiUtil.EvtGetExtendedStatus(); } finally { if (handle != null) { Wevtapi.INSTANCE.EvtClose(handle); } } START System.out.println(result); END return result; } This looks like an artifact from debugging. I was surprised when I saw the output and could not directly place it. Please remove.

Target:
private String _evtGetExtendedStatus(String query) { EVT_HANDLE handle = null; String result; try { handle = Wevtapi.INSTANCE.EvtQuery(null, "Application", query, Winevt.EVT_QUERY_FLAGS.EvtQueryChannelPath); result = WevtapiUtil.EvtGetExtendedStatus(); } finally { if (handle != null) { Wevtapi.INSTANCE.EvtClose(handle); } } return result; }
Source:
protected List getFieldOrder() { return Arrays.asList(new String[] { "dwStructSize", "lpszSourceUrlName", "lpszLocalFileName", "CacheEntryType", "dwUseCount", "dwHitRate", "dwSizeLow", "dwSizeHigh", "LastModifiedTime", "ExpireTime", "LastAccessTime", "LastSyncTime", "lpHeaderInfo", "dwHeaderInfoSize", "lpszFileExtension", "u", "additional" }); START } END Don't suppress the warning and no need to allocate _new String[]_ - use ``` java @Override protected List<String> getFieldOrder() { return Arrays.asList("field1", "field2", ...); } ```

Target:
protected List getFieldOrder() { return Arrays.asList("dwStructSize", "lpszSourceUrlName", "lpszLocalFileName", "CacheEntryType", "dwUseCount", "dwHitRate", "dwSizeLow", "dwSizeHigh", "LastModifiedTime", "ExpireTime", "LastAccessTime", "LastSyncTime", "lpHeaderInfo", "dwHeaderInfoSize", "lpszFileExtension", "u", "additional"); }
Source:
public static final void addSearchPathSuffix(String libraryName, String pathSuffix) { File ps = new File(pathSuffix); // only accept the suffix if it is not an absolute path if (!ps.isAbsolute()) { synchronized (pathSuffixes) { List customPaths = (List) pathSuffixes.get(libraryName); if (customPaths == null) { customPaths = Collections.synchronizedList(new LinkedList()); START pathSuffixes.put(libraryName, customPaths); END } customPaths.add(pathSuffix); } } } Let's use generics since we are using Java 1.5+

Target:
public static final void addSearchPathSuffix(String libraryName, String pathSuffix) { File ps = new File(pathSuffix); // only accept the suffix if it is not an absolute path if (!ps.isAbsolute()) { synchronized (pathSuffixes) { List<String> customPaths = pathSuffixes.get(libraryName); if (customPaths == null) { customPaths = Collections.synchronizedList(new LinkedList<String>()); pathSuffixes.put(libraryName, customPaths); } customPaths.add(pathSuffix); } } }
Source:
public void testSHGetKnownFolderPath() { int flags = ShlObj.KNOWN_FOLDER_FLAG.NONE.getFlag(); PointerByReference outPath = new PointerByReference(); HANDLE token = null; GUID guid = KnownFolders.FOLDERID_Fonts; HRESULT hr = Shell32.INSTANCE.SHGetKnownFolderPath(guid, flags, token, outPath); START Ole32.INSTANCE.CoTaskMemFree(new LPVOID(outPath.getPointer().getLong(0))); END assertTrue(W32Errors.SUCCEEDED(hr.intValue())); } Does declaring a `CoTaskMemFree` that takes `Pointer` work by itself? It's likely that JNA will marshal that appropriately. Otherwise I would declare another version of `CoTaskMemFree` which takes a Pointer, wrapping the LPVOID one.

Target:
public void testSHGetKnownFolderPath() { int flags = ShlObj.KNOWN_FOLDER_FLAG.NONE.getFlag(); PointerByReference outPath = new PointerByReference(); HANDLE token = null; GUID guid = KnownFolders.FOLDERID_Fonts; HRESULT hr = Shell32.INSTANCE.SHGetKnownFolderPath(guid, flags, token, outPath); Ole32.INSTANCE.CoTaskMemFree(outPath.getValue()); assertTrue(W32Errors.SUCCEEDED(hr.intValue())); }
Source:
public COMLateBindingBaseObject(IDispatch dispatch) { // enable JNA protected mode START Native.setProtected(true); END // transfer the value this.iDispatch = dispatch; } This defaults to aon for windows, so I think you can drop it from here and any other COM-related instances.

Target:
public COMLateBindingBaseObject(IDispatch dispatch) { // transfer the value this.iDispatch = dispatch; }
Source:
START public void testVariantClear() { END System.out.println("------------------------------------------"); VARIANT variant = new VARIANT(new SHORT(33333)); HRESULT hr = OleAuto.INSTANCE.VariantClear(variant.getPointer()); assertTrue("hr: " + hr.intValue(), hr.intValue() == 0); System.out.println(variant.toString(true)); System.out.println("------------------------------------------"); } Please convert these tests to use assertions rather than simply printing output. In general, unit tests should produce no output and only make assertions. It is also recommended that you use the message form of assertion, e.g. ``` // prefer this assertTrue("The number of matches should be greater than zero", matches > 0); // to this assertTrue(matches > 0); ```

Target:
public void testVariantClear() { VARIANT variant = new VARIANT(new SHORT(33333)); HRESULT hr = OleAuto.INSTANCE.VariantClear(variant.getPointer()); assertTrue("hr: " + hr.intValue(), hr.intValue() == 0); }
Source:
private void newAppBar() { DWORD dwABM = new DWORD(); APPBARDATA ABData = new APPBARDATA.ByReference(); ABData.uCallbackMessage.setValue( WM_USER + 1); ABData.cbSize.setValue( ABData.size() ); dwABM.setValue(ShellAPI.ABM_NEW); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage( dwABM, ABData); START assertNotNull(result ); END } Extra space after `result`.

Target:
private void newAppBar() { APPBARDATA data = new APPBARDATA.ByReference(); data.cbSize.setValue(data.size()); data.uCallbackMessage.setValue(WM_USER + 1); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage(new DWORD(ShellAPI.ABM_NEW), data); assertNotNull(result); }
Source:
public void htmlFlag(){ String results = (String) Eclim.execute(new String[]{ "java_element_doc", "-p", Jdt.TEST_PROJECT, "-f", TEST_FILE, "-o", "255", "-l", "11", "-e", "utf-8", "-h", "true" }); START Assert.assertTrue("HTML Format expected", results.startsWith("<html><head>")); END } Can you stick with the existing coding style and omit the `Assert.` prefix here.

Target:
public void htmlFlag(){ String results = (String) Eclim.execute(new String[]{ "java_element_doc", "-p", Jdt.TEST_PROJECT, "-f", TEST_FILE, "-o", "255", "-l", "11", "-e", "utf-8", "-h", "true" }); assertTrue("HTML Format expected", results.startsWith("<html><head>")); }
Source:
public void emit(ErrorType etype, ANTLRMessage msg) { switch ( etype.severity ) { case WARNING_ONE_OFF: START case ERROR_ONE_OFF: END if ( errorTypes.contains(etype) ) break; // fall thru case WARNING: warnings++; tool.warning(msg); break; case ERROR: errors++; tool.error(msg); break; } errorTypes.add(etype); } ❗ this is not correct

Target:
public void emit(ErrorType etype, ANTLRMessage msg) { switch ( etype.severity ) { case WARNING_ONE_OFF: if ( errorTypes.contains(etype) ) break; // fall thru case WARNING: warnings++; tool.warning(msg); break; case ERROR_ONE_OFF: if ( errorTypes.contains(etype) ) break; // fall thru case ERROR: errors++; tool.error(msg); break; } errorTypes.add(etype); }
Source:
public boolean templatesExist() { String groupFileName = CodeGenerator.TEMPLATE_ROOT + "/" + getLanguage() + "/" + getLanguage() + STGroup.GROUP_FILE_EXTENSION; URL url = Thread.currentThread().getContextClassLoader().getResource(groupFileName); STGroup result = null; try { START result = new STGroupFile(url); END } catch (IllegalArgumentException iae) { result = null; } return result!=null; } It looks to me as though STGroupFile's ctor calls `getURL()` which does exactly that getResource thing. What additional functionality are you providing? i.e., where does ST4 go wrong? Maybe we shoulda fixed that in ST4 :)

Target:
public boolean templatesExist() { String groupFileName = CodeGenerator.TEMPLATE_ROOT + "/" + getLanguage() + "/" + getLanguage() + STGroup.GROUP_FILE_EXTENSION; STGroup result = null; try { result = new STGroupFile(groupFileName); } catch (IllegalArgumentException iae) { result = null; } return result!=null; }
Source:
public Token match(int ttype) throws RecognitionException { Token t = getCurrentToken(); if ( t.getType()==ttype ) { START if ( t.getType()==Token.EOF ) { END matchedEOF = true; } _errHandler.reportMatch(this); consume(); } else { t = _errHandler.recoverInline(this); if ( _buildParseTrees && t.getTokenIndex()==-1 ) { // we must have conjured up a new token during single token insertion // if it's not the current symbol _ctx.addErrorNode(t); } } return t; } :bulb: `t.getType()` could be replaced by `ttype` for efficiency.

Target:
public Token match(int ttype) throws RecognitionException { Token t = getCurrentToken(); if ( t.getType()==ttype ) { if ( ttype==Token.EOF ) { matchedEOF = true; } _errHandler.reportMatch(this); consume(); } else { t = _errHandler.recoverInline(this); if ( _buildParseTrees && t.getTokenIndex()==-1 ) { // we must have conjured up a new token during single token insertion // if it's not the current symbol _ctx.addErrorNode(t); } } return t; }
Source:
public IntegerList(int capacity) { if (capacity < 0) { throw new IllegalArgumentException(); } if (capacity > MAX_ARRAY_SIZE) START throw new IllegalArgumentException(); END if (capacity == 0) { _data = EMPTY_DATA; } else { _data = new int[capacity]; } } :bulb: Considering `ArrayList` omits this check, I think it's safe for us to as well.

Target:
public IntegerList(int capacity) { if (capacity < 0) { throw new IllegalArgumentException(); } if (capacity == 0) { _data = EMPTY_DATA; } else { _data = new int[capacity]; } }
Source:
public final int binarySearch(int fromIndex, int toIndex, int key) { if (fromIndex < 0 || toIndex < 0 || fromIndex > _size || toIndex > _size) { throw new IndexOutOfBoundsException(); } START if (fromIndex > toIndex) END throw new IllegalArgumentException(); return Arrays.binarySearch(_data, fromIndex, toIndex, key); } I think this condition makes sense. Can you update the code to match the surrounding formatting (hard tabs, and use braces)?

Target:
public final int binarySearch(int fromIndex, int toIndex, int key) { if (fromIndex < 0 || toIndex < 0 || fromIndex > _size || toIndex > _size) { throw new IndexOutOfBoundsException(); } if (fromIndex > toIndex) { throw new IllegalArgumentException(); } return Arrays.binarySearch(_data, fromIndex, toIndex, key); }
Source:
START public ATNSimulator setProfile(boolean profile) { END ParserATNSimulator previous = getInterpreter(); if ( profile ) { setInterpreter(new ProfilingATNSimulator(this)); } else { if ( previous!=null ) { ParserATNSimulator interp = new ParserATNSimulator(this, getATN(), previous.decisionToDFA, previous.getSharedContextCache()); setInterpreter(interp); } } return previous; } I think that would be more consistent with other `set` methods. Mutating methods that return an instance are generally used for chained calls (`StringBuilder.append`) or atomic updates (`AtomicInteger.getAndSet`), neither of which apply here.

Target:
public void setProfile(boolean profile) { ParserATNSimulator interp = getInterpreter(); if ( profile ) { if (!(interp instanceof ProfilingATNSimulator)) { setInterpreter(new ProfilingATNSimulator(this)); } } else if (interp instanceof ProfilingATNSimulator) { setInterpreter(new ParserATNSimulator(this, getATN(), interp.decisionToDFA, interp.getSharedContextCache())); } }
Source:
public STGroup getTemplates() { START STGroup templates = getTarget().getTemplates(); END ST version = templates.getInstanceOf("VERSION"); if ( version==null || !version.render().equals(Tool.VERSION) ) { tool.errMgr.toolError(ErrorType.INCOMPATIBLE_TOOL_AND_TEMPLATES, version, Tool.VERSION, language); } return templates; } The version check would be much easier as a method in the `Target` class, especially considering the `Target` implementation is responsible for loading its own template files.

Target:
public STGroup getTemplates() { return getTarget().getTemplates(); }
Source:
START public void dumpTrailer(PrintStream p, String indent, boolean noArmor) { END if (!noArmor) { p.print ("\n}\n"); } } 'indent' is not used in this method

Target:
public void dumpTrailer(PrintStream p, String indent, boolean noArmor) { if (!noArmor) { p.print (indent+"\n}\n"); } }
Source:
public boolean shouldCaptureBuildInfo(@NotNull TaskContext taskContext) { boolean shouldCaptureBuildInfo = false; if (isCaptureBuildInfo()) { shouldCaptureBuildInfo = true; } else { if (isPublishBuildInfo()) { // First check if there is a publish build info task. if there is then use aggregation List<? extends TaskDefinition> taskDefinitions = taskContext.getBuildContext().getRuntimeTaskDefinitions(); if (TaskDefinitionHelper.isBuildPublishTaskExists(taskDefinitions)) { shouldCaptureBuildInfo = true; resetPublishBuildInfo(); } } } return shouldCaptureBuildInfo; START } END I suggest simplifying the code of the above method to: ``` if (isCaptureBuildInfo()) { return true; } if (isPublishBuildInfo()) { // First check if there is a publish build info task. if there is then use aggregation List<? extends TaskDefinition> taskDefinitions = taskContext.getBuildContext().getRuntimeTaskDefinitions(); if (TaskDefinitionHelper.isBuildPublishTaskExists(taskDefinitions)) { resetPublishBuildInfo(); return true; } } return false; ```

Target:
public boolean shouldCaptureBuildInfo(@NotNull TaskContext taskContext) { if (isCaptureBuildInfo()) { return true; } if (isPublishBuildInfo()) { // First check if there is a publish build info task. if there is then use aggregation List<? extends TaskDefinition> taskDefinitions = taskContext.getBuildContext().getRuntimeTaskDefinitions(); if (TaskDefinitionHelper.isBuildPublishTaskExists(taskDefinitions)) { resetPublishBuildInfo(); return true; } } return false; }
Source:
protected AbstractArtifactoryConfiguration(String builderContextPrefix, @Nullable String capabilityPrefix) { serverConfigManager = ServerConfigManager.getInstance(); if (administrationConfiguration == null) { administrationConfiguration = (AdministrationConfiguration) ContainerManager.getComponent("administrationConfiguration"); } this.builderContextPrefix = builderContextPrefix; this.capabilityPrefix = capabilityPrefix; START this.taskConfiguratorHelper = new TaskConfiguratorHelperImpl(); END } Can we initialise the instance when it is declared?

Target:
protected AbstractArtifactoryConfiguration(String builderContextPrefix, @Nullable String capabilityPrefix) { serverConfigManager = ServerConfigManager.getInstance(); if (administrationConfiguration == null) { administrationConfiguration = (AdministrationConfiguration) ContainerManager.getComponent("administrationConfiguration"); } this.builderContextPrefix = builderContextPrefix; this.capabilityPrefix = capabilityPrefix; }
Source:
public static TaskDefinition findReleaseTaskDefinition(List<? extends TaskDefinition> taskDefinitions) { if (taskDefinitions != null) { for (TaskDefinition taskDefinition : taskDefinitions) { if (taskDefinition.isEnabled()) { AbstractBuildContext config = AbstractBuildContext.createContextFromMap(taskDefinition.getConfiguration()); // Check the release management is enabled START if ((config != null) && config.releaseManagementContext.isReleaseMgmtEnabled()) { END return taskDefinition; } } } } return null; } Redundant parentheses around ```(config != null)```. Also, this method is also identical to the ```getTaskConfiguration``` method. I suggest reusing the code.

Target:
public static TaskDefinition findReleaseTaskDefinition(List<? extends TaskDefinition> taskDefinitions) { if (taskDefinitions != null) { for (TaskDefinition taskDefinition : taskDefinitions) { if (taskDefinition.isEnabled() && isReleaseMgmtEnabled(taskDefinition)) { return taskDefinition; } } } return null; }
Source:
public void showError() { Snackbar snackbar = SnackBarHandler.create(coordinatorLayout, getString(no_account_signed_in)); START snackbar.show(); END } No need to save in a variable. Directly call show

Target:
public void showError() { SnackBarHandler.create(coordinatorLayout, getString(no_account_signed_in)).show(); }
Source:
private void handleEditorImage(Intent data) { String newFilePath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT); boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false); if (isImageEdit) { } else {//Or use the original unedited pictures newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH); START ; END } //System.out.println("newFilePath---->" + newFilePath); //File file = new File(newFilePath); //System.out.println("newFilePath size ---->" + (file.length() / 1024)+"KB"); Log.d("image is edit", isImageEdit + ""); LoadImageTask loadTask = new LoadImageTask(); loadTask.execute(newFilePath); } Why is an extra semicolon placed here? Also, try not to refactor code until and unless it is absolutely required.

Target:
private void handleEditorImage(Intent data) { String newFilePath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT); boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false); if (isImageEdit) { } else {//Or use the original unedited pictures newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH); } //System.out.println("newFilePath---->" + newFilePath); //File file = new File(newFilePath); //System.out.println("newFilePath size ---->" + (file.length() / 1024)+"KB"); Log.d("image is edit", isImageEdit + ""); LoadImageTask loadTask = new LoadImageTask(); loadTask.execute(newFilePath); }
Source:
private void handleZoom(MotionEvent event, Camera.Parameters params) { int maxZoom = params.getMaxZoom(); int zoom = params.getZoom(); float newDist = getFingerSpacing(event); if (newDist > mDist) { //zoom in if (zoom < maxZoom) zoom+=6; } else if (newDist < mDist) { //zoom out START if (zoom > 0) END zoom-=6; } mDist = newDist; params.setZoom(zoom); mCamera.setParameters(params); } This condition can be combined

Target:
private void handleZoom(MotionEvent event, Camera.Parameters params) { int maxZoom = params.getMaxZoom(); int zoom = params.getZoom(); float newDist = getFingerSpacing(event); if (newDist > mDist && zoom < maxZoom) { //zoom in zoom+=6; } else if (newDist < mDist && zoom > 0) { //zoom out zoom-=6; } mDist = newDist; params.setZoom(zoom); mCamera.setParameters(params); }
Source:
public void selectAllImages() START { END for(ImageItem imageItem : localImageList) { imageItem.isSelected = true; deletableList.add(imageItem.path); } notifyDataSetChanged(); } Move the brace in the same line of the function

Target:
public void selectAllImages() { for(ImageItem imageItem : localImageList) { if(!deletableList.contains(imageItem.path)) { imageItem.isSelected = true; deletableList.add(imageItem.path); } } notifyDataSetChanged(); }
Source:
public ImageAdapter(Context c) { mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); path = imagelist.split("#"); if (path.length > 0) { noPhotos.setVisibility(View.GONE); START Log.e("Hi", "Removing"); END } } Remove the unwanted log or make it logical

Target:
public ImageAdapter(Context c) { mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); path = imagelist.split("#"); if (path.length > 0) { noPhotos.setVisibility(View.GONE); } }
Source:
private boolean entitySupportRetry(HttpRequest request) { START boolean entitySupportRetry = true; END if (request.getEntity() != null) { if (request.getEntity() instanceof InputStreamHttpEntity) { // If input stream is not 'mark supported' can not be consumed again so retry is not supported entitySupportRetry = ((InputStreamHttpEntity) request.getEntity()).getInputStream().markSupported(); } } return entitySupportRetry; } unify the conditions to make this method clearer. Return true or false according to that.

Target:
private boolean entitySupportRetry(HttpRequest request) { boolean entitySupportRetry = true; if (request.getEntity() != null && request.getEntity() instanceof InputStreamHttpEntity) { // If input stream is not 'mark supported' can not be consumed again so retry is not supported entitySupportRetry = ((InputStreamHttpEntity) request.getEntity()).getInputStream().markSupported(); } return entitySupportRetry; }
Source:
private Throwable getExceptionCause(Throwable throwable) { // For subclasses of ModuleException, we use it as it already contains additional information if (throwable.getClass().equals(ModuleException.class)) { return throwable.getCause() != null START ? suppressIfPresent(throwable.getCause(), MessagingException.class) END : new MuleRuntimeException(createStaticMessage(throwable.getMessage())); } else { return throwable; } } this doesn't look correct. You're doing this ONLY when the exception is a `ModuleException`. You're ignoring all subclasses (which is what's more frequently used).

Target:
private Throwable getExceptionCause(Throwable throwable) { // For subclasses of ModuleException, we use it as it already contains additional information if (throwable.getClass().equals(ModuleException.class)) { return throwable.getCause() != null ? suppressIfPresent(throwable.getCause(), MessagingException.class) : new MuleRuntimeException(createStaticMessage(throwable.getMessage())); } else { return suppressIfPresent(throwable, MessagingException.class); } }
Source:
private FlowRefFactoryBean createDynamicFlowRefFactoryBean(Processor target, Object targetBuilder, ApplicationContext applicationContext) throws Exception { if (targetBuilder != null) { doReturn(targetBuilder).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } else { doReturn(target).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } START return createFlowRefFactoryBean(FlowRefFactoryBeanTestCase.DYNAMIC_REFERENCED_FLOW, "flow", applicationContext); END } static import

Target:
private FlowRefFactoryBean createDynamicFlowRefFactoryBean(Processor target, Object targetBuilder, ApplicationContext applicationContext) throws Exception { if (targetBuilder != null) { doReturn(targetBuilder).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } else { doReturn(target).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } return createFlowRefFactoryBean(DYNAMIC_REFERENCED_FLOW, "flow", applicationContext); }
Source:
public boolean equals(Object o) { START if (this == o) return true; END if (!(o instanceof CaseInsensitiveMultiMap)) return false; if (!super.equals(o)) return false; CaseInsensitiveMultiMap that = (CaseInsensitiveMultiMap) o; return optimized == that.optimized; } use braces even for one line blocks

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CaseInsensitiveMultiMap)) { return false; } if (!super.equals(o)) { return false; } CaseInsensitiveMultiMap that = (CaseInsensitiveMultiMap) o; return optimized == that.optimized; }
Source:
HttpRequestBuilder(boolean preserveHeadersCase) { START headers = new LazyValue<>(() -> new CaseInsensitiveMultiMap(!preserveHeadersCase)); END } why the lazy? this will eventually always be called when `build` is called

Target:
HttpRequestBuilder(boolean preserveHeadersCase) { headers = new CaseInsensitiveMultiMap(!preserveHeadersCase); }
Source:
protected ExecutionMediator createExecutionMediator() { if (executionMediatorFactory != null) { return executionMediatorFactory.get(); } START return new DefaultExecutionMediator(extensionModel, componentModel, connectionManager, muleContext.getErrorTypeRepository()); END } What if you always use a supplier, but when creating the instance, you create the default supplier?

Target:
protected ExecutionMediator createExecutionMediator() { return new DefaultExecutionMediator(extensionModel, componentModel, connectionManager, muleContext.getErrorTypeRepository()); }
Source:
private Map<Integer, Integer> getTypeIndexesPerLevel() { if (this.typeIndexesPerLevel == null) { START this.typeIndexesPerLevel = new SmallMap<>(); END } return this.typeIndexesPerLevel; } `forSize(4)`

Target:
private Map<Integer, Integer> getTypeIndexesPerLevel() { if (this.typeIndexesPerLevel == null) { this.typeIndexesPerLevel = new HashMap<>(4); } return this.typeIndexesPerLevel; }
Source:
public void testDontDeserializeOtherThanMuleSession() throws MuleException { DefaultMuleMessage message = new DefaultMuleMessage("Test Message", muleContext); SessionHandler handler = new SerializeAndEncodeSessionHandler(); START String encodedSet = new String(Base64.encode(SerializationUtils.serialize(new HashSet<String>()))); END message.setInboundProperty(MULE_SESSION_PROPERTY, encodedSet); MuleSession session = handler.retrieveSessionInfoFromMessage(message); assertNull(session); } static import Base64.encode and SerializationUtils.serialize

Target:
public void testDontDeserializeOtherThanMuleSession() throws MuleException { DefaultMuleMessage message = new DefaultMuleMessage("Test Message", muleContext); SessionHandler handler = new SerializeAndEncodeSessionHandler(); String encodedSet = new String(encode(serialize(new HashSet<String>()))); message.setInboundProperty(MULE_SESSION_PROPERTY, encodedSet); MuleSession session = handler.retrieveSessionInfoFromMessage(message); assertNull(session); }
Source:
public ClassSpecificObjectInputStream(ClassLoader classLoader, InputStream inputStream, Class classToAccept) throws IOException, StreamCorruptedException { super(classLoader, inputStream); this.classToAccept = classToAccept; START this.firstClass = true; END } set the true value in the field declaration.

Target:
public ClassSpecificObjectInputStream(ClassLoader classLoader, InputStream inputStream, Class classToAccept) throws IOException, StreamCorruptedException { super(classLoader, inputStream); this.classToAccept = classToAccept; }
Source:
public synchronized void open(String partitionName) throws ObjectStoreException { START lock.lock(); END try { super.open(partitionName); } finally { lock.unlock(); } } use `ConcurrencyUtils#withLock`

Target:
public void open(String partitionName) throws ObjectStoreException { lock.lock(); try { super.open(partitionName); } finally { lock.unlock(); } }
Source:
public void nullMessageProcessPhaseInRegistry() throws Exception { when(mockMuleContext.getTransactionManager()).thenReturn(null); START when(mockMuleContext.getConfiguration().getId()).thenReturn("appName"); END processAndVerifyDefaultPhasesUsingRegistryPhases(null); } move this to a `@Before` method

Target:
public void nullMessageProcessPhaseInRegistry() throws Exception { when(mockMuleContext.getTransactionManager()).thenReturn(null); processAndVerifyDefaultPhasesUsingRegistryPhases(null); }
Source:
public CaseInsensitiveHashMap<K, V> toImmutableCaseInsensitiveMap() { START if (this instanceof ImmutableCaseInsensitiveHashMap) { END return this; } if (this.isEmpty() && EMPTY_MAP != null) { return EMPTY_MAP; } return new ImmutableCaseInsensitiveHashMap<>(this); } Can this check be avoided using polymorphism?

Target:
public CaseInsensitiveHashMap<K, V> toImmutableCaseInsensitiveMap() { if (this.isEmpty() && EMPTY_MAP != null) { return EMPTY_MAP; } return new ImmutableCaseInsensitiveHashMap<>(this); }
Source:
public ClassLoaderModel build() { Optional<Plugin> pluginOptional = empty(); if (processSharedLibraries || processAdditionalPluginLibraries) { pluginOptional = findMuleMavenPluginDeclaration(); } if (processSharedLibraries) { pluginOptional.ifPresent(this::exportSharedLibrariesResourcesAndPackages); } if (processAdditionalPluginLibraries) { pluginOptional.ifPresent(this::processAdditionalPluginLibraries); } // do the filtering of local packages and resources after exported and processed sharedRuntimeLibraries and additionalPluginDependencies START localPackages.removeAll(packages); END localResources.removeAll(resources); return super.build(); } delegate

Target:
public ClassLoaderModel build() { Optional<Plugin> pluginOptional = empty(); if (processSharedLibraries || processAdditionalPluginLibraries) { pluginOptional = findMuleMavenPluginDeclaration(); } if (processSharedLibraries) { pluginOptional.ifPresent(this::exportSharedLibrariesResourcesAndPackages); } if (processAdditionalPluginLibraries) { pluginOptional.ifPresent(this::processAdditionalPluginLibraries); } return super.build(); }
Source:
public void sendResponseToClient(CoreEvent response, Map<String, Object> parameters, CompletableCallback<Void> callback) { START ((BaseEventContext) response.getContext()).success(); END } I believe this is not necessary. This should happen autoamtically in the pipeline. Verify that and if that's the case remove

Target:
public void sendResponseToClient(CoreEvent response, Map<String, Object> parameters, CompletableCallback<Void> callback) { // Do nothing. }
Source:
private void doPoll() { try { InternalEvent internalEvent = InternalEvent.builder(EventContextFactory.create(flowConstruct, getLocation())).message(Message.of(null)).build(); setCurrentEvent(internalEvent); START messageProcessingManager END .processMessage(flowProcessingTemplate, flowProcessContext); } catch (Exception e) { muleContext.getExceptionListener().handleException(e); } } inline

Target:
private void doPoll() { try { setCurrentEvent(InternalEvent.builder(EventContextFactory.create(flowConstruct, getLocation())).message(Message.of(null)) .build()); messageProcessingManager.processMessage(flowProcessingTemplate, flowProcessContext); } catch (Exception e) { muleContext.getExceptionListener().handleException(e); } }
Source:
public void testActionIndifferentConfig() throws Exception { MuleTransactionConfig config = new MuleTransactionConfig(TransactionConfig.ACTION_INDIFFERENT); ExecutionTemplate executionTemplate = createExecutionTemplate(config); Object result = executionTemplate.execute(getEmptyTransactionCallback()); assertThat(result, is(RETURN_VALUE)); START assertThat(TransactionCoordination.getInstance().getTransaction(), IsNull.nullValue()); END } static import

Target:
public void testActionIndifferentConfig() throws Exception { MuleTransactionConfig config = new MuleTransactionConfig(ACTION_INDIFFERENT); ExecutionTemplate executionTemplate = createExecutionTemplate(config); Object result = executionTemplate.execute(getEmptyTransactionCallback()); assertThat(result, is(RETURN_VALUE)); assertThat(getInstance().getTransaction(), nullValue()); }
Source:
private LocalTxQueueTransactionContext createLocalTxContext(LocalTxQueueTransactionJournal txLog, QueueProvider provider) throws InterruptedException { Lock lock = mock(Lock.class); START when(lock.tryLock(anyLong(), eq(TimeUnit.MILLISECONDS))).thenAnswer((Answer<Boolean>) invocationOnMock -> { END sleep(invocationOnMock.getArgument(0, Long.class) / 2); return true; }); return new LocalTxQueueTransactionContext(txLog, provider, lock); } static import

Target:
private LocalTxQueueTransactionContext createLocalTxContext(LocalTxQueueTransactionJournal txLog, QueueProvider provider) throws InterruptedException { Lock lock = mock(Lock.class); when(lock.tryLock(anyLong(), eq(MILLISECONDS))).thenAnswer((Answer<Boolean>) invocationOnMock -> { sleep(invocationOnMock.getArgument(0, Long.class) / 2); return true; }); return new LocalTxQueueTransactionContext(txLog, provider, lock); }
Source:
protected void addInInterceptorCorrectingInterceptors(ServerFactoryBean sfb) { START if (isProxy() && isProxyEnvelope() && CxfUtils.interceptorOfClassIsPresent(sfb.getInInterceptors(), SAAJInInterceptor.class)) END { sfb.getInInterceptors().add(new SAAJEnvelopeCorrectionInterceptor()); } } static import

Target:
protected void addInInterceptorCorrectingInterceptors(ServerFactoryBean sfb) { if (isProxy() && isProxyEnvelope() && interceptorOfClassIsPresent(sfb.getInInterceptors(), SAAJInInterceptor.class)) { sfb.getInInterceptors().add(new SAAJEnvelopeCorrectionInterceptor()); } }
Source:
private boolean isRootProcessorScope(ComponentModel componentModel) { ComponentIdentifier identifier = componentModel.getIdentifier(); return identifier.equals(FLOW_IDENTIFIER) || identifier.equals(MUNIT_BEFORE_SUITE_IDENTIFIER) START || identifier.equals(SUBFLOW_IDENTIFIER) || identifier.equals(CHOICE_WHEN_COMPONENT_IDENTIFIER) END || identifier.equals(CHOICE_OTHERWISE_COMPONENT_IDENTIFIER) || identifier.equals(MUNIT_BEFORE_TEST_IDENTIFIER) || identifier.equals(MUNIT_AFTER_SUITE_IDENTIFIER) || identifier.equals(MUNIT_AFTER_TEST_IDENTIFIER); } create an issue and add a TODO to review this situation with other components (try and scatter-gather pop into my mind right now.)

Target:
private boolean isRootProcessorScope(ComponentModel componentModel) { ComponentIdentifier identifier = componentModel.getIdentifier(); return identifier.equals(FLOW_IDENTIFIER) || identifier.equals(MUNIT_BEFORE_SUITE_IDENTIFIER) || identifier.equals(SUBFLOW_IDENTIFIER) || identifier.equals(MUNIT_BEFORE_TEST_IDENTIFIER) || identifier.equals(MUNIT_AFTER_SUITE_IDENTIFIER) || identifier.equals(MUNIT_AFTER_TEST_IDENTIFIER); }
Source:
public void doNotExpireDynamicConfigWithCustomExpirationUsedBySource() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpirationForSource", "heisenbergWithCustomExpirationForSource", "Walter Blanco"); try { assertExpired(config, 10000, 1000); fail("Config should not have been expired"); } catch (AssertionError e) { START assertThat(e.getMessage(), is(not("Config should not have been expired"))); END } assertInitialised(config); sourceWithDynamicConfig.stop(); assertExpired(config, 6000, 100); } not at all elegant. Just throw an illegalStateException instead of using fail

Target:
public void doNotExpireDynamicConfigWithCustomExpirationUsedBySource() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpirationForSource", "heisenbergWithCustomExpirationForSource", "Walter Blanco"); try { assertExpired(config, 10000, 1000); throw new IllegalStateException("Config should not have been expired"); } catch (AssertionError e) { //all good } assertInitialised(config); sourceWithDynamicConfig.stop(); assertExpired(config, 6000, 100); }
Source:
public void authenticateWithoutProvider() throws SecurityException, SecurityProviderNotFoundException { expected.expect(SecurityProviderNotFoundException.class); manager.authenticate(authentication); verify(provider).authenticate(authentication); START verifyZeroInteractions(provider); END } isn't this contradictory with the line right above?

Target:
public void authenticateWithoutProvider() throws SecurityException, SecurityProviderNotFoundException { expected.expect(SecurityProviderNotFoundException.class); try { manager.authenticate(authentication); } finally { verifyZeroInteractions(provider); } }
Source:
protected void checkWithFailDropStrategy(CoreEvent event) throws FlowBackPressureException { if (!abstractPipeline.getProcessingStrategy().checkBackpressureEmitting(event)) { FlowBackPressureException exception = new FlowBackPressureException(abstractPipeline.getName()); START throw exception; END } } inline

Target:
protected void checkWithFailDropStrategy(CoreEvent event) throws FlowBackPressureException { if (!abstractPipeline.getProcessingStrategy().checkBackpressureEmitting(event)) { throw new FlowBackPressureException(abstractPipeline.getName()); } }