auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected String[] getTransformedSelection() { START System.out.println(this.selectionStateMap); END List<String> selectedItems = new ArrayList<String>(); for (String item : this.selectionStateMap.keySet()) { Boolean isSelected = this.selectionStateMap.get(item); if (isSelected != null && isSelected) { selectedItems.add(item); } } return selectedItems.toArray(new String[selectedItems.size()]); } Please remove any System.out calls from the code

Target:
protected String[] getTransformedSelection() { List<String> selectedItems = new ArrayList<String>(); for (String item : this.selectionStateMap.keySet()) { Boolean isSelected = this.selectionStateMap.get(item); if (isSelected != null && isSelected) { selectedItems.add(item); } } return selectedItems.toArray(new String[selectedItems.size()]); }
Source:
START public void doLaunch(String programName) throws Exception { END setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, programName); super.doLaunch(); } protected?

Target:
protected void doLaunch(String programName) throws Exception { setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, programName); super.doLaunch(); }
Source:
public void setLinkForeground (Color color) { checkWidget(); START if (color != null && color.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); END linkColor = color; if (getEnabled()) { styleLinkParts(); redraw(); } } Please add a check here that would simply return if the color being set is the same as the current foreground color (linkColor).

Target:
public void setLinkForeground (Color color) { checkWidget(); if (color != null) { if (color.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); if (color.equals(linkColor)) return; } else if (linkColor == null) return; linkColor = color; if (getEnabled()) { styleLinkParts(); redraw(); } }
Source:
public static boolean dialogCancellable(IEditCommandRequest request) { Object value = request.getParameter(RequestParameterConstants.DIALOG_CANCELLABLE); if (value instanceof Boolean) { return (Boolean) value; } else if (value instanceof String) { Boolean booleanObject = Boolean.valueOf((String) value); return booleanObject.booleanValue(); } START return true; // Default END } Default value is false to keep existing behavior for Mars dialogs

Target:
public static boolean dialogCancellable(IEditCommandRequest request) { Object value = request.getParameter(RequestParameterConstants.DIALOG_CANCELLABLE); if (value instanceof Boolean) { return (Boolean) value; } else if (value instanceof String) { Boolean booleanObject = Boolean.valueOf((String) value); return booleanObject.booleanValue(); } return false; // Default }
Source:
public Annotation getFirstAnnotationForOffset(int offset) { for (CommentAnnotation annotation : Iterables.filter(annotations, CommentAnnotation.class)) { START if (annotation instanceof CommentAnnotation) { END if (annotation.getPosition().offset <= offset && (annotation.getPosition().length + annotation.getPosition().offset) >= offset) { return annotation; } } } return null; } Not needed.

Target:
public Annotation getFirstAnnotationForOffset(int offset) { for (CommentAnnotation annotation : Iterables.filter(annotations, CommentAnnotation.class)) { if (annotation.getPosition().offset <= offset && (annotation.getPosition().length + annotation.getPosition().offset) >= offset) { return annotation; } } return null; }
Source:
START protected PullWithOptionsAction() END { super(ActionCommands.PULL_WITH_OPTIONS, new PullWithOptionsActionHandler()); } I get !ENTRY org.eclipse.ui 4 4 2016-01-11 20:56:17.129 !MESSAGE Could not create action delegate for id: org.eclipse.egit.ui.actionpullwithoptions !SUBENTRY 1 org.eclipse.equinox.registry 4 1 2016-01-11 20:56:17.129 !MESSAGE Plug-in "org.eclipse.egit.ui" was unable to instantiate class "org.eclipse.egit.ui.internal.actions.PullWithOptionsAction". !STACK 0 java.lang.IllegalAccessException: Class org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI can not access a member of class org.eclipse.egit.ui.internal.actions.PullWithOptionsAction with modifiers "protected" Must be public.

Target:
public PullWithOptionsAction() { super(ActionCommands.PULL_WITH_OPTIONS, new PullWithOptionsActionHandler()); }
Source:
private boolean isModifyAccessEnabled() { START boolean returnValue; END try { if (SystemGroup.OseeAccessAdmin.isCurrentUserMember()) { returnValue = true; } else if (policyTableViewer.getAccessControlList().size() > 0) { returnValue = AccessControlManager.hasPermission(accessControlledObject, PermissionEnum.OWNER); } else { returnValue = true; } } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); returnValue = false; } return returnValue; } Adding to Megumi's nit: Consider initializing the value to true, and possibly collapsing these two methods down to one with an argument

