auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static AccountCollection all(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { START return request(RequestMethod.GET, classURL(Account.class), params, AccountCollection.class, (RequestOptions) null); END } This should call all ``` java return all(params, (RequestOptions) null); ```

Target:
public static AccountCollection all(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return all(params, (RequestOptions) null); }
Source:
public void onSaveClick() { editView.setSaveState(true); WikidataDescriptionEditDataClient client = new WikidataDescriptionEditDataClient(); START client.submitDescription(pageTitle, editView.getDescription(), END new WikidataDescriptionEditDataClient.Callback() { @Override public void success() { editView.setSaveState(false); L.i("WD description edit successful"); // TODO: go to success fragment } @Override public void failure(@NonNull Throwable caught) { editView.setSaveState(false); L.e("WD description edit failed: ", caught); // TODO: go to failure fragment } }); } Since this is a Fragment with a lifecycle, consider holding a reference to Call<?> and canceling it in onDestroy() if Call<?> is nonnull.

Target:
public void onSaveClick() { editView.setSaveState(true); if (client == null) { client = new WikidataDescriptionEditDataClient(); } client.request(pageTitle, editView.getDescription(), new WikidataDescriptionEditDataClient.Callback() { @Override public void success() { editView.setSaveState(false); L.i("WD description edit successful"); // TODO: go to success fragment } @Override public void failure(@NonNull Throwable caught) { editView.setSaveState(false); L.e("WD description edit failed: ", caught); // TODO: go to failure fragment } }); }
Source:
protected ResourceSet loadResource(IEditorInput editorInput) { START final URI resourceURI = EditUIUtil.getURI(getEditorInput(), null); END return ResourceSetHelpers.loadResourceSetWithProxies(resourceURI, getCommandStack()); } why not use the passed in editorInput

Target:
protected ResourceSet loadResource(IEditorInput editorInput) { final URI resourceURI = EditUIUtil.getURI(editorInput, null); return ResourceSetHelpers.loadResourceSetWithProxies(resourceURI, getCommandStack()); }
Source:
FileReftableStack.CompactionStats getCompactionStats() START throws IOException { END return reftableStack.getStats(); } declared exception isn't thrown

Target:
FileReftableStack.CompactionStats getCompactionStats() { return reftableStack.getStats(); }
Source:
public OnlineBackup incremental( String targetDirectory ) { outcome = new BackupService().doIncrementalBackup( hostNameOrIp, port, new File( targetDirectory ), START getConsistencyCheck( true ), timeoutMillis, defaultConfig() ); END return this; } This changes default behaviour, right? Should it?

Target:
public OnlineBackup incremental( String targetDirectory ) { outcome = new BackupService().doIncrementalBackup( hostNameOrIp, port, new File( targetDirectory ), getConsistencyCheck( false ), timeoutMillis, defaultConfig() ); return this; }
Source:
private boolean isValidConfiguration() { if (isDiscarding() || isCalleeData()) { return isAsync(); } else { return true; START } END } This could just be `return !(isDiscarding() || isCalleeData()) || isAsync();`

Target:
private boolean isValidConfiguration() { return !(isDiscarding() || isCalleeData()) || isAsync(); }
Source:
public boolean setTrace(@NonNull ITmfTrace trace) throws TmfAnalysisException { boolean ret = super.setTrace(trace); if (!ret) { return ret; } ret = fCriticalPathModule.setTrace(trace); START fCriticalPathModule.setParameter(CriticalPathModule.PARAM_GRAPH, getId()); END return ret; } should this be set if ret is false? I don't know.

Target:
public boolean setTrace(@NonNull ITmfTrace trace) throws TmfAnalysisException { boolean ret = super.setTrace(trace); if (!ret) { return ret; } ret = fCriticalPathModule.setTrace(trace); if (ret) { fCriticalPathModule.setParameter(CriticalPathModule.PARAM_GRAPH, getId()); } return ret; }
Source:
public void fillContextMenu(final IMenuManager menu) { super.fillContextMenu(menu); final ISelection selection = getContext().getSelection(); if (selection.isEmpty()) { return; } // Wait the end of the loading of the representations file try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { START throw new RuntimeException(e); END } // Differents behavior between win and linux : windows will not // display contextual menu if busy cursor while dialog is shown. // Fill the context menu contextMenuFiller.fillContextMenu(menu, selection); } Before, with waitOtherJobs, we "Do nothing" in case of InterruptedException. Why do you change that? Have you test the difference?

Target:
public void fillContextMenu(final IMenuManager menu) { super.fillContextMenu(menu); final ISelection selection = getContext().getSelection(); if (selection.isEmpty()) { return; } // Wait the end of the loading of the representations file try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { // Do nothing } // Differents behavior between win and linux : windows will not // display contextual menu if busy cursor while dialog is shown. // Fill the context menu contextMenuFiller.fillContextMenu(menu, selection); }
Source:
public void dispose() { // run super. super.dispose(); // remove ourselves as a selection and registry listener getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); SaveablesList saveables = START (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); END if (saveables != null) { saveables.removeModelLifecycleListener(saveablesTracker); } currentPart = null; currentSelection = null; pinPropertySheetAction = null; } Are you sure about that cast operation? You are asking for a service interface and cast it to a concrete implementation without instanceof check. You perform that check in the tracker that is only added to a SaveablesList.

Target:
public void dispose() { // run super. super.dispose(); // remove ourselves as a selection and registry listener getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); ISaveablesLifecycleListener saveables = getSite().getService(ISaveablesLifecycleListener.class); if (saveables instanceof SaveablesList) { ((SaveablesList) saveables).removeModelLifecycleListener(saveablesTracker); } currentPart = null; currentSelection = null; pinPropertySheetAction = null; }
Source:
public void setBaseballCard(BaseballCard card) { Locale locale = Locale.getDefault(); brand.setText(card.brand); year.setText(String.format(locale, "%d", card.year)); START number.setText(String.format(locale, "%s", card.number)); END player.setText(card.playerName); } `String.format()` is no longer necessary here.

Target:
public void setBaseballCard(BaseballCard card) { Locale locale = Locale.getDefault(); brand.setText(card.brand); year.setText(String.format(locale, "%d", card.year)); number.setText(card.number); player.setText(card.playerName); }
Source:
START private String capitalize(String word) { END return Character.toUpperCase(word.charAt(0)) + word.substring(1); } Can be static

Target:
private static String capitalize(String word) { return Character.toUpperCase(word.charAt(0)) + word.substring(1); }
Source:
START private static boolean isStringParameter( END @NonNull Expression expression, @NonNull JavaContext context) { if (expression instanceof StringLiteral) { return true; } else { JavaParser.ResolvedNode resolvedNode = context.resolve(expression); if (resolvedNode instanceof JavaParser.ResolvedField) { if (((JavaParser.ResolvedField) resolvedNode).getValue() instanceof String) { return true; } } } return false; } instead of this, use (at the callsite where you have the JavaContext) TypeDescriptor type = context.getType(expression); return type != null && type.matchesSignature(JavaContext.TYPE_STRING);

Target:
private static boolean isStringParameter( @NonNull Expression expression, @NonNull JavaContext context) { if (expression instanceof StringLiteral) { return true; } else { ResolvedNode resolvedNode = context.resolve(expression); if (resolvedNode instanceof ResolvedField) { if (((ResolvedField) resolvedNode).getValue() instanceof String) { return true; } } } return false; }
Source:
protected double getScore(double availableCpu, double availableMemory, Map<String, Double> availableGenericResources) { START TopologyDetails td = getNextHighest(); END return getScore(availableCpu, availableMemory, availableGenericResources, td); } Nit: could we inline this to avoid unnecessary object creation

Target:
protected double getScore(double availableCpu, double availableMemory, Map<String, Double> availableGenericResources) { return getScore(availableCpu, availableMemory, availableGenericResources, getNextHighest()); }
Source:
public <T extends Action> List<T> getActions(Class<T> type) { START List<T> _actions = Util.filter(getPersistedActions(), type); END for (TransientActionFactory<?> taf : TransientActionFactory.factoriesFor(getClass(), type)) { _actions.addAll(Util.filter(createFor(taf), type)); } return Collections.unmodifiableList(_actions); } I think this should be reverted, so it would still take into account additions from pre-`TransientActionFactory` implementations.

Target:
public <T extends Action> List<T> getActions(Class<T> type) { List<T> _actions = Util.filter(getActions(), type); for (TransientActionFactory<?> taf : TransientActionFactory.factoriesFor(getClass(), type)) { _actions.addAll(Util.filter(createFor(taf), type)); } return Collections.unmodifiableList(_actions); }
Source:
public void addRepresentation (ImageData srcImageData, int zoom) { if (srcImageData == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); int imageSelectorIndex = DPIUtil.mapZoomToImageSelectorIndex(zoom); if (imageSelectorIndex == device.getImageSelector ()) { init(srcImageData); START init(); END } else { data [imageSelectorIndex] = srcImageData; } } ImageData for current image needs to be updated in the array?

Target:
public void addRepresentation (ImageData srcImageData, int zoom) { if (srcImageData == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); int imageSelectorIndex = DPIUtil.mapZoomToImageSelectorIndex(zoom); if (imageSelectorIndex == getImageSelector ()) { init(srcImageData); init(); } data [imageSelectorIndex] = srcImageData; }
Source:
private DefaultEnvironment buildEnvironment(EnvironmentType environmentType) { DefaultEnvironment defaultEnvironment = new DefaultEnvironment(environmentType); START defaultEnvironment.setup(); END return defaultEnvironment; } you don't need to do that if you're already calling `loadProperties` in the public constructor, right? https://github.com/caelum/vraptor4/pull/973/files#diff-b7b62c45c7478eb642acfb81c12a4227R82

Target:
private DefaultEnvironment buildEnvironment(EnvironmentType environmentType) { DefaultEnvironment defaultEnvironment = new DefaultEnvironment(environmentType); return defaultEnvironment; }
Source:
public int hashCode() { START return getRepositoryName() != null ? getRepositoryName().hashCode() : END System.identityHashCode(this); } Style-nit: This is hard to read. Maybe: if (getRepositoryName() != null) return getRepositoryName().hashCode(); return System.identityHashCode(this);

Target:
public int hashCode() { if (getRepositoryName() != null) return getRepositoryName().hashCode(); return System.identityHashCode(this); }
Source:
public List<String> getExtensions() { START return extensions == null ? DEFAULT_EXTS : extensions; END } Can be removed and return only extensions without assigning logic.

Target:
public List<String> getExtensions() { return extensions; }
Source:
public List<RadiologyOrder> getRadiologyOrdersByPatient(Patient patient) { Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatient(radiologyOrderCriteria, patient); START List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); END return result == null ? new ArrayList<RadiologyOrder>() : result; } use final

Target:
public List<RadiologyOrder> getRadiologyOrdersByPatient(Patient patient) { Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatient(radiologyOrderCriteria, patient); final List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); return result == null ? new ArrayList<RadiologyOrder>() : result; }
Source:
public Weld addExtensions(Class<? extends Extension>... extensionClasses) { START Object[] constructorParams = new Object[] {}; END for (Class<? extends Extension> extensionClass : extensionClasses) { try { Extension extension = SecurityActions.newInstance(extensionClass); addExtension(extension); } catch (Exception ex) { CommonLogger.LOG.unableToInstantiate(extensionClass, constructorParams, ex); } } return this; } This variable is useless in most cases. I would rather pass `new Object[] {}` to log method directly.

Target:
public Weld addExtensions(Class<? extends Extension>... extensionClasses) { for (Class<? extends Extension> extensionClass : extensionClasses) { try { Extension extension = SecurityActions.newInstance(extensionClass); addExtension(extension); } catch (Exception ex) { CommonLogger.LOG.unableToInstantiate(extensionClass, new Object[] {}, ex); } } return this; }
Source:
public RTTestsParser() { super(Messages._Warnings_RTTests_ParserName(), Messages._Warnings_RTTests_LinkName(), Messages._Warnings_RTTests_TrendName(), START CYCLICTEST_WARNING_PATTERN, true); END } If the last parameter is `true` then you need to overwrite `isLineInteresting`.

Target:
public RTTestsParser() { super(Messages._Warnings_RTTests_ParserName(), Messages._Warnings_RTTests_LinkName(), Messages._Warnings_RTTests_TrendName(), CYCLICTEST_WARNING_PATTERN); }
Source:
private ValidationResult hostExists() { START if (getVds() == null) { END return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST); } return ValidationResult.VALID; } You could use ternary if for this: return getVds() == null ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST) : ValidationResult.VALID;

Target:
private ValidationResult hostExists() { return getVds() == null ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST) : ValidationResult.VALID; }
Source:
public static ToolTipString fromString(String text) { START Objects.requireNonNull(text, "fromString cannot take null"); //$NON-NLS-1$ END return new ToolTipString(text, toHtmlString(text)); } You can remove all the requireNonNull due to @NNBD. I'm surprised we're allowed to use it, doing an explicit null check would be a compilation error...

Target:
public static ToolTipString fromString(String text) { return new ToolTipString(text, toHtmlString(text)); }
Source:
public DataRadioStation getNextById(String id) { START if (listStations.size() == 0) END return null; for (int i = 0; i < listStations.size() - 1; i++) { if (listStations.get(i).ID.equals(id)) { return listStations.get(i + 1); } } return listStations.get(0); } `if (listStations.isEmpty())`

Target:
public DataRadioStation getNextById(String id) { if (listStations.isEmpty()) return null; for (int i = 0; i < listStations.size() - 1; i++) { if (listStations.get(i).ID.equals(id)) { return listStations.get(i + 1); } } return listStations.get(0); }
Source:
public static void setBiomeArrayMethod(boolean jeidPresent) { try { if (jeidPresent) { biomeArrayMethod = Chunk.class.getMethod("getIntBiomeArray"); } else START biomeArrayMethod = Chunk.class.getMethod("getBiomeArray"); END } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } Please add the `{}` for the one-liner

Target:
public static void setBiomeArrayMethod(boolean jeidPresent) { try { if (jeidPresent) { biomeArrayMethod = Chunk.class.getMethod("getIntBiomeArray"); } else { biomeArrayMethod = Chunk.class.getMethod("getBiomeArray"); } } catch (NoSuchMethodException e) { throw new RuntimeException(e); } }
Source:
public String getDescription() { return "Transform files representing a structured table under an Alluxio directory." + "\n\n" + "Files are coalesced and converted to parquet format." + "\n\n" + "Definition is in format like 'write(hive).option(hive.num.files, 100)'," + "currently, the only modification you can do to the example definition is " START + "the number of files in the option." END } I think since this will change in future release, it's better to let it be here so it's easier to update.

Target:
public String getDescription() { return "Transform files representing a structured table under an Alluxio directory." + "\n\n" + "Files are coalesced and converted to parquet format." + "\n\n" + "Definition is in format like 'write(hive).option(hive.num.files, 100)'," + "currently, the only modification you can do to the example definition is " + "the number of files in the option."; }
Source:
START public static void validateNonNegative(int[] data, String paramName){ END boolean nonnegative = true; for(int value : data){ if(value < 0) { nonnegative = false; } } Preconditions.checkArgument(nonnegative, "Values for %s must be >= 0, got: %s", paramName, data); } Handling of nulls? You have some in the later methods, but not here... If null is acceptable, we should return null here. If not, let's either add a lombok ```@NonNull``` or a ```Preconditions.checkNotNull(```. At present, nulls will give a non-useful NPE.

Target:
public static void validateNonNegative(int[] data, String paramName){ if(data == null) { return; } boolean nonnegative = true; for(int value : data){ if(value < 0) { nonnegative = false; } } Preconditions.checkArgument(nonnegative, "Values for %s must be >= 0, got: %s", paramName, data); }
Source:
START public SetContentTypeFilter() { END try { mimetypeToExtensionMap = new Properties(); mimetypeToExtensionMap.load(new InputStreamReader(this.getClass().getResourceAsStream( "mimetypeToExtension.txt"))); contentTypeProperties = new Properties(); contentTypeProperties.load(new InputStreamReader(this.getClass().getResourceAsStream( "toContentType.properties"))); } catch (IOException e) { log.error("Failed to load mimetype mappings", e); } } Looking at this (and i realize this is my own crappy code), its really a configuration error for the files to fail to load, and we really don't want to be eating that and just putting something in the log. Could you either remove the try block and make this constructor throw the IOException, or rethrow an exception with a little extra context? Up to you which you prefer.

Target:
public SetContentTypeFilter() throws IOException { mimetypeToExtensionMap = new Properties(); mimetypeToExtensionMap.load(new InputStreamReader(this.getClass().getResourceAsStream( "mimetypeToExtension.txt"))); contentTypeProperties = new Properties(); contentTypeProperties.load(new InputStreamReader(this.getClass().getResourceAsStream( "toContentType.properties"))); }
Source:
private SwiftApi api(String authUrl, Properties overrides) throws IOException { if (overrides == null){ overrides = new Properties(); START } END overrides.setProperty(CREDENTIAL_TYPE, "tempAuthCredentials"); return ContextBuilder.newBuilder(new SwiftApiMetadata()) .credentials("user", "password") .endpoint(authUrl) .overrides(overrides) .modules(ImmutableSet.of(new ExecutorServiceModule(sameThreadExecutor()))) .buildApi(SwiftApi.class); } Instead of passing null, remove this check and call this method with a new Properties object.

Target:
private SwiftApi api(String authUrl, Properties overrides) throws IOException { overrides.setProperty(CREDENTIAL_TYPE, "tempAuthCredentials"); return ContextBuilder.newBuilder(new SwiftApiMetadata()) .credentials("user", "password") .endpoint(authUrl) .overrides(overrides) .modules(ImmutableSet.of(new ExecutorServiceModule(sameThreadExecutor()))) .buildApi(SwiftApi.class); }
Source:
public void setAcceptableValues(Collection<K> values) { buttons.clear(); panels.clear(); wrapperPanel.clear(); START for (final K value : values) { END addValue(value); } updateButtons(); } add null check

Target:
public void setAcceptableValues(Collection<K> values) { buttons.clear(); panels.clear(); wrapperPanel.clear(); if (values != null) { for (final K value : values) { addValue(value); } } updateButtons(); }
Source:
public Bucket getOrCreateBucket(String bucketName) { try { Bucket bucket = storage.get(bucketName); if (bucket == null) { log.debug(String.format("Creating a new bucket %s", bucketName)); return storage.create(BucketInfo.of(bucketName)); } return bucket; } catch (StorageException e) { START throw new NuxeoException(e); END } } `StorageException` is a runtime exception, no need to catch and rethrow it (several occurrences).

Target:
public Bucket getOrCreateBucket(String bucketName) { Bucket bucket = storage.get(bucketName); if (bucket == null) { log.debug(String.format("Creating a new bucket %s", bucketName)); return storage.create(BucketInfo.of(bucketName)); } return bucket; }
Source:
private void onFragmentLoaded() { if (searchAdapter == null) { searchAdapter = new SearchlistAdapter(getActivity(), itemAccess); setListAdapter(searchAdapter); } searchAdapter.notifyDataSetChanged(); setListShown(true); String query = getArguments().getString(ARG_QUERY); START setEmptyText(getString(R.string.no_results_for_query) + " \"" + query + "\""); END } You need to keep in mind that the sentence construction in other languages could be different, so the query string doesn't always show at the end. You should use %1$s in your string on values/strings.xml and pass the query term as an extra argument to getString()

Target:
private void onFragmentLoaded() { if (searchAdapter == null) { searchAdapter = new SearchlistAdapter(getActivity(), itemAccess); setListAdapter(searchAdapter); } searchAdapter.notifyDataSetChanged(); setListShown(true); String query = getArguments().getString(ARG_QUERY); setEmptyText(getString(R.string.no_results_for_query, query)); }
Source:
private Iterable<Ref> getSortedRefs() throws Exception { List<Ref> all = db.getRefDatabase().getRefsByPrefix(ALL); START if (all instanceof RefMap END || (all instanceof SortedMap && ((SortedMap) all).comparator() == null)) { return all; } return RefComparator.sort(all); } Thanks. Marking resolved.

Target:
private Iterable<Ref> getSortedRefs() throws Exception { List<Ref> all = db.getRefDatabase().getRefsByPrefix(ALL); // TODO(jrn) check if we can reintroduce fast-path by e.g. implementing // SortedList return RefComparator.sort(all); }
Source:
private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); START for (ProfileEntry profileEntry : source != null ? new ArrayList<ProfileEntry>((ArrayList<ProfileEntry>) source) END : new ArrayList<ProfileEntry>()) { results.add(profileEntry.getProfile()); } return results; } }; } I don't understand why you need to create a new ArrayList for a collection that is coming from a query - it is necessarily not being used by anyone else. Also, why cast what's coming from the backend to an ArrayList? This means you're committing to a specific implementation. I think a cast to Collection is more appropriate. If it's important for you to have the end result in specifically an ArrayList (and not any other kind of collection), then I would create a new ArrayList, but still cast the result from the backend to Collection.

Target:
private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); for (ProfileEntry profileEntry : source != null ? (Collection<ProfileEntry>) source : new ArrayList<ProfileEntry>()) { results.add(profileEntry.getProfile()); } return results; } }; }
Source:
START public FunctionKindRowColumnHeaderMetaData(final Supplier<FunctionDefinition> functionSupplier, END final CellEditorControlsView.Presenter cellEditorControls, final KindPopoverView.Presenter editor, final Optional<String> editorTitle, final FunctionGrid gridWidget) { super(cellEditorControls, editor, editorTitle); this.functionSupplier = functionSupplier; this.gridWidget = gridWidget; } Since the `class` has _package_ protected access the constructor can probably have _package_ protection too?

Target:
FunctionKindRowColumnHeaderMetaData(final Supplier<FunctionDefinition> functionSupplier, final CellEditorControlsView.Presenter cellEditorControls, final KindPopoverView.Presenter editor, final Optional<String> editorTitle, final FunctionGrid gridWidget) { super(cellEditorControls, editor, editorTitle); this.functionSupplier = functionSupplier; this.gridWidget = gridWidget; }
Source:
public List<ProxiedPlayer> matchPlayer(String partialName) { List<ProxiedPlayer> matched = new ArrayList<ProxiedPlayer>(); for (ProxiedPlayer iPlayer : this.getPlayers()) { String iterPlayerName = iPlayer.getName(); if (partialName.equalsIgnoreCase(iterPlayerName)) { matched.add(iPlayer); break; } START if (iterPlayerName.toLowerCase().contains(partialName.toLowerCase())) { END matched.add(iPlayer); } } return matched; } Wouldn't starts with make more sense?

Target:
public List<ProxiedPlayer> matchPlayer(String partialName) { List<ProxiedPlayer> matched = new ArrayList<ProxiedPlayer>(); for (ProxiedPlayer iPlayer : this.getPlayers()) { String iterPlayerName = iPlayer.getName(); if (partialName.equalsIgnoreCase(iterPlayerName)) { matched.add(iPlayer); break; } if (iterPlayerName.toLowerCase().startsWith(partialName.toLowerCase())) { matched.add(iPlayer); } } return matched; }
Source:
private int zigzagDecode(int input) { START return (input >> 1) ^ (-(input & 1)); END } I notice in the unzigzag method below, you use the unsigned right shift operator (`>>>`), but here you're using the signed one (`>>`). Is that intentional?

Target:
private int zigzagDecode(int input) { return (input >>> 1) ^ (-(input & 1)); }
Source:
START public void testEqualsCondition() { doTest(GoStringIndexIsByteQuickFix.NAME); } END Please create method`doTest() { doTest(GoStringIndexIsByteQuickFix.NAME); }` and maybe same method `doTestNoFix()`

Target:
public void testEqualsCondition() { doTest(); }
Source:
public void testRedrawAfterDispose() { LineNumberRulerColumn lineNumberRulerColumn= new LineNumberRulerColumn(); CompositeRuler ruler= new CompositeRuler(); ruler.addDecorator(0, lineNumberRulerColumn); SourceViewer sourceViewer= new SourceViewer(fParent, ruler, SWT.NONE); lineNumberRulerColumn.getControl().setSize(10, 10); sourceViewer.getTextWidget().dispose(); try { lineNumberRulerColumn.redraw(); } START catch (Exception END notExpected) { notExpected.printStackTrace(); fail(); } } why do we need try/catch here? It should not fail, and if it fails, junit will take care about the stack etc

Target:
public void testRedrawAfterDispose() { LineNumberRulerColumn lineNumberRulerColumn= new LineNumberRulerColumn(); CompositeRuler ruler= new CompositeRuler(); ruler.addDecorator(0, lineNumberRulerColumn); SourceViewer sourceViewer= new SourceViewer(fParent, ruler, SWT.NONE); lineNumberRulerColumn.getControl().setSize(10, 10); sourceViewer.getTextWidget().dispose(); lineNumberRulerColumn.redraw(); }
Source:
public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } START final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); END cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); cmd.add("--localbrname", _linkLocalBridgeName); final String result = cmd.execute(); if (result != null) { return false; } return true; } Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.

