auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
RGB acquireCurrentColorSelectionGtk3(long /*int*/ handle, GdkRGBA rgba) { int red = 0; int green = 0; int blue = 0; OS.gtk_color_chooser_get_rgba (handle, rgba); red = (int) (rgba.red * 255); green = (int) (rgba.green * 255); blue = (int) (rgba.blue * 255); rgb = new RGB (red, green, blue); return rgb; }

Target:
You are assigning 'rgb' a new value, then you return rgb and then you re-assign rgb it's own value that get's returned. This duplicate assignment is somewhat strange code. Instead consider simply returning a new RGB object without touching 'rgb' in this call and just leave the assignment in the parent method.
Source:
public void setReviewInput(ReviewInput reviewInput) { fReviewInput.setLabels(reviewInput.getLabels()); fReviewInput.setMessage(reviewInput.getMessage()); }

Target:
can you just use fReviewInput = reviewInput
Source:
private static List<Variable> removeDuplicates(List<Variable> typeMatches) { HashSet<Variable> set = new HashSet<>(); set.addAll(typeMatches); return Arrays.asList(set.toArray(new Variable[set.size()])); }

Target:
Simpler: return new ArrayList<>(new HashSet<>(typeMatches));
Source:
private static CEditor getCEditor(IEditorPart editorPart) { if (editorPart instanceof CEditor) { return (CEditor) editorPart; } else { return null; } }

Target:
Redundant "else"
Source:
public Variable(String name, VariableType variableType, int positionScore, char[] triggerChars, ImageDescriptor descriptor) { this.name = name; this.variableType = variableType; this.positionScore = positionScore; this.triggerChars = triggerChars; this.descriptor = descriptor; this.alreadyMatched = false; }

Target:
Redundant initialization.
Source:
protected IType getType(IBinding binding) { if (!isAnonymousBinding(binding)) { if (binding instanceof IVariable) { return ((IVariable) binding).getType(); } else { return null; } } return null; }

Target:
Redundant 'else' clause.
Source:
protected void doExecute() { for (Stereotype stereotype : stereotypes) { element.unapplyStereotype(stereotype); element.eNotify(new NotificationImpl(Notification.SET, true, true, true)); } }

Target:
checkif you could remove that because there is already a notification service for stereotype
Source:
public static void openInCompare(RevCommit commit1, RevCommit commit2, String commit1Path, String commit2Path, Repository repository, IWorkbenchPage workBenchPage) { final ITypedElement base = CompareUtils .getFileRevisionTypedElement(commit1Path, commit1, repository); final ITypedElement next = CompareUtils .getFileRevisionTypedElement(commit2Path, commit2, repository); CompareEditorInput in = new GitCompareFileRevisionEditorInput(base, next, repository, null); CompareUtils.openInCompareEditor(workBenchPage, in); }

Target:
avoid unrelated formatting changes
Source:
public String getPath() { URI uri = fileRevision.getURI(); if (uri != null) { return uri.getPath(); } return getName(); }

Target:
revert this unrelated formatting change
Source:
protected void initModel(String projectName, String modelName, Bundle bundle) throws CoreException, IOException { project = ProjectUtils.createProject(projectName); diModelFile = PapyrusProjectUtils.copyPapyrusModel(project, bundle, getSourcePath(), modelName); if(diModelFile!=null){ System.out.println("jhghg"); } }

Target:
To be removed
Source:
public AbstractCriticalPathAlgorithm(TmfGraph graph) { this.fGraph = graph; }

Target:
Done
Source:
protected void executeAppliedStereotypeCommentDeletion(final TransactionalEditingDomain domain, final View commentNode) { if (null != commentNode) { if (domain != null && TransactionUtil.getEditingDomain(commentNode) == domain) { DeleteCommand command = new DeleteCommand(commentNode); try { GMFUnsafe.write(domain, command); } catch (Exception e) { Activator.log.error(e); } } } }

Target:
The constant must be before the variable when you use an operator.
Source:
private static ITmfEventField getRootField(CustomTraceDefinition definition) { ITmfEventField[] fields = new ITmfEventField[definition.outputs.size()]; for (int i = 0; i < fields.length; i++) { fields[i] = new TmfEventField(nullToEmptyString(definition.outputs.get(i).name), null, null); } ITmfEventField rootField = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); return rootField; }

Target:
cnn
Source:
public Object getAdapter(@SuppressWarnings("rawtypes") final Class adapter) { /* @SuppressWarnings("rawtypes"): gdupe> Imposed by the super class */ Object result; if ("interface org.eclipse.emf.facet.widgets.table.ui.internal.exported.ITableWidgetProvider".equals(adapter.toString())) { System.out.println(); } if (adapter.isInstance(this)) { result = this; } else { result = this.widget.getAdapter(adapter); if (result == null) { result = super.getAdapter(adapter); } } return result; }

Target:
I assume you didn't expect to commit that :-D
Source:
public ColorColumn getColumnById(String id) { System.err.println(id); for (ColorColumn column : colorColumns) { if (column.getColumnId().equals(id)) { return column; } } return null; }

Target:
can this be logged instead? or removed if not needed?
Source:
private boolean isFormatValid(String format) { String formatToCheck = format.replace("'(.*?)'", ""); return !formatToCheck.contains("w") && !formatToCheck.contains("W") && !formatToCheck.contains("MMM") && !formatToCheck.contains("G") && !formatToCheck.contains("E") && !formatToCheck.contains("Z"); }

Target:
Das gibt eine NullPointerException, wenn format = null.
Source:
public void sourceSubstituteAdded() throws Throwable { sourceMappingAddedHelper(false); }

Target:
Parameter should be true here, no?
Source:
protected void addToEntryList(ITmfTrace trace, ITmfStateSystem ss, List<TimeGraphEntry> list) { addToEntryList(trace, list); synchronized (fSSEntryListMap) { List<TimeGraphEntry> entryList = fSSEntryListMap.get(ss); if (entryList == null) { fSSEntryListMap.put(ss, new CopyOnWriteArrayList<>(list)); } else { entryList.addAll(list); } fTraceSSMap.put(trace, ss); } }