Target:
private boolean isModifyAccessEnabled() { boolean returnValue; try { if (!SystemGroup.OseeAccessAdmin.isCurrentUserMember() && policyTableViewer.getAccessControlList().size() > 0) { returnValue = AccessControlManager.hasPermission(accessControlledObject, PermissionEnum.OWNER); } else { returnValue = true; } } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); returnValue = false; } return returnValue; }
Source:
START public void setUp() throws Exception { END // Automated Test logFileName = Platform.getInstallLocation().getURL().getPath() + ".." + File.separator + ".." + File.separator + "results" + File.separator + "chkpii"; // A tad bogus but this is where // the build wants to copy the // results from! // Runtime Workbench - TODO Put me back to Automated status // logFileName = "d:\\results"; // sourceDirectoryName = "d:\\sourceFetch"; } Remove throws Exception

Target:
public void setUp() { // Automated Test logFileName = Platform.getInstallLocation().getURL().getPath() + ".." + File.separator + ".." + File.separator + "results" + File.separator + "chkpii"; // A tad bogus but this is where // the build wants to copy the // results from! // Runtime Workbench - TODO Put me back to Automated status // logFileName = "d:\\results"; // sourceDirectoryName = "d:\\sourceFetch"; }
Source:
private static Map<String, RemoteRefUpdate> asUpdateMap( List<RemoteCommand> cmds) { Map<String, RemoteRefUpdate> m = new LinkedHashMap<>(); for (RemoteCommand START c : END cmds) { m.put(c.getRemoteName(), c); } return m; } s/c/cmd/

Target:
private static Map<String, RemoteRefUpdate> asUpdateMap( List<RemoteCommand> cmds) { Map<String, RemoteRefUpdate> m = new LinkedHashMap<>(); for (RemoteCommand cmd : cmds) { m.put(cmd.getRemoteName(), cmd); } return m; }
Source:
public Collection<ReceiveCommand> getCommands() { START synchronized (lock) { END return commands; } } What is this lock doing? The list is being returned unprotected. Maybe just return an unmodifiable list that is created when setting it?

Target:
public Collection<ReceiveCommand> getCommands() { return commands; }
Source:
public List<IDockerContainerListener> getContainerListeners() { final IDockerContainerListener[] listeners = new IDockerContainerListener[this.containerListeners .size()]; START for (int i = 0; i < containerListeners.getListeners().length; i++) { END listeners[i] = (IDockerContainerListener) containerListeners .getListeners()[i]; } return Arrays.asList(listeners); } better put containerListeners.getListeners() in a local variable

Target:
public List<IDockerContainerListener> getContainerListeners() { final IDockerContainerListener[] result = new IDockerContainerListener[this.containerListeners .size()]; final Object[] listeners = containerListeners.getListeners(); for (int i = 0; i < listeners.length; i++) { result[i] = (IDockerContainerListener) listeners[i]; } return Arrays.asList(result); }
Source:
private static synchronized Iterable<ISegmentGenerationListener> getListeners(ListenerList listenersList) { List<ISegmentGenerationListener> listeners = new ArrayList<>(); for (Object listener : listenersList.getListeners()) { START if (listener != null) { END listeners.add((ISegmentGenerationListener) listener); } } return listeners; } instead of != null here, you could do a instanceof ISegmentGenerationListener. There shouldn't be any ClassCastException, but this way, you would avoid any such error

Target:
private static synchronized Iterable<ISegmentGenerationListener> getListeners(ListenerList listenersList) { List<ISegmentGenerationListener> listeners = new ArrayList<>(); for (Object listener : listenersList.getListeners()) { if (listener instanceof ISegmentGenerationListener) { listeners.add((ISegmentGenerationListener) listener); } } return listeners; }
Source:
START public AbstractSegmentBaseStateSystemAnalysis() { END registerListener(); } You should call super() here

Target:
public AbstractSegmentBaseStateSystemAnalysis() { super(); registerListener(); }
Source:
public boolean isProviderFor(CSSDiagram diagram) { if(diagram.getElement() instanceof Element){ //Retrieve the UML2 element START Element element = (Element)diagram.getElement(); //Introspect its packages to check if SysML profile is applied if (SysMLResource.isSysMLProfileApplied(element)){ return true; } END } return false; } return the result without if

Target:
public boolean isProviderFor(CSSDiagram diagram) { if(diagram.getElement() instanceof Element){ //Retrieve the UML2 element Element element = (Element)diagram.getElement(); //Introspect its packages to check if SysML profile is applied return SysMLResource.isSysMLProfileApplied(element); } return false; }
Source:
public ThreadedHistoryTreeBackendTest(Boolean reOpen) { START super(reOpen); END } The notion of reopening does not apply to the threaded backend. When you re-open you should always use the non-threaded backend, because there should be no future insertions. Here I'd be tempted to just say "super(false)". It would still run the same tests twice though (it does now anyway).

Target:
public ThreadedHistoryTreeBackendTest(Boolean reOpen) { /* There is no notion of "reopening" for the threaded backend */ super(false); }
Source:
protected IStateHistoryBackend getBackendForQuerying(IStateHistoryBackend backend) { if (!fReOpen) { return backend; } backend.dispose(); try { START return new HistoryTreeBackend(SSID, checkNotNull(fTempFile), PROVIDER_VERSION); END } catch (IOException e) { fail(e.getMessage()); return null; } } assertNotNull fTempFile

Target:
protected IStateHistoryBackend getBackendForQuerying(IStateHistoryBackend backend) throws IOException { if (!fReOpen) { return backend; } backend.dispose(); return new HistoryTreeBackend(SSID, checkNotNull(fTempFile), PROVIDER_VERSION); }
Source:
public void testGetChangedAttributesWithAttachments() { TaskAttribute attributeAttachment = newData.getRoot().createAttribute("custom"); attributeAttachment.setValue("1"); attributeAttachment.getMetaData().setType(TaskAttribute.TYPE_ATTACHMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); START assertEquals(diff.getNewAttachments(), Collections.singleton(attributeAttachment)); END } Expected value should be first.

Target:
public void testGetChangedAttributesWithAttachments() { TaskAttribute attributeAttachment = newData.getRoot().createAttribute("custom"); attributeAttachment.setValue("1"); attributeAttachment.getMetaData().setType(TaskAttribute.TYPE_ATTACHMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); assertEquals(Collections.singleton(attributeAttachment), diff.getNewAttachments()); }
Source:
protected void testIntersections(Comparison comparison) { assertFalse(Iterables.any(comparison.getDifferences(), new Predicate<Diff>() { @SuppressWarnings("restriction") public boolean apply(Diff input) { return Iterators.size(Iterators .filter(input.getRefines().iterator(), START not(instanceOf(MultiplicityReferenceChange.class)))) END > 1; } })); } What is the purpose of testIntersections(Comparison)? It looks weird that we need to filter MultiplicityReferenceChanges here and not any of the other numerous UMLDiff extensions. Maybe we should filter those that we are interested in here instead.

Target:
protected void testIntersections(Comparison comparison) { assertFalse(Iterables.any(comparison.getDifferences(), new Predicate<Diff>() { public boolean apply(Diff input) { return input.getRefines().size() > 1; } })); }
Source:
public <T> Set<T> including(Set<T> set, T object) { if (set.contains(object)) { return Sets.newLinkedHashSet(set); START } else { END Set<T> result = Sets.newLinkedHashSet(set); result.add(object); return result; } } we probably want to return the set itself in this case even if it's not the same behavior on List.

Target:
public <T> Set<T> including(Set<T> set, T object) { if (set.contains(object)) { return set; } else { Set<T> result = Sets.newLinkedHashSet(set); result.add(object); return result; } }
Source:
public void childContextAdded(VElement parentElement, EMFFormsViewContext childContext) { final EMFFormsSettingToControlMapper mapper = childContext.getService(EMFFormsSettingToControlMapper.class); START validate(getAllEObjectsToValidate(mapper)); END } use the root controlMapper instead

Target:
public void childContextAdded(VElement parentElement, EMFFormsViewContext childContext) { validate(getAllEObjectsToValidate()); }
Source:
public void launch(ISelection selection, String mode) { START if (selection instanceof IStructuredSelection) { END Object element = ((IStructuredSelection)selection).getFirstElement(); if (element != null && element instanceof IResource) { IResource selectedResource = (IResource) element; launch(selectedResource, mode); } } } perhaps it is better to check selection.isEmpty() first before continuing to other checks and also eliminating the need for null checks.

Target:
public void launch(ISelection selection, String mode) { if (!selection.isEmpty() && selection instanceof IStructuredSelection) { Object element = ((IStructuredSelection)selection).getFirstElement(); if (element instanceof IResource) { IResource selectedResource = (IResource) element; launch(selectedResource, mode); } } }
Source:
START protected GdbLaunch getGDBLaunch() { END return (GdbLaunch) getSession().getModelAdapter(ILaunch.class); } Let's not create this new API. Instead, in doInitialize() set a member variable to store the launch. Or make this method private.

Target:
private GdbLaunch getGDBLaunch() { return (GdbLaunch) getSession().getModelAdapter(ILaunch.class); }
Source:
public void stop(BundleContext context) throws Exception { REGISTRY.dispose(); sessionFactoryRegistryListener.dispose(); sessionFactoryRegistryListener = null; deleteHookDescriptorRegistryListener.dispose(); deleteHookDescriptorRegistryListener = null; javaActionRegistryListener.dispose(); javaActionRegistryListener = null; ViewpointRegistry.getInstance().dispose(); MultiLanguagesValidator.getInstance().dispose(); START ResourceStrategyRegistry.getInstance().clearRegistry(); END super.stop(context); } See sessionFactoryRegistryListener.dispose() and other extension points.

Target:
public void stop(BundleContext context) throws Exception { REGISTRY.dispose(); sessionFactoryRegistryListener.dispose(); sessionFactoryRegistryListener = null; deleteHookDescriptorRegistryListener.dispose(); deleteHookDescriptorRegistryListener = null; javaActionRegistryListener.dispose(); javaActionRegistryListener = null; ViewpointRegistry.getInstance().dispose(); MultiLanguagesValidator.getInstance().dispose(); ResourceStrategyRegistry.getInstance().dispose(); super.stop(context); }
Source:
public @NonNull Map<@NonNull String, @NonNull String> getProperties() { Map<@NonNull String, @NonNull String> properties = new HashMap<>(); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyFile), NonNullUtils.checkNotNull(fSourceFile.getName())); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyType), START NonNullUtils.checkNotNull(fType.name())); END return properties; } I don't think this can return null. We should probably add an external annotation.

Target:
public @NonNull Map<@NonNull String, @NonNull String> getProperties() { Map<@NonNull String, @NonNull String> properties = new HashMap<>(); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyFile), fSourceFile.getName()); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyType), fType.name()); return properties; }
Source:
protected Composite createControlComposite(Composite composite) { final Composite controlComposite = new Composite(composite, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).align(SWT.FILL, SWT.FILL).hint(1, getTableHeightHint()) START .applyTo(controlComposite); END GridLayoutFactory.fillDefaults().numColumns(1).applyTo(controlComposite); return controlComposite; } can't you remove this call and only do it later?

