auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ScatterStringConsumer(IStringResolver<Object> resolver) { fResolver = resolver; START fMap = checkNotNull(HashBiMap.create()); END } annotate this instead

Target:
public ScatterStringConsumer(IStringResolver<Object> resolver) { fResolver = resolver; fMap = HashBiMap.create(); }
Source:
private void resolveImpl(PackList packList, AbbreviatedObjectId id, boolean noGarbage, HashSet<ObjectId> matches) throws IOException { START if (MAX_RESOLVE_MATCHES <= matches.size()) { return; } END for (DfsPackFile pack : packList.packs) { if (noGarbage && pack.isGarbage()) { continue; } pack.resolve(this, matches, id, MAX_RESOLVE_MATCHES); if (MAX_RESOLVE_MATCHES <= matches.size()) { break; } } } This seems unnecessary. The caller invokes us once on an empty set, and then again only if matches.size() < MAX_RESOLVE_MATCHES so we shouldn't need this redundant check.

Target:
private void resolveImpl(PackList packList, AbbreviatedObjectId id, boolean noGarbage, HashSet<ObjectId> matches) throws IOException { for (DfsPackFile pack : packList.packs) { if (noGarbage && pack.isGarbage()) { continue; } pack.resolve(this, matches, id, MAX_RESOLVE_MATCHES); if (MAX_RESOLVE_MATCHES <= matches.size()) { break; } } }
Source:
public boolean matchDestination(final String r) { START if (allowMismatchedWildcards && getDestination() == null) { return match(r, getSource()); } END return match(r, getDestination()); } This would be equally convenient when !allowMismatchedWildcards, but alas it would be an API change. So I think it would be more consistent for the caller to be responsible for handling this. (Or in a followup change to have a method that sets the destination from src if unset, to make this more convenient.)

Target:
public boolean matchDestination(final String r) { return match(r, getDestination()); }
Source:
START public String getExtractedToolbarGroupConfiguration() { END String toolbarGroupConfiguration = getToolbarGroupConfiguration().trim(); if( !toolbarGroupConfiguration.startsWith( CKEDITOR_CONFIG_TOOLBAR_GROUPS ) || !toolbarGroupConfiguration.endsWith( ";" ) ) { throw new RuntimeException( "Invalid CKEditor toolbarGroups configuration" ); } int equalSignIndex = toolbarGroupConfiguration.indexOf( '=' ); int lastSemicolonIndex = toolbarGroupConfiguration.lastIndexOf( ';' ); return toolbarGroupConfiguration.substring( equalSignIndex + 1, lastSemicolonIndex ).trim(); } This method should not be API as it doesn't exist in SWT Nebula RichTextEditor. The ONLY public method here is toString.

Target:
private String getExtractedToolbarGroupConfiguration() { String toolbarGroupConfiguration = getToolbarGroupConfiguration().trim(); if( !toolbarGroupConfiguration.startsWith( CKEDITOR_CONFIG_TOOLBAR_GROUPS ) || !toolbarGroupConfiguration.endsWith( ";" ) ) { throw new RuntimeException( "Invalid CKEditor toolbarGroups configuration" ); } int equalSignIndex = toolbarGroupConfiguration.indexOf( '=' ); int lastSemicolonIndex = toolbarGroupConfiguration.lastIndexOf( ';' ); return toolbarGroupConfiguration.substring( equalSignIndex + 1, lastSemicolonIndex ).trim(); }
Source:
private boolean isInLayoutingMode(GraphicalEditPart graphicalEditPart) { View notationView = graphicalEditPart.getNotationView(); if (notationView != null) { Diagram diagram = notationView.getDiagram(); if (diagram != null) { EObject element = diagram.getElement(); START if (element instanceof DDiagram && ((DDiagram) element).isIsInLayoutingMode()) { return true; } END } } return false; } return element instanceof DDiagram && ((DDiagram) element).isInLayoutingMpode();

Target:
private boolean isInLayoutingMode(GraphicalEditPart graphicalEditPart) { View notationView = graphicalEditPart.getNotationView(); if (notationView != null) { Diagram diagram = notationView.getDiagram(); if (diagram != null) { EObject element = diagram.getElement(); return element instanceof DDiagram && ((DDiagram) element).isIsInLayoutingMode(); } } return false; }
Source:
private boolean isThreadSuspended(IExecutionDMContext ctx) { assert ctx != null; START IRunControl runControl = getServicesTracker().getService(IRunControl.class); END return runControl.isSuspended(ctx); } You should check for null just in case

Target:
private boolean isThreadSuspended(IExecutionDMContext ctx) { assert ctx != null; IRunControl runControl = getServicesTracker().getService(IRunControl.class); if (runControl != null) { return runControl.isSuspended(ctx); } else { return false; } }
Source:
START protected void createAndDispatchGDBFocusChangedEvent() { END fCommandControl.getSession().dispatchEvent(new GDBFocusChangedEvent(fCurrentThreadCtx), fCommandControl.getProperties()); } Lets reduce the API and make this one private, It would also be better to assert fCurrentThreadCtx != null

