auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected IType getType(IBinding binding) { if (!isAnonymousBinding(binding)) { if (binding instanceof IVariable) { return ((IVariable) binding).getType(); } else { START return null; END } } return null; } Redundant 'else' clause.

Target:
protected IType getType(IBinding binding) { if (!isAnonymousBinding(binding) && binding instanceof IVariable) return ((IVariable) binding).getType(); return null; }
Source:
protected void doExecute() { for (Stereotype stereotype : stereotypes) { element.unapplyStereotype(stereotype); START element.eNotify(new NotificationImpl(Notification.SET, true, true, true)); END } } checkif you could remove that because there is already a notification service for stereotype

Target:
protected void doExecute() { for (Stereotype stereotype : stereotypes) { element.unapplyStereotype(stereotype); } }
Source:
START public static void openInCompare(RevCommit commit1, END 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); } avoid unrelated formatting changes

Target:
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, null); CompareUtils.openInCompare(workBenchPage, repository, in); }
Source:
public String getPath() { URI uri = fileRevision.getURI(); START if (uri != null) { END return uri.getPath(); } return getName(); } revert this unrelated formatting change

Target:
public String getPath() { URI uri = fileRevision.getURI(); if (uri != null) return uri.getPath(); return getName(); }
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){ START System.out.println("jhghg"); END } } To be removed

Target:
protected void initModel(String projectName, String modelName, Bundle bundle) throws CoreException, IOException { project = ProjectUtils.createProject(projectName); diModelFile = PapyrusProjectUtils.copyPapyrusModel(project, bundle, getSourcePath(), modelName); }
Source:
public AbstractCriticalPathAlgorithm(TmfGraph graph) { START this.fGraph = graph; END } Done

Target:
public AbstractCriticalPathAlgorithm(TmfGraph graph) { fGraph = graph; }
Source:
protected void executeAppliedStereotypeCommentDeletion(final TransactionalEditingDomain domain, final View commentNode) { if (null != commentNode) { START if (domain != null && TransactionUtil.getEditingDomain(commentNode) == domain) { END DeleteCommand command = new DeleteCommand(commentNode); try { GMFUnsafe.write(domain, command); } catch (Exception e) { Activator.log.error(e); } } } } The constant must be before the variable when you use an operator.

Target:
protected void executeAppliedStereotypeCommentDeletion(final TransactionalEditingDomain domain, final View commentNode) { if (null != commentNode) { if (null != domain && TransactionUtil.getEditingDomain(commentNode) == domain) { DeleteCommand command = new DeleteCommand(commentNode); try { GMFUnsafe.write(domain, command); } catch (Exception e) { Activator.log.error(e); } } } }
Source:
private static ITmfEventField getRootField(CustomTraceDefinition definition) { ITmfEventField[] fields = new ITmfEventField[definition.outputs.size()]; for (int i = 0; i < fields.length; i++) { START fields[i] = new TmfEventField(nullToEmptyString(definition.outputs.get(i).name), null, null); END } ITmfEventField rootField = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); return rootField; } cnn

Target:
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(definition.outputs.get(i).name, null, null); } ITmfEventField rootField = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); return rootField; }
Source:
public Object getAdapter(@SuppressWarnings("rawtypes") final Class adapter) { /* @SuppressWarnings("rawtypes"): gdupe> Imposed by the super class */ Object result; START if ("interface org.eclipse.emf.facet.widgets.table.ui.internal.exported.ITableWidgetProvider".equals(adapter.toString())) { System.out.println(); } END if (adapter.isInstance(this)) { result = this; } else { result = this.widget.getAdapter(adapter); if (result == null) { result = super.getAdapter(adapter); } } return result; } I assume you didn't expect to commit that :-D

Target:
public Object getAdapter(@SuppressWarnings("rawtypes") final Class adapter) { /* @SuppressWarnings("rawtypes"): gdupe> Imposed by the super class */ Object result; if (adapter.isInstance(this)) { result = this; } else { result = this.widget.getAdapter(adapter); if (result == null) { result = super.getAdapter(adapter); } } return result; }
Source:
public ColorColumn getColumnById(String id) { START System.err.println(id); END for (ColorColumn column : colorColumns) { if (column.getColumnId().equals(id)) { return column; } } return null; } can this be logged instead? or removed if not needed?

