auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public E next() { I id = index.next(); final Optional<E> loaded = repository.load(id); if (!loaded.isPresent()) { final String idStr = idToString(id); final String errMsg = format("Unable to load entity with ID: %s", idStr); throw new IllegalStateException(errMsg); } final E entity = loaded.get(); return entity; }

Target:
public E next() { final I id = index.next(); final Optional<E> loaded = repository.load(id); if (!loaded.isPresent()) { final String idStr = idToString(id); final String errMsg = format("Unable to load entity with ID: %s", idStr); throw new IllegalStateException(errMsg); } final E entity = loaded.get(); return entity; }
Source:
private int findWordStartingWithAny(String[] words, String ... wordStart) { for (int i=0; i<words.length; ++i) { for (int j=0; j<wordStart.length; ++j) { if (words[i].startsWith(wordStart[j])) { return i; } } } return -1; }

Target:
private int findWordStartingWithAny(String[] words, String ... wordStart) { for (int i=0; i<words.length; ++i) { if (StringUtils.startsWithAny(words[i], wordStart)) { return i; } } return -1; }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String queryString = request.getQueryString(); if (StringUtils.isNotEmpty(queryString)) { if (url.indexOf("?") == -1) { url += "?"; } else { url += "&"; } url += queryString; } response.sendRedirect(response.encodeRedirectURL(url)); }

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String queryString = request.getQueryString(); if (StringUtils.isNotEmpty(queryString)) { if (url.indexOf("?") == -1) { url += "?"; } else { url += "&"; } url += queryString; } response.sendRedirect(url); }
Source:
private boolean isRepresentationDeletion(Notification notification) { boolean representationDeleted = false; if (notification.getFeature() == ViewpointPackage.Literals.DVIEW__OWNED_REPRESENTATIONS) { int eventType = notification.getEventType(); if (eventType == Notification.REMOVE || eventType == Notification.UNSET || eventType == Notification.REMOVE_MANY) { representationDeleted = isInOldValue(notification, dRepresentation) && !(dRepresentation.eContainer().eContainer() instanceof DView); } } else if (notification.getFeature() == ViewpointPackage.Literals.DANALYSIS__OWNED_VIEWS) { int eventType = notification.getEventType(); if (eventType == Notification.REMOVE || eventType == Notification.UNSET || eventType == Notification.REMOVE_MANY) { representationDeleted = isInOldValue(notification, dRepresentation.eContainer()) && !(dRepresentation.eContainer() != null && dRepresentation.eContainer().eContainer() instanceof DView); } } return representationDeleted; }

Target:
private boolean isRepresentationDeletion(Notification notification) { boolean representationDeleted = false; if (notification.getFeature() == ViewpointPackage.Literals.DVIEW__OWNED_REPRESENTATIONS && isCurrentDRepresentationRemove(notification, dRepresentation)) { representationDeleted = !(dRepresentation.eContainer() instanceof DView); } else if (notification.getFeature() == ViewpointPackage.Literals.DANALYSIS__OWNED_VIEWS && isCurrentDRepresentationRemove(notification, dRepresentation.eContainer())) { representationDeleted = dRepresentation.eContainer() == null || !(dRepresentation.eContainer() != null && dRepresentation.eContainer().eContainer() instanceof DView); } return representationDeleted; }
Source:
public List<Object> configurations() { return Collections.singletonList(new TooManyLinesInFunctionCheck.Config(max)); }

Target:
public List<Object> configurations() { return Collections.singletonList(new Config(max)); }
Source:
public static String typeStringFromParseSpec(ParseSpec parseSpec) { StringBuilder builder = new StringBuilder("struct<"); builder.append(parseSpec.getTimestampSpec()).append(":string"); if (parseSpec.getDimensionsSpec().getDimensionNames().size() > 0) { builder.append(","); builder.append(StringUtils.join(parseSpec.getDimensionsSpec().getDimensionNames(), ":string,")).append(":string"); } builder.append(">"); return builder.toString(); }

Target:
public static String typeStringFromParseSpec(ParseSpec parseSpec) { StringBuilder builder = new StringBuilder("struct<"); builder.append(parseSpec.getTimestampSpec().getTimestampColumn()).append(":string"); if (parseSpec.getDimensionsSpec().getDimensionNames().size() > 0) { builder.append(","); builder.append(StringUtils.join(parseSpec.getDimensionsSpec().getDimensionNames(), ":string,")).append(":string"); } builder.append(">"); return builder.toString(); }
Source:
public void testClassCastException() { Thread thread = new Thread(() -> { editor = (SWTBotSiriusDiagramEditor) openRepresentation(localSession.getOpenedSession(), DESC_NAME, REPRESENTATION_NAME, DDiagram.class); }); thread.start(); bot.waitUntil(Conditions.shellIsActive("Refresh the diagram")); bot.activeShell().bot().button("OK").click(); bot.waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return editor != null && editor.isDirty() && editor.getTitle().equals(REPRESENTATION_NAME); } @Override public String getFailureMessage() { return "The editor should be opened and dirty."; } }); }

Target:
public void testClassCastException() { changeSiriusUIPreference(SiriusUIPreferencesKeys.PREF_REFRESH_ON_REPRESENTATION_OPENING.name(), false); Thread thread = new Thread(() -> { editor = (SWTBotSiriusDiagramEditor) openRepresentation(localSession.getOpenedSession(), DESC_NAME, REPRESENTATION_NAME, DDiagram.class); }); thread.start(); bot.waitUntil(Conditions.shellIsActive("Refresh the diagram")); bot.activeShell().bot().button("OK").click(); bot.waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return editor != null && editor.isDirty() && editor.getTitle().equals(REPRESENTATION_NAME); } @Override public String getFailureMessage() { return "The editor should be opened and dirty."; } }); }
Source:
public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("project".equals(qName)) { projects.add(new Project(attributes.getValue("name"), attributes.getValue("path"))); } else if ("remote".equals(qName)) { remotes.put(attributes.getValue("name"), attributes.getValue("fetch")); } else if ("default".equals(qName)) { defaultRemote = attributes.getValue("remote"); } else if ("copyfile".equals(qName)) { } }

