auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void commit(boolean pushUpstream) { boolean reEnable = false; // Don't allow to do anything as long as commit is in progress enableAllWidgets(false); try { boolean jobScheduled = START !internalCommit(pushUpstream, END () -> enableAllWidgets(true)); // If a job was scheduled, our Runnable will re-enable the widgets // once the commit and push is done; even if it fails. Otherwise, we // must re-enable the widgets here and now ourselves. reEnable = !jobScheduled; } catch (RuntimeException e) { // See bugs 550336, 550513 // If internalCommit() should fail after having scheduled the job, // we may re-enable a little too early. But better that than never. reEnable = true; Activator.handleError(e.getLocalizedMessage(), e, true); } finally { if (reEnable) { enableAllWidgets(true); } } } why that ? I think internalCommit() returns true if a job was scheduled

Target:
private void commit(boolean pushUpstream) { boolean reEnable = false; // Don't allow to do anything as long as commit is in progress enableAllWidgets(false); try { boolean jobScheduled = internalCommit(pushUpstream, () -> enableAllWidgets(true)); // If a job was scheduled, our Runnable will re-enable the widgets // once the commit and push is done; even if it fails. Otherwise, we // must re-enable the widgets here and now ourselves. reEnable = !jobScheduled; } catch (RuntimeException e) { // See bugs 550336, 550513 // If internalCommit() should fail after having scheduled the job, // we may re-enable a little too early. But better that than never. reEnable = true; Activator.handleError(e.getLocalizedMessage(), e, true); } finally { if (reEnable) { enableAllWidgets(true); } } }
Source:
private String getObjectText(IProductModel obj) { IProduct product = obj.getProduct(); String name = preventNull(product.getId()); START if (VersionUtil.isEmptyVersion(product.getVersion())) { END return name; } return name + ' ' + formatVersion(product.getVersion()); } We have products without an ID in the workspace, we could fallback to the name instead of an empty string.

Target:
private String getObjectText(IProductModel obj) { IProduct product = obj.getProduct(); String name = preventNull(product.getId()); if (name.isEmpty()) { name = preventNull(product.getName()); } if (VersionUtil.isEmptyVersion(product.getVersion())) { return name; } return name + ' ' + formatVersion(product.getVersion()); }
Source:
public void processQueue() { if (Thread.currentThread() == thread) { throw new IllegalStateException( "Cannot execute this method in the realm's own thread"); } try { synchronized (queue) { doProcess = true; START queue.notifyAll(); END while (!queue.isEmpty()) { if (!block) throw new IllegalStateException( "Cannot process queue, ThreadRealm is not blocking on its thread"); queue.wait(); } doProcess = false; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } What is this call for? If the queue is not empty then the `block` method should be running already? And if an element is added to the queue then notifyAll is called from that method? Do I miss some case?

Target:
public void processQueue() { if (Thread.currentThread() == thread) { throw new IllegalStateException( "Cannot execute this method in the realm's own thread"); } try { synchronized (queue) { while (!queue.isEmpty()) { if (!block) throw new IllegalStateException( "Cannot process queue, ThreadRealm is not blocking on its thread"); queue.wait(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
Source:
protected boolean handles(EObject owner, EReference reference) { return !(owner instanceof Template) && EcoreUtil.getRootContainer(owner) instanceof TemplateCollection START && !reference.isContainment(); END } A pedant would check the ereference-is-containment before the root container check that navigates the model. :-)

Target:
protected boolean handles(EObject owner, EReference reference) { return !(owner instanceof Template) && !reference.isContainment() && EcoreUtil.getRootContainer(owner) instanceof TemplateCollection; }
Source:
public boolean isThereAnInternalTraceBetween(EObject first, EObject second) { if (first.equals(second)) { return false; } else if (first instanceof INamed && second instanceof INamed) { START if (!first.eCrossReferences().isEmpty() && !second.eCrossReferences().isEmpty()) { END if (first.eCrossReferences().contains(second) || second.eCrossReferences().contains(first)) { return true; } } } return false; } Can eCrossReferences() ever return null? In that case, we would get an uncaught exception here.

Target:
public boolean isThereAnInternalTraceBetween(EObject first, EObject second) { if (first.equals(second)) { return false; } else if (first instanceof INamed && second instanceof INamed) { if (first.eCrossReferences() != null && second.eCrossReferences() != null) { if (first.eCrossReferences().contains(second) || second.eCrossReferences().contains(first)) { return true; } } } return false; }
Source:
public boolean isThereAnInternalTraceBetween(EObject first, EObject second) { if (first.equals(second)) { return false; } else if (first instanceof INamed && second instanceof INamed) { START if (first.eCrossReferences().contains(second) || second.eCrossReferences().contains(first)) { END return true; } } return false; } Are these lists always initialised? Might be worthwhile to put in a null check here.

Target:
public boolean isThereAnInternalTraceBetween(EObject first, EObject second) { if (first.equals(second)) { return false; } else if (first instanceof INamed && second instanceof INamed) { if (!first.eCrossReferences().isEmpty() && !second.eCrossReferences().isEmpty()) { if (first.eCrossReferences().contains(second) || second.eCrossReferences().contains(first)) { return true; } } } return false; }
Source:
public void dispose() { historyPage.removePropertyChangeListener(this); START if (dialog != null) END dialog.close(); } missing braces

Target:
public void dispose() { historyPage.removePropertyChangeListener(this); if (dialog != null) { dialog.close(); } }
Source:
public boolean isOnlyHEADSelected(Set<RefFilter> filters) { for (RefFilter filter : filters) { if (filter.isSelected()) { START if (!filtersForHEAD.contains(filter)) END return false; } else { if (filtersForHEAD.contains(filter)) return false; } } return true; } missing braces

Target:
public boolean isOnlyHEADSelected(Set<RefFilter> filters) { for (RefFilter filter : filters) { if (filter.isSelected()) { if (!filtersForHEAD.contains(filter)) { return false; } } else { if (filtersForHEAD.contains(filter)) { return false; } } } return true; }
Source:
public void dispose() { writeSettings(); START LogReaderService[] services = this.logReaderServiceTracker.getServices(new LogReaderService[0]); END for (LogReaderService logReaderService : services) { logReaderService.removeLogListener(this); } this.logReaderServiceTracker.close(); fClipboard.dispose(); if (fTextShell != null) fTextShell.dispose(); fLabelProvider.disconnect(this); fFilteredTree.dispose(); super.dispose(); } I think ist is enough to close the tracker heres, this will triger "removedService in line 198 and then remove the listeners

Target:
public void dispose() { writeSettings(); this.logReaderServiceTracker.close(); fClipboard.dispose(); if (fTextShell != null) fTextShell.dispose(); fLabelProvider.disconnect(this); fFilteredTree.dispose(); super.dispose(); }
Source:
private File getRunDirectory(Repository repository, @NonNull String hookName) { if (repository.isBare()) { return repository.getDirectory(); START } else { END switch (hookName) { case "pre-receive": //$NON-NLS-1$ case "update": //$NON-NLS-1$ case "post-receive": //$NON-NLS-1$ case "post-update": //$NON-NLS-1$ case "push-to-checkout": //$NON-NLS-1$ return repository.getDirectory(); default: return repository.getWorkTree(); } } } remove unnecessary else clause ?

Target:
private File getRunDirectory(Repository repository, @NonNull String hookName) { if (repository.isBare()) { return repository.getDirectory(); } switch (hookName) { case "pre-receive": //$NON-NLS-1$ case "update": //$NON-NLS-1$ case "post-receive": //$NON-NLS-1$ case "post-update": //$NON-NLS-1$ case "push-to-checkout": //$NON-NLS-1$ return repository.getDirectory(); default: return repository.getWorkTree(); } }
Source:
private static void testPidSorting(final SWTBotTree tree, final SWTBotTimeGraph timeGraph) { SWTBotTreeColumn column = tree.header(PID_COLUMN); String[] expected = { START LTTNG_CONSUMER_PROCESS_NAME, KTHREAD_PROCESS_NAME, SYSTEMD_PROCESS_NAME }; END /* Sort direction Up */ SWTBotTestCondition condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected, timeGraph, false); clickColumn(tree, column, condition); /* Sort direction Down */ String[] expected2 = { SYSTEMD_PROCESS_NAME, KTHREAD_PROCESS_NAME, LTTNG_CONSUMER_PROCESS_NAME }; condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected2, timeGraph, false); clickColumn(tree, column, condition); } If you use here the order of expected2 and below this order, then it's successful.

Target:
private static void testPidSorting(final SWTBotTree tree, final SWTBotTimeGraph timeGraph) { SWTBotTreeColumn column = tree.header(PID_COLUMN); String[] expected = { SYSTEMD_PROCESS_NAME, KTHREAD_PROCESS_NAME, LTTNG_CONSUMER_PROCESS_NAME }; /* Sort direction Up */ SWTBotTestCondition condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected, timeGraph, false); clickColumn(tree, column, condition); /* Sort direction Down */ String[] expected2 = { LTTNG_CONSUMER_PROCESS_NAME, KTHREAD_PROCESS_NAME, SYSTEMD_PROCESS_NAME }; condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected2, timeGraph, false); clickColumn(tree, column, condition); }
Source:
public void log(IStatus status) { log(0, status); if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); for (IStatus START children1 : END children) { log(1, children1); } } } child

Target:
public void log(IStatus status) { log(0, status); if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); for (IStatus child : children) { log(1, child); } } }
Source:
public void log(IStatus status) { int severity = status.getSeverity(); // Log the status message log(status.getMessage(), severity); // Log the exception if applicable if (status.getException() != null) log(status.getException().getMessage(), severity); // Log any children of this status IStatus[] nestedStatus = status.getChildren(); if (nestedStatus != null) for (IStatus START nestedStatu : END nestedStatus) { log(nestedStatu); } } better name needed

Target:
public void log(IStatus status) { int severity = status.getSeverity(); // Log the status message log(status.getMessage(), severity); // Log the exception if applicable if (status.getException() != null) log(status.getException().getMessage(), severity); // Log any children of this status IStatus[] nestedStatus = status.getChildren(); if (nestedStatus != null) for (IStatus s : nestedStatus) { log(s); } }
Source:
protected void writeChildren(URI[] children) { if (children == null || children.length == 0) return; start(CHILDREN_ELEMENT); attribute(COLLECTION_SIZE_ATTRIBUTE, children.length); for (URI START children1 : END children) { writeChild(children1); } end(CHILDREN_ELEMENT); } child

Target:
protected void writeChildren(URI[] children) { if (children == null || children.length == 0) return; start(CHILDREN_ELEMENT); attribute(COLLECTION_SIZE_ATTRIBUTE, children.length); for (URI child : children) { writeChild(child); } end(CHILDREN_ELEMENT); }
Source:
private boolean fullyDelete(File file) { if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File START children1 : END children) { // we will not stop even if some deletion failed fullyDelete(new File(file, children1.getName())); } } } // will attempt to delete before exists check to get rid of dead links if (file.delete()) { return true; } // will return true if files does not actually exist even delete fails return !file.exists(); } child

Target:
private boolean fullyDelete(File file) { if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { // we will not stop even if some deletion failed fullyDelete(new File(file, child.getName())); } } } // will attempt to delete before exists check to get rid of dead links if (file.delete()) { return true; } // will return true if files does not actually exist even delete fails return !file.exists(); }
Source:
public static void deleteDir(File file) throws IOException { if (file.isFile()) { if (!file.delete()) throw new IOException("Fail to delete File(" + file.getAbsolutePath() + ")"); return; } File[] children = file.listFiles(); for (File START children1 : END children) { deleteDir(children1); } if (!file.delete()) throw new IOException("Fail to delete Dir(" + file.getAbsolutePath() + ")"); return; } child

Target:
public static void deleteDir(File file) throws IOException { if (file.isFile()) { if (!file.delete()) throw new IOException("Fail to delete File(" + file.getAbsolutePath() + ")"); return; } File[] children = file.listFiles(); for (File child : children) { deleteDir(child); } if (!file.delete()) throw new IOException("Fail to delete Dir(" + file.getAbsolutePath() + ")"); return; }
Source:
public boolean applicabilityExistsOnBranchView(BranchId branch, ArtifactId viewId, String applicability) { boolean exists = false; List<GammaId> tuples = new ArrayList<>(); queryFactory.tupleQuery().getTuple2GammaFromE1E2(CoreTupleTypes.ViewApplicability, branch, viewId, applicability, tuples::add); START if (!tuples.isEmpty()) { END exists = true; } return exists; } remove exists variable and just return !tuples.isEmpty();

Target:
public boolean applicabilityExistsOnBranchView(BranchId branch, ArtifactId viewId, String applicability) { List<GammaId> tuples = new ArrayList<>(); queryFactory.tupleQuery().getTuple2GammaFromE1E2(CoreTupleTypes.ViewApplicability, branch, viewId, applicability, tuples::add); return tuples.isEmpty(); }
Source:
protected boolean synchronizeModel(IDocument doc) { if (doc == null) { return false; } IFeatureModel model = (IFeatureModel) getModel(); String text = doc.get(); try (InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8))) { model.reload(stream, false); } catch (CoreException e) { return false; START } catch (IOException e) { END } return true; } should return false also in this case use multi-catch catch (CoreException | IOException e) { return false; }

Target:
protected boolean synchronizeModel(IDocument doc) { if (doc == null) { return false; } IFeatureModel model = (IFeatureModel) getModel(); String text = doc.get(); try (InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8))) { model.reload(stream, false); } catch (CoreException | IOException e) { return false; } return true; }
Source:
public void delete(Collection<RepositoryGroup> groupsToDelete) { for (RepositoryGroup group : groupsToDelete) { preferences .remove(PREFS_GROUP_PREFIX + START group.getGroupId().toString()); END groupMap.remove(group.getGroupId()); } savePreferences(); } No necessary. + operator with a string operand (the prefix) performs auto-stringification of the other operand.

Target:
public void delete(Collection<RepositoryGroup> groupsToDelete) { for (RepositoryGroup group : groupsToDelete) { preferences .remove(PREFS_GROUP_PREFIX + group.getGroupId()); groupMap.remove(group.getGroupId()); } savePreferences(); }
Source:
protected void initialize() { if (fields != null) { Iterator<FieldEditor> e = fields.iterator(); IPreferenceStore pagePreferenceStore = getPreferenceStore(); while (e.hasNext()) { FieldEditor pe = e.next(); pe.setPage(this); pe.setPropertyChangeListener(this); if (pe.getPreferenceStore() == null) { START pe.setPreferenceStore(pagePreferenceStore); END } pe.load(); } } } I think the intention is clearer when you avoid pagePreferenceStore variable and write here: pe.setPreferenceStore(this.getPreferenceStore());

Target:
protected void initialize() { if (fields != null) { Iterator<FieldEditor> e = fields.iterator(); while (e.hasNext()) { FieldEditor pe = e.next(); pe.setPage(this); pe.setPropertyChangeListener(this); if (pe.getPreferenceStore() == null) { pe.setPreferenceStore(getPreferenceStore()); } pe.load(); } } }
Source:
public ExecuteCliParsersJob(CliCommandLine commandLine) { super("Executing CLI parser"); //$NON-NLS-1$ START setSystem(true); END fCommandLine = commandLine; } System jobs cannot be cancelled by the users. I wonder if we should have as user job so that it could be cancelled using the progress view?

Target:
public ExecuteCliParsersJob(CliCommandLine commandLine) { super("Executing CLI parser"); //$NON-NLS-1$ fCommandLine = commandLine; }
Source:
public static Job getWorkspaceLoadingJob(CliCommandLine commandLine) { START ExecuteCliParsersJob job = new ExecuteCliParsersJob(commandLine); return job; END } return new ExecuteCliParsersJob(commandLine);

Target:
public static Job getWorkspaceLoadingJob(CliCommandLine commandLine) { return new ExecuteCliParsersJob(commandLine); }
Source:
private static P2ResolutionResult singleEnv(Map<TargetEnvironment, P2ResolutionResult> map) { assertEquals(1, map.size()); START for (P2ResolutionResult result : map.values()) { END return result; } throw new AssertionError("should never happen"); } map.entrySet().iterator().next() seems a bit more idiomatic than using a loop with an unconditional return.

Target:
private static P2ResolutionResult singleEnv(Map<TargetEnvironment, P2ResolutionResult> map) { assertEquals(1, map.size()); return map.values().iterator().next(); }
Source:
protected boolean hasTextTransform(CSSValue value) { if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) { CSSPrimitiveValue primitiveValue = (CSSPrimitiveValue) value; String textTransform = primitiveValue.getStringValue(); START if ("capitalize".equals(textTransform)) { END return true; } if ("uppercase".equals(textTransform)) { return true; } if ("lowercase".equals(textTransform)) { return true; } } return false; } use switch

Target:
protected boolean hasTextTransform(CSSValue value) { if (value.getCssValueType() != CSSValue.CSS_PRIMITIVE_VALUE || ((CSSPrimitiveValue) value).getStringValue() == null) { return false; } String textTransform = ((CSSPrimitiveValue) value).getStringValue(); switch (textTransform) { case "capitalize": case "uppercase": case "lowercase": return true; } return false; }
Source:
public void disconnect() { START Object lock = partitions != null ? partitions : new Object(); synchronized (lock) { END document = null; partitions.clear(); try { inputStream.close(); } catch (IOException e) { } } } The code is still wrong. One shoulkd never lock on objects that can be null, the check above is not reliable (it can be wrong just after the null check), and locking on a new Object() makes no sense at all - it does not lock *anything*, only the current thread knows the local object instance.

Target:
public void disconnect() { synchronized (partitions) { document = null; partitions.clear(); try { inputStream.close(); } catch (IOException e) { } } }
Source:
public boolean shouldRun() { final boolean shouldRun = START pendingPartitions != null && END pendingPartitions.size() > 0; return shouldRun; } that can be null? This means all the locks above can throw NPE? Also accessing this object here without synchronized lock? I don't get what is the strategy is here. Again: object that can be set to null CAN'T BE USED FOR SYNCHRONIZATION. Please either make sure they are never null or use different objects for synchronization.

Target:
public boolean shouldRun() { final boolean shouldRun = pendingPartitions.size() > 0; return shouldRun; }
Source:
public void disconnect() { START synchronized (partitions) { synchronized (pendingPartitions) { END pendingPartitions.notifyAll(); } trimJob.cancel(); queueJob.cancel(); lld = null; document = null; inputPartitions = null; pendingPartitions.clear(); pendingSize = 0; partitions.clear(); } } I'm worrying to see two locks acquired here. Can we first acquire pending partitions, notify and acquire partitions?

Target:
public void disconnect() { synchronized (pendingPartitions) { pendingPartitions.clear(); pendingSize = 0; pendingPartitions.notifyAll(); } synchronized (partitions) { trimJob.cancel(); queueJob.cancel(); lld = null; document = null; inputPartitions = null; partitions.clear(); } }
Source:
public void clearBuffer() { if START (trimJob != null) { END trimJob.setOffset(-1); trimJob.schedule(); } } I don't see any place that would set trimJob to null. We also access that in other places without null check. So either we null the job somewhere and introduce checks, or remove check here.

Target:
public void clearBuffer() { trimJob.setOffset(-1); trimJob.schedule(); }
Source:
protected void dispose() { START super.dispose(); END // Get lock on ourself before closing. Closing streams check for console finish. // Finish check need lock on (this) console. Since closing also lock on stream // this can deadlock with other threads (double) closing streams at same time // but already own a lock on console. (bug 551902) // Long story short. Before closing IOConsole...Stream get lock from associated // console to prevent deadlocks. synchronized (this) { // make a copy of the open streams and close them all // a copy is needed as close the streams results in a callback that // removes the streams from the openStreams collection (bug 152794) List<Closeable> list = new ArrayList<>(openStreams); for (Closeable closable : list) { try { closable.close(); } catch (IOException e) { // e.printStackTrace(); } } inputStream = null; } final IDocument document = partitioner.getDocument(); document.setDocumentPartitioner(null); partitioner.disconnect(); } Not sure I've mentioned already : it is highly unusual that suoer.dispose() is called *before* the child dispose. Surely not your change, but I wonder if it makes sense to cleanup this too.

Target:
protected void dispose() { // Get lock on ourself before closing. Closing streams check for console finish. // Finish check need lock on (this) console. Since closing also lock on stream // this can deadlock with other threads (double) closing streams at same time // but already own a lock on console. (bug 551902) // Long story short. Before closing IOConsole...Stream get lock from associated // console to prevent deadlocks. synchronized (this) { // make a copy of the open streams and close them all // a copy is needed as close the streams results in a callback that // removes the streams from the openStreams collection (bug 152794) List<Closeable> list = new ArrayList<>(openStreams); for (Closeable closable : list) { try { closable.close(); } catch (IOException e) { // e.printStackTrace(); } } inputStream = null; } final IDocument document = partitioner.getDocument(); document.setDocumentPartitioner(null); partitioner.disconnect(); super.dispose(); }
Source:
public void connect(IDocument doc) { if (doc == document) { return; } synchronized (partitions) { START disconnect(); END if (doc != null) { inputPartitions = new ArrayList<>(); document = doc; legalLineDelimiterMatcher = MultiStringMatcher.create(document.getLegalLineDelimiters()); } } } does the disconnect() need to be inside the sync block? We are going to acquire another lock while holding partitions lock. Danger!

Target:
public void connect(IDocument doc) { if (doc == document) { return; } disconnect(); if (doc != null) { synchronized (partitions) { inputPartitions = new ArrayList<>(); document = doc; legalLineDelimiterMatcher = MultiStringMatcher.create(document.getLegalLineDelimiters()); } } }
Source:
START protected IShowInTargetList END getShowInTargetList() { final String[] targetList= createShowInTargetList(); if (targetList != null && targetList.length > 0) { return () -> targetList; } return null; } @since 3.13 missing

Target:
private IShowInTargetList getShowInTargetList() { final String[] targetList= createShowInTargetList(); if (targetList != null && targetList.length > 0) { return () -> targetList; } return null; }
Source:
START public boolean hasChildren(Object element) { END Predicate<Object> predicate = Stream.of(fViewer.getFilters()) .map(filter -> predicateFor(filter, element)) .reduce(t -> true, Predicate::and); return Stream.of(getChildren(element)) .filter(predicate) .findAny() .isPresent(); } This is not necessary, you can simply call setExpandPreCheckFilters(true) on the viewer.

Target:
public boolean hasChildren(Object element) { return getChildren(element).length > 0; }
Source:
private void finishInternal() { // Ensure task not currently running. START if (m_leasedThread.get() != null) { END return; } // Ensure task to be in done state, because method also called for periodic tasks which did not complete yet. if (!isDone()) { return; } // Ensure to be called only once (thread safety). if (!m_finished.compareAndSet(false, true)) { return; } finished(); } At this point, too, an AtomicReference does not bring any added value compared to a volatile variable.

Target:
private void finishInternal() { // Ensure task not currently running. if (m_leasedThread != null) { return; } // Ensure task to be in done state, because method also called for periodic tasks which did not complete yet. if (!isDone()) { return; } // Ensure to be called only once (thread safety). if (!m_finished.compareAndSet(false, true)) { return; } finished(); }
Source:
public boolean applicabilityExistsOnBranchView(BranchId branch, ArtifactId viewId, String applicability) { List<GammaId> tuples = new ArrayList<>(); queryFactory.tupleQuery().getTuple2GammaFromE1E2(CoreTupleTypes.ViewApplicability, branch, viewId, applicability, START tuples::add); END return (!tuples.isEmpty()); } don't need parens

Target:
public boolean applicabilityExistsOnBranchView(BranchId branch, ArtifactId viewId, String applicability) { List<GammaId> tuples = new ArrayList<>(); queryFactory.tupleQuery().getTuple2GammaFromE1E2(CoreTupleTypes.ViewApplicability, branch, viewId, applicability, tuples::add); return !tuples.isEmpty(); }
Source:
private static ILaunchConfigurationWorkingCopy getWorkingCopy(ILaunchConfiguration configuration) throws CoreException { ILaunchConfigurationWorkingCopy wc = null; if (configuration.isWorkingCopy()) { START wc = (ILaunchConfigurationWorkingCopy) configuration; END } else { wc = configuration.getWorkingCopy(); } return wc; } should return directly

Target:
private static ILaunchConfigurationWorkingCopy getWorkingCopy(ILaunchConfiguration configuration) throws CoreException { if (configuration.isWorkingCopy()) { return (ILaunchConfigurationWorkingCopy) configuration; } return configuration.getWorkingCopy(); }
Source:
public static boolean isResurrected(ChangeItem changeItem) { // There's a change corresponding to a Deleted Item, item MUST have been resurrected START return (changeItem.getBaselineVersion().isValid() && isDeleted( END changeItem.getBaselineVersion())) || (changeItem.getChangeType().equals( ChangeType.TUPLE_CHANGE) && changeItem.getDestinationVersion().isValid() && isDeleted( changeItem.getDestinationVersion()) && changeItem.getCurrentVersion().getModType().equals( ModificationType.INTRODUCED)); } I don't think this logic should require special support for tuples

Target:
public static boolean isResurrected(ChangeItem changeItem) { // There's a change corresponding to a Deleted Item, item MUST have been resurrected return (changeItem.getBaselineVersion().isValid() && isDeleted( changeItem.getBaselineVersion())) || changeItem.getCurrentVersion().getModType().equals( ModificationType.INTRODUCED); }
Source:
private CloseableHttpResponse get(final HttpGet httpGet) { try { return this.httpclient.execute(httpGet, this.context); } catch (IOException e) { START throw new IllegalArgumentException(); END } } Missing stacktrace

Target:
private CloseableHttpResponse get(final HttpGet httpGet) { try { return this.httpclient.execute(httpGet, this.context); } catch (IOException e) { throw new IllegalArgumentException(e); } }
Source:
private CloseableHttpResponse put(final HttpPut httpPut) { try { return this.httpclient.execute(httpPut, this.context); } catch (IOException e) { START throw new IllegalArgumentException(); END } } Missing stacktrace

Target:
private CloseableHttpResponse put(final HttpPut httpPut) { try { return this.httpclient.execute(httpPut, this.context); } catch (IOException e) { throw new IllegalArgumentException(e); } }
Source:
START private static Image getFBTypeImage(IFile element) { Image image; FBType type = getFBTypeFromFile(element); if (type instanceof BasicFBType) { image = FordiacImage.ICON_BASIC_FB.getImage(); } else if (type instanceof CompositeFBType) { image = FordiacImage.ICON_COMPOSITE_FB.getImage(); } else if (type instanceof ServiceInterfaceFBType) { image = FordiacImage.ICON_SIFB.getImage(); } else { // partly load file to determine type image = checkUnloadedFBType(element); } return image; } END instead of the pure declaration of image on top, returns for each if body would be nicer imho

Target:
private static Image getFBTypeImage(IFile element) { FBType type = getFBTypeFromFile(element); if (type instanceof BasicFBType) { return FordiacImage.ICON_BASIC_FB.getImage(); } else if (type instanceof CompositeFBType) { return FordiacImage.ICON_COMPOSITE_FB.getImage(); } else if (type instanceof ServiceInterfaceFBType) { return FordiacImage.ICON_SIFB.getImage(); } // partly load file to determine type return checkUnloadedFBType(element); }
Source:
public void handleSchemes(Collection<IScheme> toAdd, Collection<IScheme> toRemove) throws Exception { List<ISchemeInformation> schemesInformation = getSchemesInformation(toAdd); START for (ISchemeInformation schemeInformation : schemesInformation) { END String handlerInstanceLocation = schemeInformation.getHandlerInstanceLocation(); processExecutor.execute(LSREGISTER, UNREGISTER, handlerInstanceLocation); } String pathToEclipseApp = getPathToEclipseApp(); changePlistFile(toAdd, toRemove, pathToEclipseApp); registerAppWithLsregister(pathToEclipseApp); } we by intention did not attempt to modify the info.plist of another app. One has to remove the registration in the other app manually. The platform pref page also provides a hint for the user.

Target:
public void handleSchemes(Collection<IScheme> toAdd, Collection<IScheme> toRemove) throws Exception { String pathToEclipseApp = getPathToEclipseApp(); changePlistFile(toAdd, toRemove, pathToEclipseApp); registerAppWithLsregister(pathToEclipseApp); }
Source:
public void start(BundleContext context) throws Exception { super.start(context); fPlugin = this; try { fCommandLine = CliParserManager.getInstance().parse(Platform.getCommandLineArgs()); } catch (CliParserException e) { logError("Error parsing command line arguments", e); //$NON-NLS-1$ START throw e; END } } Don't throw the exception. It causes a lot of exception stack traces printed on the screen and stored in the .log file. It would be easy for the user to miss the usage message that is printed as well. I suggest, to find a different way to exit the application. Can't you just call CliParserManager.getInstance().parse(Platform.getCommandLineArgs()); in Application.java and exit if needed? I don't see the reason why it's done in the activator class.

Target:
public void start(BundleContext context) throws Exception { super.start(context); fPlugin = this; }
Source:
START public static void run(Repository repository, Work work) throws IOException { try (ConfigScope scope = new ConfigScope(repository)) { work.execute(); END } } Maybe it's just confused me, but did you eventually mean to have this and the next static method named exactly the other way around? Right now static run() calls instance execute, and static execute() calls instance run. And to avoid that confusion, would it eventually be possible to name the 2 methods identically? Or does that confuse the compiler? BTW: The class looks even better than I had thought when describing the lambda idea.

Target:
public static void run(Repository repository, Work work) throws IOException { try (ConfigScope scope = new ConfigScope(repository)) { work.run(); } }
Source:
START public static END String getLineIndentation(IDocument document, int offset) throws BadLocationException { // find start of line int adjustedOffset= (offset == document.getLength() ? offset - 1 : offset); IRegion line= document.getLineInformationOfOffset(adjustedOffset); int start= line.getOffset(); // find white spaces int end= findEndOfWhiteSpace(document, start, offset + line.getLength()); return document.get(start, end - start); } Not used outside the class. Can still be private.

Target:
private static String getLineIndentation(IDocument document, int offset) throws BadLocationException { // find start of line int adjustedOffset= (offset == document.getLength() ? offset - 1 : offset); IRegion line= document.getLineInformationOfOffset(adjustedOffset); int start= line.getOffset(); // find white spaces int end= findEndOfWhiteSpace(document, start, offset + line.getLength()); return document.get(start, end - start); }
Source:
public OwApplicability getOrCreateApplicability(OwArtifact artifact) { OwApplicability app = null; START app = artifact.getAppId(); END if (app == null) { app = new OwApplicability(); artifact.setAppId(app); } return app; } combine these two lines -> OwApplicability app = artifact.getAppId();

Target:
public OwApplicability getOrCreateApplicability(OwArtifact artifact) { OwApplicability app = artifact.getAppId(); if (app == null) { app = new OwApplicability(); artifact.setAppId(app); } return app; }
Source:
public @Nullable Range getFixedYRange() { return START this.fFixedYRange; END } remove the this here also

Target:
public @Nullable Range getFixedYRange() { return fFixedYRange; }
Source:
public void START setFixedYRange(@Nullable END Range fixedYRange) { this.fFixedYRange = fixedYRange; this.updateContent(); } how about calling this "fixRange(boolean fixed)" and then override the getWindowRange()? Just a thought.

Target:
public void setFixedYRange(@Nullable Range fixedYRange) { fFixedYRange = fixedYRange; updateContent(); }
Source:
public List<@Nullable Object> getOngoingStateValues() { fRWLock.readLock().lock(); try { START return Collections.unmodifiableList(fOngoingStateInfo); END } finally { fRWLock.readLock().unlock(); } } This returns a view of the transient state that is also transient, e.g. changes to transient state will be visible by the user of this method. I don't know if that's OK? Come to think of it, should all the queryOngoing*() methods have been in ITmfStateSystemBuilder instead of ITmfStateSystem?

Target:
public List<@Nullable Object> getOngoingStateValues() { fRWLock.readLock().lock(); try { return new ArrayList<>(fOngoingStateInfo); } finally { fRWLock.readLock().unlock(); } }
Source:
public BreakpointContainer[] getRoots(IBreakpoint breakpoint) { if (isShowingGroups()) { List<BreakpointContainer> list = new ArrayList<>(); for (Object START fElement : END fElements) { BreakpointContainer container = (BreakpointContainer) fElement; if (container.contains(breakpoint)) { list.add(container); } } return list.toArray(new BreakpointContainer[list.size()]); } return null; } rename to element

Target:
public BreakpointContainer[] getRoots(IBreakpoint breakpoint) { if (isShowingGroups()) { List<BreakpointContainer> list = new ArrayList<>(); for (Object element : fElements) { BreakpointContainer container = (BreakpointContainer) element; if (container.contains(breakpoint)) { list.add(container); } } return list.toArray(new BreakpointContainer[list.size()]); } return null; }
Source:
private void setSearchFilter(String string) { if START (patternFilter == null) { END patternFilter = new TypeListPatternFilter(); commonViewer.addFilter(patternFilter); } patternFilter.setPattern(string); commonViewer.refresh(false); handleTreeExpansion(string); } this should be: null == patternFilter

Target:
private void setSearchFilter(String string) { if (null == patternFilter) { patternFilter = new TypeListPatternFilter(); commonViewer.addFilter(patternFilter); } patternFilter.setPattern(string); commonViewer.refresh(false); handleTreeExpansion(string); }
Source:
public void run() { if (fBreakpoints != null) { for (BreakpointSetElement START fBreakpoint : END fBreakpoints) { fBreakpoint.container.getOrganizer().removeBreakpoint(fBreakpoint.breakpoint, fBreakpoint.container.getCategory()); } } } rename to breakpoint

Target:
public void run() { if (fBreakpoints != null) { for (BreakpointSetElement breakpoint : fBreakpoints) { breakpoint.container.getOrganizer().removeBreakpoint(breakpoint.breakpoint, breakpoint.container.getCategory()); } } }
Source:
public boolean isItemVisible(VirtualItem item) { // visible items. For now only mark the selected items as visible. for (VirtualItem element : fSelection) { START VirtualItem selectionItem = element; END while (selectionItem != null) { if (item.equals(selectionItem)) { return true; } selectionItem = selectionItem.getParent(); } } return false; } use as loopvar?

Target:
public boolean isItemVisible(VirtualItem item) { // visible items. For now only mark the selected items as visible. for (VirtualItem selectionItem : fSelection) { while (selectionItem != null) { if (item.equals(selectionItem)) { return true; } selectionItem = selectionItem.getParent(); } } return false; }
Source:
public void setup() { START Link link = new Link(new Shell(), SWT.NONE); END event = new HyperlinkEvent(link, "uri://test", "link", 0); linkEventConsumer = new HyperlinkEventConsumer(); } shell should be disposed in teardown

Target:
public void setup() { event = new HyperlinkEvent(link, "uri://test", "link", 0); linkEventConsumer = new HyperlinkEventConsumer(); }
Source:
public synchronized IPath[] getPaths() { List<IPath> result = new ArrayList<>(); for (Object element : objects.keySet()) { START IPath path = (IPath) element; END Node node = getNode(path); if (node.getPayload() != null) result.add(path); } return result.toArray(new IPath[result.size()]); } to loop var; objects is typed

Target:
public synchronized IPath[] getPaths() { List<IPath> result = new ArrayList<>(); for (IPath path : objects.keySet()) { Node node = getNode(path); if (node.getPayload() != null) result.add(path); } return result.toArray(new IPath[result.size()]); }
Source:
public synchronized Collection<Object> values() { List<Object> result = new ArrayList<>(); for (Object element : objects.keySet()) { START IPath path = (IPath) element; END Node node = getNode(path); if (node.getPayload() != null) result.add(node.getPayload()); } return result; } to loop var

Target:
public synchronized Collection<Object> values() { List<Object> result = new ArrayList<>(); for (IPath path : objects.keySet()) { Node node = getNode(path); if (node.getPayload() != null) result.add(node.getPayload()); } return result; }
Source:
public boolean ruleContains(IResource resource) { for (Object element : rules) { START ISchedulingRule rule = (ISchedulingRule) element; END if (rule != NULL_SCHEDULING_RULE && rule.contains(resource)) { return true; } } return false; } to loop var

Target:
public boolean ruleContains(IResource resource) { for (ISchedulingRule rule : rules) { if (rule != NULL_SCHEDULING_RULE && rule.contains(resource)) { return true; } } return false; }
Source:
private boolean isDescendantOfAddedRoot(IResource resource) { for (Object element : addedSubtrees) { START IResource root = (IResource) element; END if (isParent(root, resource)) { // There is a higher added root already in the list return true; } } return false; } to loop var

Target:
private boolean isDescendantOfAddedRoot(IResource resource) { for (IResource root : addedSubtrees) { if (isParent(root, resource)) { // There is a higher added root already in the list return true; } } return false; }
Source:
private void applyDiff(MapDiff<? extends K, ? extends V> diff, Map<K, V> map) { for (K START name : END diff.getRemovedKeys()) map.remove(name); for (K key : diff.getChangedKeys()) { map.put(key, diff.getNewValue(key)); } for (K key : diff.getAddedKeys()) { map.put(key, diff.getNewValue(key)); } } rename to key

Target:
private void applyDiff(MapDiff<? extends K, ? extends V> diff, Map<K, V> map) { for (K key : diff.getRemovedKeys()) { map.remove(key); } for (K key : diff.getChangedKeys()) { map.put(key, diff.getNewValue(key)); } for (K key : diff.getAddedKeys()) { map.put(key, diff.getNewValue(key)); } }
Source:
public void setGlobalEntries(IAntClasspathEntry[] entries) { if (fUserGlobalEntry == null) { String name = AntPreferencesMessages.ClasspathModel_3; fUserGlobalEntry = createGlobalEntry(entries, name, true, true, GLOBAL_USER); } else { fUserGlobalEntry.removeAll(); for (IAntClasspathEntry START entrie : END entries) { fUserGlobalEntry.addEntry(new ClasspathEntry(entrie, fUserGlobalEntry)); } } } rename to entry

Target:
public void setGlobalEntries(IAntClasspathEntry[] entries) { if (fUserGlobalEntry == null) { String name = AntPreferencesMessages.ClasspathModel_3; fUserGlobalEntry = createGlobalEntry(entries, name, true, true, GLOBAL_USER); } else { fUserGlobalEntry.removeAll(); for (IAntClasspathEntry entry : entries) { fUserGlobalEntry.addEntry(new ClasspathEntry(entry, fUserGlobalEntry)); } } }
Source:
public void isGitRepository() { START assertTrue(new File(db.getDirectory(), "HEAD").delete()); END assertTrue(RepositoryCache.FileKey.isGitRepository(db.getDirectory(), db.getFS())); } Why does a repository converted to reftable contain .git/HEAD ? Shouldn't that be deleted by convertToReftable() ?

Target:
public void isGitRepository() { assertTrue(RepositoryCache.FileKey.isGitRepository(db.getDirectory(), db.getFS())); }
Source:
public void isGitRepository() START throws IOException { END assertTrue(new File(db.getDirectory(), "HEAD").delete()); assertTrue(RepositoryCache.FileKey.isGitRepository(db.getDirectory(), db.getFS())); } This exception is not thrown, which causes the compilation failure: org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileReftableTest.java:[507,17333] The declared exception IOException is not actually thrown by the method isGitRepository() from type FileReftableTest

Target:
public void isGitRepository() { assertTrue(new File(db.getDirectory(), "HEAD").delete()); assertTrue(RepositoryCache.FileKey.isGitRepository(db.getDirectory(), db.getFS())); }
Source:
public long getNotificationCount() { return adapter.map(ad -> START ad.getNotificationCount()).orElse(0l); END } why 0l? that could even be taken as a legitimate notification count. Or, with many fonts, misread as 01 (zero one) Instead, we could return a public static final long NOT_ATTACHED = -1l;

Target:
public long getNotificationCount() { return adapter.getNotificationCount(); }
Source:
private static void clearPrefixedSystemProperties(String prefix, Map<String, String> targetPropertyMap) { for (Object START element : END System.getProperties().keySet()) { String propertyName = (String) element; if (propertyName.startsWith(prefix) && !targetPropertyMap.containsKey(propertyName)) { targetPropertyMap.put(propertyName, null); } } } rename to key

Target:
private static void clearPrefixedSystemProperties(String prefix, Map<String, String> targetPropertyMap) { for (Object key : System.getProperties().keySet()) { String propertyName = (String) key; if (propertyName.startsWith(prefix) && !targetPropertyMap.containsKey(propertyName)) { targetPropertyMap.put(propertyName, null); } } }
Source:
public void start(@Nullable BundleContext context) throws Exception { super.start(context); plugin = this; // Register CLI parser only if the class exists try { START Class.forName("org.eclipse.tracecompass.tracing.rcp.ui.cli.CliParserExtension"); END //$NON-NLS-1$ } catch (ClassNotFoundException e) { // RCP not loaded return; } } class doesn't exist

Target:
public void start(@Nullable BundleContext context) throws Exception { super.start(context); plugin = this; }
Source:
public NewSubAppCommand(FBNetwork fbNetwork, List<?> selection, int x, int y) { super(fbNetwork, LibraryElementFactory.eINSTANCE.createSubApp(), x, y); getSubApp().setSubAppNetwork(LibraryElementFactory.eINSTANCE.createFBNetwork()); START PositioningUtilities.removeXYOffsetForFBNetwork(selection); END addElements = new AddElementsToSubAppCommand(getSubApp(), selection); checkMapping(selection); } wouldn't this break undo?

Target:
public NewSubAppCommand(FBNetwork fbNetwork, List<?> selection, int x, int y) { super(fbNetwork, LibraryElementFactory.eINSTANCE.createSubApp(), x, y); getSubApp().setSubAppNetwork(LibraryElementFactory.eINSTANCE.createFBNetwork()); addElements = new AddElementsToSubAppCommand(getSubApp(), selection); checkMapping(selection); }
Source:
protected URI[] getSelectedLocations(Object[] selectionArray) { List<URI> urls = new ArrayList<>(); for (Object element : selectionArray) { START if (element instanceof MetadataRepositoryElement) urls.add(((MetadataRepositoryElement) element).getLocation()); END } return urls.toArray(new URI[urls.size()]); } when you are on it: add braces

Target:
protected URI[] getSelectedLocations(Object[] selectionArray) { List<URI> urls = new ArrayList<>(); for (Object element : selectionArray) { if (element instanceof MetadataRepositoryElement) { urls.add(((MetadataRepositoryElement) element).getLocation()); } } return urls.toArray(new URI[urls.size()]); }
Source:
protected List<Object> getModelChildren() { START ArrayList<Object> END elements = new ArrayList<>(); elements.add(new InstanceName(getModel())); elements.addAll(getModel().getInterface().getAllInterfaceElements()); return elements; } List<Object>

Target:
protected List<Object> getModelChildren() { List<Object> elements = new ArrayList<>(); elements.add(new InstanceName(getModel())); elements.addAll(getModel().getInterface().getAllInterfaceElements()); return elements; }
Source:
private DirectEditManager getManager() { if START (manager == null) { END manager = createDirectEditManager(); } return manager; } null == manager

Target:
private DirectEditManager getManager() { if (null == manager) { manager = createDirectEditManager(); } return manager; }
Source:
public static boolean isSupported(AST ast, int nodeType) { switch (nodeType) { case ASTNode.SWITCH_EXPRESSION: case ASTNode.YIELD_STATEMENT: START if (ast.apiLevel() < AST.JLS14_INTERNAL) { END return false; } break; case ASTNode.TEXT_BLOCK: return ast.isPreviewEnabled(); } return true; } Another nitpick :) this can be replaced by return ast.apiLevel() >= AST.JLS14_INTERNAL

Target:
public static boolean isSupported(AST ast, int nodeType) { switch (nodeType) { case ASTNode.SWITCH_EXPRESSION: case ASTNode.YIELD_STATEMENT: return ast.apiLevel() >= AST.JLS14_INTERNAL; case ASTNode.TEXT_BLOCK: return ast.isPreviewEnabled(); } return true; }
Source:
public static boolean isSupported(AST ast, int nodeType) { switch (nodeType) { case ASTNode.SWITCH_EXPRESSION: case ASTNode.YIELD_STATEMENT: if (ast.apiLevel() < AST.JLS14_INTERNAL) { return false; } break; case ASTNode.TEXT_BLOCK: START if (!ast.isPreviewEnabled()) { END return false; } } return true; } you can as well return ast.isPreviewEnabled() ; However, is there a reason for skipping ast.apiLevel() == AST.JLS14_INTERNAL? [Consider the case where this is called from <14 levels]

Target:
public static boolean isSupported(AST ast, int nodeType) { switch (nodeType) { case ASTNode.SWITCH_EXPRESSION: case ASTNode.YIELD_STATEMENT: if (ast.apiLevel() < AST.JLS14_INTERNAL) { return false; } break; case ASTNode.TEXT_BLOCK: return ast.isPreviewEnabled(); } return true; }
Source:
public boolean isPreviewEnabled() { START if (this.apiLevel == AST.JLS_Latest && this.previewEnabled) { END return true; } return false; } nitpick: just return <cond> sufficient

Target:
public boolean isPreviewEnabled() { return (this.apiLevel == AST.JLS_Latest && this.previewEnabled); }
Source:
public boolean getFlag(String flag) { String[] flags = getFlags(); for (String START flag2 : END flags) { if (flag2.equals(flag)) return true; } return false; } rename to f

Target:
public boolean getFlag(String flag) { for (String f : getFlags()) { if (f.equals(flag)) return true; } return false; }