Target:
public ColorColumn getColumnById(String id) { for (ColorColumn column : colorColumns) { if (column.getColumnId().equals(id)) { return column; } } return null; }
Source:
private boolean isFormatValid(String format) { START String formatToCheck = format.replace("'(.*?)'", ""); END return !formatToCheck.contains("w") && !formatToCheck.contains("W") && !formatToCheck.contains("MMM") && !formatToCheck.contains("G") && !formatToCheck.contains("E") && !formatToCheck.contains("Z"); } Das gibt eine NullPointerException, wenn format = null.

Target:
private boolean isFormatValid(String format) { if (format == null) { return true; } String formatToCheck = format.replace("'(.*?)'", ""); return !formatToCheck.contains("w") && !formatToCheck.contains("W") && !formatToCheck.contains("MMM") && !formatToCheck.contains("G") && !formatToCheck.contains("E") && !formatToCheck.contains("Z"); }
Source:
public void sourceSubstituteAdded() throws Throwable { START sourceMappingAddedHelper(false); END } Parameter should be true here, no?

Target:
public void sourceSubstituteAdded() throws Throwable { sourceMappingAddedHelper(true); }
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); } START fTraceSSMap.put(trace, ss); END } } 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.

Target:
protected void addToEntryList(ITmfTrace trace, ITmfStateSystem ss, List<TimeGraphEntry> list) { super.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); } }
Source:
public void setData(@Nullable LatencyAnalysis analysis) { if (analysis == null) { START return; END } 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); } If selected trace is not a kernel trace, the old viewer data remains. You could call updateModel(null) here.

Target:
public void setData(@Nullable LatencyAnalysis analysis) { if (analysis == null) { updateModel(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; } updateModel(null); LatencyViewerUtils.runAnalysis(fListener); }
Source:
public void dispose() { START getTableViewer().getTable().dispose(); END super.dispose(); } The controls will get disposed by the platform. You only need to call super.dispose() because the viewer is a TmfComponent.

Target:
public void dispose() { super.dispose(); }
Source:
public void traceSelected(@Nullable TmfTraceSelectedSignal signal) { LatencyAnalysis analysis = LatencyViewerUtils.getAnalysisFromSignal(signal); if (analysis != null) { START analysis.addListener(fListener); END // 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); } } If you switch back and forth between traces you are added many times as a listener

Target:
public void traceSelected(@Nullable TmfTraceSelectedSignal signal) { LatencyAnalysis analysis = LatencyViewerUtils.getAnalysisFromSignal(signal); fData = LatencyViewerUtils.getResultsFromAnalysis(analysis); updateModel(fData); }
Source:
public void traceOpened(@Nullable TmfTraceOpenedSignal signal) { LatencyAnalysis analysis = LatencyViewerUtils.getAnalysisFromSignal(signal); if (analysis != null) { START analysis.addListener(fListener); END LatencyViewerUtils.runAnalysis(); } } You will be a listener at least twice, since traceSelected follows traceOpened

Target:
public void traceOpened(@Nullable TmfTraceOpenedSignal signal) { LatencyAnalysis analysis = LatencyViewerUtils.getAnalysisFromSignal(signal); if (analysis != null) { LatencyViewerUtils.runAnalysis(fListener); } }
Source:
public static LatencyDataStore getResultsFromAnalysis(@Nullable LatencyAnalysis analysis) { if (analysis != null) { ISegmentStore<ISegment> results = analysis.getResults(); if (results != null) { START return storeAndGet(results); END } } return new LatencyDataStore(new TreeMapStore<>()); } 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?

Target:
public static LatencyDataStore getResultsFromAnalysis(@Nullable LatencyAnalysis analysis) { ISegmentStore<ISegment> results = null; if (analysis != null) { results = analysis.getResults(); } return storeAndGet(results); }
Source:
public void updateElement(int index) { final TableViewer tableViewer = fTableViewer; final ISegment[] segmentArray = fSegmentArray; START if (tableViewer != null && segmentArray != null) { tableViewer.replace(segmentArray[index], index); } END } 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?

Target:
public void updateElement(int index) { final TableViewer tableViewer = fTableViewer; final ISegment[] segmentArray = fSegmentArray; if (tableViewer != null && segmentArray != null) { if (index < segmentArray.length) { tableViewer.replace(segmentArray[index], index); } } }
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); } START } END } Set the segment array to null if the input is not a valid segment store.

Target:
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); } } else { fSegmentArray = null; } }
Source:
protected boolean START isSpanMarkup(char END character) { return SPAN_MARKUP_CHARACTERS.matches(character); } consider making this method private or package scope