Target:
public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("project".equals(qName)) projects.add(new Project(attributes.getValue("name"), attributes.getValue("path"))); else if ("remote".equals(qName)) remotes.put(attributes.getValue("name"), attributes.getValue("fetch")); else if ("default".equals(qName)) defaultRemote = attributes.getValue("remote"); else if ("copyfile".equals(qName)) { } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUploadButton = findViewById(R.id.upload_key_action_upload); mKeyServerSpinner = (Spinner) findViewById(R.id.upload_key_keyserver); mMultiUserIdsFragment = (MultiUserIdsFragment) getSupportFragmentManager().findFragmentById(R.id.multi_user_ids_fragment); mMultiUserIdsFragment.setCheckboxVisibility(false); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Preferences.getPreferences(this) .getKeyServers() ); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mKeyServerSpinner.setAdapter(adapter); if (adapter.getCount() > 0) { mKeyServerSpinner.setSelection(0); } else { mUploadButton.setEnabled(false); } mUploadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { uploadKey(); } }); mDataUri = getIntent().getData(); if (mDataUri == null) { Log.e(Constants.TAG, "Intent data missing. Should be Uri of key!"); finish(); return; } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUploadButton = findViewById(R.id.upload_key_action_upload); mKeyServerSpinner = (Spinner) findViewById(R.id.upload_key_keyserver); MultiUserIdsFragment mMultiUserIdsFragment = (MultiUserIdsFragment) getSupportFragmentManager().findFragmentById(R.id.multi_user_ids_fragment); mMultiUserIdsFragment.setCheckboxVisibility(false); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Preferences.getPreferences(this) .getKeyServers() ); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mKeyServerSpinner.setAdapter(adapter); if (adapter.getCount() > 0) { mKeyServerSpinner.setSelection(0); } else { mUploadButton.setEnabled(false); } mUploadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { uploadKey(); } }); mDataUri = getIntent().getData(); if (mDataUri == null) { Log.e(Constants.TAG, "Intent data missing. Should be Uri of key!"); finish(); return; } }
Source:
public void patchNotOwnMetadataByNonAdminUser() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withPassword(password) .build(); EPerson ePerson2 = EPersonBuilder.createEPerson(context) .withNameInMetadata("Jane", "Smith") .withEmail("Janesmith@fake-email.com") .withPassword(password) .build(); String newName = "JohnReplace"; context.restoreAuthSystemState(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/metadata/eperson.firstname", newName); ops.add(replaceOperation); String patchBody = getPatchContent(ops); String token = getAuthToken(ePerson2.getEmail(), password); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isForbidden()); }

Target:
public void patchNotOwnMetadataByNonAdminUser() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@example.com") .withPassword(password) .build(); EPerson ePerson2 = EPersonBuilder.createEPerson(context) .withNameInMetadata("Jane", "Smith") .withEmail("Janesmith@example.com") .withPassword(password) .build(); String newName = "JohnReplace"; context.restoreAuthSystemState(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/metadata/eperson.firstname", newName); ops.add(replaceOperation); String patchBody = getPatchContent(ops); String token2 = getAuthToken(ePerson2.getEmail(), password); String token = getAuthToken(ePerson.getEmail(), password); getClient(token2).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isForbidden()); getClient(token).perform(get("/api/eperson/epersons/" + ePerson.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasJsonPath("$.metadata", allOf( matchMetadata("eperson.firstname", "John"))))); }
Source:
private static void deleteDirectory(File file) { if (file.isDirectory()) for (File subFile : file.listFiles()) { deleteDirectory(subFile); } file.delete(); }

Target:
private static void deleteDirectory(File file) { if (file.isDirectory()) for (File subFile : file.listFiles()) { deleteDirectory(subFile); } if (!file.delete()) { Log.e(TAG, "Failed to delete file: " + file.getPath()); } }
Source:
private static Properties loadProperties() { Path path = Paths.get(System.getProperty("user.home"), "cosmos-v4.properties"); Properties properties = new Properties(System.getProperties()); if (Files.exists(path)) { try (InputStream in = Files.newInputStream(path)) { properties.load(in); } catch (Exception e) { logger.error("loading properties failed", path, e); } } return properties; }

Target:
private static Properties loadProperties() { Path root = FileSystems.getDefault().getPath("").toAbsolutePath(); Path propertiesInProject = Paths.get(root.toString(),"../cosmos-v4.properties"); Properties props = loadFromPathIfExists(propertiesInProject); if (props != null) { return props; } Path propertiesInUserHome = Paths.get(System.getProperty("user.home"), "cosmos-v4.properties"); props = loadFromPathIfExists(propertiesInUserHome); if (props != null) { return props; } return System.getProperties(); }
Source:
public Registration next() { try (Jedis j = pool.getResource()) { if (!hasNext()) { throw new NoSuchElementException(); } return scanResult.remove(0); } }

Target:
public Registration next() { if (!hasNext()) { throw new NoSuchElementException(); } return scanResult.remove(0); }
Source:
protected int findDefaultTrafficStatsTag(String url) { if (url != null && !TextUtils.isEmpty(url)) { Uri uri = Uri.parse(url); if (uri != null) { String host = uri.getHost(); if (host != null) { return host.hashCode(); } } } return 0; }