Target:
public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); cmd.add("--localbrname", _linkLocalBridgeName); final String result = cmd.execute(); if (result != null) { return false; } return true; }
Source:
public void testQueryCumulativeTable() { computeActual("SELECT * FROM \"*:*\""); computeActual("SELECT * FROM \"java.util.logging:*\""); START assertTrue(computeActual("SELECT * FROM \"java.lang:*\"").getRowCount() > 0); END assertTrue(computeActual("SELECT * FROM \"jAVA.LANg:*\"").getRowCount() > 0); } shouldn't it be `> 1`

Target:
public void testQueryCumulativeTable() { computeActual("SELECT * FROM \"*:*\""); computeActual("SELECT * FROM \"java.util.logging:*\""); assertTrue(computeActual("SELECT * FROM \"java.lang:*\"").getRowCount() > 1); assertTrue(computeActual("SELECT * FROM \"jAVA.LANg:*\"").getRowCount() > 1); }
Source:
public RequestLogger get() { LoggingRequestLogger logger = new LoggingRequestLogger(mapper, setMDC, setContextMDC); START log.info(new Exception("Stack trace"), "Creating %s at", logger); END return logger; } should these be `debug` level?

Target:
public RequestLogger get() { LoggingRequestLogger logger = new LoggingRequestLogger(mapper, setMDC, setContextMDC); log.debug(new Exception("Stack trace"), "Creating %s at", logger); return logger; }
Source:
private IllegalReferenceCountException handleIllegalReferenceCountException(IllegalReferenceCountException e) { String accessRecord = leak.toString(); if (StringUtil.isNullOrEmpty(accessRecord)) { // means leak has been closed and there is no accessRecord. return e; } START return new TrackedIllegalReferenceCountException(e.getMessage(), accessRecord); END } shouldn't we wrap the original `e` ?

Target:
private IllegalReferenceCountException handleIllegalReferenceCountException(IllegalReferenceCountException e) { String accessRecord = leak.toString(); if (StringUtil.isNullOrEmpty(accessRecord)) { // means leak has been closed and there is no accessRecord. return e; } return new TrackedIllegalReferenceCountException(accessRecord, e); }
Source:
public List<Payment> getAccountPayments(final UUID accountId, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { START return paymentProcessor.getAccountPayments(accountId, withPluginInfo, tenantContext, internalCallContextFactory.createInternalTenantContext(accountId, tenantContext)); END } The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`

Target:
public List<Payment> getAccountPayments(final UUID accountId, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { return paymentProcessor.getAccountPayments(accountId, withPluginInfo, withAttempts, tenantContext, internalCallContextFactory.createInternalTenantContext(accountId, tenantContext)); }
Source:
public void startBucket(String bucketKey) { BulkCommand command = getCurrentCommand(); Serializable auditParam = command.getParam(NXAuditEventsService.DISABLE_AUDIT_LOGGER); disableAudit = auditParam != null && Boolean.parseBoolean(auditParam.toString()); retentionManager = Framework.getService(RetentionManager.class); START ruleId = (String) command.getParam(PARAM_RULE_ID); END } No need to cast to `String`, here `getParam` is a generic method `public <T> T getParam(String key)`

Target:
public void startBucket(String bucketKey) { BulkCommand command = getCurrentCommand(); Serializable auditParam = command.getParam(NXAuditEventsService.DISABLE_AUDIT_LOGGER); disableAudit = auditParam != null && Boolean.parseBoolean(auditParam.toString()); retentionManager = Framework.getService(RetentionManager.class); ruleId = command.getParam(PARAM_RULE_ID); }
Source:
public boolean remove(Connection connection) { boolean removed = connectionPool.remove(connection); if (getHttpExchanges().isEmpty()) { tryRemoveIdleDestination(); } else { // We need to execute queued requests // even if this connection was removed. // We may create a connection that is not // needed, but it will eventually idle timeout. if (removed) START process(true); END } return connectionPool.remove(connection); } should this check that the queue is not 0? Why acquire a connection if there are no waiting exchanges?

Target:
public boolean remove(Connection connection) { boolean removed = connectionPool.remove(connection); if (getHttpExchanges().isEmpty()) { tryRemoveIdleDestination(); } else if (removed) { // Process queued requests that may be waiting. // We may create a connection that is not // needed, but it will eventually idle timeout. process(true); } return removed; }
Source:
public boolean getRewriteBatchedStatements() { final String isRewrite = super.connectionProperties.getProperty(REWRITE_BATCHED_STATEMENTS); START return isRewrite == null ? null : Boolean.valueOf(isRewrite); END } return null ? I think you meant 'false', did not you?

Target:
public boolean getRewriteBatchedStatements() { final String isRewrite = super.connectionProperties.getProperty(REWRITE_BATCHED_STATEMENTS); return isRewrite == null ? false : Boolean.valueOf(isRewrite); }
Source:
public static ScheduledExecutorService newScheduler(int numThreads, String threadNamePrefix, boolean isDaemon) { ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(numThreads, new SchedulerThreadFactory(threadNamePrefix, isDaemon)); scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); START scheduler.setRemoveOnCancelPolicy(true); END return scheduler; } I am little wary about this. coz, all our existing schedulers are using this and setting this might cause them to be removed immediately. Even though ideally we want to be in that position, when rolling this out, don't want to have any unexpected behaviors.

Target:
public static ScheduledExecutorService newScheduler(int numThreads, String threadNamePrefix, boolean isDaemon) { ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(numThreads, new SchedulerThreadFactory(threadNamePrefix, isDaemon)); scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); return scheduler; }
Source:
public boolean setValue(T newValue) { if (!validator.validate(newValue)) { START LOGGER.warn("The passed value is invalid.", newValue); END return false; } PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); this.value = newValue; dispatchChangedEvent(event); return true; } Ah, that's what you meant. =) No, this isn't good: it's too generic, it wouldn't help you debug a failure. The validator itself has to log a warning and then return false, so that the warning can be very specific on what went wrong, i.e. the new value being beyond the maximum value allowed.

Target:
public boolean setValue(T newValue) { if (!validate(newValue)) { return false; } PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); this.value = newValue; dispatchChangedEvent(event); return true; }
Source:
public void onMessage(MessageHolderWithTokens message) { try { START logger.debug("receiving tokens from queue, triggering Notification Dispatcher class to pick the right sender"); END dequeueEvent.fire(message); } catch (DispatchInitiationException e) { throw e; } catch (Exception e) { logger.error("NotificationDispatcher or PushNotificationSender unexpectedly failed, the message won't be redelivered", e); } } Do we really want to move this from `trace` to `debug`?

Target:
public void onMessage(MessageHolderWithTokens message) { try { logger.trace("receiving tokens from queue, triggering Notification Dispatcher class to pick the right sender"); dequeueEvent.fire(message); } catch (DispatchInitiationException e) { throw e; } catch (Exception e) { logger.error("NotificationDispatcher or PushNotificationSender unexpectedly failed, the message won't be redelivered", e); } }
Source:
private Collection<Key> getRegisteredKeys() { List<Key> result = new ArrayList<Key>(); START for (Iterator<Key> i = cacheMap.keySet().iterator(); i.hasNext();) { result.add(i.next()); } return result; END } why not: return result.addAll(cacheMap.keySet());

Target:
private Collection<Key> getRegisteredKeys() { return new ArrayList<Key>(cacheMap.keySet()); }
Source:
START public AbstractMetric(String metricName, String metricType, T initialValue, MetricReportManager manager) { END name = metricName; type = metricType; value = initialValue; metricManager = manager; } I would make this constructor `protected` because you cannot directly instantiate abstract classes. See the answers to http://stackoverflow.com/questions/260666/can-an-abstract-class-have-a-constructor for a discussion.

Target:
protected AbstractMetric(String metricName, String metricType, T initialValue, MetricReportManager manager) { name = metricName; type = metricType; value = initialValue; metricManager = manager; }
Source:
public void hasSameValues_checkingAgainstSameInstanceOfAllergy_shouldInterpretAsSameValues() { Allergy allergy = allergy(); START allergy.hasSameValues(allergy()); END } Shouldn't this line be something like AssertTrue(allergy.hasSameValues(allergy())); ?

Target:
public void hasSameValues_checkingAgainstSameInstanceOfAllergy_shouldInterpretAsSameValues() { Allergy allergy = allergy(); assertThat(allergy.hasSameValues(allergy()),is(true)); }
Source:
private static String readMapping() throws IOException, ParseException { JSONParser parser = new JSONParser(); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); START InputStream inputStream = classloader.getResourceAsStream("mapping.json"); END String mapping = IOUtils.toString(inputStream, "UTF-8"); Object object = parser.parse(mapping); JSONObject jsonObject = (JSONObject) object; return jsonObject.toJSONString(); } You are open a stream object without closing it never. Maybe you can use the try-with-resources statement here and avoid / handle the unhandled IOException here.

Target:
private static String readMapping() throws ParseException { JSONParser parser = new JSONParser(); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); try (InputStream inputStream = classloader.getResourceAsStream("mapping.json")) { String mapping = IOUtils.toString(inputStream, "UTF-8"); Object object = parser.parse(mapping); JSONObject jsonObject = (JSONObject) object; return jsonObject.toJSONString(); } catch (IOException e) { logger.error(e); return ""; } }
Source:
public synchronized void commit() throws CommitException { SyncCommitObserver sco = null; try { sco = new SyncCommitObserver(); commitAsync(sco); sco.waitForCommit(); } finally { updates.clear(); weakNotification = null; START observedColumns.clear(); END columnsRead.clear(); } } @mjwall I found the bug. Its my fault, I suggested clearing `observedColumns` and that is a bad thing to do. `observedColumns` is shared between transactions. It should be an immutable set, I'll open an issue for that.

Target:
public synchronized void commit() throws CommitException { SyncCommitObserver sco = null; try { sco = new SyncCommitObserver(); commitAsync(sco); sco.waitForCommit(); } finally { updates.clear(); weakNotification = null; columnsRead.clear(); } }
Source:
public static boolean hasPictureId(byte[] buf, int off, int len) { if (!isValid(buf, off)) return false; if ((buf[off] & X_BIT) == 0 || (buf[off+1] & I_BIT) == 0) START return false; END return true; } I would simplify to "return isValid(buf,off) && (buf[off] & X_BIT != 0) && (buf[off+1] & I_BIT) != 0)"

Target:
public static boolean hasPictureId(byte[] buf, int off, int len) { return isValid(buf, off, len) && (buf[off] & X_BIT) != 0 && (buf[off+1] & I_BIT) != 0; }
Source:
public void setEnabled(boolean enabled) { this.active = enabled; START System.out.println("active state change: " + active); END updateButtonState(); } remove the println

Target:
public void setEnabled(boolean enabled) { this.active = enabled; updateButtonState(); }
Source:
START default void beforeDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { END throw new UnsupportedOperationException("Method is not implemented"); } Same here. I dont think we should be throwing exceptions.We should instead be having empty implementations.

Target:
default void beforeDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { // not implemented }
Source:
private void handleEndActionJobAndStep() { if (!hasTaskHandlers() || getExecutionIndex() == getTaskHandlers().size() - 1) { START if (!parentHasCallback() || getExecutionContext().getExecutionMethod() == ExecutionMethod.AsStep) { END startFinalizingStep(); } } } the inner 'if' isn't needed - the conditions can be added to the outer 'if'

Target:
private void handleEndActionJobAndStep() { if ((!hasTaskHandlers() || getExecutionIndex() == getTaskHandlers().size() - 1) && (!parentHasCallback() || getExecutionContext().getExecutionMethod() == ExecutionMethod.AsStep)) { startFinalizingStep(); } }
Source:
private boolean waitForScanState(ScanStates state) { try { START while (!getScanState().equals(state)) { END scanState.wait(); } return true; } catch (InterruptedException e) { tsLogger.logger.warn("problem waiting for scanLock whilst in state " + state.name(), e); return false; } } why did you change the do ... while into a while do loop. The caller already knows the scan state is not equal to state and since this is a private method it is safe to assume that the caller has already checked (under the lock) that he has to wait for a state change.

Target:
private boolean waitForScanState(ScanStates state) { try { do { scanState.wait(); } while (!getScanState().equals(state)); return true; } catch (InterruptedException e) { tsLogger.logger.warn("problem waiting for scanLock whilst in state " + state.name(), e); return false; } }
Source:
private void maybeScheduleCheckpoint() { switch (state()) { START case RESTORING: END this.checkpoint = checkpointableOffsets(); break; case RUNNING: if (!eosEnabled) { this.checkpoint = checkpointableOffsets(); } break; case SUSPENDED: this.checkpoint = checkpointableOffsets(); break; case CREATED: case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while scheduling checkpoint for active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while scheduling checkpoint for active task " + id); } } Could we merge RESTORING and SUSPENDED?

Target:
private void maybeScheduleCheckpoint() { switch (state()) { case RESTORING: case SUSPENDED: this.checkpoint = checkpointableOffsets(); break; case RUNNING: if (!eosEnabled) { this.checkpoint = checkpointableOffsets(); } break; case CREATED: case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while scheduling checkpoint for active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while scheduling checkpoint for active task " + id); } }
Source:
protected void executeQueryCommand() { Provider hostProvider = getProvider(); START HostProviderProxy proxy = ((HostProviderProxy) ProviderProxyFactory.getInstance().create(hostProvider)); END getQueryReturnValue().setReturnValue(chainToString(proxy.getCertificateChain())); } Why do you cast to HostProviderProxy?

Target:
protected void executeQueryCommand() { Provider hostProvider = getProvider(); HostProviderProxy proxy = ProviderProxyFactory.getInstance().create(hostProvider); getQueryReturnValue().setReturnValue(chainToString(proxy.getCertificateChain())); }
Source:
public void t1() { START testCaseExecutionOrder.add(new Object() {}.getClass().getEnclosingMethod().getName()); END } We could have leveraged `InvokedMethodListener` for this. See [here](https://github.com/cbeust/testng/blob/master/src/test/java/test/InvokedMethodListener.java)

Target:
public void t1() { }
Source:
public void testValidateDataStreamsNoConflicts() { Metadata metadata = createIndices(5, 10, "foo-datastream").metadata; try { START validateDataStreams(metadata.getIndicesLookup(), (DataStreamMetadata) metadata.customs().get(DataStreamMetadata.TYPE)); END } catch (Exception e) { fail("did not expect exception when validating a system without indices that would conflict with future backing indices: " + e.getMessage()); } } Currently when the test fails with any error then there is no stacktrace to the original failure, which I think makes pinpointing the culprit easier? That being said, this is just preference, so feel free to ignore :)

Target:
public void testValidateDataStreamsNoConflicts() { Metadata metadata = createIndices(5, 10, "foo-datastream").metadata; // don't expect any exception when validating a system without indices that would conflict with future backing indices validateDataStreams(metadata.getIndicesLookup(), (DataStreamMetadata) metadata.customs().get(DataStreamMetadata.TYPE)); }
Source:
public ShaderProvider getPassShaderProvider (int n) { START if (n >= passShaderProviders.length) END throw new GdxRuntimeException("ShaderProvider " + n + " doesn't exist in " + getClass().getName()); return passShaderProviders[n]; } I dont think that this check is needed here (otherwise it will throw an index out of bounds exception, which says the same). https://github.com/libgdx/libgdx/wiki/Contributing#performance-considerations

Target:
public ShaderProvider getPassShaderProvider (int n) { return passShaderProviders[n]; }
Source:
public void onConnectionClosedForUser(QBRTCSession qbrtcSession, Integer integer) { setStatusForOpponent(integer, getString(R.string.closed)); START stopTimer(); END } stopTimer() нужно поставить где сессия закрывается вообще, а не для конкретного юзера

Target:
public void onConnectionClosedForUser(QBRTCSession qbrtcSession, Integer integer) { setStatusForOpponent(integer, getString(R.string.closed)); }
Source:
public void install(ITextViewer textViewer) { for (IReconciler iReconciler : fReconcilers) { START if(iReconciler != null) { END iReconciler.install(textViewer); } } } It would be better to run checks in the constructor to make sure no reconciler is null, or to create an actual list of non-null reconcilers that would be dereferenced here.

Target:
public void install(ITextViewer textViewer) { for (IReconciler iReconciler : fReconcilers) { iReconciler.install(textViewer); } }
Source:
public JettyServer run(WebApplicationContext baseContext, boolean directlyUseAsWebAppRoot, Function<Function<Integer, JettyServer>, JettyServer> serverStarter, boolean exitOnError) { try { configureLogger(); configureSentry(baseContext); JettyServer jettyServer = createJettyServer(baseContext, directlyUseAsWebAppRoot, serverStarter, START v->v.addLifeCycleListener(new JettyLifeCycleListener(baseContext))); END jettyServer.start(); logStartupInfo(baseContext); return jettyServer; } catch (Exception e) { return logErrorAndExit(e, exitOnError); } } а мы разве можем хоть когда-то не захотеть добавлять listener - я бы это унес прям в основной webAppInitializer

Target:
public JettyServer run(WebApplicationContext baseContext, boolean directlyUseAsWebAppRoot, Function<Function<Integer, JettyServer>, JettyServer> serverStarter, boolean exitOnError) { try { configureLogger(); configureSentry(baseContext); JettyServer jettyServer = createJettyServer(baseContext, directlyUseAsWebAppRoot, serverStarter); jettyServer.start(); logStartupInfo(baseContext); return jettyServer; } catch (Exception e) { return logErrorAndExit(e, exitOnError); } }
Source:
public PlanItem(String id, String definitionRef) { START super(); END this.id = id; this.definitionRef = definitionRef; } AFAIK this is redundant.

Target:
public PlanItem(String id, String definitionRef) { this.id = id; this.definitionRef = definitionRef; }
Source:
public int hashCode() { START return name.hashCode(); END } Looking on `QName` class, maybe we should use `return ~~name.hashCode()`.

Target:
public int hashCode() { return ~~name.hashCode(); }