Target:
private boolean isSpanMarkup(char character) { return SPAN_MARKUP_CHARACTERS.matches(character); }
Source:
public String getPath() { START try { return file.toURI().getPath(); } catch (URISyntaxException e) { return file.getFile(); } END } can you please set the instruction file.getPath () in case of errors instead of file.getFile()

Target:
public String getPath() { try { return file.toURI().getPath(); } catch (URISyntaxException e) { return file.getPath(); } }
Source:
START public void setAlphabeticallySortActive(boolean sort) { END this.alphabeticallySort = sort; } doesn't need to be public

Target:
private void setAlphabeticallySortActive(boolean sort) { this.alphabeticallySort = sort; }
Source:
protected String getLabel(EObject eObject) { START Preconditions.checkNotNull(adapterFactory); END if (eObject != null) { Object adapter = adapterFactory.adapt(eObject, ISemanticObjectLabelProvider.class); if (adapter instanceof ISemanticObjectLabelProvider) { return ((ISemanticObjectLabelProvider)adapter).getSemanticObjectLabel(eObject); } } return null; } 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.

Target:
protected String getLabel(EObject eObject) { if (eObject != null) { Object adapter = adapterFactory.adapt(eObject, ISemanticObjectLabelProvider.class); if (adapter instanceof ISemanticObjectLabelProvider) { return ((ISemanticObjectLabelProvider)adapter).getSemanticObjectLabel(eObject); } } return null; }
Source:
public void updateElement(int index) { final TableViewer tableViewer = fTableViewer; final ISegment[] segmentArray = fSegmentArray; if ((tableViewer != null) && (segmentArray != null) && START (segmentArray.length > index) && !fOngoingUpdate) { END fOngoingUpdate = true; tableViewer.replace(segmentArray[index], index); fOngoingUpdate = false; } } 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.

Target:
public void updateElement(int index) { final TableViewer tableViewer = fTableViewer; final ISegment[] segmentArray = fSegmentArray; if ((tableViewer != null) && (segmentArray != null) && (segmentArray.length > index)) { tableViewer.replace(segmentArray[index], index); } }
Source:
START public void refreshPieCharts(final boolean refreshGlobal, final boolean refreshSelection) { END 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); } } }); } protected

Target:
protected 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); } } }); }
Source:
START public void modelComplete(boolean global) { END refreshTree(); waitCursor(false); } protected

Target:
protected void modelComplete(boolean global) { refreshTree(); waitCursor(false); }
Source:
START PieChart getGlobalPC() { END return fGlobalPC; } needs to be synchronized

Target:
synchronized PieChart getGlobalPC() { return fGlobalPC; }
Source:
public TmfPieChartStatisticsModel getPieChartModel(){ START return fPieChartModel; END } 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;

Target:
public TmfPieChartStatisticsModel getPieChartModel(){ if (fPieChartModel == null) { fPieChartModel = new TmfPieChartStatisticsModel(); } return fPieChartModel; }
Source:
START public void refreshTree(){ END 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(); } } }); } can be private

Target:
private 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(); } } }); }
Source:
START public void removeFromJobs(boolean isGlobal, ITmfTrace jobTrace) { END Map<ITmfTrace, Job> updateJobs = isGlobal ? fUpdateJobsGlobal : fUpdateJobsPartial; Job job = updateJobs.remove(jobTrace); if (job != null) { job.cancel(); } } package visible only

Target:
void removeFromJobs(boolean isGlobal, ITmfTrace jobTrace) { Map<ITmfTrace, Job> updateJobs = isGlobal ? fUpdateJobsGlobal : fUpdateJobsPartial; Job job = updateJobs.remove(jobTrace); if (job != null) { job.cancel(); } }
Source:
public void newGlobalEntries(final TmfPieChartViewer context) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { START synchronized (context.getMutexLayoutChange()) { END if (!context.isDisposed()) { context.updateGlobalPieChart(); context.getGlobalPC().redraw(); } } } }); } just use context as sync obj.

Target:
public void newGlobalEntries(final TmfPieChartViewer context) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { synchronized (context) { if (!context.isDisposed()) { context.updateGlobalPieChart(); context.getGlobalPC().redraw(); } } } }); }
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; START fModel = new TmfStatisticsModel(); END // The viewer will process all events if he is assigned to an experiment fProcessAll = (trace instanceof TmfExperiment); initContent(parent); initInput(); } remove

