auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void cacheParents(CloneSourceProvider repositoryImport, Collection<RepositoryServerInfo> repositoryServerInfos) { for (RepositoryServerInfo info : repositoryServerInfos) { parents.put(info, repositoryImport); } }

Target:
nit: no braces around single line block
Source:
private void configureFetchSpec(CloneOperation op, GitRepositoryInfo gitRepositoryInfo, String remoteName) { for (String fetchRefSpec : gitRepositoryInfo.getFetchRefSpecs()) { op.addPostCloneTask(new ConfigureFetchAfterCloneTask(remoteName, fetchRefSpec)); } }

Target:
style nit: no curly braces around single line blocks
Source:
public void dispose() { repoImage.dispose(); for (Image image : images) { image.dispose(); } }

Target:
style nit: no braces around single line blocks
Source:
private SkipRevFilter(int skip) { this.count = 0; this.skip = skip; }

Target:
Count doesn't need to be explicitly initialized since it is 0 by default
Source:
protected void run() throws Exception { if (list) { list(); } else { throw new NotSupportedException( "only --list option is currently supported"); } }

Target:
style nit: no braces around single line blocks
Source:
private boolean equalIdAndMode(ObjectId id1, FileMode mode1, ObjectId id2, FileMode mode2) { if (mode1.equals(mode2)) { if (id1 == null) return id2 == null; return (id1.equals(id2)); } return false; }

Target:
right, looks much nicer. done!
Source:
public CleanCommand setCleanDirectories(boolean dirs) { this.directories = dirs; return this; }

Target:
this keyword not needed
Source:
public static List<ReceiveCommand> filter(List<ReceiveCommand> commands, final Result want) { final List<ReceiveCommand> r = new ArrayList<ReceiveCommand>(commands .size()); for (final ReceiveCommand cmd : commands) { if (cmd.getResult() == want) r.add(cmd); } return r; }

Target:
If you drop the final qualifier on "r" will this all fit on one line?
Source:
public void addTags(String remotePath, CVSTag[] tags) { if (tags.length == 0) { return; } addDateTags(tags); addVersionAndBranchTags(remotePath, tags); }

