auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void returnIterator() throws IOException { final String user = "testuser1"; final RepoCommits commits = new MkRepoCommits( new MkStorage.InFile(), user, new Coordinates.Simple(user, "testrepo1") ); MatcherAssert.assertThat( commits.iterate( Collections.<String, String>emptyMap() ), START Matchers.notNullValue() END ); } looks like wrong indentation, maybe you forgot to run build with `qulice` profile enabled?

Target:
public void returnIterator() throws IOException { final String user = "testuser1"; MatcherAssert.assertThat( new MkRepoCommits( new MkStorage.InFile(), user, new Coordinates.Simple(user, "testrepo1") ).iterate(Collections.<String, String>emptyMap()), Matchers.notNullValue() ); }
Source:
public Tags tags() { START return new RtTags(this.entry, this.entry, this.owner); END } Why pass `this.entry` twice? Better just use one parameter if they're going to have the same value.

Target:
public Tags tags() { return new RtTags(this.entry, this.owner); }
Source:
START public static Repo repo() { END final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); final String keyrepo = System.getProperty("failsafe.github.repo"); Assume.assumeThat(keyrepo, Matchers.notNullValue()); return new RtGithub(key).repos().get(new Coordinates.Simple(keyrepo)); } This method should be `private` in visibility.

Target:
private static Repo repo() { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); final String keyrepo = System.getProperty("failsafe.github.repo"); Assume.assumeThat(keyrepo, Matchers.notNullValue()); return new RtGithub(key).repos().get(new Coordinates.Simple(keyrepo)); }
Source:
START public RtCollaborators(final Request req, final Repo repo) { END this.entry = req; final Coordinates coords = repo.coordinates(); this.request = this.entry.uri() .path("/repos") .path(coords.user()) .path(coords.repo()) .path("/collaborators") .back(); this.owner = repo; } don't make it public, see how it's done in `RtIssue`

Target:
RtCollaborators(final Request req, final Repo repo) { this.entry = req; final Coordinates coords = repo.coordinates(); this.request = this.entry.uri() .path("/repos") .path(coords.user()) .path(coords.repo()) .path("/collaborators") .back(); this.owner = repo; }
Source:
public Iterable<PullComment> iterate(final Map<String, String> params) { return new RtPagination<PullComment>( this.request.uri().queryParams(params).back(), new RtPagination.Mapping<PullComment, JsonObject>() { @Override public PullComment map(final JsonObject value) { START return new RtPullComment( END RtPullComments.this.request, RtPullComments.this.owner, value.getInt("id") ); } } ); } I think it's better to use `RtPullComments.this.get(value.getInt("id"))`

Target:
public Iterable<PullComment> iterate(final Map<String, String> params) { return new RtPagination<PullComment>( this.request.uri().queryParams(params).back(), new RtPagination.Mapping<PullComment, JsonObject>() { @Override public PullComment map(final JsonObject value) { return RtPullComments.this.get( value.getInt("id") ); } } ); }
Source:
private static JsonObject fork( START final String organization) throws Exception { END return Json.createObjectBuilder() .add("id", 1) .add(ORGANIZATION, organization) .build(); } I don't think that `Exception` can ever be thrown by this method

Target:
private static JsonObject fork( final String organization) { return Json.createObjectBuilder() .add("id", 1) .add(ORGANIZATION, organization) .build(); }
Source:
public void canFetchReadmeFileFromSpecifiedBranch() throws IOException { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_OK, "{\"name\": \"README.md\"}") ).start(); START final Contents contents = new RtContents( END new ApacheRequest(container.home()), RtContentsTest.repo()); MatcherAssert.assertThat( contents.readme("somebranch"), Matchers.notNullValue() ); container.stop(); } I test fails than container will remain started and port is busy. So, good practice is to enclose tested code in `try` block and stop container in `finally`

Target:
public void canFetchReadmeFileFromSpecifiedBranch() throws IOException { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_OK, "{\"name\": \"README.md\"}" ) ).start(); final Contents contents = new RtContents( new ApacheRequest(container.home()), RtContentsTest.repo() ); try { MatcherAssert.assertThat( contents.readme("somebranch"), Matchers.notNullValue() ); } finally { container.stop(); } }
Source:
public void retrievesForks() throws Exception { final RtForks forks = new RtForks(new FakeRequest(), this.repo()); MatcherAssert.assertThat( forks.iterate("newest"), START Matchers.notNullValue() END ); } the test checks nothing, because `iterate()` method always return nonNull object. It's worth to use `forks.iterate("newest").next()` and check for some attribute

Target:
public void retrievesForks() throws Exception { // To be implemented. }
Source:
public void getOrganization() throws Exception { final String login = "github"; final Github github = RtOrganizationsITCase.github(); final Organizations orgs = github.users().self().organizations(); START final Organization org = orgs.get(login); END MatcherAssert.assertThat(org.login(), Matchers.equalTo(login)); } A lot of one-time variables are created. Please, use this manual to fix https://github.com/tpc2/qulice/wiki/mistakes#wiki-one-time-variables

Target:
public void getOrganization() throws Exception { final String login = "github"; final Organization org = github() .users().self().organizations().get(login); MatcherAssert.assertThat(org.login(), Matchers.equalTo(login)); }
Source:
RtRepos(final Github github, final Request req) { this.ghub = github; this.entry = req; this.createRequest = this.entry.uri().path("user/repos").back(); START this.removeRequest = this.entry.uri().path("/repos").back(); END } What is the point of saving them in class variables, if they are used only once?

Target:
RtRepos(final Github github, final Request req) { this.ghub = github; this.entry = req; }
Source:
public void throwsWhenResourceIsAbsent() throws Exception { final Limit limit = Mockito.mock(Limit.class); final Throttled throttled = new Throttled(limit, 23); Mockito.when(limit.json()).thenReturn( Json.createObjectBuilder().add("absent", "absentValue").build() ); START throttled.json(); END MatcherAssert.assertThat( limit.json().toString(), Matchers.equalTo("{}") ); } Hm.. you are testing Mockito here, instead of our `Throttled` class :) Are you familiar with TDD, Mockito and JUnit? Can you explain the logic of this test method?