Target:
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; // The viewer will process all events if he is assigned to an experiment fProcessAll = (trace instanceof TmfExperiment); initContent(parent); initInput(); }
Source:
public Boolean exists(Collection<Object> collection, LambdaValue lambda) { Boolean result = Boolean.FALSE; if (collection != null && lambda == null) { result = Boolean.FALSE; } else { START for (Object input : collection) { END 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; } 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.

Target:
public Boolean exists(Collection<Object> collection, LambdaValue lambda) { Boolean result = Boolean.FALSE; if (collection != null && lambda != null) { 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; }
Source:
START public Map<String, ArtifactReadable> getCoverageUnits(long branchUuid, String artifactUuid) { END IOseeBranch branch = TokenFactory.createBranch(branchUuid, ""); ArtifactReadable coveragePackage = getQuery().fromBranch(branchUuid).andGuid(artifactUuid).getResults().getOneOrNull(); List<ArtifactReadable> descendants = coveragePackage.getDescendants(); return getChildrenRecurse(descendants, branch); } don't think branch is needed, but if it is, it can be gotten from the coveragePackage artifact readable.

Target:
public Map<String, ArtifactReadable> getCoverageUnits(long branchUuid, String artifactUuid) { ArtifactReadable coveragePackage = getQuery().fromBranch(branchUuid).andGuid(artifactUuid).getResults().getOneOrNull(); List<ArtifactReadable> descendants = coveragePackage.getDescendants(); return getChildrenRecurse(descendants); }
Source:
protected CtfTmfEvent getEvent(int rank) { START ITmfContext ctx = fTrace.getTrace().seekEvent(0); END for (int i = 0; i < rank; i++) { fTrace.getTrace().getNext(ctx); } final CtfTmfEvent next = fTrace.getTrace().getNext(ctx); ctx.dispose(); return next; } Why not seekEvent(rank) ?

Target:
protected CtfTmfEvent getEvent(int rank) { ITmfContext ctx = fTrace.getTrace().seekEvent(rank); final CtfTmfEvent next = fTrace.getTrace().getNext(ctx); ctx.dispose(); return next; }
Source:
START private void updateTitle(String brand) { END IBrandManager brandManager = TasksUiPlugin.getDefault().getBrandManager(); setTitle(brandManager.getConnectorLabel(getConnector(), brand)); } Should this be protected?

Target:
protected void updateTitle(String brand) { IBrandManager brandManager = TasksUiPlugin.getDefault().getBrandManager(); setTitle(brandManager.getConnectorLabel(getConnector(), brand)); }
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(); } START dir.deleteOnExit(); END return path; } weird

Target:
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(); } return path; }
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$ START setPageComplete(true); END this.model = model; } Is this necessary ? isPageComplete() is overriden anyways to check for a selected image and should always be checked.

Target:
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$ this.model = model; }
Source:
public Object[] getElements(Object inputElement) { START List<IBrowserDescriptor> list = new ArrayList<IBrowserDescriptor>(); END Iterator<IBrowserDescriptor> iterator = BrowserManager.getInstance().getWebBrowsers() .iterator(); while (iterator.hasNext()) { IBrowserDescriptor browser = iterator .next(); list.add(browser); } return list.toArray(); } Please remove redundant type information in another follow up commit

Target:
public Object[] getElements(Object inputElement) { List<IBrowserDescriptor> list = new ArrayList<>(); Iterator<IBrowserDescriptor> iterator = BrowserManager.getInstance().getWebBrowsers() .iterator(); while (iterator.hasNext()) { IBrowserDescriptor browser = iterator .next(); list.add(browser); } return list.toArray(); }
Source:
public Command START transactionAboutToCommit(ResourceSetChangeEvent END 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; } 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.