Target:
private static int findDefaultTrafficStatsTag(String url) { if (!TextUtils.isEmpty(url)) { Uri uri = Uri.parse(url); if (uri != null) { String host = uri.getHost(); if (host != null) { return host.hashCode(); } } } return 0; }
Source:
public static String ConvertToStandardDuration(Long timeInMilliseconds){ return timeInMilliseconds !=null? String.format("%dm:%ds:%dms", timeInMilliseconds / 60000, timeInMilliseconds / 1000, timeInMilliseconds % 1000) : ""; }

Target:
public static String ConvertToStandardDuration(Long timeInMilliseconds){ return timeInMilliseconds !=null? String.format("%d:%d:%d", timeInMilliseconds / 60000, timeInMilliseconds / 1000, timeInMilliseconds % 1000) : ""; }
Source:
public boolean isLoaded() { return gpxFile.modifiedTime != 0; }

Target:
public boolean isLoaded() { return gpxFile.modifiedTime != -1; }
Source:
protected MutableBoundedValue<Integer> constructValue(Integer defaultValue) { return SpongeValueBuilder.boundedBuilder(Keys.PASSED_BURN_TIME) .minimum(0) .maximum(1000) .defaultValue(defaultValue) .build(); }

Target:
protected MutableBoundedValue<Integer> constructValue(Integer defaultValue) { return SpongeValueBuilder.boundedBuilder(Keys.PASSED_BURN_TIME) .minimum(0) .maximum(1600) .defaultValue(defaultValue) .build(); }
Source:
public static List<GerritProject> fetch(String gerritTriggerConfigUrl, String serverName) throws IOException, ParseException { URL url = new URL(gerritTriggerConfigUrl); URLConnection connection = url.openConnection(); connection.setReadTimeout(SOCKET_READ_TIMEOUT); connection.setDoInput(true); InputStream instream = null; BufferedReader reader = null; try { instream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8"))); return readAndParseTriggerConfig(reader, serverName); } finally { if (reader != null) { reader.close(); } else if (instream != null) { instream.close(); } } }

Target:
public static List<GerritProject> fetch(String gerritTriggerConfigUrl, String serverName) throws IOException, ParseException { if (gerritTriggerConfigUrl == null) { throw new MalformedURLException("The gerritTriggerConfigUrl is null"); } if (gerritTriggerConfigUrl.isEmpty()) { throw new MalformedURLException("The gerritTriggerConfigUrl is empty"); } URL url = new URL(gerritTriggerConfigUrl); URLConnection connection = url.openConnection(); connection.setReadTimeout(SOCKET_READ_TIMEOUT); connection.setDoInput(true); InputStream instream = null; BufferedReader reader = null; try { instream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8"))); return readAndParseTriggerConfig(reader, serverName); } finally { if (reader != null) { reader.close(); } else if (instream != null) { instream.close(); } } }
Source:
private Connection<CL> getConnection(BaseOperation<CL, ?> op, Long token, int duration, TimeUnit unit) throws NoAvailableHostsException, PoolExhaustedException { HostConnectionPool<CL> hostPool = null; DynoConnectException lastEx = null; boolean useFallback = false; try { hostPool = (op != null) ? localSelector.getPoolForOperation(op) : localSelector.getPoolForToken(token); useFallback = !isConnectionPoolActive(hostPool); } catch (NoAvailableHostsException e) { lastEx = e; useFallback = true; } if (!useFallback) { try { return hostPool.borrowConnection(duration, unit); } catch (DynoConnectException e) { if (e instanceof PoolExhaustedException && replicationFactor.get() == 3) { throw e; } lastEx = e; cpMonitor.incOperationFailure(null, e); useFallback = true; } } if (useFallback && cpConfig.getMaxFailoverCount() > 0) { cpMonitor.incFailover(null, null); int numRemotes = remoteDCNames.getEntireList().size(); if (numRemotes == 0) { if (lastEx != null) { cpMonitor.incOperationFailure(null,lastEx); throw lastEx; } else { PoolOfflineException poe = new PoolOfflineException(hostPool.getHost(), "host pool is offline and no Racks available for fallback"); cpMonitor.incOperationFailure(null, poe); throw poe; } } else { hostPool = getFallbackHostPool(op, token); } } else if (useFallback && cpConfig.getMaxFailoverCount() == 0) { cpMonitor.incOperationFailure(null, lastEx); } if (hostPool == null) { throw new NoAvailableHostsException("Found no hosts when using fallback Rack"); } return hostPool.borrowConnection(duration, unit); }

Target:
private Connection<CL> getConnection(BaseOperation<CL, ?> op, Long token, int duration, TimeUnit unit) throws NoAvailableHostsException, PoolExhaustedException { HostConnectionPool<CL> hostPool = null; DynoConnectException lastEx = null; boolean useFallback = false; try { hostPool = (op != null) ? localSelector.getPoolForOperation(op) : localSelector.getPoolForToken(token); useFallback = !isConnectionPoolActive(hostPool); } catch (NoAvailableHostsException e) { lastEx = e; useFallback = true; } if (!useFallback) { try { return hostPool.borrowConnection(duration, unit); } catch (DynoConnectException e) { if (e instanceof PoolExhaustedException) { throw e; } lastEx = e; cpMonitor.incOperationFailure(null, e); useFallback = true; } } if (useFallback && cpConfig.getMaxFailoverCount() > 0) { cpMonitor.incFailover(null, null); int numRemotes = remoteDCNames.getEntireList().size(); if (numRemotes == 0) { if (lastEx != null) { cpMonitor.incOperationFailure(null,lastEx); throw lastEx; } else { PoolOfflineException poe = new PoolOfflineException(hostPool.getHost(), "host pool is offline and no Racks available for fallback"); cpMonitor.incOperationFailure(null, poe); throw poe; } } else { hostPool = getFallbackHostPool(op, token); } } else if (useFallback && cpConfig.getMaxFailoverCount() == 0) { cpMonitor.incOperationFailure(null, lastEx); } if (hostPool == null) { throw new NoAvailableHostsException("Found no hosts when using fallback Rack"); } return hostPool.borrowConnection(duration, unit); }
Source:
public void explains_when_constructor_cannot_be_found() { try { new ConstructorInstantiator(null).newInstance(SomeClass2.class); fail(); } catch (InstantiationException e) { assertThat(e).hasMessageContaining("Unable to create instance of 'SomeClass2'.\n" + "Please ensure that it has a constructor that matches these arguments: []"); } }

Target:
public void explains_when_constructor_cannot_be_found() { try { new ConstructorInstantiator(false, new Object[0]).newInstance(SomeClass2.class); fail(); } catch (InstantiationException e) { assertThat(e).hasMessageContaining("Unable to create instance of 'SomeClass2'.\n" + "Please ensure that the target class has a 0-arg constructor."); } }
Source:
public void provision( WorkspaceConfigImpl workspaceConfig, String environmentType, List<HasMetadata> toolObjects, Map<String, MachineConfigImpl> machines) throws DevfileException, DevfileRecipeFormatException { String defaultEnv = workspaceConfig.getDefaultEnv(); EnvironmentImpl environment = workspaceConfig.getEnvironments().get(defaultEnv); if (environment == null) { checkItemsHasUniqueKindToName(toolObjects); RecipeImpl recipe = new RecipeImpl(environmentType, YAML_CONTENT_TYPE, asYaml(toolObjects), null); String envName = "default"; EnvironmentImpl env = new EnvironmentImpl(recipe, emptyMap()); env.getMachines().putAll(machines); workspaceConfig.getEnvironments().put(envName, env); workspaceConfig.setDefaultEnv(envName); } else { RecipeImpl envRecipe = environment.getRecipe(); environment.getMachines().putAll(machines); if (OPENSHIFT_TOOL_TYPE.equals(environmentType) && KubernetesEnvironment.TYPE.equals(envRecipe.getType())) { envRecipe.setType(OpenShiftEnvironment.TYPE); } List<HasMetadata> envObjects = unmarshalDefaultEnvObjects(workspaceConfig); envObjects.addAll(toolObjects); envRecipe.setContent(asYaml(envObjects)); } }

Target:
public void provision( WorkspaceConfigImpl workspaceConfig, String environmentType, List<HasMetadata> toolObjects, Map<String, MachineConfigImpl> machines) throws DevfileException, DevfileRecipeFormatException { String defaultEnv = workspaceConfig.getDefaultEnv(); EnvironmentImpl environment = workspaceConfig.getEnvironments().get(defaultEnv); if (environment == null) { checkItemsHasUniqueKindToName(toolObjects); RecipeImpl recipe = new RecipeImpl(environmentType, YAML_CONTENT_TYPE, asYaml(toolObjects), null); String envName = "default"; EnvironmentImpl env = new EnvironmentImpl(recipe, emptyMap()); env.getMachines().putAll(machines); workspaceConfig.getEnvironments().put(envName, env); workspaceConfig.setDefaultEnv(envName); } else { RecipeImpl envRecipe = environment.getRecipe(); for (Entry<String, MachineConfigImpl> machineEntry : machines.entrySet()) { if (environment.getMachines().put(machineEntry.getKey(), machineEntry.getValue()) != null) { throw new DevfileException( format("Environment already contains machine '%s'", machineEntry.getKey())); } } environment.getMachines().putAll(machines); if (OPENSHIFT_TOOL_TYPE.equals(environmentType) && KubernetesEnvironment.TYPE.equals(envRecipe.getType())) { envRecipe.setType(OpenShiftEnvironment.TYPE); } List<HasMetadata> envObjects = unmarshalObjects(envRecipe); envObjects.addAll(toolObjects); envRecipe.setContent(asYaml(envObjects)); } }
Source:
public void onPageLoadComplete() { editHandler.setPage(model.getPage()); refreshView.setEnabled(true); refreshView.setRefreshing(false); requireActivity().invalidateOptionsMenu(); initPageScrollFunnel(); if (model.getReadingListPage() != null) { final ReadingListPage page = model.getReadingListPage(); final PageTitle title = model.getTitle(); disposables.add(Completable.fromAction(() -> { if (!TextUtils.equals(page.thumbUrl(), title.getThumbUrl()) || !TextUtils.equals(page.description(), title.getDescription())) { page.thumbUrl(title.getThumbUrl()); page.description(title.getDescription()); ReadingListDbHelper.instance().updatePage(page); } }).subscribeOn(Schedulers.io()).subscribe()); } if (!errorState) { setupToC(model, pageFragmentLoadState.isFirstPage()); editHandler.setPage(model.getPage()); webView.setVisibility(View.VISIBLE); } checkAndShowBookmarkOnboarding(); maybeShowAnnouncement(); }

Target:
public void onPageLoadComplete() { editHandler.setPage(model.getPage()); refreshView.setEnabled(true); refreshView.setRefreshing(false); requireActivity().invalidateOptionsMenu(); initPageScrollFunnel(); if (model.getReadingListPage() != null) { final ReadingListPage page = model.getReadingListPage(); final PageTitle title = model.getTitle(); disposables.add(Completable.fromAction(() -> { if (!TextUtils.equals(page.thumbUrl(), title.getThumbUrl()) || !TextUtils.equals(page.description(), title.getDescription())) { page.thumbUrl(title.getThumbUrl()); page.description(title.getDescription()); ReadingListDbHelper.instance().updatePage(page); } }).subscribeOn(Schedulers.io()).subscribe()); } if (!errorState) { setupToC(model, pageFragmentLoadState.isFirstPage()); editHandler.setPage(model.getPage()); webView.setVisibility(View.VISIBLE); } bridge.evaluate(JavaScriptActionHandler.getRevision(), revision -> this.revision = Long.parseLong(revision.replace("\"", ""))); checkAndShowBookmarkOnboarding(); maybeShowAnnouncement(); }
Source:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View layout = inflater.inflate(R.layout.feeditem_pager_fragment, container, false); Toolbar toolbar = layout.findViewById(R.id.toolbar); toolbar.setTitle(""); ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar); feedItems = getArguments().getLongArray(ARG_FEEDITEMS); int feedItemPos = getArguments().getInt(ARG_FEEDITEM_POS); ViewPager2 pager = layout.findViewById(R.id.pager); int newId = ViewCompat.generateViewId(); pager.setId(newId); pager.setAdapter(new ItemPagerAdapter(this)); pager.setCurrentItem(feedItemPos); loadItem(feedItems[feedItemPos]); pager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override public void onPageSelected(int position) { loadItem(feedItems[position]); } }); EventBus.getDefault().register(this); return layout; }

