auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public byte[] getCacheKey() { byte[] dimensionBytes = StringUtils.toUtf8(dimension); final byte[][] valuesBytes = new byte[values.size()][]; int valuesBytesSize = 0; int index = 0; boolean hasNull = false; for (String value : values) { if (value == null) { hasNull = true; } valuesBytes[index] = StringUtils.toUtf8(Strings.nullToEmpty(value)); valuesBytesSize += valuesBytes[index].length + 1; ++index; } byte[] extractionFnBytes = extractionFn == null ? new byte[0] : extractionFn.getCacheKey(); ByteBuffer filterCacheKey = ByteBuffer.allocate(5 + dimensionBytes.length + valuesBytesSize + extractionFnBytes.length) .put(DimFilterUtils.IN_CACHE_ID) .put(dimensionBytes) .put(DimFilterUtils.STRING_SEPARATOR) .put(extractionFnBytes) .put(DimFilterUtils.STRING_SEPARATOR) .put(hasNull ? NullHandling.IS_NULL_BYTE : NullHandling.IS_NOT_NULL_BYTE) .put(DimFilterUtils.STRING_SEPARATOR); for (byte[] bytes : valuesBytes) { filterCacheKey.put(bytes) .put((byte) 0xFF); } return filterCacheKey.array(); }

Target:
public byte[] getCacheKey() { boolean hasNull = false; for (String value : values) { if (value == null) { hasNull = true; break; } } return new CacheKeyBuilder(DimFilterUtils.IN_CACHE_ID) .appendString(dimension) .appendByte(DimFilterUtils.STRING_SEPARATOR) .appendByteArray(extractionFn == null ? new byte[0] : extractionFn.getCacheKey()) .appendByte(DimFilterUtils.STRING_SEPARATOR) .appendByte(hasNull ? NullHandling.IS_NULL_BYTE : NullHandling.IS_NOT_NULL_BYTE) .appendByte(DimFilterUtils.STRING_SEPARATOR) .appendStrings(values).build(); }
Source:
public List<UsagePermission> getEffectivePermissions() { List<UsagePermission> ps = buildPermissions(); Set<String> inheritedClouds = getInheritedClouds(); for (UsagePermission p : ps) { if (inheritedClouds.contains(p.name)) { p.setGranted(true); p.setInherited(true); } if (getPermittedClouds().contains(p.name)) { p.setGranted(true); } } if (!userHasAdministerPermission()) { ps = ps.stream().filter(f -> f.granted).collect(Collectors.toList()); } return ps; }

Target:
public List<UsagePermission> getEffectivePermissions() { List<UsagePermission> ps = buildPermissions(); Set<String> inheritedClouds = getInheritedClouds(); for (UsagePermission p : ps) { if (inheritedClouds.contains(p.name)) { p.setGranted(true); p.setInherited(true); } if (getPermittedClouds().contains(p.name)) { p.setGranted(true); } } if (!userHasAdministerPermission()) { ps = ps.stream().filter(UsagePermission::isGranted).collect(Collectors.toList()); } return ps; }
Source:
private void setLeader(HelixManager manager) throws Exception { System.out.println("Setting controller " + manager.getInstanceName() + " as leader"); HelixDataAccessor accessor = manager.getHelixDataAccessor(); final LiveInstance leader = new LiveInstance(manager.getInstanceName()); leader.setLiveInstance(ManagementFactory.getRuntimeMXBean().getName()); leader.setSessionId(manager.getSessionId()); leader.setHelixVersion(manager.getVersion()); while (!manager.isLeader()) { accessor.getBaseDataAccessor() .remove(PropertyPathBuilder.controllerLeader(manager.getClusterName()), AccessOption.EPHEMERAL); Thread.sleep(50); } }

Target:
private void setLeader(HelixManager manager) throws Exception { HelixDataAccessor accessor = manager.getHelixDataAccessor(); final LiveInstance leader = new LiveInstance(manager.getInstanceName()); leader.setLiveInstance(ManagementFactory.getRuntimeMXBean().getName()); leader.setSessionId(manager.getSessionId()); leader.setHelixVersion(manager.getVersion()); while (!manager.isLeader()) { accessor.getBaseDataAccessor() .remove(PropertyPathBuilder.controllerLeader(manager.getClusterName()), AccessOption.EPHEMERAL); Thread.sleep(50); } }
Source:
public synchronized void updatePartitionStatistics(String databaseName, String tableName, String partitionName, Function<PartitionStatistics, PartitionStatistics> update) { PartitionStatistics originalStatistics = requireNonNull(getPartitionStatistics(databaseName, tableName, ImmutableSet.of(partitionName)).get(partitionName), "originalStatistics is null"); PartitionStatistics updatedStatistics = update.apply(originalStatistics); Table table = getRequiredTable(databaseName, tableName); List<String> partitionValues = extractPartitionKeyValues(partitionName); Path partitionDirectory = getPartitionMetadataDirectory(table, partitionValues); PartitionMetadata partitionMetadata = readSchemaFile("partition", partitionDirectory, partitionCodec) .orElseThrow(() -> new PartitionNotFoundException(new SchemaTableName(databaseName, tableName), partitionValues)); PartitionMetadata updatedMetadata = partitionMetadata .withParameters(updateStatisticParameters(partitionMetadata.getParameters(), updatedStatistics.getBasicStatistics())) .withColumnStatistics(updatedStatistics.getColumnStatistics()); writeSchemaFile("partition", partitionDirectory, partitionCodec, updatedMetadata, true); }

Target:
public synchronized void updatePartitionStatistics(String databaseName, String tableName, String partitionName, Function<PartitionStatistics, PartitionStatistics> update) { PartitionStatistics originalStatistics = requireNonNull( getPartitionStatistics(databaseName, tableName, ImmutableSet.of(partitionName)).get(partitionName), "getPartitionStatistics() returned null"); PartitionStatistics updatedStatistics = update.apply(originalStatistics); Table table = getRequiredTable(databaseName, tableName); List<String> partitionValues = extractPartitionKeyValues(partitionName); Path partitionDirectory = getPartitionMetadataDirectory(table, partitionValues); PartitionMetadata partitionMetadata = readSchemaFile("partition", partitionDirectory, partitionCodec) .orElseThrow(() -> new PartitionNotFoundException(new SchemaTableName(databaseName, tableName), partitionValues)); PartitionMetadata updatedMetadata = partitionMetadata .withParameters(updateStatisticParameters(partitionMetadata.getParameters(), updatedStatistics.getBasicStatistics())) .withColumnStatistics(updatedStatistics.getColumnStatistics()); writeSchemaFile("partition", partitionDirectory, partitionCodec, updatedMetadata, true); }
Source:
public synchronized boolean isComplete(int requestId, boolean remove) { if (!operations.containsKey(requestId)) return true; if (operations.get(requestId).getStatus().isComplete()) { if (logger.isDebugEnabled()) logger.debug("Operation complete " + requestId); if (remove) operations.remove(requestId); return true; } return false; }