Target:
protected Composite createControlComposite(Composite composite) { final Composite controlComposite = new Composite(composite, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(1).applyTo(controlComposite); return controlComposite; }
Source:
private void reflowAsync() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { START getParentSection().getTaskEditorPage().reflow(); END } }); } call reflow() instead?

Target:
private void reflowAsync() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { reflow(); } }); }
Source:
public static IEditorDescriptor getEditorDescriptor(IFile file) throws PartInitException { START try { return getEditorDescriptor(file, true, false); } catch (OperationCanceledException ex) { throw new PartInitException(ex.getMessage(), ex); } END } This should just call the old method like in 4.5: ==> return getEditorDescriptor(file, true);

Target:
public static IEditorDescriptor getEditorDescriptor(IFile file) throws PartInitException { return getEditorDescriptor(file, true); }
Source:
public boolean hasVariable(final String identifier) { START if (identifier == null || identifier.isEmpty()) END return false; return getVariable(identifier) != null; } remove unnecessary checks

Target:
public boolean hasVariable(final String identifier) { return getVariable(identifier) != null; }
Source:
public static SWTBotTreeItem getTreeItem(final SWTBotTreeItem[] treeElements, final String name) { SWTBotTreeItem foundTreeItem = null; if (treeElements != null && treeElements.length > 0) { START for (SWTBotTreeItem swtBotTreeItem : treeElements) { END if (swtBotTreeItem.getText().equals(name)) { foundTreeItem = swtBotTreeItem; break; } foundTreeItem = getTreeItem(swtBotTreeItem.getItems(), name); if (foundTreeItem != null) { break; } } } return foundTreeItem; } You could use SWTBotTreeItem.getNode(s)(String) instead of doing text equality test and catch WidgetNotFoundException to iterate recursively on children items.