Target:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View layout = inflater.inflate(R.layout.feeditem_pager_fragment, container, false); Toolbar toolbar = layout.findViewById(R.id.toolbar); toolbar.setTitle(""); ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar); feedItems = getArguments().getLongArray(ARG_FEEDITEMS); int feedItemPos = getArguments().getInt(ARG_FEEDITEM_POS); ViewPager2 pager = layout.findViewById(R.id.pager); int newId = ViewCompat.generateViewId(); pager.setId(newId); pager.setAdapter(new ItemPagerAdapter(this)); pager.setCurrentItem(feedItemPos, false); loadItem(feedItems[feedItemPos]); pager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override public void onPageSelected(int position) { loadItem(feedItems[position]); } }); EventBus.getDefault().register(this); return layout; }
Source:
protected int compare(Number number) { if ( number instanceof Double ) { return NumberComparatorHelper.compare( (Double) number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); } if ( number instanceof Float ) { return NumberComparatorHelper.compare( (Float) number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); } return NumberComparatorHelper.compare( number, maxValue ); }

Target:
protected int compare(Number number) { return NumberComparatorHelper.compare( number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); }
Source:
public static void main(String[] args) throws Exception { Crypto crypto = Crypto.initJava(); NetworkAccess network = NetworkAccess.buildJava(new URL("<LINK_0>")).get(); String username = args[0]; String fromPath = args[1]; String toPath = args[2]; Console console = System.console(); String password = new String(console.readPassword("Enter password for " + username + ":")); UserContext context = UserContext.signIn(username, password, network, crypto).get(); ForkJoinPool pool = new ForkJoinPool(50); long t1 = System.currentTimeMillis(); downloadTo(context, fromPath, Paths.get(toPath), props -> true, pool); long t2 = System.currentTimeMillis(); LOG.info("Download took " + (t2-t1) + " mS"); }