Target:
public synchronized boolean isComplete(int requestId, boolean remove) { if (!operations.containsKey(requestId)) throw new VoldemortException("No operation with id " + requestId + " found"); if (operations.get(requestId).getStatus().isComplete()) { if (logger.isDebugEnabled()) logger.debug("Operation complete " + requestId); if (remove) operations.remove(requestId); return true; } return false; }
Source:
private void initFolder() { mFolder = new Folder(); mFolder.id = (getIntent().hasExtra(EXTRA_FOLDER_ID)) ? getIntent().getStringExtra(EXTRA_FOLDER_ID) : generateRandomFolderId(); mFolder.label = getIntent().getStringExtra(EXTRA_FOLDER_LABEL); mFolder.rescanIntervalS = 3600; mFolder.versioning = new Folder.Versioning(); }

Target:
private void initFolder() { mFolder = new Folder(); mFolder.id = (getIntent().hasExtra(EXTRA_FOLDER_ID)) ? getIntent().getStringExtra(EXTRA_FOLDER_ID) : generateRandomFolderId(); mFolder.label = getIntent().getStringExtra(EXTRA_FOLDER_LABEL); mFolder.fsWatcherEnabled = true; mFolder.fsWatcherDelayS = 10; mFolder.rescanIntervalS = 3600; mFolder.versioning = new Folder.Versioning(); }
Source:
private void changePreferenceSummary(String preferenceKey) { if (preferenceKey.equalsIgnoreCase(getString(R.string.preference_key_region)) || preferenceKey.equalsIgnoreCase(getString(R.string.preference_key_oba_api_url))) { if (Application.get().getCurrentRegion() != null) { mPreference.setSummary(Application.get().getCurrentRegion().getName()); mCustomApiUrlPref .setSummary(getString(R.string.preferences_oba_api_servername_summary)); String customOtpApiUrl = Application.get().getCustomOtpApiUrl(); if (customOtpApiUrl == null) { mCustomOtpApiUrlPref .setSummary(getString(R.string.preferences_otp_api_servername_summary)); } else { mCustomOtpApiUrlPref.setSummary(customOtpApiUrl); } } else { mPreference.setSummary(getString(R.string.preferences_region_summary_custom_api)); mCustomApiUrlPref.setSummary(Application.get().getCustomApiUrl()); } } else if (preferenceKey .equalsIgnoreCase(getString(R.string.preference_key_preferred_units))) { preferredUnits.setSummary(preferredUnits.getValue()); } else if (preferenceKey .equalsIgnoreCase(getString(R.string.preference_key_otp_api_url))) { String otpApiUrl = Application.get().getCustomOtpApiUrl(); if (!TextUtils.isEmpty(otpApiUrl)) { mCustomOtpApiUrlPref.setSummary(otpApiUrl); } else { mCustomOtpApiUrlPref.setSummary( getString(R.string.preferences_otp_api_servername_summary)); } Application.get().setUseOldOtpApiUrlVersion(false); mOtpCustomAPIUrlChanged = true; } }

Target:
private void changePreferenceSummary(String preferenceKey) { if (preferenceKey.equalsIgnoreCase(getString(R.string.preference_key_region)) || preferenceKey.equalsIgnoreCase(getString(R.string.preference_key_oba_api_url))) { if (Application.get().getCurrentRegion() != null) { mPreference.setSummary(Application.get().getCurrentRegion().getName()); mCustomApiUrlPref .setSummary(getString(R.string.preferences_oba_api_servername_summary)); String customOtpApiUrl = Application.get().getCustomOtpApiUrl(); if (!TextUtils.isEmpty(customOtpApiUrl)) { mCustomOtpApiUrlPref.setSummary(customOtpApiUrl); } else { mCustomOtpApiUrlPref .setSummary(getString(R.string.preferences_otp_api_servername_summary)); } } else { mPreference.setSummary(getString(R.string.preferences_region_summary_custom_api)); mCustomApiUrlPref.setSummary(Application.get().getCustomApiUrl()); } } else if (preferenceKey .equalsIgnoreCase(getString(R.string.preference_key_preferred_units))) { preferredUnits.setSummary(preferredUnits.getValue()); } else if (preferenceKey .equalsIgnoreCase(getString(R.string.preference_key_otp_api_url))) { String customOtpApiUrl = Application.get().getCustomOtpApiUrl(); if (!TextUtils.isEmpty(customOtpApiUrl)) { mCustomOtpApiUrlPref.setSummary(customOtpApiUrl); } else { mCustomOtpApiUrlPref.setSummary( getString(R.string.preferences_otp_api_servername_summary)); } Application.get().setUseOldOtpApiUrlVersion(false); mOtpCustomAPIUrlChanged = true; } }
Source:
public void init() { executorService.schedule(this::setPublications, 1, TimeUnit.MILLISECONDS); }

Target:
public void init() { executorService.submit(this::setPublications); }
Source:
public CloseableIterable<RyaStatement> query(final BatchRyaQuery batchRyaQuery) throws RyaDAOException { final Map<RyaStatement, BindingSet> queries = new HashMap<>(); for (final RyaStatement stmt : batchRyaQuery.getQueries()) { queries.put(stmt, new MapBindingSet()); } Iterator<RyaStatement> iterator = new RyaStatementCursorIterator(queryWithBindingSet(queries.entrySet(), getConf())); return CloseableIterables.wrap((Iterable<RyaStatement>) () -> iterator); }

