auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void writeInfoFromNode(ITmfStateIntervalList stateInfo) { assert (this.isDone); // not sure this will always be the case... START if (intervals.size() == 0) { END return; } for (int i = 0; i < intervals.size(); i++) { stateInfo.add(intervals.get(i)); } return; } This is common in the code base, and I dislike it. size() == 0 -> isEmpty() You cannot assume the way the List operator implements size() and may be a huge cost (linear and not constant time).

Target:
void writeInfoFromNode(ITmfStateIntervalList stateInfo) { assert (this.isDone); // not sure this will always be the case... if (intervals.isEmpty()) { return; } for (int i = 0; i < intervals.size(); i++) { stateInfo.add(intervals.get(i)); } return; }
Source:
START public EList<org.eclipse.sirius.diagram.description.filter.FilterDescription> getFilters() { END if (filters == null) { filters = new EObjectContainmentEList.Resolving<org.eclipse.sirius.diagram.description.filter.FilterDescription>(org.eclipse.sirius.diagram.description.filter.FilterDescription.class, this, DescriptionPackage.DIAGRAM_DESCRIPTION__FILTERS); } return filters; } There should be an import in the import section.

Target:
public EList<FilterDescription> getFilters() { if (filters == null) { filters = new EObjectContainmentEList.Resolving<FilterDescription>(FilterDescription.class, this, DescriptionPackage.DIAGRAM_DESCRIPTION__FILTERS); } return filters; }
Source:
public int getLocationQuark(ITmfEvent event, int startQuark) { int quark = startQuark; for (TmfXmlStateAttribute attrib : fPath) { START quark = attrib.getAttributeQuark(event, quark); END } return quark; } throw an error

Target:
public int getLocationQuark(ITmfEvent event, int startQuark) { int quark = startQuark; for (TmfXmlStateAttribute attrib : fPath) { quark = attrib.getAttributeQuark(event, quark); if (quark == -1) { break; } } return quark; }
Source:
protected void updateTreeNode(ITreeNode node) { START if (getSwtTreeViewer() != null) { END getSwtTreeViewer().update(node, null); } } null check needed?

Target:
protected void updateTreeNode(ITreeNode node) { getSwtTreeViewer().update(node, null); }
Source:
public String getGuid() { START return String.valueOf(id); END } Why the valueof? Id is already a String

Target:
public String getGuid() { return id; }
Source:
public void start(BundleContext context) throws Exception { super.start(context); setDefault(this); START TmfAnalysisManager.initializeModuleSources(); END } we already have this in tmf.core.Activator now. Since this plugin depends on tmf.core, it will already be loaded. Is this necessary to call this again?

Target:
public void start(BundleContext context) throws Exception { super.start(context); setDefault(this); }
Source:
START public Iterable<IAnalysisModuleHelper> getAnalysisModules() { END if (fModules == null) { populateAnalysisModules(); } return fModules; } Why is fModules static? The list of modules is really the same for all XML modules? In this case, the getAnalysisModules() method here should be a static method also (and not using the interface method). And the whole class ends up being a "static" class, so it could have an empty private constructor to prevent instantiation. Also this method should be synchronized, to avoid the risk of two threads calling it at the same time and both entering the if block.

Target:
public synchronized Iterable<IAnalysisModuleHelper> getAnalysisModules() { if (fModules == null) { populateAnalysisModules(); } return fModules; }
Source:
public void invalidate(final boolean direct) { if (direct) { START layoutState = LAYOUT_REDO; END // if (getParent() instanceof AbstractBlockBox) { // // The parent box may contain text elements after the edited offset, that has to be updated // ((AbstractBlockBox) getParent()).invalidateChildrenAfterOffset(getStartOffset()); // } } else if (layoutState != LAYOUT_REDO) { layoutState = LAYOUT_PROPAGATE; } if (getParent() instanceof AbstractBlockBox) { ((AbstractBlockBox) getParent()).invalidate(false); } } If it's not needed anymore, just delete it ;-)

Target:
public void invalidate(final boolean direct) { if (direct) { layoutState = LAYOUT_REDO; } else { layoutState = LAYOUT_PROPAGATE; } if (getParent() instanceof AbstractBlockBox) { ((AbstractBlockBox) getParent()).invalidate(false); } }
Source:
private List<ProblemMarkerFilterDesc> findEnabledFilters(IProject project) { START List<ProblemMarkerFilterDesc> result = filtersCache.get(project); END if (result == null) { result = new ArrayList<ProblemMarkerFilterDesc>(); for (ProblemMarkerFilterDesc filterDesc: filters) { if ( filterDesc.matches(project) ) { result.add(filterDesc); } } filtersCache.put(project, result); } return result; } I think that access to filtersCache should be synchronized, no?

Target:
private List<ProblemMarkerFilterDesc> findEnabledFilters(IProject project) { synchronized (filtersCache) { List<ProblemMarkerFilterDesc> result = filtersCache.get(project); if (result == null) { result = new ArrayList<ProblemMarkerFilterDesc>(); for (ProblemMarkerFilterDesc filterDesc: filters) { if ( filterDesc.matches(project) ) { result.add(filterDesc); } } filtersCache.put(project, result); } return result; } }
Source:
START protected int getNbPendingBackgroundRequests() { END int nbBackgroundRequests = 0; synchronized (fLock) { for (ITmfEventRequest request : fPendingCoalescedRequests) { if (request.getExecType().equals(ExecutionType.BACKGROUND)) { nbBackgroundRequests++; } } } return nbBackgroundRequests; } Does this need to be protected, couldn't it be private? The "number of background requests" is really something that is specific to the internal implementation (just as the notion of foreground and background, but that's another story ;) ).

Target:
private int getNbPendingBackgroundRequests() { int nbBackgroundRequests = 0; synchronized (fLock) { for (ITmfEventRequest request : fPendingCoalescedRequests) { if (request.getExecType().equals(ExecutionType.BACKGROUND)) { nbBackgroundRequests++; } } } return nbBackgroundRequests; }
Source:
START private void setUp() throws CTFReaderException { END assumeTrue(testTrace.exists()); fixture = new Metadata(testTrace.getTrace()); } We should probably keep setUp for @Before and make another method "init". The assumeTrue should probably stay in the setUp

Target:
public void setUp() throws CTFReaderException { assumeTrue(testTrace.exists()); fixture = new Metadata(testTrace.getTrace()); }
Source:
public void setFirstReference(PDOMLinkage linkage, PDOMName name) throws CoreException { START if (linkage.equals(getLinkage())) END setFirstReference(name); else new PDOMExternalReferencesList(getPDOM(), record + FIRST_EXTREF_OFFSET).setFirstReference(linkage, name); } 'If" statements with 'else' branches should have curly braces around both branches.

Target:
public void setFirstReference(PDOMLinkage linkage, PDOMName name) throws CoreException { if (linkage.equals(getLinkage())) { setFirstReference(name); } else { new PDOMExternalReferencesList(getPDOM(), record + FIRST_EXTREF_OFFSET).setFirstReference(linkage, name); } }
Source:
private boolean transitionToWithWorkingBranchRuleExists(IAtsStateDefinition toStateDef) { START return (toStateDef.hasRule(RuleDefinitionOption.AllowTransitionWithWorkingBranch.name())); END } remove unnecessary surrounding parenthesis

Target:
private boolean transitionToWithWorkingBranchRuleExists(IAtsStateDefinition toStateDef) { return toStateDef.hasRule(RuleDefinitionOption.AllowTransitionWithWorkingBranch.name()); }
Source:
START public void set(V future) { END this.resultObject = future; } Should be protected.

Target:
protected void set(V future) { this.resultObject = future; }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } START return this.repository.equals(((RepositoryKey) obj).getRepository()); END } (Rather than a bunch of IF statements, you could do this all as one return statement w/ && for above.)

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.repository.equals(((RepositoryKey) obj).getRepository()); }
Source:
public void setUp() { START manager = new TaskRepositoryManager(); END manager.addRepository(actualFixture.repository()); connector = new BugzillaRestConnector(); } Do we need this? It doesn't seem to be used.