Target:
For an experiment, the parameter trace is the experiment. However, later on when handling the traceClosed signal the traces of the experiment are used to remove from fTraceSSMap.
Source:
public void setData(@Nullable LatencyAnalysis analysis) { if (analysis == null) { return; } ISegmentStore<ISegment> results = analysis.getResults(); // If results are not null, then analysis is completed and model can be // updated if (results != null) { updateModel(LatencyViewerUtils.storeAndGet(results)); return; } LatencyViewerUtils.runAnalysis(fListener); }

Target:
If selected trace is not a kernel trace, the old viewer data remains. You could call updateModel(null) here.
Source:
public void dispose() { getTableViewer().getTable().dispose(); super.dispose(); }

Target:
The controls will get disposed by the platform. You only need to call super.dispose() because the viewer is a TmfComponent.
Source:
public void traceSelected(@Nullable TmfTraceSelectedSignal signal) { LatencyAnalysis analysis = LatencyViewerUtils.getAnalysisFromSignal(signal); if (analysis != null) { analysis.addListener(fListener); // Check if latency analysis was performed on selected trace if (analysis.getResults() == null) { // Run analysis if (LatencyViewerUtils.runAnalysis()) { return; } } fData = LatencyViewerUtils.getResultsFromAnalysis(analysis); // Update model is analysis was already performed updateModel(fData); } }

Target:
If you switch back and forth between traces you are added many times as a listener
Source:
public void traceOpened(@Nullable TmfTraceOpenedSignal signal) { LatencyAnalysis analysis = LatencyViewerUtils.getAnalysisFromSignal(signal); if (analysis != null) { analysis.addListener(fListener); LatencyViewerUtils.runAnalysis(); } }

Target:
You will be a listener at least twice, since traceSelected follows traceOpened
Source:
public static LatencyDataStore getResultsFromAnalysis(@Nullable LatencyAnalysis analysis) { if (analysis != null) { ISegmentStore<ISegment> results = analysis.getResults(); if (results != null) { return storeAndGet(results); } } return new LatencyDataStore(new TreeMapStore<>()); }

Target:
If I'm not mistaken, the analysis results stay in memory as long as the trace is opened. Then here you have your own full copy of these results in the tree map store. Would it be possible to keep only one copy in memory?
Source:
public void updateElement(int index) { final TableViewer tableViewer = fTableViewer; final ISegment[] segmentArray = fSegmentArray; if (tableViewer != null && segmentArray != null) { tableViewer.replace(segmentArray[index], index); } }

Target:
When TableViewer.setInput() is called, it tries the preserve the selection (based on index). In AbstractTableViewer.getVirtualSelection():489, it first tries to update the element (which calls this method here) *then* it does a bounds check on the selection index. I think that might be a bug in JFace, but a workaround would be for us to clear the selection before changing the input, which makes sense. Why would we want to preserve the selected index from an unrelated input segment store?
Source:
public void inputChanged(@Nullable Viewer viewer, @Nullable Object oldInput, @Nullable Object newInput) { fTableViewer = (TableViewer) viewer; if (newInput instanceof ISegmentStore<?>) { ISegmentStore<?> segmentStore = (ISegmentStore<?>) newInput; fSegmentArray = Iterables.toArray(segmentStore, ISegment.class); if (fComparator != null){ Arrays.sort(fSegmentArray, fComparator); } } }

Target:
Set the segment array to null if the input is not a valid segment store.
Source:
protected boolean isSpanMarkup(char character) { return SPAN_MARKUP_CHARACTERS.matches(character); }

Target:
consider making this method private or package scope
Source:
public String getPath() { try { return file.toURI().getPath(); } catch (URISyntaxException e) { return file.getFile(); } }

Target:
can you please set the instruction file.getPath () in case of errors instead of file.getFile()
Source:
public void setAlphabeticallySortActive(boolean sort) { this.alphabeticallySort = sort; }

Target:
doesn't need to be public
Source:
protected String getLabel(EObject eObject) { Preconditions.checkNotNull(adapterFactory); if (eObject != null) { Object adapter = adapterFactory.adapt(eObject, ISemanticObjectLabelProvider.class); if (adapter instanceof ISemanticObjectLabelProvider) { return ((ISemanticObjectLabelProvider)adapter).getSemanticObjectLabel(eObject); } } return null; }

Target:
please delete this line, and replace it by adapterfactory != null in the following If statement. We don't want to raise an error if the tooltip can't be computed.
Source:
public void updateElement(int index) { final TableViewer tableViewer = fTableViewer; final ISegment[] segmentArray = fSegmentArray; if ((tableViewer != null) && (segmentArray != null) && (segmentArray.length > index) && !fOngoingUpdate) { fOngoingUpdate = true; tableViewer.replace(segmentArray[index], index); fOngoingUpdate = false; } }

Target:
The fOngoingUpdate is to prevent re-entrant calls to this function. I'm not really sure why this happens, and if it is normal, but the table cannot "be modified while it is being modified". The boolean flag avoids this problem. Then there is the added (segmentArray.length > index) check. This is needed because the number of entries in the "Current Intervals" view can be reduced when selecting a new timestamp, and the viewer does not know the new limit yet.
Source:
public void refreshPieCharts(final boolean refreshGlobal, final boolean refreshSelection) { final Control viewerControl = getControl(); // Ignore update if disposed if (viewerControl.isDisposed()) { return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (!viewerControl.isDisposed()) { fPieChartViewer.refresh(refreshGlobal, refreshSelection); } } }); }

Target:
protected
Source:
public void modelComplete(boolean global) { refreshTree(); waitCursor(false); }

Target:
protected
Source:
PieChart getGlobalPC() { return fGlobalPC; }

Target:
needs to be synchronized
Source:
public TmfPieChartStatisticsModel getPieChartModel(){ return fPieChartModel; }

Target:
The purpose of the getPieChartModel method was to allow extenders to overwrite the implementation. So, do instead: if (fPieChartModel == null) { fPieChartModel = new TmfPieChartStatisticsModel(); } return fPieChartModel;
Source:
public void refreshTree(){ final Control viewerControl = getControl(); // Ignore update if disposed if (viewerControl.isDisposed()) { return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (!viewerControl.isDisposed()) { fTreeViewer.refresh(); } } }); }

Target:
can be private
Source:
public void removeFromJobs(boolean isGlobal, ITmfTrace jobTrace) { Map<ITmfTrace, Job> updateJobs = isGlobal ? fUpdateJobsGlobal : fUpdateJobsPartial; Job job = updateJobs.remove(jobTrace); if (job != null) { job.cancel(); } }

Target:
package visible only
Source:
public void newGlobalEntries(final TmfPieChartViewer context) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { synchronized (context.getMutexLayoutChange()) { if (!context.isDisposed()) { context.updateGlobalPieChart(); context.getGlobalPC().redraw(); } } } }); }

Target:
just use context as sync obj.
Source:
public void init(Composite parent, String viewerName, ITmfTrace trace) { super.init(parent, viewerName); // Increment a counter to make sure the tree ID is unique. fCountInstance++; fInstanceNb = fCountInstance; fTrace = trace; fModel = new TmfStatisticsModel(); // The viewer will process all events if he is assigned to an experiment fProcessAll = (trace instanceof TmfExperiment); initContent(parent); initInput(); }

Target:
remove
Source:
public Boolean exists(Collection<Object> collection, LambdaValue lambda) { Boolean result = Boolean.FALSE; if (collection != null && lambda == null) { result = Boolean.FALSE; } else { for (Object input : collection) { try { if (Boolean.TRUE.equals(lambda.eval(new Object[] {input }))) { result = Boolean.TRUE; break; } // CHECKSTYLE:OFF } catch (Exception e) { // TODO: log the exception. } // CHECKSTYLE:ON } } return result; }

Target:
Do we want that potential NPE in there? the first if checks if collection != null, so we "can" be here with a null collection. And that one is not caught by the catch below. I'd also argue that "if lambda == null" then the result is FALSE in all cases, whether the collection is null or not.
Source:
public Map<String, ArtifactReadable> getCoverageUnits(long branchUuid, String artifactUuid) { IOseeBranch branch = TokenFactory.createBranch(branchUuid, ""); ArtifactReadable coveragePackage = getQuery().fromBranch(branchUuid).andGuid(artifactUuid).getResults().getOneOrNull(); List<ArtifactReadable> descendants = coveragePackage.getDescendants(); return getChildrenRecurse(descendants, branch); }

Target:
don't think branch is needed, but if it is, it can be gotten from the coveragePackage artifact readable.
Source:
protected CtfTmfEvent getEvent(int rank) { ITmfContext ctx = fTrace.getTrace().seekEvent(0); for (int i = 0; i < rank; i++) { fTrace.getTrace().getNext(ctx); } final CtfTmfEvent next = fTrace.getTrace().getNext(ctx); ctx.dispose(); return next; }

Target:
Why not seekEvent(rank) ?
Source:
private void updateTitle(String brand) { IBrandManager brandManager = TasksUiPlugin.getDefault().getBrandManager(); setTitle(brandManager.getConnectorLabel(getConnector(), brand)); }

Target:
Should this be protected?
Source:
public static IPath getXmlFilesPath() { IPath path = Activator.getDefault().getStateLocation(); path = path.addTrailingSeparator().append(XML_DIRECTORY); /* Check if directory exists, otherwise create it */ File dir = path.toFile(); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } dir.deleteOnExit(); return path; }

Target:
weird
Source:
public ImageSearchPage(final ImageSearchModel model) { super("ImageSearchPage", //$NON-NLS-1$ WizardMessages.getString("ImageSearchPage.title"), //$NON-NLS-1$ SWTImagesFactory.DESC_BANNER_REPOSITORY); setMessage(WizardMessages.getString("ImageSearchPage.title")); //$NON-NLS-1$ setPageComplete(true); this.model = model; }

Target:
Is this necessary ? isPageComplete() is overriden anyways to check for a selected image and should always be checked.
Source:
public Object[] getElements(Object inputElement) { List<IBrowserDescriptor> list = new ArrayList<IBrowserDescriptor>(); Iterator<IBrowserDescriptor> iterator = BrowserManager.getInstance().getWebBrowsers() .iterator(); while (iterator.hasNext()) { IBrowserDescriptor browser = iterator .next(); list.add(browser); } return list.toArray(); }

Target:
Please remove redundant type information in another follow up commit
Source:
public Command transactionAboutToCommit(ResourceSetChangeEvent event) throws RollbackException { // Get filtered notifications List<Notification> filteredNotificationsList = event.getNotifications(); CompoundCommand commands = new CompoundCommand(); // Handle each filtered notification for (Notification notification : filteredNotificationsList) { Command refactorCommand = handleFilteredNotification(notification); if (null != refactorCommand) { commands.append(refactorCommand); } } return commands.isEmpty() ? null : commands; }

Target:
If this is going to be a pre-commit listener (which I agree makes more sense than a post-commit listener), then I think it needs to be an aggregate pre-commit listener, meaning that it will be invoked only before commit of the top-most transaction. Otherwise, in the case of nested transactions, we may end up running a refactoring operation (with user interaction each time?) for every nested transaction when it commits.
Source:
public String getText(Object element) { String label = UNKNOWN_LABEL_TEXT; if (element instanceof IStorage) { label = ((IStorage) element).getName(); } else { label = super.getText(element); } return label; }

Target:
This is never returned.
Source:
public String getText(final Object element) { String text = "<UNKNOWN>"; if (element instanceof RefactorScope) { text = element.toString(); } return text; }

Target:
This is the all-capitals name of the enumeration constant in the code. Better would be the human-readable name (from the getName() method).
Source:
public StorageTraversal getStorageTraversal() { Collection<IResource> resources = Arrays.asList(papyrusFile.getAssociatedResources()); Set<IStorage> storages = getStorages(resources); return new StorageTraversal(storages); }

Target:
I know old APIs with arrays are boring, but here I think you do something dangerous by transforming it into a List: - If getAssociatedResources() returns null, you will get a NullPointerException - You're just turning it into a list to iterate over it in your private method, which you decided to define with a Collection parameter but might as weel receive an array parameter => I recommend you directly use an array, and that you check the null case for security
Source:
public Tree createListControl(Composite parent) { Tree table = (Tree) getTreeControl(); if (table == null) { listParent = parent; treeViewer = doCreateTreeViewer(parent, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION); table = treeViewer.getTree(); table.setFont(parent.getFont()); treeViewer.setComparator(new ViewerComparator()); treeViewer.addCheckStateListener(this); } else { //checkParent(table, parent); // Bug 471967 this seems to be not necessary and causing issues } return table; }

Target:
Remove the 'else' branch.
Source:
private List<Object> buildParametersList() { List<Object> result = new ArrayList(this.generatorParameters.length); for (String param : this.generatorParameters) { result.add(param); } return result; }

Target:
Can be changed to Arrays.asList(this.generatorParameters)
Source:
public boolean performOk() { doGetPreferenceStore().setValue(UIPreferences.WARN_BEFORE_COMMITTING, warnCheckbox.getSelection()); System.out.println(warnCheckbox.getSelection()); System.out.println(blockCheckbox.getSelection()); doGetPreferenceStore().setValue(UIPreferences.BLOCK_COMMIT, blockCheckbox.getSelection()); return super.performOk(); }

Target:
these trace statements should be removed
Source:
public void tearDown() throws Exception { setFixture(null); }

Target:
Not necessary. See quality rule : MITRE, CWE-397 - Declaration of Throws for Generic Exception
Source:
private void selectRepresentationElements(ISelection selection, DialectEditor dialectEditor) { List<DRepresentationElement> representationElements = getRepresentationElements(dialectEditor.getRepresentation(), ((IStructuredSelection) selection).toList()); if (!representationElements.isEmpty()) { DialectUIManager.INSTANCE.selectAndReveal(dialectEditor, representationElements); } }

Target:
If the list is empty, we must change the selection to select nothing (erase the current editor selection). For example, for diagram editor, we must select the diagram in this case.
Source:
AlternateHandle.Id getAlternateId() { return wrapped.getAlternateId(); }

Target:
this method could be declared private
Source:
Set<AlternateHandle.Id> skipMe(Set<AlternateHandle.Id> skips) { Set<AlternateHandle.Id> withMe = new HashSet<AlternateHandle.Id>(); if (skips != null) withMe.addAll(skips); withMe.add(getAlternateId()); return withMe; }

Target:
nit: add braces on the if-block.
Source:
public Adapter createStoragePathAdapter(String path, boolean isLocal) { IFileRevision findFileRevision = findFileRevision((ITypedElement)accessor); IFile file = findFile((ITypedElement)accessor); // The parameter isLocal is overwritten because more informations are available here to determine // whether the file is local or remote boolean local; if (file == null) { local = false; } else { local = true; } if (!isLocal && findFileRevision != null) { return new StoragePathAdapter(path, local, findFileRevision.getContentIdentifier(), findFileRevision.getAuthor()); } else { return new StoragePathAdapter(path, local); } }

Target:
Replace with boolean local = file != null;
Source:
public void setContainer(final IWizardContainer wizardContainer) { super.setContainer(wizardContainer); // Bug 476838: the container was null using getShell() of this wizard. wizardContainer.getShell().setImage(Activator.getDefault().getImage(ImageConstants.PAPYRUS_ICON_PATH)); // $NON-NLS-1$ }

Target:
A conditionnal test must be added for the wizard container (null !=)
Source:
private View getPortView(Port port) { View portView = null; Iterator<?> iterator = hostView.getChildren().iterator(); while (iterator.hasNext() && null == portView) { Object child = iterator.next(); if ((child instanceof Node) && ((Node) child).getElement().equals(port)) { portView = (Node) child; } } return portView; }

Target:
The break-condition has to be before continue-condition.
Source:
public void testCall() throws Exception { // Run test ListBranchesCommand listBranchesCommand = fGerrit.listBranches(Common.TEST_PROJECT); BranchInfo[] listBranchesResult = null; try { listBranchesResult = listBranchesCommand.call(); } catch (EGerritException e) { fail(e.getMessage()); } System.out.println(listBranchesResult[0].getRef()); // Verify result assertEquals(listBranchesResult[0].getRef(), "HEAD"); }

Target:
The System.out should be removed here
Source:
public String isCan_delete() { return can_delete; }

Target:
should return a boolean
Source:
public Collection<RepositoryMapping> find(IProgressMonitor m, boolean searchLinkedFolders) throws CoreException { IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; find(monitor, proj, searchLinkedFolders); return results; }

Target:
Delete and pass on m.
Source:
public void run(IProgressMonitor monitor) throws CoreException { ArrayList<TextFileChange> list = new ArrayList<>(); if (fDesc != null) { SubMonitor subMonitor = SubMonitor.convert(monitor, "", 3); //$NON-NLS-1$ findRequireBundleReferences(list, subMonitor.newChild(1)); findFragmentReferences(list, subMonitor.newChild(1)); findXFriendReferences(list, subMonitor.newChild(1)); } fChanges = list.toArray(new Change[list.size()]); }

Target:
Use the two-argument constructor
Source:
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { CompositeChange change = new CompositeChange(MessageFormat.format(PDEUIMessages.RenameExtensionPointProcessor_changeTitle, new Object[] {fInfo.getCurrentValue(), fInfo.getNewValue()})); SubMonitor subMonitor = SubMonitor.convert(pm, "", 2); //$NON-NLS-1$ changeExtensionPoint(change, subMonitor.newChild(1)); if (fInfo.isUpdateReferences()) findReferences(change, subMonitor.newChild(1)); return change; }

Target:
Use two parameter constructor
Source:
private boolean isUnused(ImportPackageObject pkg, Collection<?> exportedPackages, IProgressMonitor monitor) { if (exportedPackages != null && exportedPackages.contains(pkg.getValue())) { monitor.done(); return false; } return !provideJavaClasses(pkg, monitor); }

Target:
Unnecessary
Source:
public void addReviewData(ITask review, String description) { TaskData reviewData = new TaskData(new TaskAttributeMapper(new TaskRepository("", "")), "", review.getUrl(), review.getTaskId()); reviewData.getRoot().createMappedAttribute(TaskAttribute.DESCRIPTION).setValue(description); try { when(taskDataManager.getTaskData(review)).thenReturn(reviewData); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

Target:
Just throw (don't catch) the exception so the test fails.
Source:
public void testNull() { org.eclipse.papyrus.sysml14.nattable.requirement.tester.RequirementTableTester tableRequirementTester = new org.eclipse.papyrus.sysml14.nattable.requirement.tester.RequirementTableTester(); IStatus emptyNotAllowed = tableRequirementTester.isAllowed(null); Assert.assertEquals("The tester should not work on a null entry", IStatus.ERROR, emptyNotAllowed.getSeverity()); }

Target:
import just
Source:
public void testMissingProfile() { org.eclipse.papyrus.sysml14.nattable.requirement.tester.RequirementTableTester tableRequirementTester = new org.eclipse.papyrus.sysml14.nattable.requirement.tester.RequirementTableTester(); org.eclipse.uml2.uml.Package pck = UMLFactory.eINSTANCE.createPackage(); IStatus missingStereotypeNotAllowed = tableRequirementTester.isAllowed(pck); Assert.assertEquals("The tester should not work on a non profiled entry", IStatus.ERROR, missingStereotypeNotAllowed.getSeverity()); }

Target:
//$NON-NLS-0$ ?
Source:
private void autoIgnoreDerivedResources(IProject project, IProgressMonitor monitor) throws CoreException { if (!Activator.autoIgnoreDerived()) { return; } List<IPath> paths = findDerivedResources(project); if (paths.size() > 0) { IgnoreOperation ignoreOp = new IgnoreOperation(paths); IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1); ignoreOp.execute(subMonitor); } }

Target:
Why this? Just pass through 'monitor'.
Source:
public void initializeDefaultPreferences() { IPreferenceStore pstore = CDebugUIPlugin.getDefault().getPreferenceStore(); CDebugPreferencePage.initDefaults( pstore ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_OPEN_NO_SOURCE_INFO, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_OPEN_SOURCE_NOT_FOUND, false ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_SHOW_INSTRUCTIONS, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_SHOW_SOURCE, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_SHOW_ERROR_REVERSE_TRACE_METHOD_NOT_AVAILABLE, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_REVERSE_TRACE_METHOD_HARDWARE, ICDebugPreferenceConstants.PREF_REVERSE_TRACE_METHOD_GDB_TRACE); }

Target:
If we move the preference page to dsf.gdb.ui then the above change should go in GdbPreferenceInitializer.java
Source:
private void stopListening() { if (dependencies != null) { for (int i = 0; i < dependencies.length; i++) { IObservable observable = dependencies[i]; observable.removeChangeListener(privateInterface); } } }

Target:
I would use the forech loop
Source:
protected SelectRootNodeWizardPage(TmfExperimentElement experiment) { super(""); //$NON-NLS-1$ setTitle(Messages.SelectRootNodeWizardPage_WindowTitle); setDescription(Messages.SelectRootNodeWizardPage_Description); fExperiment = experiment; }

Target:
this is overridable and probably better off in createcontrol?
Source:
protected IFile getFile(IResource resource) { if (resource instanceof IFile) { return (IFile) resource; } return Adapters.getAdapter(resource, IFile.class, true); }

Target:
Lines 1051-1053 are redundant.
Source:
private SaveablesProvider createSaveablesProvider(NavigatorContentDescriptor descriptor) { NavigatorContentExtension extension = contentService .getExtension(descriptor, true); // Use getContentProvider to get the client objects, this is important // for the adaptation below. See bug 306545 ITreeContentProvider contentProvider = extension .getContentProvider(); return (SaveablesProvider)Adapters.getAdapter(contentProvider, SaveablesProvider.class, true); }

Target:
Unnecessary cast
Source:
public static ISaveablePart getSaveable(Object o) { if (o instanceof ISaveablePart) { return (ISaveablePart) o; } return Adapters.getAdapter(o, ISaveablePart.class, true); }

Target:
I think this instanceof check can be deleted, is also done via getAdapter
Source:
public static boolean isText(File file) throws IOException { try (FileInputStream rafile = new FileInputStream(file)) { int count = 0; while (count++ < MAX_NB_BINARY_BYTES) { int val = rafile.read(); if (val == 0) { return false; } } } return true; }

Target:
could this be the min between size and MAX_NB... to avoid an io, or check if val == -1, return true;
Source:
public void testEGetNullEObject() { assertEquals(null, eObjectServices.eGet(null, "query")); }

Target:
Remove useless assert
Source:
public void testEGetNullEObjectNullFeature() { assertEquals(null, eObjectServices.eGet(null, null)); }

Target:
Remove useless assert
Source:
public ChildrenIterator(E root) { this.expectedModCount = Graph.this.modcount; this.iteratorStack = new LinkedList<Iterator<Node<E>>>(); iteratorStack.add(Iterators.singletonIterator(Graph.this.nodes.get(root))); consumedNodes = new LinkedHashSet<Node<E>>(); }

Target:
Why are you using a LinkedHashSet instead of a HashSet? It seems to me that in this usage scenario, maintaining the linked list within LinkedHashSet doesn't pay off, right?
Source:
protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, true); Button button = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); button.setEnabled(false); }

Target:
Both buttons are marked as defaultButton, make up your mind ;) Actually, setting a default button makes that button execute when you press ENTER. So this prevents the 'root path' text in the RemoteResourceBrowserWidget to execute its selection listener, and therefore a user cannot manually type in a path and have the tree update to the typed-in root path. So perhaps they should all be false?
Source:
protected IDocument acquireDocument(IProgressMonitor pm) throws CoreException { SubMonitor subMonitor= SubMonitor.convert(pm, 2); fCUnit.becomeWorkingCopy(subMonitor.newChild(1)); Assert.isTrue(fCUnit.isWorkingCopy(), fCUnit.toString()); return super.acquireDocument(subMonitor.newChild(1)); }

Target:
Change from subMonitor.newChild(...) to subMonitor.split(...)
Source:
void moveAllEventsTo (Synchronizer toReceiveTheEvents) { RunnableLock[] oldMessages; int oldMessageCount; synchronized (messageLock) { oldMessages = messages; oldMessageCount = messageCount; messageCount = 0; } toReceiveTheEvents.addFirst(oldMessages, oldMessageCount); }

Target:
what worries me is that the oldMessages is left unprotected between the calls and in theory could be modified.
Source:
private String getColumnText(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return reviewContainer.getSummary(); case 1: return reviewContainer.getCrString(); case 2: return reviewContainer.getVString(); case 3: return reviewContainer.getIncomingChanges(); default: return ""; } }

Target:
If this is the only reason we have a `getCrString` it'll be user to just store the value as an integer internally (it's true representation) and make a call out to Integer.toString to create the representation.
Source:
public TaskReview(String summary, String cr, String v, String incomingChanges) { super(); this.summary = summary; this.cr = cr; this.v = v; this.incomingChanges = incomingChanges; }

Target:
Why call `super` if there is nothing above it? Maybe there's a best practice I missed the memo on.
Source:
private void expandSection(final FormToolkit toolkit, Section section) { reviewsComposite = toolkit.createComposite(section); section.setClient(reviewsComposite); reviewsComposite.setLayout(EditorUtil.createSectionClientLayout()); getTaskEditorPage().registerDefaultDropListener(section); createReviewsTable(toolkit, reviewsComposite); toolkit.paintBordersFor(reviewsComposite); section.setClient(reviewsComposite); }

Target:
I see a duplicate `setClient` call just below. Are both strictly necessary?
Source:
private static void assertBufferStringAndVariables(String expected, TemplateBuffer buffer) { assertEquals(expected, buffer.getString()); for (TemplateVariable v : buffer.getVariables()) { assertEquals(true, v.isResolved()); assertEquals(true, v.isUnambiguous()); } }

Target:
Why not using directly assertTrue?
Source:
protected String getFileName() { final String fileText = getFileText(); String[] extensions = getFileExtensions(); for (int i = 0; i < extensions.length; ++i) { String extension = extensions[i]; if (extension.isEmpty() || (!extension.isEmpty() && fileText.endsWith("." + extension))) { //$NON-NLS-1$ return fileText; } } return fileText + "." + extensions[0]; //$NON-NLS-1$ }

Target:
Should the empty extension be rather handled here? Just to keep that condition simpler.
Source:
public void setServerContent(Map<String, String> serverContent) { Preconditions.checkNotNull(serverContent); this.serverContent = serverContent; }

Target:
I'd prefer to use static imports for Preconditions, for improved readability and consistency. What do you think?
Source:
public void testRgb() { E4ThemeColor e4ThemeColor = new E4ThemeColor(); RGB rgb = E4ThemeColor.getRGBFromCssString("rgb(238, 238, 238)"); assertEquals(new RGB(238, 238, 238), rgb); }

Target:
Seems like there's no reason to instantiate E4ThemeColor. In fact, can you add a private constructor to E4ThemeColor?
Source:
int nextSpan(int distanceFromTip) { if (distanceFromTip < 0) throw new IllegalArgumentException(); // Commits more toward the start will have more bitmaps. if (distanceFromTip <= recentCommitCount) return recentCommitSpan; int next = Math.min(distanceFromTip - recentCommitCount, distantCommitSpan); return Math.max(next, recentCommitSpan); }

Target:
(nit) braces around one-line if body
Source:
private int extractWorkFromLine(String line) { int pos1 = line.indexOf(DLTK_TOTAL_WORK_START); int pos2 = line.indexOf(DLTK_TOTAL_WORK_END); if (pos1 != -1 && pos2 != -1) { String totalWork = line.substring(pos1 + DLTK_TOTAL_WORK_START.length(), pos2); int intValue = Integer.valueOf(totalWork).intValue(); if (intValue == -1) { return IProgressMonitor.UNKNOWN; } return intValue; } return NOT_WORK_COUNT; }

Target:
parseInt()
Source:
private void traceContainers(String action, long start) { Long delta = Long.valueOf(System.currentTimeMillis() - start); Long length = Long.valueOf(getContainersFile().length()); String pattern = "{0} {1} bytes in containers.dat in {2}ms"; //$NON-NLS-1$ String message = NLS.bind(pattern, new Object[] { action, length, delta }); System.out.println(message); }

Target:
I would suggest "long" type here and let autoboxing work later
Source:
public CellEditor createPropertyEditor(Composite parent) { CellEditor cellEditor = null; if (object instanceof EObject && getPermissionAuthority().canEditInstance((EObject) object)) { cellEditor = super.createPropertyEditor(parent); } return cellEditor; }

Target:
why not call super.createPropertyEditor(parent); if the object is not a EObject? I think this is a bug.
Source:
protected IPapyrusMarker getMarkerA() { if (markerA == null) { // create new marker for node A markerA = new NodeAMarker(getView()); } return markerA; }

Target:
'null' must be the first operande
Source:
public boolean provides(final IOperation operation) { boolean provide = false; // it needs to be a CreateDecoratorsOperation if (operation instanceof CreateDecoratorsOperation) { final IDecoratorTarget decoratorTarget = ((CreateDecoratorsOperation) operation).getDecoratorTarget(); final View view = decoratorTarget.getAdapter(View.class); // Test if the decoratorTarget element is a CallBehavoirAction if (view != null && ActivityDiagramEditPart.MODEL_ID.equals(UMLVisualIDRegistry.getModelID(view)) && view.getElement() instanceof CallBehaviorAction) { provide = true; } else { provide = false; } } return provide; }

Target:
'null' must be first operande
Source:
public void launchTargetsChanged() { targetSelector.refresh(); }

Target:
null check here now
Source:
private static void loadRulesFromFile(IgnoreNode r, File exclude) throws FileNotFoundException, IOException { try { if (FS.DETECTED.exists(exclude)) { FileInputStream in = new FileInputStream(exclude); try { r.parse(in); } finally { in.close(); } } } catch (AccessControlException ignored) { } }

Target:
how is this related to ignoring non-accessibility of ~/.gitconfig ?
Source:
public FileBasedConfig openUserConfig(Config parent, FS fs) { final File home = fs.userHome(); File userConfig = new File(home, ".gitconfig"); try { userConfig.canRead(); } catch (AccessControlException e) { return new FileBasedConfig(null, fs) { public void load() { // empty, do not load } public boolean isOutdated() { // regular class would bomb here return false; } }; } return new FileBasedConfig(parent, userConfig, fs); //$NON-NLS-1$ }

Target:
Does this lose the parent Config?
Source:
final public List<IDecoration> setDecorationsNode(List<IPapyrusDecoration> pDecorations, int margin, boolean isVolatile) { decorations = new BasicEList<IDecoration>(); for (IPapyrusDecoration pDecoration : pDecorations) { Image image = addDecorationNode(pDecoration, margin, isVolatile); if (image != null) { margin += image.getBounds().width; } } // this.pDecorations = pDecorations; return decorations; }

Target:
Now that the list is always created during instantiation, a simple clear() should be sufficient (Rather than creating a new list each time)
Source:
public ITimeGraphEntry @Nullable getChildren(@Nullable Object parentElement) { if (parentElement instanceof CriticalPathEntry) { List<@NonNull ? extends ITimeGraphEntry> children = ((CriticalPathEntry) parentElement).getChildren(); return children.toArray(new TimeGraphEntry[children.size()]); } return null; }

Target:
This does not change anything? However if we change the declaration in ITimeGraphEntry to List<@NonNull ? extends ITimeGraphEntry> getChildren(); Then the returned getChildren() here fits the required declaration, and no more warning. (ok I just noticed you also changed this, ok good!)
Source:
public Iterable<@NonNull IEventDeclaration> getEventDeclarations() { return checkNotNull(ImmutableList.copyOf(fStreamInput.getStream().getEventDeclarations())); }

Target:
redundant, class is @NNBD
Source:
public Iterable<@NonNull ITmfEventAspect> getEventAspects() { return CTF_ASPECTS; }

Target:
We could annotate the base method in TmfTrace directly.
Source:
public @NonNull String getName() { return fTypeId; }

Target:
super-method only
Source:
public static <@NonNull T> Iterable<@NonNull T> getAnalysisModulesOfClass(ITmfTrace trace, Class<T> moduleClass) { Iterable<@NonNull IAnalysisModule> analysisModules = trace.getAnalysisModules(); Set<T> modules = new HashSet<>(); for (IAnalysisModule module : analysisModules) { if (moduleClass.isAssignableFrom(module.getClass())) { modules.add(moduleClass.cast(module)); } } return modules; }

Target:
don't annotate the first part
Source:
public IKernelAnalysisEventLayout getEventLayout(ITmfTrace trace) { IKernelAnalysisEventLayout layout = LttngEventLayout.getInstance(); if (trace instanceof LttngKernelTrace) { layout = ((LttngKernelTrace) trace).getKernelEventLayout(); } return layout; }

Target:
You don't need this variable: if (trace instanceof LttngKernelTrace) { return ((LttngKernelTrace) trace).getKernelEventLayout(); } return LttngEventLayout.getInstance();
Source:
public long getAtsSearchUuid() { if (iWorldEditorProvider instanceof WorldEditorParameterSearchItemProvider) { WorldSearchItem worldSearchItem = ((WorldEditorParameterSearchItemProvider) iWorldEditorProvider).getWorldSearchItem(); if (worldSearchItem instanceof AtsSearchWorkflowSearchItem) { return ((AtsSearchWorkflowSearchItem) worldSearchItem).getSearchUuid(); } } return 0L; }

Target:
long or Long in this case? There's been discussion making this consistent in our code base. Is it appropriate to make that change here and now?
Source:
private boolean isArtifact(ITask task) { // If it has associated task and has no context, scheduled date, or due date; artifact // TODO: This will require work on Blaine's part.. pending boolean hasAssosciatedTask = true; boolean hasContext = TasksUiPlugin.getContextStore().hasContext(task); // Two kludgy options here... // A) Cast to AbstractTask; do a direct comparison... but requires knowledge of the "concrete implementation" // B) Seems like we could delegate out to TaskActivityManager (better option?) // TODO: Figure out the best course of action for this; using the kludge for now (since I know it'l be replaced // and it'll give me a push to actually come back) boolean hasScheduledDate = false; AbstractTask abstractTask = (AbstractTask) task; if (abstractTask != null) { hasScheduledDate = abstractTask.getScheduledForDate() != null; } boolean hasDueDate = task.getDueDate() != null; return hasAssosciatedTask && !(hasAssosciatedTask || hasScheduledDate || hasDueDate); }

Target:
The second hasAssosciatedTask should be hasContext?
Source:
public void setToolTipText(ILaunchTarget target) { String text = Messages.TargetSelector_ToolTipPrefix + ": " + targetManager.getStatus(target).getMessage(); //$NON-NLS-1$ setToolTipText(text); System.out.println(text); }

Target:
debug print
Source:
public static boolean needFigureChange(final WorkspaceImage bundledImage, IWorkspaceImageFigure figure) { boolean result = false; String workspacePath = bundledImage.getWorkspacePath(); if (StringUtil.isEmpty(workspacePath)) { if (!(figure instanceof WorkspaceImageFigure)) { result = true; } } else if (WorkspaceImageFigure.isSvgImage(workspacePath)) { if (!(figure instanceof SVGWorkspaceImageFigure)) { result = true; } } else if (!(figure instanceof WorkspaceImageFigure)) { result = true; } return result; }

Target:
We should simplify this by replacing the if(x){result = true;} by result = x;
Source:
protected IStatus run(IProgressMonitor monitor) { ISourceModule module = null; while ((module = modules.poll()) != null) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } processModule(module, buildType, state); } return Status.OK_STATUS; }

Target:
initial null seems not needed. Probably can be a for () loop :) for (ISourceModule module; (module = modules.poll()) != null;) { ... }
Source:
public IBorderItemLocator getNewBorderItemLocator(IFigure mainFigure) { ParameterPositionLocator locator = new ParameterPositionLocator(mainFigure, PositionConstants.NONE); return locator; }

Target:
return directly the value (Sonar rule)
Source:
public void testReviewArtifactIsFiltered() { ITask task = mock(ITask.class); when(task.getAttribute("ARTIFACT")).thenReturn("true"); TaskReviewArtifactFilter filter = new TaskReviewArtifactFilter(); boolean wasFiltered = !filter.select(null, task); Assert.assertTrue(wasFiltered); }

Target:
use static import for Assert.* methods.
Source:
public long getModificationDate() { if (getResource().isAccessible()) { return super.getModificationDate(); } return timestamp; }

Target:
why do we need this ? The type says it's a non-workspace typed element ... I'd assume that instances which are resources are rather of the super-class type
Source:
public boolean isSynchronized() { if (getResource().isAccessible()) { return super.isSynchronized(); } return path.toFile().lastModified() == timestamp; }

Target:
why do we need this ? The type says it's a non-workspace typed element ... I'd assume that instances which are resources are rather of the super-class type
Source:
private Repository getRepository(IFileBuffer buffer) { IPath location = getPath(buffer); if (location != null) { return org.eclipse.egit.core.Activator.getDefault() .getRepositoryCache().getRepository(location); } return null; }

Target:
Nit: package can be removed; Activator is already imported.
Source:
public String getBranch() throws IOException { String name = getFullBranch(); if (name != null) return shortenRefName(name); return name; }

Target:
return null to make this more explicit ?
Source:
private void initRevPool(boolean reverse) { if (queue != null) throw new IllegalStateException(); if (revPool != null) revPool.close(); if (reverse) revPool = new ReverseWalk(getRepository()); else revPool = new RevWalk(getRepository()); SEEN = revPool.newFlag("SEEN"); //$NON-NLS-1$ reader = revPool.getObjectReader(); treeWalk = new TreeWalk(getRepository(), reader); treeWalk.setRecursive(true); }

Target:
is this change needed?
Source:
InCoreMerger(final Repository local) { super(local); tw = new NameConflictTreeWalk(local, reader); cache = DirCache.newInCore(); }

Target:
The incore merger works in memory without a working tree. Does he need attribute handling?
Source:
public int getKeyBinding(int key) { checkWidget(); Integer action = keyActionMap.get(new Integer(key)); return action == null ? SWT.NULL : action.intValue(); }

Target:
Revert ?
Source:
public static int resolveTextDirection (String text) { return 0; }

Target:
Suggest we replace with: return SWT.NONE;
Source:
protected int getSpecificHeaderSize() { int maxChildren = getConfig().getMaxChildren(); int specificSize = SIZE_INT /* 1x int (extension node) */ + SIZE_INT /* 1x int (nbChildren) */ /* MAX_NB * int ('children' table) */ + SIZE_INT * maxChildren /* MAX_NB * Timevalue ('childStart' table) */ + SIZE_LONG * maxChildren /* MAX_NB * Timevalue ('childEnd' table) */ + SIZE_LONG * maxChildren /* MAX_NB * Timevalue ('childMin' table) */ + SIZE_INT * maxChildren /* MAX_NB * Timevalue ('childMax' table) */ + SIZE_INT * maxChildren; return specificSize; }

Target:
What are those 2 ints? I don't see them written to the header
Source:
public int setCloseTime(int childSequenceNumber, long endTime) { int index = -1; for (int i = 0; i < nbChildren; i++) { if (childSequenceNumber == this.children[i]) { childEnd[i] = endTime; index = i; } } return index; }

Target:
return i; Or break; No need to continue the loop
Source:
public List<Integer> getIntersectingChildren(long time) { List<Integer> intersectingChildren = new LinkedList<>(); for (int i = 0; i < nbChildren; i++) { if (time >= childStart[i] && time <= childEnd[i]) { intersectingChildren.add(children[i]); } } return intersectingChildren; }

Target:
This might be better as an array list. Faster iteration, and such.
Source:
public int setCloseTime(int childSequenceNumber, long endTime) { for (int i = 0; i < nbChildren; i++) { if (childSequenceNumber == this.children[i]) { childEnd[i] = endTime; return i; } } return -1; }

Target:
no need for the "this"
Source:
public LooseRef peel(ObjectIdRef newLeaf) { ObjectId peeledObjectId = newLeaf.getPeeledObjectId(); ObjectId objectId = getObjectId(); assert objectId != null; if (peeledObjectId != null) { return new LoosePeeledTag(snapShot, getName(), objectId, peeledObjectId); } else { return new LooseNonTag(snapShot, getName(), objectId); } }

Target:
An alternative way to phrase this would be to make ObjectIdRef.Unpeeled.getObjectId return non-null: @NonNull @Override public ObjectId getObjectId() { ObjectId id = super.getObjectId(); assert id != null; // checked in constructor return id; }
Source:
private static <T> T getService(Class<T> serviceClass) { final Bundle bundle = FrameworkUtil.getBundle(ViewModelMigratorUtil.class); final BundleContext bundleContext = bundle.getBundleContext(); final ServiceReference<T> serviceReference = bundleContext.getServiceReference(serviceClass); if (serviceReference == null) { return null; } final Object service = bundleContext.getService(serviceReference); bundleContext.ungetService(serviceReference); return serviceClass.cast(service); }

Target:
this should already be T so no cast necessary later