Target:
public static void main(String[] args) throws Exception { Crypto crypto = Crypto.initJava(); NetworkAccess network = NetworkAccess.buildJava(new URL("<LINK_0>")).get(); String username = args[0]; String fromPath = args[1]; String toPath = args[2]; Console console = System.console(); String password = new String(console.readPassword("Enter password for " + username + ":")); UserContext context = UserContext.signIn(username, password, network, crypto).get(); ForkJoinPool pool = new ForkJoinPool(50); long t1 = System.currentTimeMillis(); downloadTo(context, fromPath, Paths.get(toPath), props -> true, pool); long t2 = System.currentTimeMillis(); System.out.println("Download took " + (t2-t1) + " mS"); }
Source:
public CharSequence getHost() { return host; }

Target:
public CharSequence getHost() { return uri.getHost(); }
Source:
void valid() { try { int aaa = this.field; final int twelveletter = ++aaa; final int id = -1; } catch (final IllegalStateException ise) { throw ise; } catch (final IllegalArgumentException ex) { throw ex; } }

Target:
void valid() { try { int aaa = this.field; int id = ++aaa; final int ise = 0; final int twelveletter = ++aaa + ++id; } catch (final IllegalStateException ise) { throw ise; } catch (final IllegalArgumentException ex) { throw ex; } }
Source:
public void onClick(View v) { if (v.getId() == R.id.upload_files_btn_cancel) { setResult(RESULT_CANCELED); finish(); } else if (v.getId() == R.id.upload_files_btn_upload) { new CheckAvailableSpaceTask().execute(); } }

Target:
public void onClick(View v) { if (v.getId() == R.id.upload_files_btn_cancel) { setResult(RESULT_CANCELED); finish(); } else if (v.getId() == R.id.upload_files_btn_upload) { new CheckAvailableSpaceTask(null).execute(); } }
Source:
private OnHeapValueHolder<V> putReturnHolder(final K key, final V value) throws CacheAccessException { putObserver.begin(); checkKey(key); checkValue(value); final AtomicBoolean entryActuallyAdded = new AtomicBoolean(); final long now = timeSource.getTimeMillis(); long estimatedSize = 1; long sizeOfKey = 0; if(byteSized) { sizeOfKey = getSizeOfKeyWithOffset(key); estimatedSize = getSizeOfValueWithOffset(value) + sizeOfKey + sizeOfEngine.getCHMOffset(); } final long delta = estimatedSize; final AtomicLong replacedValueSize = new AtomicLong(0l); try { OnHeapValueHolder<V> valuePut = map.compute(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, OnHeapValueHolder<V> mappedValue) { entryActuallyAdded.set(mappedValue == null); if (mappedValue != null && mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { mappedValue = null; } if (mappedValue == null) { return newCreateValueHolder(key, value, now); } else { if (byteSized) { replacedValueSize.set(sizeOfEngine.sizeof(mappedValue.value())); } return newUpdateValueHolder(key, mappedValue, value, now); } } }); if (entryActuallyAdded.get()) { putObserver.end(StoreOperationOutcomes.PutOutcome.PUT); enforceCapacity(delta); } else { putObserver.end(StoreOperationOutcomes.PutOutcome.REPLACED); if(byteSized) { long replacedDelta = delta - (sizeOfKey + replacedValueSize.get() + sizeOfEngine.getCHMOffset()); replaceByteCapacity(replacedDelta); } } return valuePut; } catch (RuntimeException re) { handleRuntimeException(re); return null; } }