Target:
public void throwsWhenResourceIsAbsent() throws Exception { final Limit limit = Mockito.mock(Limit.class); final Throttled throttled = new Throttled(limit, 23); Mockito.when(limit.json()).thenReturn( Json.createObjectBuilder().add("absent", "absentValue").build() ); throttled.json(); }
Source:
public boolean starred() throws IOException { final List<String> xpath = this.storage.xml().xpath(String START .format("%s/@starred", this.xpath()) END ); return !xpath.isEmpty() && StringUtils.equalsIgnoreCase( MkGist.STARRED_VALUE, xpath.get(0) ); } Why did you leave String on a previous line?? See https://github.com/tpc2/qulice/wiki/mistakes#indentation

Target:
public boolean starred() throws IOException { final List<String> xpath = this.storage.xml().xpath( String.format("%s/@starred", this.xpath()) ); return !xpath.isEmpty() && StringUtils.equalsIgnoreCase( Boolean.toString(true), xpath.get(0) ); }
Source:
public void star() throws IOException { START final Directives gistlocation = new Directives().xpath( END this.xpath() ); final Directives attributelocation = gistlocation.attr( "starred", MkGist.STARRED_VALUE ); this.storage.apply( attributelocation ); } This is how it should look: ``` this.storage.apply( new Directives() .xpath(this.xpath()) .attr("starred", Boolean.toString(true)) ); ``` Looks good, huh?

Target:
public void star() throws IOException { this.storage.apply( new Directives() .xpath(this.xpath()) .attr("starred", Boolean.toString(true)) ); }
Source:
START public void getCashPointsByLocation_shouldReturnAnEmptyListIfTheLocationHasNoCashpoints() throws Exception { END Location location = Context.getLocationService().getLocation(1); List<CashPoint> results = service.getCashPointsByLocation(location,false); Assert.assertNotNull(results); Assert.assertEquals(1,results.size()); } This does not test what it says it is going to test. This should test that a location with no cash points returns a non-null list with zero items.

Target:
public void getCashPointsByLocation_shouldReturnAnEmptyListIfTheLocationHasNoCashpoints() throws Exception { Location location = Context.getLocationService().getLocation(4); List<CashPoint> results = service.getCashPointsByLocation(location,false); Assert.assertNotNull(results); Assert.assertEquals(0,results.size()); }
Source:
START public void findCashPoints_shouldThrowIllegalArgumentExceptionIfTheNameIsEmpty() throws Exception { END service.findCashPoints(Context.getLocationService().getLocation(1),"Test 1 Cash Point",false); } This test does not expect the exception nor pass in an empty string.

Target:
public void findCashPoints_shouldThrowIllegalArgumentExceptionIfTheNameIsEmpty() throws Exception { service.findCashPoints(Context.getLocationService().getLocation(1),"",false); }
Source:
public static Headers of(StringMap headers) { final Builder builder = new Builder(); if (headers == null) { return builder.build(); } START ; END headers.forEach(new StringMap.Consumer() { @Override public void accept(String key, Object value) { if (null != value) { builder.add(key, value.toString()); } } }); return builder.build(); } @sxci 这个分号？