Target:
public CloseableIterable<RyaStatement> query(final BatchRyaQuery batchRyaQuery) throws RyaDAOException { Preconditions.checkNotNull(batchRyaQuery); final Map<RyaStatement, BindingSet> queries = new HashMap<>(); for (final RyaStatement stmt : batchRyaQuery.getQueries()) { queries.put(stmt, new MapBindingSet()); } Iterator<RyaStatement> iterator = new RyaStatementCursorIterator(queryWithBindingSet(queries.entrySet(), getConf())); return CloseableIterables.wrap((Iterable<RyaStatement>) () -> iterator); }
Source:
public String save() { String login = this.userObject.getLogin(); if (Objects.isNull(userObject.getId()) && !userService.isLoginValid(login)) { Helper.setErrorMessage("loginNotValid", new Object[] {login }); return this.stayOnCurrentPage; } if (isMissingClient()) { Helper.setErrorMessage("errorMissingClient"); return this.stayOnCurrentPage; } try { if (userService.getAmountOfUsersWithExactlyTheSameLogin(this.userObject.getId(), login) == 0) { if (Objects.nonNull(this.passwordToEncrypt)) { this.userObject.setPassword(passwordEncoder.encrypt(this.passwordToEncrypt)); } userService.saveToDatabase(this.userObject); if (userService.getAuthenticatedUser().getId().equals(this.userObject.getId())) { loginForm.setLoggedUser(this.userObject); } return userListPath; } else { Helper.setErrorMessage("loginInUse"); return this.stayOnCurrentPage; } } catch (DAOException | RuntimeException e) { Helper.setErrorMessage(ERROR_SAVING, new Object[] {ObjectType.USER.getTranslationSingular() }, logger, e); return this.stayOnCurrentPage; } }

Target:
public String save() { String login = this.userObject.getLogin(); if (!isUserExistingOrLoginValid(login)) { Helper.setErrorMessage("loginNotValid", new Object[] {login }); return this.stayOnCurrentPage; } if (isMissingClient()) { Helper.setErrorMessage("errorMissingClient"); return this.stayOnCurrentPage; } try { if (userService.getAmountOfUsersWithExactlyTheSameLogin(this.userObject.getId(), login) == 0) { if (Objects.nonNull(this.passwordToEncrypt)) { this.userObject.setPassword(passwordEncoder.encrypt(this.passwordToEncrypt)); } userService.saveToDatabase(this.userObject); if (userService.getAuthenticatedUser().getId().equals(this.userObject.getId())) { loginForm.setLoggedUser(this.userObject); } return userListPath; } else { Helper.setErrorMessage("loginInUse"); return this.stayOnCurrentPage; } } catch (DAOException | RuntimeException e) { Helper.setErrorMessage(ERROR_SAVING, new Object[] {ObjectType.USER.getTranslationSingular() }, logger, e); return this.stayOnCurrentPage; } }
Source:
public void fireSolvingStarted(DefaultSolverScope<Solution_> solverScope) { if (eventListenerSet.isEmpty()) { return; } final SolvingStartedEvent<Solution_> event = new SolvingStartedEvent<>(solver); for (SolverListener<Solution_> listener : eventListenerSet) { listener.solvingStarted(event); } }

Target:
public void fireSolvingStarted(DefaultSolverScope<Solution_> solverScope) { if (eventListenerSet.isEmpty()) { return; } final SolvingStartedEvent event = new SolvingStartedEvent(solver); for (SolverListener listener : eventListenerSet) { listener.solvingStarted(event); } }
Source:
public void invokeCallbackMethods() { initCommandExecutor(); Iterator<Entry<Guid, CommandContainer>> iterator = cmdCallbackMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<Guid, CommandContainer> entry = iterator.next(); if (--entry.getValue().executionCountdown > 1) { continue; } Guid cmdId = entry.getKey(); CommandCallback callback = entry.getValue().callback; CommandStatus status = coco.getCommandStatus(cmdId); boolean errorInCallback = false; try { switch (status) { case FAILED: callback.onFailed(cmdId, coco.getChildCommandIds(cmdId)); break; case SUCCEEDED: callback.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); break; case ACTIVE: if (coco.getCommandEntity(cmdId).isExecuted()) { callback.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } break; default: break; } } catch (Exception ex) { errorInCallback = true; handleError(ex, status, cmdId); } finally { if (CommandStatus.FAILED.equals(status) || (CommandStatus.SUCCEEDED.equals(status) && !errorInCallback)) { coco.updateCallbackNotified(cmdId); iterator.remove(); } else { int maxDelay = Config.<Integer>getValue(ConfigValues.AsyncCommandPollingRateInSeconds); entry.getValue().executionDelay = Math.min(maxDelay, entry.getValue().executionDelay * 2); entry.getValue().executionCountdown = entry.getValue().executionDelay; } } } }

Target:
public void invokeCallbackMethods() { initCommandExecutor(); Iterator<Entry<Guid, CommandContainer>> iterator = cmdCallbackMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<Guid, CommandContainer> entry = iterator.next(); if (--entry.getValue().executionCountdown > 0) { continue; } Guid cmdId = entry.getKey(); CommandCallback callback = entry.getValue().callback; CommandStatus status = coco.getCommandStatus(cmdId); boolean errorInCallback = false; try { switch (status) { case FAILED: callback.onFailed(cmdId, coco.getChildCommandIds(cmdId)); break; case SUCCEEDED: callback.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); break; case ACTIVE: if (coco.getCommandEntity(cmdId).isExecuted()) { callback.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } break; default: break; } } catch (Exception ex) { errorInCallback = true; handleError(ex, status, cmdId); } finally { if (CommandStatus.FAILED.equals(status) || (CommandStatus.SUCCEEDED.equals(status) && !errorInCallback)) { coco.updateCallbackNotified(cmdId); iterator.remove(); } else { int maxDelay = Config.<Integer>getValue(ConfigValues.AsyncCommandPollingRateInSeconds); entry.getValue().executionDelay = Math.min(maxDelay, entry.getValue().executionDelay * 2); entry.getValue().executionCountdown = entry.getValue().executionDelay; } } } }
Source:
public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { final Player player = event.getPlayer(); final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH); if (ess.getUser(player).isMuted() && (ess.getSettings().getMuteCommands().contains(cmd) || ess.getSettings().getMuteCommands().contains("*"))) { event.setCancelled(true); player.sendMessage(tl("voiceSilenced")); LOGGER.info(tl("mutedUserSpeaks", player.getName())); return; } if (ess.getSettings().getSocialSpyCommands().contains(cmd) || ess.getSettings().getSocialSpyCommands().contains("*")) { if (!player.hasPermission("essentials.chat.spy.exempt")) { for (User spyer : ess.getOnlineUsers()) { if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) { spyer.sendMessage(player.getDisplayName() + " : " + event.getMessage()); } } } } boolean broadcast = true; boolean update = true; PluginCommand pluginCommand = ess.getServer().getPluginCommand(cmd); if (pluginCommand != null) { switch (pluginCommand.getName()) { case "afk": update = false; case "vanish": broadcast = false; } } if (update) { final User user = ess.getUser(player); user.updateActivity(broadcast); } }