Target:
private OnHeapValueHolder<V> putReturnHolder(final K key, final V value) throws CacheAccessException { putObserver.begin(); checkKey(key); checkValue(value); final AtomicBoolean entryActuallyAdded = new AtomicBoolean(); final long now = timeSource.getTimeMillis(); final AtomicReference<OnHeapValueHolder<V>> replacedValue = new AtomicReference<OnHeapValueHolder<V>>(null); try { OnHeapValueHolder<V> valuePut = map.compute(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, OnHeapValueHolder<V> mappedValue) { if (mappedValue != null && mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { mappedValue = null; } OnHeapValueHolder<V> toReturn = null; if (mappedValue == null) { toReturn = newCreateValueHolder(key, value, now); entryActuallyAdded.set(toReturn != null); } else { replacedValue.set(mappedValue); toReturn = newUpdateValueHolder(key, mappedValue, value, now); } return toReturn; } }); if (entryActuallyAdded.get()) { putObserver.end(StoreOperationOutcomes.PutOutcome.PUT); enforceCapacity(valuePut.size()); } else { putObserver.end(StoreOperationOutcomes.PutOutcome.REPLACED); long replacedDelta = valuePut == null ? 0 : valuePut.size() - (replacedValue.get() == null ? 0 : replacedValue.get().size()); replaceByteCapacity(replacedDelta); } return valuePut; } catch (RuntimeException re) { handleRuntimeException(re); return null; } }
Source:
private void appendRows(Map<Integer, Map<Integer, String>> rowsMap) { if (!rowsMap.isEmpty()) { rowsMap.forEach((rowIndex, cellValueMap) -> { model.insertRow(rowIndex, new ScenarioGridRow()); cellValueMap.forEach((columnIndex, cellValue) -> model.setCell(rowIndex, columnIndex, () -> new ScenarioGridCell(new ScenarioGridCellValue(cellValue)))); }); } }

Target:
private void appendRows(Map<Integer, Map<Integer, String>> rowsMap) { rowsMap.forEach((rowIndex, cellValueMap) -> { model.insertRow(rowIndex, new ScenarioGridRow()); cellValueMap.forEach((columnIndex, cellValue) -> model.setCell(rowIndex, columnIndex, () -> new ScenarioGridCell(new ScenarioGridCellValue(cellValue)))); }); }
Source:
private File createXmlFile(int numberOfTags, String fileName) throws Exception { init(false, temporaryFolder.getRoot()); File file = temporaryFolder.newFile(fileName); String simpleTag = "<tag1 attr=\"val1\">text</tag1>\n"; String xml = "<?xml version=\"1.0\"?><root>\n"; StringBuilder str = new StringBuilder(xml); for (int i = 0; i < numberOfTags; i++) { str.append(simpleTag); } str.append("</root>"); FileUtils.write(file, str.toString()); fs.add(createInputFile(file.getAbsolutePath())); return file; }

Target:
private File createXmlFile(int numberOfTags, String fileName) throws IOException { File file = temporaryFolder.newFile(fileName); StringBuilder str = new StringBuilder("<?xml version=\"1.0\"?><root>\n"); IntStream.range(0, numberOfTags).forEach(iteration -> str.append("<tag1 attr=\"val1\">text</tag1>\n")); str.append("</root>"); FileUtils.write(file, str.toString()); return file; }
Source:
public String buildZipFinishContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { logger.debug(this + ".buildZipFinishContext()"); context.put("tlang",trb); context.put ("collectionId", state.getAttribute (STATE_COLLECTION_ID) ); context.put ("collectionPath", state.getAttribute (STATE_COLLECTION_PATH)); List zipItems = (List) state.getAttribute(STATE_DELETE_SET); context.put ("zipItems", zipItems); if (RESOURCES_MODE_RESOURCES.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES))) { context.put("dropboxMode", Boolean.FALSE); } else if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES))) { context.put("dropboxMode", Boolean.TRUE); } context.put("homeCollection", (String) state.getAttribute (STATE_HOME_COLLECTION_ID)); context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE)); context.put ("resourceProperties", ContentHostingService.newResourceProperties ()); return TEMPLATE_ZIP_FINISH; }