Target:
public static SWTBotTreeItem getTreeItem(final SWTBotTreeItem[] treeElements, final String name) { SWTBotTreeItem foundTreeItem = null; if (treeElements != null) { for (SWTBotTreeItem swtBotTreeItem : treeElements) { if (swtBotTreeItem.getText().equals(name)) { foundTreeItem = swtBotTreeItem; break; } foundTreeItem = getTreeItem(swtBotTreeItem.getItems(), name); if (foundTreeItem != null) { break; } } } return foundTreeItem; }
Source:
public Map<String, String> getTraceProperties() { Map<String, String> properties = new HashMap<>(); properties.putAll(fTrace.getEnvironment()); properties.put(CLOCK_OFFSET, START Long.toUnsignedString(fTrace.getOffset())); END properties.put(Messages.CtfTmfTrace_HostID, getHostId()); return properties; } This method was added in java 8. It will fail with java 7. Note that it might compile on Gerrit because we compile with java 8.

Target:
public Map<String, String> getTraceProperties() { Map<String, String> properties = new HashMap<>(); properties.putAll(fTrace.getEnvironment()); properties.put(CLOCK_OFFSET, Long.toString(fTrace.getOffset())); properties.put(Messages.CtfTmfTrace_HostID, getHostId()); return properties; }
Source:
public void tearDown() throws Exception { super.tearDown(); START if (editor != null) END { editor.close(false); editor = null; } } The editor can't be null

Target:
public void tearDown() throws Exception { super.tearDown(); editor.close(false); editor= null; }
Source:
public Long getUuid() { START return new Long(getArtId()); END } use Long.valueOf() instead of new Long() - always for performance reasons

Target:
public Long getUuid() { return Long.valueOf(getArtId()); }
Source:
public ITmfStateProvider getNewInstance() { START return new KernelMemoryStateProvider(this.getTrace(), this.fLayout); END } remove the this.