Target:
public static Headers of(StringMap headers) { final Builder builder = new Builder(); if (headers == null) { return builder.build(); } headers.forEach(new StringMap.Consumer() { @Override public void accept(String key, Object value) { if (null != value) { builder.add(key, value.toString()); } } }); return builder.build(); }
Source:
START public static String userAgent() { END String javaVersion = "Java/" + System.getProperty("java.version"); String os = System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version"); String sdk = "QiniuJava/" + Constants.VERSION; return sdk + " (" + os + ") " + javaVersion; } 这个没有必要变更private属性？

Target:
private static String userAgent() { String javaVersion = "Java/" + System.getProperty("java.version"); String os = System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version"); String sdk = "QiniuJava/" + Constants.VERSION; return sdk + " (" + os + ") " + javaVersion; }
Source:
public String deleteApp(String appId) throws Exception { START String urlStr = String.format("%s%s%s", host + "/v3/apps/", appId); END StringMap headers = auth.authorizationV2(urlStr, "DELETE", null, null); Response response = client.delete(urlStr, headers); String[] resJson = response.getInfo().split("\n"); return response.statusCode + "\n" + resJson[2]; } 这里写错了，是 host, "/v3/apps/"

Target:
public String deleteApp(String appId) throws Exception { String urlStr = String.format("%s%s%s", host, "/v3/apps/", appId); StringMap headers = auth.authorizationV2(urlStr, "DELETE", null, null); Response response = client.delete(urlStr, headers); String[] resJson = response.getInfo().split("\n"); return response.statusCode + "\n" + resJson[2]; }
Source:
private String getLink(String appId, String roomName, String param) { StringBuilder builder = new StringBuilder(); builder.append(host); START builder.append("/v3/apps/" + appId + "/rooms"); END if (roomName != null) { builder.append("/" + roomName + "/"); } builder.append(param); return builder.toString(); } 如果用StringBuilder了，那仍然应该用append方法，不用再用 +，额外创建很多String对象

Target:
private String getLink(String appId, String roomName, String param) { StringBuilder builder = new StringBuilder(); builder.append(host); builder.append("/v3/apps/").append(appId).append("/rooms"); if (roomName != null) { builder.append("/").append(roomName).append("/"); } builder.append(param); return builder.toString(); }
Source:
private static void setKey(MultipartEntity requestEntity, String key) throws UnsupportedEncodingException{ START if(key != null && key.trim().length() > 0){ END requestEntity.addPart("key", new StringBody(key,Charset.forName("utf-8"))); } } 调用 key.trim() 干什么？ 另外，key.length() = 0 并不代表是非法的 key！

Target:
private static void setKey(MultipartEntity requestEntity, String key) throws UnsupportedEncodingException{ if(key != null){ requestEntity.addPart("key", new StringBody(key,Charset.forName("utf-8"))); } }
Source:
public PutPolicy(String scope, long expiry) { if (expiry <= 0) { throw new IllegalArgumentException("expiry can't be negative or zero!"); } if (scope == null || scope.trim().length() == 0) { START throw new IllegalArgumentException("scope can't be null or an empty value!"); END } this.scope = scope; this.expiry = System.currentTimeMillis() / 1000 + expiry; } PutPolicy.scope 是允许为空字符串的。

Target:
public PutPolicy(String scope, long expiry) { if (expiry <= 0) { throw new IllegalArgumentException("expiry can't be negative or zero!"); } this.scope = scope; this.expiry = System.currentTimeMillis() / 1000 + expiry; }
Source:
public GetPolicy(String scope, long expiry) { START if (scope == null || scope.trim().length() == 0) { END throw new IllegalArgumentException("scope can't be null or an empty value!"); } if (expiry <= 0) { throw new IllegalArgumentException("expiry can't be negative or zero!"); } this.expiry = System.currentTimeMillis() / 1000 + expiry; this.scope = scope; } scope.trim() 是何意？

Target:
public GetPolicy(String scope, long expiry) { if (scope == null || scope.length() == 0) { throw new IllegalArgumentException("scope can't be null or an empty value!"); } if (expiry <= 0) { throw new IllegalArgumentException("expiry can't be negative or zero!"); } this.expiry = System.currentTimeMillis() / 1000 + expiry; this.scope = scope; }
Source:
START public String makeRequest(String url) { END return url + "?exif"; } 因为没有成员，这个可以声明为 static 了。

Target:
public static String makeRequest(String url) { return url + "?exif"; }
Source:
START public String getImageMogrURL(String url, String params) { END return url + "?imageMogr/" + params ; } 这一系列方法都是无状态的，考虑声明成static。

Target:
public static String getImageMogrURL(String url, String params) { return url + "?imageMogr/" + params ; }
Source:
START public CallRet saveAs(String targetBucketName, String targetKey, String srcUrl, String opWirthParams) { END String entryUrl = targetBucketName + ":" + targetKey ; String encodedUrl = Client.urlsafeEncode(entryUrl) ; String url = srcUrl + "?" + opWirthParams + "/save-as/" + encodedUrl ; CallRet callRet = conn.call(url) ; return callRet ; } 目前只支持imageMogrify的saveas，这个方法不应该是public的

Target:
private CallRet saveAs(String targetBucketName, String targetKey, String srcUrl, String opWirthParams) { String entryUrl = targetBucketName + ":" + targetKey ; String encodedUrl = Client.urlsafeEncode(entryUrl) ; String url = srcUrl + "?" + opWirthParams + "/save-as/" + encodedUrl ; CallRet callRet = conn.call(url) ; return callRet ; }
Source:
protected void configure() { START install(new SingularityServiceModule()); END } side note to bringing in this dep, installing this module would also likely start up a number of pollers/db connections/zk connections/etc which we don't want

Target:
protected void configure() { }
Source:
public SingularityWebhookSender(SingularityConfiguration configuration, AsyncHttpClient http, ObjectMapper objectMapper, TaskHistoryHelper taskHistoryHelper, WebhookManager webhookManager) { this.configuration = configuration; this.http = http; this.webhookManager = webhookManager; this.taskHistoryHelper = taskHistoryHelper; this.objectMapper = objectMapper; this.webhookSemaphore = AsyncSemaphore.newBuilder(configuration::getMaxConcurrentWebhooks).build(); START this.webhookExecutorService = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("webhooks-%d").build()); END } Doesn't look like this guy is used anywhere after being created.

Target:
public SingularityWebhookSender(SingularityConfiguration configuration, AsyncHttpClient http, ObjectMapper objectMapper, TaskHistoryHelper taskHistoryHelper, WebhookManager webhookManager) { this.configuration = configuration; this.http = http; this.webhookManager = webhookManager; this.taskHistoryHelper = taskHistoryHelper; this.objectMapper = objectMapper; this.webhookSemaphore = AsyncSemaphore.newBuilder(configuration::getMaxConcurrentWebhooks).build(); }
Source:
private double getSystemLoadMetric() { switch (systemLoadMetric) { case LOAD_1: return slaveUsage.getSystemLoad1Min(); case LOAD_15: return slaveUsage.getSystemLoad5Min(); case LOAD_5: default: return slaveUsage.getSystemLoad15Min(); START } END } Fat-finger switcheroo here

Target:
private double getSystemLoadMetric() { switch (systemLoadMetric) { case LOAD_1: return slaveUsage.getSystemLoad1Min(); case LOAD_15: return slaveUsage.getSystemLoad15Min(); case LOAD_5: default: return slaveUsage.getSystemLoad5Min(); } }
Source:
START public long lock(String requestId, String name) { END final long start = System.currentTimeMillis(); LOG.trace("{} - Locking {}", name, requestId); ReentrantLock lock = requestLocks.computeIfAbsent(requestId, (r) -> new ReentrantLock()); lock.lock(); LOG.trace("{} - Acquired lock on ({})", name, requestId, JavaUtils.duration(start)); return System.currentTimeMillis(); } Could it be a good idea to accept the calling class here instead of a name, and then log out the class name in the trace logs below? Just to ensure that the names we pass when locking aren't arbitrary and are useful for tracing the flow of the scheduler.

Target:
private long lock(String requestId, String name) { final long start = System.currentTimeMillis(); LOG.trace("{} - Locking {}", name, requestId); ReentrantLock lock = requestLocks.computeIfAbsent(requestId, (r) -> new ReentrantLock()); lock.lock(); LOG.trace("{} - Acquired lock on ({})", name, requestId, JavaUtils.duration(start)); return System.currentTimeMillis(); }
Source:
START public void unlock(String requestId, String name, long start) { END LOG.trace("{} - Unlocking ({})", name, requestId, JavaUtils.duration(start)); ReentrantLock lock = requestLocks.computeIfAbsent(requestId, (r) -> new ReentrantLock()); lock.unlock(); } Should be safe to make `lock()` and `unlock()` private now, and only allow the rest of the scheduler to interact via `runWithRequestLock()`.

Target:
private void unlock(String requestId, String name, long start) { LOG.trace("{} - Unlocking ({})", name, requestId, JavaUtils.duration(start)); ReentrantLock lock = requestLocks.computeIfAbsent(requestId, (r) -> new ReentrantLock()); lock.unlock(); }
Source:
START public Optional<List<SingularityMesosArtifact>> getExtraArtifacts() { END return extraArtifacts; } Instead of passing Optional lists around, let’s just default it to an empty list if the constructor arg is null. Same for the other objects that use this. Will save a lot of isPresent being throw around

Target:
public List<SingularityMesosArtifact> getExtraArtifacts() { return extraArtifacts; }
Source:
public void testOneOffsDontMoveDuringDecomission() { SingularityRequestBuilder bldr = new SingularityRequestBuilder(requestId, RequestType.ON_DEMAND); requestResource.postRequest(bldr.build()); deploy("d2"); START requestResource.scheduleImmediately(requestId, Optional.absent()); END validateTaskDoesntMoveDuringDecommission(); } would it have made sense to create a method here that didn't take the second parameter?

Target:
public void testOneOffsDontMoveDuringDecomission() { SingularityRequestBuilder bldr = new SingularityRequestBuilder(requestId, RequestType.ON_DEMAND); requestResource.postRequest(bldr.build()); deploy("d2"); requestResource.scheduleImmediately(requestId); validateTaskDoesntMoveDuringDecommission(); }
Source:
private void checkOut() { LOG.trace("Checking out offer {}", offerId); START Preconditions.checkState(offerState == OfferState.AVAILABLE, "Offer %s was in state %s", offerId, offerState); END this.offerState = OfferState.CHECKED_OUT; } Saw a sentry come through for this the other day. This exception will bubble all the way back up to the LeaderOnlyPoller and cause us to abort. Should we maybe catch this and just skip the offer in the case that something else has it checked out?

Target:
private void checkOut() { Preconditions.checkState(offerState == OfferState.AVAILABLE, "Offer %s was in state %s", offerId, offerState); this.offerState = OfferState.CHECKED_OUT; }
Source:
START public Long getS3ChunkDownloadTimeoutMillis() { END return s3ChunkDownloadTimeoutMillis; } why `Long` here?

Target:
public int getS3ChunkDownloadTimeoutMillis() { return s3ChunkDownloadTimeoutMillis; }
Source:
public SingularityDeployProgress withCompletedStep() { START return new SingularityDeployProgress(targetActiveInstances, currentActiveInstances + 1, deployInstanceCountPerStep, deployStepWaitTimeMs, true, autoAdvanceDeploySteps, failedDeployTasks, System.currentTimeMillis()); END } is `currentActiveInstances + 1` correct here? wouldn't it be `currentActiveInstances + deployInstanceCountPerStep`?

Target:
public SingularityDeployProgress withCompletedStep() { return new SingularityDeployProgress(targetActiveInstances, currentActiveInstances, deployInstanceCountPerStep, deployStepWaitTimeMs, true, autoAdvanceDeploySteps, failedDeployTasks, System.currentTimeMillis()); }
Source:
START private static Boolean hasRole(Resource r) { END return r.hasRole() && !r.getRole().equals("*"); } can you switch to primitive `boolean`s instead? removes the potential for NullPointerExceptions

Target:
private static boolean hasRole(Resource r) { return r.hasRole() && !r.getRole().equals("*"); }
Source:
public void downloadFile(String uri, File target) { Matcher m = parseURI(uri); if (m.matches()) { try { START InputStream s = minioClient.getObject(m.group("bucket"), m.group("path")); END FileUtils.copyInputStreamToFile(s, target); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } } Is this stream getting closed? Add it to try block just in case: `try(InputStream s = minioClient.getObject(m.group("bucket"), m.group("path"))) {`

Target:
protected void downloadFile(String uri, File target) { Matcher m = parseURI(uri); if (m.matches()) { try (InputStream s = minioClient.getObject(m.group("bucket"), m.group("path"))) { FileUtils.copyInputStreamToFile(s, target); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } }
Source:
public void setSingleBlockMode(boolean singleBlockMode) { START logger.log(Level.INFO, "Setting singleBlockMode to ".concat((singleBlockMode)?"true":"false")); END this.singleBlockMode = singleBlockMode; changed(); } It's a matter of taste of course, but I'd prefer to use `Boolean.toString(singleBlockMode)` here.

Target:
public void setSingleBlockMode(boolean singleBlockMode) { logger.log(Level.INFO, "Setting singleBlockMode to ".concat( ((Boolean)singleBlockMode).toString() )); this.singleBlockMode = singleBlockMode; changed(); }
Source:
private void checkForLanguageChangeAndAskForRestart(UGSEvent ugsEvent) { if (ugsEvent.isSettingChangeEvent()) { if (!StringUtils.equalsIgnoreCase(lastSelectedLanguage, backend.getSettings().getLanguage())) { lastSelectedLanguage = backend.getSettings().getLanguage(); Localization.initialize(backend.getSettings().getLanguage()); notifyRestartRequired(); START } else if (!StringUtils.equalsIgnoreCase(lastSelectedConnectionClass, backend.getSettings().getConnectionClass())) { END notifyRestartRequired(); } } } Gotcha, because the settings are reloaded in the `ConnectionFactory` the app needs to flush the file first. You could also call `SettingsFactory.saveSettings(backend.getSettings())` instead of making the user restart the app. Or if it isn't too much work the connection-string idea.

Target:
private void checkForLanguageChangeAndAskForRestart(UGSEvent ugsEvent) { if (ugsEvent.isSettingChangeEvent() && !StringUtils.equalsIgnoreCase(lastSelectedLanguage, backend.getSettings().getLanguage())) { lastSelectedLanguage = backend.getSettings().getLanguage(); Localization.initialize(backend.getSettings().getLanguage()); notifyRestartRequired(); } }
Source:
protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); START AnkiDroidApp.updateContextWithLanguage(this); END } Are both of these lines required? I'd have expected we'd only need the `attachBaseContext`

Target:
protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); }
Source:
private void setCustomServerWithNoUrl() { SharedPreferences userPreferences = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance()); START userPreferences.edit().putBoolean("useCustomSyncServer", true).commit(); END } Just out of curiosity since you just up on SharedPreferences, why `commit` here vs `apply`? I scanned back and saw you used apply (correctly, I believe) in PreferenceBackedHostNum, and I think apply would be fine here as well. For the same reasons commit is typically unnecessary and may slow things down, I think it may be unnecessary and just slow testing down here, but perhaps I'm about to learn something about SharedPreferences, or I read it wrong