Target:
public String buildZipFinishContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { logger.debug(this + ".buildZipFinishContext()"); context.put("tlang",trb); context.put ("collectionId", state.getAttribute (STATE_COLLECTION_ID) ); context.put ("collectionPath", state.getAttribute (STATE_COLLECTION_PATH)); List zipItems = (List) state.getAttribute(STATE_DELETE_SET); context.put ("zipItems", zipItems); context.put("homeCollection", state.getAttribute(STATE_HOME_COLLECTION_ID)); return TEMPLATE_ZIP_FINISH; }
Source:
public static CompilerDelegate getCompilerDelegate(final Context context) { CompilerDelegate compilerDelegate = context.get(compilerDelegateKey); if (compilerDelegate == null) { return new CompilerDelegate() { @Override public ModuleManager getModuleManager() { com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext = getCeylonContextInstance(context); return new CompilerModuleManager(ceylonContext, context); } @Override public PhasedUnit getExternalSourcePhasedUnit( VirtualFile srcDir, VirtualFile file) { return null; } @Override public void typeCheck(java.util.List<PhasedUnit> listOfUnits) { for (PhasedUnit pu : listOfUnits) { pu.validateTree(); pu.scanDeclarations(); } for (PhasedUnit pu : listOfUnits) { pu.scanTypeDeclarations(); } for (PhasedUnit pu: listOfUnits) { pu.validateRefinement(); } for (PhasedUnit pu : listOfUnits) { pu.analyseTypes(); } for (PhasedUnit pu : listOfUnits) { pu.analyseFlow(); } UnknownTypeCollector utc = new UnknownTypeCollector(); for (PhasedUnit pu : listOfUnits) { pu.getCompilationUnit().visit(utc); } } @Override public void visitModules(PhasedUnits phasedUnits) { phasedUnits.visitModules(); } @Override public void prepareForTypeChecking(List<JCCompilationUnit> trees) { CeylonEnter.instance(context).prepareForTypeChecking(trees); } }; } return compilerDelegate; }

Target:
public static CompilerDelegate getCompilerDelegate(final Context context) { CompilerDelegate compilerDelegate = context.get(compilerDelegateKey); if (compilerDelegate == null) { return new CeyloncCompilerDelegate(context); } return compilerDelegate; }
Source:
public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) { onExternalViewChange(externalView, idealState, onlineSegments); }

Target:
public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) { int numSegments = onlineSegments.size(); List<String> segments = new ArrayList<>(numSegments); List<String> segmentZKMetadataPaths = new ArrayList<>(numSegments); for (String segment : segments) { segments.add(segment); segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment); } List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, false); for (int i = 0; i < numSegments; i++) { String segment = segments.get(i); Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, znRecords.get(i)); _intervalMap.put(segment, interval); } _intervalTree = new IntervalTree<>(_intervalMap); }
Source:
public String getRoleName(String role) { return NLS.get("Permission." + role); }

Target:
public String getRoleName(String role) { return Permissions.getTranslatedPermission(role); }
Source:
protected ITmfTreeColumnDataProvider getColumnDataProvider() { return () -> { return ImmutableList.of( createColumn(Messages.AbstractSegmentStoreScatterView_Type, Comparator.comparing(TmfGenericTreeEntry::getName)), new TmfTreeColumnData(Messages.AbstractSegmentStoreScatterView_Legend)); }; }

Target:
protected ITmfTreeColumnDataProvider getColumnDataProvider() { return () -> ImmutableList.of( createColumn(Messages.AbstractSegmentStoreScatterView_Type, Comparator.comparing(TmfGenericTreeEntry::getName)), new TmfTreeColumnData(Messages.AbstractSegmentStoreScatterView_Legend)); }
Source:
public @ResponseBody PendingCertifiedProductResults getPendingCertifiedProducts() throws EntityRetrievalException, AccessDeniedException { if(Util.isUserRoleAdmin()){ throw new AccessDeniedException("Pending products may only be viewed by the ACB Administrators that manage them."); } List<CertificationBodyDTO> acbs = acbManager.getAllForUser(false); List<PendingCertifiedProductDTO> allProductDtos = new ArrayList<PendingCertifiedProductDTO>(); if (acbs != null) { for (CertificationBodyDTO acb : acbs) { try { List<PendingCertifiedProductDTO> pendingCpsByAcb = pcpManager .getPendingCertifiedProductsByAcb(acb.getId()); allProductDtos.addAll(pendingCpsByAcb); } catch (final AccessDeniedException denied) { LOGGER.warn("Access denied to pending certified products for acb " + acb.getName() + " and user " + Util.getUsername()); } } } List<PendingCertifiedProductDetails> result = new ArrayList<PendingCertifiedProductDetails>(); for (PendingCertifiedProductDTO product : allProductDtos) { PendingCertifiedProductDetails pcpDetails = new PendingCertifiedProductDetails(product); pcpManager.addAllVersionsToCmsCriterion(pcpDetails); pcpManager.addAllMeasuresToCertificationCriteria(pcpDetails); result.add(pcpDetails); } PendingCertifiedProductResults results = new PendingCertifiedProductResults(); results.getPendingCertifiedProducts().addAll(result); return results; }

Target:
public @ResponseBody PendingCertifiedProductResults getPendingCertifiedProducts() throws EntityRetrievalException, AccessDeniedException { if(!Util.isUserRoleAcbAdmin()){ throw new AccessDeniedException(String .format(messageSource.getMessage( new DefaultMessageSourceResolvable("access.pendingCertifiedProducts"), LocaleContextHolder.getLocale()))); } List<CertificationBodyDTO> acbs = acbManager.getAllForUser(false); List<PendingCertifiedProductDTO> allProductDtos = new ArrayList<PendingCertifiedProductDTO>(); if (acbs != null) { for (CertificationBodyDTO acb : acbs) { try { List<PendingCertifiedProductDTO> pendingCpsByAcb = pcpManager .getPendingCertifiedProductsByAcb(acb.getId()); allProductDtos.addAll(pendingCpsByAcb); } catch (final AccessDeniedException denied) { LOGGER.warn("Access denied to pending certified products for acb " + acb.getName() + " and user " + Util.getUsername()); } } } List<PendingCertifiedProductDetails> result = new ArrayList<PendingCertifiedProductDetails>(); for (PendingCertifiedProductDTO product : allProductDtos) { PendingCertifiedProductDetails pcpDetails = new PendingCertifiedProductDetails(product); pcpManager.addAllVersionsToCmsCriterion(pcpDetails); pcpManager.addAllMeasuresToCertificationCriteria(pcpDetails); result.add(pcpDetails); } PendingCertifiedProductResults results = new PendingCertifiedProductResults(); results.getPendingCertifiedProducts().addAll(result); return results; }
Source:
public boolean confirmStateTransfer(Address node, boolean statusOk) { synchronized (collector) { if (log.isDebugEnabled()) { log.debugf("Remove %s from %s. Status=%s", node, collector, statusOk); } if (this.statusOk && !statusOk) { this.statusOk = false; } return collector.remove(node) && collector.isEmpty(); } }