Target:
private void createAndDispatchGDBFocusChangedEvent() { assert fCurrentThreadCtx != null; fCommandControl.getSession().dispatchEvent(new GDBFocusChangedEvent(fCurrentThreadCtx), fCommandControl.getProperties()); }
Source:
protected IMIBackend createBackendGDBService(DsfSession session, ILaunchConfiguration lc) { if (compareVersionWith(GDB_7_12_VERSION) >= 0 || compareVersionWith("7.11.50") >= 0 // TODO remove once GDB 7.12 is released START ) { END return new GDBBackend_7_12(session, lc); } return new GDBBackend(session, lc); } Remove the 7.11.50 condition as GDB 7.12 is now available

Target:
protected IMIBackend createBackendGDBService(DsfSession session, ILaunchConfiguration lc) { if (compareVersionWith(GDB_7_12_VERSION) >= 0) { return new GDBBackend_7_12(session, lc); } return new GDBBackend(session, lc); }
Source:
private IFrameDMContext createFrameContext(IExecutionDMContext execCtx, String frameNum) { assert execCtx != null && frameNum != null; if (execCtx == null || frameNum == null) { return null; } int intFrameNum = 0; try { intFrameNum = Integer.parseInt(frameNum); } catch (NumberFormatException e){ GdbPlugin.log(e); } START return fStackService.createFrameDMContext(execCtx, intFrameNum); END } I've added a check for null, in case some extender has replaced our MIStack service and does not yet implement IGDBStack

Target:
private IFrameDMContext createFrameContext(IExecutionDMContext execCtx, String frameNum) { assert execCtx != null && frameNum != null; if (execCtx == null || frameNum == null) { return null; } int intFrameNum = 0; try { intFrameNum = Integer.parseInt(frameNum); } catch (NumberFormatException e){ GdbPlugin.log(e); } if (fStackService != null) { return fStackService.createFrameDMContext(execCtx, intFrameNum); } return null; }
Source:
public void update() { IDebuggerConsole[] consoles = getDebuggerConsoleManager().getConsoles(); START setEnabled(consoles.length > 1); END } In the typical use-case, there will be a single session / console, so this will be disabled. The user might wonder why this button is there. So I wonder if it would be less confusing to enable the widget even if there is a single console? The caption "display selected console" doesn't shed much more light on the situation, since there appears to be nothing to select, in the single session case :)

Target:
public void update() { IDebuggerConsole[] consoles = getDebuggerConsoleManager().getConsoles(); // Keep the button enabled as soon as there is at least one console. // Having it disabled for a single console can prove confusing to users, // so we enable it even for a single console. setEnabled(consoles.length > 0); }
Source:
public Direction getDirection(ITmfEvent event) { try { START IKernelAnalysisEventLayout layout = TRACE_LAYOUTS.get(event.getTrace()); END if (layout == null) { return null; } String evname = event.getName(); /* Is the event a tcp socket in or out event */ if (layout.eventsNetworkReceive().contains(evname)) { return Direction.EFFECT; } else if (layout.eventsNetworkSend().contains(evname)) { return Direction.CAUSE; } } catch (ExecutionException e) { } return null; } You can do getUnchecked() if you know the load() method does not throw any exception. The ExecutionException is just a wrapper that allows catching potential exceptions that get thrown by load().

Target:
public Direction getDirection(ITmfEvent event) { IKernelAnalysisEventLayout layout = TRACE_LAYOUTS.get(event.getTrace()); if (layout == null) { return null; } String evname = event.getName(); /* Is the event a tcp socket in or out event */ if (layout.eventsNetworkReceive().contains(evname)) { return Direction.EFFECT; } else if (layout.eventsNetworkSend().contains(evname)) { return Direction.CAUSE; } return null; }
Source:
public List<String> getPushOptions() { START if (allowPushOptions) { END if (enabledCapabilities == null) { throw new RequestNotYetReadException(); } return pushOptions == null ? null : Collections.unmodifiableList(pushOptions); } else { throw new IllegalStateException(); } } Can simplify by dealing with the exceptional case first: if (!allowPushOptions) { // Reading push options without a prior setAllowPushOptions(true) // call doesn't make sense. throw new IllegalStateException(); } if (enabledCapabilities == null) { // Push options are not available until receive() has been called. throw new RequestNotYetReadException(); } if (pushOptions == null) { // The client doesn't support push options. Return null to distinguish // this from the case where the client declared support for push // options and sent an empty list of them. return null; } return Collections.unmodifiableList(pushOptions);

Target:
public List<String> getPushOptions() { if (!allowPushOptions) { // Reading push options without a prior setAllowPushOptions(true) // call doesn't make sense. throw new IllegalStateException(); } if (enabledCapabilities == null) { // Push options are not available until receive() has been called. throw new RequestNotYetReadException(); } if (pushOptions == null) { // The client doesn't support push options. Return null to // distinguish this from the case where the client declared support // for push options and sent an empty list of them. return null; } return Collections.unmodifiableList(pushOptions); }
Source:
protected boolean isHandledByDirectEditor(final EObject element) { START return DirectEditorEditingSupport.getConfiguration(element) != null; END } null must be the first operande

Target:
protected boolean isHandledByDirectEditor(final EObject element) { return null != DirectEditorEditingSupport.getConfiguration(element); }
Source:
private static String computeNewName(String str) { START String fileExtension = ""; //$NON-NLS-1$ END String fileNameNoExtension = str; Pattern p = Pattern.compile("[0-9]+$"); //$NON-NLS-1$ Matcher m = p.matcher(fileNameNoExtension); if (m.find()) { // String ends with a number: increment it by 1 int newNumber = Integer.parseInt(m.group()) + 1; String numberStr = m.replaceFirst(Integer.toString(newNumber)); return numberStr + fileExtension; } return fileNameNoExtension + "2" + fileExtension; //$NON-NLS-1$ } fileExtension doesn't actually seem to be used?

Target:
private static String computeNewName(String str) { String fileNameNoExtension = str; Pattern p = Pattern.compile("[0-9]+$"); //$NON-NLS-1$ Matcher m = p.matcher(fileNameNoExtension); if (m.find()) { // String ends with a number: increment it by 1 int newNumber = Integer.parseInt(m.group()) + 1; return m.replaceFirst(Integer.toString(newNumber)); } return fileNameNoExtension + "2"; //$NON-NLS-1$ }
Source:
public AbstractCounterAspect(String fieldName, String label) { START Objects.requireNonNull(fieldName); fFieldName = fieldName; END fLabel = label; } put this on one line and add an exception message

Target:
public AbstractCounterAspect(String fieldName, String label) { fFieldName = fieldName; fLabel = label; }
Source:
public Object getParent(Object object, IMergeViewerItemProviderConfiguration configuration) { START return ResourceAttachmentChangeMergeViewerItem.class.cast(object).getParent(); END } Please use the following syntax for casts, as is done everywhere else in the project: return ((ResourceAttachmentChangeMergeViewerItem)object).getParent();

Target:
public Object getParent(Object object, IMergeViewerItemProviderConfiguration configuration) { return ((ResourceAttachmentChangeMergeViewerItem)object).getParent(); }
Source:
public Object[] getChildren(Object object, IMergeViewerItemProviderConfiguration configuration) { START return ResourceAttachmentChangeMergeViewerItem.class.cast(object).getChildren( END configuration.getDifferenceGroupProvider(), configuration.getDifferenceFilterPredicate()); } Done

Target:
public Object[] getChildren(Object object, IMergeViewerItemProviderConfiguration configuration) { return ((ResourceAttachmentChangeMergeViewerItem)object).getChildren( configuration.getDifferenceGroupProvider(), configuration.getDifferenceFilterPredicate()); }
Source:
public boolean hasChildren(Object object, IMergeViewerItemProviderConfiguration configuration) { START return ResourceAttachmentChangeMergeViewerItem.class.cast(object).hasChildren( END configuration.getDifferenceGroupProvider(), configuration.getDifferenceFilterPredicate()); } Done

Target:
public boolean hasChildren(Object object, IMergeViewerItemProviderConfiguration configuration) { return ((ResourceAttachmentChangeMergeViewerItem)object).hasChildren( configuration.getDifferenceGroupProvider(), configuration.getDifferenceFilterPredicate()); }
Source:
protected AbstractMergeViewer createMergeViewer(final Composite parent, final MergeViewerSide side) { final TreeMergeViewer mergeTreeViewer = new TreeMergeViewer(parent, side, this, getCompareConfiguration()); final IContentProvider contentProvider = createMergeViewerContentProvider(); mergeTreeViewer.setContentProvider(contentProvider); START final IBaseLabelProvider labelProvider = new PapyrusTreeContentMergeViewerItemLabelProvider( END getResourceBundle(), getAdapterFactory(), side); mergeTreeViewer.setLabelProvider(labelProvider); hookListeners(mergeTreeViewer); return mergeTreeViewer; } We should think about if we also want to enable customizing the LabelProvider with this PS.

Target:
protected AbstractMergeViewer createMergeViewer(final Composite parent, final MergeViewerSide side) { final TreeMergeViewer mergeTreeViewer = new TreeMergeViewer(parent, side, this, getCompareConfiguration()); final IContentProvider contentProvider = createMergeViewerContentProvider(side); mergeTreeViewer.setContentProvider(contentProvider); final IBaseLabelProvider labelProvider = new PapyrusTreeContentMergeViewerItemLabelProvider( getResourceBundle(), getAdapterFactory(), side); mergeTreeViewer.setLabelProvider(labelProvider); hookListeners(mergeTreeViewer); return mergeTreeViewer; }
Source:
public IDEWorkflow(@Named(CTX_SERVERS) List<IServerDescriptor> endpoints, ILogEventsQueue queue, ISystemSettings settings, IEventBroker broker, MylynNotificationsSupport notificationSupport, UploadReportsScheduler uploadService, IEclipseContext context, @Named(IDEWorkflow.CTX_REPORT_PROCESSORS) List<IProcessorDescriptor> descriptors) { this.servers = endpoints; this.queue = queue; this.system = settings; this.broker = broker; this.notificationSupport = notificationSupport; this.uploadService = uploadService; this.context = context; START this.descriptors = descriptors; END } please make fields final, if possible.

Target:
public IDEWorkflow(@Named(CTX_SERVERS) List<IServerDescriptor> endpoints, ILogEventsQueue queue, ISystemSettings settings, IEventBroker broker, MylynNotificationsSupport notificationSupport, UploadReportsScheduler uploadService, IEclipseContext context, @Named(IDEWorkflow.CTX_REPORT_PROCESSORS) List<IProcessorDescriptor> descriptors) { this.servers = endpoints; this.queue = queue; this.settings = settings; this.broker = broker; this.notificationSupport = notificationSupport; this.uploadService = uploadService; this.context = context; this.descriptors = descriptors; }
Source:
public <T> T getSoleAttributeValue(IAttributeType attributeType, DeletionFlag flag, T defaultValue) { T value = defaultValue; Attribute<T> attribute = null; try { attribute = getSoleAttribute(attributeType, flag); } catch (AttributeDoesNotExist ex) { // do nothing } START if (attribute != null) { END value = attribute.getValue(); } return value; } move this to 244, then can get rid of extra if check

Target:
public <T> T getSoleAttributeValue(IAttributeType attributeType, DeletionFlag flag, T defaultValue) { T value = defaultValue; Attribute<T> attribute = null; try { attribute = getSoleAttribute(attributeType, flag); value = attribute.getValue(); } catch (AttributeDoesNotExist ex) { // do nothing } return value; }
Source:
public void testIsDeleteD() { when(data.getModType()).thenReturn(ModificationType.DELETED); assertTrue(relation.isHardDeleted()); when(data.getModType()).thenReturn(ModificationType.ARTIFACT_DELETED); START assertTrue(relation.isHardDeleted()); END when(data.getModType()).thenReturn(ModificationType.MODIFIED); assertFalse(relation.isHardDeleted()); } Is ARTIFACT_DELETED hard deleted? I thought from the modificationType file above, isDeleted was true when DELETED | ARTIFACT_DELETED, but isHardDeleted was when DELETED only.

Target:
public void testIsDeleteD() { when(data.getModType()).thenReturn(ModificationType.DELETED); assertTrue(relation.isHardDeleted()); when(data.getModType()).thenReturn(ModificationType.MODIFIED); assertFalse(relation.isHardDeleted()); }
Source:
public boolean isPending() { START return fScenarioInfo.getStatus().equals(ScenarioStatusType.PENDING); END } Since these are enums, you can use == instead

Target:
public boolean isPending() { return fScenarioInfo.getStatus() == ScenarioStatusType.PENDING; }
Source:
private void joinConflicts(UMLRTDiff change1, UMLRTDiff change2, Comparison comparison) { final Conflict change2Conflict = change2.getConflict(); change1.getConflict().getDifferences().addAll(change2Conflict.getDifferences()); START change1.getConflict().getDifferences().removeAll(change1.getRefinedBy()); change1.getConflict().getDifferences().removeAll(change2.getRefinedBy()); END comparison.getConflicts().remove(change2Conflict); } Why is this necessary? Shouldn't we "join" the refines as well? If removing refines is desired than it should be included in the test as well.

Target:
private void joinConflicts(UMLRTDiff change1, UMLRTDiff change2, Comparison comparison) { final Conflict change2Conflict = change2.getConflict(); change1.getConflict().getDifferences().addAll(change2Conflict.getDifferences()); comparison.getConflicts().remove(change2Conflict); }
Source:
protected void updateURLInformation() { START String url = serverUrlCombo.getText(); END apiKey.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apiKeyLabel.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apikeyPreferenceLink.setText(url + userprefs); apikeyPreferenceLink .setToolTipText(NLS.bind(Messages.BugzillaRestRepositorySettingsPage_View_your_apikey_settings, url)); apikeyPreferenceLink.setEnabled(TasksUiInternal.isValidUrl(url + userprefs)); } url = serverUrl + userprefs, shouldn't all these use the full URL to the place with the API key?

Target:
protected void updateURLInformation() { String url = serverUrlCombo.getText() + userprefs; apiKey.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apiKeyLabel.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apikeyPreferenceLink.setText(url); apikeyPreferenceLink .setToolTipText(NLS.bind(Messages.BugzillaRestRepositorySettingsPage_View_your_apikey_settings, url)); apikeyPreferenceLink.setEnabled(TasksUiInternal.isValidUrl(url)); }
Source:
protected void doTearDown() throws Exception { START super.doTearDown(); END if (project.exists()) { project.delete(true, null); } } super.tearDown should be executed after, not before this test code

Target:
protected void doTearDown() throws Exception { if (project.exists()) { project.delete(true, null); } super.doTearDown(); }
Source:
private static IMarker[] getMarkersOfView(String viewId, IMarker[] markers) throws CoreException { if (null == viewId) // all markers should be shown return markers; ArrayList<IMarker> markersOfView = new ArrayList<>(); for (IMarker marker : markers) { START if (viewId.equals(getViewId(marker))) END markersOfView.add(marker); } return markersOfView.toArray(new IMarker[markersOfView.size()]); } please add if(marker != null &&

Target:
private static IMarker[] getMarkersOfView(String viewId, IMarker[] markers) throws CoreException { if (null == viewId) // all markers should be shown return markers; ArrayList<IMarker> markersOfView = new ArrayList<>(); for (IMarker marker : markers) { if (null != marker && viewId.equals(getViewId(marker))) markersOfView.add(marker); } return markersOfView.toArray(new IMarker[markersOfView.size()]); }
Source:
public Object getImage(final Object object) { EObject element = EMFHelper.getEObject(object); START if (element == null) { END return null; } // Delegate to UML2 Edit providers to get localized and inferred names where applicable IItemLabelProvider provider = getDelegate(element); return (provider == null) ? null : provider.getImage(element); } PLease invert operande

Target:
public Object getImage(final Object object) { EObject element = EMFHelper.getEObject(object); if (null == element) { return null; } // Delegate to UML2 Edit providers to get localized and inferred names where applicable IItemLabelProvider provider = getDelegate(element); return (provider == null) ? null : provider.getImage(element); }
Source:
public static void selectFolder(SWTBot bot, boolean check, String... treePath) { SWTBotTree tree = bot.tree(); bot.waitUntil(Conditions.widgetIsEnabled(tree)); SWTBotTreeItem folderNode = SWTBotUtils.getTreeItem(bot, tree, treePath); if (check) { START folderNode.check(); END } else { folderNode.select(); } } This checks the element but does not select it (so the file table doesn't show that folder's files). That doesn't seem like something that should be possible with the UI, I wonder if this should not be fixed in SWTBotTreeItem.setChecked()?

Target:
public static void selectFolder(SWTBot bot, boolean check, String... treePath) { SWTBotTree tree = bot.tree(); bot.waitUntil(Conditions.widgetIsEnabled(tree)); SWTBotTreeItem folderNode = SWTBotUtils.getTreeItem(bot, tree, treePath); folderNode.select(); if (check) { folderNode.check(); } }
Source:
START public IPath buildPath(IPath END sourcePath, IPath targetPath, int count) { sourcePath = sourcePath.removeFirstSegments(count); return targetPath.append(sourcePath); } make static

Target:
public static IPath buildPath(IPath sourcePath, IPath targetPath, int count) { sourcePath = sourcePath.removeFirstSegments(count); return targetPath.append(sourcePath); }
Source:
public void dragStart(DragSourceEvent event) { final IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection(); START LocalSelectionTransfer.getTransfer().setSelection(selection); END } setSelection takes an ISelection, no need to cast what you get from the viewer. you also do not need a local variable

Target:
public void dragStart(DragSourceEvent event) { LocalSelectionTransfer.getTransfer().setSelection(fTreeViewer.getSelection()); }
Source:
protected VariablesDropSupport(TreeViewer viewer, TestSuiteModel model) { super(viewer); START fTreeViewer = viewer; END fModel = model; } if super() is already storing the viewer, do you need to store your own copy?

Target:
protected VariablesDropSupport(TreeViewer viewer, TestSuiteModel model) { super(viewer); fModel = model; }
Source:
public void dragStart(DragSourceEvent event) { START event.doit = !((event.data instanceof IPath) || (event.data instanceof Variable)); END final IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection(); LocalSelectionTransfer.getTransfer().setSelection(selection); } are there cases where this evaluates to false?

Target:
public void dragStart(DragSourceEvent event) { final IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection(); LocalSelectionTransfer.getTransfer().setSelection(selection); }
Source:
public void run() { try { fLaunch.terminate(); START setImageDescriptor(GdbUIPlugin.getImageDescriptor(IConsoleImagesConst.IMG_CONSOLE_TERMINATE_DISABLED_COLOR)); END } catch (DebugException e) { GdbUIPlugin.log(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Unable to terminate launch", e)); //$NON-NLS-1$ } } We shoudn't change the active image but instead disable the action. Notice that after the terminate button is pressed, the icon currently becomes 'disabled' but one can still press the button. Calling setEnabled(false) will actually disable the action.

Target:
public void run() { try { fLaunch.terminate(); } catch (DebugException e) { GdbUIPlugin.log(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Unable to terminate launch", e)); //$NON-NLS-1$ } }
Source:
public void createPartControl(Composite parent) { super.createPartControl(parent); START viewer = super.getViewer(); END createFilterAction(); initToolBar(); } I don't think that is necessary.

Target:
public void createPartControl(Composite parent) { super.createPartControl(parent); createFilterAction(); initToolBar(); }
Source:
public static boolean isSystemProtocol(Collaboration element) { START return (UMLUtil.getStereotypeApplication(element, SystemProtocol.class) != null) ? true : false; END } You don't need the ternary operator: the parenthesized boolean expression is already the result. Also, probably it should also be checked that the collaboration is a <<Protocol>> to start with.

Target:
public static boolean isSystemProtocol(Collaboration element) { return (UMLUtil.getStereotypeApplication(element, SystemProtocol.class) != null); }
Source:
public static String unlink(LinkType sourceLinkType, Artifact source, String content) throws OseeCoreException { LinkType linkType = checkLinkType(sourceLinkType); String modified = content; HashCollection<String, MatchRange> matchMap = parseOseeWordMLLinks(content); if (!matchMap.isEmpty()) { START modified = modifiedContent(linkType, source, content, matchMap, true, null, null); END } return modified; } provide a method that does not require the caller to pass null for the presentationType

Target:
public static String unlink(LinkType sourceLinkType, Artifact source, String content) throws OseeCoreException { LinkType linkType = checkLinkType(sourceLinkType); String modified = content; HashCollection<String, MatchRange> matchMap = parseOseeWordMLLinks(content); if (!matchMap.isEmpty()) { modified = modifiedContent(linkType, source, content, matchMap, true, null); } return modified; }
Source:
public void createControl(Composite parent, FormToolkit toolkit) { START super.createControl(parent, toolkit, (getLayoutHint().rowSpan == RowSpan.MULTIPLE ? SWT.WRAP : SWT.NONE)); END if (!isReadOnly() && isMultiSelect) { getText().setToolTipText("Separate multiple values with a comma"); //$NON-NLS-1$ } } Need to check the hint is not null.

Target:
public void createControl(Composite parent, FormToolkit toolkit) { super.createControl(parent, toolkit, (getLayoutHint() != null && getLayoutHint().rowSpan == RowSpan.MULTIPLE ? SWT.WRAP : SWT.NONE)); if (!isReadOnly() && isMultiSelect) { getText().setToolTipText("Separate multiple values with a comma"); //$NON-NLS-1$ } }
Source:
public String toString() { if (getName() == null) { return getPersonId(); } else { if (getPersonId() == null) { START return ""; //$NON-NLS-1$ END } else { if (getName().equals(getPersonId())) { return getName(); } else { return getName() + " <" + getPersonId() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } } } } Why not return name in this case?

Target:
public String toString() { if (getName() == null) { return getPersonId(); } else { if (getPersonId() == null) { return getName(); } else { if (getName().equals(getPersonId())) { return getName(); } else { return getName() + " <" + getPersonId() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } } } }
Source:
public String toString() { START if (getName() == null) { END return getPersonId(); } else { if (getPersonId() == null) { return getName(); } else { if (getName().equals(getPersonId())) { return getName(); } else { return getName() + " <" + getPersonId() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } } } } Please avoid unnecessarily nesting if blocks. This method could be written as: if (getName() == null) { return getPersonId(); } else if (getPersonId() == null) { return getName(); } else if (getName().equals(getPersonId())) { return getName(); } else { return getName() + " <" + getPersonId() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ }

Target:
public String toString() { if (getName() == null) { return getPersonId(); } else if (getPersonId() == null) { return getName(); } else if (getName().equals(getPersonId())) { return getName(); } else { return getName() + " <" + getPersonId() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } }
Source:
public void beginTask(String name, int totalWork) { fTaskName = name; fSubTaskName = ""; //$NON-NLS-1$ updateLabel(); if ((totalWork == IProgressMonitor.UNKNOWN || totalWork == 0) && !fProgressIndicator.isDisposed()) { fProgressIndicator.beginAnimatedTask(); } else { START fProgressIndicator.beginTask(totalWork); END } if (fToolBar != null && !fToolBar.isDisposed()) { fToolBar.setVisible(true); fToolBar.setFocus(); } } Why should we access thiss if the indicator is disposed? This will fail same way as the other if branch?

Target:
public void beginTask(String name, int totalWork) { fTaskName = name; fSubTaskName = ""; //$NON-NLS-1$ updateLabel(); if (!fProgressIndicator.isDisposed()) { if (totalWork == IProgressMonitor.UNKNOWN || totalWork == 0) { fProgressIndicator.beginAnimatedTask(); } else { fProgressIndicator.beginTask(totalWork); } } if (fToolBar != null && !fToolBar.isDisposed()) { fToolBar.setVisible(true); fToolBar.setFocus(); } }
Source:
public int hashCode() { START final int prime = 31; int result = 1; result = prime * result + ((this.logEntry == null) ? 0 : this.logEntry.hashCode()); return result; END } Why not simply Objects.hashCode(logEntry)?

Target:
public int hashCode() { return this.logEntry.hashCode(); }
Source:
public GdbAutoTerminateAction() { super(ConsoleMessages.ConsoleAutoTerminateAction_name, IAction.AS_CHECK_BOX); START setText(ConsoleMessages.ConsoleAutoTerminateAction_name); END setToolTipText(ConsoleMessages.ConsoleAutoTerminateAction_description); // initialize state setChecked(readState()); } Done

Target:
public GdbAutoTerminateAction() { super(ConsoleMessages.ConsoleAutoTerminateAction_name, IAction.AS_CHECK_BOX); setToolTipText(ConsoleMessages.ConsoleAutoTerminateAction_description); // initialize state setChecked(readState()); }
Source:
public void run() { // Toggle and update the new state boolean terminate = !readState(); START setChecked(terminate); END // Update preference store IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GdbPlugin.PLUGIN_ID); if (preferences != null) { preferences.putBoolean(IGdbDebugPreferenceConstants.PREF_AUTO_TERMINATE_GDB, terminate); try { preferences.flush(); } catch (BackingStoreException e) { } } } Done

Target:
public void run() { // All we need to do is update the preference store. There is no other // immediate action to take. IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GdbPlugin.PLUGIN_ID); if (preferences != null) { preferences.putBoolean(IGdbDebugPreferenceConstants.PREF_AUTO_TERMINATE_GDB, !readState()); try { preferences.flush(); } catch (BackingStoreException e) { } } }
Source:
private boolean canPerformInverseNavigation(EStructuralFeature feature){ return START allowInverseNavigation && END ( // Feature has opposite (this only possible for references) hasEOpposite(feature) || ( // Or // indexing is enabled, and the feature can be indexed (it's not a non-well-behaving derived feature) // and it's a reference TODO this constraint might not be needed. It shall be possible to find elements by an attribute value using the base indexer useIndex && modelComprehension.representable(feature) && (feature instanceof EReference) )); } what is the point of disallowing cheap (eOpposite-based) inverse navigation? How about checking this switch only in case we have to rely on the index to navigate backards

Target:
private boolean canPerformInverseNavigation(EStructuralFeature feature){ return ( // Feature has opposite (this only possible for references) hasEOpposite(feature) || ( // Or indexing is enabled, and the feature can be indexed (it's not a non-well-behaving // derived feature) and it's a reference TODO this constraint might not be needed. It shall be possible to find elements by an attribute value using the base indexer useIndex && modelComprehension.representable(feature) && (feature instanceof EReference) )); }
Source:
public static void closeSecondaryShells(SWTWorkbenchBot bot) { SWTBotShell[] shells = bot.shells(); SWTBotShell mainShell = getMainShell(shells); if (mainShell == null) { return; } for (SWTBotShell shell : shells) { boolean visible = shell.isVisible(); START if (shell != mainShell && visible) { END shell.close(); } } } Could a test spawn a separate shell that is actually visible (a new window?). Why not just close all the shells that are not the mainShell?

Target:
public static void closeSecondaryShells(SWTWorkbenchBot bot) { SWTBotShell[] shells = bot.shells(); SWTBotShell mainShell = getMainShell(shells); if (mainShell == null) { return; } // Close all non-main shell but make sure we don't close an invisible // shell such the special "limbo shell" that Eclipse needs to work Arrays.stream(shells) .filter(shell -> shell != mainShell) .filter(SWTBotShell::isVisible) .forEach(SWTBotShell::close); }
Source:
public AssertChecker(Dim[] dimensions) { START fDimensions = new HashSet<Dim>(); END fDimensions.addAll(Arrays.asList(dimensions)); } This creates a warning.

Target:
public AssertChecker(Dim[] dimensions) { fDimensions = new HashSet<>(); fDimensions.addAll(Arrays.asList(dimensions)); }
Source:
private void unregisterAndCloseRepository(final Key location, Repository db) { synchronized (lockFor(location)) { START if (isExpired(db)) { END Repository oldDb = unregisterRepository(location); if (oldDb != null) { oldDb.doClose(); } } } } this should be removed

Target:
private void unregisterAndCloseRepository(final Key location, Repository db) { synchronized (lockFor(location)) { Repository oldDb = unregisterRepository(location); if (oldDb != null) { oldDb.doClose(); } } }
Source:
protected IStatus run(IProgressMonitor monitor) { try { runnable.run(monitor); } catch (CoreException e) { IStatus st = e.getStatus(); return new Status(st.getSeverity(), st.getPlugin(), st.getCode(), st.getMessage(), e); START } finally { monitor.done(); END } return Status.OK_STATUS; } The 'finally' block is not needed since calling monitor.done() is not required.

Target:
protected IStatus run(IProgressMonitor monitor) { try { runnable.run(monitor); } catch (CoreException e) { IStatus st = e.getStatus(); return new Status(st.getSeverity(), st.getPlugin(), st.getCode(), st.getMessage(), e); } return Status.OK_STATUS; }
Source:
public void startup(IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); Preferences preferences = ResourcesPlugin.getPlugin().getPluginPreferences(); preferences.addPropertyChangeListener(this); refreshJob = new RefreshJob(); monitors = new MonitorManager(workspace, this); boolean autoRefresh = preferences.getBoolean(ResourcesPlugin.PREF_AUTO_REFRESH); if (autoRefresh) manageAutoRefresh(autoRefresh, subMonitor.split(1)); START subMonitor.setWorkRemaining(0); END } This method doesn't advance the monitor.

Target:
public void startup(IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); Preferences preferences = ResourcesPlugin.getPlugin().getPluginPreferences(); preferences.addPropertyChangeListener(this); refreshJob = new RefreshJob(); monitors = new MonitorManager(workspace, this); boolean autoRefresh = preferences.getBoolean(ResourcesPlugin.PREF_AUTO_REFRESH); if (autoRefresh) manageAutoRefresh(autoRefresh, subMonitor.split(1)); }
Source:
public int hashCode() { if (isEmpty()) { return START Objects.hash(comparer); END } int r; if (comparer != null) { r = 31 + comparer.hashCode(); for (Object e : elements) { r = 31 * r + (e == null ? 0 : comparer.hashCode(e)); } } else { r = Arrays.hashCode(elements); } return r; } if isEmpty() and comparer==null, this will return the hash code of a null Object. - Is this the intended behavior? - Perhaps we could use getClass().hashCode() instead?

Target:
public int hashCode() { if (isEmpty()) { return Objects.hashCode(comparer); } int r; if (comparer != null) { r = 31 + comparer.hashCode(); for (Object e : elements) { r = 31 * r + (e == null ? 0 : comparer.hashCode(e)); } } else { r = Arrays.hashCode(elements); } return r; }
Source:
public int hashCode() { if (elements == null) { return Objects.hash(comparer); } START int r = 1; END if (comparer != null) { r = 31 + comparer.hashCode(); for (Object e : elements) { r = 31 * r + (e == null ? 0 : comparer.hashCode(e)); } } else { Arrays.hashCode(elements); } return r; } assignment has no effect

Target:
public int hashCode() { if (elements == null) { return Objects.hash(comparer); } int r; if (comparer != null) { r = 31 + comparer.hashCode(); for (Object e : elements) { r = 31 * r + (e == null ? 0 : comparer.hashCode(e)); } } else { r = Arrays.hashCode(elements); } return r; }
Source:
protected Control createDialogArea(Composite parent) { Composite parent2 = (Composite) super.createDialogArea(parent); Composite composite = new Composite(parent2, SWT.NONE); composite.setLayout(new GridLayout(1, false)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.BEGINNING).applyTo(composite); createCenterArea(composite); composite.pack(); START return parent; END } this should return parent2

Target:
protected Control createDialogArea(Composite parent) { Composite parent2 = (Composite) super.createDialogArea(parent); Composite composite = new Composite(parent2, SWT.NONE); composite.setLayout(new GridLayout(1, false)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.BEGINNING).applyTo(composite); createCenterArea(composite); composite.pack(); return parent2; }
Source:
protected ResourceBundle getPluginResourceBundle() { Bundle bundle = START FrameworkUtil.getBundle(PDETemplateSection.class); END return Platform.getResourceBundle(bundle); } I think the result of this call will not change at any time. So we could improve the code by keeping the Bundle in an instance variable so it is not needed to request it everytime.

Target:
protected ResourceBundle getPluginResourceBundle() { return Platform.getResourceBundle(bundle); }
Source:
public void testCanContribute() { // if the test fails, a section is probably renamed in the configuration section START assertTrue(processor.canContribute(mock(IStatus.class))); END } why not keep using hamcrest matchers?

Target:
public void testCanContribute() { // if the test fails, a section is probably renamed in the configuration section assertThat(processor.canContribute(mock(IStatus.class)),is(true)); }
Source:
private void recordSaveables(Saveable[] sourceSaveables) { if (knownSaveables == null) START knownSaveables = new HashSet<Saveable>(); END for (int i = 0; i < sourceSaveables.length; i++) { Saveable saveable = sourceSaveables[i]; knownSaveables.add(saveable); } } Use new HashSet<>

Target:
private void recordSaveables(Saveable[] sourceSaveables) { if (knownSaveables == null) knownSaveables = new HashSet<>(); Collections.addAll(knownSaveables, sourceSaveables); }
Source:
public void start(BundleContext context) throws Exception { super.start(context); START Hashtable<String, String> properties = new Hashtable<String, String>(2); END properties.put(DebugOptions.LISTENER_SYMBOLICNAME, PLUGIN_ID); debugRegistration = context.registerService(DebugOptionsListener.class, Policy.DEBUG_OPTIONS_LISTENER, properties); ComparePlugin.getDefault().setCappingDisabled( getPreferenceStore().getBoolean( ComparePreferencePage.CAPPING_DISABLED)); } Use new Hashtable<>

Target:
public void start(BundleContext context) throws Exception { super.start(context); Hashtable<String, String> properties = new Hashtable<>(2); properties.put(DebugOptions.LISTENER_SYMBOLICNAME, PLUGIN_ID); debugRegistration = context.registerService(DebugOptionsListener.class, Policy.DEBUG_OPTIONS_LISTENER, properties); ComparePlugin.getDefault().setCappingDisabled( getPreferenceStore().getBoolean( ComparePreferencePage.CAPPING_DISABLED)); }
Source:
private static Map<IFile, Long> createModificationStampMap(List<IResource> files) { Map<IFile, Long> map= new HashMap<IFile, Long>(); START for (Iterator<IResource> iter= files.iterator(); iter.hasNext(); ) { END IFile file= (IFile)iter.next(); map.put(file, new Long(file.getModificationStamp())); } return map; } Use modern for loop.

Target:
private static Map<IFile, Long> createModificationStampMap(List<IResource> files) { Map<IFile, Long> map= new HashMap<IFile, Long>(); for (IResource file : files) { map.put((IFile) file, file.getModificationStamp()); } return map; }
Source:
IgnoreCondition create() { checkConditionType(); try { return createCondition(); START } catch (RuntimeException re) { END throw Throwables.propagate(re); } catch (Exception e) { throw new RuntimeException(e); } } This can just be catch Exception.

Target:
IgnoreCondition create() { checkConditionType(); try { return createCondition(); } catch (Exception re) { throw Throwables.propagate(re); } }
Source:
protected static void setOverrideFileName(String... path) { String filePaths = Joiner.on(LIST_SEPARATOR).skipNulls().join(path); START fOverridePath = filePaths == null ? null : filePaths.isEmpty() ? null : filePaths; END fOverride = true; } Should just store the String[] and for open() and getFileName() you return the first item in the array.

Target:
public static void setOverrideFileName(String... path) { fOverridePath = (path == null) ? null : path; fOverride = true; }
Source:
public void addPageTerminalControl(ITerminalControl terminalControl) { fTerminalPageControls.add(terminalControl); // write the currently available buffered history to this new terminal if (fHistoryBuffer.size() > 0) { new WriteHistoryJob(terminalControl).schedule(); START } END } I wonder if we shouldn't finish the writing of the history before we add the new terminalControl to fTerminalPageControls? Couldn't we get new output written to the page by OutputReadJob before WriteHistoryJob is finished?

Target:
public void addPageTerminalControl(ITerminalControl terminalControl) { // write the currently available buffered history to this new terminal if (fHistoryBuffer.size() > 0) { new WriteHistoryJob(terminalControl).schedule(); } // Add it to the list so it can now receive new input fTerminalPageControls.add(terminalControl); }
Source:
protected Point getSize() { if (size == null) { size = new START Point(getBaseImageData().width, END getBaseImageData().height); } return size; } This triggers now baseImage.getImageData() if size was not specified for Image based constructors but would lead to NPE before. For descriptor-based data this creates a second ImageData object (parent has one).

Target:
protected Point getSize() { return size.get(); }
Source:
public String generateModelElementId(EObject eObject, ESObjectContainer<ModelElementId> collection) { if (EGenericType.class.isInstance(eObject)) { final EGenericType eGeneric = EGenericType.class.cast(eObject); if (eGeneric.eContainer() != null && START eGeneric.eContainer() != this END && collection.contains(eGeneric.eContainer())) { final ModelElementId containerId = collection.getModelElementId(eGeneric.eContainer()); return containerId.getId() + ID_SUFFIX; } } return null; } This is wrong, probably CP error :),this should check against collection NOT this.

Target:
public String generateModelElementId(EObject eObject, ESObjectContainer<ModelElementId> collection) { if (EGenericType.class.isInstance(eObject)) { final EGenericType eGeneric = EGenericType.class.cast(eObject); if (eGeneric.eContainer() != null && eGeneric.eContainer() != collection && collection.contains(eGeneric.eContainer())) { // generate artificial ID based on the container of the EGenericType final ModelElementId containerId = collection.getModelElementId(eGeneric.eContainer()); return containerId.getId() + ID_SUFFIX; } } return null; }
Source:
private void clearAll() { START for (int stage = 0; stage < 2; stage++) { END for (Iterator<Map.Entry<Key, Reference<Repository>>> i = cacheMap .entrySet().iterator(); i.hasNext();) { final Map.Entry<Key, Reference<Repository>> e = i.next(); unregisterAndCloseRepository(e.getKey(), null); } } } Could you explain a bit more detailled what's the purpose of this loop? Maybe I miss the bigger context: I haven't got the whole idea of how the cache intends to care about Repository refcount. Is it explained somewhere?

Target:
private void clearAll() { for (Iterator<Map.Entry<Key, Reference<Repository>>> i = cacheMap .entrySet().iterator(); i.hasNext();) { final Map.Entry<Key, Reference<Repository>> e = i.next(); unregisterAndCloseRepository(e.getKey(), null); } }
Source:
public boolean canHandleSelection(Object selection) { if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; START Object element = structuredSelection.getFirstElement(); END if (element instanceof SpecHierarchyImpl) { return true; } } return false; } Are we sure that selection is not null? Otherwise, a null check before we call getFirstElement() is in order.

Target:
public boolean canHandleSelection(Object selection) { if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; if (!(structuredSelection.getFirstElement() == null)) { Object element = structuredSelection.getFirstElement(); if (element instanceof SpecHierarchyImpl) { return true; } } } return false; }
Source:
public Set<ModelElementId> getAllInvolvedModelElements(AbstractChangePackage changePackage) { final Set<ModelElementId> result = new LinkedHashSet<ModelElementId>(); final START ESCloseableIterable<AbstractOperation> END operations = changePackage.operations(); for (final AbstractOperation op : operations.iterable()) { result.addAll(op.getAllInvolvedModelElements()); } return result; } must be closed?

Target:
public Set<ModelElementId> getAllInvolvedModelElements(AbstractChangePackage changePackage) { final Set<ModelElementId> result = new LinkedHashSet<ModelElementId>(); final ESCloseableIterable<AbstractOperation> operations = changePackage.operations(); try { for (final AbstractOperation op : operations.iterable()) { result.addAll(op.getAllInvolvedModelElements()); } } finally { operations.close(); } return result; }
Source:
public void testNoSetting() throws START IOException, InterruptedException { END Process start = processBuilder.start(); start.waitFor(); assertEquals( "http.proxyHost: null, http.proxyPort: null, https.proxyHost: null, https.proxyPort: null", getOutput(start)); } Isn't it enough to declare Exception here? An exception will fail the test, regardless of the specific type.

Target:
public void testNoSetting() throws Exception { Process start = processBuilder.start(); start.waitFor(); assertEquals( "http.proxyHost: null, http.proxyPort: null, https.proxyHost: null, https.proxyPort: null", getOutput(start)); }