Target:
Yes, even if we add empty set of tags the entry is treated as accessed. I don't think it's correct.
Source:
private void removeTagsFromChildrenCacheEntries(TagCacheEntry entry, CVSTag[] tags) { for (int i = 0; i < tags.length; i++) { removeTagFromChildrenCacheEntries(entry, tags[i]); } entry.getTags().removeAll(Arrays.asList(tags)); if (entry.getTags().size() == 0 && entry.children.size() == 0) { // remove this entry when the last tags where removed // keep the entry if there are any children that have tags removeTagCacheEntry(entry); } }

Target:
Use #isEmpty.
Source:
private void removeTagCacheEntry(TagCacheEntry entry) { if (entry.parent == null) { // We cannot remove root tag cache entry return; } Map newParentChildren = new HashMap(); newParentChildren.putAll(entry.parent.children); newParentChildren.remove(entry.path.lastSegment()); entry.parent.children = newParentChildren; if (entry.parent.getTags().isEmpty() && entry.children.isEmpty()) { // remove parents if they no longer carry any value removeTagCacheEntry(entry.parent); } }

Target:
Shouldn't the second condition be "entry.parent.children.isEmpty()"?
Source:
private void removeTagFromChildrenCacheEntries(TagCacheEntry entry, CVSTag tag) { Iterator childrenIterator = entry.getChildrenIterator(); while (childrenIterator.hasNext()) { TagCacheEntry child = (TagCacheEntry) childrenIterator.next(); removeTagFromChildrenCacheEntries(child, tag); child.getTags().remove(tag); if (child.getTags().size() == 0 && child.children.size() == 0) { // remove this entry when the last tag was removed // keep the entry if there are any children that have tags removeTagCacheEntry(child); } } }

Target:
Use #isEmpty()
Source:
public void execute(IProgressMonitor monitor) throws CVSException, InterruptedException { super.execute(monitor); if (tempFile.length() == 0) { tempFile.delete(); reportEmptyDiff(); return; } if (this.isMultiPatch && (!patchHasContents && !patchHasNewFiles && !emptyDiffReported)){ tempFile.delete(); reportEmptyDiff(); return; } copyFile(); }

Target:
Shouldn't the temp file be deleted anyway?
Source:
public BatchRefUpdate addCommand(ReceiveCommand... cmd) { commands.addAll(Arrays.asList(cmd)); classifiedUpdates = false; return this; }

Target:
addCommand(Arrays.asList(cmd))?
Source:
byte[] getCachedBytes(RevObject obj, ObjectLoader ldr) throws LargeObjectException, MissingObjectException, IOException { try { return ldr.getCachedBytes(streamFileThreshold); } catch (LargeObjectException tooBig) { tooBig.setObjectId(obj); throw tooBig; } }

Target:
I think you can just drop this parameter, and the MiB constant and that is the entire commit.
Source:
private String[] addFilePathToArgs(String actualFilePath, String[] configuredArgs) { int argCount = configuredArgs.length; String[] allArgs = new String[argCount + 1]; // Arrays.copyOf leaves empty cells at the end. We need an empty cell at the beginning of // the array. System.arraycopy(configuredArgs, 0, allArgs, 1, argCount); // We add the path of the file to process as the first argument to pass. allArgs[0] = actualFilePath; return allArgs; }

Target:
Move after line 51.
Source:
private void readCheckerEnablementVerifier() { IExtensionPoint ep = getExtensionPoint(CHECKER_ENABLEMENT_EXTENSION_POINT_NAME); for (IConfigurationElement ce : ep.getConfigurationElements()) { try { Object o = ce.createExecutableExtension(CLASS_ATTR); checkerEnablementVerifier = (ICheckerEnablementVerifier) o; } catch (CoreException e) { CodanCorePlugin.log(e); } } }

Target:
inline o
Source:
public static int getValue(String text) { if (text == null || text.isEmpty() || text.equals("build")) { //$NON-NLS-1$ return BUILD; } if (text.equals("codan")) { //$NON-NLS-1$ return CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); //$NON-NLS-1$ }

Target:
Please remove isEmpty() check. Null check should be removed too, but the comparisons should be made null-proof.
Source:
public void removeChildrenFromLRU() { if (children != null) { for (ExpressionInfo child : children) { removeChildFromLRU(child); } children = null; numChildrenHint = 0; } if (fakeChildren != null) { for (ExpressionInfo fakeChild : fakeChildren) { if (fakeChild == null) { break; } removeChildFromLRU(fakeChild); } clearFakeChildren(); } }

Target:
fakeChildren removal can be cleaned up when using a Vector
Source:
public static Test suite() { TestSuite suite = new TestSuite(RegressionTests.class.getName()); // Test that common builder does the correct amount of work. suite.addTestSuite(Bug_303953.class); suite.addTestSuite(Bug_377295.class); return suite; }

Target:
I don't think it is useful for us to organize the tests using "regression" category. I'd rather see them in the regular test suite.
Source:
public URI getWorkingDirectoryURI() { if (!fDirectoryStack.isEmpty()) return fDirectoryStack.lastElement(); // Fall back to the Project Location / Build directory return fBaseDirectoryURI; }

Target:
Please bring the braces back.
Source:
public void pushDirectory(IPath dir) { if (dir != null) { URI uri; URI workingDirectoryURI = getWorkingDirectoryURI(); if (!dir.isAbsolute()) uri = URIUtil.append(workingDirectoryURI, dir.toString()); else { uri = toURI(dir); if (uri == null) // Shouldn't happen; error logged return; } pushDirectoryURI(uri); } }

Target:
Please bring the braces back.
Source:
public void pushDirectoryURI(URI dir) { if (dir != null) { if (dir.isAbsolute()) fDirectoryStack.addElement(dir); else fDirectoryStack.addElement(URIUtil.makeAbsolute(dir, getWorkingDirectoryURI())); } }

Target:
Please bring the braces back.
Source:
protected IFile findFileInWorkspace(IPath path) { URI uri; if (!path.isAbsolute()) { URI workingDirectoryURI = getWorkingDirectoryURI(); uri = EFSExtensionManager.getDefault().append(workingDirectoryURI, path.toString()); } else { uri = toURI(path); if (uri == null) // Shouldn't happen; error logged return null; } return findFileInWorkspace(uri); }

Target:
Please bring the braces back.
Source:
protected IFile findFileInWorkspace(URI uri) { if (!uri.isAbsolute()) uri = URIUtil.makeAbsolute(uri, getWorkingDirectoryURI()); IFile f = ResourceLookup.selectFileForLocationURI(uri, fProject); if (f != null && f.isAccessible()) return f; return null; }

Target:
Please bring the braces back.
Source:
public void addProblemMarker(ProblemMarkerInfo problemMarkerInfo){ fErrors.add(problemMarkerInfo); fMarkerGenerator.addMarker(problemMarkerInfo); if (problemMarkerInfo.severity == IMarkerGenerator.SEVERITY_ERROR_RESOURCE) hasErrors = true; }

Target:
Please bring the braces back.
Source:
public void flush() throws IOException { if (outputStream != null) outputStream.flush(); }

Target:
Please bring the braces back.
Source:
private URI toURI(IPath path) { // try { URI baseURI = getWorkingDirectoryURI(); String uriString = path.toString(); // On Windows "C:/folder/" -> "/C:/folder/" if (path.isAbsolute() && uriString.charAt(0) != IPath.SEPARATOR) uriString = IPath.SEPARATOR + uriString; return EFSExtensionManager.getDefault().createNewURIFromPath(baseURI, uriString); }

Target:
Please bring the braces back.
Source:
public static String[] getErrorParserExtensionIds() { return fExtensionErrorParsers.keySet().toArray(new String[0]); }

Target:
Better: new String[fExtensionErrorParsers.size()]
Source:
public static String[] getDefaultErrorParserIds() { if (fDefaultErrorParserIds==null) { return fAvailableErrorParsers.keySet().toArray(new String[0]); } return fDefaultErrorParserIds.toArray(new String[0]); }

Target:
Restore the spaces.
Source:
public boolean isEnabled() { final Repository repository = getRepository(); return repository != null && containsHead(repository); }

Target:
I'd prefer to remove the field itself. Feels a bit unclean to have a field which is only valid during the execute method. It should be a local variable in execute and passed as an argument to getTagTarget. What do you think?
Source:
public static void trace(String option, String message, Throwable throwable) { //copy the message to a new string, then print the new string to the //console in blocks of 100 characters. String systemPrintableMessage = message; while (systemPrintableMessage.length() > 100) { String partial = systemPrintableMessage.substring(0, 100); systemPrintableMessage = systemPrintableMessage.substring(100); System.out.println(partial + "\\"); //$NON-NLS-1$ } //then pass the original message to be traced into a file if(fgDebugTrace != null) { fgDebugTrace.trace(option, message, throwable); } }

Target:
Missing System.out.print(systemPrintableMessage); after the while loop, to deal with the part of the string that is <= 100.
Source:
public GdbCommandTimeoutManager( ICommandControl commandControl ) { fCommandControl = commandControl; fListeners = new ListenerList(); new GdbDebugOptions(GdbPlugin.getBundleContext()); }

Target:
Remove. This is done only once in the plugin.start() method.
Source:
public static void trace(String option, String message, Throwable throwable) { //divide the string into substrings of 100 chars or less for printing //to console String systemPrintableMessage = message; while (systemPrintableMessage.length() > 100) { String partial = systemPrintableMessage.substring(0, 100); systemPrintableMessage = systemPrintableMessage.substring(100); System.out.print(partial + "\\"); //$NON-NLS-1$ } System.out.println(systemPrintableMessage); //then pass the original message to be traced into a file if(fgDebugTrace != null) { fgDebugTrace.trace(option, message, throwable); } }

Target:
You changed the wrong one :) It is the one outside the while loop that must be print()
Source:
public PullCommand setRebase(boolean useRebase) { checkCallable(); if (useRebase) { pullRebaseMode = PullRebaseMode.REBASE; } else { pullRebaseMode = PullRebaseMode.NO_REBASE; } return this; }

Target:
style nit: we don't use curly braces around single line statements
Source:
private String getAttribute(PlexusConfiguration dom, String attrName) throws PlexusConfigurationException { String attr = dom.getAttribute(attrName); if (attr == null) { return null; } attr = attr.trim(); if (attr.length() == 0) { return null; } return attr; }

Target:
This Exception is never thrown. It may be that while developing, you had a change here that required the throws clause, but it isn't need in the proposed patch. I would have expected that would have reviewed your own change before proposing it here, and that you have removed this change.
Source:
public String getLabel(Object object) { return "" + object; //$NON-NLS-1$ }

Target:
Should invoke object.toString()
Source:
private void lazyLoadModulesConfig() throws IOException, ConfigInvalidException { if (modulesConfig == null) { loadModulesConfig(); } }

Target:
curly braces aren't required
Source:
public static SubmoduleWalk forIndex(Repository repository) throws IOException { SubmoduleWalk generator = new SubmoduleWalk(repository); try { DirCache index = repository.readDirCache(); generator.setTree(new DirCacheIterator(index)); if (repository.isBare()) generator.setRootTree(new DirCacheIterator(index)); else generator.useWorkingTree = true; } catch (IOException e) { generator.release(); throw e; } return generator; }

Target:
Does this make sense? I didn't think bare repositories have an index so repository.readDirCache() would already throw an exception at this point since repository.getIndexFile() throws an exception for bare repositories as is called by DirCache.read
Source:
public String toString() { return "SubscribeCommand[" + command.toString() + " " + spec + "]"; }

Target:
.toString() isn't necessary. + will call it for you.
Source:
public int hashCode() { int hash = 1; hash = hash * 31 + command.hashCode(); hash = hash * 31 + spec.hashCode(); return hash; }

Target:
Alternatively you can do: Arrays.hashCode(new Object[]{command, spec});
Source:
private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; default: throw new IllegalArgumentException(); } } }

Target:
include the cmd as the message.
Source:
BasePackSubscribeConnection(PackTransport packTransport) { super(packTransport); closed = false; }

Target:
Unnecessary, booleans default to false.
Source:
public void dispose() { fTCPBlock.dispose(); fSerialBlock.dispose(); fConnectionStack.dispose(); fConnectionField.dispose(); }

Target:
This method overrides StandardGDBDebuggerPage.dispose(). Why don't you just use super.dispose() in it and dispose only of the widgets and classes added to GDBServerDebuggerPage?
Source:
public void setSessionLifetime(int lifetime) { sessionLifetime = lifetime; }

Target:
synchronized
Source:
private Window(Node n, int capacity) { current = start = first = n; markCapacity = capacity; marked = new ArrayList<Node>(capacity); }

Target:
capacity + 1
Source:
public static boolean isPublishSubscribe(String pathOrUri) { return pathOrUri != null && pathOrUri.endsWith(PUBLISH_SUBSCRIBE_PATH); }

Target:
Because the pubsub handler matches ^/ rather than */, this logic needs to be different.
Source:
long milliTime() { return System.nanoTime() / 1000000; }

Target:
I usually prefer TimeUnit.NANOS.toMillis(System.nanoTime())
Source:
void doSubscribe( Map<String, List<SubscribeCommand>> commands, PrintWriter output) throws NotSupportedException, TransportException, InterruptedException, IOException { connection = transport.openSubscribe(subscriber); transport.setTimeout(timeout); try { connection.subscribe(subscriber, commands, output); } finally { closeConnection(); } }

Target:
this should be private.
Source:
public void start(BundleContext context) throws Exception { super.start(context); contextStore = new LocalContextStore(commonContextScaling); File storeFile = getDefaultContextLocation().toFile(); if (!storeFile.exists()) { storeFile.mkdirs(); } contextStore.setContextDirectory(storeFile); contextManager = new InteractionContextManager(contextStore); // Because ContextContributor are ContextListener, we need them right away initContextContributor(); }

Target:
Loading a chain of classes and potentially activating other bundles during bundle startup can be very problematic. We'll need to find a way to initialize contributors lazily, e.g. on first context activation.
Source:
protected void setDefaultProfileAttributes( ILaunchConfigurationWorkingCopy wc) throws CoreException { wc.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false); wc.setAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true); }

Target:
CoreException is not actaully thrown from this method body.
Source:
public String getResult() { try { float res = Float.parseFloat(result); if (res > 0) { return "+" + result; } else { return result; } } catch (Exception e) { return result; } }

Target:
Again, please don't catch Exception. Code compiles fine without the try catch but you might want to replace it with catch for NumberFormatException.
Source:
public DefaultDsfExecutor(String name) { super(1, new DsfThreadFactory(name + " - " + fgInstanceCounter++)); //$NON-NLS-1$ fName = name; if(DsfDebugOptions.DEBUG_EXECUTOR || ASSERTIONS_ENABLED) { // If tracing, pre-start the dispatch thread, and add it to the map. prestartAllCoreThreads(); fThreadToExecutorMap.put(((DsfThreadFactory)getThreadFactory()).fThread, DefaultDsfExecutor.this); } }

Target:
This is done in the constructor and therefore does not allow to be changed during a debug session. However, other areas below do allow such a dynamic change. I'm worried that we'll have a conflict where we try tracing while not everything is initialized. Either the stuff in the constructor should be moved out in a smart way, or the flags should be per instance of the class and not allowed to change once the class is created.
Source:
public void execute(Runnable command) { // Check if executable wasn't executed already. if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_EXECUTOR && command instanceof DsfExecutable) { assert !((DsfExecutable)command).getSubmitted() : "Executable was previously executed."; //$NON-NLS-1$ ((DsfExecutable)command).setSubmitted(); } command.run(); }

Target:
Remove chedk for DEBUG which should be part of DsfDebugOptions directly
Source:
public void registerModelAdapter(Class<?> adapterType, Object adapter) { if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_SESSION && DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { String msg = new Formatter().format( "%s Registering model adapter %s of type %s to session %s (%s)", //$NON-NLS-1$ DsfPlugin.getDebugTime(), LoggingUtils.toString(adapter), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.put(adapterType, adapter); }

Target:
Let's only use DsfDebugOptions... as mentioned above
Source:
public void unregisterModelAdapter(Class<?> adapterType) { if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_SESSION && DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { String msg = new Formatter().format( "%s Unregistering model adapter of type %s from session %s (%s)", //$NON-NLS-1$ DsfPlugin.getDebugTime(), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.remove(adapterType); }

Target:
Let's only use DsfDebugOptions... as mentioned above
Source:
public double getLocationRatio(ITmfLocation<?> location) { final CtfLocation curLocation = (CtfLocation) location; CtfIterator iterator = CtfIteratorManager.getIterator(this, ctx); ctx.setLocation(curLocation); ctx.seek(curLocation.getLocation()); long currentTime = ((Long)ctx.getLocation().getLocation()); return ((double) currentTime - iterator.getStartTime()) / (iterator.getEndTime() - iterator.getStartTime()); }

Target:
Could you use a local context instead?
Source:
public void addResolutionListener(IQualifiedTypeResolutionListener resolutionListener) { for (int i = 0; i < this.resolutionListeners.length; i++){ if (this.resolutionListeners[i].equals(resolutionListener)) return; } int length = this.resolutionListeners.length; System.arraycopy(this.resolutionListeners, 0, this.resolutionListeners = new IQualifiedTypeResolutionListener[length + 1], 0, length); this.resolutionListeners[this.resolutionListeners.length - 1] = resolutionListener; }

Target:
this.resolutionListeners[length] = resolutionListener would have sufficed.
Source:
public void registerEventInTimeRange(ITmfEvent event, ITmfExtraEventInfo extraInfo) { TmfFixedArray<String>[] paths = getNormalPaths(event, extraInfo); for (TmfFixedArray<String> path : paths) ++(getOrCreate(path).getValue().nbEventsInTimeRange); paths = getTypePaths(event, extraInfo); for (TmfFixedArray<String> path : paths) ++(getOrCreate(path).getValue().nbEventsInTimeRange); }

Target:
Hmm, this I don't really like, a getter shouldn't be used for writing to a value. You could add .incrementValue() method or something.
Source:
public int compareTo(ActivityEvent object) { if (date == null || object.getDate() == null) { return 0; } return date.compareTo(object.getDate()); }

Target:
This implementation is not transitive. null elements should either be ordered first or last.
Source:
private void initialize() { Assert.isNotNull(scope, "Task scope should not be null."); //$NON-NLS-1$ events.addAll(manager.getEvents(scope)); try { ReviewTaskProvider reviewTaskProvider = new ReviewTaskProvider(); reviewTaskProvider.open(manager); reviewTaskProvider.query(scope, null); } catch (CoreException e) { System.out.println(e); } events.addAll(manager.getEvents(scope)); }

Target:
the constructor already asserts that
Source:
public Collection<ActivityEvent> getEvents(ActivityScope scope) { Assert.isNotNull(scope, "Task scope should not be null."); //$NON-NLS-1$ events.addAll(new ReviewTaskProvider().getReviews(((TaskActivityScope) scope).getTask().getTaskId())); return events; }

Target:
Querying of provider should be implemented in ActivityStream by invoking the query() method on the different providers.
Source:
public void dispose() { super.dispose(); if (fStatsViewers != null) { fStatsViewers.dispose(); } // clean the model TmfStatisticsTreeRootFactory.removeAll(); }

Target:
I see this check in many places. Can fStatsViewers actually be null? Would it be possible to make it final, and initialize it in the constructor?
Source:
public IQueryResult<IInstallableUnit> query(IQuery<IInstallableUnit> query, IProgressMonitor monitor) { if (consider == Consider.FALSE) { return new CollectionResult<IInstallableUnit>(Collections.<IInstallableUnit> emptyList()); } else { return super.query(query, monitor); } }

Target:
I am wondering if this check shouldn't be on the caller side of this method.
Source:
void setDeltaAttempted(boolean deltaAttempted) { if (deltaAttempted) flags |= DELTA_ATTEMPTED; else flags &= DELTA_ATTEMPTED; }

Target:
Missing ~
Source:
public TmfSimpleTimestamp(final ITmfTimestamp timestamp) { super(timestamp.getValue(), 0, 0); if (timestamp.getScale() != 0 || timestamp.getPrecision() != 0) { throw new IllegalArgumentException(); } }

Target:
I'm having second thought on this one: maybe we should not throw an exception but use this as a conversion function i.e. normalize to scale=0 and drop the precision.
Source:
public ITmfContext seekEvent(double ratio) { CtfTmfLightweightContext context = new CtfTmfLightweightContext(this); final long end = this.getEndTime().getValue(); final long start = this.getStartTime().getValue(); final long diff = end - start; final CtfTmfTimestamp ratioTs = new CtfTmfTimestamp((long) (diff * ratio) + start); context.seek( ratioTs.getValue() ); context.setRank(ITmfContext.UNKNOWN_RANK); return context; }

Target:
Spacing is wrong, Ctrl+Shift+F this part
Source:
private void setExecutionEnvironment(TargetPlatformConfiguration result, Xpp3Dom configuration) { String value = getStringValue(configuration.getChild("executionEnvironment")); if (value == null) { return; } if (value.startsWith("?")) { throw new RuntimeException( "The target-platform-configuration parameter <executionEnvironment> must not start with a '?'. Use <defaultExecutionEnvironment> without a leading '?' instead."); } try { ExecutionEnvironmentUtils.getExecutionEnvironment(value); } catch (UnknownEnvironmentException e) { throw new RuntimeException("Invalid execution environment profile name " + value); } result.setExecutionEnvironment(value); }

Target:
We don't need this check. Even if "?" is used somewhere, which I doubt, UnknownEnvironmentException be self-exlanatory enough for somebody to investigate and fix it.
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { Hashtable<String, String> parameters = (Hashtable<String, String>) data; String profilingType = parameters .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY); String profilingTypeName = parameters .get(ProviderProfileConstants.INIT_DATA_NAME_KEY); if (profilingType == null) { profilingType = ""; } if (profilingTypeName == null) { profilingTypeName = ""; } setProfilingType(profilingType); setProfilingTypeName(profilingTypeName); }

Target:
even though data is a HashTable, it's best to cast it as a Map since that's all that we require.
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { Hashtable<String, String> parameters = (Hashtable<String, String>) data; String profilingType = parameters .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY); String configId = parameters .get(ProviderProfileConstants.INIT_DATA_CONFIG_ID_KEY); if (profilingType == null) { profilingType = ""; } if (configId == null) { configId = ""; } setLaunchConfigID(configId); setProfilingType(profilingType); }

Target:
This should cast to Map<String,String>.
Source:
public String getCommitMessage() { String text = getText(); text = Utils.normalizeLineEndings(text); if (shouldHardWrap()) { text = hardWrap(text); } return text; }

Target:
style nit: we don't use braces around single line blocks
Source:
public void doSubmit() { if (!checkCanSubmit(IMessageProvider.ERROR)) { return; } super.doSubmit(); }

Target:
style nit: we don't use braces around single line blocks
Source:
public void execute() throws MojoExecutionException, MojoFailureException { if (!TARGET_DEFINITION_PACKAGING.equals(project.getPackaging())) { throw new MojoExecutionException("This goal can only be executed on projects with packaging type '" + TARGET_DEFINITION_PACKAGING + "'"); } File targetFile = new File(project.getBasedir(), project.getArtifactId() + FILE_EXTENSION); if (!targetFile.isFile()) { throw new MojoExecutionException("Expected target definition file '" + targetFile.getAbsolutePath() + "' could not be found."); } project.getArtifact().setFile(targetFile); }

Target:
What is this check needed for? We might as well omit it to allow others to create a packaging type "my-eclipse-target-definition" that for example includes additional steps in the default lifecycle.
Source:
protected DirCacheEntry keep(DirCacheEntry e) { DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(), e.getStage()); newEntry.setFileMode(e.getFileMode()); newEntry.setObjectId(e.getObjectId()); newEntry.setLastModified(e.getLastModified()); newEntry.setLength(e.getLength()); builder.add(newEntry); return newEntry; }

Target:
You don't need to change this method signature. I would leave this method private
Source:
protected int mergeFileModes(int modeB, int modeO, int modeT) { if (modeO == modeT) return modeO; if (modeB == modeO) // Base equal to Ours -> chooses Theirs if that is not missing return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT; if (modeB == modeT) // Base equal to Theirs -> chooses Ours if that is not missing return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO; return FileMode.MISSING.getBits(); }

Target:
You don't need to change this method signature. I would leave this method private.
Source:
protected boolean mergeImpl() throws IOException { boolean implicitDirCache = false; boolean clean = false; if (dircache == null) { dircache = getRepository().lockDirCache(); implicitDirCache = true; } clean = mergeTrees(mergeBase().getEntryObjectId(), sourceTrees[0], sourceTrees[1]); if (implicitDirCache) { dircache.unlock(); } return clean; }

Target:
style nit: no braces around single line blocks
Source:
public TaskJobEvent(ITask originalTask, ITask task) { this.originalTask = originalTask; this.task = task; }

Target:
This should invoke the other constructor so that taskData can be marked as final.
Source:
public boolean filter(List<?> filters) { if (filters == null) { return true; } fLock.lock(); try { cancelOngoingRequests(); List<FilterCriteria> list = (List<FilterCriteria>)filters; fFilterCriteria = new ArrayList<FilterCriteria>(list); fillCurrentPage(fEvents); } finally { fLock.unlock(); } return true; }

Target:
Will the page update if filters were previously active?
Source:
public BugzillaPeoplePart() { setPartName(Messages.BugzillaPeoplePart_People); }

Target:
This is the same string so we don't need to do this.
Source:
private void createAttributeEditors(FormToolkit toolkit, Composite peopleComposite) { Collection<TaskAttribute> attributes = getAttributes(); for (TaskAttribute attribute : attributes) { addAttribute(peopleComposite, toolkit, attribute); } }

Target:
We should probably leave this protected to avoid breaking people.
Source:
private AlternateHandle openAlternate(File objdir) throws IOException { final File parent = objdir.getParentFile(); if (FileKey.isGitRepository(parent, fs)) { FileKey key = FileKey.exact(parent, fs); FileRepository db = (FileRepository) RepositoryCache.open(key); return new AlternateRepository(db); } ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, shallowFile); return new AlternateHandle(db); }

Target:
The alternate shouldn't have this repository's shallow file. Define the alternate to have a shallow file of null and handle this case in getShallowCommits() where shallowFile == null means use the empty set.
Source:
public boolean isMergedInto(final RevCommit base, final RevCommit tip) throws MissingObjectException, IncorrectObjectTypeException, IOException { initializeShallowCommits(); final RevFilter oldRF = filter; final TreeFilter oldTF = treeFilter; try { finishDelayedFreeFlags(); reset(~freeFlags & APP_FLAGS); filter = RevFilter.MERGE_BASE; treeFilter = TreeFilter.ALL; markStart(tip); markStart(base); return next() == base; } finally { filter = oldRF; treeFilter = oldTF; } }

Target:
Not necessary here.
Source:
public RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { initializeShallowCommits(); return pending.next(); }

Target:
Not necessary here.
Source:
public RevCommit parseCommit(final AnyObjectId id) throws MissingObjectException, IncorrectObjectTypeException, IOException { initializeShallowCommits(); RevObject c = peel(parseAny(id)); if (!(c instanceof RevCommit)) throw new IncorrectObjectTypeException(id.toObjectId(), Constants.TYPE_COMMIT); return (RevCommit) c; }

Target:
Not necessary here. Its handled within parseAny.
Source:
private RevCommit getCommit(Repository repository, String objectId) { RevWalk revWalk = null; try { revWalk = new RevWalk(repository); return revWalk.parseCommit(ObjectId.fromString(objectId)); } catch (MissingObjectException e) { return null; } catch (IncorrectObjectTypeException e) { return null; } catch (IOException e) { return null; } finally { if (revWalk != null) { revWalk.release(); } } }

Target:
Catch Exception instead to simplify the code?
Source:
FileRevisionTypedElement getAncestorRevision() { if (ancestor instanceof FileRevisionTypedElement) { return (FileRevisionTypedElement) ancestor; } return null; }

Target:
style nit: no braces here
Source:
public String getProperty(String key) { if (properties != null) { if (properties.containsKey(key)) { return properties.get(key); } } return null; }

Target:
Should just return properties.get(), the containsKey() call is redundant.
Source:
public void add(final String[] log) { table.getControl().getDisplay().syncExec(new Runnable() { public void run() { table.addRow(log); try { PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().showView(ID); } catch(PartInitException pie) { } catch(NullPointerException npe) } }); }

Target:
NPE should not be catched btu the case where it might appear should be checked with if (smth != null). We definetely don't want to ignore every NPE.
Source:
public void doAfterTest() throws Exception { getGDBLaunch().terminate(); fBreakpointService = null; fTraceService = null; fBreakpointsDmc = null; fTraceTargetDmc = null; if (fServicesTracker != null) { fServicesTracker.dispose(); fServicesTracker = null; } super.doAfterTest(); }

Target:
This is already done by super.doAfterTest();
Source:
public void testSFINAEInDefaultArgument() throws Exception { parseAndCheckBindings(getAboveComment(), CPP, true); }

Target:
parseAndCheckBindings() is sufficient since GNU extensions are not needed.
Source:
public String[] getProbeVariableCompletions(String probe, String prefix){ TreeNode node = TapsetLibrary.getProbes(); // Get the matching leaf node. node = node.getChildByName(getTapset(probe)); if (node == null ) return NO_MATCHES; node = node.getChildByName(probe); if (node == null ) return NO_MATCHES; // Get the completions. String[] matchingChildren = getMatchingChildren(node, prefix); if(matchingChildren.length == 0) return NO_MATCHES; return matchingChildren; }

Target:
Here if we change NO_MATCHES to be of length 0 then we would not need this change because any array of length 0 would do
Source:
public void testCustomAttributes() { Collection<String> attributes = fixture.listCustomAttributes(); assertEquals(0, attributes.size()); String attrib = fixture.getCustomAttribute("bozo"); //$NON-NLS-1$ assertNull(attrib); }

Target:
You can use Set<String> here now, but it doesn't really matter...
Source:
public void dispose() { for (StreamInputReader reader : streamInputReaders) { if (reader != null) { reader.dispose(); } } }

Target:
We should call clear after disposing all the readers
Source:
static String readSymlink(File path) throws IOException { Path nioPath = path.toPath(); Path target = Files.readSymbolicLink(nioPath); String targetString = target.toString(); if (SystemReader.getInstance().isWindows()) targetString = targetString.replace('\\', '/'); else if (SystemReader.getInstance().isMacOS()) { targetString = Normalizer.normalize(targetString, Form.NFC); } return targetString; }

Target:
style nit: no braces here
Source:
public void setHidden(File path, boolean hidden) throws IOException { super.setHidden(path, hidden); }

Target:
instead of delegating to the super class I would instead not override this method in this subclass
Source:
public RDTCommandLauncher(IProject project) { fProcess = null; fShowCommand = false; try { if (project.hasNature(SYNC_NATURE)) { IRemoteResource remoteRes = (IRemoteResource)project.getAdapter(IRemoteResource.class); uri = remoteRes.getActiveLocationURI(); } else{ uri = project.getLocationURI(); } lineSeparator = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

Target:
Please don't print the stack trace.
Source:
private String toStringDescription() { if (Strings.isValid(getDescription())) { return " - " + getDescription(); } return ""; }

Target:
Can we adhere to the coding style of this file and not have multiple return statements?
Source:
public static int indexOfChangeId(String message, String delimiter) { String[] lines = message.split(delimiter); int footerFirstLine = indexOfFirstFooterLine(lines); if (footerFirstLine == lines.length) return -1; int indexOfFooter = 0; for (int i = 0; i < footerFirstLine; ++i) { indexOfFooter += lines[i].length() + delimiter.length(); } return message.indexOf(CHANGE_ID, indexOfFooter); }

Target:
style nit: no braces around single line blocks
Source:
public void getReport(XResultData rd) { rd.logWithFormat("AtsConfigCache\n", AtsConfigCache.instance); rd.logWithFormat("TagToConfigObject size %d\n", tagToConfigObject.keySet().size()); rd.logWithFormat("ConfigObjects size %d\n", configObjects.size()); }

Target:
Looks like you don't need to pass in the instance here since there's no formatting characters in the string.
Source:
public DfsPackDescription(DfsRepositoryDescription repoDesc, String name) { this.repoDesc = repoDesc; int dot = name.lastIndexOf('.'); this.packName = (dot < 0) ? name : name.substring(0, dot); this.sizeMap = new HashMap<String, Long>(); }

Target:
Set the table size to 5. We expect ~4 entries. 5 is a good default size.
Source:
public long getFileSize(String ext) { Long size = sizeMap.get(ext); return (size == null) ? 0 : size.longValue(); }

Target:
No parens on condition.
Source:
public String printMatchingStats() { String stats = ""; for (int i = 0; i<fTraces.length; i++) { stats += "Trace " + i + ": " + fUnmatched[i].size() + " unmatched events"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } return stats; }

Target:
Instead of using String += otherString, it's more efficient to use a StringBuilder and .append() (especially when in a loop), then return sb.toString() at the end.
Source:
protected int countEvents(Map<Object, LinkedList<ITmfEvent>> tbl) { Iterator<Entry<Object, LinkedList<ITmfEvent>>> iterator = tbl.entrySet().iterator(); int count = 0; while (iterator.hasNext()) { count += iterator.next().getValue().size(); } return count; }

Target:
Would be a tad simpler to do: for (List<ITmfEvent> list : tbl.values()) { count += list.size(); }
Source:
public void run() { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { ScriptConsole console = ScriptConsole.getActive(); if(null != console && console.isRunning()){ console.stop(); } } }); }

Target:
We should use console class member not ask for the active.
Source:
public CtfTmfEvent getCurrentEvent() { final StreamInputReader top = super.prio.peek(); if (top != null) { return new CtfKernelEvent(top.getCurrentEvent(), top.getFilename(), (CtfKernelTrace) this.getCtfTmfTrace()); } return null; }

Target:
CtfKernelEvent
Source:
private boolean hasExt(PackExt ext) { return (extensions & ext.getBit()) == ext.getBit(); }

Target:
!= 0 is also valid if the bit is only ever 1 bit set.
Source:
public void setLoadMeterTimerPeriod(int p) { if (m_loadMeterTimerPeriod == p) return; m_loadMeterTimerPeriod = p > LOAD_METER_TIMER_MIN ? p : LOAD_METER_TIMER_MIN; disposeLoadMeterTimer(); initializeLoadMeterTimer(); }

Target:
You can still put the assert if you want. assert (p > m_LoadMeterTimerPeriodMin); It will warn the designer that something is wrong, but the code below will recover when in production.
Source:
public OneCoreTickCounters(Integer[] c) { assert (c != null && c.length >= 7); fUser = c[0]; fNice = c[1]; fSystem = c[2]; fIdle = c[3]; fIowait = c[4]; fIrq = c[5]; fSoftirq = c[6]; }

Target:
I think you should also have if (c == null || c.length < 7) return; or else we'll hav an NPE
Source:
public String toString() { if(m_highLoadWatermark != null) { return "Load:" + m_load + ", high water-mark:" + m_highLoadWatermark.intValue(); //$NON-NLS-1$ //$NON-NLS-2$ } else { return "Load:" + m_load + ", high water-mark: not defined"; //$NON-NLS-1$ //$NON-NLS-2$ } }

Target:
Only one uses intValue(). Let's remove it.
Source:
public int getLoad() { return m_load; }

Target:
Let's have this one return Integer too, to be consistent.
Source:
public void setLoadMetersEnabled(boolean enabled) { m_loadMetersEnabled = enabled; disposeLoadMeterTimer(); initializeLoadMeterTimer(); }

Target:
Maybe if (m_loadMetersEnabled == enabled) return;
Source:
protected String getFilePath() { if (path != null){ return path.toOSString(); } IEditorPart ed = fWindow.getActivePage().getActiveEditor(); if(ed.getEditorInput() instanceof PathEditorInput) return ((PathEditorInput)ed.getEditorInput()).getPath().toString(); else return ResourceUtil.getFile(ed.getEditorInput()).getLocation().toString(); }

Target:
Braces should be used in the above if-else statement.
Source:
public List<CtfTmfEventField> getValue() { return new ArrayList<CtfTmfEventField>(Arrays.asList((CtfTmfEventField[])super.getValue())); }

Target:
> The return type must be an Object, the toString() function is called on it so it had to converted to a List or else the string doesn't look good Hmm, good point. But the getValue() should return the same type that is passed to the constructor. And we pass a field[] so we can reuse the sub-fields attribute in the super class... I think the easiest/cleanest way would be to override .toString() in here, and have it use Arrays.toString() to correctly print the array.
Source:
public TmfLocationArray(ITmfLocation[] locations, long[] ranks) { assert(locations.length == ranks.length); fLocations = Arrays.copyOf(locations, locations.length); fRanks = Arrays.copyOf(ranks, ranks.length); }

Target:
Are you sure you want to leave asserts in the code? Maybe just checking and throwing IllegalArgumentException, or similar, is better?
Source:
private String loadWorkDefinitionFromArtifact(String name) throws OseeCoreException { Artifact artifact = null; try { artifact = ArtifactQuery.getArtifactFromTypeAndNameNoException(AtsArtifactTypes.WorkDefinition, name, BranchManager.getCommonBranch()); if (artifact != null) { return loadWorkDefinitionFromArtifact(artifact); } } catch (OseeCoreException ex) { throw ex; } catch (Exception ex) { throw new OseeWrappedException(String.format("Error loading AtsDsl [%s] from Artifact", name), ex); } return null; }

Target:
Error handling is confusing. Seems like you always want to throw exceptions from ArtifactQuery so that call should be outside the try catch block and the exception you really want to catch are those generated from loadWorkDefinitionFromArtifact.
Source:
static void assertDerivedFrom(RevCommit derived, RevCommit original) { assertThat(derived, not(equalTo(original))); assertEquals(derived.getFullMessage(), original.getFullMessage()); }

Target:
Switch arguments, expected comes first for assertEquals.
Source:
public void marshal(ITypeMarshalBuffer buffer, boolean includeValue) throws CoreException { includeValue= includeValue && fValue != Value.UNKNOWN; short firstBytes = ITypeMarshalBuffer.EVAL_FIXED; if (includeValue) firstBytes |= ITypeMarshalBuffer.FLAG1; switch (fValueCategory) { case LVALUE: firstBytes |= ITypeMarshalBuffer.FLAG2; break; case PRVALUE: firstBytes |= ITypeMarshalBuffer.FLAG3; break; default: break; } buffer.putShort(firstBytes); buffer.marshalType(fType); if (includeValue) { buffer.marshalValue(fValue); } }

Target:
Makes sense to swap FLAG2 and FLAG3 since LVALUE is less common than PRVALUE.
Source:
public ISerializableEvaluation unmarshalEvaluation() throws CoreException { int oldPos = fPos; short firstBytes = getShort(); if (firstBytes == NULL_TYPE) { return null; } fPos = oldPos; // fLinkage.unmarshalEvaluation() will read firstBytes again return fLinkage.unmarshalEvaluation(this); }

Target:
It's probably makes sense to move this condition to PDOMLinkage.unmarshalEvaluation.
Source:
public AbstractDifferenceFilter() { super(); setPredicateWhenSelected(); setPredicateWhenUnselected(); }

Target:
should not call the setPredicateWhenSelected in constructor. I would prefer you override getPredicateWhen{Selected/Unselected} in concrete class.
Source:
public String toString() { StringBuilder sb = new StringBuilder(getName()); sb.append('='); sb.append(formatNumber(getValue(), base)); return sb.toString(); }

Target:
Here return getName + '=' + formatNumber(getValue(), base); // trailing space it would be nicer.
Source:
private StringBuilder format() { StringBuilder sb = new StringBuilder(String.valueOf(tip)); if (distance > 0) sb.append('~').append(distance); return sb; }

Target:
OK so StringBuilder(null) NPEs. Why are we calling format on something with a null tip? Why are we formatting that string as "null~5" when we know its not a valid reference name?
Source:
public IReviewRemoteFactoryProvider createFactoryProvider(TaskRepository repository) { GerritClient client = getClient(repository); return new GerritRemoteFactoryProvider(client); }

Target:
Very minor, but these two lines could be combined together
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { RebaseCurrentRefCommand rebaseCurrent = new RebaseCurrentRefCommand(); rebaseCurrent.setEnabled(event.getApplicationContext()); // Because the enabled state is for both starting a new rebase as well // as working with an existing rebase, it can be that this is executed // even though starting a new rebase is not possible. So check enabled // state again here. See also isEnabled. if (rebaseCurrent.isEnabled()) { return rebaseCurrent.execute(event); } else { return null; } }

Target:
style nit: no braces here
Source:
private void updateActions() { initialize(); IStructuredSelection selection = getStructuredSelection(); copyDetailsAction.selectionChanged(selection); copyCommenterNameAction.selectionChanged(selection); copyCommentDetailsURL.selectionChanged(selection); Object firstElement = selection.getFirstElement(); if (firstElement != null && firstElement instanceof ITaskComment) { copyCommentDetailsURL.setEnabled(((ITaskComment) firstElement).getUrl() != null); } }

Target:
You can just test firstElement instanceof ITaskComment since null is not an instanceof anything.
Source:
public void clearCandidates() { fTraceTypes.clear(); fTraceFiles.clear(); }

Target:
add missing java-doc
Source:
protected void updateButtons() { BatchImportTraceWizard wiz = getBatchWizard(); ImportUtils.buildFilesToScan(wiz); updateTable(); wiz.getContainer().updateButtons(); }

Target:
If selecting a directory with a lot of sub-directories the method buildFilesToScan() takes very long (due to ImportUtil.recurseFiles()) and blocks the GUI. It would be good to run this in a Job and show a progress bar with the possibility to cancel.
Source:
public void testToString() { assertEquals("toString", "filename1:10 func1()", fCallsite1.toString()); assertEquals("toString", "filename2:25 func2()", fCallsite2.toString()); assertEquals("toString", "filename3:123", fCallsite3.toString()); ITmfCallsite callsite = new TmfCallsite(null, fFunctionName1, fLine1); assertEquals("toString", ":10 func1()", callsite.toString()); }

Target:
filename should not be null according to interface (or do we want to allow it?)
Source:
public Object getPropertyValue(Object id) { if (id.equals(ID_FILE_NAME) && fSourceLookup.getCallsite().getFileName() != null) { return fSourceLookup.getCallsite().getFileName(); } else if (id.equals(ID_FUNCTION_NAME)) { return fSourceLookup.getCallsite().getFunctionName(); } else if (id.equals(ID_LINE_NUMBER)) { return Long.valueOf(fSourceLookup.getCallsite().getLineNumber()); } return null; }

Target:
useless null check (not supposed to be null, and anyways it would be ok to return null)
Source:
public void testCallsiteCopy2() { try { new TmfCallsite(null); fail("null copy"); } catch (final IllegalArgumentException e) { // Success } }

Target:
In the wonderful world of JUnit4 ;) you can use @Test(expected=IllegalArgumentException.class) public void testCallsiteCopy2() { new TmfCallsite(null); }
Source:
private void checkElementAndSubtree(Object element) { Object e = element; checkElement(e); for (Object child : fContentProvider.getChildren(e)) { checkElementAndSubtree(child); } }

Target:
I don't think you have to "cast" the parameter in this case since you do not assign it.
Source:
private void checkLoadable(DeltaWindowEntry ent, long need) { if (maxMemory == 0) return; DeltaWindowEntry n = res.next; while (maxMemory < loaded + need) { clear(n); if (n == ent) throw new LargeObjectException.ExceedsLimit( maxMemory, loaded + need); n = n.next; } }

Target:
nit: this could be a for loop like you did above (or vice versa)