Target:
public void setUp() { connector = new BugzillaRestConnector(); }
Source:
public void testLoadCacheWrongRepository() throws Exception { BugzillaRestConnector connector = new BugzillaRestConnector(); assertNotNull(connector); START assertEquals(connector, BugzillaRestConnector.getDefault()); END TaskRepository taskRepository = new TaskRepository(BugzillaRestConnector.getDefault().getConnectorKind(), "http://mylyn.org/bugzilla-rest-trunk-wrong/"); AuthenticationCredentials credentials = new AuthenticationCredentials("username", "password"); taskRepository.setCredentials(AuthenticationType.REPOSITORY, credentials, false); BugzillaRestConfiguration configuration = BugzillaRestConnector.getDefault().getRepositoryConfiguration( taskRepository); assertNull(configuration); } Instead of making it a singleton, why not create the connector in setUp?

Target:
public void testLoadCacheWrongRepository() throws Exception { TaskRepository taskRepository = new TaskRepository(connector.getConnectorKind(), "http://mylyn.org/bugzilla-rest-trunk-wrong/"); AuthenticationCredentials credentials = new AuthenticationCredentials("username", "password"); taskRepository.setCredentials(AuthenticationType.REPOSITORY, credentials, false); BugzillaRestConfiguration configuration = connector.getRepositoryConfiguration(taskRepository); assertNull(configuration); }
Source:
public int hashCode() { final int prime = 31; int result = 1; START result = prime * result + ((repository == null) ? 0 : repository.hashCode()); END return result; } This can just return repository.hashCode()

Target:
public int hashCode() { return repository.hashCode(); }
Source:
public Collection<Field> getFields() { START return fields.values(); END } This should return an immutable collection.

Target:
public Map<String, Field> getFields() { return fields; }
Source:
START public Map<String, Product> getProducts(IOperationMonitor monitor) throws BugzillaRestException { END return retrieveItems(monitor, "/product?type=accessible", new Function<ProductResponse, Product[]>() { public Product[] apply(ProductResponse input) { return input.getProducts(); } }, new TypeToken<ProductResponse>() { }); } Should these methods be private?

Target:
private Map<String, Product> getProducts(IOperationMonitor monitor) throws BugzillaRestException { return retrieveItems(monitor, "/product?type=accessible", new TypeToken<ProductResponse>() { }); }
Source:
public void init(String name, Class<? extends ITmfEvent> type) { super.init(name); fType = type; fDataQueue = (fQueueSize > 1) ? new LinkedBlockingQueue<ITmfEvent>(fQueueSize) : new SynchronousQueue<ITmfEvent>(); fExecutor.init(); fSignalDepth = 0; synchronized (fLock) { START fTimer = new Timer(); END } TmfProviderManager.register(fType, this); } One of the constructors calls init() directly, so this could still create a thread at construction. Or are we sure that one is never called from "fake traces"? I think it'd be safer with the lazy-init that was done in the previous version. getTimer() and dispose() could both be synchronized (so it synchronizes on "this"), it doesn't really have anything to do with fLock.

Target:
public void init(String name, Class<? extends ITmfEvent> type) { super.init(name); fType = type; fExecutor.init(); fSignalDepth = 0; synchronized (fLock) { fTimer = new Timer(); } TmfProviderManager.register(fType, this); }
Source:
public void assumeShallow(Collection<? extends ObjectId> ids) throws IOException { if (!shallowCommitsInitialized) START initializeShallowCommits(); END for (ObjectId id : ids) lookupCommit(id).parents = RevCommit.NO_PARENTS; } I think handling fetches from a server that has its own shallow commits will take more work (see v1.9-rc0~3^2~17, "upload-pack: make sure deepening preserves shallow roots", 2013-12-05). Are the above two lines needed here?

