auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected ContentSecurityPolicy addOrAppend(String key, String value) { if (m_directives.containsKey(key)) { String existingSource = m_directives.get(key); // Only change directive, if the former value was not-null OR the new value is not null. // If existingSource and new value are both null, do not change directive, since StringUtility.join creates an empty string for two null values // Further check for duplicates and do not add new value, if value already is part of the existing source START if ((existingSource != null || value != null) && !StringUtility.containsString(existingSource, value)) { END m_directives.put(key, StringUtility.join(SOURCE_SEPARATOR, existingSource, value)); } } else { m_directives.put(key, value); } return this; } Could we write that simpler? if (value == null) { return; } if (m_directives.containKey(key)) { ... if (!StringUtility.containsString(existingSource, value)) { ...

Target:
protected ContentSecurityPolicy addOrAppend(String key, String value) { if (value == null) { return this; } if (m_directives.containsKey(key)) { String existingSource = m_directives.get(key); // Check for duplicates and do not add new value, if value already is part of the existing source if (!StringUtility.containsString(existingSource, value)) { m_directives.put(key, StringUtility.join(SOURCE_SEPARATOR, existingSource, value)); } } else { m_directives.put(key, value); } return this; }
Source:
public String getModelPluginId(EPackage ePackage, ResourceSet set) { if (getProvidedMetamodels().contains(ePackage.getNsURI())) { GenPackage genPackage = getGenmodelRegistry().findGenPackage(ePackage.getNsURI(), set); getModelPluginId(genPackage); } START return null; END } Should this method always return null? Inside the 'if' there is no return statement...

Target:
public String getModelPluginId(EPackage ePackage, ResourceSet set) { if (getProvidedMetamodels().contains(ePackage.getNsURI())) { GenPackage genPackage = getGenmodelRegistry().findGenPackage(ePackage.getNsURI(), set); return getModelPluginId(genPackage); } return null; }
Source:
protected boolean updateSelection(IStructuredSelection selection) { START BuildState buildState = BuildState.STOPPED; END if (selection.getFirstElement() instanceof IBuildPlan) { IBuildPlan buildPlan = (IBuildPlan) selection.getFirstElement(); return buildPlan.getState() == BuildState.RUNNING; } return false; } this is unused.

Target:
protected boolean updateSelection(IStructuredSelection selection) { if (selection.getFirstElement() instanceof IBuildPlan) { IBuildPlan buildPlan = (IBuildPlan) selection.getFirstElement(); return buildPlan.getState() == BuildState.RUNNING; } return false; }
Source:
public void testCrash() throws Exception { IRunnableWithProgress operation = new CrashingRunnable(); try{ PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, false, operation); fail("Should have an invocation target exception"); } catch (InvocationTargetException e){ //We should get this } boolean START interrupted = END Thread.interrupted(); if (interrupted) { fail("Thread was interrupted at end of test"); } } Why not inline this variable?

Target:
public void testCrash() throws Exception { IRunnableWithProgress operation = new CrashingRunnable(); try{ PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, false, operation); fail("Should have an invocation target exception"); } catch (InvocationTargetException e){ //We should get this } if (Thread.interrupted()) { fail("Thread was interrupted at end of test"); } }
Source:
private StoredConfig loadUserConfig() throws IOException { FileBasedConfig c = SystemReader.getInstance().openUserConfig(null, FS.DETECTED); try { c.load(); } catch (ConfigInvalidException e1) { IOException e2 = new IOException(MessageFormat .format(LfsText.get().userConfigInvalid, c.getFile() .getAbsolutePath(), e1)); START e2.initCause(e1); END throw e2; } return c; } This should not be necessary. IOException can take the cause as an argument. I.e. this entire block can be replaced with a single "throw new IOException(...) rather than creating the instance, setting the cause on it, and then throwing it. See for example the change I did here: https://git.eclipse.org/r/#/c/114363/4/org.eclipse.jgit/src/org/eclipse/jgit/gitrepo/ManifestParser.java

Target:
private StoredConfig loadUserConfig() throws IOException { FileBasedConfig c = SystemReader.getInstance().openUserConfig(null, FS.DETECTED); try { c.load(); } catch (ConfigInvalidException e1) { throw new IOException(MessageFormat .format(LfsText.get().userConfigInvalid, c.getFile() .getAbsolutePath(), e1), e1); } return c; }
Source:
public boolean isDirty() { if (getTrace() == null) { return false; } TmfTraceContext ctx = TmfTraceManager.getInstance().getCurrentTraceContext(); long startTime = ctx.getWindowRange().getStartTime().toNanos(); long endTime = ctx.getWindowRange().getEndTime().toNanos(); // If the time graph control hasn't updated all the way to the end of // the window range then it's dirty. A refresh should happen later. START if (getWindowStartTime() != startTime || getWindowEndTime() != endTime) { END return true; } return false; } how about a single return instead of an if?

Target:
public boolean isDirty() { if (getTrace() == null) { return false; } TmfTraceContext ctx = TmfTraceManager.getInstance().getCurrentTraceContext(); long startTime = ctx.getWindowRange().getStartTime().toNanos(); long endTime = ctx.getWindowRange().getEndTime().toNanos(); // If the chart viewer hasn't updated all the way to the end of // the window range then it's dirty. A refresh should happen later. return (getWindowStartTime() != startTime || getWindowEndTime() != endTime); }
Source:
private static Object iterateCompare(long startTime, long endTime, ISegmentStore<@NonNull ISegment> store, @NonNull Comparator<@NonNull ISegment> comparator) { Object shutupCompilerWarnings = null; for (ISegment elem : store.getIntersectingElements((endTime - startTime) / 2, comparator)) { shutupCompilerWarnings = elem; } START return shutupCompilerWarnings; END } I LOVE THIS

Target:
private static Object iterateCompare(long startTime, long endTime, ISegmentStore<@NonNull ISegment> store, @NonNull Comparator<@NonNull ISegment> comparator) { Object shutupCompilerWarnings = null; for (ISegment elem : store.getIntersectingElements(startTime, endTime, comparator)) { shutupCompilerWarnings = elem; } return shutupCompilerWarnings; }
Source:
START public IBinding END getPromiscuousBinding() { return promiscuousBinding; } Make final.

Target:
public final IBinding getPromiscuousBinding() { return promiscuousBinding; }
Source:
private IBinding resolveBindingPromiscuous() { // If we haven't already resolved the non-promiscuous binding, do so now. if (fBinding == null) { try { CPPSemantics.disablePromiscuousBindingResolution(); resolveBindingNormal(); } finally { CPPSemantics.enablePromiscuousBindingResolution(); } } // If the non-promiscuous binding is not a ProblemBinding, the promiscuous // binding will be the same, so just return it. if (!(fBinding instanceof ProblemBinding)) { return fBinding; } // Otherwise, the non-promiscuous binding is a ProblemBinding. ProblemBinding problem = (ProblemBinding) fBinding; if START (problem.getPromiscuousBinding() END == null) { // Resolve the promiscuous binding, and store it in the ProblemBinding. IBinding promiscuous = resolveBindingNormal(); problem.setPromiscuousBinding(promiscuous); // Restore the cached ProblemBinding (which resolveBindingNormal() overwrote). fBinding = problem; } return problem.getPromiscuousBinding(); } Better to write: IBinding promiscuous = problem.getPromiscuousBinding(); if (promiscuous == null) { ... } return promiscuous;

Target:
private IBinding resolveBindingPromiscuous() { // If we haven't already resolved the non-promiscuous binding, do so now. if (fBinding == null) { try { CPPSemantics.disablePromiscuousBindingResolution(); resolveBindingNormal(); } finally { CPPSemantics.enablePromiscuousBindingResolution(); } } // If the non-promiscuous binding is not a ProblemBinding, the promiscuous // binding will be the same, so just return it. if (!(fBinding instanceof ProblemBinding)) { return fBinding; } // Otherwise, the non-promiscuous binding is a ProblemBinding. ProblemBinding problem = (ProblemBinding) fBinding; IBinding promiscuous = problem.getPromiscuousBinding(); if (promiscuous == null) { // Resolve the promiscuous binding, and store it in the ProblemBinding. promiscuous = resolveBindingNormal(); problem.setPromiscuousBinding(promiscuous); // Restore the cached ProblemBinding (which resolveBindingNormal() overwrote). fBinding = problem; } return promiscuous; }
Source:
public void redraw() { if (fRelayoutRequired) { layout(true); return; } if (fCachedTextViewer != null && fCachedTextViewer.getTextWidget() START != null END && fCanvas != null && !fCanvas.isDisposed()) { if (VerticalRuler.AVOID_NEW_GC) { fCanvas.redraw(); fCanvas.update(); } else { GC gc= new GC(fCanvas); doubleBufferPaint(gc); gc.dispose(); } } } can we please wrap this long condition, so it can be readable?

Target:
public void redraw() { if (fRelayoutRequired) { layout(true); return; } if (!isDisposed()) { if (VerticalRuler.AVOID_NEW_GC) { fCanvas.redraw(); fCanvas.update(); } else { GC gc= new GC(fCanvas); doubleBufferPaint(gc); gc.dispose(); } } }
Source:
public EList<IBuildPlan> getPlanAndAllChildren() { START return new BasicEList<IBuildPlan>( END Stream.concat(Stream.of(this), getChildren().stream().flatMap(IBuildPlan::flattened)) .collect(Collectors.toList())); } I don't think we need the EList.

Target:
public List<IBuildPlan> getPlanAndAllChildren() { return Stream.concat(Stream.of(this), getChildren().stream().flatMap(IBuildPlan::flattened)) .collect(Collectors.toList()); }
Source:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long count, INewSegment segmentCreator) { for (int i = 0; i < count; i++) { START long start = i + fuzz[i % size]; END store.add(segmentCreator.createSegment(start, start + 10, i)); } } I had this line create overflows and Segments with negative start times (before the tree start)

Target:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long count, INewSegment segmentCreator) { for (int i = 0; i < count; i++) { long start = (long) i + fuzz[i % size]; store.add(segmentCreator.createSegment(start, start + 10, i)); } }
Source:
public void setTimeGraphScale(TimeGraphScale timeGraphScale) { fTimeGraphScale = timeGraphScale; START setHeaderHeight(timeGraphScale.getBounds().height); END } This shouldn't be necessary anymore.

Target:
public void setTimeGraphScale(TimeGraphScale timeGraphScale) { fTimeGraphScale = timeGraphScale; }
Source:
public void paintControl(PaintEvent event) { if (fTextWidget != null) { try { handleDrawRequest(event.gc); } catch (IllegalStateException e) { // Do not allow the exception to escape this PaintListener method into the SWT code. // See http://bugs.eclipse.org/498907 String PLUGIN_ID= "org.eclipse.jface.text"; //$NON-NLS-1$ ILog log= Platform.getLog(Platform.getBundle(PLUGIN_ID)); log.log(new Status(IStatus.ERROR, PLUGIN_ID, START JFaceTextMessages.getString("MatchingCharacterPainter.unexpected_error"), END e)); //$NON-NLS-1$ return; } } } Log messages are generally English strings and do not come from translation bundles. Messages written to the log are intended to be read by the Eclipse developers, not the end user.

Target:
public void paintControl(PaintEvent event) { if (fTextWidget != null) { try { handleDrawRequest(event.gc); } catch (IllegalStateException e) { // Do not allow the exception to escape this PaintListener method into the SWT code. // See http://bugs.eclipse.org/498907 String PLUGIN_ID= "org.eclipse.jface.text"; //$NON-NLS-1$ ILog log= Platform.getLog(Platform.getBundle(PLUGIN_ID)); log.log(new Status(IStatus.ERROR, PLUGIN_ID, e.getMessage(), e)); } } }
Source:
public static int nvl(Integer value, int valueWhenNull) { if (value != null) { return value.intValue(); } START else { END return valueWhenNull; } } Unnecessary "else" blocks, just return

Target:
public static int nvl(Integer value, int valueWhenNull) { if (value != null) { return value.intValue(); } return valueWhenNull; }
Source:
START public @NonNull ISegment createSegment(long start, long end) { END return new BasicSegment(start, end); } Should this be protected

Target:
protected @NonNull ISegment createSegment(long start, long end) { return new BasicSegment(start, end); }
Source:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long low, long high) { for (int i = (int) low; i < high; i++) { START long start = (long) i + fuzz[i % size]; END store.add(new BasicSegment(start, start + 10)); } } especially because of this. long->int->long

Target:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long low, long high) { for (long i = low; i < high; i++) { long start = i + fuzz[(int) (i % size)]; store.add(new BasicSegment(start, start + 10)); } }
Source:
private static int[] fuzzyArray(int size){ int[] fuzz = new int[DEFAULT_SAMPLE]; Random rng = new Random(10); for (int i = 0; i < DEFAULT_SAMPLE; i++) { START fuzz[i] = rng.nextInt(); END } return fuzz; } rng.nextInt(1000);

Target:
private static int[] fuzzyArray(int size) { int[] fuzz = new int[DEFAULT_SAMPLE]; Random rng = new Random(10); for (int i = 0; i < DEFAULT_SAMPLE; i++) { fuzz[i] = rng.nextInt(DEFAULT_SAMPLE); } return fuzz; }
Source:
public Object execute(ExecutionEvent event) throws START ExecutionException { END rebuildJob.cancel(); rebuildJob.schedule(); return null; } ExecutionException is unnecessary but ok.

Target:
public Object execute(ExecutionEvent event) { rebuildJob.cancel(); rebuildJob.schedule(); return null; }
Source:
START protected synchronized void setPinned(boolean pinned) { END if (!pinned) { if (fSavedRangeSyncSignal != null) { windowRangeUpdated(fSavedRangeSyncSignal); fSavedRangeSyncSignal = null; } if (fSavedTimeSyncSignal != null) { selectionRangeUpdated(fSavedTimeSyncSignal); fSavedTimeSyncSignal = null; } } } I would propose to have a common pin implementation to the base class AbstractTimeGraphView. Also note, the existing implementation in this class only inhibits changes coming in from external, but doesn't prevent the pinned Call Stack view from broadcasting a new window range.

Target:
public void setPinned(boolean pinned) { if (!pinned) { if (fSavedRangeSyncSignal != null) { windowRangeUpdated(fSavedRangeSyncSignal); fSavedRangeSyncSignal = null; } if (fSavedTimeSyncSignal != null) { selectionRangeUpdated(fSavedTimeSyncSignal); fSavedTimeSyncSignal = null; } } }
Source:
private boolean requiresIncomingDecoration(AbstractAttributeEditor editor, TaskDataModel model, TaskAttribute attribute) { return editor.isDecorationEnabled() && model.hasBeenRead() && model.hasIncomingChanges(attribute) START && isCompatibleKind(attribute.getMetaData().getKind()) ? true : false; END } Remove "? true : false"

Target:
private boolean requiresIncomingDecoration(AbstractAttributeEditor editor, TaskDataModel model, TaskAttribute attribute) { return editor.isDecorationEnabled() && model.hasBeenRead() && model.hasIncomingChanges(attribute) && isCompatibleKind(attribute.getMetaData().getKind()); }
Source:
protected int getMaximumTotalSize() { // Define max size in properties file. START int maxSize = Integer.parseInt(DiagramUIPlugin.INSTANCE.getString("_Pref_DiagramExportSizeMax")); //$NON-NLS-1$ return maxSize; END } return Integer.parseInt(DiagramUIPlugin.INSTANCE.getString("_Pref_DiagramExportSizeMax")); //$NON-NLS-1$

Target:
protected int getMaximumTotalSize() { // Define max size in properties file. return Integer.parseInt(DiagramUIPlugin.INSTANCE.getString("_Pref_DiagramExportSizeMax")); //$NON-NLS-1$; }
Source:
public org.eclipse.swt.graphics.Rectangle calculateImageRectangle(List editparts) { org.eclipse.swt.graphics.Rectangle sourceRect = super.calculateImageRectangle(editparts); return new START org.eclipse.swt.graphics.Rectangle(sourceRect.x, sourceRect.y, scaleAsInt(sourceRect.width), END scaleAsInt(sourceRect.height)); } No sure but in getDiagramPartInfo the x and y coordinates are scaled but not here. Is it expected?

Target:
public org.eclipse.swt.graphics.Rectangle calculateImageRectangle(List editparts) { org.eclipse.swt.graphics.Rectangle sourceRect = super.calculateImageRectangle(editparts); return new org.eclipse.swt.graphics.Rectangle(scaleAsInt(sourceRect.x), scaleAsInt(sourceRect.y), scaleAsInt(sourceRect.width), scaleAsInt(sourceRect.height)); }
Source:
public String toString() { START final ToStringBuilder builder = new ToStringBuilder(this); END builder .attr("name", m_name) .attr("type", m_type) .attr("resolveMethod", m_resolveMethod) .attr("properties", m_properties); return builder.toString(); } Change to: return new ToStringBuilder(this) .attr("name", m_name) .attr("type", m_type) .attr("resolveMethod", m_resolveMethod) .attr("properties", m_properties) .toString();

Target:
public String toString() { return new ToStringBuilder(this) .attr("name", m_name) .attr("type", m_type) .attr("resolveMethod", m_resolveMethod) .attr("properties", m_properties) .toString(); }
Source:
public void test_addKeyListenerKeyPressedAdapterLorg_eclipse_swt_events_KeyListener() { START KeyListener listener = KeyListener.keyPressedAdapter(event -> { END eventOccurred = true; }); control.addKeyListener(listener); eventOccurred = false; control.notifyListeners(SWT.KeyDown, new Event()); assertTrue(eventOccurred); control.removeKeyListener(listener); eventOccurred = false; control.notifyListeners(SWT.KeyDown, new Event()); assertFalse(eventOccurred); } Why not the shorter version? KeyListener listener = KeyListener.keyPressedAdapter(event -> eventOccurred = true);

Target:
public void test_addKeyListenerKeyPressedAdapterLorg_eclipse_swt_events_KeyListener() { KeyListener listener = KeyListener.keyPressedAdapter(event -> eventOccurred = true); control.addKeyListener(listener); eventOccurred = false; control.notifyListeners(SWT.KeyDown, new Event()); assertTrue(eventOccurred); control.removeKeyListener(listener); eventOccurred = false; control.notifyListeners(SWT.KeyDown, new Event()); assertFalse(eventOccurred); }
Source:
public START boolean isMirroringEnabled() END { return fMirroringEnabled; } final

Target:
public final boolean isMirroringEnabled() { return fMirroringEnabled; }
Source:
public START void setMirroringEnabled(boolean END value) { fMirroringEnabled = value; } final

Target:
public final void setMirroringEnabled(boolean value) { fMirroringEnabled = value; }
Source:
protected void fireStoppedEvent(final MIOutput output, final IExecutionDMContext ctx) { final DsfSession session = DsfSession.getSession(ctx.getSessionId()); START session.getExecutor().execute(new DsfRunnable() { END @Override public void run() { int token = output.getMIResultRecord().getToken(); session.dispatchEvent(MIErrorEvent.parse(ctx, token, output.getMIResultRecord().getMIResults(), output.getMIOOBRecords()), null); } }); } No need to call session.dispatchEvent() on the executor since it is @ThreadSafe. It will make its own call to the executor.

Target:
protected void fireStoppedEvent(final MIOutput output, final IExecutionDMContext ctx) { DsfSession session = DsfSession.getSession(ctx.getSessionId()); int token = output.getMIResultRecord().getToken(); session.dispatchEvent(MIErrorEvent.parse(ctx, token, output.getMIResultRecord().getMIResults(), output.getMIOOBRecords()), null); }
Source:
public UniquenessEnforcerNode(ReteContainer reteContainer, int tupleWidth) { super(reteContainer); this.parents = new ArrayList<Supplier>(); this.memory = new TupleMemory(); this.rederivableMemory = new TupleMemory(); this.tupleWidth = tupleWidth; START reteContainer.registerClearable(this.memory); END this.nullMask = TupleMask.linear(0, tupleWidth); this.identityMask = TupleMask.identity(tupleWidth); this.deleteRederive = true; } rederivableMemory should be registered as clearable as well!

Target:
public UniquenessEnforcerNode(ReteContainer reteContainer, int tupleWidth) { super(reteContainer); this.parents = new ArrayList<Supplier>(); this.memory = new TupleMemory(); this.rederivableMemory = new TupleMemory(); this.tupleWidth = tupleWidth; reteContainer.registerClearable(this.memory); reteContainer.registerClearable(this.rederivableMemory); this.nullMask = TupleMask.linear(0, tupleWidth); this.identityMask = TupleMask.identity(tupleWidth); this.deleteRederive = true; }
Source:
START protected IDialogSettings END getDialogBoundsSettings() { IDialogSettings settings = DebugUIPlugin.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(SETTINGS_ID); if (section == null) { section = settings.addNewSection(SETTINGS_ID); } return section; } Do we really want this protected?

Target:
private IDialogSettings getDialogBoundsSettings() { IDialogSettings settings = DebugUIPlugin.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(SETTINGS_ID); if (section == null) { section = settings.addNewSection(SETTINGS_ID); } return section; }
Source:
void messageConsumptionSingleThreaded() { while (!activeMailboxes.isEmpty() || getFirstRederivable() != null) { RederivableNode node = getFirstRederivable(); while (node != null) { node.rederiveOne(); node = getFirstRederivable(); } START if (!activeMailboxes.isEmpty()) { END Mailbox mailbox = activeMailboxes.iterator().next(); activeMailboxes.remove(mailbox); mailbox.deliverMessages(); } } } why are the two steps reversed?

Target:
void messageConsumptionSingleThreaded() { while (!activeMailboxes.isEmpty() || getFirstRederivable() != null) { // first deliver all the messages ... while (!activeMailboxes.isEmpty()) { Mailbox mailbox = activeMailboxes.iterator().next(); activeMailboxes.remove(mailbox); mailbox.deliverMessages(); } // ... and then start a re-derivation phase RederivableNode node = getFirstRederivable(); if (node != null) { node.rederiveOne(); } } }
Source:
START public RangeCondition<E> subCondition(E from, E to) { if (from.compareTo(to) > 0) { throw new IllegalArgumentException(from.toString() + " is greater than " + to.toString()); //$NON-NLS-1$ } END return new ContinuousRangeCondition<>(max(fMin, from), min(fMax, to)); } while I think it makes sense to check this if we are calling it E from, E to, wouldn't the constructor be a better place to enforce this? In the 2D query patch, Genevieve suggested not enforcing it in the constructor and using min/max instead.

Target:
public RangeCondition<E> subCondition(E from, E to) { return new ContinuousRangeCondition<>(from, to); }
Source:
public boolean close() { START if (fetchResultImage != null) END fetchResultImage.dispose(); return super.close(); } Missing braces.

Target:
public boolean close() { if (fetchResultImage != null) { fetchResultImage.dispose(); } return super.close(); }
Source:
private void addViewerToSelectionProvider() { IWorkbenchPart part = getCompareConfiguration().getContainer().getWorkbenchPart(); ISelectionProvider provider = part.getSite().getSelectionProvider(); if (provider instanceof CompareEditorSelectionProvider) { // Replace existing selection provider with our own to track non-text selection EMFCompareEditorSelectionProviderWrapper compareProvider = new EMFCompareEditorSelectionProviderWrapper( (CompareEditorSelectionProvider)provider); part.getSite().setSelectionProvider(compareProvider); START compareProvider.addViewers(Arrays.asList((Viewer)getViewer()), getViewer()); END } } Please declare method addViewers(List<? extends Viewer>...) and remove the cast to (Viewer) here.

Target:
private void addViewerToSelectionProvider() { IWorkbenchPart part = getCompareConfiguration().getContainer().getWorkbenchPart(); ISelectionProvider provider = part.getSite().getSelectionProvider(); if (provider instanceof CompareEditorSelectionProvider) { // Replace existing selection provider with our own to track non-text selection EMFCompareEditorSelectionProviderWrapper compareProvider = new EMFCompareEditorSelectionProviderWrapper( (CompareEditorSelectionProvider)provider); part.getSite().setSelectionProvider(compareProvider); compareProvider.addViewers(Arrays.asList(getViewer()), getViewer()); } }
Source:
public boolean provides(IDiagramElementEditPart editPart) { boolean provides = false; if START (!(editPart instanceof IDiagramNameEditPart)) { END provides = true; } return provides; } This is not the same logic as org.eclipse.sirius.diagram.ui.tools.api.decoration.AbstractSiriusDecorationDescriptorProvider.shouldBeDecorated(EditPart). Is it expected?

Target:
public boolean provides(IDiagramElementEditPart editPart) { return true; }
Source:
public void setBranchName(String branchName) { this.branchName = branchName; START if (nameText != null) END nameText.setText(branchName); } Missing braces.

Target:
public void setBranchName(String branchName) { this.branchName = branchName; if (nameText != null) { nameText.setText(branchName); } }
Source:
public void setNewBranchName(String newBranchName) { this.newBranchName = newBranchName; START if (myPage != null) END myPage.setBranchName(newBranchName); } Missing braces.

Target:
public void setNewBranchName(String newBranchName) { this.newBranchName = newBranchName; if (myPage != null) { myPage.setBranchName(newBranchName); } }
Source:
public static boolean isConnectedInside(Port port) { START UMLRTPort rt = (port == null) ? null : UMLRTPort.getInstance(port); END return (rt != null) && rt.isConnectedInside(); } Could we consider here that a null Port is a non valid RTPort? This would avoid null tests (that are already performed in the getFacade() operation).

Target:
public static boolean isConnectedInside(Port port) { UMLRTPort rt = UMLRTPort.getInstance(port); return (rt != null) && rt.isConnectedInside(); }
Source:
public String toString() { return new String(this.workspacePath) + START "|" + END new String(this.fieldDescriptor); //$NON-NLS-1$ } This is an anti-pattern. Use a StringBuilder instead. Why not comma instead of |?

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.workspacePath); builder.append("|"); //$NON-NLS-1$ builder.append(this.fieldDescriptor); return builder.toString(); }
Source:
START public final String toStringWithId() { END return String.format("[%s][%s]", getId(), getName()); } other methods like this put name first, then id. switch for consistency

Target:
public final String toStringWithId() { return String.format("[%s][%s]", getName(), getId()); }
Source:
public static String normalizeBranchName(String name, boolean trim) { if (trim) { START name = END name.trim(); } return name.replaceAll("\\s+([_:-])\\s+", "$1") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll(":", "-") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("\\s+", "_") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("_{2,}", "_") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("^_", "") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("[^\\w-]", ""); //$NON-NLS-1$ //$NON-NLS-2$ } I know it's done in plenty of other places in the code base, but I would prefer not to use parameter assignment.

Target:
public static String normalizeBranchName(String name, boolean trim) { String result = name; if (trim) { result = name.trim(); } return result.replaceAll("\\s+([_:-])\\s+", "$1") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll(":", "-") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("\\s+", "_") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("_{2,}", "_") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("^_", "") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("[^\\w-]", ""); //$NON-NLS-1$ //$NON-NLS-2$ }
Source:
public void removePage(int pageIndex) { START if (0 > pageIndex || pageIndex >= getChildren().size()) { END getChildren().remove(pageIndex); } } Recheck the condition, it should be 0 <= pageIndex && pageIndex < getChildren().size()

Target:
public void removePage(int pageIndex) { if (0 <= pageIndex && pageIndex < getChildren().size()) { getChildren().remove(pageIndex); } }
Source:
protected void processDescriptionPropertiesRecursively(SIRIUS processedDescription, SIRIUS originalDescription, TransformationCache cache) { SIRIUS currentDescription = originalDescription; while (currentDescription != null) { START for (EStructuralFeature feature : currentDescription.eClass().getEAllStructuralFeatures()) { this.processDescriptionFeature(feature, processedDescription, currentDescription, cache); } END currentDescription = getParentOf(currentDescription); } } java8-isation [forEach]

Target:
protected void processDescriptionPropertiesRecursively(SIRIUS processedDescription, SIRIUS originalDescription, TransformationCache cache) { Optional<SIRIUS> currentDescription = Optional.of(originalDescription); while (currentDescription.isPresent()) { for (EStructuralFeature feature : currentDescription.get().eClass().getEAllStructuralFeatures()) { this.processDescriptionFeature(feature, processedDescription, currentDescription.get(), cache); } currentDescription = this.getParentOf(currentDescription.get()); } }
Source:
protected void updateProtocols() { protocols = new UniqueEList<>(); if (trigger != null) { for (Port port : trigger.getPorts()) { UMLRTPort facade = START UMLRTPort.getInstance(port); END UMLRTProtocol protocol = facade.getType(); if (protocol != null) { protocols.add(protocol); } } } } This can return null if the port is not a valid UML-RT port (in particular, if it is missing its RTPort stereotype application for some reason).

Target:
protected void updateProtocols() { protocols = new UniqueEList<>(); if (trigger != null) { for (Port port : trigger.getPorts()) { UMLRTPort facade = UMLRTPort.getInstance(port); if (facade != null) { UMLRTProtocol protocol = facade.getType(); if (protocol != null) { protocols.add(protocol); } } } } }
Source:
public void run(IAction action) { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView( RepositoryUi.ID_VIEW_REPOSITORIES); } catch (PartInitException e) { StatusHandler .log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Can not show Team Repository View", e)); //$NON-NLS-1$ START e.printStackTrace(); END } } We should never printStackTrace. The log will have the stack trace.

Target:
public void run(IAction action) { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView( RepositoryUi.ID_VIEW_REPOSITORIES); } catch (PartInitException e) { StatusHandler .log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Can not show Team Repository View", e)); //$NON-NLS-1$ } }
Source:
START static int getRefreshIndexInterval() { END return 1000 * getDefault().getPreferenceStore() .getInt(UIPreferences.REFESH_INDEX_INTERVAL); } private

Target:
private static int getRefreshIndexInterval() { return 1000 * getDefault().getPreferenceStore() .getInt(UIPreferences.REFESH_INDEX_INTERVAL); }
Source:
private static IStatistics<@NonNull BasicSegment> getDescriptiveStatistics(ISeries series) { double[] ySeries = series.getYSeries(); assertNotNull(ySeries); IStatistics<@NonNull BasicSegment> stats = new Statistics<>(s -> s.getLength()); for (double item : ySeries) { START stats.update(new BasicSegment(0, (long) (item - 1.0))); END } return stats; } Why not IStatistics<Long> ?

Target:
private static IStatistics<@NonNull Long> getDescriptiveStatistics(ISeries series) { double[] ySeries = series.getYSeries(); assertNotNull(ySeries); IStatistics<@NonNull Long> stats = new Statistics<>(); for (double item : ySeries) { stats.update((long) (item - 1.0)); } return stats; }
Source:
public Collection<EObject> getInverseReferences(final String featureName) { Preconditions.checkNotNull(featureName); return getInverseReferences(new Predicate<EStructuralFeature.Setting>() { @Override public boolean apply(Setting input) { return input != null START && input.getEStructuralFeature() != null ? featureName.equals(input.getEStructuralFeature().getName()) END : false; } }); } && input.getESF() != null && featureName.equals(input.getEFS().geName()

Target:
public Collection<EObject> getInverseReferences(final String featureName) { Preconditions.checkNotNull(featureName); return getInverseReferences(new Predicate<EStructuralFeature.Setting>() { @Override public boolean apply(Setting input) { return input != null && input.getEStructuralFeature() != null && featureName.equals(input.getEStructuralFeature().getName()); } }); }
Source:
START static void rotateProc(long /*int*/ gesture, double angle, double angle_delta, long/*int*/ user_data) { END if (OS.gtk_gesture_is_recognized(gesture)) { // returning delta is off by two decimal points double delta = OS.gtk_gesture_rotate_get_angle_delta(gesture)*100; Control control = getControl(user_data); /* TODO: X and Y positions are not retrieved yet */ control.sendGestureEvent(0,SWT.GESTURE_ROTATE,0,0,delta); } } space between long/*int*/ is critical for the replace task.

Target:
static void rotateProc(long /*int*/ gesture, double angle, double angle_delta, long/*int*/ user_data) { if (OS.gtk_gesture_is_recognized(gesture)) { /* * Returning delta is off by two decimal points and is returning negative numbers on * counter clockwise rotations from GTK. From the java doc of GestureEvent.rotation, * we have to invert the rotation number so that positive/negative numbers are returned * correctly (inversed). */ double delta = -(OS.gtk_gesture_rotate_get_angle_delta(gesture)*100); Control control = getControl(user_data); /* TODO: X and Y positions are not retrieved yet */ control.sendGestureEvent(0,SWT.GESTURE_ROTATE,0,0,delta); } }
Source:
public Object getParent(Object element) { if (element instanceof IWorkingSet && element != workingSetRoot) return workingSetRoot; Object res = parents.get(element); if (res != null) { return res; } if START (unassignedProjects.contains(res)) END { return OTHERS_WORKING_SET; } return null; } res is null here. Do we really expect that unassignedProjects contains null?

Target:
public Object getParent(Object element) { if (element instanceof IWorkingSet && element != workingSetRoot) return workingSetRoot; Object res = parents.get(element); if (res != null) { return res; } if (unassignedProjects.contains(element)) { return OTHERS_WORKING_SET; } return null; }
Source:
private void assertIsLegalIndex(final int index) { int totalCount = itemCount(); START Assert.isTrue(index < totalCount && index > 0, java.text.MessageFormat.format( END "The index ({0}) is more than the number of items ({1}) in the list.", index, totalCount)); //$NON-NLS-1$ } This makes it illegal to select index 0... should be >= 0

Target:
private void assertIsLegalIndex(final int index) { int totalCount = itemCount(); Assert.isTrue(index < totalCount && index >= 0, java.text.MessageFormat.format( "The index ({0}) is more than the number of items ({1}) in the list.", index, totalCount)); //$NON-NLS-1$ }
Source:
protected void notifySelect() { notify(SWT.MouseEnter); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.MouseMove); notify(SWT.MouseDown); notify(SWT.Selection); START notify(SWT.MouseUp); END notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); } I think we should remove the following events

Target:
protected void notifySelect() { notifySelect(true); }
Source:
private IRegisterGroupDescriptor createGroupDescriptor(final String groupName, final IRegisterDescriptor[] iSelectedRegisters) { IRegisterGroupDescriptor groupDescriptor = new IRegisterGroupDescriptor() { @Override public boolean isEnabled() { return true; } @Override public String getName() { return groupName; } @Override public String getContainerId() { return null; // Not used START } END @Override public IRegisterDescriptor[] getChildren() throws CoreException { return iSelectedRegisters; } }; return groupDescriptor; } we can move this one as a default method in the actual interface, thanks to Java 8.

Target:
private IRegisterGroupDescriptor createGroupDescriptor(final String groupName, final IRegisterDescriptor[] iSelectedRegisters) { IRegisterGroupDescriptor groupDescriptor = new IRegisterGroupDescriptor() { @Override public boolean isEnabled() { return true; } @Override public String getName() { return groupName; } @Override public IRegisterDescriptor[] getChildren() throws CoreException { return iSelectedRegisters; } }; return groupDescriptor; }
Source:
public void doAfterTest() throws Exception { super.doAfterTest(); START if (fServicesTracker != null) fServicesTracker.dispose(); END } It's a recommended practice to enclose the statement after the condition in curly brackets

Target:
public void doAfterTest() throws Exception { super.doAfterTest(); if (fServicesTracker != null) { fServicesTracker.dispose(); } }
Source:
private boolean isOrphan(File file) { String fileName = file.getName(); return fileName.startsWith("pack") && //$NON-NLS-1$ (fileName.endsWith(PackExt.BITMAP_INDEX.getExtension()) || fileName.endsWith(PackExt.INDEX.getExtension())) && !new File(file.getParentFile(), START fileName.substring(0, fileName.lastIndexOf(".") + 1) //$NON-NLS-1$ END + PackExt.PACK.getExtension()).exists(); } What happens when we have a file named "pack-1234idx" in that directory. No '.' but ending in a well known extension. Such files would be deleted, or?

Target:
private boolean isOrphan(File file) { String fileName = file.getName(); return fileName.startsWith("pack") && //$NON-NLS-1$ (fileName.endsWith("." + PackExt.BITMAP_INDEX.getExtension()) //$NON-NLS-1$ || fileName .endsWith("." + PackExt.INDEX.getExtension())) //$NON-NLS-1$ && !new File(file.getParentFile(), fileName.substring(0, fileName.lastIndexOf(".") + 1) //$NON-NLS-1$ + PackExt.PACK.getExtension()).exists(); }
Source:
public boolean canStart(String line, int lineOffset) { if (lineOffset == 0) { Matcher m = pattern.matcher(line); if (m.matches()) { START matcher = m; END return true; } } matcher = null; return false; } consider saving the value of group 1 and group 2 here rather than the whole matcher

Target:
public boolean canStart(String line, int lineOffset) { if (lineOffset == 0) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { key = matcher.group(1); value = matcher.group(2); return true; } } key = null; value = null; return false; }
Source:
protected boolean isLocationAllowed(Rectangle newBounds, Rectangle parentBounds, GraphicalEditPart containerEditpart) { boolean allowed = false; if (null != containerEditpart) { Rectangle absoluteBounds = newBounds.getTranslated(parentBounds.getLocation()); if START (null != containerEditpart && END containerEditpart.getFigure().getBounds().contains(absoluteBounds)) { allowed = true; } } return allowed; } "null != containerEditpart" is already checked in the outer if

Target:
protected boolean isLocationAllowed(Rectangle newBounds, Rectangle parentBounds, GraphicalEditPart containerEditpart) { boolean allowed = false; if (null != containerEditpart) { Rectangle absoluteBounds = newBounds.getTranslated(parentBounds.getLocation()); if (containerEditpart.getFigure().getBounds().contains(absoluteBounds)) { allowed = true; } } return allowed; }
Source:
START public ObjectId END insert(int type, byte[] data, int off, int len, boolean createDuplicate) throws IOException { ObjectId id = idFor(type, data, off, len); if (!createDuplicate && db.has(id)) { return id; } else { File tmp = toTemp(type, data, off, len); return insertOneObject(tmp, id, createDuplicate); } } Does this need to be public? I think the only caller is in the same package.

Target:
ObjectId insert(int type, byte[] data, int off, int len, boolean createDuplicate) throws IOException { ObjectId id = idFor(type, data, off, len); if (!createDuplicate && db.has(id)) { return id; } else { File tmp = toTemp(type, data, off, len); return insertOneObject(tmp, id, createDuplicate); } }
Source:
START protected String getJavaCallDeclaration() { END return "if (!window.callJava) {\n" + " window.callJava = function callJava(index, token, args) {\n" + " return external.callJava(index,token,args);\n" + " }\n" + "};\n"; } You can not expose such thing as an API. There is now way one can open at that level and prevent crashes/deadlocks.

Target:
String getJavaCallDeclaration() { return "if (!window.callJava) {\n" + " window.callJava = function callJava(index, token, args) {\n" + " return external.callJava(index,token,args);\n" + " }\n" + "};\n"; }
Source:
public void focusLost(FocusEvent e) { if (this.handleFocusChanges) { if (!e.widget.isDisposed() && !commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control START && !e.widget.isDisposed()) { END ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } } minor thing ... the second check is not necessary anymore

Target:
public void focusLost(FocusEvent e) { if (this.handleFocusChanges) { if (!e.widget.isDisposed() && !commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control) { ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } }
Source:
public void focusLost(FocusEvent e) { START if (this.handleFocusChanges && !e.widget.isDisposed()) { END if (!commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control && !e.widget.isDisposed()) { ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } } would it not make more sense to move this check one line down? the commit() call could produce such an error, so that one should be guarded. The else condition could be matched. Of course it needs to be the first check

Target:
public void focusLost(FocusEvent e) { if (this.handleFocusChanges) { if (!e.widget.isDisposed() && !commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control && !e.widget.isDisposed()) { ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } }
Source:
START public boolean supportsRefreshing() { END for (AbstractTaskEditorPart part : subParts) { if (!part.supportsRefreshing()) { return false; } } return true; } Should return false if !super.supportsRefreshing()

Target:
public boolean supportsRefreshing() { if (!super.supportsRefreshing()) { return false; } for (AbstractTaskEditorPart part : subParts) { if (!part.supportsRefreshing()) { return false; } } return true; }
Source:
START public boolean hasIncomingChanges() { END for (AbstractTaskEditorPart part : subParts) { if (part.hasIncomingChanges()) { return true; } } return false; } Should return true if super.hasIncomingChanges (the parent section may contain attribute editors directly, e.g. the bugzilla attribute section has attribute editors and also a subsection called Flags).

Target:
public boolean hasIncomingChanges() { if (super.hasIncomingChanges()) { return true; } for (AbstractTaskEditorPart part : subParts) { if (part.hasIncomingChanges()) { return true; } } return false; }
Source:
public Object[] getElements(Object inputElement) { if (inputElement instanceof IBuild) { return getChildren(inputElement); } START if (inputElement instanceof String) { END return new Object[] { inputElement }; } return NO_ELEMENTS; } remore this case

Target:
public Object[] getElements(Object inputElement) { if (inputElement instanceof IBuild) { return getChildren(inputElement); } return NO_ELEMENTS; }
Source:
public Object getParent(Object element) { if (element instanceof IBuild) { return ((IBuild) element).getParent(); } START return NO_ELEMENTS; END } return null

Target:
public Object getParent(Object element) { if (element instanceof IBuild) { return ((IBuild) element).getParent(); } return null; }
Source:
public void testCall() { GetDiffCommand diff = new GetDiffCommand(fGerrit.getRepository(), change_id, commit_id, "/COMMIT_MSG"); try { DiffInfo di = diff.call(); START System.out.println(di); END } catch (EGerritException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Just a system.out, no validation here

Target:
public void testCall() throws EGerritException { GetDiffCommand diff = new GetDiffCommand(fGerrit.getRepository(), change_id, commit_id, "/COMMIT_MSG", 2); diff.call(); }
Source:
public void setUp() throws IOException { DfsRepositoryDescription desc = new DfsRepositoryDescription("test"); git = new TestRepository<>(new InMemoryRepository(desc)); repo = git.getRepository(); odb = repo.getObjectDatabase(); ticks = 0; mockSystemReader = new MockSystemReader() { @Override public long getCurrentTime() { // move forward time with every call START return super.getCurrentTime() + ticks++; END } }; SystemReader.setInstance(mockSystemReader); } You can use tick() for this: tick(1); return super.getCurrentTime(); Most TestRepository operations call tick on its mockSystemReader, which is a little more resilient (since it makes behavior change less based on the number of times getCurrentTime gets called). Can the TestRepository use this as their MockSystemReader? Repository db = new InMemoryRepository(desc); git = new TestRepository<>(db, new RevWalk(db), mockSystemReader);

Target:
public void setUp() throws IOException { DfsRepositoryDescription desc = new DfsRepositoryDescription("test"); git = new TestRepository<>(new InMemoryRepository(desc)); repo = git.getRepository(); odb = repo.getObjectDatabase(); mockSystemReader = new MockSystemReader(); SystemReader.setInstance(mockSystemReader); }
Source:
public boolean containsAll(Collection<?> c) { for (Object START name : END c) if (!wrappedSet.contains(IdentityWrapper.wrap(name))) return false; return true; } rename 'element'

Target:
public boolean containsAll(Collection<?> c) { for (Object element : c) if (!wrappedSet.contains(IdentityWrapper.wrap(element))) return false; return true; }
Source:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (Object START name : END c) changed |= remove(name); return changed; } rename 'element'

Target:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (Object element : c) changed |= remove(element); return changed; }
Source:
private void sleepGroup(GroupInfo group, JobInfo info) { Object[] listenersArray = listeners.getListeners(); START for (Object element : listenersArray) { END IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (isNeverDisplaying(info.getJob(), listener.showsDebug())) continue; if (listener.showsDebug() || group.isActive()) listener.refreshGroup(group); else listener.removeGroup(group); } } inline listeners.getListeners()

Target:
private void sleepGroup(GroupInfo group, JobInfo info) { for (Object element : listeners.getListeners()) { IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (isNeverDisplaying(info.getJob(), listener.showsDebug())) continue; if (listener.showsDebug() || group.isActive()) listener.refreshGroup(group); else listener.removeGroup(group); } }
Source:
public void refreshGroup(GroupInfo info) { Object[] listenersArray = listeners.getListeners(); START for (Object element : listenersArray) { END ((IJobProgressManagerListener)element).refreshGroup(info); } } inline listeners.getListeners()

Target:
public void refreshGroup(GroupInfo info) { for (Object element : listeners.getListeners()) { ((IJobProgressManagerListener)element).refreshGroup(info); } }
Source:
public void refreshAll() { pruneStaleJobs(); Object[] listenersArray = listeners.getListeners(); START for (Object element : listenersArray) { END ((IJobProgressManagerListener)element).refreshAll(); } } inline listeners.getListeners()

Target:
public void refreshAll() { pruneStaleJobs(); for (Object element : listeners.getListeners()) { ((IJobProgressManagerListener)element).refreshAll(); } }
Source:
public void removeJobInfo(JobInfo info) { Job job = info.getJob(); jobs.remove(job); runnableMonitors.remove(job); Object[] listenersArray = listeners.getListeners(); START for (Object element : listenersArray) { END IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (!isCurrentDisplaying(info.getJob(), listener.showsDebug())) { listener.removeJob(info); } } } inline listeners.getListeners()

Target:
public void removeJobInfo(JobInfo info) { Job job = info.getJob(); jobs.remove(job); runnableMonitors.remove(job); for (Object element : listeners.getListeners()) { IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (!isCurrentDisplaying(info.getJob(), listener.showsDebug())) { listener.removeJob(info); } } }