Target:
public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { final Player player = event.getPlayer(); final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH); if (ess.getUser(player).isMuted() && (ess.getSettings().getMuteCommands().contains(cmd) || ess.getSettings().getMuteCommands().contains("*"))) { event.setCancelled(true); player.sendMessage(tl("voiceSilenced")); LOGGER.info(tl("mutedUserSpeaks", player.getName())); return; } if (ess.getSettings().getSocialSpyCommands().contains(cmd) || ess.getSettings().getSocialSpyCommands().contains("*")) { if (!player.hasPermission("essentials.chat.spy.exempt")) { for (User spyer : ess.getOnlineUsers()) { if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) { spyer.sendMessage(player.getDisplayName() + " : " + event.getMessage()); } } } } else { boolean broadcast = true; boolean update = true; PluginCommand pluginCommand = ess.getServer().getPluginCommand(cmd); if (pluginCommand != null) { switch (pluginCommand.getName()) { case "afk": update = false; case "vanish": broadcast = false; } } if (update) { final User user = ess.getUser(player); user.updateActivity(broadcast); } } }
Source:
private void showShiftDateSnackBar(boolean isSuccess) { SnackbarErrorNotification snackbarErrorNotification = new SnackbarErrorNotification(authWebView); if (isSuccess) { snackbarErrorNotification.showError(R.string.assessment_shift_dates_success_msg, null, R.string.assessment_view_all_dates, Snackbar.LENGTH_LONG, v -> Log.i("showPopupWindow", "Error Click")); } else { snackbarErrorNotification.showError(R.string.course_dates_reset_unsuccessful, null, 0, Snackbar.LENGTH_LONG, null); } }

Target:
private void showShiftDateSnackBar(boolean isSuccess) { SnackbarErrorNotification snackbarErrorNotification = new SnackbarErrorNotification(authWebView); if (isSuccess) { snackbarErrorNotification.showError(R.string.assessment_shift_dates_success_msg, null, R.string.assessment_view_all_dates, SnackbarErrorNotification.COURSE_DATE_MESSAGE_DURATION, v -> environment.getRouter().showCourseDashboardTabs(getActivity(), null, unit.getCourseId(), null, null, false, Screen.COURSE_DATES)); } else { snackbarErrorNotification.showError(R.string.course_dates_reset_unsuccessful, null, 0, SnackbarErrorNotification.COURSE_DATE_MESSAGE_DURATION, null); } }
Source:
public void beginTask(int max) { done(); progressBar = new ProgressBar(this, styleForProgressBar); this.totalWork = max; this.sumWorked = 0; progressBar.setMinimum(0); progressBar.setMaximum(PROGRESS_MAX); progressBar.setSelection(0); requestLayout(); animated = false; }

Target:
public void beginTask(int max) { if (progressBar == null || progressBar.isDisposed()) { progressBar = new ProgressBar(this, styleForProgressBar); requestLayout(); } this.totalWork = max; this.sumWorked = 0; progressBar.setMinimum(0); progressBar.setMaximum(PROGRESS_MAX); progressBar.setSelection(0); animated = false; }
Source:
public void test000_openrepo_default_relative_workdirconfig() throws IOException { File repo1Parent = new File(trash.getParentFile(), "r1"); File workdir = new File(trash.getParentFile(), "rw"); assertTrue(workdir.mkdir()); FileRepository repo1initial = new FileRepository(new File(repo1Parent, Constants.DOT_GIT)); repo1initial.create(); final FileBasedConfig cfg = repo1initial.getConfig(); cfg.setString("core", null, "worktree", "../../rw"); cfg.save(); repo1initial.close(); File theDir = new File(repo1Parent, Constants.DOT_GIT); FileRepository r = new FileRepositoryBuilder().setGitDir(theDir) .build(); assertEqualsPath(theDir, r.getDirectory()); assertEqualsPath(workdir, r.getWorkTree()); assertEqualsPath(new File(theDir, "index"), r.getIndexFile()); assertEqualsPath(new File(theDir, "objects"), r.getObjectDatabase() .getDirectory()); }

Target:
public void test000_openrepo_default_relative_workdirconfig() throws IOException { File repo1Parent = new File(trash.getParentFile(), "r1"); File workdir = new File(trash.getParentFile(), "rw"); FileUtils.mkdir(workdir); FileRepository repo1initial = new FileRepository(new File(repo1Parent, Constants.DOT_GIT)); repo1initial.create(); final FileBasedConfig cfg = repo1initial.getConfig(); cfg.setString("core", null, "worktree", "../../rw"); cfg.save(); repo1initial.close(); File theDir = new File(repo1Parent, Constants.DOT_GIT); FileRepository r = new FileRepositoryBuilder().setGitDir(theDir) .build(); assertEqualsPath(theDir, r.getDirectory()); assertEqualsPath(workdir, r.getWorkTree()); assertEqualsPath(new File(theDir, "index"), r.getIndexFile()); assertEqualsPath(new File(theDir, "objects"), r.getObjectDatabase() .getDirectory()); }
Source:
public static void updateVmInitFromDB(VmBase vm, boolean secure) { VmInitDAO db = DbFacade.getInstance().getVmInitDao(); vm.setVmInit(db.get(vm.getId())); if (secure && vm.getVmInit() != null) { vm.getVmInit().setPasswordAlreadyStored(!StringUtils.isEmpty(vm.getVmInit().getRootPassword())); vm.getVmInit().setRootPassword(null); } }

Target:
public static void updateVmInitFromDB(VmBase vm, boolean secure) { VmInitDAO db = DbFacade.getInstance().getVmInitDao(); vm.setVmInit(db.get(vm.getId())); if (vm.getVmInit() != null) { if (secure) { vm.getVmInit().setPasswordAlreadyStored(!StringUtils.isEmpty(vm.getVmInit().getRootPassword())); } else { vm.getVmInit().setPasswordAlreadyStored(false); } vm.getVmInit().setRootPassword(null); } }
Source:
private static String resolvePathParameters(final String basePath, final String classPathAnnotation, final String methodPathAnnotation, final Map<String, Object> pathParameterValues) { final UriBuilder builder = UriBuilder.fromUri(basePath); if (classPathAnnotation != null && !classPathAnnotation.equals("")) { builder.path(classPathAnnotation); } if (methodPathAnnotation != null && !methodPathAnnotation.equals("")) { builder.path(methodPathAnnotation); } String returnUri = null; Map<String, Object> parameters = pathParameterValues; if (pathParameterValues == null) parameters = new HashMap<String, Object>(); final URI resolvedUri = builder.buildFromMap(parameters); if (resolvedUri != null) { returnUri = resolvedUri.toString(); } return returnUri; }