Target:
public Command transactionAboutToCommit(ResourceSetChangeEvent event) throws RollbackException { // Get filtered notifications List<Notification> filteredNotificationsList = event.getNotifications(); Command refactorCommand = null; // Handle each filtered notification if (!filteredNotificationsList.isEmpty()) { refactorCommand = handleFilteredNotification(filteredNotificationsList.get(0)); } return refactorCommand; }
Source:
public String getText(Object element) { String label = START UNKNOWN_LABEL_TEXT; END if (element instanceof IStorage) { label = ((IStorage) element).getName(); } else { label = super.getText(element); } return label; } This is never returned.

Target:
public String getText(Object element) { String label = null; if (element instanceof IStorage) { label = ((IStorage) element).getName(); } else { label = super.getText(element); } return label; }
Source:
public String getText(final Object element) { String text = "<UNKNOWN>"; if (element instanceof RefactorScope) { text = START element.toString(); END } return text; } This is the all-capitals name of the enumeration constant in the code. Better would be the human-readable name (from the getName() method).

Target:
public String getText(final Object element) { String text = "<UNKNOWN>"; if (element instanceof RefactorScope) { text = ((RefactorScope) element).getName(); } return text; }
Source:
public StorageTraversal getStorageTraversal() { START Collection<IResource> resources = Arrays.asList(papyrusFile.getAssociatedResources()); END Set<IStorage> storages = getStorages(resources); return new StorageTraversal(storages); } 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

Target:
public StorageTraversal getStorageTraversal() { IResource[] resources = papyrusFile.getAssociatedResources(); Set<IStorage> storages = getStorages(resources); return new StorageTraversal(storages); }
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); } START else { END //checkParent(table, parent); // Bug 471967 this seems to be not necessary and causing issues } return table; } Remove the 'else' branch.

Target:
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); } return table; }
Source:
START private List<Object> buildParametersList() { END List<Object> result = new ArrayList(this.generatorParameters.length); for (String param : this.generatorParameters) { result.add(param); } return result; } Can be changed to Arrays.asList(this.generatorParameters)

Target:
private List<String> buildParametersList() { return Arrays.asList(this.generatorParameters); }
Source:
public boolean performOk() { doGetPreferenceStore().setValue(UIPreferences.WARN_BEFORE_COMMITTING, warnCheckbox.getSelection()); START System.out.println(warnCheckbox.getSelection()); END System.out.println(blockCheckbox.getSelection()); doGetPreferenceStore().setValue(UIPreferences.BLOCK_COMMIT, blockCheckbox.getSelection()); return super.performOk(); } these trace statements should be removed

Target:
public boolean performOk() { doGetPreferenceStore().setValue(UIPreferences.WARN_BEFORE_COMMITTING, warnCheckbox.getSelection()); doGetPreferenceStore().setValue(UIPreferences.BLOCK_COMMIT, blockCheckbox.getSelection()); return super.performOk(); }
Source:
public void tearDown() START throws Exception { END setFixture(null); } Not necessary. See quality rule : MITRE, CWE-397 - Declaration of Throws for Generic Exception

Target:
public void tearDown(){ setFixture(null); }
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); START } END } 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.

Target:
private void selectRepresentationElements(ISelection selection, DialectEditor dialectEditor) { List<DRepresentationElement> representationElements = getRepresentationElements(dialectEditor.getRepresentation(), ((IStructuredSelection) selection).toList()); // if (!representationElements.isEmpty()) { DialectUIManager.INSTANCE.selectAndReveal(dialectEditor, representationElements); // } }
Source:
START AlternateHandle.Id getAlternateId() { END return wrapped.getAlternateId(); } this method could be declared private

Target:
private AlternateHandle.Id getAlternateId() { return wrapped.getAlternateId(); }
Source:
Set<AlternateHandle.Id> skipMe(Set<AlternateHandle.Id> skips) { Set<AlternateHandle.Id> withMe = new HashSet<AlternateHandle.Id>(); START if (skips != null) withMe.addAll(skips); END withMe.add(getAlternateId()); return withMe; } nit: add braces on the if-block.

Target:
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; }
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; START if (file == null) { END local = false; } else { local = true; } if (!isLocal && findFileRevision != null) { return new StoragePathAdapter(path, local, findFileRevision.getContentIdentifier(), findFileRevision.getAuthor()); } else { return new StoragePathAdapter(path, local); } } Replace with boolean local = file != null;

