auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public TagOperation(Repository repo, TagBuilder tag, boolean shouldMoveTag) { START this.tag = tag; this.repo = repo; this.shouldMoveTag = shouldMoveTag; this.annotated = true; END } while that pattern can be found quite often in the egit sources, it's code duplication for me. I'm a big fan of just one implemented constructor and constructor chaining. Call the other constructor from this one please.

Target:
public TagOperation(Repository repo, TagBuilder tag, boolean shouldMoveTag) { this(repo, tag, shouldMoveTag, true); }
Source:
public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 2); progress.setTaskName(NLS.bind(CoreText.TagOperation_performingTagging, tag.getTag())); ObjectId tagId = START !annotated ? tag.getObjectId() : updateTagObject(); END progress.worked(1); updateRepo(tagId); progress.worked(1); } please invert the conditional operator to get rid of the negation

Target:
public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 2); progress.setTaskName(NLS.bind(CoreText.TagOperation_performingTagging, tag.getTag())); ObjectId tagId = annotated ? updateTagObject() : tag.getObjectId(); progress.worked(1); updateRepo(tagId); progress.worked(1); }
Source:
public int getInt(String key) throws NumberFormatException { String setting = items.get(key); if (setting == null) { // Integer.valueOf(null) will throw a NumberFormatException and // meet our spec, but this message is clearer. throw new NumberFormatException( "There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$ } START return Integer.valueOf(setting).intValue(); END } Not an exception

Target:
public int getInt(String key) throws NumberFormatException { String setting = items.get(key); if (setting == null) { // Integer.valueOf(null) will throw a NumberFormatException and // meet our spec, but this message is clearer. throw new NumberFormatException( "There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$ } return Integer.parseInt(setting); }
Source:
private static void runInCurrentThread(IRunnableWithProgress runnable, IProgressMonitor progressMonitor) throws InterruptedException, InvocationTargetException { try { if (runnable != null) { runnable.run(progressMonitor); } } catch (InvocationTargetException | InterruptedException | ThreadDeath e) { // Make sure to propagate ThreadDeath, or threads will never fully // terminate. throw e; START }catch (OperationCanceledException e) { END throw new InterruptedException(); } catch (RuntimeException | Error e) { throw new InvocationTargetException(e); } } space before catch

Target:
private static void runInCurrentThread(IRunnableWithProgress runnable, IProgressMonitor progressMonitor) throws InterruptedException, InvocationTargetException { try { if (runnable != null) { runnable.run(progressMonitor); } } catch (InvocationTargetException | InterruptedException e) { throw e; } catch (OperationCanceledException e) { throw new InterruptedException(); } catch (ThreadDeath e) { // Make sure to propagate ThreadDeath, or threads will never fully // terminate. throw e; } catch (RuntimeException | Error e) { throw new InvocationTargetException(e); } }
Source:
public static boolean isTarFile(String fileName) { if (fileName.length() == 0) { return false; } TarFile tarFile = null; try { tarFile = new TarFile(fileName); START } catch (TarException | IOException tarException) { END return false; } finally { if (tarFile != null) { try { tarFile.close(); } catch (IOException e) { // ignore } } } return true; } rename exception

Target:
public static boolean isTarFile(String fileName) { if (fileName.length() == 0) { return false; } TarFile tarFile = null; try { tarFile = new TarFile(fileName); } catch (TarException | IOException exception) { return false; } finally { if (tarFile != null) { try { tarFile.close(); } catch (IOException e) { // ignore } } } return true; }
Source:
public Expression create(ExpressionConverter converter, IConfigurationElement element) { String name = element.getName(); START if (name==null) END return null; switch (name) { case HasFileExpression.TAG: return new HasFileExpression(element); case HasFileRecursivelyExpression.TAG: return new HasFileRecursivelyExpression(element); case HasFileWithSuffixRecursivelyExpression.TAG: return new HasFileWithSuffixRecursivelyExpression(element); case HasFolderExpression.TAG: return new HasFolderExpression(element); default: break; } return null; } Use for blocks

Target:
public Expression create(ExpressionConverter converter, IConfigurationElement element) { String name = element.getName(); if (name == null) { return null; } switch (name) { case HasFileExpression.TAG: return new HasFileExpression(element); case HasFileRecursivelyExpression.TAG: return new HasFileRecursivelyExpression(element); case HasFileWithSuffixRecursivelyExpression.TAG: return new HasFileWithSuffixRecursivelyExpression(element); case HasFolderExpression.TAG: return new HasFolderExpression(element); default: break; } return null; }
Source:
private void copyFiles(File src, File dest) throws IOException { START FileOutputStream fos; END try (FileInputStream fis = new FileInputStream(src)) { fos = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } fos.close(); } fos can be inside try ()

Target:
private void copyFiles(File src, File dest) throws IOException { try (FileOutputStream fos = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src)) { byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } }
Source:
public static int positionToDragCursor(int swtPositionConstant) { switch (swtPositionConstant) { case SWT.LEFT: return LEFT; case SWT.RIGHT: return RIGHT; case SWT.TOP: return TOP; case SWT.BOTTOM: return BOTTOM; case SWT.CENTER: return START CENTER; END } return INVALID; } and default ?

Target:
public static int positionToDragCursor(int swtPositionConstant) { switch (swtPositionConstant) { case SWT.LEFT: return LEFT; case SWT.RIGHT: return RIGHT; case SWT.TOP: return TOP; case SWT.BOTTOM: return BOTTOM; case SWT.CENTER: return CENTER; default: return INVALID; } }
Source:
public void refresh() { START fCategoryViewer.setInput(fModel); END super.refresh(); } Is this necessary? It causes the tree to collapse.

Target:
public void refresh() { fCategoryViewer.refresh(); super.refresh(); }
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (obj instanceof ReferenceBindingSetWrapper) { ReferenceBindingSetWrapper other = (ReferenceBindingSetWrapper) obj; return START identityEqual(this.referenceBinding, END other.referenceBinding); } return false; } I see that the only reason for this is the compiler error created: The uninterned types ReferenceBinding and ReferenceBinding should not be compared using ==/!= operators. See discussion here https://bugs.eclipse.org/bugs/show_bug.cgi?id=417803 Not sure if it is safe what we are doing here.

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ReferenceBindingSetWrapper) { ReferenceBindingSetWrapper other = (ReferenceBindingSetWrapper) obj; return identityEqual(this.referenceBinding, other.referenceBinding); } return false; }
Source:
private boolean contains(CodeSource codeSource) { if (codeSource == null) return false; URL START url = END codeSource.getLocation(); if (url == null) return false; // Check to see if this URL is in our set of URLs to give AllPermissions to. for (URL url1 : urls) { // We do simple equals test here because we assume the URLs will be the same objects. if (url1 == url) { return true; } } return false; } rename this url variable to location and then simply use the variable name url in the foreach loop below

Target:
private boolean contains(CodeSource codeSource) { if (codeSource == null) return false; URL location = codeSource.getLocation(); if (location == null) return false; // Check to see if this URL is in our set of URLs to give AllPermissions to. for (URL url : urls) { // We do simple equals test here because we assume the URLs will be the same objects. if (url == location) { return true; } } return false; }
Source:
private void writeList(DataOutputStream out, String[] list) throws IOException { if (list == null) { out.writeInt(0); } else { out.writeInt(list.length); for (String START list1 : END list) { writeStringOrNull(list1, out); } } } rename to s or string

Target:
private void writeList(DataOutputStream out, String[] list) throws IOException { if (list == null) { out.writeInt(0); } else { out.writeInt(list.length); for (String s : list) { writeStringOrNull(s, out); } } }
Source:
public String toString() { START StringBuffer buffer END = new StringBuffer(); for (int i = 0; i < this.size; i++) { buffer.append(CharOperation.toString(this.elements[i])).append("\n"); //$NON-NLS-1$ } return buffer.toString(); } If Lars would see it, he would cry. How could you even think about using StringBuffer in 21 century? (I know, copy/paste).

Target:
public String toString() { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < this.size; i++) { buffer.append(CharOperation.toString(this.elements[i])).append("\n"); //$NON-NLS-1$ } return buffer.toString(); }
Source:
public Position START cursorPosition() END { return syncExec(new Result<Position>() { @Override public Position run() { widget.setFocus(); int offset = widget.getSelectionRange().x; int line = widget.getContent().getLineAtOffset(offset); int offsetAtLine = widget.getContent().getOffsetAtLine(line); int column = offset - offsetAtLine; return new Position(line, column); } }); } I think that using the start of selection was just wrong. I would have no problem to use the caret position for this one too as part of the bug fix. Then the implementation could just be to call cursorPosition(false).

Target:
public Position cursorPosition() { return cursorPosition(false); }
Source:
protected static ILaunchConfiguration findLaunchConfiguration(String name) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfiguration[] launchConfigurations = launchManager.getLaunchConfigurations(); for (ILaunchConfiguration START lConf : END launchConfigurations) { if (lConf.getName().equals(name)) { return lConf; } } return null; } rename to conf/config

Target:
protected static ILaunchConfiguration findLaunchConfiguration(String name) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfiguration[] launchConfigurations = launchManager.getLaunchConfigurations(); for (ILaunchConfiguration config : launchConfigurations) { if (config.getName().equals(name)) { return config; } } return null; }
Source:
public Color getForeground(Object element, int columnIndex) { String legendItemText = (String) element; START if (legendItemText.equals("Population > 1,000,000") | legendItemText.equals("Population > 50,000")) { END return Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); } return null; } I guess || should be used here

Target:
public Color getForeground(Object element, int columnIndex) { String legendItemText = (String) element; if (legendItemText.equals("Population > 1,000,000") || legendItemText.equals("Population > 50,000")) { return Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); } return null; }
Source:
public void register() { Chart chart = getChart(); START chart.getPlotArea().addMouseTrackListener(this); END chart.getPlotArea().addMouseMoveListener(this); chart.getPlotArea().addPaintListener(this); fTooltipHandler.activateHoverHelp(chart.getPlotArea()); } remove

Target:
public void register() { Chart chart = getChart(); chart.getPlotArea().addMouseMoveListener(this); chart.getPlotArea().addPaintListener(this); fTooltipHandler.activateHoverHelp(chart.getPlotArea()); }
Source:
public void deregister() { Chart chart = getChart(); if ((chart != null) && !chart.isDisposed()) { START chart.getPlotArea().removeMouseTrackListener(this); END chart.getPlotArea().removeMouseMoveListener(this); chart.getPlotArea().removePaintListener(this); fTooltipHandler.deactivateHoverHelp(chart.getPlotArea()); } } remove

Target:
public void deregister() { Chart chart = getChart(); if ((chart != null) && !chart.isDisposed()) { chart.getPlotArea().removeMouseMoveListener(this); chart.getPlotArea().removePaintListener(this); fTooltipHandler.deactivateHoverHelp(chart.getPlotArea()); } }
Source:
public Saveable[] getSaveables() { if (!hasSaveablesProvider()) { IEditorPart saveablePart = getSite().getPage().getActiveEditor(); START return saveablePart instanceof ISaveablesSource ? ((ISaveablesSource) saveablePart).getSaveables() END : new Saveable[] { new DefaultSaveable(saveablePart) }; } return super.getSaveables(); } Case of null should return an empty array.

Target:
public Saveable[] getSaveables() { if (!hasSaveablesProvider()) { IEditorPart saveablePart = getSite().getPage().getActiveEditor(); return saveablePart != null ? saveablePart instanceof ISaveablesSource ? ((ISaveablesSource) saveablePart).getSaveables() : new Saveable[] { new DefaultSaveable(saveablePart) } : new Saveable[] {}; } return super.getSaveables(); }
Source:
private URI resolve(IResourceLocator locator) { String attributeDataPath = getAttributeDataPath(); START StringBuilder builder = new StringBuilder(attributeDataPath); END String rawPath = locator.getRawPath(); builder.append(rawPath); String pathname = builder.toString(); // Default db/attr to workspace if this is developer's runtime if (pathname.contains("workspace")) { pathname = pathname.replaceAll("\\\\", "/"); pathname = pathname.replaceFirst("file:", ""); } File file = new File(pathname); return file.toURI(); } lines 82 to 86 collapse to: String pathname = attributeDataPath + locator.getRawPath();

Target:
private URI resolve(IResourceLocator locator) { String attributeDataPath = getAttributeDataPath(); String rawPath = locator.getRawPath(); String pathname = attributeDataPath + rawPath; // Default db/attr to workspace if this is developer's runtime if (pathname.contains("workspace")) { pathname = pathname.replaceAll("\\\\", "/"); pathname = pathname.replaceFirst("file:", ""); } File file = new File(pathname); return file.toURI(); }
Source:
public void setImage (Image image) { checkWidget (); if ((style & SWT.SEPARATOR) != 0) return; if (image != null && image.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT); this.image = image; START updateStyleBits(false); END OS.InvalidateRect (handle, null, true); } With the proposed change: updateStyleBits(image == null)

Target:
public void setImage (Image image) { checkWidget (); if ((style & SWT.SEPARATOR) != 0) return; if (image != null && image.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT); this.image = image; updateStyleBits(image == null); OS.InvalidateRect (handle, null, true); }
Source:
START public AttributeEntryModel(long id, long parentId, String name, long start, long end, int quark) { END super(id, parentId, name, start, end, true); fQuark = quark; } Since you use builders and you may not want to have external code create new entries, just use the content, you can make the constructor private or protected.

Target:
protected AttributeEntryModel(long id, long parentId, String name, long start, long end, int quark) { super(id, parentId, name, start, end, true); fQuark = quark; }
Source:
public void setVisible(final boolean visible) { super.setVisible(visible); fIsVisible = visible; if (visible) { START getContainer().getShell().getDisplay().asyncExec(() -> updateViewer()); END } else { getElementViewer().setInput(null); } } can this be a method reference?

Target:
public void setVisible(final boolean visible) { super.setVisible(visible); fIsVisible = visible; if (visible) { getContainer().getShell().getDisplay().asyncExec(this::updateViewer); } else { getElementViewer().setInput(null); } }
Source:
public void setUp() throws Exception { IEclipseContext context = E4Application.createDefaultContext(); START modelService = context.get(EModelService.class); END editor = modelService.createModelElement(MPart.class); editor.setElementId(DUMMY_EDITOR_ID); editor.getTags().add("Editor"); } I think we don't need this, because the EModelService is injected via WorkbenchContextRule

Target:
public void setUp() throws Exception { editor = modelService.createModelElement(MPart.class); editor.setElementId(DUMMY_EDITOR_ID); editor.getTags().add("Editor"); }
Source:
private String getGitPath(IFileRevision revision) { if (revision instanceof CommitFileRevision) { return ((CommitFileRevision) revision).getGitPath(); } IResourceVariant variant = START Adapters.adapt((revision), END IResourceVariant.class); if (variant instanceof GitRemoteResource) { return ((GitRemoteResource) variant).getPath(); } return null; } Extra parentheses could go away, too.

Target:
private String getGitPath(IFileRevision revision) { if (revision instanceof CommitFileRevision) { return ((CommitFileRevision) revision).getGitPath(); } IResourceVariant variant = Adapters.adapt(revision, IResourceVariant.class); if (variant instanceof GitRemoteResource) { return ((GitRemoteResource) variant).getPath(); } return null; }
Source:
START private boolean sameCommit(RevCommit a, RevCommit b) { END // Reference comparison is intentional; BlameGenerator uses a single // RevWalk which caches the RevCommit objects, and if a given commit // is cached the RevWalk returns the same instance. return a == b; } this method can be made static

Target:
private static boolean sameCommit(RevCommit a, RevCommit b) { // Reference comparison is intentional; BlameGenerator uses a single // RevWalk which caches the RevCommit objects, and if a given commit // is cached the RevWalk returns the same instance. return a == b; }
Source:
private void setListForWhiteSelection(Object treeElement) { List listItemsChecked = new ArrayList(); START java.util.Collections.addAll(listItemsChecked, listContentProvider.getElements(treeElement)); END checkedStateStore.put(treeElement, listItemsChecked); } Maybe directly add to contructor here? List listItemsChecked = new ArrayList(Arrays.asList(listContentProvider.getElements(treeElement)));

Target:
private void setListForWhiteSelection(Object treeElement) { List listItemsChecked = new ArrayList(Arrays.asList(listContentProvider.getElements(treeElement))); checkedStateStore.put(treeElement, listItemsChecked); }
Source:
public IterateExpression(Element element) throws CoreException { String opValue= element.getAttribute(ATT_OPERATOR); initializeOperatorValue(opValue.isEmpty() ? START opValue : END null); String ifEmpty= element.getAttribute(ATT_IF_EMPTY); initializeEmptyResultValue(ifEmpty.isEmpty() ? null : ifEmpty); } bug

Target:
public IterateExpression(Element element) throws CoreException { String opValue= element.getAttribute(ATT_OPERATOR); initializeOperatorValue(opValue.isEmpty() ? null : opValue); String ifEmpty= element.getAttribute(ATT_IF_EMPTY); initializeEmptyResultValue(ifEmpty.isEmpty() ? null : ifEmpty); }
Source:
public void initializeDefaultPreferences() { IEclipsePreferences node = DefaultScope.INSTANCE .getNode(CodanCorePlugin.getDefault().getBundle().getSymbolicName()); START node.putBoolean(PreferenceConstants.P_RUN_ON_BUILD, true); END node.putBoolean(PreferenceConstants.P_RUN_IN_EDITOR, true); node.putBoolean(PreferenceConstants.P_USE_PARENT, true); } Setting this to true initially won't have any effect because the codan builder is added when the property changes, see BuildPropertyPage. I'm also not sure we should impose such a big change in behavior.

Target:
public void initializeDefaultPreferences() { IEclipsePreferences node = DefaultScope.INSTANCE .getNode(CodanCorePlugin.getDefault().getBundle().getSymbolicName()); node.putBoolean(PreferenceConstants.P_RUN_ON_BUILD, false); node.putBoolean(PreferenceConstants.P_RUN_IN_EDITOR, true); node.putBoolean(PreferenceConstants.P_USE_PARENT, true); }
Source:
protected void setSelectionToWidget(ISelection selection, boolean reveal) { if (selection instanceof ITreeSelection) { ITreeSelection treeSelection = (ITreeSelection) selection; START setSelectionToWidget(new ArrayList<Object>(Arrays.asList(treeSelection.getPaths())), reveal); END } else { super.setSelectionToWidget(selection, reveal); } } this change does not seem to be needed it would create 2 lists, where just an array-to-list conversion is needed

Target:
protected void setSelectionToWidget(ISelection selection, boolean reveal) { if (selection instanceof ITreeSelection) { ITreeSelection treeSelection = (ITreeSelection) selection; setSelectionToWidget(Arrays.asList(treeSelection.getPaths()), reveal); } else { super.setSelectionToWidget(selection, reveal); } }
Source:
public void testBug548456_concurrentElementInfoAccess() throws Exception { int iterations = 20; int numberOfThreads = START 2; END for (int i = 0; i < iterations; ++i) { doTestBug548456_concurrentCallBinaryTypeExists(numberOfThreads); } } with 10 threads I can almost always reproduce the bug.

Target:
public void testBug548456_concurrentElementInfoAccess() throws Exception { int iterations = 20; int numberOfThreads = 10; for (int i = 0; i < iterations; ++i) { doTestBug548456_concurrentCallBinaryTypeExists(numberOfThreads); } }
Source:
private MethodInvocation createStandaloneJ7HashCall() { MethodInvocation j7Invoc= fAst.newMethodInvocation(); START for (IVariableBinding fField : fFields) { END j7Invoc.arguments().add(fAst.newSimpleName(fField.getName())); } j7Invoc.setExpression(getQualifiedName(JAVA_UTIL_OBJECTS)); j7Invoc.setName(fAst.newSimpleName(METHODNAME_HASH)); return j7Invoc; } rename to field

Target:
private MethodInvocation createStandaloneJ7HashCall() { MethodInvocation j7Invoc= fAst.newMethodInvocation(); for (IVariableBinding field : fFields) { j7Invoc.arguments().add(fAst.newSimpleName(field.getName())); } j7Invoc.setExpression(getQualifiedName(JAVA_UTIL_OBJECTS)); j7Invoc.setName(fAst.newSimpleName(METHODNAME_HASH)); return j7Invoc; }
Source:
private void delete(File file) { if (file.isDirectory()) { for (File START listFile : END file.listFiles()) { delete(listFile); } } file.delete(); } rename to f

Target:
private void delete(File file) { if (file.isDirectory()) { for (File f : file.listFiles()) { delete(f); } } file.delete(); }
Source:
private RefactoringStatus checkAbstractMembersInDestinationClasses(IMember[] membersToPushDown, IType[] destinationClassesForAbstract) throws JavaModelException { RefactoringStatus result= new RefactoringStatus(); IMember[] abstractMembersToPushDown= getAbstractMembers(membersToPushDown); for (IType START t : END destinationClassesForAbstract) { result.merge(MemberCheckUtil.checkMembersInDestinationType(abstractMembersToPushDown, t)); } return result; } rename to type

Target:
private RefactoringStatus checkAbstractMembersInDestinationClasses(IMember[] membersToPushDown, IType[] destinationClassesForAbstract) throws JavaModelException { RefactoringStatus result= new RefactoringStatus(); IMember[] abstractMembersToPushDown= getAbstractMembers(membersToPushDown); for (IType type : destinationClassesForAbstract) { result.merge(MemberCheckUtil.checkMembersInDestinationType(abstractMembersToPushDown, type)); } return result; }
Source:
private static void findFiles(IResource resource, List<IResource> files) throws CoreException { if (resource instanceof IFile) { files.add(resource); return; } if (resource instanceof IContainer) { for (IResource START resource1 : END ((IContainer) resource).members()) { findFiles(resource1, files); } } } rename to res

Target:
private static void findFiles(IResource resource, List<IResource> files) throws CoreException { if (resource instanceof IFile) { files.add(resource); return; } if (resource instanceof IContainer) { for (IResource res : ((IContainer) resource).members()) { findFiles(res, files); } } }
Source:
private static String getTracePath(String projectName, String traceName, Boolean isExperiment) { String separator = "/"; //$NON-NLS-1$ StringJoiner filePath = new StringJoiner(separator, separator, separator); filePath.add(projectName); String childrenName = isExperiment ? "Experiments" : "Traces"; //$NON-NLS-1$ //$NON-NLS-2$ filePath.add(childrenName); filePath.add(traceName); START return filePath.toString(); END } String.valueOf(filePath) is equivalent and nonNull, it will remove a warning

Target:
private static String getTracePath(String projectName, String traceName, Boolean isExperiment) { String separator = "/"; //$NON-NLS-1$ StringJoiner filePath = new StringJoiner(separator, separator, separator); filePath.add(projectName); String childrenName = isExperiment ? "Experiments" : "Traces"; //$NON-NLS-1$ //$NON-NLS-2$ filePath.add(childrenName); filePath.add(traceName); return String.valueOf(filePath); }
Source:
public int getMarks(TreeWalk walk) throws MissingObjectException, IncorrectObjectTypeException, IOException { int marks = 0; for (int index = 0; index < filters.length; index++) { TreeFilter filter = filters[index]; if (filter != null) { try { boolean marked = filter.include(walk); if (marked) START marks |= (int) (1L << index); END } catch (StopWalkException e) { // Don't check tree filter anymore, it will no longer // match filters[index] = null; } } } return marks; } Instead of casting can't we just omit the "L"?

Target:
public int getMarks(TreeWalk walk) throws MissingObjectException, IncorrectObjectTypeException, IOException { int marks = 0; for (int index = 0; index < filters.length; index++) { TreeFilter filter = filters[index]; if (filter != null) { try { boolean marked = filter.include(walk); if (marked) marks |= (1 << index); } catch (StopWalkException e) { // Don't check tree filter anymore, it will no longer // match filters[index] = null; } } } return marks; }
Source:
public boolean isDecorationReady(Object element, IDecorationContext context) { // the decoration is only reported as ready, if we are in the UI thread and if // the update job is running. // Because the update job is running in the UI thread, it can be the only caller // of this method if the flag isUpdateJobRunning is TRUE START if (isUpdateJobRunning.get()) { END return internalGetResult(element, context) != null; } // in all other cases, some other logic than the update job is asking and that // should always be answered with false - see Bug 417255 return false; } this is always called on the UI, so I would replace the threadlocal with a simple boolean

Target:
public boolean isDecorationReady(Object element, IDecorationContext context) { // the decoration is only reported as ready, if we are in the UI thread and if // the update job is running. // Because the update job is running in the UI thread, it can be the only caller // of this method if the flag isUpdateJobRunning is TRUE if (isUpdateJobRunning) { return internalGetResult(element, context) != null; } // in all other cases, some other logic than the update job is asking and that // should always be answered with false - see Bug 417255 return false; }
Source:
public void addStream(long id, File streamFile) throws CTFException { final File file = streamFile; if (file == null) { throw new CTFException("cannot create a stream with no file"); //$NON-NLS-1$ } START ICTFStream stream = fStreams.computeIfAbsent(id, k -> new CTFStream(this)); END if (stream instanceof CTFStream) { CTFStream ctfStream = (CTFStream) stream; ctfStream.addInput(new CTFStreamInput(stream, file)); } else { throw new CTFException("Stream does not support adding input"); //$NON-NLS-1$ } } method ref?

Target:
public void addStream(long id, File streamFile) throws CTFException { final File file = streamFile; if (file == null) { throw new CTFException("cannot create a stream with no file"); //$NON-NLS-1$ } ICTFStream stream = fStreams.computeIfAbsent(id, ctfStream -> new CTFStream(this)); if (stream instanceof CTFStream) { CTFStream ctfStream = (CTFStream) stream; ctfStream.addInput(new CTFStreamInput(stream, file)); } else { throw new CTFException("Stream does not support adding input"); //$NON-NLS-1$ } }
Source:
public StringFieldEditor(String name, String labelText, int width, int strategy, Composite parent) { START init(name, labelText); END widthInChars = width; setValidateStrategy(strategy); isValid = false; errorMessage = JFaceResources .getString("StringFieldEditor.errorMessage");//$NON-NLS-1$ createControl(parent); } I suggest you invoke `this(name, labelText, wight, 1, strategy, parent)` here.

Target:
public StringFieldEditor(String name, String labelText, int width, int strategy, Composite parent) { this(name, labelText, width, 1, strategy, parent); }
Source:
public static void touch(Path f) throws IOException { try (FileChannel fc = FileChannel.open(f, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC)) { Files.setLastModifiedTime(f, START FileTime.from(Instant.now())); END } } Now Andrey's question about clock sync between NFS and the machine this Java code runs on becomes relevant?

Target:
public static void touch(Path f) throws IOException { try (FileChannel fc = FileChannel.open(f, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC)) { // touch } Files.setLastModifiedTime(f, FileTime.from(Instant.now())); }
Source:
protected void doExecute() { if (representationDescriptor != null) { representationDescriptor.setName(newName); START representationDescriptor.setName(newName); END } } to remove. Same line as above :)

Target:
protected void doExecute() { if (representationDescriptor != null) { representationDescriptor.setName(newName); } }
Source:
private static List<IProject> getSelectedProjects(ISelection selection) { List<IProject> projectSelection = new ArrayList<>(); if (selection instanceof IStructuredSelection) { for (Object element : ((StructuredSelection) selection).toList()) { if START (element instanceof AutomationSystem) { END projectSelection.add(((AutomationSystem) element).getProject()); } } } return projectSelection; } same question here: is this limitation to AutomationSystem wanted nad/or necessary? What if a user has also other types of projects open, e.g. as part of a research prototype?

Target:
private static List<IProject> getSelectedProjects(ISelection selection) { List<IProject> projectSelection = new ArrayList<>(); if (selection instanceof IStructuredSelection) { for (Object element : ((StructuredSelection) selection).toList()) { if (element instanceof AutomationSystem) { projectSelection.add(((AutomationSystem) element).getProject()); } else if (element instanceof IProject) { projectSelection.add((IProject) element); } } } return projectSelection; }
Source:
public static boolean openRenameWizard(String newName, IStructuredSelection structuredSelection) { Map<String, Object> commandParameters = Collections.emptyMap(); START commandParameters.put(LTK_RENAME_COMMAND_NEWNAME_PARAMETER_KEY, newName); END return runCommand(LTK_RENAME_ID, structuredSelection, commandParameters); } This is not legal: collections.emptyMap returns a non-modifiable empty map (and always the very same empty map). Invoking .put on it should fail. For maps with a single element, use Collections.singletonMap(...). It also return a non-modifiable map. Note that this is highlighting an trap in the Java language and API.

Target:
public static boolean openRenameWizard(String newName, IStructuredSelection structuredSelection) { Map<String, Object> commandParameters = new HashMap<>(); commandParameters.put(LTK_RENAME_COMMAND_NEWNAME_PARAMETER_KEY, newName); return runCommand(LTK_RENAME_ID, structuredSelection, commandParameters); }
Source:
public int hashCode() { START return Objects.hash(fEntry, fTime, fDuration, fValue); END } Active properties are ignored.

Target:
public int hashCode() { return Objects.hash(fEntry, fTime, fDuration, getValue()); }
Source:
private boolean isFileKeyChanged(Object currFileKey) { boolean changed = currFileKey != MISSING_FILEKEY && !currFileKey.equals(fileKey); START LOG.debug("file={}, FileKey changed from to {}", //$NON-NLS-1$ file, fileKey, currFileKey); END return changed; } Should this be enclosed in "if (changed)" like in the following method?

Target:
private boolean isFileKeyChanged(Object currFileKey) { boolean changed = currFileKey != MISSING_FILEKEY && !currFileKey.equals(fileKey); if (changed) { LOG.debug("file={}, FileKey changed from to {}", //$NON-NLS-1$ file, fileKey, currFileKey); } return changed; }
Source:
private void start() { START if (!control.isDisposed()) { END if (control instanceof Text) { ((Text) control).addVerifyListener(this); } else if (control instanceof Combo) { ((Combo) control).addVerifyListener(this); } } } how can this happen? and should we check for null like in stop?

Target:
private void start() { if (control != null && !control.isDisposed()) { if (control instanceof Text) { ((Text) control).addVerifyListener(this); } else if (control instanceof Combo) { ((Combo) control).addVerifyListener(this); } } }
Source:
public void dispose() { if (fOverlayStore != null) { fOverlayStore.stop(); fOverlayStore= null; } for (Image image : colorPreviewImages) { image.dispose(); START } END super.dispose(); } I suggest you reset colorPreviewImages to null after that.

Target:
public void dispose() { if (fOverlayStore != null) { fOverlayStore.stop(); fOverlayStore= null; } for (Image image : colorPreviewImages) { image.dispose(); } colorPreviewImages= null; super.dispose(); }
Source:
private void updateAppearanceColorWidgets(String systemDefaultKey) { if (systemDefaultKey == null) { fAppearanceColorDefault.setSelection(false); fAppearanceColorDefault.setVisible(false); fAppearanceColorEditor.getButton().setEnabled(true); } else { boolean systemDefault= fOverlayStore.getBoolean(systemDefaultKey); fAppearanceColorDefault.setSelection(systemDefault); fAppearanceColorDefault.setVisible(true); fAppearanceColorEditor.getButton().setEnabled(!systemDefault); } START fAppearanceColorTableViewer.refresh(); END } Why is this necessary here?

Target:
private void updateAppearanceColorWidgets(String systemDefaultKey) { if (systemDefaultKey == null) { fAppearanceColorDefault.setSelection(false); fAppearanceColorDefault.setVisible(false); fAppearanceColorEditor.getButton().setEnabled(true); } else { boolean systemDefault= fOverlayStore.getBoolean(systemDefaultKey); fAppearanceColorDefault.setSelection(systemDefault); fAppearanceColorDefault.setVisible(true); fAppearanceColorEditor.getButton().setEnabled(!systemDefault); } }
Source:
private void createShowFirstParentOnlyAction() { showFirstParentOnlyAction = new ShowFirstParentOnlyPrefAction(); START showFirstParentOnlyAction .setImageDescriptor(UIIcons.FIRST_PARENT_ONLY); showFirstParentOnlyAction .setToolTipText(UIText.GitHistoryPage_showFirstParentOnly); END actionsToDispose.add(showFirstParentOnlyAction); } why not in the constructor of that action class?

Target:
private void createShowFirstParentOnlyAction() { showFirstParentOnlyAction = new ShowFirstParentOnlyPrefAction(); actionsToDispose.add(showFirstParentOnlyAction); }
Source:
public void dispose() { START super.dispose(); END for (IAction action : this.actions) { action.removePropertyChangeListener(listener); } } is there any reason for calling super first? I thought calling super.dispose last were a common best practice (unless some of the other code in this dispose method requires some fields to be disposed by such a call before).

Target:
public void dispose() { for (IAction action : this.actions) { action.removePropertyChangeListener(listener); } super.dispose(); }
Source:
public static Set<String> getPreviousTypeParamNames(List<TypeParameter> typeParams, ASTNode missingNode) { Set<String> previousNames= new HashSet<>(); for (int i = 0; i < START typeParams.size(); END i++) { TypeParameter curr= typeParams.get(i); if (curr == missingNode) { return previousNames; } previousNames.add('<' + curr.getName().getIdentifier() + '>'); } return previousNames; } Foreach?

Target:
public static Set<String> getPreviousTypeParamNames(List<TypeParameter> typeParams, ASTNode missingNode) { Set<String> previousNames= new HashSet<>(); for (TypeParameter curr : typeParams) { if (curr == missingNode) { return previousNames; } previousNames.add('<' + curr.getName().getIdentifier() + '>'); } return previousNames; }
Source:
public void testRenameSymref() throws IOException { START ObjectId id = END db.resolve("HEAD"); RefRename r = db.renameRef("HEAD", "KOPF"); assertEquals(IO_FAILURE, r.rename()); } unused

Target:
public void testRenameSymref() throws IOException { db.resolve("HEAD"); RefRename r = db.renameRef("HEAD", "KOPF"); assertEquals(IO_FAILURE, r.rename()); }
Source:
private static MergedReftable merge(byte[]... START table) throws IOException { END List<ReftableReader> stack = new ArrayList<>(table.length); for (byte[] b : table) { stack.add(read(b)); } return new MergedReftable(stack); } remove unthrown exception

Target:
private static MergedReftable merge(byte[]... table) { List<ReftableReader> stack = new ArrayList<>(table.length); for (byte[] b : table) { stack.add(read(b)); } return new MergedReftable(stack); }
Source:
protected void addUserInputPages() { RenameResourceProcessor processor= getRefactoring().getAdapter(RenameResourceProcessor.class); START RenameResourceRefactoringConfigurationPage page= new RenameResourceRefactoringConfigurationPage(processor); addPage(page); END } Is this change necessary? Seems like you're just breaking it up but it's not any different in functionality from how it was before.

Target:
protected void addUserInputPages() { RenameResourceProcessor processor= getRefactoring().getAdapter(RenameResourceProcessor.class); addPage(new RenameResourceRefactoringConfigurationPage(processor)); }
Source:
public RenameResourceWizard(IResource resource, String newName) { START super(new RenameRefactoring(new RenameResourceProcessor(resource)), DIALOG_BASED_USER_INTERFACE); END RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); setDefaultPageTitle(RefactoringUIMessages.RenameResourceWizard_page_title); setWindowTitle(RefactoringUIMessages.RenameResourceWizard_window_title); } you can make it this(resource); fRenameResourceProcessor.setNewResourceName(newName); which would improve factorization

Target:
public RenameResourceWizard(IResource resource, String newName) { this(resource); RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); setDefaultPageTitle(RefactoringUIMessages.RenameResourceWizard_page_title); setWindowTitle(RefactoringUIMessages.RenameResourceWizard_window_title); }
Source:
public RenameResourceWizard(IResource resource, String newName) { this(resource); RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); setDefaultPageTitle(RefactoringUIMessages.RenameResourceWizard_page_title); START setWindowTitle(RefactoringUIMessages.RenameResourceWizard_window_title); END } You don't need to repeat lines 67, 69 and 70 as this will be invoked by this(resource) : this(...) invokes the other constructor first so no need to repeat it's content.

Target:
public RenameResourceWizard(IResource resource, String newName) { this(resource); RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); }
Source:
public void setNewName(String newName) { this.fRenameResourceProcessor.setNewResourceName(newName); super.setForcePreview(true); START super.setForceFinish(true); END } Instead of calling those 2 setters, you could try invoking `validatePage` which should take care of fixing button enablement.

Target:
public void setNewName(String newName) { this.fRenameResourceProcessor.setNewResourceName(newName); }
Source:
public void setNewName(String newName) { this.fRenameResourceProcessor.setNewResourceName(newName); super.setForcePreview(true); super.setForceFinish(true); START System.out.println("new name set"); //$NON-NLS-1$ END } Please don't use System.out in production code ;)

Target:
public void setNewName(String newName) { this.fRenameResourceProcessor.setNewResourceName(newName); super.setForcePreview(true); super.setForceFinish(true); }
Source:
START private END Expression getExpressionWithoutParenthezis(Expression expression) { Expression currExpression= expression; while (currExpression instanceof ParenthesizedExpression) { currExpression= ((ParenthesizedExpression) currExpression).getExpression(); } return currExpression; } 'static' could be added, since it doesn't rely on any particular instance of the class.

Target:
private static Expression getExpressionWithoutParenthezis(Expression expression) { Expression currExpression= expression; while (currExpression instanceof ParenthesizedExpression) { currExpression= ((ParenthesizedExpression) currExpression).getExpression(); } return currExpression; }
Source:
public boolean handleSelection() { START try { END if (FoundInVersionColumnUI.promptFoundInVersion((TeamWorkFlowArtifact) getArtifact(), VersionReleaseType.UnReleased, VersionLockedType.UnLocked, getRelation())) { notifyXModifiedListeners(); refresh(); return true; } return false; } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } return false; } Don't think we want to specify UnLocked and UnReleased. We want to be able to select any version.

Target:
public boolean handleSelection() { try { if (FoundInVersionColumnUI.promptFoundInVersion((TeamWorkFlowArtifact) getArtifact(), getRelation())) { notifyXModifiedListeners(); refresh(); return true; } return false; } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } return false; }
Source:
public Map<String, Ref> getRefs(String prefix) throws IOException { List<Ref> refs = reftableDatabase.getRefsByPrefix(prefix); START RefList.Builder builder = new RefList.Builder(refs.size()); END for (Ref r : refs) { builder.add(r); } return new RefMap(prefix, builder.toRefList(), RefList.emptyList(), RefList.emptyList()); } missing type parameter causing warnings: RefList.Builder<Ref> builder = new RefList.Builder<>(refs.size());

Target:
public Map<String, Ref> getRefs(String prefix) throws IOException { List<Ref> refs = reftableDatabase.getRefsByPrefix(prefix); RefList.Builder<Ref> builder = new RefList.Builder<>(refs.size()); for (Ref r : refs) { builder.add(r); } return new RefMap(prefix, builder.toRefList(), RefList.emptyList(), RefList.emptyList()); }
Source:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = null; try { userConfig = SystemReader.getInstance().getUserConfig(); updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { // Log it, but otherwise ignore here. LOG.error(MessageFormat.format(JGitText.get().userConfigInvalid, START userConfig, e)); END } } Hm. We need to think a bit more about exception handling and how to report which config was invalid. Here in any case userConfig is always null. I think the ConfigInvalidException's message would include the file name.

Target:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = null; try { userConfig = SystemReader.getInstance().getUserConfig(); updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { // Log it, but otherwise ignore here. LOG.error(e.getMessage(), e); } }
Source:
public HttpConfig(URIish uri) { StoredConfig userConfig = GlobalConfigCache.getInstance() .getUserConfig(); try { START userConfig.load(); END } catch (IOException | ConfigInvalidException e) { // Log it and then work with default values. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); init(new Config(), uri); return; } init(userConfig, uri); } load() not needed anymore, and need to catch RuntimeException.

Target:
public HttpConfig(URIish uri) { StoredConfig userConfig = null; try { userConfig = GlobalConfigCache.getInstance().getUserConfig(); } catch (IOException | ConfigInvalidException e) { // Log it and then work with default values. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); init(new Config(), uri); return; } init(userConfig, uri); }
Source:
START public static GlobalConfigCache getInstance() { END return INSTANCE.get(); } I think the SystemReader should server this cache instance. With two static instances, there is a brief interval in which this cache instance will be the old one while the SystemReader instance will already be the new one. Might be simpler if the two methods getSystemConfig() and getUserConfig() were on SystemReader, without this separate class.

Target:
public static GlobalConfigCache getInstance() { return INSTANCE; }
Source:
START public StoredConfig getSystemConfig() { END if (systemConfig.isOutdated()) { try { LOG.debug("loading system config {}", //$NON-NLS-1$ systemConfig); systemConfig.load(); } catch (IOException e) { throw new RuntimeException(e); } catch (ConfigInvalidException e) { throw new RuntimeException( MessageFormat.format( JGitText.get().systemConfigFileInvalid, systemConfig.getFile().getAbsolutePath(), e), e); } } return systemConfig; } Propagate IOE and ConfigInvalidException instead of translating to RuntimeException? I'm not happy about this translation -- unclear what the effects will be. If you propagate checked exceptions, the caller has to think about what to do with it. Most callers already catch IOE and ConfigInvalidException from load().

Target:
public StoredConfig getSystemConfig() throws IOException, ConfigInvalidException { if (systemConfig.isOutdated()) { try { LOG.debug("loading system config {}", //$NON-NLS-1$ systemConfig); systemConfig.load(); } catch (ConfigInvalidException e) { LOG.error(MessageFormat.format( JGitText.get().systemConfigFileInvalid, systemConfig.getFile().getAbsolutePath()), e); throw e; } } return systemConfig; }
Source:
private void add(String... searchStrings) { if (searchStrings != null) { for (String searchString : searchStrings) { if (searchString == null || searchString.isEmpty()) { START return; END } Node node= root; for (char c : searchString.toCharArray()) { node= node.add(c); } node.match= searchString; } } } True, was to thoughtless while inlining...

Target:
private void add(String... searchStrings) { if (searchStrings != null) { for (String searchString : searchStrings) { if (searchString == null || searchString.isEmpty()) { continue; } Node node= root; for (char c : searchString.toCharArray()) { node= node.add(c); } node.match= searchString; } } }
Source:
protected ConfigurableObject getInputType(Object input) { START if (input instanceof EditPart) { input = ((EditPart) input).getModel(); } if (input instanceof ConfigurableObject) { return (ConfigurableObject) input; } END return null; } why not put this all in one if condition? if (input instanceof EditPart && ((EditPart) input).getModel() instanceof ConfigurableObject)

Target:
protected ConfigurableObject getInputType(Object input) { if (input instanceof EditPart && ((EditPart) input).getModel() instanceof ConfigurableObject) { return (ConfigurableObject) input; } return null; }
Source:
START public PropertyParameter[] getParameters() { END return m_parameters.values().toArray(new PropertyParameter[m_parameters.values().size()]); } could we change to List<PropertyParameter> or is this API fixed?

Target:
public Collection<PropertyParameter> getParameters() { return m_parameters.values(); }
Source:
public StateItem(Map<String, Object> style) { Map<String, Object> styleMap = new HashMap<>(); styleMap.putAll(style); fStyleMap = StylePropertiesUtils.updateEventStyleProperties(styleMap); fOriginalStyleMap = START ImmutableMap.copyOf(StylePropertiesUtils.updateEventStyleProperties(styleMap)); END } can use fStyleMap here

Target:
public StateItem(Map<String, Object> style) { Map<String, Object> styleMap = new HashMap<>(); styleMap.putAll(style); fStyleMap = StylePropertiesUtils.updateEventStyleProperties(styleMap); fOriginalStyleMap = ImmutableMap.copyOf(fStyleMap); }