auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Collection<String> populatePlatformTypes() throws IOException { Collection<PlatformType> platforms = requestManager.listActivePlatformTypes(); if (platforms.size() > 0) { START return PlatformType.platformTypeNames(requestManager.listActivePlatformTypes()); END } else { return requestManager.listDistinctPlatformNames(); } } Can `return PlatformType.platformTypeNames(platforms);` instead of doing the same lookup twice

Target:
public Collection<String> populatePlatformTypes() throws IOException { Collection<PlatformType> platforms = requestManager.listActivePlatformTypes(); if (platforms.size() > 0) { return PlatformType.platformTypeNames(platforms); } else { return requestManager.listDistinctPlatformNames(); } }
Source:
public Collection<Sample> listBySearch(String querystr) throws IOException { Criteria criteria = currentSession().createCriteria(Sample.class); criteria.add(Restrictions.or(Restrictions.ilike("identificationBarcode", querystr + "%"), Restrictions.ilike("name", querystr + "%"), START Restrictions.ilike("alias", querystr + "%"))); END @SuppressWarnings("unchecked") List<Sample> records = criteria.list(); return fetchSqlStore(records); } Consider adding a wildcard to the front of the string as well. Right now searching for `KGMT` will match `KGMT_0015`, but searching for `0015` will not. Since the query string is not escaped, it's currently possible to use SQL wildcards in queries (this is not something a general user will do.) So searching for `%0015` will match against `KGMT_0015`.

Target:
public Collection<Sample> listBySearch(String querystr) throws IOException { Criteria criteria = currentSession().createCriteria(Sample.class); criteria.add(Restrictions.or(Restrictions.ilike("identificationBarcode", "%" + querystr + "%"), Restrictions.ilike("name", "%" + querystr + "%"), Restrictions.ilike("alias", "%" + querystr + "%"))); @SuppressWarnings("unchecked") List<Sample> records = criteria.list(); return fetchSqlStore(records); }
Source:
private void updateTissueMaterialDaoDependencies() { if (sampleService != null) sampleService.setTissueMaterialDao(tissueMaterialDao); START updateSamplePurposeDaoDependencies(); END } Wrong place. This should be done in the setSamplePurposeDao method, where it was originally

Target:
private void updateTissueMaterialDaoDependencies() { if (sampleService != null) sampleService.setTissueMaterialDao(tissueMaterialDao); }
Source:
public Integer getCutsRemaining() { START Integer cutsConsumed = 0; END for (Sample child : getChildren()) { if (child instanceof SampleLCMTube && ((SampleLCMTube) child).getCutsConsumed() != null) { cutsConsumed += ((SampleLCMTube) child).getCutsConsumed(); } } return (getCuts() - getDiscards() - cutsConsumed); } This should be `int`.

Target:
public Integer getCutsRemaining() { int cutsConsumed = 0; for (Sample child : getChildren()) { if (child != null && child instanceof SampleLCMTube && ((SampleLCMTube) child).getCutsConsumed() != null) { cutsConsumed += ((SampleLCMTube) child).getCutsConsumed(); } } return (getCuts() - getDiscards() - cutsConsumed); }
Source:
public String getBulkSamples(@RequestBody JSONObject json) throws IOException { JSONArray ids = JSONArray.fromObject(json.get("ids")); StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < ids.size(); ++i) { stringBuffer.append(ids.getLong(i)); START if (i + 1 < ids.size()) { END stringBuffer.append(","); } } return "redirect:/miso/sample/bulk/edit/" + stringBuffer.toString(); } This is easier to read as: ``` for (int i = 0; i < ids.size(); ++i) { if (i>0) { stringBuffer.append(","); } stringBuffer.append(ids.getLong(i)); } ```

Target:
public String getBulkSamples(@RequestBody JSONObject json) throws IOException { JSONArray ids = JSONArray.fromObject(json.get("ids")); StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < ids.size(); ++i) { if (i > 0) stringBuffer.append(","); stringBuffer.append(ids.getLong(i)); } return "redirect:/miso/sample/bulk/edit/" + stringBuffer.toString(); }
Source:
public static SampleAdditionalInfo to(SampleAdditionalInfoDto from) { SampleAdditionalInfo to = new SampleAdditionalInfoImpl(); to.setPassageNumber(from.getPassageNumber()); to.setTimesReceived(from.getTimesReceived()); to.setTubeNumber(from.getTubeNumber()); to.setVolume(from.getVolume()); to.setConcentration(from.getConcentration()); to.setTubeNumber(from.getTubeNumber()); START return to; END } It is already set in this method, three lines up.

Target:
public static SampleAdditionalInfo to(SampleAdditionalInfoDto from) { SampleAdditionalInfo to = new SampleAdditionalInfoImpl(); to.setPassageNumber(from.getPassageNumber()); to.setTimesReceived(from.getTimesReceived()); to.setTubeNumber(from.getTubeNumber()); to.setVolume(from.getVolume()); to.setConcentration(from.getConcentration()); return to; }
Source:
public String toString() { return "SampleTissueDto [bioBankId=" + bioBankId + ", cellularity=" + cellularity + ", createdById=" + createdById + ", createdByUrl=" + createdByUrl + ", creationDate=" + creationDate + ", id=" + id + ", labUrl=" + labUrl + ", instituteTissueName=" + instituteTissueName + ", lastUpdated=" + lastUpdated + ", updatedById=" + updatedById + ", updatedByUrl=" + updatedByUrl + ", url=" + url + "]"; START } END labUrl needs to be taken out as well, and added in to SampleAdditionalInfoDto