Target:
private void setCustomServerWithNoUrl() { SharedPreferences userPreferences = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance()); userPreferences.edit().putBoolean("useCustomSyncServer", true).apply(); }
Source:
public boolean newDue() { START return mCol.getDb().queryScalar("SELECT 1 FROM cards WHERE did IN " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_NEW + " LIMIT 1", new Object[] {_deckLimit()}) != 0; END } ⚠️ The parameter seems wrong

Target:
public boolean newDue() { return mCol.getDb().queryScalar("SELECT 1 FROM cards WHERE did IN " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_NEW + " LIMIT 1") != 0; }
Source:
public void load() { START if (mFutureTask != null) { END return; } mFutureTask = new FutureTask<Models> (() -> new Models(mCol).load(loadColumn("models"))); new Thread(mFutureTask).start(); } This function could potentially be called simultaneously from multiple threads which would lead to a race condition, so better make it `synchronized`

Target:
public synchronized void load() { if (mFutureTask != null) { return; } mFutureTask = new FutureTask<Models> (() -> new Models(mCol).load(loadColumn("models"))); new Thread(mFutureTask).start(); }
Source:
public void addSharedDeck() { START if(AdaptionUtil.hasWebBrowser(DeckPicker.this)) { openUrl(Uri.parse(getResources().getString(R.string.shared_decks_url))); }else { UIUtils.showThemedToast(DeckPicker.this, getResources().getString(R.string.no_browser_notification)+ getResources().getString(R.string.shared_decks_url), false); END } } ```suggestion if (AdaptionUtil.hasWebBrowser(DeckPicker.this)) { openUrl(Uri.parse(getResources().getString(R.string.shared_decks_url))); } else { UIUtils.showThemedToast(DeckPicker.this, getResources().getString(R.string.no_browser_notification) + getResources().getString(R.string.shared_decks_url), false); ```