Target:
private static String resolvePathParameters(final String basePath, final String classPathAnnotation, final String methodPathAnnotation, final Map<String, Object> pathParameterValues) { final UriBuilder builder = UriBuilder.fromUri(basePath); if (classPathAnnotation != null && !classPathAnnotation.equals("")) { builder.path(classPathAnnotation); } if (methodPathAnnotation != null && !methodPathAnnotation.equals("")) { builder.path(methodPathAnnotation); } final URI resolvedUri = builder.buildFromMap(pathParameterValues); if (resolvedUri != null) { return resolvedUri.toString(); } log.warn("Could not build a path URI for basePath={} and path annotations (class='{}',method='{}')", basePath, classPathAnnotation, methodPathAnnotation ); return null; }
Source:
public void copyFile_shouldNotCopyTheOutputstreamWhenOutputstreamIsNull() throws Exception { String exampleInputStreamString = "ExampleInputStream"; ByteArrayInputStream input = new ByteArrayInputStream(exampleInputStreamString.getBytes()); OutputStream output = null; OpenmrsUtil.copyFile(input, output); assertEquals(null, output); assertNotEquals(null, input); }

Target:
public void copyFile_shouldNotCopyTheOutputstreamWhenOutputstreamIsNull() throws Exception { String exampleInputStreamString = "ExampleInputStream"; ByteArrayInputStream input = new ByteArrayInputStream(exampleInputStreamString.getBytes()); OutputStream output = null; OpenmrsUtil.copyFile(input, output); assertNull(output); assertNotNull(input); }
Source:
public AggregateExpression(ExpressionType type) { super(type); m_userAggregateId = "-1"; m_name = "notUDAF"; }

Target:
public AggregateExpression(ExpressionType type) { super(type); m_userAggregateId = -1; m_name = ""; }
Source:
@Override public void addPathParam(String name, String value) { boolean disableUrlEncoding = false; addPathParam(name, value, disableUrlEncoding); }

Target:
@Override public void addPathParam(String name, String value) { addPathParam(name, value, true); }
Source:
private boolean sponge$onCreateDataDirectory(File dir) { return WorldManager.mkdirsIfSaveable(dir); }

Target:
private boolean forgeImpl$onCreateDataDirectory(File dir) { return WorldManager.mkdirsIfSaveable(dir); }
Source:
public void testMigration(EntitySpec<? extends JavaWebAppSoftwareProcess> webServerSpec) throws Exception { final JavaWebAppSoftwareProcess server = app.createAndManageChild(webServerSpec .addInitializer(new JavaWebAppMigrateEffector()) .configure(JavaWebAppSoftwareProcess.OPEN_IPTABLES, true) .configure("war", getTestWar())); app.start(ImmutableList.of(amazonProvisioningLocation)); EntityTestUtils.assertAttributeEqualsEventually(server, Attributes.SERVICE_UP, Boolean.TRUE); String preMigrationUrl = server.getAttribute(JavaWebAppSoftwareProcess.ROOT_URL); HttpTestUtils.assertUrlReachable(preMigrationUrl); Effectors.invocation(AllowsMigration.MIGRATE, MutableMap.of("locationSpec", LOCATION_SPEC), server).asTask().blockUntilEnded(); EntityTestUtils.assertAttributeEqualsEventually(server, Attributes.SERVICE_UP, Boolean.TRUE); String afterMigrationUrl = server.getAttribute(JavaWebAppSoftwareProcess.ROOT_URL); HttpTestUtils.assertUrlReachable(afterMigrationUrl); HttpTestUtils.assertUrlUnreachable(preMigrationUrl); }

Target:
public void testMigration(EntitySpec<? extends JavaWebAppSoftwareProcess> webServerSpec) throws Exception { final JavaWebAppSoftwareProcess server = app.createAndManageChild(webServerSpec .addInitializer(new AddMigrateEffectorEntityInitializer()) .configure(JavaWebAppSoftwareProcess.OPEN_IPTABLES, true) .configure("war", getTestWar())); app.start(ImmutableList.of(amazonProvisioningLocation)); EntityTestUtils.assertAttributeEqualsEventually(server, Attributes.SERVICE_UP, Boolean.TRUE); String preMigrationUrl = server.getAttribute(JavaWebAppSoftwareProcess.ROOT_URL); HttpTestUtils.assertUrlReachable(preMigrationUrl); Effectors.invocation(MigrateEffector.MIGRATE, MutableMap.of("locationSpec", LOCATION_SPEC), server).asTask().blockUntilEnded(Duration.FIVE_MINUTES); EntityTestUtils.assertAttributeEqualsEventually(server, Attributes.SERVICE_UP, Boolean.TRUE); String afterMigrationUrl = server.getAttribute(JavaWebAppSoftwareProcess.ROOT_URL); HttpTestUtils.assertUrlReachable(afterMigrationUrl); HttpTestUtils.assertUrlUnreachable(preMigrationUrl); }
Source:
public static CreateMode fromFlag(int flag) throws KeeperException { switch (flag) { case 0: return CreateMode.PERSISTENT; case 1: return CreateMode.EPHEMERAL; case 2: return CreateMode.PERSISTENT_SEQUENTIAL; case 3: return CreateMode.EPHEMERAL_SEQUENTIAL; case 4: return CreateMode.CONTAINER; case 5: return CreateMode.PERSISTENT_WITH_TTL; case 6: return CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL; default: String errMsg = "Received an invalid flag value: " + flag + " to convert to a CreateMode"; LOG.error(errMsg); throw new KeeperException.BadArgumentsException(); } }