Target:
public String toString() { return "SampleTissueDto [bioBankId=" + bioBankId + ", cellularity=" + cellularity + ", createdById=" + createdById + ", createdByUrl=" + createdByUrl + ", creationDate=" + creationDate + ", id=" + id + ", instituteTissueName=" + instituteTissueName + ", lastUpdated=" + lastUpdated + ", updatedById=" + updatedById + ", updatedByUrl=" + updatedByUrl + ", url=" + url + "]"; }
Source:
private SampleNumberPerProject createSampleNumberPerProject(Project project, User user) { SampleNumberPerProject sampleNumberPerProject; sampleNumberPerProject = new SampleNumberPerProjectImpl(); sampleNumberPerProject.setProject(project); sampleNumberPerProject.setHighestSampleNumber(0); sampleNumberPerProject.setPadding(DEFAULT_PADDING); sampleNumberPerProject.setCreatedBy(user); sampleNumberPerProject.setUpdatedBy(user); sampleNumberPerProject.setLastUpdated(new Date()); START sampleNumberPerProject.setCreationDate(new Date()); END addSampleNumberPerProject(sampleNumberPerProject); return sampleNumberPerProject; } Setting the dates is handled inside the addSampleNumberPerProject method, so is not required here.

Target:
private SampleNumberPerProject createSampleNumberPerProject(Project project, User user) { SampleNumberPerProject sampleNumberPerProject; sampleNumberPerProject = new SampleNumberPerProjectImpl(); sampleNumberPerProject.setProject(project); sampleNumberPerProject.setHighestSampleNumber(0); sampleNumberPerProject.setPadding(DEFAULT_PADDING); sampleNumberPerProject.setCreatedBy(user); sampleNumberPerProject.setUpdatedBy(user); addSampleNumberPerProject(sampleNumberPerProject); return sampleNumberPerProject; }
Source:
public static String loadFile(String path) { String result = ""; Scanner sc = new Scanner(ResourcesUtil.class.getClassLoader().getResourceAsStream(path)); while (sc.hasNextLine()) { result += sc.nextLine(); } START sc.close(); END return result; } try/finally?