Target:
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 = file != null; if (!isLocal && findFileRevision != null) { return new StoragePathAdapter(path, local, findFileRevision.getContentIdentifier(), findFileRevision.getAuthor()); } else { return new StoragePathAdapter(path, local); } }
Source:
public void setContainer(final IWizardContainer wizardContainer) { super.setContainer(wizardContainer); // Bug 476838: the container was null using getShell() of this wizard. START wizardContainer.getShell().setImage(Activator.getDefault().getImage(ImageConstants.PAPYRUS_ICON_PATH)); // $NON-NLS-1$ END } A conditionnal test must be added for the wizard container (null !=)

Target:
public void setContainer(final IWizardContainer wizardContainer) { super.setContainer(wizardContainer); // Bug 476838: the container was null using getShell() of this wizard. if (null != wizardContainer) { wizardContainer.getShell().setImage(Activator.getDefault().getImage(ImageConstants.PAPYRUS_ICON_PATH)); // $NON-NLS-1$ } }
Source:
private View getPortView(Port port) { View portView = null; Iterator<?> iterator = hostView.getChildren().iterator(); while (iterator.hasNext() START && null == portView) { END Object child = iterator.next(); if ((child instanceof Node) && ((Node) child).getElement().equals(port)) { portView = (Node) child; } } return portView; } The break-condition has to be before continue-condition.

Target:
private View getPortView(Port port) { View portView = null; Iterator<?> iterator = hostView.getChildren().iterator(); while (null == portView && iterator.hasNext()) { Object child = iterator.next(); if ((child instanceof Node) && ((Node) child).getElement().equals(port)) { portView = (Node) child; } } return portView; }
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()); } START System.out.println(listBranchesResult[0].getRef()); END // Verify result assertEquals(listBranchesResult[0].getRef(), "HEAD"); } The System.out should be removed here

Target:
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()); } // Verify result assertEquals(listBranchesResult[0].getRef(), "HEAD"); }
Source:
public String isCan_delete() { START return can_delete; END } should return a boolean

Target:
public boolean isCan_delete() { return can_delete; }
Source:
public Collection<RepositoryMapping> find(IProgressMonitor m, boolean searchLinkedFolders) throws CoreException { START IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; END find(monitor, proj, searchLinkedFolders); return results; } Delete and pass on m.

Target:
public List<RepositoryMapping> find(IProgressMonitor m, boolean searchLinkedFolders) throws CoreException { find(m, proj, searchLinkedFolders); return results; }
Source:
public void run(IProgressMonitor monitor) throws CoreException { ArrayList<TextFileChange> list = new ArrayList<>(); if (fDesc != null) { START SubMonitor subMonitor = SubMonitor.convert(monitor, "", 3); //$NON-NLS-1$ END findRequireBundleReferences(list, subMonitor.newChild(1)); findFragmentReferences(list, subMonitor.newChild(1)); findXFriendReferences(list, subMonitor.newChild(1)); } fChanges = list.toArray(new Change[list.size()]); } Use the two-argument constructor

Target:
public void run(IProgressMonitor monitor) throws CoreException { ArrayList<TextFileChange> list = new ArrayList<>(); if (fDesc != null) { SubMonitor subMonitor = SubMonitor.convert(monitor, 3); findRequireBundleReferences(list, subMonitor.newChild(1)); findFragmentReferences(list, subMonitor.newChild(1)); findXFriendReferences(list, subMonitor.newChild(1)); } fChanges = list.toArray(new Change[list.size()]); }
Source:
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { CompositeChange change = new CompositeChange(MessageFormat.format(PDEUIMessages.RenameExtensionPointProcessor_changeTitle, new Object[] {fInfo.getCurrentValue(), fInfo.getNewValue()})); START SubMonitor subMonitor = SubMonitor.convert(pm, "", 2); //$NON-NLS-1$ END changeExtensionPoint(change, subMonitor.newChild(1)); if (fInfo.isUpdateReferences()) findReferences(change, subMonitor.newChild(1)); return change; } Use two parameter constructor

Target:
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); changeExtensionPoint(change, subMonitor.newChild(1)); if (fInfo.isUpdateReferences()) findReferences(change, subMonitor.newChild(1)); return change; }
Source:
private boolean isUnused(ImportPackageObject pkg, Collection<?> exportedPackages, IProgressMonitor monitor) { if (exportedPackages != null && exportedPackages.contains(pkg.getValue())) { START monitor.done(); END return false; } return !provideJavaClasses(pkg, monitor); } Unnecessary

Target:
private boolean isUnused(ImportPackageObject pkg, Collection<?> exportedPackages, IProgressMonitor monitor) { if (exportedPackages != null && exportedPackages.contains(pkg.getValue())) { return false; } return !provideJavaClasses(pkg, monitor); }
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 START e.printStackTrace(); END } } Just throw (don't catch) the exception so the test fails.

Target:
public void addReviewData(ITask review, String description) throws CoreException { TaskData reviewData = new TaskData(new TaskAttributeMapper(new TaskRepository("", "")), "", review.getUrl(), review.getTaskId()); reviewData.getRoot().createMappedAttribute(TaskAttribute.DESCRIPTION).setValue(description); when(taskDataManager.getTaskData(review)).thenReturn(reviewData); }
Source:
public void testNull() { START org.eclipse.papyrus.sysml14.nattable.requirement.tester.RequirementTableTester END 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()); } import just