Target:
public static CreateMode fromFlag(int flag) throws KeeperException { switch (flag) { case 0: return CreateMode.PERSISTENT; case 1: return CreateMode.EPHEMERAL; case 2: return CreateMode.PERSISTENT_SEQUENTIAL; case 3: return CreateMode.EPHEMERAL_SEQUENTIAL; case 4: return CreateMode.CONTAINER; case 5: return CreateMode.PERSISTENT_WITH_TTL; case 6: return CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL; default: String errMsg = "Received an invalid flag value: " + flag + " to convert to a CreateMode"; LOG.error(errMsg); throw new KeeperException.BadArgumentsException(errMsg); } }
Source:
public void setUp() { checkXmlRequest("hosts/123/setupnetworks", 200, "<action><modified_bonds><host_nic><bonding><options><option><name>mode</name><type>4</type></option></options><slaves><slave><name>eth1</name></slave><slave><name>eth2</name></slave></slaves></bonding><name>bond0</name></host_nic></modified_bonds></action>"); startServer(); connection = testConnection(); hostService = connection.systemService().hostsService().hostService("123"); }

Target:
public void setUp() { expectXmlRequest( "hosts/123/setupnetworks", 200, "<action>" + "<modified_bonds>" + "<host_nic>" + "<bonding>" + "<options>" + "<option>" + "<name>mode</name>" + "<type>4</type>" + "</option>" + "</options>" + "<slaves>" + "<slave>" + "<name>eth1</name>" + "</slave>" + "<slave>" + "<name>eth2</name>" + "</slave>" + "</slaves>" + "</bonding>" + "<name>bond0</name>" + "</host_nic>" + "</modified_bonds>" + "</action>" ); startServer(); connection = testConnection(); hostService = connection.systemService().hostsService().hostService("123"); }
Source:
public Authentication authenticate(Authentication authentication) { Preconditions.checkArgument(authentication instanceof InternalAuthentication, "InternalAuthenticationProvider only supports InternalAuthentication."); String username = authentication.getName(); String password = (String) authentication.getCredentials(); if (Strings.isNullOrEmpty(username)) { throw new BadCredentialsException("InternalAuthenticationProvider: Empty Username"); } if (Strings.isNullOrEmpty(password)) { throw new BadCredentialsException("InternalAuthenticationProvider: Empty Password"); } assertUserNotLocked(username); User user = userProvisioning.getByUsernameWithPassword(username); if (user == null) { throw new BadCredentialsException("The user with the username '" + username + "' doesn't exist!"); } if (user.isActive() != Boolean.TRUE) { throw new DisabledException("The user with the username '" + username + "' is disabled!"); } if (!bCryptPasswordEncoder.matches(password, user.getPassword())) { if (passwordEncoder.isPasswordValid(user.getPassword(), password, user.getId())) { User replaceUser = new User.Builder(user).setPassword(password).build(); userProvisioning.replace(user.getId(), replaceUser); } else { throw new BadCredentialsException("Bad credentials"); } } User authUser = new User.Builder(username).setId(user.getId()).build(); List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (Role role : user.getRoles()) { grantedAuthorities.add(new SimpleGrantedAuthority(role.getValue())); } return new InternalAuthentication(authUser, password, grantedAuthorities); }

Target:
public Authentication authenticate(Authentication authentication) { Preconditions.checkArgument(authentication instanceof InternalAuthentication, "InternalAuthenticationProvider only supports InternalAuthentication."); String username = authentication.getName(); String password = (String) authentication.getCredentials(); if (Strings.isNullOrEmpty(username)) { throw new BadCredentialsException("InternalAuthenticationProvider: Empty Username"); } if (Strings.isNullOrEmpty(password)) { throw new BadCredentialsException("InternalAuthenticationProvider: Empty Password"); } assertUserNotLocked(username); User user = userProvisioning.getByUsernameWithPassword(username); if (user == null) { throw new BadCredentialsException("The user with the username '" + username + "' doesn't exist!"); } if (user.isActive() != Boolean.TRUE) { throw new DisabledException("The user with the username '" + username + "' is disabled!"); } if (!bCryptPasswordEncoder.matches(password, user.getPassword())) { if (shaPasswordEncoder.isPasswordValid(user.getPassword(), password, user.getId())) { User replaceUser = new User.Builder(user).setPassword(password).build(); userProvisioning.replace(user.getId(), replaceUser); } else { throw new BadCredentialsException("Bad credentials"); } } User authUser = new User.Builder(username).setId(user.getId()).build(); List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (Role role : user.getRoles()) { grantedAuthorities.add(new SimpleGrantedAuthority(role.getValue())); } return new InternalAuthentication(authUser, password, grantedAuthorities); }
Source:
private VoltTable constructFragmentResultsTable() { ColumnInfo[] result_columns = new ColumnInfo[10]; int ii = 0; result_columns[ii++] = new ColumnInfo(VoltSystemProcedure.CNAME_HOST_ID, VoltSystemProcedure.CTYPE_ID); result_columns[ii++] = new ColumnInfo("HOSTNAME", VoltType.STRING); result_columns[ii++] = new ColumnInfo("PATH", VoltType.STRING); result_columns[ii++] = new ColumnInfo("PATHTYPE", VoltType.STRING); result_columns[ii++] = new ColumnInfo("NONCE", VoltType.STRING); result_columns[ii++] = new ColumnInfo("NAME", VoltType.STRING); result_columns[ii++] = new ColumnInfo("SIZE", VoltType.BIGINT); result_columns[ii++] = new ColumnInfo("DELETED", VoltType.STRING); result_columns[ii++] = new ColumnInfo("RESULT", VoltType.STRING); result_columns[ii++] = new ColumnInfo("ERR_MSG", VoltType.STRING); return new VoltTable(result_columns); }

Target:
private VoltTable constructFragmentResultsTable() { return new VoltTable(new ColumnInfo( VoltSystemProcedure.CNAME_HOST_ID, VoltSystemProcedure.CTYPE_ID) , new ColumnInfo("HOSTNAME", VoltType.STRING) , new ColumnInfo("PATH", VoltType.STRING) , new ColumnInfo("PATHTYPE", VoltType.STRING) , new ColumnInfo("NONCE", VoltType.STRING) , new ColumnInfo("NAME", VoltType.STRING) , new ColumnInfo("SIZE", VoltType.BIGINT) , new ColumnInfo("DELETED", VoltType.STRING) , new ColumnInfo("RESULT", VoltType.STRING) , new ColumnInfo("ERR_MSG", VoltType.STRING)); }
Source:
public Map<String, JsonElement> allFlags(LDUser user) { if (isOffline()) { logger.warn("allFlags() was called when client is in offline mode!"); } if (!initialized()) { logger.warn("allFlags() was called before Client has been initialized! Returning null."); return null; } if (user == null || user.getKey() == null) { logger.warn("allFlags() was called with null user or null user key! returning null"); return null; } Map<String, FeatureFlag> flags = this.config.featureStore.all(); Map<String, JsonElement> result = new HashMap<>(); for (Map.Entry<String, FeatureFlag> entry : flags.entrySet()) { try { JsonElement evalResult = entry.getValue().evaluate(user, config.featureStore).getValue(); result.put(entry.getKey(), evalResult); } catch (EvaluationException e) { logger.error("Exception caught when evaluating all flags:", e); } } return result; }