Target:
public static String loadFile(String path) { String result = ""; Scanner sc = null; try { sc = new Scanner(ResourcesUtil.class.getClassLoader().getResourceAsStream(path)); while (sc.hasNextLine()) { result += sc.nextLine(); } sc.close(); } finally { if (sc != null) { sc.close(); } } return result; }
Source:
private static Activity getActivity(final Context context) { START if (context == null) { END // TODO Mapsme API will do a hard cast. We could locally fix this by re-declaring all API methods return null; } else if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return getActivity(((ContextWrapper) context).getBaseContext()); } return null; } The first if is superfluous. instanceof is always false for null, therefore a null value bypasses the instanceof checks and returns null from the end of the method already.

Target:
private static Activity getActivity(final Context context) { // TODO Mapsme API will do a hard cast. We could locally fix this by re-declaring all API methods if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return getActivity(((ContextWrapper) context).getBaseContext()); } return null; }
Source:
START public static IConnector[] getActiveConnectors() { END final List<IConnector> activeConnectors = new ArrayList<>(); for (final IConnector conn : CONNECTORS) { if (conn.isActive()) { activeConnectors.add(conn); } } return activeConnectors.toArray(new IConnector[activeConnectors.size()]); } Why not return directly the `List<IConnector>`?

Target:
public static List<IConnector> getActiveConnectors() { final List<IConnector> activeConnectors = new ArrayList<>(); for (final IConnector conn : CONNECTORS) { if (conn.isActive()) { activeConnectors.add(conn); } } return activeConnectors; }
Source:
public boolean onOptionsItemSelected(final MenuItem item) { START switch (item.getItemId()) { END case android.R.id.home: finish(); return true; } return false; } Can be transformed into an `if` statement.

Target:
public boolean onOptionsItemSelected(final MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } return false; }
Source:
static List<TrackableInventoryEntry> getTrackableInventory() { final List<TrackableInventoryEntry> trackableInventoryEntries = new ArrayList<>(); int skip = 0; TrackableInventoryEntry[] entries = null; START while (entries == null || entries.length == MAX_TAKE) { END entries = getAPI("/trackables?inCollection=false&take=" + MAX_TAKE + "&skip=" + skip, TrackableInventoryEntry[].class).blockingGet(); trackableInventoryEntries.addAll(Arrays.asList(entries)); skip += MAX_TAKE; } return trackableInventoryEntries; } We can get rid of the first condition (and the `null`-initialization of `entries`) by using a do-while loop.

Target:
static List<TrackableInventoryEntry> getTrackableInventory() { final List<TrackableInventoryEntry> trackableInventoryEntries = new ArrayList<>(); int skip = 0; TrackableInventoryEntry[] entries; do { entries = getAPI("/trackables?inCollection=false&take=" + MAX_TAKE + "&skip=" + skip, TrackableInventoryEntry[].class).blockingGet(); trackableInventoryEntries.addAll(Arrays.asList(entries)); skip += MAX_TAKE; } while (entries.length == MAX_TAKE); return trackableInventoryEntries; }
Source:
public void increaseActualCachesFound() { if (actualCachesFound >= 0) { START setActualCachesFound(actualCachesFound + 1); END } } That's actually `actualCachesFound++;`. Sorry, I though you already had this in mind when you proposed to reference the field directly.

Target:
public void increaseActualCachesFound() { if (actualCachesFound >= 0) { actualCachesFound++; } }
Source:
public static CalcState fromJSON(final String json) throws JSONException { CalcState rv = null; if (json != null) { rv = new CalcState(new JSONObject(json)); } START return rv; END } Your proposal is even better. Early returns make it easier to understand: Here it will return, (almost) nothing will be executed after this line. So please change this to ```java if (json == null) { return null; } return new CalcState(new JSONObject(json)); ```

Target:
public static CalcState fromJSON(final String json) throws JSONException { if (json == null) { return null; } return new CalcState(new JSONObject(json)); }
Source:
public JSONObject toJASON() throws JSONException { START JSONObject rv = new JSONObject(); END rv.put("type", type.ordinal()); rv.put("inputVal", inputVal); rv.put("autoChar", autoChar); rv.put("customChar", customChar); return rv; } Should be `final JSONObject rv = …`.

Target:
public JSONObject toJASON() throws JSONException { final JSONObject rv = new JSONObject(); rv.put("type", type.ordinal()); rv.put("inputVal", inputVal); rv.put("autoChar", autoChar); rv.put("customChar", customChar); return rv; }
Source:
START public void testShouldRemoveNoCache() throws Exception { END // GIVEN lists1.add(LIST_ID1); lists2.add(LIST_ID3); lists3.add(LIST_ID3); final Set<Geocache> toBeRemoved = RemoveNotUniqueHelper.removeNonUniqueCaches(geoCaches); assertThat(toBeRemoved.size()).isEqualTo(0); assertThat(toBeRemoved.contains(gc1)).isFalse(); assertThat(toBeRemoved.contains(gc2)).isFalse(); assertThat(toBeRemoved.contains(gc3)).isFalse(); } Please add an empty line between the two methods.

Target:
public void testShouldRemoveNoCache() { // GIVEN lists1.add(LIST_ID1); lists2.add(LIST_ID3); lists3.add(LIST_ID3); // WHEN final Set<Geocache> toBeRemoved = RemoveNotUniqueHelper.removeNonUniqueCaches(geoCaches); // THEN assertThat(toBeRemoved.size()).isEqualTo(0); assertThat(toBeRemoved.contains(gc1)).isFalse(); assertThat(toBeRemoved.contains(gc2)).isFalse(); assertThat(toBeRemoved.contains(gc3)).isFalse(); }
Source:
private void initializeFavoriteCheck() { if (ConnectorFactory.getConnector(cache).supportsAddToFavorite(cache, typeSelected)) { if (premFavPoints > 0) { favCheck.setVisibility(View.VISIBLE); START favCheck.setText(getString(R.string.fav_points_remaining, String.valueOf(premFavPoints))); END } } else { favCheck.setVisibility(View.GONE); } } Why not either: - fix the string to use `%d` instead of `%s` - do nothing and let the implicit `.toString()` do the job rather than calling `String.valueOf` explicitly?

Target:
private void initializeFavoriteCheck() { if (ConnectorFactory.getConnector(cache).supportsAddToFavorite(cache, typeSelected)) { if (premFavPoints > 0) { favCheck.setVisibility(View.VISIBLE); favCheck.setText(getString(R.string.fav_points_remaining, premFavPoints)); } } else { favCheck.setVisibility(View.GONE); } }
Source:
START private void initializeCommonFields() { END supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); AndroidBeam.disable(this); // initialize commonly used members res = this.getResources(); app = (CgeoApplication) this.getApplication(); // only needed in some activities, but implemented in super class nonetheless Cookies.restoreCookieStore(Settings.getCookieStore()); ActivityMixin.onCreate(this, keepScreenOn); } If you re-purpose the method, you should change its name as well

Target:
private void initializeCommonFields() { // initialize commonly used members res = this.getResources(); app = (CgeoApplication) this.getApplication(); // only needed in some activities, but implemented in super class nonetheless Cookies.restoreCookieStore(Settings.getCookieStore()); ActivityMixin.onCreate(this, keepScreenOn); }
Source:
protected InputStream getInputStream() throws IOException { try { return contentResolver.openInputStream(uri); } catch (final FileNotFoundException e) { // for http links, we may need to download the content ourself, if it has no mime type announced by the browser if (uri.toString().startsWith("http")) { return Network.getResponseStream(Network.getRequest(uri.toString())); } // only log error for non-http URI START Log.e("GpxZip import cannot resolve " + uri); END } return null; } No, I mean take the `Log.e()` near the `return null;`.

Target:
protected InputStream getInputStream() throws IOException { try { return contentResolver.openInputStream(uri); } catch (final FileNotFoundException e) { // for http links, we may need to download the content ourself, if it has no mime type announced by the browser if (uri.toString().startsWith("http")) { return Network.getResponseStream(Network.getRequest(uri.toString())); } } Log.e("GpxZip import cannot resolve " + uri); return null; }
Source:
public void addInventoryItem(final Trackable newTrackable) { if (inventory == null) { inventory = new ArrayList<Trackable>(); } START Boolean foundTrackable = false; END for (final Trackable trackable: inventory) { if (trackable.getUniqueID().equals(newTrackable.getUniqueID())) { // Trackable already present, merge data foundTrackable = true; trackable.mergeTrackable(newTrackable); break; } } if (!foundTrackable) { inventory.add(newTrackable); } inventoryItems = inventory.size(); } please avoid boxed primitives

Target:
public void addInventoryItem(final Trackable newTrackable) { if (inventory == null) { inventory = new ArrayList<>(); } Boolean foundTrackable = false; for (final Trackable trackable: inventory) { if (trackable.getUniqueID().equals(newTrackable.getUniqueID())) { // Trackable already present, merge data foundTrackable = true; trackable.mergeTrackable(newTrackable); break; } } if (!foundTrackable) { inventory.add(newTrackable); } inventoryItems = inventory.size(); }
Source:
public DistanceComparator() { this.coords = null; START this.list = null; END } What does it mean to have the `list` set to `null`? As soon as `compareCaches()` will be called, then `calculateAllDistances` will be called as well, and there will be a `NullPointerException` in the `for` loop. Does it mean that `compareCaches()` will never be called on the singleton? If this is the case, why not use `null` instead of this singleton? I'm not sure I follow the logic here.

Target:
public DistanceComparator() { // This constructor should not be used as a comparator as distances will not be updated. // It is needed in order to really know we are sorting by Distances in the sort menu. // If you need it for sorting, please use the second construtor coords = null; list = new ArrayList<>(); }
Source:
public static List<Trackable> parse(final InputSource page) { try { // Create a new instance of the SAX parser START SAXParserFactory saxPF = SAXParserFactory.newInstance(); END SAXParser saxP = saxPF.newSAXParser(); XMLReader xmlR = saxP.getXMLReader(); // Create the Handler to handle each of the XML tags. final GeokretyHandler gkXMLHandler = new GeokretyHandler(); xmlR.setContentHandler(gkXMLHandler); xmlR.parse(page); return gkXMLHandler.getTrackables(); } catch (final Exception e) { Log.w("Cannot parse geokrety", e); } return null; } Should be `final`.

Target:
public static List<Trackable> parse(final InputSource page) { try { // Create a new instance of the SAX parser final SAXParserFactory saxPF = SAXParserFactory.newInstance(); final SAXParser saxP = saxPF.newSAXParser(); final XMLReader xmlR = saxP.getXMLReader(); // Create the Handler to handle each of the XML tags. final GeokretyHandler gkXMLHandler = new GeokretyHandler(); xmlR.setContentHandler(gkXMLHandler); xmlR.parse(page); return gkXMLHandler.getTrackables(); } catch (final Exception e) { Log.w("Cannot parse geokrety", e); } return null; }
Source:
START public static boolean mergeFriendsLogs(final List<LogEntry> mergedLogs, List<LogEntry> logsToMerge) { END if (logsToMerge != null && !logsToMerge.isEmpty()) { for (final LogEntry log : logsToMerge) { if (mergedLogs.contains(log)) { mergedLogs.get(mergedLogs.indexOf(log)).friend = true; } else { log.friend = true; mergedLogs.add(log); } } return true; } return false; } Why public?

Target:
private static boolean mergeFriendsLogs(final List<LogEntry> mergedLogs, List<LogEntry> logsToMerge) { if (logsToMerge != null && !logsToMerge.isEmpty()) { for (final LogEntry log : logsToMerge) { if (mergedLogs.contains(log)) { mergedLogs.get(mergedLogs.indexOf(log)).friend = true; } else { mergedLogs.add(log); } } return true; } return false; }
Source:
public SearchResult searchByGeocode(final String geocode, final String guid, final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_loadpage); final Geocache cache = ECApi.searchByGeoCode(geocode); START if (cache == null) { END return null; } final SearchResult searchResult = new SearchResult(cache); return searchResult; } This line and all the following ones can be replaced by the single line ``` java return cache != null ? new SearchResult(cache) : null; ```

Target:
public SearchResult searchByGeocode(final String geocode, final String guid, final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_loadpage); final Geocache cache = ECApi.searchByGeoCode(geocode); return cache != null ? new SearchResult(cache) : null; }
Source:
public final LogResult postLog(final Geocache cache, final LogType logType, final Calendar date, final String log, final String logPassword, final List<TrackableLog> trackableLogs) { START final LogResult result = ECApi.postLog(cache, logType, date, log); END return result; } Please do not create useless variables, it is more readable if you directly use: ``` java return ECApi.postLog(cache, logType, date, log); ```

Target:
public final LogResult postLog(final Geocache cache, final LogType logType, final Calendar date, final String log, final String logPassword, final List<TrackableLog> trackableLogs) { return ECApi.postLog(cache, logType, date, log); }
Source:
public static String getResponseDataAlways(@Nullable final HttpResponse response) { if (response == null) { return null; } START return getResponseDataNoError(response, false); END } You could use the shorter ``` java return response != null ? getResponseDataNoError(response, false) : null; ```

Target:
public static String getResponseDataAlways(@Nullable final HttpResponse response) { return response != null ? getResponseDataNoError(response, false) : null; }
Source:
public void onLoadFinished(Loader<String> arg0, String page) { if (page == null) { hasLoaderError = true; } else { viewstates = Login.getViewstates(page); trackables = GCParser.parseTrackableLog(page); possibleLogTypes = GCParser.parseTypes(page); START if (possibleLogTypes.isEmpty()) { END hasLoaderError = true; } else { hasLoaderError = false; } } activity.onLoadFinished(); } the if-else can be transformed to a simple assignment.

Target:
public void onLoadFinished(Loader<String> arg0, String page) { if (page == null) { hasLoaderError = true; } else { viewstates = Login.getViewstates(page); trackables = GCParser.parseTrackableLog(page); possibleLogTypes = GCParser.parseTypes(page); hasLoaderError = possibleLogTypes.isEmpty(); } activity.onLoadFinished(); }
Source:
public static void clearVisitDate(String[] selected) { ArrayList<String> geocodes = new ArrayList<String>(); for (int i = 0; i < selected.length; i++) { geocodes.add(selected[i]); } setVisitDate(geocodes, 0); START } END This method could be written as ``` java public static void clearVisitDate(String[] selected) { setVisitDate(Arrays.asList(selected), 0); } ```

Target:
public static void clearVisitDate(String[] selected) { setVisitDate(Arrays.asList(selected), 0); }
Source:
public SearchResult loadInBackground() { loading = true; if (search == null) { search = runSearch(); } else { //Unless we make a new Search the Loader framework won't deliver results. It does't do equals only identity SearchResult newSearch = new SearchResult(search); newSearch.setUrl(search.getUrl()); START newSearch.setViewstates(search.getViewstates()); END search = GCParser.searchByNextPage(newSearch, Settings.isShowCaptcha(), this); } loading = false; return search; } I'm confused by those. Those fields (as well as `geocodes`, `error` and `totalCnt`) would have been copied already by the `new SearchResult(search)` constructor, wouldn't they?

Target:
public SearchResult loadInBackground() { loading = true; if (search == null) { search = runSearch(); } else { // Unless we make a new Search the Loader framework won't deliver results. It does't do equals only identity search = GCParser.searchByNextPage(new SearchResult(search), Settings.isShowCaptcha(), this); } loading = false; return search; }
Source:
public boolean isMapDatabaseSwitchSupported() { START return !getMapGenerator().requiresInternetConnection() END && null != Settings.getMapFile(); //if no file is specified in settings then disable the switch map option } This can be read easier by others by splitting the check using "guards style": http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html if (getMapGenerator.requiresInternetConnection()) { return false; } if (Settings.getMapFile() == null) { return false; } return true; And if you now want to ask: But isn't my original code much more compact and optimized? No, it is not. The compiler will create basically the same binary code for both versions. Besides that, even if there are differences in the binary, they don't matter. Code should always be optimized for readability and understandability, as that is the most severe problem in software development.

Target:
public boolean isMapDatabaseSwitchSupported() { if (getMapGenerator().requiresInternetConnection()) { return false; } if (null == Settings.getMapFile()) { //if no file is specified in settings then disable the switch map option return false; } return true; }
Source:
public boolean isEnabled(Geopoint geopoint) { if (geopoint == null) { return true; } START return false; END } This should be ``` java return geopoint == null; ``` but as I wrote, the semantics of this are questionable…

Target:
public boolean isEnabled(Geopoint geopoint) { return geopoint == null; }
Source:
START public synchronized void stopIt() { END stop = true; } Why do you make this synchronized? IMHO it can be stopped as many times as you wish.

Target:
public void stopIt() { stop = true; }
Source:
public cgeocoords(final AbstractActivity contextIn, cgSettings settingsIn, final Geopoint gpIn, final cgGeo geoIn) { super(contextIn); context = contextIn; settings = settingsIn; geo = geoIn; if (gpIn != null) { gp = gpIn; } else if (geo != null && geo.latitudeNow != null && geo.longitudeNow != null) { gp = new Geopoint(geo.latitudeNow, geo.longitudeNow); } else { START gp = new Geopoint(); END } } I removed the empty constructor because (0|0) doesn't make sense here. So there are two possibilities: - set valid coordinates (preferred) - set gp to null and check it later

Target:
public cgeocoords(final AbstractActivity contextIn, cgSettings settingsIn, final Geopoint gpIn, final cgGeo geoIn) { super(contextIn); context = contextIn; settings = settingsIn; geo = geoIn; if (gpIn != null) { gp = gpIn; } else if (geo != null && geo.latitudeNow != null && geo.longitudeNow != null) { gp = new Geopoint(geo.latitudeNow, geo.longitudeNow); } }
Source:
protected PreparedStatement getPreparedStatement(String query) throws SQLException { START return (connection.prepareStatement(query)); END } Unnecessary parenthesis

Target:
protected PreparedStatement getPreparedStatement(String query) throws SQLException { return connection.prepareStatement(query); }
Source:
START public void failToFindNonExistentElement() { END WebDriver d = getDriver(); d.get("http://www.google.com"); try { WebElement inputField = d.findElement(By.cssSelector("input[name='idontexist']")); fail(); } catch (NoSuchElementException e) { // expected } } There is a better way to handle the exception in a more JUnit-y way. See for example: http://www.mkyong.com/unittest/junit-4-tutorial-2-expected-exception-test/ If you update with this, I'll merge straightaway: the code itself looks great. Thanks ;)

Target:
public void failToFindNonExistentElement() { WebDriver d = getDriver(); d.get("http://www.google.com"); WebElement inputField = d.findElement(By.cssSelector("input[name='idontexist']")); }
Source:
public void peopleMessage(final PeopleDescription peopleDescription) { try { START peopleDescription.getMessage().toString(); END final Message m = Message.obtain(); m.what = ENQUEUE_PEOPLE; m.obj = peopleDescription; mWorker.runMessage(m); } catch (AssertionError e) { MPLog.e(LOGTAG, "Could not record people update (see https://github.com/mixpanel/mixpanel-android/issues/567)", e); } } Shouldn't it be already normalized in `MixpanelMessageDescription` constructor?

Target:
public void peopleMessage(final PeopleDescription peopleDescription) { final Message m = Message.obtain(); m.what = ENQUEUE_PEOPLE; m.obj = peopleDescription; mWorker.runMessage(m); }
Source:
public void testInvalidNotificationBadge() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); START intent.putExtra("mp_bdgcnt", "0"); END mpPushSpy.createNotification(intent); verify(builderSpy, never()).setNumber(any(Integer.class)); } it's unclear whether this is invalid because 0 is not valid or because it's a string. I'd recommend being a bit more specific here or potentially having two tests if both are invalid to make it clear what our expectations are.

Target:
public void testInvalidNotificationBadge() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_bdgcnt", 0); mpPushSpy.createNotification(intent); verify(builderSpy, never()).setNumber(any(Integer.class)); }
Source:
public void testNoChannelId() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); Notification notification = mpPushSpy.createNotification(intent); START verify(builderSpy).setChannelId(anyString()); END assertEquals(notification.getChannelId(), MixpanelPushNotification.NotificationData.DEFAULT_CHANNEL_ID); } can't we be more specific here and verify that `setChannelId(MixpanelPushNotification.NotificationData.DEFAULT_CHANNEL_ID)`?

Target:
public void testNoChannelId() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); Notification notification = mpPushSpy.createNotification(intent); verify(builderSpy).setChannelId(MixpanelPushNotification.NotificationData.DEFAULT_CHANNEL_ID); assertEquals(notification.getChannelId(), MixpanelPushNotification.NotificationData.DEFAULT_CHANNEL_ID); }
Source:
protected Bitmap getBitmapFromUrl(String url) { ImageStore is = new ImageStore(context, "MixpanelPushNotification"); try { Bitmap bm = is.getImage(url); START return bm; END } catch (ImageStore.CantGetImageException e) { return null; } } just return `is.getImage(url)` no need to create a local var

Target:
protected Bitmap getBitmapFromUrl(String url) { ImageStore is = new ImageStore(context, "MixpanelPushNotification"); try { return is.getImage(url); } catch (ImageStore.CantGetImageException e) { return null; } }
Source:
protected void maybeSetNotificationBadge(NotificationData data) { START if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE && data.badgeCount > 0) { END builder.setNumber(data.badgeCount); } } just to repeat the question I had in the test code, what happens if you set badgeCount to 0?

Target:
protected void maybeSetNotificationBadge(NotificationData data) { if (data.badgeCount > 0) { builder.setNumber(data.badgeCount); } }
Source:
START protected Intent buildIntentForUri(Uri uri) { END return new Intent(Intent.ACTION_VIEW, uri); } ```suggestion /* package */ Intent buildIntentForUri(Uri uri) { ```

Target:
/* package */ Intent buildIntentForUri(Uri uri) { return new Intent(Intent.ACTION_VIEW, uri); }
Source:
public double eventElapsedTime(final String eventName) { final long currentTime = System.currentTimeMillis(); long startTime; synchronized (mEventTimings) { START startTime = mEventTimings.get(eventName); END } return (double)((currentTime - startTime) / 1000); } We probably want to check if there is a timed event for the given name and return 0 in that case 👍

Target:
public double eventElapsedTime(final String eventName) { final long currentTime = System.currentTimeMillis(); Long startTime; synchronized (mEventTimings) { startTime = mEventTimings.get(eventName); } return startTime == null ? 0 : (double)((currentTime - startTime) / 1000); }
Source:
private boolean isInEmulator() { return Build.FINGERPRINT.startsWith("generic") START || Build.FINGERPRINT.startsWith("unknown") END || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") || Build.MANUFACTURER.contains("Genymotion") || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")) || "google_sdk".equals(Build.PRODUCT); } On the stackoverflow post there are 4 people suggesting `Build.MANUFACTURER.equals("unknown")`. Also, this library does it as well: https://github.com/gingo/android-emulator-detector/blob/master/EmulatorDetectorProject/EmulatorDetector/src/main/java/net/skoumal/emulatordetector/EmulatorDetector.java#L41 I think its worth to include it.

Target:
private boolean isInEmulator() { return Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") || Build.MANUFACTURER.contains("Genymotion") || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")) || Build.PRODUCT.equals("google_sdk"); }
Source:
private void handleVariantsReceived(JSONArray variants) { final SharedPreferences preferences = getSharedPreferences(); final SharedPreferences.Editor editor = preferences.edit(); START if(variants != null) { END editor.putString(SHARED_PREF_CHANGES_KEY, variants.toString()); } else { editor.remove(SHARED_PREF_CHANGES_KEY); } editor.apply(); initializeChanges(); } I am not a fan of using `null` as a meaningful value that will change the behavior/flow of the product. For instance, `variants` could be just an empty `JSONArray` if there are really no `variants`. The `SHARED_PREF_CHANGES_KEY` could always be in the device, just with empty variants.

Target:
private void handleVariantsReceived(JSONArray variants) { final SharedPreferences preferences = getSharedPreferences(); final SharedPreferences.Editor editor = preferences.edit(); if(variants.length() > 0) { editor.putString(SHARED_PREF_CHANGES_KEY, variants.toString()); } else { editor.remove(SHARED_PREF_CHANGES_KEY); } editor.apply(); initializeChanges(); }
Source:
public DecideMessages(String token, OnNewResultsListener listener, UpdatesFromMixpanel updatesFromMixpanel) { mToken = token; mListener = listener; mUpdatesFromMixpanel = updatesFromMixpanel; mDistinctId = null; mUnseenSurveys = new LinkedList<Survey>(); mUnseenNotifications = new LinkedList<InAppNotification>(); mSurveyIds = new HashSet<Integer>(); mNotificationIds = new HashSet<Integer>(); START if(mVariants == null) { END mVariants = new JSONArray(); } } `mVariants` will always be `null` here.

Target:
public DecideMessages(String token, OnNewResultsListener listener, UpdatesFromMixpanel updatesFromMixpanel) { mToken = token; mListener = listener; mUpdatesFromMixpanel = updatesFromMixpanel; mDistinctId = null; mUnseenSurveys = new LinkedList<Survey>(); mUnseenNotifications = new LinkedList<InAppNotification>(); mSurveyIds = new HashSet<Integer>(); mNotificationIds = new HashSet<Integer>(); mVariants = new JSONArray(); }
Source:
public String getStringValue() { String ret = null; try { ret = (String) defaultValue; START } catch (ClassCastException e2) { END ; // ok } try { ret = (String) value; } catch (ClassCastException e) { ; // ok } return ret; } should be `ClassCastException e`

Target:
public String getStringValue() { String ret = null; try { ret = (String) defaultValue; } catch (ClassCastException e) { ; // ok } try { ret = (String) value; } catch (ClassCastException e) { ; // ok } return ret; }
Source:
public void run() { if (!mAlive) { return; } final View viewRoot = mViewRoot.get(); if (null == viewRoot || mDying) { cleanUp(); return; } // ELSE View is alive and we are alive try { mEdit.visit(viewRoot); } catch (ViewVisitor.LayoutUpdateException e) { cleanUp(); START throw e; END } mHandler.removeCallbacks(this); mHandler.postDelayed(this, 1000); } I'm worried that this rethrow will crash the app. Perhaps LayoutUpdateException shouldn't be a runtime error?

Target:
public void run() { if (!mAlive) { return; } final View viewRoot = mViewRoot.get(); if (null == viewRoot || mDying) { cleanUp(); return; } // ELSE View is alive and we are alive mEdit.visit(viewRoot); mHandler.removeCallbacks(this); mHandler.postDelayed(this, 1000); }
Source:
public void visit(View rootView) { START if (mAlive) { END super.getPathfinder().findTargetsInRoot(rootView, super.getPath(), this); } } Great!

Target:
public void visit(View rootView) { if (mAlive) { getPathfinder().findTargetsInRoot(rootView, getPath(), this); } }
Source:
START public void onActivityCreated(Activity activity, Bundle savedInstanceState) { END checkForDecideUpdates(activity); } Is it okay to only checkForDecideUpdates() in onActivityResumed()? I think with the current logic, only one call is necessary now since we register the listeners.

Target:
public void onActivityCreated(Activity activity, Bundle savedInstanceState) { }
Source:
public static MPMetrics getInstance(Context context, String token) { MPMetrics instance = mInstanceMap.get(token); if (instance == null) { instance = new MPMetrics(context.getApplicationContext(), token); mInstanceMap.put(token, instance); } START instance.mPushPref.edit().putString("mp_token", token).commit(); END return instance; } I think the SharedPreferences will be shared across tokens, so if someone is using multiple tokens, this will overwrite the first token. And then you'll be writing device ids to the wrong project. Please check this.

Target:
public static MPMetrics getInstance(Context context, String token) { MPMetrics instance = mInstanceMap.get(token); if (instance == null) { instance = new MPMetrics(context.getApplicationContext(), token); mInstanceMap.put(token, instance); } return instance; }
Source:
START public void setProperties(List<String> properties) { END this.properties = properties; } Could have `@VisibleForTesting` annotation. Also could `public` be removed?

Target:
void setProperties(List<String> properties) { this.properties = properties; }
Source:
private String stream2String(InputStream in) { try { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int length; START while ((length = in.read(buffer)) != -1) { END result.write(buffer, 0, length); } return result.toString(StandardCharsets.UTF_8.name()); } catch (IOException e) { throw new UncheckedIOException(e); } } Configuration files are relatively small. Will this stream ever be sufficiently large to warrant this bufferred reading approach, rather than simply reading the whole stream in? We're eventually reading the whole stream into memory anyway. Why not just readFully or similar?

Target:
private String stream2String(InputStream in) { try { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString(UTF_8.name()); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
START private CompletableFuture<Void> rollbackLocks(CommitData cd) throws Exception { END CommitStep firstStep = new RollbackOtherLocks(); firstStep.andThen(new RollbackPrimaryLock()); return firstStep.compose(cd) .thenRun(() -> cd.commitObserver.commitFailed(cd.getShortCollisionMessage())); } I don't think this throws any checked exceptions, so could drop `throws Exception`.

Target:
private CompletableFuture<Void> rollbackLocks(CommitData cd) { CommitStep firstStep = new RollbackOtherLocks(); firstStep.andThen(new RollbackPrimaryLock()); return firstStep.compose(cd) .thenRun(() -> cd.commitObserver.commitFailed(cd.getShortCollisionMessage())); }
Source:
public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) { dest.clear(); for (int i = 0; i < timeStamps.size(); i++) { long time = timeStamps.get(i); if (timestampTest.test(time)) { START dest.add(new Key(key.getRow(), time), values.get(i)); END } } } It would be nice to avoid creating the key object. Since its the same class you can directly access private things in dest. Could directly add stuff to `dest.timeStamps` and `dest.values`. Alternatively, could create a private method like `private void add(long timestamp, Value v){...}` and call that method here. I think the private method is a little cleaner.

Target:
public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) { dest.clear(); if (key != null) { dest.key = new Key(key); } for (int i = 0; i < timeStamps.size(); i++) { long time = timeStamps.get(i); if (timestampTest.test(time)) { dest.add(time, values.get(i)); } } }
Source:
private synchronized void scheduleRetry() { START schedExecutor.schedule(() -> updatePartitionInfo(), retrySleepTime, TimeUnit.MILLISECONDS); END retrySleepTime = Math.min(maxSleepTime, (long) (1.5 * retrySleepTime) + (long) (retrySleepTime * Math.random())); } IntelliJ is suggesting to method reference `this::updatePartitionInfo` rather than `() -> updatePartitionInfo()`

Target:
private synchronized void scheduleRetry() { schedExecutor.schedule(this::updatePartitionInfo, retrySleepTime, TimeUnit.MILLISECONDS); retrySleepTime = Math.min(maxSleepTime, (long) (1.5 * retrySleepTime) + (long) (retrySleepTime * Math.random())); }
Source:
private synchronized void scheduleUpdate() { START schedExecutor.schedule(() -> updatePartitionInfo(), 0, TimeUnit.MILLISECONDS); END } Could use `this::updatePartionInfo`

Target:
private synchronized void scheduleUpdate() { schedExecutor.schedule(this::updatePartitionInfo, 0, TimeUnit.MILLISECONDS); }
Source:
START public void beginSecondCommitPhase(CommitData cd, Stamp commitStamp) throws Exception { END if (startTs < commitStamp.getGcTimestamp()) { rollbackOtherLocks(cd); } else { // Notification are written here for the following reasons : // * At this point all columns are locked, this guarantees that anything triggering as a // result of this transaction will see all of this transactions changes. // * The transaction is not yet committed. If the process dies at this point whatever // was running this transaction should rerun and recreate all of the notifications. // The next transactions will rerun because this transaction will have to be rolled back. // * If notifications are written in the 2nd phase of commit, then when the 2nd phase // partially succeeds notifications may never be written. Because in the case of failure // notifications would not be written until a column is read and it may never be read. // See https://github.com/fluo-io/fluo/issues/642 // // Its very important the notifications which trigger an observer are deleted after the 2nd // phase of commit finishes. getStats().setCommitTs(commitStamp.getTxTimestamp()); writeNotificationsAsync(cd, commitStamp.getTxTimestamp()); } } can be private

Target:
private void beginSecondCommitPhase(CommitData cd, Stamp commitStamp) throws Exception { if (startTs < commitStamp.getGcTimestamp()) { rollbackOtherLocks(cd); } else { // Notification are written here for the following reasons : // * At this point all columns are locked, this guarantees that anything triggering as a // result of this transaction will see all of this transactions changes. // * The transaction is not yet committed. If the process dies at this point whatever // was running this transaction should rerun and recreate all of the notifications. // The next transactions will rerun because this transaction will have to be rolled back. // * If notifications are written in the 2nd phase of commit, then when the 2nd phase // partially succeeds notifications may never be written. Because in the case of failure // notifications would not be written until a column is read and it may never be read. // See https://github.com/fluo-io/fluo/issues/642 // // Its very important the notifications which trigger an observer are deleted after the 2nd // phase of commit finishes. getStats().setCommitTs(commitStamp.getTxTimestamp()); writeNotificationsAsync(cd, commitStamp.getTxTimestamp()); } }
Source:
START public ListenableFuture<Void> writeMutationsAsyncFuture(Collection<Mutation> ml) { END if (ml.size() == 0) { return Futures.immediateFuture(null); } ListenableFutureTask<Void> lf = ListenableFutureTask.create(DO_NOTHING, null); try { MutationBatch mb = new MutationBatch(ml, lf); mutQueue.put(mb); return lf; } catch (Exception e) { throw new RuntimeException(e); } } Several methods in this class do not need to be public and can be package local

Target:
ListenableFuture<Void> writeMutationsAsyncFuture(Collection<Mutation> ml) { if (ml.size() == 0) { return Futures.immediateFuture(null); } ListenableFutureTask<Void> lf = ListenableFutureTask.create(DO_NOTHING, null); try { MutationBatch mb = new MutationBatch(ml, lf); mutQueue.put(mb); return lf; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
START public FluoConfiguration setPositiveInt(String property, int value) { END Preconditions.checkArgument(value > 0, property+" must be positive"); setProperty(property, value); return this; } why make these public and part of the API? I was thinking of these methods as implementation. If we make them part of API then we have to support them.

Target:
private FluoConfiguration setPositiveInt(String property, int value) { Preconditions.checkArgument(value > 0, property+" must be positive"); setProperty(property, value); return this; }
Source:
public static String parseRoot(String zookeepers) { int slashIndex = zookeepers.indexOf("/"); if (slashIndex != -1) { START return zookeepers.substring(slashIndex); END } return "/"; } could return `zookeepers.substring(slashIndex).trim()` to remove any trailing whitespace...

Target:
public static String parseRoot(String zookeepers) { int slashIndex = zookeepers.indexOf("/"); if (slashIndex != -1) { return zookeepers.substring(slashIndex).trim(); } return "/"; }
Source:
public MutationBuilder put(Column col, Bytes value) { START Flutation.put(null, mutation, col, ColumnConstants.DATA_PREFIX | 0, value.toArray()); END Flutation.put(null, mutation, col, ColumnConstants.WRITE_PREFIX | 1, WriteValue.encode(0, false, false)); return this; } what about creating a separate put method with no Environment parameter to avoid using null?

Target:
public MutationBuilder put(Column col, Bytes value) { Flutation.put(mutation, col, ColumnConstants.DATA_PREFIX | 0, value.toArray()); Flutation.put(mutation, col, ColumnConstants.WRITE_PREFIX | 1, WriteValue.encode(0, false, false)); return this; }
Source:
public Long allocateTimestamp() { START synchronized(status) { END Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp Long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } // retrieve timestamp to return Long ts = getTimestamp(); timestamps.add(ts); status = TrackerStatus.BUSY; //System.out.println("allocated "+ts); return ts; } } synchronizing on an object that changes in sync blocks is not good

Target:
public synchronized long allocateTimestamp() { // initialize zookeeper if idle and node does not exist Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } // retrieve timestamp to return long ts = getTimestamp(); // update timestamp set and status timestamps.add(ts); status = TrackerStatus.BUSY; return ts; }
Source:
public long allocateTimestamp() { // initialize zookeeper if idle and node does not exist synchronized(this) { Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp Long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } } // retrieve timestamp to return long ts = getTimestamp(); // update timestamp set and status synchronized(this) { START timestamps.add(ts); END status = TrackerStatus.BUSY; } return ts; } thinking about this some more, its possible that the zknode could be deleted (and state is set to IDLE) while lock was not held. That can be detected here, but then what? retry? An alternative to retrying would be to increment an allocating counter in the first block and decrement it in the second sync block. Code that deletes node would not do so if allocating counter > 0. Another alternative would be to use a read-write lock.

Target:
public synchronized long allocateTimestamp() { // initialize zookeeper if idle and node does not exist Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } // retrieve timestamp to return long ts = getTimestamp(); // update timestamp set and status timestamps.add(ts); status = TrackerStatus.BUSY; return ts; }