Target:
public void addSharedDeck() { if (AdaptionUtil.hasWebBrowser(DeckPicker.this)) { openUrl(Uri.parse(getResources().getString(R.string.shared_decks_url))); } else { UIUtils.showThemedToast(DeckPicker.this, getResources().getString(R.string.no_browser_notification) + getResources().getString(R.string.shared_decks_url), false); } }
Source:
public Long[] cardIds() { Long[] cids; START if (mDid < 0) { END cids = Utils.list2ObjectArray(mCol.getDb().queryColumn(Long.class, "select id from cards", 0)); } else { cids = mCol.getDecks().cids(mDid, true); } mCount = cids.length; return cids; } Before we were checking if `mDid == null`, whereas now we're invoking the comparison operator without checking for null, which will presumably crash with NPE when it is indeed null...? This is a place we have to be extra careful when translating from Python. Could you please double check that it's correct for both branches?

Target:
public Long[] cardIds() { Long[] cids; if (mDid == null) { cids = Utils.list2ObjectArray(mCol.getDb().queryColumn(Long.class, "select id from cards", 0)); } else { cids = mCol.getDecks().cids(mDid, true); } mCount = cids.length; return cids; }
Source:
public Exporter(Collection col) { mCol = col; mDid = null; START mCids = null; END } Seems to be unused... What's going on here?

Target:
public Exporter(Collection col) { mCol = col; mDid = null; }
Source:
public static @Nullable JSONObject getTempModel(@NonNull String tempModelFileName) { Timber.d("getTempModel() fetching tempModel %s", tempModelFileName); try (ByteArrayOutputStream target = new ByteArrayOutputStream()) { CompatHelper.getCompat().copyFile(tempModelFileName, target); return new JSONObject(target.toString()); START } catch (IOException | JSONException e) { END Timber.e(e, "Unable to read+parse tempModel from file %s", tempModelFileName); return null; } } Would make sense to me to catch `Exception` here and return null on any failure, rather than on specific failures.