Target:
public Map<String, JsonElement> allFlags(LDUser user) { if (isOffline()) { logger.debug("allFlags() was called when client is in offline mode."); } if (!initialized()) { logger.warn("allFlags() was called before Client has been initialized! Returning null."); return null; } if (user == null || user.getKey() == null) { logger.warn("allFlags() was called with null user or null user key! returning null"); return null; } Map<String, FeatureFlag> flags = this.config.featureStore.all(); Map<String, JsonElement> result = new HashMap<>(); for (Map.Entry<String, FeatureFlag> entry : flags.entrySet()) { try { JsonElement evalResult = entry.getValue().evaluate(user, config.featureStore).getValue(); result.put(entry.getKey(), evalResult); } catch (EvaluationException e) { logger.error("Exception caught when evaluating all flags:", e); } } return result; }
Source:
@Test public void testBigDecimalLiteral() { final RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT); final RexBuilder builder = new RexBuilder(typeFactory); final RexNode literal1 = builder.makeExactLiteral(new BigDecimal("25")); assertThat(((RexLiteral) literal1).getValueAs(BigDecimal.class) .toString(), is("25")); final RexNode literal2 = builder.makeExactLiteral(new BigDecimal("9.9")); assertThat(((RexLiteral) literal2).getValueAs(BigDecimal.class) .toString(), is("9.9")); final RexNode literal3 = builder.makeExactLiteral(new BigDecimal("0")); assertThat(((RexLiteral) literal3).getValueAs(BigDecimal.class) .toString(), is("0")); final RexNode literal4 = builder.makeExactLiteral(new BigDecimal("-75.5")); assertThat(((RexLiteral) literal4).getValueAs(BigDecimal.class) .toString(), is("-75.5")); final RexNode literal5 = builder.makeExactLiteral(new BigDecimal("10000000")); assertThat(((RexLiteral) literal5).getValueAs(BigDecimal.class) .toString(), is("10000000")); final RexNode literal6 = builder.makeExactLiteral(new BigDecimal("100000.111111111111111111")); assertThat(((RexLiteral) literal6).getValueAs(BigDecimal.class) .toString(), is("100000.111111111111111111")); final RexNode literal7 = builder.makeExactLiteral(new BigDecimal("73786976294838206464")); assertThat(((RexLiteral) literal7).getValueAs(BigDecimal.class) .toString(), is("73786976294838206464")); }

Target:
@Test public void testBigDecimalLiteral() { final RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT); final RexBuilder builder = new RexBuilder(typeFactory); assertBigDecimalLiteral(builder, "25"); assertBigDecimalLiteral(builder, "9.9"); assertBigDecimalLiteral(builder, "0"); assertBigDecimalLiteral(builder, "-75.5"); assertBigDecimalLiteral(builder, "10000000"); assertBigDecimalLiteral(builder, "100000.111111111111111111"); assertBigDecimalLiteral(builder, "-100000.111111111111111111"); assertBigDecimalLiteral(builder, "73786976294838206464"); assertBigDecimalLiteral(builder, "-73786976294838206464"); }
Source:
private void help(CommandSender sender) { sender.sendMessage(Prism.messenger.playerHeaderMsg(ChatColor.GOLD + "--- Flags Help ---")); sender.sendMessage(Prism.messenger.playerMsg( ChatColor.GRAY + "Flags control how Prism applies a rollback/restore, or formats lookup results.")); sender.sendMessage(Prism.messenger .playerMsg(ChatColor.GRAY + "Use them after parameters, like /pr l p:[player] -extended")); for (final Flag flag : Flag.values()) { sender.sendMessage(Prism.messenger.playerMsg(ChatColor.LIGHT_PURPLE + flag.getUsage().replace("_", "-") + ChatColor.WHITE + " " + flag.getDescription())); } }

Target:
private void help(CommandSender sender) { sender.sendMessage(Prism.messenger.playerHeaderMsg(ChatColor.GOLD + "--- Flags Help ---")); sender.sendMessage(Prism.messenger.playerMsg( ChatColor.GRAY + "Flags control how Prism applies a rollback/restore, or formats lookup results.")); sender.sendMessage(Prism.messenger .playerMsg(ChatColor.GRAY + "Use them after parameters, like /pr l p:<player> -extended")); for (final Flag flag : Flag.values()) { sender.sendMessage(Prism.messenger.playerMsg(ChatColor.LIGHT_PURPLE + flag.getUsage().replace("_", "-") + ChatColor.WHITE + " " + flag.getDescription())); } }
Source:
public void testListDList() { DList<Integer> d = listDList(List.range(0, 1000)); assertThat(d.toJavaList(), is(d.run().toJavaList())); }

Target:
public void testListDList() { DList<Integer> d = listDList(List.range(0, 1000)); assertThat(d.toJavaList(), is(List.range(0, 1000).toJavaList())); }
Source:
@Override public StaticInjection getStaticInjection(Class<?> injectedClass) { try { StaticInjection result = GeneratedAdapters.initStaticInjection(injectedClass); if (result == null) { result = ReflectiveStaticInjection.create(injectedClass); } return result; } catch (RuntimeException e) { logNotFound("Static injection", injectedClass.getName(), e); throw e; } }

Target:
@Override public StaticInjection getStaticInjection(Class<?> injectedClass) { StaticInjection result = GeneratedAdapters.initStaticInjection(injectedClass); if (result == null) { result = ReflectiveStaticInjection.create(injectedClass); } return result; }
Source:
public void testValidResources() { cleanUp(); final Resource[] resources = new Resource[]{new ClassPathResource(validName1)}; NeverFailAutoDeploymentStrategy deploymentStrategy = new NeverFailAutoDeploymentStrategy(); deploymentStrategy.deployResources(nameHint, resources, repositoryService); assertEquals(1, repositoryService.createDeploymentQuery().count()); cleanUp(); }