Target:
public void testNull() { RequirementTableTester tableRequirementTester = new RequirementTableTester(); IStatus emptyNotAllowed = tableRequirementTester.isAllowed(null); Assert.assertEquals("The tester should not work on a null entry", IStatus.ERROR, emptyNotAllowed.getSeverity()); //$NON-NLS-1$ }
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); START Assert.assertEquals("The tester should not work on a non profiled entry", IStatus.ERROR, missingStereotypeNotAllowed.getSeverity()); END } //$NON-NLS-0$ ?

Target:
public void testMissingProfile() { RequirementTableTester tableRequirementTester = new 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()); //$NON-NLS-1$ }
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 START SubProgressMonitor(monitor, END 1); ignoreOp.execute(subMonitor); } } Why this? Just pass through 'monitor'.

Target:
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); ignoreOp.execute(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 ); START pstore.setDefault( ICDebugPreferenceConstants.PREF_REVERSE_TRACE_METHOD_HARDWARE, ICDebugPreferenceConstants.PREF_REVERSE_TRACE_METHOD_GDB_TRACE); END } If we move the preference page to dsf.gdb.ui then the above change should go in GdbPreferenceInitializer.java

Target:
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); }
Source:
private void stopListening() { if (dependencies != null) { START for (int i = 0; i < dependencies.length; i++) { END IObservable observable = dependencies[i]; observable.removeChangeListener(privateInterface); } } } I would use the forech loop

Target:
private void stopListening() { if (dependencies != null) { for (IObservable observable : dependencies) { observable.removeChangeListener(privateInterface); } } }
Source:
protected SelectRootNodeWizardPage(TmfExperimentElement experiment) { super(""); //$NON-NLS-1$ START setTitle(Messages.SelectRootNodeWizardPage_WindowTitle); END setDescription(Messages.SelectRootNodeWizardPage_Description); fExperiment = experiment; } this is overridable and probably better off in createcontrol?

Target:
protected SelectRootNodeWizardPage(TmfExperimentElement experiment) { super(""); //$NON-NLS-1$ fExperiment = experiment; }
Source:
protected IFile getFile(IResource resource) { if START (resource instanceof END IFile) { return (IFile) resource; } return Adapters.getAdapter(resource, IFile.class, true); } Lines 1051-1053 are redundant.

Target:
protected IFile getFile(IResource resource) { return Adapters.getAdapter(resource, IFile.class, true); }
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(); START return (SaveablesProvider)Adapters.getAdapter(contentProvider, SaveablesProvider.class, true); END } Unnecessary cast

Target:
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 Adapters.getAdapter(contentProvider, SaveablesProvider.class, true); }
Source:
public static ISaveablePart getSaveable(Object o) { START if (o instanceof ISaveablePart) { END return (ISaveablePart) o; } return Adapters.getAdapter(o, ISaveablePart.class, true); } I think this instanceof check can be deleted, is also done via getAdapter

Target:
public static ISaveablePart getSaveable(Object o) { return Adapters.getAdapter(o, ISaveablePart.class, true); }
Source:
public static boolean isText(File file) throws IOException { try (FileInputStream rafile = new FileInputStream(file)) { int count = 0; START while (count++ < MAX_NB_BINARY_BYTES) { END int val = rafile.read(); if (val == 0) { return false; } } } return true; } could this be the min between size and MAX_NB... to avoid an io, or check if val == -1, return true;

Target:
public static boolean isText(File file) throws IOException { try (FileInputStream rafile = new FileInputStream(file)) { int count = 0; int val = rafile.read(); while ((count < MAX_NB_BINARY_BYTES) && (val >= 0)) { if (val == 0) { return false; } count++; val = rafile.read(); } } return true; }
Source:
public void testEGetNullEObject() { assertEquals(null, eObjectServices.eGet(null, "query")); START } END Remove useless assert

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

Target:
public void testEGetNullEObjectNullFeature() { eObjectServices.eGet(null, null); }
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 START LinkedHashSet<Node<E>>(); END } 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?

Target:
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 HashSet<Node<E>>(); }