Target:
public static JSONObject getTempModel(@NonNull String tempModelFileName) throws IOException { Timber.d("getTempModel() fetching tempModel %s", tempModelFileName); try (ByteArrayOutputStream target = new ByteArrayOutputStream()) { CompatHelper.getCompat().copyFile(tempModelFileName, target); return new JSONObject(target.toString()); } catch (IOException e) { Timber.e(e, "Unable to read+parse tempModel from file %s", tempModelFileName); throw e; } }
Source:
public static void setLanguage(String localeCode) { Configuration config = getInstance().getResources().getConfiguration(); Locale newLocale = LanguageUtil.getLocale(localeCode); config.locale = newLocale; getInstance().getResources().updateConfiguration(config, getInstance().getResources().getDisplayMetrics()); // The notification channels have persistent user-visible text so we need language set first START AnkiDroidApp.getInstance().setupNotificationChannels(); END } A function called `setLanguage()` should set the language, nothing more nothing less... You can call `setupNotificationChannels()` immediately after the function is called without actually putting it inside the function, right?

Target:
public static void setLanguage(String localeCode) { Configuration config = getInstance().getResources().getConfiguration(); Locale newLocale = LanguageUtil.getLocale(localeCode); config.locale = newLocale; getInstance().getResources().updateConfiguration(config, getInstance().getResources().getDisplayMetrics()); }
Source:
START public static String getName(Channel channel, Resources res) { END switch (channel) { case SYNC: return res.getString(R.string.sync_title); case GLOBAL_REMINDERS: return res.getString(R.string.widget_minimum_cards_due_notification_ticker_title); case DECK_REMINDERS: return res.getString(R.string.deck_conf_reminders); case GENERAL: default: return res.getString(R.string.app_name); } } Is it a lot of work to make this private?

Target:
private static String getName(Channel channel, Resources res) { switch (channel) { case SYNC: return res.getString(R.string.sync_title); case GLOBAL_REMINDERS: return res.getString(R.string.widget_minimum_cards_due_notification_ticker_title); case DECK_REMINDERS: return res.getString(R.string.deck_conf_reminders); case GENERAL: default: return res.getString(R.string.app_name); } }
Source:
START public void setDebugACRAConfig(SharedPreferences prefs) { END // Disable crash reporting setAcraReportingMode(FEEDBACK_REPORT_NEVER); prefs.edit().putString(FEEDBACK_REPORT_KEY, FEEDBACK_REPORT_NEVER).apply(); // Use a wider logcat filter in case crash reporting manually re-enabled String logcatArgs = { "-t", "300", "-v", "long", "ACRA:S"}; setAcraConfigBuilder(getAcraCoreConfigBuilder().setLogcatArguments(logcatArgs)); } Can you make these methods private? I know you're using them in the unit test, but I think you can use the deencapsulation feature of the testing framework, right? The interface of a class should not be changed to accommodate a unit test.

Target:
private void setDebugACRAConfig(SharedPreferences prefs) { // Disable crash reporting setAcraReportingMode(FEEDBACK_REPORT_NEVER); prefs.edit().putString(FEEDBACK_REPORT_KEY, FEEDBACK_REPORT_NEVER).apply(); // Use a wider logcat filter in case crash reporting manually re-enabled String logcatArgs = { "-t", "300", "-v", "long", "ACRA:S"}; setAcraConfigBuilder(getAcraCoreConfigBuilder().setLogcatArguments(logcatArgs)); }
Source:
START public void setAcraConfigBuilder(CoreConfigurationBuilder acraCoreConfigBuilder) { END this.acraCoreConfigBuilder = acraCoreConfigBuilder; ACRA.init(this, acraCoreConfigBuilder); } This should be private

Target:
private void setAcraConfigBuilder(CoreConfigurationBuilder acraCoreConfigBuilder) { this.acraCoreConfigBuilder = acraCoreConfigBuilder; ACRA.init(this, acraCoreConfigBuilder); }
Source:
private void onCheckAll() { boolean all = mCheckedCardPositions.size() < getCards().size(); if (all) { START for (int i = 0; i < mCards.size(); i++) END mCheckedCardPositions.add(i); } else { mCheckedCardPositions.clear(); } updateMultiselectMenu(); mActionBarTitle.setText(Integer.toString(mCheckedCardPositions.size())); mCardsAdapter.notifyDataSetChanged(); } braces

Target:
private void onCheckAll() { boolean all = mCheckedCardPositions.size() < getCards().size(); if (all) { for (int i = 0; i < mCards.size(); i++) { mCheckedCardPositions.add(i); } } else { mCheckedCardPositions.clear(); } updateMultiselectMenu(); mActionBarTitle.setText(Integer.toString(mCheckedCardPositions.size())); mCardsAdapter.notifyDataSetChanged(); }
Source:
private static String _imgLink(Collection col, String latex, JSONObject model) { String txt = _latexFromHtml(col, latex); String ext = "png"; START if (model.optBoolean("latexsvg", false)) END ext = "svg"; String fname = "latex-" + Utils.checksum(txt) + "." + ext; return "<img class=latex src=\"" + fname + "\">"; } Please use braces here

Target:
private static String _imgLink(Collection col, String latex, JSONObject model) { String txt = _latexFromHtml(col, latex); String ext = "png"; if (model.optBoolean("latexsvg", false)) { ext = "svg"; } String fname = "latex-" + Utils.checksum(txt) + "." + ext; return "<img class=latex src=\"" + fname + "\">"; }
Source:
protected void onHandleIntent(Intent intent) { START if (sWasRun) END return; scheduleDeckReminder(); scheduleNotification(this); sWasRun = true; } Please use braces with your one-line `if` statements

Target:
protected void onHandleIntent(Intent intent) { if (sWasRun) { return; } scheduleDeckReminder(); scheduleNotification(this); sWasRun = true; }
Source:
public long abort() throws UnknownHttpResponseException { START return parseLong(_run("abort", new JSONObject())); END } abort doesn't modify the mod time, so there's no value to return. it's probably returning None encoded as json (null), but as long as you get a 200 reply the command succeeded

Target:
public void abort() throws UnknownHttpResponseException { _run("abort", new JSONObject()); }
Source:
public void applyChunk(JSONObject sech) throws UnknownHttpResponseException { START parseDict(_run("applyChunk", sech)); END } The return value can be ignored https://github.com/dae/anki/blob/master/anki/sync.py#L177

Target:
public void applyChunk(JSONObject sech) throws UnknownHttpResponseException { _run("applyChunk", sech); }
Source:
private String getLogMessage(String methodName, Uri uri) { String format = "%s.%s %s"; String path = uri == null ? null : uri.getPath(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return String.format(format, CardContentProvider.class.getSimpleName(), methodName, path); } else { START return String.format(format + " (%s)", CardContentProvider.class.getSimpleName(), methodName, path, getCallingPackage()); END } } Use getClass() in these two places.

Target:
private String getLogMessage(String methodName, Uri uri) { String format = "%s.%s %s"; String path = uri == null ? null : uri.getPath(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return String.format(format, getClass().getSimpleName(), methodName, path); } else { return String.format(format + " (%s)", getClass().getSimpleName(), methodName, path, getCallingPackage()); } }
Source:
public int getProviderSpecVersionCode() { try { // the Android documentation for PackageManager#resolveContentProvider suggests flags should be 0, but GET_META_DATA seems to work anyway ProviderInfo info = mContext.getPackageManager().resolveContentProvider(FlashCardsContract.AUTHORITY, PackageManager.GET_META_DATA); if (info == null) { return -1; } Bundle metaData = info.metaData; if (metaData == null) { // this happens for one of two reasons: // 1. There are no metadata keys specified for the provider // 2. if we use the flag 0 instead of PackageManager.GET_META_DATA in PackageManager#resolveContentProvider() // we should presume the first one (and so return the default), since the second one is a programming error return DEFAULT_PROVIDER_SPEC_VALUE; } if (info.metaData.containsKey(PROVIDER_SPEC_META_DATA_KEY)) { return info.metaData.getInt(PROVIDER_SPEC_META_DATA_KEY); } else { return DEFAULT_PROVIDER_SPEC_VALUE; } } START catch (Throwable t) { END //Timber.w("metaDataKeyError: " + key, t); return -2; } } It looks like you missed my edits to `getProviderSpecVersionCode()`... 9 lines vs. 24 lines in yours

Target:
private int getProviderSpecVersionCode() { // PackageManager#resolveContentProvider docs suggest flags should be 0 (but that gives null metadata) // GET_META_DATA seems to work anyway ProviderInfo info = mContext.getPackageManager().resolveContentProvider(FlashCardsContract.AUTHORITY, PackageManager.GET_META_DATA); if (info == null) { return -1; } if (info.metaData != null && info.metaData.containsKey(PROVIDER_SPEC_META_DATA_KEY)) { return info.metaData.getInt(PROVIDER_SPEC_META_DATA_KEY); } else { return DEFAULT_PROVIDER_SPEC_VALUE; } }
Source:
public NexusUnexpectedResponseException( final int statusCode, final String statusMessage ) { this( statusCode, statusMessage, String.format( "Unexpected response: %s %s", String.valueOf( statusCode ), String.valueOf( statusMessage ) ) ); START } END Uneeded String.valueOf() in arguments to String.format()

Target:
public NexusUnexpectedResponseException( final int statusCode, final String statusMessage ) { this( statusCode, statusMessage, String.format( "Unexpected response: %s %s", statusCode, statusMessage ) ); }
Source:
public void onAdjustment( final FixedRateWalkerThrottleController controller ) { START logger.info( END "Current speed upgrades/sec, with average upgrade/sec (is limited to upgrades/sec), currently sleeping {}ms per upgrade.", new Object[] { controller.getLastSliceTps(), controller.getGlobalAverageTps(), controller.getLimiterTps(), controller.getCurrentSleepTime() } ); } Probably better to have this at DEBUG level for final release.

Target:
public void onAdjustment( final FixedRateWalkerThrottleController controller ) { logger.debug( "Current speed upgrades/sec, with average upgrade/sec (is limited to upgrades/sec), currently sleeping {}ms per upgrade.", new Object[] { controller.getLastSliceTps(), controller.getGlobalAverageTps(), controller.getLimiterTps(), controller.getCurrentSleepTime() } ); }
Source:
START public List<LauncherActivityInfo> getActivityList(String packageName, UserHandle user) { END final Predicate<LauncherActivityInfo> predicatePackage = info -> info.getComponentName() != null && packageName != null && packageName.equals(info.getComponentName().getPackageName()); return activityList.get(user).stream().filter(predicatePackage).collect(Collectors.toList()); } nit: @Implementation should be protected to avoid introducing extra shadow APIs

Target:
protected List<LauncherActivityInfo> getActivityList(String packageName, UserHandle user) { final Predicate<LauncherActivityInfo> predicatePackage = info -> info.getComponentName() != null && packageName != null && packageName.equals(info.getComponentName().getPackageName()); return activityList.get(user).stream().filter(predicatePackage).collect(Collectors.toList()); }
Source:
public MqttConnectOptions getConnectionInfo() { MqttConnectOptions options = this.clientFactory.getConnectionOptions(); if (options.getServerURIs() == null && getUrl() != null) { options = MqttUtils.cloneConnectOptions(options); START options.setServerURIs(new String[] { getUrl() }); END } return options; } Better to extract local variable for `URL` to avoid noise from Sonar that we defer NPE calling the method several times.

Target:
public MqttConnectOptions getConnectionInfo() { MqttConnectOptions options = this.clientFactory.getConnectionOptions(); if (options.getServerURIs() == null) { String url = getUrl(); if (url != null) { options = MqttUtils.cloneConnectOptions(options); options.setServerURIs(new String[] { url }); } } return options; }
Source:
public MqttConnectOptions getConnectionInfo() { MqttConnectOptions options = this.clientFactory.getConnectionOptions(); if (options.getServerURIs() == null && getUrl() != null) { START if (options.getServerURIs() == null && getUrl() != null) { END options = MqttUtils.cloneConnectOptions(options); options.setServerURIs(new String[] { getUrl() }); } options.setServerURIs(new String[] { getUrl() }); } return options; } Looks like duplication for this `if`s

Target:
public MqttConnectOptions getConnectionInfo() { MqttConnectOptions options = this.clientFactory.getConnectionOptions(); if (options.getServerURIs() == null) { String url = getUrl(); if (url != null) { options = MqttUtils.cloneConnectOptions(options); options.setServerURIs(new String[] { url }); } } return options; }
Source:
START public final void setSendTimeoutExpression(Expression sendTimeoutExpression) { END Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null"); this.sendTimeoutExpression = sendTimeoutExpression; } Looks like you have changed your mind and decided to not use this setter in the ctor. I mean doesn't look like there is still a justification for a `final`...

Target:
public void setSendTimeoutExpression(Expression sendTimeoutExpression) { Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null"); this.sendTimeoutExpression = sendTimeoutExpression; }
Source:
public void destroy() throws Exception { this.pool.close(); START this.pool.removeAllIdleItems(); END } Why that new `close()` can't do this for us, too?

Target:
public void destroy() throws Exception { this.pool.close(); }
Source:
public void setReplyChannel(MessageChannel replyChannel) { START this.setOutputChannel(replyChannel); END } `this.` on method calls? I guess you have just moved those existing setter over here for better class structure. Nevertheless can we fix `this.` as well since we are already here in a change?

Target:
public void setReplyChannel(MessageChannel replyChannel) { setOutputChannel(replyChannel); }
Source:
public Integer getId() { START return id; END } `this.` prefix should be used for class properties.

Target:
public Integer getId() { return this.id; }
Source:
public void acknowledge() { if (this.ackClient != null || !this.ackClient.equals(MqttPahoMessageDrivenChannelAdapter.this.client)) { try { this.ackClient.messageArrivedComplete(this.id, this.qos); } catch (MqttException e) { throw new IllegalStateException(e); } } else { START throw new IllegalStateException("Client has changed"); END } } I wonder why do we care about this. We are just have her self-containing `AcknowledgmentImpl` with the client it has been created. If that client becomes invalid at the moment of `acknowledge()` we have nothing to do anyway. What am I missing?

Target:
public void acknowledge() { if (this.ackClient != null) { try { this.ackClient.messageArrivedComplete(this.id, this.qos); } catch (MqttException e) { throw new IllegalStateException(e); } } else { throw new IllegalStateException("Client has changed"); } }
Source:
public void addSessionFactory(String key, SessionFactory<F> factory) { START this.factories.put(key, factory); END } I have an opinion that deprecated API should call a new one for better coverage. This way when we need to make a change in the target logic, a deprecated API won't be affected because it is meant to be for removal eventually anyway. 😄

Target:
public void addSessionFactory(String key, SessionFactory<F> factory) { addSessionFactory((Object) key, factory); }
Source:
START AmqpOutboundChannelAdapterSpec(AmqpTemplate amqpTemplate) { END super(amqpTemplate, false); } Gary, can you make all the ctors and `final` props in these AMQP specs as `protected` for possible extension? So, I won't include them into my extensions PR #3167 to avoid conflicts between our two fixes. Thanks

Target:
protected AmqpOutboundChannelAdapterSpec(AmqpTemplate amqpTemplate) { super(amqpTemplate, false); }
Source:
public AbstractHttpRequestExecutingMessageHandler(Expression uriExpression) { Assert.notNull(uriExpression, "URI Expression is required"); this.uriExpression = uriExpression; START this.uriFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.TEMPLATE_AND_VALUES); END } Why is this needed? This is the default.

Target:
public AbstractHttpRequestExecutingMessageHandler(Expression uriExpression) { Assert.notNull(uriExpression, "URI Expression is required"); this.uriExpression = uriExpression; }
Source:
public void subscribe(Subscriber<? super Message<?>> subscriber) { this.processor .doFinally((s) -> this.subscribedSignal.onNext(this.processor.hasDownstreams())) .subscribe(subscriber); if (this.processor.hasDownstreams()) { START this.subscribedSignal.onNext(true); END } } probably `this.subscribedSignal.onNext(this.processor.hasDownstreams())` would be better

Target:
public void subscribe(Subscriber<? super Message<?>> subscriber) { this.processor .doFinally((s) -> this.subscribedSignal.onNext(this.processor.hasDownstreams())) .subscribe(subscriber); this.subscribedSignal.onNext(this.processor.hasDownstreams()); }
Source:
public void processBeforeCommit(IntegrationResourceHolder holder) { START if (this.beforeCommitChannel != null) { END doProcess(holder, this.beforeCommitExpression, this.beforeCommitChannel, "beforeCommit"); } } I don't this this is right solution. We don't need to to build and send a message only when there is no particular channel.

Target:
public void processBeforeCommit(IntegrationResourceHolder holder) { doProcess(holder, this.beforeCommitExpression, this.beforeCommitChannel, "beforeCommit"); }
Source:
START private Channels() { END } Best to leave super() to avoid empty block complaint from Sonar.

Target:
private Channels() { super(); }
Source:
protected Duration getConfirmTimeout() { START if (this.confirmTimeout == null) { END return DEFAULT_CONFIRM_TIMEOUT; } return this.confirmTimeout; } Can't we have a `confirmTimeout` initialized with `DEFAULT_CONFIRM_TIMEOUT` by default? I see there is a logic where `if (this.confirmTimeout != null)` though, but why then just don't return that `null` with an appropriate `@Nullable` on this method instead? I think that way we would have a consistency with the current logic and what is possible with this `getConfirmTimeout()` in the inheritors.

Target:
protected Duration getConfirmTimeout() { return this.confirmTimeout; }
Source:
public String toString() { return "FileWrittenEvent [remoteHandle=" + this.remoteHandle + ", file=" + this.file + ", dataLen=" START + this.dataLen + ", cause=" + this.cause + ", clientAddress=" END + getSession().getClientAddress() + "]"; } I think `cause` should be conditional because it can be `null`. Therefore an explicit `StringBuilder` instead.

Target:
public String toString() { return "FileWrittenEvent [remoteHandle=" + this.remoteHandle + ", file=" + this.file + ", dataLen=" + this.dataLen + (this.cause == null ? "" : ", cause=" + this.cause) + ", clientAddress=" + getSession().getClientAddress() + "]"; }