Target:
public void testValidResources() { final Resource[] resources = new Resource[]{new ClassPathResource(validName1)}; NeverFailAutoDeploymentStrategy deploymentStrategy = new NeverFailAutoDeploymentStrategy(); deploymentStrategy.deployResources(nameHint, resources, repositoryService); assertEquals(1, repositoryService.createDeploymentQuery().count()); }
Source:
private boolean evaluateDeterministicFilterFunctionWithConstantInputs(FilterFunction function) { int[] inputs = function.getInputChannels(); Block[] blocks = new Block[inputs.length]; for (int i = 0; i < inputs.length; i++) { int columnIndex = filterFunctionInputMapping.get(inputs[i]); Object constantValue = constantValues[columnIndex]; blocks[i] = RunLengthEncodedBlock.create(columnTypes.get(columnIndex), constantValue == NULL_MARKER ? null : constantValue, 1); } int[] positions = new int[] {0}; initializeTmpErrors(1); int positionCount = function.filter(new Page(blocks), positions, 1, tmpErrors); if (tmpErrors[0] != null) { this.constantFilterError = tmpErrors[0]; } return positionCount == 1; }

Target:
private boolean evaluateDeterministicFilterFunctionWithConstantInputs(FilterFunction function) { int[] inputs = function.getInputChannels(); Block[] blocks = new Block[inputs.length]; for (int i = 0; i < inputs.length; i++) { int columnIndex = filterFunctionInputMapping.get(inputs[i]); Object constantValue = constantValues[columnIndex]; blocks[i] = RunLengthEncodedBlock.create(columnTypes.get(columnIndex), constantValue == NULL_MARKER ? null : constantValue, 1); } initializeTmpErrors(1); int positionCount = function.filter(new Page(blocks), new int[] {0}, 1, tmpErrors); if (tmpErrors[0] != null) { constantFilterError = tmpErrors[0]; } return positionCount == 1; }
Source:
public List<HostInventory> getConnectedHostForOperation(PrimaryStorageInventory pri, int startPage, int pageLimit) { if (pri.getAttachedClusterUuids().isEmpty()) { throw new OperationFailureException(operr("cannot find a Connected host to execute command for nfs primary storage[uuid:%s]", pri.getUuid())); } String sql = "select h from HostVO h " + "where h.state = :state and h.status = :connectionState and h.clusterUuid in (:clusterUuids) " + "and h.uuid not in (select ref.hostUuid from PrimaryStorageHostRefVO ref " + "where ref.primaryStorageUuid = :psUuid and ref.hostUuid = h.uuid and ref.status = :status)"; TypedQuery<HostVO> q = dbf.getEntityManager().createQuery(sql, HostVO.class); q.setParameter("state", HostState.Enabled); q.setParameter("connectionState", HostStatus.Connected); q.setParameter("clusterUuids", pri.getAttachedClusterUuids()); q.setParameter("psUuid", pri.getUuid()); q.setParameter("status", PrimaryStorageHostStatus.Disconnected); q.setFirstResult(startPage * pageLimit); if (pageLimit > 0){ q.setMaxResults(pageLimit); } List<HostVO> ret = q.getResultList(); if (ret.isEmpty() && q.getFirstResult() == 0) { throw new OperationFailureException(operr("cannot find a Connected host-NFS connection to execute command for nfs primary storage[uuid:%s]", pri.getUuid())); } else { Collections.shuffle(ret); return HostInventory.valueOf(ret); } }

Target:
public List<HostInventory> getConnectedHostForOperation(PrimaryStorageInventory pri, int startPage, int pageLimit) { if (pri.getAttachedClusterUuids().isEmpty()) { throw new OperationFailureException(operr("cannot find a Connected host to execute command for nfs primary storage[uuid:%s]", pri.getUuid())); } String sql = "select h from HostVO h " + "where h.state = :state and h.status = :connectionState and h.clusterUuid in (:clusterUuids) " + "and h.uuid not in (select ref.hostUuid from PrimaryStorageHostRefVO ref " + "where ref.primaryStorageUuid = :psUuid and ref.hostUuid = h.uuid and ref.status = :status)"; TypedQuery<HostVO> q = dbf.getEntityManager().createQuery(sql, HostVO.class); q.setParameter("state", HostState.Enabled); q.setParameter("connectionState", HostStatus.Connected); q.setParameter("clusterUuids", pri.getAttachedClusterUuids()); q.setParameter("psUuid", pri.getUuid()); q.setParameter("status", PrimaryStorageHostStatus.Disconnected); q.setFirstResult(startPage * pageLimit); if (pageLimit > 0){ q.setMaxResults(pageLimit); } List<HostVO> ret = q.getResultList(); if (ret.isEmpty() && startPage == 0) { throw new OperationFailureException(operr("cannot find a Connected host-NFS connection to execute command for nfs primary storage[uuid:%s]", pri.getUuid())); } else { Collections.shuffle(ret); return HostInventory.valueOf(ret); } }
Source:
private void populateBestMatchingMilestones(String querySentence) { bestMatchingMilestones.clear(); addMatchingMilestones(bestMatchingMilestones, getRemainingBestMatchesToLimit(), getSelectableMilestones(allMilestones)); if (isMilestonesSizeBelowLimit(bestMatchingMilestones, BEST_MATCHING_LIMIT)) { addPartiallyMatchingMilestones(bestMatchingMilestones, getRemainingBestMatchesToLimit(), querySentence, getSelectableMilestones(allMilestones)); } if (isMilestonesSizeBelowLimit(bestMatchingMilestones, BEST_MATCHING_LIMIT)) { addLikelyUnmatchedMilestones(bestMatchingMilestones, getRemainingBestMatchesToLimit(), getSelectableMilestones(allMilestones)); } }

Target:
private void populateBestMatchingMilestones(String querySentence) { bestMatchingMilestones.clear(); List<PickerMilestone> selectableMilestones = PickerMilestone.getSelectableMilestones(allMilestones); addMatchingMilestones(bestMatchingMilestones, getRemainingBestMatchesToLimit(), selectableMilestones); if (isMilestonesSizeBelowLimit(bestMatchingMilestones, BEST_MATCHING_LIMIT)) { addPartiallyMatchingMilestones(bestMatchingMilestones, getRemainingBestMatchesToLimit(), querySentence, selectableMilestones); } if (isMilestonesSizeBelowLimit(bestMatchingMilestones, BEST_MATCHING_LIMIT)) { addLikelyUnmatchedMilestones(bestMatchingMilestones, getRemainingBestMatchesToLimit(), selectableMilestones); } }