auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public CauseOfBlockage getCauseOfBlockage() { long diff = -(System.currentTimeMillis() - timestamp.getTimeInMillis()); if (diff > 100) return CauseOfBlockage.fromMessage(Messages._Queue_InQuietPeriod(Util.getTimeSpanString(diff))); else return CauseOfBlockage.fromMessage(Messages._Queue_FinishedWaiting()); }

Target:
public CauseOfBlockage getCauseOfBlockage() { long diff = timestamp.getTimeInMillis() - System.currentTimeMillis(); if (diff >= 0) return CauseOfBlockage.fromMessage(Messages._Queue_InQuietPeriod(Util.getTimeSpanString(diff))); else return CauseOfBlockage.fromMessage(Messages._Queue_FinishedWaiting()); }
Source:
public StreamTaskListener(Writer w) throws IOException { // It's not possible to retrieve the charset that the writer is using; // however, for all uses of this constructor, the writer is an instance // of StringWriter, so it's okay to assume UTF-8. this(new WriterOutputStream(w), StandardCharsets.UTF_8); }

Target:
public StreamTaskListener(Writer w) throws IOException { // It's not possible to retrieve the charset that the writer is using; // however, for all uses of this constructor, the writer is an instance // of StringWriter, so it's okay to assume UTF-8. this(new WriterOutputStream(w, StandardCharsets.UTF_8), StandardCharsets.UTF_8); }
Source:
private static void _chmod(File f, int mask) throws IOException { // TODO WindowsPosix actually does something here (WindowsLibC._wchmod); should we let it? // Anyway the existing calls already skip this method if on Windows. if (File.pathSeparatorChar==';') return; // noop if (Util.NATIVE_CHMOD_MODE) { PosixAPI.jnr().chmod(f.getAbsolutePath(), mask); } else { Files.setPosixFilePermissions(Util.fileToPath(f).toAbsolutePath(), Util.modeToPermissions(mask)); } }

Target:
private static void _chmod(File f, int mask) throws IOException { // TODO WindowsPosix actually does something here (WindowsLibC._wchmod); should we let it? // Anyway the existing calls already skip this method if on Windows. if (File.pathSeparatorChar==';') return; // noop if (Util.NATIVE_CHMOD_MODE) { PosixAPI.jnr().chmod(f.getAbsolutePath(), mask); } else { Files.setPosixFilePermissions(Util.fileToPath(f), Util.modeToPermissions(mask)); } }
Source:
public void verifyRestartable() throws RestartNotSupportedException { // see http://lists.apple.com/archives/cocoa-dev/2005/Oct/msg00836.html and // http://factor-language.blogspot.com/2007/07/execve-returning-enotsup-on-mac-os-x.html // on Mac, execv fails with ENOTSUP if the caller is multi-threaded, resulting in an error like // the one described in http://www.nabble.com/Restarting-hudson-not-working-on-MacOS--to24641779.html // // according to http://www.mail-archive.com/wine-devel@winehq.org/msg66797.html this now works on Snow Leopard if (EXIT_ON_RESTART == null) { if (Platform.isDarwin() && !Platform.isSnowLeopardOrLater()) throw new RestartNotSupportedException("Restart is not supported on Mac OS X"); if (args==null) throw new RestartNotSupportedException("Failed to obtain the command line arguments of the process",failedToObtainArgs); } }

Target:
public void verifyRestartable() throws RestartNotSupportedException { // see http://lists.apple.com/archives/cocoa-dev/2005/Oct/msg00836.html and // http://factor-language.blogspot.com/2007/07/execve-returning-enotsup-on-mac-os-x.html // on Mac, execv fails with ENOTSUP if the caller is multi-threaded, resulting in an error like // the one described in http://www.nabble.com/Restarting-hudson-not-working-on-MacOS--to24641779.html // // according to http://www.mail-archive.com/wine-devel@winehq.org/msg66797.html this now works on Snow Leopard if (Platform.isDarwin() && !Platform.isSnowLeopardOrLater()) throw new RestartNotSupportedException("Restart is not supported on Mac OS X"); if (args==null) throw new RestartNotSupportedException("Failed to obtain the command line arguments of the process",failedToObtainArgs); }
Source:
public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder sib = new SearchIndexBuilder().addAllAnnotations(this); sib.add(new CollectionSearchIndex<TopLevelItem>() {// for jobs in the view protected TopLevelItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } @Override protected String getName(TopLevelItem o) { // return the name instead of the display for suggestion searching return o.getName(); } }); // add the display name for each item in the search index addDisplayNamesToSearchIndex(sib, getItems(false)); return sib; }

Target:
public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder sib = new SearchIndexBuilder().addAllAnnotations(this); sib.add(new CollectionSearchIndex<TopLevelItem>() {// for jobs in the view protected TopLevelItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } @Override protected String getName(TopLevelItem o) { // return the name instead of the display for suggestion searching return o.getName(); } }); // add the display name for each item in the search index addDisplayNamesToSearchIndex(sib, getItems(true)); return sib; }
Source:
public VersionNumber getNeededDependenciesRequiredCore() { VersionNumber versionNumber = null; try { versionNumber = requiredCore == null ? null : new VersionNumber(requiredCore); } catch (NumberFormatException nfe) { // unable to parse version } for (Plugin p: getAllDependencies()) { VersionNumber v = new VersionNumber(p.version); if (versionNumber == null || v.isNewerThan(versionNumber)) versionNumber = v; } return versionNumber; }

Target:
public VersionNumber getNeededDependenciesRequiredCore() { VersionNumber versionNumber = null; try { versionNumber = requiredCore == null ? null : new VersionNumber(requiredCore); } catch (NumberFormatException nfe) { // unable to parse version } for (Plugin p: getAllDependencies()) { VersionNumber v = new VersionNumber(p.requiredCore); if (versionNumber == null || v.isNewerThan(versionNumber)) versionNumber = v; } return versionNumber; }
Source:
public View getView(String name) { for (View v : views) { if (v.getViewName().equals(name)) return v; if (v instanceof ViewGroup) { View nestedView = ((ViewGroup) v).getView(name); if (nestedView != null) { return nestedView; } } } return null; }

Target:
public View getView(String name) { //Top level views returned first if match for (View v : views) { if (v.getViewName().equals(name)) { return v; } } for (View v : views) { if (v instanceof ViewGroup) { View nestedView = ((ViewGroup) v).getView(name); if (nestedView != null) { return nestedView; } } } return null; }
Source:
public void onRollback(@Nonnull NodeProvisioner.PlannedNode plannedNode, @Nonnull Node node, @Nonnull Throwable t) { ; // Noop by default }

Target:
public void onRollback(@Nonnull NodeProvisioner.PlannedNode plannedNode, @Nonnull Node node, @Nonnull Throwable t) { // Noop by default }
Source:
private Object readResolve() { // If we get invalid state from the configuration, fallback to unknown if (StringUtils.isBlank(name)) { LOGGER.log(Level.WARNING, "Read install state with blank name: ''{0}''. It will be ignored", name); return UNKNOWN; } InstallState state = InstallState.valueOf(name); if (state == null) { LOGGER.log(Level.WARNING, "Cannot locate an extension point for the state ''{0}''. It will be ignored", name); return UNKNOWN; } // Otherwise we return the actual state return state; }

Target:
protected Object readResolve() { // If we get invalid state from the configuration, fallback to unknown if (StringUtils.isBlank(name)) { LOGGER.log(Level.WARNING, "Read install state with blank name: ''{0}''. It will be ignored", name); return UNKNOWN; } InstallState state = InstallState.valueOf(name); if (state == null) { LOGGER.log(Level.WARNING, "Cannot locate an extension point for the state ''{0}''. It will be ignored", name); return UNKNOWN; } // Otherwise we return the actual state return state; }
Source:
public void writeToAtomicFile() throws Exception { // Given afw.write(expectedContent, 0, expectedContent.length()); // When afw.flush(); // Then assertTrue("File writer did not properly flush to temporary file", Files.size(afw.getTemporaryPath()) == expectedContent.length()); }

Target:
public void writeToAtomicFile() throws Exception { // Given afw.write(expectedContent, 0, expectedContent.length()); // When afw.flush(); // Then assertEquals("File writer did not properly flush to temporary file", expectedContent.length(), Files.size(afw.getTemporaryPath())); }
Source:
public static String resolveSymlink(@Nonnull File link) throws InterruptedException, IOException { try { Path path = link.toPath(); return Files.readSymbolicLink(path).toString(); } catch (UnsupportedOperationException | FileSystemException x) { // no symlinks on this platform (windows?), // or not a link (// Thrown ("Incorrect function.") on JDK 7u21 in Windows 2012 when called on a non-symlink, // rather than NotLinkException, contrary to documentation. Maybe only when not on NTFS?) ? return null; } catch (Exception x) { throw (IOException) new IOException(x.toString()).initCause(x); } }

Target:
public static String resolveSymlink(@Nonnull File link) throws InterruptedException, IOException { try { Path path = link.toPath(); return Files.readSymbolicLink(path).toString(); } catch (UnsupportedOperationException | FileSystemException x) { // no symlinks on this platform (windows?), // or not a link (// Thrown ("Incorrect function.") on JDK 7u21 in Windows 2012 when called on a non-symlink, // rather than NotLinkException, contrary to documentation. Maybe only when not on NTFS?) ? return null; } catch (IOException x) { throw x; } catch (Exception x) { throw (IOException) new IOException(x.toString()).initCause(x); } }
Source:
public void onLoaded() { wa.contextDestroyed(null); // make the Jenkins.<init> thread abort throw new Error(); }

Target:
public void onLoaded() { wa.contextDestroyed(null); }
Source:
/*package*/ void resolvePluginDependencies() throws IOException { List<Dependency> missingDependencies = new ArrayList<Dependency>(); // make sure dependencies exist for (Dependency d : dependencies) { if (parent.getPlugin(d.shortName) == null) missingDependencies.add(d); } if (!missingDependencies.isEmpty()) throw new MissingDependencyException(missingDependencies); // add the optional dependencies that exists for (Dependency d : optionalDependencies) { if (parent.getPlugin(d.shortName) != null) dependencies.add(d); } }

Target:
/*package*/ void resolvePluginDependencies() throws IOException { List<Dependency> missingDependencies = new ArrayList<>(); // make sure dependencies exist for (Dependency d : dependencies) { if (parent.getPlugin(d.shortName) == null) missingDependencies.add(d); } if (!missingDependencies.isEmpty()) throw new MissingDependencyException(this.shortName, missingDependencies); // add the optional dependencies that exists for (Dependency d : optionalDependencies) { if (parent.getPlugin(d.shortName) != null) dependencies.add(d); } }
Source:
public void makeDisabled(boolean b) throws IOException { if(disabled==b) return; // noop if (b && !supportsMakeDisabled()) return; // do nothing if the disabling is unsupported this.disabled = b; if (b) { this.disabledSince = System.currentTimeMillis(); Jenkins.getInstance().getQueue().cancel(this); } save(); ItemListener.fireOnUpdated(this); }

Target:
public void makeDisabled(boolean b) throws IOException { if(disabled==b) return; // noop if (b && !supportsMakeDisabled()) return; // do nothing if the disabling is unsupported this.disabled = b; if (b) { this.disabledSince = System.currentTimeMillis(); Jenkins.getInstance().getQueue().cancel(this); } else { this.disabledSince = null; } save(); ItemListener.fireOnUpdated(this); }
Source:
private File makeJunction(File baseDir, File pointToDir) throws Exception { File junc = new File(baseDir, "test Junction"); String cmd = "mklink /J \"" + junc.getPath() + "\" \"" + pointToDir.getPath() + "\""; ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", cmd); pb.inheritIO(); Process p = pb.start(); assertTrue("Running mklink failed (cmd=" + cmd + ")", p.waitFor() == 0); return junc; }

Target:
private File makeJunction(File baseDir, File pointToDir) throws Exception { File junc = new File(baseDir, "test Junction"); String cmd = "mklink /J \"" + junc.getPath() + "\" \"" + pointToDir.getPath() + "\""; ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", cmd); pb.inheritIO(); Process p = pb.start(); assertEquals("Running mklink failed (cmd=" + cmd + ")", 0, p.waitFor()); return junc; }
Source:
@Override public CauseOfBlockage getCauseOfBlockage() { // Block builds until they are done with post-production if (isLogUpdated() && !isConcurrentBuild()) { return new BlockedBecauseOfBuildInProgress(getLastBuild()); } if (blockBuildWhenDownstreamBuilding()) { AbstractProject<?,?> bup = getBuildingDownstream(); if (bup!=null) return new BecauseOfDownstreamBuildInProgress(bup); } if (blockBuildWhenUpstreamBuilding()) { AbstractProject<?,?> bup = getBuildingUpstream(); if (bup!=null) return new BecauseOfUpstreamBuildInProgress(bup); } return null; }

Target:
public CauseOfBlockage getCauseOfBlockage() { // Block builds until they are done with post-production if (isLogUpdated() && !isConcurrentBuild()) { return new BlockedBecauseOfBuildInProgress(getLastBuild()); } if (blockBuildWhenDownstreamBuilding()) { AbstractProject<?,?> bup = getBuildingDownstream(); if (bup!=null) return new BecauseOfDownstreamBuildInProgress(bup); } if (blockBuildWhenUpstreamBuilding()) { AbstractProject<?,?> bup = getBuildingUpstream(); if (bup!=null) return new BecauseOfUpstreamBuildInProgress(bup); } return null; }
Source:
public static boolean isDefaultName(String name) { if (name != null) { return false; } else if (name.equals(DEFAULT_NAME)) { return false; } else if (name.equals("(Default)")) { // DEFAULT_NAME took this value prior to 1.598. return false; } return true; }

Target:
public static boolean isDefaultName(String name) { if ("(Default)".equals(name)) { // DEFAULT_NAME took this value prior to 1.598. return true; } return DEFAULT_NAME.equals(name); }
Source:
private void init() { try { //optional properties if (hasPropertyAndNotNull("manual_output")) { manualOutput = Boolean.valueOf(getProperty("manual_output")); } if (hasPropertyAndNotNull("greeting")) { greeting = getProperty("greeting"); } //these two properties are essential to the workflow. If they are null or do not //exist in the INI, the workflow should exit. catPath = getProperty("cat"); echoPath = getProperty("echo"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }

Target:
private void init() { try { //optional properties if (hasPropertyAndNotNull("manual_output")) { manualOutput = Boolean.valueOf(getProperty("manual_output")); } if (hasPropertyAndNotNull("greeting")) { greeting = getProperty("greeting"); } //these two properties are essential to the workflow. If they are null or do not //exist in the INI, the workflow should exit. catPath = getProperty("cat"); echoPath = getProperty("echo"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
Source:
private Long createdAt(final Release release) { Long result = 0L; try { final Date created = this.smart(release).createdAt(); if (created != null) { result = created.getTime(); } } catch (final IOException iox) { throw new IllegalArgumentException(iox); } return result; }

Target:
private long createdAt(final Release release) { long result = 0; try { final Date created = this.smart(release).createdAt(); if (created != null) { result = created.getTime(); } } catch (final IOException iox) { throw new IllegalArgumentException(iox); } return result; }
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) { return new RtPullComment( RtPullComments.this.request, RtPullComments.this.owner, 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:
public void retrievesForks() throws Exception { final RtForks forks = new RtForks(new FakeRequest(), this.repo()); MatcherAssert.assertThat( forks.iterate("newest"), Matchers.notNullValue() ); }

Target:
public void retrievesForks() throws Exception { // To be implemented. }
Source:
public boolean starred() throws IOException { final List<String> xpath = this.storage.xml().xpath(String .format("%s/@starred", this.xpath()) ); return !xpath.isEmpty() && StringUtils.equalsIgnoreCase( MkGist.STARRED_VALUE, xpath.get(0) ); }

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 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(); }

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:
public 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; }

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 { 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]; }

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); builder.append("/v3/apps/" + appId + "/rooms"); if (roomName != null) { builder.append("/" + roomName + "/"); } builder.append(param); return builder.toString(); }

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{ if(key != null && key.trim().length() > 0){ requestEntity.addPart("key", new StringBody(key,Charset.forName("utf-8"))); } }

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) { throw new IllegalArgumentException("scope can't be null or an empty value!"); } this.scope = scope; this.expiry = System.currentTimeMillis() / 1000 + expiry; }

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) { if (scope == null || scope.trim().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; }

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:
public String makeRequest(String url) { return url + "?exif"; }

Target:
public static String makeRequest(String url) { return url + "?exif"; }
Source:
public String getImageMogrURL(String url, String params) { return url + "?imageMogr/" + params ; }

Target:
public static String getImageMogrURL(String url, String params) { return url + "?imageMogr/" + params ; }
Source:
public 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 ; }

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:
private double getSystemLoadMetric() { switch (systemLoadMetric) { case LOAD_1: return slaveUsage.getSystemLoad1Min(); case LOAD_15: return slaveUsage.getSystemLoad5Min(); case LOAD_5: default: return slaveUsage.getSystemLoad15Min(); } }

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:
private void checkOut() { LOG.trace("Checking out offer {}", offerId); Preconditions.checkState(offerState == OfferState.AVAILABLE, "Offer %s was in state %s", offerId, offerState); this.offerState = OfferState.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:
public Long getS3ChunkDownloadTimeoutMillis() { return s3ChunkDownloadTimeoutMillis; }

Target:
public int getS3ChunkDownloadTimeoutMillis() { return s3ChunkDownloadTimeoutMillis; }
Source:
public SingularityDeployProgress withCompletedStep() { return new SingularityDeployProgress(targetActiveInstances, currentActiveInstances + 1, deployInstanceCountPerStep, deployStepWaitTimeMs, true, autoAdvanceDeploySteps, failedDeployTasks, System.currentTimeMillis()); }

Target:
public SingularityDeployProgress withCompletedStep() { return new SingularityDeployProgress(targetActiveInstances, currentActiveInstances, deployInstanceCountPerStep, deployStepWaitTimeMs, true, autoAdvanceDeploySteps, failedDeployTasks, System.currentTimeMillis()); }
Source:
private static Boolean hasRole(Resource r) { return r.hasRole() && !r.getRole().equals("*"); }

Target:
private static boolean hasRole(Resource r) { return r.hasRole() && !r.getRole().equals("*"); }
Source:
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); } }

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 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 AnkiDroidApp.getInstance().setupNotificationChannels(); }

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:
public 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)); }

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:
public void setAcraConfigBuilder(CoreConfigurationBuilder acraCoreConfigBuilder) { this.acraCoreConfigBuilder = acraCoreConfigBuilder; ACRA.init(this, acraCoreConfigBuilder); }

Target:
private void setAcraConfigBuilder(CoreConfigurationBuilder acraCoreConfigBuilder) { this.acraCoreConfigBuilder = acraCoreConfigBuilder; ACRA.init(this, acraCoreConfigBuilder); }
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; } } catch (Throwable t) { //Timber.w("metaDataKeyError: " + key, t); return -2; } }

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 void subscribe(Subscriber<? super Message<?>> subscriber) { this.processor .doFinally((s) -> this.subscribedSignal.onNext(this.processor.hasDownstreams())) .subscribe(subscriber); if (this.processor.hasDownstreams()) { this.subscribedSignal.onNext(true); } }

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 String toString() { return "RSocketConnectedEvent{" + "destination='" + this.destination + '\'' + ", data length=" + this.data.asByteBuffer().array().length + ", requester=" + this.requester + '}'; }

Target:
public String toString() { return "RSocketConnectedEvent{" + "destination='" + this.destination + '\'' + ", requester=" + this.requester + '}'; }
Source:
public void destroy() { if (this.roleController != null) { this.roleController.removeLifecycle(this); } }

Target:
public void destroy() throws Exception { // NOSONAR TODO: remove throws in 5.2 if (this.roleController != null) { this.roleController.removeLifecycle(this); } }
Source:
public boolean isTransacted() { return this.transacted; }

Target:
protected boolean isTransacted() { return this.transacted; }
Source:
public Session<F> getSession() { if (this.activeTemplateCallbacks.get() > 0) { return this.contextSessions.get(); } else { return this.sessionFactory.getSession(); } }

Target:
public Session<F> getSession() { if (this.activeTemplateCallbacks.get() > 0) { Session<F> session = this.contextSessions.get(); // If no session in the ThreadLocal, no {@code invoke()} in this call stack if (session != null) { return session; } } return this.sessionFactory.getSession(); }
Source:
public ExpressionEvaluatingRouter(String expressionString) { super(new ExpressionEvaluatingMessageProcessor<Object>(EXPRESSION_PARSER.parseExpression(expressionString))); setPrimaryExpression(getExpression()); }

Target:
public ExpressionEvaluatingRouter(String expressionString) { this(EXPRESSION_PARSER.parseExpression(expressionString)); }
Source:
public void setRequestFactory(ClientHttpRequestFactory requestFactory) { if (this.isAsync()) { throw new IllegalArgumentException("ClientHttpRequestFactory cannot be set in async mode"); } this.restTemplate.setRequestFactory(requestFactory); }

Target:
public void setRequestFactory(ClientHttpRequestFactory requestFactory) { this.restTemplate.setRequestFactory(requestFactory); }
Source:
private void publishIdleEvent(long idleTime) { if (this.eventPublisher != null && getFile().exists()) { FileTailingIdleEvent event = new FileTailingIdleEvent(this, this.file, idleTime); this.eventPublisher.publishEvent(event); } else { logger.info("No publisher for idle event"); } }

Target:
private void publishIdleEvent(long idleTime) { if (this.eventPublisher != null) { if (getFile().exists()) { FileTailingIdleEvent event = new FileTailingIdleEvent(this, this.file, idleTime); this.eventPublisher.publishEvent(event); } } else { logger.info("No publisher for idle event"); } }
Source:
public Map<String, Object> getProperties() { return this.properties == null ? null : this.properties; }

Target:
public Map<String, Object> getProperties() { return this.properties.size() == 0 ? null : this.properties; }
Source:
public void handleTransportError(StompSession session, Throwable exception) { if (exception instanceof ConnectionLostException) { this.session = null; AbstractStompSessionManager.this.connected = false; scheduleReconnect(); } synchronized (this.delegates) { for (StompSessionHandler delegate : this.delegates) { delegate.handleTransportError(session, exception); } } }

Target:
public void handleTransportError(StompSession session, Throwable exception) { if (exception instanceof ConnectionLostException) { this.session = null; scheduleReconnect(exception); } synchronized (this.delegates) { for (StompSessionHandler delegate : this.delegates) { delegate.handleTransportError(session, exception); } } }
Source:
public MongoDbMetadataStore(MongoDbFactory factory, String collectionName) { Assert.notNull(factory, "'factory' must not be null."); Assert.hasText(collectionName, "'collectionName' must not be empty."); template = new MongoTemplate(factory); this.collectionName = collectionName; }

Target:
public MongoDbMetadataStore(MongoDbFactory factory, String collectionName) { this(new MongoTemplate(factory), collectionName); }
Source:
protected void onInit() { if (this.getSessionAcknowledgeMode()!= null) { Integer acknowledgeMode = JmsAdapterUtils.parseAcknowledgeMode(this.getSessionAcknowledgeMode()); if (acknowledgeMode != null) { if (JmsAdapterUtils.SESSION_TRANSACTED == acknowledgeMode) { jmsTemplate.setSessionTransacted(true); } else { jmsTemplate.setSessionAcknowledgeMode(acknowledgeMode); } } } }

Target:
protected void onInit() { if (this.getSessionAcknowledgeMode() != null) { Integer acknowledgeMode = JmsAdapterUtils.parseAcknowledgeMode(this.getSessionAcknowledgeMode()); if (acknowledgeMode != null) { if (JmsAdapterUtils.SESSION_TRANSACTED == acknowledgeMode) { this.jmsTemplate.setSessionTransacted(true); } else { this.jmsTemplate.setSessionAcknowledgeMode(acknowledgeMode); } } } }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("JpaParameter [name=").append(this.name) .append(", value=").append(this.value) .append(", expression=").append(this.expression) .append(", projectionExpression=").append(this.projectionExpression) .append("]"); return builder.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("JpaParameter [name=").append(this.name) .append(", value=").append(this.value) .append(", expression=").append(this.expression) .append("]"); return builder.toString(); }
Source:
protected boolean isPostProcessWithinAdviceIfPresent() { return this.hasAdviceChain() ? this.postProcessWithinAdvice : true; }

Target:
protected boolean isPostProcessWithinAdviceIfPresent() { return !this.hasAdviceChain() || this.postProcessWithinAdvice; }
Source:
protected Object handleRequestMessage(Message<?> requestMessage) { Object result = this.doHandleRequestMessage(requestMessage); if (this.isPostProcessWithinAdviceIfPresent()) { this.postProcess(requestMessage, result); } return result; }

Target:
protected final Object handleRequestMessage(Message<?> requestMessage) { Object result = this.doHandleRequestMessage(requestMessage); if (this.isPostProcessWithinAdviceIfPresent()) { this.postProcess(requestMessage, result); } return result; }
Source:
public HDPath extend(List<ChildNumber> path2) { List<ChildNumber> mutable = new ArrayList<>(this.unmodifiableList); // Mutable copy mutable.addAll(path2); return new HDPath(mutable); }

Target:
public HDPath extend(List<ChildNumber> path2) { return this.extend(HDPath.of(path2)); }
Source:
public byte[] getProgram() { try { // Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch. if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { bos.write(chunk.toByteArray()); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } }

Target:
public byte[] getProgram() { try { // Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch. if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } }
Source:
public final MessageSerializer getDefaultSerializer() { // Construct a default serializer if we don't have one if (null == this.defaultSerializer) { this.defaultSerializer = getSerializer(false, false); } return defaultSerializer; }

Target:
public final MessageSerializer getDefaultSerializer() { // Construct a default serializer if we don't have one if (null == this.defaultSerializer) { // Don't grab a lock unless we absolutely need it synchronized(this) { // Now we have a lock, double check there's still no serializer // and create one if so. if (null == this.defaultSerializer) { // As the serializers are intended to be immutable, creating // two due to a race condition should not be a problem, however // to be safe we ensure only one exists for each network. this.defaultSerializer = getSerializer(false, false); } } } return defaultSerializer; }
Source:
public long calculateAverageDynamicConfigRefreshInterval() { long total = 0; for (GerritServer server : PluginImpl.getServers_()) { total += server.getConfig().getDynamicConfigRefreshInterval(); } long average = total / Math.max(1, PluginImpl.getServers_().size()); //Avoid division by 0 return Math.max(GerritDefaultValues.MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL, average); }

Target:
long calculateAverageDynamicConfigRefreshInterval() { long total = 0; for (GerritServer server : PluginImpl.getServers_()) { total += server.getConfig().getDynamicConfigRefreshInterval(); } long average = total / Math.max(1, PluginImpl.getServers_().size()); //Avoid division by 0 return Math.max(GerritDefaultValues.MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL, average); }
Source:
public void setTriggerConfigURL(String triggerConfigURL) { // If the trigger URL has changed from the previous value, then we can't use // the project list that we might already have loaded from the last time this trigger // was started. Just make a note of that here; we'll deal with it in "start()". if (triggerConfigURL == null) { if (this.triggerConfigURL != null) { // We need to start fresh when the URL has changed. this.dynamicConfigurationChangedFromLastStart = true; } } else { if (!triggerConfigURL.equals(this.triggerConfigURL)) { // We need to start fresh when the URL has changed. this.dynamicConfigurationChangedFromLastStart = true; } else { // We had this same configuration before. this.dynamicConfigurationChangedFromLastStart = false; } } this.triggerConfigURL = triggerConfigURL; }

Target:
public void setTriggerConfigURL(String triggerConfigURL) { this.triggerConfigURL = triggerConfigURL; }
Source:
/*package*/ RunningJobs getRunningJobs() { if (runningJobs == null) { runningJobs = new RunningJobs(); } return runningJobs; }

Target:
/*package*/ synchronized RunningJobs getRunningJobs() { if (runningJobs == null) { runningJobs = new RunningJobs(); } return runningJobs; }
Source:
public List<PreparedRemark> prepareRemarkList(List<Remark> list) { if (list.isEmpty()) { return ImmutableList.of(); } List<PreparedRemark> remarksPrepared = new ArrayList<PreparedRemark>(list.size()); for (Remark remark : list) { try{ User refUser = userDao.getUserCached(remark.getRefUserId()); remarksPrepared.add(new PreparedRemark(remark,refUser)); }catch(UserNotFoundException e){ } } return remarksPrepared; }

Target:
public List<PreparedRemark> prepareRemarkList(List<Remark> list) throws Exception { if (list.isEmpty()) { return ImmutableList.of(); } List<PreparedRemark> remarksPrepared = new ArrayList<PreparedRemark>(list.size()); for (Remark remark : list) { User refUser = userDao.getUserCached(remark.getRefUserId()); remarksPrepared.add(new PreparedRemark(remark,refUser)); } return remarksPrepared; }
Source:
public void deleteTagFromTopic(int msgId, int tagId) { jdbcTemplate.update( "DELETE FROM tags WHERE msgid=? and tagid=?", new Object[]{new Integer(msgId), new Integer(tagId)} ); }

Target:
public void deleteTagFromTopic(int msgId, int tagId) { jdbcTemplate.update( "DELETE FROM tags WHERE msgid=? and tagid=?", new Object[]{ msgId, tagId } ); }
Source:
public void setMaxInactiveInterval(int seconds) { _dftMaxIdleSecs = seconds; System.err.println("SETMAXINACTIVE = " + seconds); if (LOG.isDebugEnabled()) { if (_dftMaxIdleSecs <= 0) LOG.debug("Sessions created by this manager are immortal (default maxInactiveInterval={})", _dftMaxIdleSecs); else LOG.debug("SessionManager default maxInactiveInterval={}", _dftMaxIdleSecs); } }

Target:
public void setMaxInactiveInterval(int seconds) { _dftMaxIdleSecs = seconds; if (LOG.isDebugEnabled()) { if (_dftMaxIdleSecs <= 0) LOG.debug("Sessions created by this manager are immortal (default maxInactiveInterval={})", _dftMaxIdleSecs); else LOG.debug("SessionManager default maxInactiveInterval={}", _dftMaxIdleSecs); } }
Source:
protected JSONObject getApiPropertiesTrackingOptions() { JSONObject apiPropertiesTrackingOptions = new JSONObject(); if (disabledFields.size() == 0) { return apiPropertiesTrackingOptions; } for (String key : SERVER_SIDE_PROPERTIES) { if (disabledFields.contains(key)) { try { apiPropertiesTrackingOptions.put(key, false); } catch (JSONException e) { AmplitudeLog.getLogger().e(TAG, e.toString()); } } } return apiPropertiesTrackingOptions; }

Target:
protected JSONObject getApiPropertiesTrackingOptions() { JSONObject apiPropertiesTrackingOptions = new JSONObject(); if (disabledFields.isEmpty()) { return apiPropertiesTrackingOptions; } for (String key : SERVER_SIDE_PROPERTIES) { if (disabledFields.contains(key)) { try { apiPropertiesTrackingOptions.put(key, false); } catch (JSONException e) { AmplitudeLog.getLogger().e(TAG, e.toString()); } } } return apiPropertiesTrackingOptions; }
Source:
private String getCountryFromNetwork() { TelephonyManager manager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); try { if (manager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { String country = manager.getNetworkCountryIso(); if (country != null) { return country.toUpperCase(Locale.US); } } } catch (NullPointerException e) { // Failed to get phone type } catch (Resources.NotFoundException e) { // Failed to get phone type } return null; }

Target:
private String getCountryFromNetwork() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); if (manager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { String country = manager.getNetworkCountryIso(); if (country != null) { return country.toUpperCase(Locale.US); } } } catch (Exception e) { // Failed to get country from network } return null; }
Source:
public void start() { // Checks if logged in if (!ctx.game.loggedIn()){ ctx.controller.stop(); return; } System.out.println("Script Started!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); }

Target:
public void start() { System.out.println("Script Started!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); }
Source:
private void recycle() { if(!options.isKeepAliveTTLEnabled()) expirationTimestamp = keepAliveTimeout == 0 ? 0L : System.currentTimeMillis() + keepAliveTimeout * 1000; else { long now = System.currentTimeMillis(); long keepAliveTTL = options.getKeepAliveTTL() * 1000 - (now - initialTimestamp); expirationTimestamp = keepAliveTimeout == 0 || (keepAliveTTL <= 0) ? 0L : Math.min(now + keepAliveTimeout * 1000, now + keepAliveTTL); } listener.onRecycle(); }

Target:
private void recycle() { expirationTimestamp = keepAliveTimeout == 0 ? 0L : System.currentTimeMillis() + keepAliveTimeout * 1000; listener.onRecycle(); }
Source:
public void testListenInvalidPort() { final int port = 9090; final HttpServer httpServer = vertx.createHttpServer() .requestHandler(ignore -> {}) .listen(port, onSuccess(s -> vertx.createNetServer() .connectHandler(ignore -> {}) .listen(port, onFailure(error -> { assertNotNull(error); testComplete(); })))); await(); httpServer.close(); }

Target:
public void testListenInvalidPort() { final int port = 9090; final HttpServer httpServer = vertx.createHttpServer(); try { httpServer.requestHandler(ignore -> {}) .listen(port, onSuccess(s -> vertx.createNetServer() .connectHandler(ignore -> {}) .listen(port, onFailure(error -> { assertNotNull(error); testComplete(); })))); await(); } finally { httpServer.close(); } }
Source:
public <T> T convert(Class<T> type) { try { if (type == JsonObject.class || type == JsonArray.class) { return (T) Json.decodeValue(buffer.toString()); } else { return Json.decodeValue(buffer.toString(), type); } } catch (Exception e) { e.printStackTrace(); throw new DecodeException(e.getMessage()); } }

Target:
public <T> T convert(Class<T> type) { try { if (type == JsonObject.class || type == JsonArray.class) { return (T) Json.decodeValue(buffer.toString()); } else { return Json.decodeValue(buffer.toString(), type); } } catch (Exception e) { throw new DecodeException(e.getMessage()); } }
Source:
public void example1Pointers() { // Build a pointer from a string JsonPointer pointer1 = JsonPointer.from("/hello/world"); // Build a pointer from an URI JsonPointer pointer2 = JsonPointer.fromURI(URI.create("#/hello/world")); // Build a pointer manually JsonPointer pointer3 = JsonPointer.create() .append("hello") .append("world"); }

Target:
public void example1Pointers() { // Build a pointer from a string JsonPointer pointer1 = JsonPointer.from("/hello/world"); // Build a pointer manually JsonPointer pointer2 = JsonPointer.create() .append("hello") .append("world"); }
Source:
void add(Closeable hook) { if (closeHooks == null) { // Has to be concurrent as can be removed from non context thread closeHooks = new ConcurrentHashSet<>(); } closeHooks.add(hook); }

Target:
synchronized void add(Closeable hook) { if (closeHooks == null) { // Has to be concurrent as can be removed from non context thread closeHooks = new HashSet<>(); } closeHooks.add(hook); }
Source:
private List<String> getArguments() { List<String> args = executionContext.commandLine().allArguments(); // Add system properties passed as parameter if (systemProperties != null) { args.addAll( systemProperties.stream().map( entry -> "-D" + entry) .collect(Collectors.toList())); } // Add id - it's important as it's the application mark. args.add("-Dvertx.id=" + getId()); return args; }

Target:
private List<String> getArguments() { List<String> args = executionContext.commandLine().allArguments(); // Add system properties passed as parameter if (systemProperties != null) { systemProperties.stream().map(entry -> "-D" + entry).forEach(args::add); } // Add id - it's important as it's the application mark. args.add("-Dvertx.id=" + getId()); return args; }
Source:
public List<String> processArgs() { // As we are maintaining the launcher and starter class, choose the right one. final List<String> processArgument = VertxCommandLauncher.getProcessArguments(); return processArgument != null ? processArgument : Starter.PROCESS_ARGS; }

Target:
public List<String> processArgs() { // As we are maintaining the launcher and starter class, choose the right one. List<String> processArgument = VertxCommandLauncher.getProcessArguments(); return processArgument != null ? processArgument : Starter.PROCESS_ARGS; }
Source:
public void testVersion() throws Exception { String[] args = new String[]{"-version"}; MyStarter starter = new MyStarter(); starter.run(args); // TODO some way of getting this from the version in pom.xml assertEquals(System.getProperty("vertxVersion"), starter.getVersion()); }

Target:
public void testVersion() throws Exception { String[] args = {"-version"}; MyStarter starter = new MyStarter(); starter.run(args); // TODO some way of getting this from the version in pom.xml assertEquals(System.getProperty("vertxVersion"), starter.getVersion()); }