Target:
public void assumeShallow(Collection<? extends ObjectId> ids) { for (ObjectId id : ids) lookupCommit(id).parents = RevCommit.NO_PARENTS; }
Source:
START protected RGB getBackground() { END return fDisplay.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(); } this should be private

Target:
private RGB getBackground() { return fDisplay.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(); }
Source:
protected void preHookCreateControlAndViewer() { fAdapterFactory = new ComposedAdapterFactory(EMFCompareRCPPlugin.getDefault() .getAdapterFactoryRegistry()); fAdapterFactory.addAdapterFactory(new TreeItemProviderAdapterFactorySpec()); fAdapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory()); fAdapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory()); getCompareConfiguration().setAdapterFactory(fAdapterFactory); START updateColors(); END inputChangedTask = new CompareInputChangedJob("Computing Model Differences"); } use ICompareColor instead, it will ease the maintenance

Target:
protected void preHookCreateControlAndViewer() { fAdapterFactory = new ComposedAdapterFactory(EMFCompareRCPPlugin.getDefault() .getAdapterFactoryRegistry()); fAdapterFactory.addAdapterFactory(new TreeItemProviderAdapterFactorySpec()); fAdapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory()); fAdapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory()); getCompareConfiguration().setAdapterFactory(fAdapterFactory); inputChangedTask = new CompareInputChangedJob("Computing Model Differences"); }
Source:
public DefaultDiffEngine() { START this.diffProcessor = new DiffBuilder(); END } call the other constructor and giving the diff builder instance in parameter

Target:
public DefaultDiffEngine() { this(new DiffBuilder()); }
Source:
START public Binding[] getBindings() { END Set<Binding> bindings = new HashSet<Binding>(); bindings.addAll(bindingService.getActiveBindings()); for (Binding binding : manager.getBindings()) { bindings.add(binding); } return bindings.toArray(new Binding[0]); } This probably isn't the place for modifying the list of bindings that can be seen. I would think that progammatically created bindings would have to be added to the model to survive

Target:
public Binding[] getBindings() { return manager.getBindings(); }
Source:
public List<IItemDescriptor<T>> getItemDescriptors() { ArrayList<IItemDescriptor<T>> descriptors = Lists.newArrayList(registry.values()); if (descriptors.size() > 0) { START Collections.sort(descriptors); END } return descriptors; } get this sort out of the getter