Target:
public boolean confirmStateTransfer(Address node, boolean statusOk) { synchronized (collector) { if (log.isTraceEnabled()) { log.tracef("Remove %s from %s. Status=%s", node, collector, statusOk); } if (this.statusOk && !statusOk) { this.statusOk = false; } return collector.remove(node) && collector.isEmpty(); } }
Source:
private void createAndExecuteConsumer(Subscription subscription) { logger.info("Creating consumer for {}", subscription.getId()); try { Consumer consumer = consumerFactory.createConsumer(subscription); logger.debug("Created consumer for {}", subscription.getId()); consumerHolder.add(subscription.getTopicName(), subscription.getName(), consumer); executor.execute(consumer); logger.debug("Consumer for is created and executed ", subscription.getId()); } catch (Exception ex) { logger.info("Failed to create consumer for subscription ", subscription.getId(), ex); } }

Target:
private void createAndExecuteConsumer(Subscription subscription) { logger.info("Creating consumer for {}", subscription.getId()); try { Consumer consumer = consumerFactory.createConsumer(subscription); logger.debug("Created consumer for {}", subscription.getId()); consumerHolder.add(subscription.getTopicName(), subscription.getName(), consumer); executor.execute(consumer); logger.debug("Consumer for was created and executed ", subscription.getId()); } catch (Exception ex) { logger.info("Failed to create consumer for subscription ", subscription.getId(), ex); } }
Source:
public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); fetchImageTemplates(); if (imageTemplates != null) { for (DiskImage disk : imageTemplates) { if (disk.getQuotaId() != null && !Guid.Empty.equals(disk.getQuotaId())) { list.add(new QuotaStorageConsumptionParameter( disk.getQuotaId(), null, QuotaStorageConsumptionParameter.QuotaAction.RELEASE, disk.getStorageIds().get(0), (double) disk.getSizeInGigabytes() * disk.getStorageIds().size())); } } } return list; }

Target:
public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); fetchImageTemplates(); if (imageTemplates != null) { for (DiskImage disk : imageTemplates) { if (disk.getQuotaId() != null && !Guid.Empty.equals(disk.getQuotaId())) { for (Guid storageId : disk.getStorageIds()) { list.add(new QuotaStorageConsumptionParameter( disk.getQuotaId(), null, QuotaStorageConsumptionParameter.QuotaAction.RELEASE, storageId, (double) disk.getSizeInGigabytes())); } } } } return list; }
Source:
public boolean doSupportDynamicMemoryAllocation() { return false; }

Target:
public boolean doSupportDynamicMemoryAllocation() { return true; }
Source:
public EventHubSharedAccessKeyCredential(String policyName, String sharedAccessKey, Duration tokenValidity) throws NoSuchAlgorithmException, InvalidKeyException { if (ImplUtils.isNullOrEmpty(policyName)) { throw new IllegalArgumentException("'policyName' cannot be null or empty"); } if (ImplUtils.isNullOrEmpty(sharedAccessKey)) { throw new IllegalArgumentException("'sharedAccessKey' cannot be null or empty."); } Objects.requireNonNull(tokenValidity); if (tokenValidity.isZero() || tokenValidity.isNegative()) { throw new IllegalArgumentException("'tokenTimeToLive' has to positive and in the order-of seconds"); } this.policyName = policyName; this.tokenValidity = tokenValidity; hmac = Mac.getInstance(HASH_ALGORITHM); final byte[] sasKeyBytes = sharedAccessKey.getBytes(UTF_8); final SecretKeySpec finalKey = new SecretKeySpec(sasKeyBytes, HASH_ALGORITHM); hmac.init(finalKey); }

Target:
public EventHubSharedAccessKeyCredential(String policyName, String sharedAccessKey, Duration tokenValidity) throws NoSuchAlgorithmException, InvalidKeyException { Objects.requireNonNull(sharedAccessKey, "'sharedAccessKey' cannot be null."); this.policyName = Objects.requireNonNull(policyName, "'sharedAccessKey' cannot be null."); this.tokenValidity = Objects.requireNonNull(tokenValidity, "'tokenValidity' cannot be null."); if (policyName.isEmpty()) { throw new IllegalArgumentException("'policyName' cannot be an empty string."); } else if (sharedAccessKey.isEmpty()) { throw new IllegalArgumentException("'sharedAccessKey' cannot be an empty string."); } else if (tokenValidity.isZero() || tokenValidity.isNegative()) { throw new IllegalArgumentException("'tokenTimeToLive' has to positive and in the order-of seconds"); } hmac = Mac.getInstance(HASH_ALGORITHM); final byte[] sasKeyBytes = sharedAccessKey.getBytes(UTF_8); final SecretKeySpec finalKey = new SecretKeySpec(sasKeyBytes, HASH_ALGORITHM); hmac.init(finalKey); }
Source:
protected void implReset() { super.implReset(); if (iconv_tPointer != 0) { IconvProvider.release(iconv_tPointer); iconv_tPointer = 0; } }

Target:
protected void implReset() { super.implReset(); this.release(); }