Target:
public ITmfStateProvider getNewInstance() { return new KernelMemoryStateProvider(getTrace(), fLayout); }
Source:
START public @NonNull String eventKmemPageAlloc() { END return "kmem:page_alloc"; //$NON-NLS-1$ } you do not need the @NonNull

Target:
public String eventKmemPageAlloc() { return "kmem:page_alloc"; //$NON-NLS-1$ }
Source:
public int getMaximumSize() { int maxSize = 0; for (IDeclaration field : fFields) { maxSize += field.getMaximumSize(); } START return Math.min(maxSize, Integer.MAX_VALUE); END } maxSize being an int, that Math.min is quite unnecessary. But you do need to make sure it did not overflow, so I'd say Math.max(0, maxSize);

Target:
public int getMaximumSize() { long maxSize = 0; for (IDeclaration field : fFields) { maxSize += field.getMaximumSize(); } return (int) Math.min(maxSize, Integer.MAX_VALUE); }
Source:
public final void run() { doRun(); START fHasDrawnEntries = true; END fDirty.decrementAndGet(); } A possible problem with this is that it relies on the zoom thread, and you might have an implementation that does not use any zoom list or thread (could override createZoomThread() to return null). Also, it's not clear what value the flag should have if you have completed the zoom with an empty entry list, or if the entries are all filtered out. Does it work if the build thread has done a first iteration and called refresh() but hasn't discovered any entries yet?

Target:
public final void run() { doRun(); fDirty.decrementAndGet(); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[TimeLineEvent Values=").append(getValues()) //$NON-NLS-1$ .append(", Entry=").append(getEntry()) //$NON-NLS-1$ .append(", fTime=").append(getTime()) //$NON-NLS-1$ START .append(", Duration=").append(getDuration()) //$NON-NLS-1$ END .append(']'); return builder.toString(); } The format of the names is inconsistent, also remove duration.

Target:
public String toString() { return new StringBuilder().append("[TimeLineEvent Values=").append(getValues()) //$NON-NLS-1$ .append(", Entry=").append(getEntry()) //$NON-NLS-1$ .append(", fTime=").append(getTime()) //$NON-NLS-1$ .append(", Duration=").append(getDuration()) //$NON-NLS-1$ .append(']').toString(); }
Source:
public String getLabel() { String label = fLabel; if (label == null) { StringJoiner sj = new StringJoiner(", "); //$NON-NLS-1$ getValues().forEach((Long value) -> sj.add(NumberFormat.getNumberInstance(Locale.getDefault()).format(value))); label = sj.toString(); START fLabel = label; END } return label; } When addValue() is called (or if the user changes the list returned by getValues()), the label is not changed and becomes inconsistent!

Target:
public String getLabel() { String label = fLabel; if (label == null) { StringJoiner sj = new StringJoiner(", "); //$NON-NLS-1$ getValues().forEach((Long value) -> sj.add(value == null ? String.valueOf(value) : NumberFormat.getNumberInstance(Locale.getDefault()).format(value))); label = sj.toString(); fLabel = label; } return label; }
Source:
public String getValueAt(int column) { String value = getColumns().get(column); if START (value.equals(StringConstants.UNICODE_NULL)) { END return null; } return value; } Switch equals check (a.equals(b) --> b.equals(a)) is null-safe and potentially faster.

Target:
public String getValueAt(int column) { String value = getColumns().get(column); if (StringConstants.UNICODE_NULL.equals(value)) { return null; } return value; }
Source:
void setColumns(List<String> columns) { START for (ListIterator<String> iterator = columns.listIterator(); iterator .hasNext();) { String string = iterator.next(); iterator.set(StringUtils.defaultIfEmpty(string, StringConstants.UNICODE_NULL)); } END m_columns = columns; } Editing on setter is making the collection dirty.

Target:
void setColumns(List<String> columns) { m_columns = columns; }
Source:
public Map<IPath, RepositoryMapping> getRepositoryMappings() { START return mappings; END } Presumably you'd want to return here a read-only view of mappings.

Target:
public final Map<IPath, RepositoryMapping> getRepositoryMappings() { return mappings; }
Source:
private void gtk_swt_set_border_color (GdkColor color) { //Convert GtkColor to GdkRGBA //TODO : Reactor in future commit. This and widget:setForegroundColor have duplicate code. GdkRGBA rgba = null; if (color != null) { rgba = new GdkRGBA (); START rgba = display.toGdkRGBA (color); END } //Construct CSS String //TODO : Reactor in future commit. // This and Control:setBackgroundColorGradient(..). as there is similar code. // ideally we should have a 'constructCssString(..) that accepts attribute-value pairs. String css_string = "* {\n"; if (rgba != null) { String css_color = gtk_rgba_to_css_string (rgba); css_string += "border-color: " + css_color + ";\n"; } css_string += "}\n"; //Apply CSS to widget. long /*int*/context = OS.gtk_widget_get_style_context (handle); gtk_css_provider_load_from_css (context, css_string); } As display.toGdkRGBA never returns null remove "rgba=new GdkRGBA()"

Target:
private void gtk_swt_set_border_color (GdkColor color) { //Convert GtkColor to GdkRGBA //TODO : Reactor in future commit. This and widget:setForegroundColor have duplicate code. GdkRGBA rgba = null; if (color != null) { rgba = display.toGdkRGBA (color); } //Construct CSS String //TODO : Reactor in future commit. // This and Control:setBackgroundColorGradient(..). as there is similar code. // ideally we should have a 'constructCssString(..) that accepts attribute-value pairs. String css_string = "* {\n"; if (rgba != null) { String css_color = gtk_rgba_to_css_string (rgba); css_string += "border-color: " + css_color + ";\n"; } css_string += "}\n"; //Apply CSS to widget. long /*int*/context = OS.gtk_widget_get_style_context (handle); gtk_css_provider_load_from_css (context, css_string); }
Source:
GdkRGBA gdk_color_to_rgba (GdkColor color) { GdkRGBA rgba = null; if (color != null) { START rgba = new GdkRGBA (); END rgba = display.toGdkRGBA (color); } return rgba; } As display.toGdkRGBA never returns null remove "rgba=new GdkRGBA()"

Target:
GdkRGBA gdk_color_to_rgba (GdkColor color) { GdkRGBA rgba = null; if (color != null) { rgba = display.toGdkRGBA (color); } return rgba; }
Source:
private static TmfTreeViewerEntry createTraceEntry(ITmfTrace trace) { TmfTreeViewerEntry traceEntry = new TmfTreeViewerEntry(trace.getName()); Iterable<ITmfAnalysisModuleWithStateSystems> modules = TmfTraceUtils.getAnalysisModulesOfClass(trace, ITmfAnalysisModuleWithStateSystems.class); for (ITmfAnalysisModuleWithStateSystems module : modules) { /* Just schedule the module, the data will be filled when available */ module.schedule(); if (!module.waitForInitialization()) { START return traceEntry; END } for (ITmfStateSystem ss : module.getStateSystems()) { traceEntry.addChild(new StateSystemEntry(ss)); } } return traceEntry; } Don't return, just do a continue so other modules can still add their state systems as children.

Target:
private static TmfTreeViewerEntry createTraceEntry(ITmfTrace trace) { TmfTreeViewerEntry traceEntry = new TmfTreeViewerEntry(trace.getName()); Iterable<ITmfAnalysisModuleWithStateSystems> modules = TmfTraceUtils.getAnalysisModulesOfClass(trace, ITmfAnalysisModuleWithStateSystems.class); for (ITmfAnalysisModuleWithStateSystems module : modules) { /* Just schedule the module, the data will be filled when available */ module.schedule(); if (!module.waitForInitialization()) { continue; } for (ITmfStateSystem ss : module.getStateSystems()) { traceEntry.addChild(new StateSystemEntry(ss)); } } return traceEntry; }
Source:
public boolean waitForInitialization() { try { fInitialized.await(); START } catch (InterruptedException e) END return fInitializationSucceeded; } Here too false should be returned

Target:
public boolean waitForInitialization() { try { fInitialized.await(); } catch (InterruptedException e) { return false; } return fInitializationSucceeded; }
Source:
public void testInitialization() { assertNull(fModule.getStateSystem()); fModule.schedule(); START assertEquals("Initialization succeeded", true, fModule.waitForInitialization()); END assertNotNull(fModule.getStateSystem()); } assertTrue instead

Target:
public void testInitialization() { assertNull(fModule.getStateSystem()); fModule.schedule(); assertTrue("Initialization succeeded", fModule.waitForInitialization()); assertNotNull(fModule.getStateSystem()); }
Source:
public boolean visit(LambdaExpression node) { fCurrentMethodsAndLambdas.push(node); START return visit((Expression) node); END } Can be written as: return super.visit(node); for consistency.

Target:
public boolean visit(LambdaExpression node) { fCurrentMethodsAndLambdas.push(node); return super.visit(node); }
Source:
START public @NonNull String getSymbolText(long address) { END if ((address & (0xFFFFFFFF << 32)) != 0) { return String.format("%08x", address); //$NON-NLS-1$ } return String.format("%016x", address); //$NON-NLS-1$ } Wouldn't this implementation apply to all cases? It looks like a generic utility method. Should it be defined as a default, perhaps even a static, method in the interface?

Target:
public @NonNull String getSymbolText(long address) { if ((address & (0xFFFFFFFF << 32)) == 0) { return String.format("%08x", address); //$NON-NLS-1$ } return String.format("%016x", address); //$NON-NLS-1$ }
Source:
protected void parseReverseMethod(String output) { START if (output.toString().contains("Processor")) { //$NON-NLS-1$ END fReverseMethod = ReverseTraceMethod.PROCESSOR_TRACE; } else if (output.toString().contains("Branch")) { //$NON-NLS-1$ fReverseMethod = ReverseTraceMethod.BRANCH_TRACE; } else if (output.toString().contains("full")) { //$NON-NLS-1$ fReverseMethod = ReverseTraceMethod.FULL_TRACE; } else { fReverseMethod = ReverseTraceMethod.STOP_TRACE; } } Why the toString()? output is already a String. I've pushed a new patch that removes them and reformats some stuff

Target:
protected void parseReverseMethod(String output) { if (output.contains("Processor")) { //$NON-NLS-1$ fReverseMethod = ReverseTraceMethod.PROCESSOR_TRACE; } else if (output.contains("Branch")) { //$NON-NLS-1$ fReverseMethod = ReverseTraceMethod.BRANCH_TRACE; } else if (output.contains("full")) { //$NON-NLS-1$ fReverseMethod = ReverseTraceMethod.FULL_TRACE; } else { fReverseMethod = ReverseTraceMethod.STOP_TRACE; } }
Source:
public Iterable<ITmfEventAspect> getEventAspects() { ImmutableSet.Builder<ITmfEventAspect> builder = ImmutableSet.builder(); builder.addAll(super.getEventAspects()); builder.add(KernelTidAspect.INSTANCE); builder.add(ThreadPriorityAspect.INSTANCE); return START NonNullUtils.checkNotNull(builder.build()); END } This method has an external annotation now.

Target:
public Iterable<ITmfEventAspect> getEventAspects() { /* * This method needs to fill the aspects dynamically because aspects in * the parent class are not all present at the beginning of the trace */ ImmutableSet.Builder<ITmfEventAspect> builder = ImmutableSet.builder(); builder.addAll(super.getEventAspects()); builder.add(KernelTidAspect.INSTANCE); builder.add(ThreadPriorityAspect.INSTANCE); return builder.build(); }
Source:
public Object execute(final ExecutionEvent event) throws ExecutionException { final ISelection currentSelection = HandlerUtil.getCurrentSelection(event); final Resource resourceSelected = getSelectedResource(currentSelection); final TableConfiguration configuration = getEditedTableConfiguration(resourceSelected); START CreateNattableConfigurationWizard wizard = new CreateNattableConfigurationWizard(configuration, resourceSelected); END WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard); dialog.open(); return null; } final

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { final ISelection currentSelection = HandlerUtil.getCurrentSelection(event); final Resource resourceSelected = getSelectedResource(currentSelection); final TableConfiguration configuration = getEditedTableConfiguration(resourceSelected); final CreateNattableConfigurationWizard wizard = new CreateNattableConfigurationWizard(configuration, resourceSelected); final WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard); dialog.open(); return null; }
Source:
protected MasterObjectAxisProvider getMasterObjectAxisProvider(final TableConfiguration configuration) { MasterObjectAxisProvider master = null; // Try to get an existing master axis provider if (0 < configuration.getRowAxisProviders().size()) { final Iterator<AbstractAxisProvider> rowAxisProvidersIterator = configuration.getRowAxisProviders().iterator(); while (rowAxisProvidersIterator.hasNext() && null == master) { START AbstractAxisProvider axisProvider = rowAxisProvidersIterator.next(); END if (axisProvider instanceof MasterObjectAxisProvider) { master = (MasterObjectAxisProvider) axisProvider; } } } return master; } final

Target:
protected MasterObjectAxisProvider getMasterObjectAxisProvider(final TableConfiguration configuration) { MasterObjectAxisProvider master = null; // Try to get an existing master axis provider if (0 < configuration.getRowAxisProviders().size()) { final Iterator<AbstractAxisProvider> rowAxisProvidersIterator = configuration.getRowAxisProviders().iterator(); while (rowAxisProvidersIterator.hasNext() && null == master) { final AbstractAxisProvider axisProvider = rowAxisProvidersIterator.next(); if (axisProvider instanceof MasterObjectAxisProvider) { master = (MasterObjectAxisProvider) axisProvider; } } } return master; }
Source:
protected SlaveObjectAxisProvider getSlaveObjectAxisProvider(final TableConfiguration configuration) { SlaveObjectAxisProvider slave = null; // Try to get an existing master axis provider if (0 < configuration.getRowAxisProviders().size()) { final Iterator<AbstractAxisProvider> columnAxisProvidersIterator = configuration.getColumnAxisProviders().iterator(); while (columnAxisProvidersIterator.hasNext() && null == slave) { START AbstractAxisProvider axisProvider = columnAxisProvidersIterator.next(); END if (axisProvider instanceof SlaveObjectAxisProvider) { slave = (SlaveObjectAxisProvider) axisProvider; } } } return slave; } final

Target:
protected SlaveObjectAxisProvider getSlaveObjectAxisProvider(final TableConfiguration configuration) { SlaveObjectAxisProvider slave = null; // Try to get an existing master axis provider if (0 < configuration.getRowAxisProviders().size()) { final Iterator<AbstractAxisProvider> columnAxisProvidersIterator = configuration.getColumnAxisProviders().iterator(); while (columnAxisProvidersIterator.hasNext() && null == slave) { final AbstractAxisProvider axisProvider = columnAxisProvidersIterator.next(); if (axisProvider instanceof SlaveObjectAxisProvider) { slave = (SlaveObjectAxisProvider) axisProvider; } } } return slave; }
Source:
public static final boolean isSingleColumnTreeTable(final TableConfiguration tableConfiguration) { START TableDisplayStyle style = (TableDisplayStyle) tableConfiguration.getStyle(NattablestylePackage.eINSTANCE.getTableDisplayStyle()); END Assert.isNotNull(style); final DisplayStyle displayStyle = style.getDisplayStyle(); return DisplayStyle.HIERARCHIC_SINGLE_TREE_COLUMN.equals(displayStyle); } final

Target:
public static final boolean isSingleColumnTreeTable(final TableConfiguration tableConfiguration) { final TableDisplayStyle style = (TableDisplayStyle) tableConfiguration.getStyle(NattablestylePackage.eINSTANCE.getTableDisplayStyle()); Assert.isNotNull(style); final DisplayStyle displayStyle = style.getDisplayStyle(); return DisplayStyle.HIERARCHIC_SINGLE_TREE_COLUMN.equals(displayStyle); }
Source:
private boolean isOverrideType(String type) { START return Arrays.asList(OVERRIDE_TYPES).contains(type); END } Use the set in the class variable directly.

Target:
private boolean isOverrideType(String type) { return OVERRIDE_TYPES.contains(type); }
Source:
public START @NonNull Image END getIcon() { String iconFile = getIconFile(); if (iconFile != null) { Bundle bundle = getBundle(); if (bundle != null) { Image icon = TmfProjectModelIcons.loadIcon(bundle, iconFile); if (icon != null) { return icon; } } } return TmfProjectModelIcons.DEFAULT_ANALYSIS_ICON; } Is this an artifact or intentional? It's not in the interface.

Target:
public Image getIcon() { String iconFile = getIconFile(); if (iconFile != null) { Bundle bundle = getBundle(); if (bundle != null) { Image icon = TmfProjectModelIcons.loadIcon(bundle, iconFile); if (icon != null) { return icon; } } } return TmfProjectModelIcons.DEFAULT_ANALYSIS_ICON; }
Source:
START public END UnassociatedEditorStrategyRegistry getUnassociatedEditorStrategyRegistry() { if (unassociatedEditorStrategyRegistry == null) { unassociatedEditorStrategyRegistry = new UnassociatedEditorStrategyRegistry(); } return unassociatedEditorStrategyRegistry; } Should be synchronized

Target:
public synchronized UnassociatedEditorStrategyRegistry getUnassociatedEditorStrategyRegistry() { if (unassociatedEditorStrategyRegistry == null) { unassociatedEditorStrategyRegistry = new UnassociatedEditorStrategyRegistry(); } return unassociatedEditorStrategyRegistry; }
Source:
public void before() { writer = new StringWriter(); delegate = new HtmlDocumentBuilder(writer); delegate.setEmitAsDocument(false); builder = new HtmlSubsetDocumentBuilder(delegate); builder.setSupportedBlockTypes(Sets.newHashSet(BlockType.PARAGRAPH)); builder.setSupportedSpanTypes(Sets.newHashSet(SpanType.BOLD), Collections.<SpanHtmlElementStrategy> emptyList(), START ImmutableMap.<SpanType, String> of()); END builder.setSupportedHeadingLevel(3); builder.beginDocument(); } these changes would be unnecessary if the builder had a separate method for setting span substitutions

Target:
public void before() { writer = new StringWriter(); delegate = new HtmlDocumentBuilder(writer); delegate.setEmitAsDocument(false); builder = new HtmlSubsetDocumentBuilder(delegate); builder.setSupportedBlockTypes(Sets.newHashSet(BlockType.PARAGRAPH)); builder.setSupportedSpanTypes(Sets.newHashSet(SpanType.BOLD), Collections.<SpanHtmlElementStrategy> emptyList()); builder.setSupportedHeadingLevel(3); builder.beginDocument(); }
Source:
private Set<String> toDirSet(String dirs) { START if (dirs == null || dirs.length() == 0) END return Collections.emptySet(); Set<String> configuredStrings = new HashSet<String>(); StringTokenizer tok = new StringTokenizer(dirs, File.pathSeparator); while (tok.hasMoreTokens()) { configuredStrings .add(workspacePath.resolve(tok.nextToken()).toString()); } return configuredStrings; } While you're touching this, why not add the missing braces? And maybe use dirs.isEmpty()?

Target:
private Set<String> toDirSet(String dirs) { if (dirs == null || dirs.isEmpty()) { return Collections.emptySet(); } Set<String> configuredStrings = new HashSet<String>(); StringTokenizer tok = new StringTokenizer(dirs, File.pathSeparator); while (tok.hasMoreTokens()) { configuredStrings .add(workspacePath.resolve(tok.nextToken()).toString()); } return configuredStrings; }
Source:
protected void setupInternals() throws IOException { if (getObjectDirectory() == null) { START if (getGitCommonDir() != null) END setObjectDirectory( safeFS().resolve(getGitCommonDir(), OBJECTS)); // $NON-NLS-1$ else if (getGitDir() != null) setObjectDirectory(safeFS().resolve(getGitDir(), OBJECTS)); // $NON-NLS-1$ } } style nit: missing braces

Target:
protected void setupInternals() throws IOException { if (getObjectDirectory() == null) { if (getGitCommonDir() != null) { setObjectDirectory( safeFS().resolve(getGitCommonDir(), OBJECTS)); } else if (getGitDir() != null) { setObjectDirectory(safeFS().resolve(getGitDir(), OBJECTS)); } } }
Source:
public static SetMultimap<String, String> getRequirementValuesMap(Iterable<IAnalysisRequirementProvider> providers) { START SetMultimap<String, String> valuesByType = NonNullUtils.checkNotNull(HashMultimap.create()); END for (IAnalysisRequirementProvider provider : providers) { for (TmfAnalysisRequirement requirement : provider.getAnalysisRequirements()) { valuesByType.putAll(requirement.getType(), requirement.getValues()); } } return valuesByType; } This should be added to external annotations instead.

Target:
public static SetMultimap<String, String> getRequirementValuesMap(Iterable<IAnalysisRequirementProvider> providers) { SetMultimap<String, String> valuesByType = HashMultimap.create(); for (IAnalysisRequirementProvider provider : providers) { for (TmfAnalysisRequirement requirement : provider.getAnalysisRequirements()) { valuesByType.putAll(requirement.getType(), requirement.getValues()); } } return valuesByType; }
Source:
public void cleanup() { File tempFile = fTempFile; if (tempFile != null) { START tempFile.delete(); END } } There is a guarantee that the first statement after a if is executed without being preempted. But only the very first statement [1]. So you could null-check directly on fTempFile here. It's very good practice to extract to a local variable in general, but here it's a very small method that does only one thing, it would be fine, imo. [1] I remember this I think from a class a looong time ago, but I can't find any references online... The compiler seems to agree with me though. Or it's a bug and I'm becoming crazy? :O

Target:
public void cleanup() { if (fTempFile != null) { fTempFile.delete(); } }
Source:
START public @NonNull String getTraceHost() { END return fHostThread.getHost(); } You could add a package-info.java file to the package

Target:
public String getTraceHost() { return fHostThread.getHost(); }
Source:
public Object getParameter(String name) { if (name.equals(CriticalPathModule.PARAM_WORKER)) { final HostThread currentHostThread = fCurrentHostThread; if (currentHostThread == null) { return null; } /* Try to find the worker for the critical path */ IAnalysisModule mod = getModule(); if ((mod != null) && (mod instanceof CriticalPathModule)) { LttngWorker worker = new LttngWorker(currentHostThread, "", 0); //$NON-NLS-1$ return worker; } START return currentHostThread; END } return null; } I really don't know why currentHostThread is returned (or the previous entry)... Only the critical path module needs anything. You could remove this line while updating this file.

Target:
public Object getParameter(String name) { if (name.equals(CriticalPathModule.PARAM_WORKER)) { final HostThread currentHostThread = fCurrentHostThread; if (currentHostThread == null) { return null; } /* Try to find the worker for the critical path */ IAnalysisModule mod = getModule(); if ((mod != null) && (mod instanceof CriticalPathModule)) { LttngWorker worker = new LttngWorker(currentHostThread, "", 0); //$NON-NLS-1$ return worker; } } return null; }
Source:
private START ArrayList<DataChangedEvent> END getReuseChangedEvents( Set<IComponentNamePO> reuseChangedCompNames) { ArrayList<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : reuseChangedCompNames) { events.add(new DataChangedEvent(compName, DataState.ReuseChanged, UpdateState.all)); } return events; } Please use interfaces where possible.

Target:
private List<DataChangedEvent> getReuseChangedEvents( Set<IComponentNamePO> reuseChangedCompNames) { List<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : reuseChangedCompNames) { events.add(new DataChangedEvent(compName, DataState.ReuseChanged, UpdateState.all)); } return events; }
Source:
private START ArrayList<DataChangedEvent> END getRenamedEvents(Set<IComponentNamePO> renamedCompNames) { ArrayList<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : renamedCompNames) { events.add(new DataChangedEvent(compName, DataState.Renamed, UpdateState.all)); } return events; } Please use interfaces where possible.

Target:
private List<DataChangedEvent> getRenamedEvents(Set<IComponentNamePO> renamedCompNames) { List<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : renamedCompNames) { events.add(new DataChangedEvent(compName, DataState.Renamed, UpdateState.all)); } return events; }
Source:
public String getCellDataValueByPosition(int row, int col) { assertIsLegalCell(row, col); Object obj = widget.getDataValueByPosition(col, row); if(obj != null) { return obj.toString(); } START else END return ""; } block please

Target:
public String getCellDataValueByPosition(int row, int col) { assertIsLegalCell(row, col); Object obj = widget.getDataValueByPosition(col, row); if (obj != null) { return obj.toString(); } else { return ""; } }
Source:
public SWTBotRootMenu contextMenu(final Control control) throws WidgetNotFoundException { waitForEnabled(); START rightClick(); END Rectangle location = widgetBounds(); return NatTableContextMenuFinder.contextMenu(widget, location.x + (location.width / 2), location.y + (location.height / 2)); } In a real application the order of events will be MouseDown, MenuDetect, MouseUp. Here you will send the MenuDetect only later below in the NatTableContextMenuFinder. Since, for now, NatTable requires the MouseDown event, perhaps it would be better to not call rightClick here but instead send those mouse events from the NatTableContextMenuFinder?

Target:
public SWTBotRootMenu contextMenu(final Control control) throws WidgetNotFoundException { waitForEnabled(); Rectangle location = widgetBounds(); return NatTableContextMenuFinder.contextMenu(widget, location.width / 2, location.height / 2); }
Source:
public SWTBotMenu contextMenu(int row, int col, String text) throws WidgetNotFoundException { assertIsLegalCell(row, col); Assert.isNotNull(text); waitForEnabled(); rightClick(row, col); Rectangle location = widget.getBoundsByPosition(col, row); START return NatTableContextMenuFinder.contextMenu(widget, location.x + (location.width / 2), location.y + (location.height / 2), text); END } Here it's OK, assuming getBoundsByPosition is cell's bound relative to NatTable control.

Target:
public SWTBotMenu contextMenu(int row, int col, String text) throws WidgetNotFoundException { assertIsLegalCell(row, col); Assert.isNotNull(text); waitForEnabled(); Rectangle location = widget.getBoundsByPosition(col, row); return NatTableContextMenuFinder.contextMenu(widget, location.x + (location.width / 2), location.y + (location.height / 2), text); }
Source:
START public SWTBotRootMenu END contextMenu(final Control control) throws WidgetNotFoundException { waitForEnabled(); Rectangle location = widgetBounds(); return NatTableContextMenuFinder.contextMenu(widget, location.width / 2, location.height / 2); } I think we want to leave this one as protected. The user should call the public contextMenu() that will in turn call this one.

Target:
protected SWTBotRootMenu contextMenu(final Control control) throws WidgetNotFoundException { waitForEnabled(); Rectangle location = widgetBounds(); return NatTableContextMenuFinder.contextMenu(widget, location.width / 2, location.height / 2); }
Source:
public @NonNull Iterable<@NonNull TmfAnalysisRequirement> getAnalysisRequirements() { Set<@NonNull TmfAnalysisRequirement> requirements = fAnalysisRequirements; if (requirements == null) { LttngUstTrace trace = getTrace(); START ILttngUstEventLayout layout = ILttngUstEventLayout.DEFAULT_LAYOUT; END if (trace != null) { layout = trace.getEventLayout(); } requirements = ImmutableSet.of(new LttngUstCallStackAnalysisRequirement(layout)); fAnalysisRequirements = requirements; } return requirements; } here, to avoid first assignation, you could (trace != null) ? trace.getEventLayout : ILttngUst....

Target:
public @NonNull Iterable<@NonNull TmfAnalysisRequirement> getAnalysisRequirements() { Set<@NonNull TmfAnalysisRequirement> requirements = fAnalysisRequirements; if (requirements == null) { LttngUstTrace trace = getTrace(); ILttngUstEventLayout layout = (trace != null) ? trace.getEventLayout() : ILttngUstEventLayout.DEFAULT_LAYOUT; requirements = ImmutableSet.of(new LttngUstCallStackAnalysisRequirement(layout)); fAnalysisRequirements = requirements; } return requirements; }