Target:
public List<IItemDescriptor<T>> getItemDescriptors() { return Lists.newArrayList(registry.values()); }
Source:
private void initPreferenceDefaults() { getPreferenceStore().setDefault(CHANGE_SET_MANAGE, true); getPreferenceStore().setDefault(COMMIT_TEMPLATE, DEFAULT_COMMIT_TEMPLATE); // 2.0M1 - 2.0M2 Default template migration if (getPreferenceStore().getString(COMMIT_TEMPLATE).equals(OLD_DEFAULT_COMMIT_TEMPLATE) || getPreferenceStore().getString(COMMIT_TEMPLATE).equals(OLD_DEFAULT_COMMIT_TEMPLATE2) START || getPreferenceStore().getString(COMMIT_TEMPLATE).equals(OLD_DEFAULT_COMMIT_TEMPLATE3)) { END getPreferenceStore().setValue(COMMIT_TEMPLATE, DEFAULT_COMMIT_TEMPLATE); } } Since we already have a bunch of old templates I would keep them in a list/set and check if it contains the template from pref store.

Target:
private void initPreferenceDefaults() { getPreferenceStore().setDefault(CHANGE_SET_MANAGE, true); getPreferenceStore().setDefault(COMMIT_TEMPLATE, DEFAULT_COMMIT_TEMPLATE); }
Source:
public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); START if (!(input instanceof FileEditorInput)) { END throw new PartInitException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Expected editor input to be of type FileEditorInput")); } FileEditorInput fileInput = ((FileEditorInput)input); if (fileInput != null) { source = fileInput.getFile(); } } This should occur before setInput(input);

Target:
public void init(IEditorSite site, IEditorInput input) throws PartInitException { if (!(input instanceof FileEditorInput)) { throw new PartInitException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Expected editor input to be of type FileEditorInput")); } setSite(site); setInput(input); FileEditorInput fileInput = ((FileEditorInput) input); if (fileInput != null) { source = fileInput.getFile(); } }
Source:
public NetRC(File netrc) { START this.netrc = netrc; END } shouldn't we call parse() here as well ?

Target:
public NetRC(File netrc) { this.netrc = netrc; parse(); }
Source:
public static void install() { START final NetRCCredentialsProvider c = new NetRCCredentialsProvider(); END CredentialsProvider.setDefault(c); } there is no need for this variable, instead inline this

Target:
public static void install() { CredentialsProvider.setDefault(new NetRCCredentialsProvider()); }
Source:
private boolean isSelected(EditPart part) { boolean result; START result = part != null && part.getSelected() == EditPart.SELECTED_PRIMARY || part.getSelected() == EditPart.SELECTED; END return result; } Introducing a local variable for this is not justified.

Target:
private boolean isSelected(EditPart part) { return part != null && part.getSelected() == EditPart.SELECTED_PRIMARY || part.getSelected() == EditPart.SELECTED; }
Source:
public static boolean isDynamicTabbar() { START return isJuno4Platform() || isKeplerPlatform(); END } Isn't this condition inverted? Juno and Kepler are the only versions for which we can *not* support the dynamic tabbar.

Target:
public static boolean isDynamicTabbar() { return !(isJuno4Platform() || isKeplerPlatform()); }
Source:
public TaskRepository repository() { START repository = new TaskRepository(getConnectorKind(), getRepositoryUrl()); END return repository; } The field should be removed as well.

Target:
public TaskRepository repository() { return new TaskRepository(getConnectorKind(), getRepositoryUrl()); }
Source:
public String getSelection() { START if (fSelection == null) { END return ""; } else { return fSelection; } } I think it's ok to return null here, looking at how the GerritTableView is handling the result.

Target:
public String getSelection() { return fSelection; }
Source:
public BugzillaRestTaskEditorPage(TaskEditor editor, String connectorKind) { super(editor, connectorKind); START setNeedsPrivateSection(false); END setNeedsSubmitButton(false); } Why do we set these false? It seems that we should set them true.

Target:
public BugzillaRestTaskEditorPage(TaskEditor editor, String connectorKind) { super(editor, connectorKind); setNeedsPrivateSection(true); setNeedsSubmitButton(true); }
Source:
public void traceOpened(TmfTraceOpenedSignal signal) { assert (signal != null); fTrace = signal.getTrace(); ITmfTrace[] traces = TmfTraceManager.getTraceSet(fTrace); if (traces != null) { this.showTraceAction.setEnabled(traces.length < fFullTraceHistogram.getMaxNbTraces()); START } END loadTrace(); } This needs to be done in traceSelected() below too. Maybe it's better to do it in initalizeHistogram() instead.

Target:
public void traceOpened(TmfTraceOpenedSignal signal) { assert (signal != null); fTrace = signal.getTrace(); loadTrace(); }
Source:
public CTFCallsite(String en, String func, long ip, String fn, long line) { fEventName = en; fFileName = fn; fFunctionName = func; START this.fIp = ip; END this.fLineNumber = line; } Let's remove 'this.' also below.

Target:
public CTFCallsite(String en, String func, long ip, String fn, long line) { fEventName = en; fFileName = fn; fFunctionName = func; fIp = ip; fLineNumber = line; }
Source:
protected T validateValueInternal(T rawValue) throws ProcessingException { T validValue; if (rawValue == null) { validValue = null; } else { START T t = TypeCastUtility.castValue(rawValue, getHolderType()); END IRadioButton b = getButtonFor(t); if (b != null) { validValue = t; } else { throw new ProcessingException("Illegal radio value: " + rawValue); } } return validValue; } there is no need for casting here

Target:
protected T validateValueInternal(T rawValue) throws ProcessingException { T validValue; if (rawValue == null) { validValue = null; } else { IRadioButton b = getButtonFor(rawValue); if (b != null) { validValue = rawValue; } else { throw new ProcessingException("Illegal radio value: " + rawValue); } } return validValue; }
Source:
public IRadioButton<T> getButtonFor(T value) { for (IRadioButton<T> b : getButtons()) { START T radioValue = TypeCastUtility.castValue(b.getRadioValue(), getHolderType()); END if (CompareUtility.equals(radioValue, value)) { return b; } } return null; } no need for casting here

Target:
public IRadioButton<T> getButtonFor(T value) { for (IRadioButton<T> b : getButtons()) { T radioValue = b.getRadioValue(); if (CompareUtility.equals(radioValue, value)) { return b; } } return null; }
Source:
protected void execLoad() throws ProcessingException { getResultTableField().getTable().setDefaultIconId(getContentAssistField().getBrowseIconId()); getActiveStateRadioButtonGroup().setVisible(getContentAssistField().isActiveFilterEnabled()); START getActiveStateRadioButtonGroup().setValue((TriState) getContentAssistField().getActiveFilter()); END getNewButton().setEnabled(getContentAssistField().getBrowseNewText() != null); getNewButton().setLabel(getContentAssistField().getBrowseNewText()); } remove unnecessary cast

Target:
protected void execLoad() throws ProcessingException { getResultTableField().getTable().setDefaultIconId(getContentAssistField().getBrowseIconId()); getActiveStateRadioButtonGroup().setVisible(getContentAssistField().isActiveFilterEnabled()); getActiveStateRadioButtonGroup().setValue(getContentAssistField().getActiveFilter()); getNewButton().setEnabled(getContentAssistField().getBrowseNewText() != null); getNewButton().setLabel(getContentAssistField().getBrowseNewText()); }
Source:
public EventDefinition(IEventDeclaration declaration, StreamInputReader streamInputReader) { START this.fDeclaration = declaration; END this.fStreamInputReader = streamInputReader; } Remove this. and the one below

Target:
public EventDefinition(IEventDeclaration declaration, StreamInputReader streamInputReader) { fDeclaration = declaration; fStreamInputReader = streamInputReader; }
Source:
public DeclarationScope(DeclarationScope parentScope) { START this.fParentScope = parentScope; END } remove this.

Target:
public DeclarationScope(DeclarationScope parentScope) { fParentScope = parentScope; }
Source:
public IOStructGen(CommonTree tree, CTFTrace trace) { START this.fTrace = trace; END this.fTree = tree; } Remove this. and the one below

Target:
public IOStructGen(CommonTree tree, CTFTrace trace) { fTrace = trace; fTree = tree; }
Source:
public ICPPASTAttributeSpecifier copy(CopyStyle style) { START ICPPASTAttributeSpecifier copy = copy(new CPPASTAttributeSpecifier(), style); END for (ICPPASTAttribute attribute : ArrayUtil.trim(attributes)){ copy.addAttribute(attribute.copy(style)); } return copy; } Slightly more efficient: CPPASTAttributeSpecifier copy = copy(new CPPASTAttributeSpecifier(), style); copy.attributes = ArrayUtil.trim(attributes); for (int i = 0; i < copy.attributes.length; i++) { copy.attributes[i] = copy.attributes[i].copy(style); } return copy;

Target:
public ICPPASTAttributeSpecifier copy(CopyStyle style) { CPPASTAttributeSpecifier copy = copy(new CPPASTAttributeSpecifier(), style); copy.attributes = ArrayUtil.trim(attributes, true); for (int i = 0; i < copy.attributes.length; i++) { copy.attributes[i] = copy.attributes[i].copy(style); } return copy; }
Source:
public void toggleStarred(String key, String value) { TaskAttribute taskAttribute = fTaskData.getRoot(); START taskAttribute.getAttribute(key).setValue(value); END // Update the Review Table setAttribute(key, value); } Could the attribute be null here?

Target:
public void toggleStarred(String key, String value) { if (key != null && value != null) { TaskAttribute taskAttribute = fTaskData.getRoot(); taskAttribute.getAttribute(key).setValue(value); // Update the Review Table setAttribute(key, value); } }
Source:
protected ArrayList<TaskAttribute> parseFromJson(InputStreamReader in) { START TypeToken<ArrayList<TaskAttribute>> END type = new TypeToken<ArrayList<TaskAttribute>>() { }; return new GsonBuilder().registerTypeAdapter(type.getType(), new JSonTaskDataDeserializer()) .setExclusionStrategies(exclustionStrategy) .create() .fromJson(in, type.getType()); } Should use List

Target:
protected ArrayList<TaskAttribute> parseFromJson(InputStreamReader in) { TypeToken<ArrayList<TaskAttribute>> type = new TypeToken<ArrayList<TaskAttribute>>() { }; return new GsonBuilder().registerTypeAdapter(type.getType(), new JSonTaskDataDeserializer()) .create() .fromJson(in, type.getType()); }
Source:
public InteractiveUIContent build() { if (isSimple) { // If simple only one element check at a time START Preconditions.checkArgument(defaultCheck == null || defaultCheck.size() == 1); END } boolean hasConfiguration = configurationUIRegistry != null; if (hasConfiguration) { // If has a configuration composite then the key to retreive te preference shall be set up. Preconditions.checkArgument(configurationNodeKey != null); } final InteractiveUIContent interactiveUI = new InteractiveUIContent(parent, hasDescription, hasConfiguration); CheckboxTableViewer descriptorViewer = createViewer(interactiveUI); if (hasConfiguration) { createConfigurationComposite(interactiveUI); } // Filter input with input with higher rank than default item descriptor setViewerInput(descriptorViewer); // Init and bind data bindAndInit(interactiveUI, descriptorViewer); return interactiveUI; } Change this whole if to Preconditions.checkArgument(!isSimple || defaultCheck == null || defaultCheck.size() == 1)

Target:
public InteractiveUIContent build() { // If simple only one element check at a time Preconditions.checkArgument(!isSimple || defaultCheck == null || defaultCheck.size() == 1); boolean hasConfiguration = configurationUIRegistry != null; // If has a configuration composite then the key to retrieve the preference must be set up. Preconditions.checkArgument(!hasConfiguration || configurationNodeKey != null); final InteractiveUIContent interactiveUI = new InteractiveUIContent(parent, hasDescription, hasConfiguration); CheckboxTableViewer descriptorViewer = createViewer(interactiveUI); if (hasConfiguration) { createConfigurationComposite(interactiveUI); } setViewerInput(descriptorViewer); // Init and bind data bindAndInit(interactiveUI, descriptorViewer); return interactiveUI; }
Source:
public static void closeView(String title, SWTWorkbenchBot bot) { START final List<SWTBotView> openViews = bot.views(); END for (SWTBotView view : openViews) { if (view.getTitle().toLowerCase().equals(title.toLowerCase())) { view.close(); bot.waitUntil(ConditionHelpers.ViewIsClosed(view)); } } } can bot.viewByTitle be used instead of looping?

Target:
public static void closeView(String title, SWTWorkbenchBot bot) { final List<SWTBotView> openViews = bot.views(); for (SWTBotView view : openViews) { if (view.getTitle().equalsIgnoreCase(title)) { view.close(); bot.waitUntil(ConditionHelpers.ViewIsClosed(view)); } } }
Source:
public static String execWithFile(String filename) { try (BufferedReader br = new BufferedReader(new FileReader(filename))) { StringBuffer buffer = new StringBuffer(); String line; while ((line = br.readLine()) != null) { buffer.append(line.concat("\n")); //$NON-NLS-1$ } return exec(buffer.toString()); } catch (IOException e) { START e.printStackTrace(); END return ""; //$NON-NLS-1$ } } Please don't print stack trace like that. Either log it properly or ignore if the information is useless.

Target:
public static String execWithFile(String filename) { try (BufferedReader br = new BufferedReader(new FileReader(filename))) { StringBuffer buffer = new StringBuffer(); String line; while ((line = br.readLine()) != null) { buffer.append(line.concat("\n")); //$NON-NLS-1$ } return exec(buffer.toString()); } catch (IOException e) { return ""; //$NON-NLS-1$ } }
Source:
START public static void registerModuleSource(IAnalysisModuleSource source) { END synchronized (fSources) { fSources.add(source); refreshModules(); } } This needs to be synchronized because of fSources

Target:
public static synchronized void registerModuleSource(IAnalysisModuleSource source) { fSources.add(source); refreshModules(); }
Source:
START public static Map<String, IAnalysisModuleHelper> getAnalysisModules() { END synchronized (fAnalysisModules) { if (fAnalysisModules.isEmpty()) { for (IAnalysisModuleSource source : fSources) { for (IAnalysisModuleHelper helper : source.getAnalysisModules()) { fAnalysisModules.put(helper.getId(), helper); } } } } return Collections.unmodifiableMap(fAnalysisModules); } This needs to be synchronized because of fSources / registerModuleSource / initialize

Target:
public static synchronized Map<String, IAnalysisModuleHelper> getAnalysisModules() { if (fAnalysisModules.isEmpty()) { for (IAnalysisModuleSource source : fSources) { for (IAnalysisModuleHelper helper : source.getAnalysisModules()) { fAnalysisModules.put(helper.getId(), helper); } } } return Collections.unmodifiableMap(fAnalysisModules); }
Source:
public void sortingShouldWorkForEasyStrings() { assertSortedLike("", ""); assertSortedLike("", "a"); assertSortedLike("a", "asdf"); assertSortedLike("aaa", "bbb"); assertSortedLike("1", "2"); START assertEquals(0, cmp("", "")); END assertEquals(0, cmp("a", "a")); assertTrue(cmp("", "a") < 0); assertTrue(cmp("a", "") > 0); } Consider moving these assertions to separate method.

Target:
public void sortingShouldWorkForEasyStrings() { assertSortedLike("", ""); assertSortedLike("", "a"); assertSortedLike("a", "asdf"); assertSortedLike("aaa", "bbb"); assertSortedLike("1", "2"); }
Source:
private boolean isDotGit(byte[] buf, int p) { START if (ignoreCase || windows) END return toLower(buf[p]) == 'g' && toLower(buf[p + 1]) == 'i' && toLower(buf[p + 2]) == 't'; return buf[p] == 'g' && buf[p + 1] == 'i' && buf[p + 2] == 't'; } Not needed, since windows implies ignoreCase (unless someone has explicitly chosen to setIgnoreCase(false) after setSafeForWindows(true)).

Target:
private boolean isDotGit(byte[] buf, int p) { if (windows) return toLower(buf[p]) == 'g' && toLower(buf[p + 1]) == 'i' && toLower(buf[p + 2]) == 't'; return buf[p] == 'g' && buf[p + 1] == 'i' && buf[p + 2] == 't'; }
Source:
void sendSelection (long /*int*/ id, long /*int*/ sel, long /*int*/ arg) { panel.validateVisibleColumns(); START if (filterExtensions.length > 0){ END setAllowedFileType(filterExtensions[(int)/*64*/popup.indexOfSelectedItem()]); } } - add single space before '{'

Target:
void sendSelection (long /*int*/ id, long /*int*/ sel, long /*int*/ arg) { panel.validateVisibleColumns(); if (filterExtensions != null && filterExtensions.length > 0) { setAllowedFileType(filterExtensions[(int)/*64*/popup.indexOfSelectedItem()]); } }
Source:
public void dispose() { START super.dispose(); END if (control != null) { control.dispose(); } } You'd probably dispose your stuff, and call super.dispose() at the end.

Target:
public void dispose() { if (control != null) { control.dispose(); } super.dispose(); }
Source:
protected PatchLineComment execute(GerritClient client, IProgressMonitor monitor) throws GerritException { START return client.saveDraft(getPatchKey(), getMessage(), getLine(), getSide(), getParentUuid(), monitor, getUuid()); END } By convention if there is a monitor being passed, it's always the last param.

Target:
protected PatchLineComment execute(GerritClient client, IProgressMonitor monitor) throws GerritException { return client.saveDraft(getPatchKey(), getMessage(), getLine(), getSide(), getParentUuid(), getUuid(), monitor); }
Source:
private boolean isWindowPlatform() { START if (Platform.getOS().equals(Platform.WS_WIN32)) { END return true; } return false; } return Platform.getOS().equals(Platform.WS_WIN32)

Target:
private boolean isWindowPlatform() { return Platform.getOS().equals(Platform.WS_WIN32); }
Source:
public static ReviewCompareAnnotationSupport getAnnotationSupport(Viewer contentViewer) { ReviewCompareAnnotationSupport support = (ReviewCompareAnnotationSupport) contentViewer.getData(KEY_ANNOTAION_SUPPORT); if (support == null) { START if (support == null) { END support = new ReviewCompareAnnotationSupport(contentViewer); contentViewer.setData(KEY_ANNOTAION_SUPPORT, support); } } return support; } Making *really* sure it's null? ;)

Target:
public static ReviewCompareAnnotationSupport getAnnotationSupport(Viewer contentViewer) { ReviewCompareAnnotationSupport support = (ReviewCompareAnnotationSupport) contentViewer.getData(KEY_ANNOTAION_SUPPORT); if (support == null) { support = new ReviewCompareAnnotationSupport(contentViewer); contentViewer.setData(KEY_ANNOTAION_SUPPORT, support); } return support; }
Source:
public void addStream(long id, File streamFile) throws CTFReaderException { if (!fStreams.containsKey(id)) { fStreams.put(id, new Stream(this)); } START Stream stream = fStreams.get(id); END stream.addInput(new StreamInput(stream, streamFile)); } minor thing, but in the case where you go inside the if, you could keep a reference to the "new Stream", so you do not need to do a map lookup in that case.

Target:
public void addStream(long id, File streamFile) throws CTFReaderException { Stream stream = null; if (fStreams.containsKey(id)) { stream = fStreams.get(id); } else { stream = new Stream(this); fStreams.put(id, stream); } stream.addInput(new StreamInput(stream, streamFile)); }
Source:
public void setSessionId(long sessionId) { START this.fSessionId = sessionId; END } remote this

Target:
public void setSessionId(long sessionId) { fSessionId = sessionId; }
Source:
public void setSeek(SeekCommand seekCommand) { START this.fSeek = seekCommand; END } remove this

Target:
public void setSeek(SeekCommand seekCommand) { fSeek = seekCommand; }
Source:
public void handleData(final @Nullable ITmfEvent event) { super.handleData(event); if (event != null && event.getTrace() != trace) { START System.out.println("alld"); //$NON-NLS-1$ END } if (event != null && event.getTrace() == trace) { sci.processEvent(event); } } I guess this is the WIP part...

Target:
public void handleData(final @Nullable ITmfEvent event) { super.handleData(event); if (event != null && event.getTrace() == trace) { sci.processEvent(event); } }
Source:
START int findItemIndex(ITimeGraphEntry entry) { END Item item = fItemMap.get(entry); if (item == null) { return -1; } return item.fExpandedIndex; } should have public modifier, for consistency.

Target:
public int findItemIndex(ITimeGraphEntry entry) { Item item = fItemMap.get(entry); if (item == null) { return -1; } return item.fExpandedIndex; }
Source:
public EditCommitOperation(Repository repository, RevCommit commit) { START if (commit.getParentCount() != 1) { END throw new UnsupportedOperationException( "commit is expected to have exactly one parent"); //$NON-NLS-1$ } this.repository = repository; this.commit = commit; } no braces around single line block

Target:
public EditCommitOperation(Repository repository, RevCommit commit) { if (commit.getParentCount() != 1) throw new UnsupportedOperationException( "commit is expected to have exactly one parent"); //$NON-NLS-1$ this.repository = repository; this.commit = commit; }
Source:
public void contextDisposed() { START super.contextDisposed(); END eventBroker.unsubscribe(itemUpdater); eventBroker.unsubscribe(selectionUpdater); eventBroker.unsubscribe(enabledUpdater); eventBroker.unsubscribe(toBeRenderedUpdater); eventBroker.unsubscribe(childAdditionUpdater); } Should probably be at the end of the method.

Target:
public void contextDisposed() { eventBroker.unsubscribe(itemUpdater); eventBroker.unsubscribe(selectionUpdater); eventBroker.unsubscribe(enabledUpdater); eventBroker.unsubscribe(toBeRenderedUpdater); eventBroker.unsubscribe(childAdditionUpdater); super.contextDisposed(); }
Source:
public void testAddNull() { registry.add(null); START assertTrue(registry.getItemDescriptors().isEmpty()); END } remove this assertion, since it will never be reached.

Target:
public void testAddNull() { registry.add(null); }
Source:
public void removeCompareInputChangeListener(ICompareInputChangeListener listener) { START if (containsListener(listener)) { END listeners.remove(listener); } } No use checking if the list contains() before remove(), let's avoid double iterations.

Target:
public void removeCompareInputChangeListener(ICompareInputChangeListener listener) { listeners.remove(listener); }
Source:
public String getNamespaceURI() { if (namespaceURI == null) { namespaceURI = ClassUtils.getPackageName(getNativeWidget() .getClass()); } START System.err.println(namespaceURI); END return namespaceURI; } We should remove syserrs

Target:
public String getNamespaceURI() { if (namespaceURI == null) { namespaceURI = ClassUtils.getPackageName(getNativeWidget() .getClass()); } return namespaceURI; }
Source:
public void addSubAttribute(Attribute newSubAttribute) { /* This should catch buggy state changing statements */ if (newSubAttribute == null || newSubAttribute.getName() == null || START newSubAttribute.getName().equals(this.getName())) { END throw new IllegalArgumentException(); } subAttributes.put(newSubAttribute.getName(), newSubAttribute); } That 3rd one is a weird condition: I cannot add an attribute "0" (the tid) as a subattribute of "0" (the cpu) it throws this exception. Since the asserts did do nothing, I never noticed before.

Target:
public void addSubAttribute(Attribute newSubAttribute) { if (newSubAttribute == null || newSubAttribute.getName() == null) { throw new IllegalArgumentException(); } subAttributes.put(newSubAttribute.getName(), newSubAttribute); }
Source:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { START List<TmfAnalysisRequirement> requirements = new ArrayList<>(); END AnalysisRequirementFactory factory = new AnalysisRequirementFactory(); switch (fModule) { case TEST: requirements.add(factory.getRequirement1()); requirements.add(factory.getRequirement3()); break; case TESTCTF: requirements.add(factory.getRequirement2()); requirements.add(factory.getRequirement3()); break; default: break; } return requirements; } Here a Set could be used instead of ArrayList

Target:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { Set<TmfAnalysisRequirement> requirements = new HashSet<>(); AnalysisRequirementFactory factory = new AnalysisRequirementFactory(); switch (fModule) { case TEST: requirements.add(factory.getRequirement1()); requirements.add(factory.getRequirement3()); break; case TESTCTF: requirements.add(factory.getRequirement2()); requirements.add(factory.getRequirement3()); break; default: break; } return requirements; }
Source:
public int getLength() { Widget widget = getWidget(); int childCount = 0; if (widget instanceof Composite) { childCount = ((Composite) widget).getChildren().length; if (widget instanceof CTabFolder) { // if it's a CTabFolder, include the child items in the count for (CTabItem tabItem : ((CTabFolder) widget).getItems()) { if (tabItem.isDisposed()) { // widget (CTabFolder) is internaly marked as inDispose // It has disposed the CTabItem, but has not taken it out of the items array. // Do not return disposed items to the css engine // TODO: When as to why CTabFolderElement is even getting called is solved, we can remove this guard. START System.err.println("CTabItem was disposed"); END break; } else { childCount++; } } } } return childCount; } The syserr should come out.

Target:
public int getLength() { Widget widget = getWidget(); int childCount = 0; if (widget instanceof Composite) { childCount = ((Composite) widget).getChildren().length; if (widget instanceof CTabFolder) { // if it's a CTabFolder, include the child items in the count for (CTabItem tabItem : ((CTabFolder) widget).getItems()) { if (tabItem.isDisposed()) { // THIS IS A WORKAROUND // widget (CTabFolder) is internaly marked as inDispose // It has disposed the CTabItem, but has not taken it out of the items array. // Do not return disposed items to the css engine break; } else { childCount++; } } } } return childCount; }
Source:
Project(String name, String path, String groups) { this.name = name; this.path = path; this.groups = new HashSet<String>(); START if (groups != null && groups.length() > 0) { END this.groups.addAll(Arrays.asList(groups.split(","))); } } we don't use braces around single line blocks

Target:
Project(String name, String path, String groups) { this.name = name; this.path = path; this.groups = new HashSet<String>(); if (groups != null && groups.length() > 0) this.groups.addAll(Arrays.asList(groups.split(","))); //$NON-NLS-1$ }
Source:
void copy() throws IOException { FileInputStream input = new FileInputStream(src); FileOutputStream output = new FileOutputStream(dest); try { FileChannel channel = input.getChannel(); output.getChannel().transferFrom(channel, 0, channel.size()); START } finally { input.close(); output.close(); } END } Actually you need two levels of try/finally here as the input should be closed if the FileOutputStream fails to create.

Target:
void copy() throws IOException { FileInputStream input = new FileInputStream(src); try { FileOutputStream output = new FileOutputStream(dest); try { FileChannel channel = input.getChannel(); output.getChannel().transferFrom(channel, 0, channel.size()); } finally { output.close(); } } finally { input.close(); } }
Source:
void copy() throws IOException { FileInputStream input = new FileInputStream(src); FileOutputStream output = new FileOutputStream(dest); START FileChannel channel = input.getChannel(); output.getChannel().transferFrom(channel, 0, channel.size()); input.close(); output.close(); END } Wrap with try/finally to ensure the streams are closed in case of failure.

Target:
void copy() throws IOException { FileInputStream input = new FileInputStream(src); FileOutputStream output = new FileOutputStream(dest); try { FileChannel channel = input.getChannel(); output.getChannel().transferFrom(channel, 0, channel.size()); } finally { input.close(); output.close(); } }
Source:
private static Map<String, String> getMergedEnvironment(LaunchConfiguration configuration) throws IOException { START Map<String, String> currentEnv = new HashMap<String, String>(EnvironmentUtils.getProcEnvironment()); END currentEnv.putAll(configuration.getEnvironment()); return currentEnv; } Does order matter here?

Target:
private static Map<String, String> getMergedEnvironment(LaunchConfiguration configuration) throws IOException { Map<String, String> currentEnv = EnvironmentUtils.getProcEnvironment(); currentEnv.putAll(configuration.getEnvironment()); return currentEnv; }
Source:
START public Version getVersion() { END return version; } I think we should still return a string here.

Target:
public String getVersion() { return version; }
Source:
public boolean isNewerJenkinsServer() { START return Type.JENKINS.equals(type) && HudsonServerInfo.JENKINS_1_511.compareTo(version) < 0; END } No need to qualify the access to JENKINS_1_511 with the type name.

Target:
public boolean isNewerJenkinsServer() { return Type.JENKINS.equals(type) && JENKINS_1_511.compareTo(version) < 0; }
Source:
private static PrintStream printTime(long start, long end) { START return System.out.format(", %.3f", 0.000000001 * (end - start)); END } You could add a text here to show what the output means. You probably know, but me running this benchmark, I'd need something more verbose ;-)

Target:
private static void printTime(long start, long end) { /* print out the difference between the two nanosecond times in ms */ System.out.format(", %.3f", 0.000000001 * (end - start)); }
Source:
boolean add(RevFlag flag) { if (sourceCommit.has(flag)) return false; START else { END sourceCommit.add(flag); return true; } } style nit: use the early return above to avoid the need for else here for the two statements in the else case.

Target:
boolean add(RevFlag flag) { if (sourceCommit.has(flag)) return false; sourceCommit.add(flag); return true; }
Source:
public Response getDispoItemsByIdJson(@PathParam("itemId") String itemId) { Response response; DispoItem result = dispoApi.getDispoItemById(program, itemId); if (result == null) { response = Response.status(Response.Status.NOT_FOUND).entity(DispoMessages.Item_NotFound).build(); } else { START response = Response.status(Response.Status.OK).entity(DispoUtil.itemArtToItemData(result)).build(); END } return response; } should this be part of a different commit?

Target:
public Response getDispoItemsByIdJson(@PathParam("itemId") String itemId) { Response response; DispoItem result = dispoApi.getDispoItemById(program, itemId); if (result == null) { response = Response.status(Response.Status.NOT_FOUND).entity(DispoMessages.Item_NotFound).build(); } else { response = Response.status(Response.Status.OK).entity(result).build(); } return response; }
Source:
public DefaultInterpretedExpressionTargetSwitch(EStructuralFeature feature, IInterpretedExpressionTargetSwitch globalSwitch) { IInterpretedExpressionTargetSwitch theGlobalSwitch = Objects.firstNonNull(globalSwitch, this); START this.firstRelevantContainerFinder = new FirstRelevantContainerDefaultFunction(); END this.descriptionSwitch = new DescriptionInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.styleSwitch = new StyleInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.toolSwitch = new ToolInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.validationSwitch = new ValidationInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); } We should remove the field and directly create the function in the getFirstRelevantContainer method.

Target:
public DefaultInterpretedExpressionTargetSwitch(EStructuralFeature feature, IInterpretedExpressionTargetSwitch globalSwitch) { IInterpretedExpressionTargetSwitch theGlobalSwitch = Objects.firstNonNull(globalSwitch, this); this.descriptionSwitch = new DescriptionInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.styleSwitch = new StyleInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.toolSwitch = new ToolInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.validationSwitch = new ValidationInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); }
Source:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { try { (new BugzillaXmlRpcOperation<Integer>(this) { @Override public Integer execute() throws XmlRpcException { call(monitor, XML_USER_LOGOUT); return -1; } }).execute(); START } catch (XmlRpcException e) { END e.printStackTrace(); throw e; } finally { userID = -1; token = null; } return; } I don't think we should have a catch block if we're just going to rethrow the exception.

Target:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { try { (new BugzillaXmlRpcOperation<Integer>(this) { @Override public Integer execute() throws XmlRpcException { call(monitor, XML_USER_LOGOUT); return -1; } }).execute(); } finally { userID = -1; token = null; } return; }
Source:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { userID = -1; token = null; (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { try { START bugzillaClient.authenticate(null); END } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); return; } It seems to call authenticate when logging out. Also, why not pass the monitor?

Target:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { userID = -1; token = null; (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { try { bugzillaClient.authenticate(monitor); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); return; }
Source:
START public static boolean isZippedContent(byte[] bin) { END return bin.length > 4 && bin[0] == 'P' && bin[1] == 'K' && bin[2] == 3 && bin[3] == 4; } Is null possible to be passed here?

Target:
public static boolean isZippedContent(byte[] bin) { return bin != null && bin.length > 4 && bin[0] == 'P' && bin[1] == 'K' && bin[2] == 3 && bin[3] == 4; }