auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public int hashCode() { <END> int result = address != null ? address.hashCode() : 0; result = 31 * result + (href != null ? href.hashCode() : 0); result = 31 * result + (adjustments != null ? adjustments.hashCode() : 0); result = 31 * result + (invoices != null ? invoices.hashCode() : 0); result = 31 * result + (subscriptions != null ? subscriptions.hashCode() : 0); result = 31 * result + (transactions != null ? transactions.hashCode() : 0); result = 31 * result + (accountCode != null ? accountCode.hashCode() : 0); result = 31 * result + (state != null ? state.hashCode() : 0); result = 31 * result + (username != null ? username.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (firstName != null ? firstName.hashCode() : 0); result = 31 * result + (lastName != null ? lastName.hashCode() : 0); result = 31 * result + (companyName != null ? companyName.hashCode() : 0); result = 31 * result + (acceptLanguage != null ? acceptLanguage.hashCode() : 0); result = 31 * result + (hostedLoginToken != null ? hostedLoginToken.hashCode() : 0); result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0); result = 31 * result + (billingInfo != null ? billingInfo.hashCode() : 0); return result; }</code><technical_language>rely hashCode for equals (because of complex object types, DateTime)</technical_language>

Target:
public int hashCode() { return Objects.hashCode( address, href, adjustments, invoices, subscriptions, transactions, accountCode, state, username, email, firstName, lastName, companyName, acceptLanguage, hostedLoginToken, createdAt, billingInfo ); }
Source:
<code>private ResponseEntity<String> executeQuery(String query) throws QStoreStorageException { List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = buildRestHeader(messageConverters, restTemplate); HttpEntity<String> request = new HttpEntity<String>(query, headers); try { String url = getQStoreQueryURL(); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParam("class", RELATION_EVENT); return restTemplate.postForEntity(builder.build().encode().toUri(), request, String.class); } catch (RestClientException e) { <START> throw new QStoreStorageException(e); <END> } }</code><technical_language>here: storage exception</technical_language>

Target:
private ResponseEntity<String> executeQuery(String query) throws AsyncExecutionException { List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = buildRestHeader(messageConverters, restTemplate); headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML)); HttpEntity<String> request = new HttpEntity<String>(query, headers); try { String url = getQStoreQueryURL(); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParam("class", RELATION_EVENT); return restTemplate.postForEntity(builder.build().encode().toUri(), request, String.class); } catch (RestClientException e) { throw new AsyncExecutionException(e); } }
Source:
<code>public void testGetTableDescriptor_nullTable() throws Exception { <START> if (SharedTestEnvRule.getInstance().isBigtable()) { <END> AsyncAdmin asyncAdmin = getAsyncConnection().getAdmin(); assertEquals(null, asyncAdmin.getDescriptor(null).get()); } }</code><technical_language>cleaner assumptions: <LINK_0> Assume.assumeTrue(SharedTestEnvRule.getInstance().isBigtable())</technical_language>

Target:
public void testGetTableDescriptor_nullTable() throws Exception { Assume.assumeTrue("HBase asyncAdmin.getDescriptor(null) seems to break the mini-cluster", SharedTestEnvRule.getInstance().isBigtable()); AsyncAdmin asyncAdmin = getAsyncConnection().getAdmin(); assertEquals(null, asyncAdmin.getDescriptor(null).get()); }
Source:
<code>private List<HasMetadata> unmarshalToolObjects(Tool k8sTool, String toolLocalContent) throws DevfileRecipeFormatException { try { return unmarshal(toolLocalContent); } catch (DevfileRecipeFormatException e) { throw new DevfileRecipeFormatException( format( "Error occurred during parsing list from file %s for tool '%s': %s", <START> k8sTool.getLocal(), k8sTool.getName(), e.getMessage())); <END> } }</code><technical_language>do lose here</technical_language>

Target:
private List<HasMetadata> unmarshalToolObjects(Tool k8sTool, String toolLocalContent) throws DevfileRecipeFormatException { try { return unmarshal(toolLocalContent); } catch (DevfileRecipeFormatException e) { throw new DevfileRecipeFormatException( format( "Error occurred during parsing list from file %s for tool '%s': %s", k8sTool.getLocal(), k8sTool.getName(), e.getMessage()), e); } }
Source:
<code>public Long getUuid() { <START> return new Long(getLocalId()); <END> }</code><technical_language>Long.valueOf() instead of new Long() - for performance reasons</technical_language>

Target:
public Long getUuid() { return Long.valueOf(getLocalId()); }
Source:
<code>public Subject authenticate() { KerberosConfiguration configuration = new KerberosConfiguration(); <START> Set<Principal> principals = ImmutableSet.of(new KerberosPrincipal(principal)); <END> Subject subject = new Subject(false, principals, ImmutableSet.of(), ImmutableSet.of()); try { LoginContext loginContext = new LoginContext("", subject, null, configuration); loginContext.login(); return loginContext.getSubject(); } catch (LoginException e) { throw Throwables.propagate(e); } }</code><technical_language>compute principals in constructor store in field</technical_language>

Target:
public Subject authenticate() { Subject subject = new Subject(false, principalsSet, emptySet(), emptySet()); try { LoginContext loginContext = new LoginContext("", subject, null, kerberosConfiguration); loginContext.login(); return loginContext.getSubject(); } catch (LoginException e) { throw Throwables.propagate(e); } }
Source:
<code><START> HandshakeConfig(HttpMessage httpMessage, boolean followRedirects, boolean useSessionState){ <END> this.httpMessage = httpMessage; this.followRedirects = followRedirects; this.useSessionState = useSessionState; }</code><technical_language>public</technical_language>

Target:
public HandshakeConfig(HttpMessage httpMessage, boolean followRedirects, boolean useSessionState){ this.httpMessage = httpMessage; this.followRedirects = followRedirects; this.useSessionState = useSessionState; }
Source:
<code>private void display() throws Failure { final PrintWriter stdout = toPrintWriter(out); try { for (final Project p : db.projects().all()) { if (p.getNameKey().equals(wildProject)) { continue; } final ProjectState e = projectCache.get(p.getNameKey()); if (e != null && e.controlFor(currentUser).isVisible()) { stdout.print(p.getName()); if (showBranch != null) { RevId revId = getRevIdForBranch(p.getNameKey(), showBranch); if (revId != null) { <START> stdout.print("\t" + revId.get()); <END> } } stdout.println(); } } } catch (OrmException e) { throw new Failure(1, "fatal: database error", e); } finally { stdout.flush(); } }</code><technical_language>posing a question, sense print revision first? revision is fixed-width in size. if print first, output a nice table feel it. if print last, skewed place. If do print revision first, a single space instead of a tab? easy split project name, horizontal width run command manually</technical_language>

Target:
private void display() throws Failure { final PrintWriter stdout = toPrintWriter(out); try { for (final Project p : db.projects().all()) { if (p.getNameKey().equals(wildProject)) { continue; } final ProjectState e = projectCache.get(p.getNameKey()); if (e != null && e.controlFor(currentUser).isVisible()) { if (showBranch != null) { ObjectId id = getObjectIdForBranch(p.getNameKey(), showBranch); if (id != null) { stdout.print(ObjectId.toString(id) + " "); } } stdout.print(p.getName()); stdout.println(); } } } catch (OrmException e) { throw new Failure(1, "fatal: database error", e); } finally { stdout.flush(); } }
Source:
<code>public Object getMetadata() { Object[] ports = _state.snapshot().keySet().toArray(); Integer[] p = new Integer[ports.length]; for (int i = 0; i < ports.length; i++) { p[i] = Integer.parseInt((String) ports[i]); } <START> return PersistentVector.create((Object[]) p); <END> }</code><technical_language>do explicitly downcast p</technical_language>

Target:
public Object getMetadata() { Set<Integer> ports = _taskAssignments.getAssignedPorts(); if (ports == null) { return null; } return PersistentVector.create(ports); }
Source:
<code>public DiagnosticsElement getDiagnostics(String diagnosticsElementName) { if (!hasDiagnostics(diagnosticsElementName)) { throw new NoSuchElementException(diagnosticsElementName); } JsonNode node = getJson().get(diagnosticsElementName); boolean isHealthy = false; String message = null; if (node.get(HEALTHY) != null) { isHealthy = node.get(HEALTHY).asBoolean(); } <START> if (node.get(MESSAGE) != null) { <END> message = node.get(MESSAGE).asText(); } return new DiagnosticsElement(diagnosticsElementName, isHealthy, message); }</code><technical_language>if message is a required field. "message": null in JSON response? In this case a NullNode parsing, I think. if this happen in reality, though, I depends health check serialization is configured</technical_language>

Target:
public DiagnosticsElement getDiagnostics(String diagnosticsElementName) { if (!hasDiagnostics(diagnosticsElementName)) { throw new NoSuchElementException(diagnosticsElementName); } JsonNode node = getJson().get(diagnosticsElementName); boolean isHealthy = false; String message = null; if (node.get(HEALTHY) != null) { isHealthy = node.get(HEALTHY).asBoolean(); } if (node.get(MESSAGE) != null) { message = node.get(MESSAGE).asText(); } else { message = new String("Message Unavailable"); } return new DiagnosticsElement(diagnosticsElementName, isHealthy, message); }
Source:
<code>protected void clientInit() { CommonHelper.assertNotBlank("fields", getConfiguration().getFields()); configuration.setApi(FacebookApi.instance()); configuration.setProfileDefinition(new FacebookProfileDefinition()); configuration.setHasBeenCancelledFactory(ctx -> { final Optional<String> error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); final Optional<String> errorReason = ctx.getRequestParameter(OAuthCredentialsException.ERROR_REASON); <START> if ("access_denied".equals(error.orElse(null)) && "user_denied".equals(errorReason.orElse(null))) { <END> return true; } else { return false; } }); configuration.setWithState(true); defaultProfileCreator(new FacebookProfileCreator(configuration, this)); super.clientInit(); }</code><technical_language>prefer map and/or flatMap nulls</technical_language>

Target:
protected void clientInit() { CommonHelper.assertNotBlank("fields", getConfiguration().getFields()); configuration.setApi(FacebookApi.instance()); configuration.setProfileDefinition(new FacebookProfileDefinition()); configuration.setHasBeenCancelledFactory(ctx -> { final Optional<String> error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); final Optional<String> errorReason = ctx.getRequestParameter(OAuthCredentialsException.ERROR_REASON); return error.map(e -> "access_denied".equals(e)).orElse(false) && errorReason.map(e -> "user_denied".equals(e)).orElse(false); }); configuration.setWithState(true); defaultProfileCreator(new FacebookProfileCreator(configuration, this)); super.clientInit(); }
Source:
<code>public void processCommandInsert(JsonObject request, WebSocketSession session) { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); final String deviceId = gson.fromJson(request.get(DEVICE_ID), String.class); final DeviceCommandWrapper deviceCommand = gson .fromJson(request.getAsJsonObject(COMMAND), DeviceCommandWrapper.class); logger.debug("command/insert action for {}, Session ", deviceId, session.getId()); Set<DeviceVO> devices = new HashSet<>(); if (deviceId == null) { throw new HiveException(Messages.DEVICE_ID_REQUIRED, SC_BAD_REQUEST); } DeviceVO deviceVO = deviceService.findByIdWithPermissionsCheck(deviceId, principal); if (deviceVO == null) { throw new HiveException(String.format(Messages.DEVICE_NOT_FOUND, deviceId), SC_NOT_FOUND); } devices.add(deviceVO); <START> if (devices.isEmpty()) { <END> throw new HiveException(String.format(Messages.DEVICE_NOT_FOUND, deviceId), SC_NOT_FOUND); } if (deviceCommand == null) { throw new HiveException(Messages.EMPTY_COMMAND, SC_BAD_REQUEST); } final UserVO user = principal.getUser(); WebSocketResponse response = new WebSocketResponse(); for (DeviceVO device : devices) { commandService.insert(deviceCommand, device, user) .thenAccept(command -> { response.addValue(COMMAND, command, COMMAND_TO_CLIENT); clientHandler.sendMessage(request, response, session); }) .exceptionally(ex -> { logger.warn("Unable to insert notification.", ex); throw new HiveException(Messages.INTERNAL_SERVER_ERROR, SC_INTERNAL_SERVER_ERROR); }); } }</code><technical_language>this point devices empty, this check removed</technical_language>

Target:
public void processCommandInsert(JsonObject request, WebSocketSession session) { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); final String deviceId = gson.fromJson(request.get(DEVICE_ID), String.class); final DeviceCommandWrapper deviceCommand = gson .fromJson(request.getAsJsonObject(COMMAND), DeviceCommandWrapper.class); logger.debug("command/insert action for {}, Session ", deviceId, session.getId()); Set<DeviceVO> devices = new HashSet<>(); if (deviceId == null) { throw new HiveException(Messages.DEVICE_ID_REQUIRED, SC_BAD_REQUEST); } DeviceVO deviceVO = deviceService.findByIdWithPermissionsCheck(deviceId, principal); if (deviceVO == null) { throw new HiveException(String.format(Messages.DEVICE_NOT_FOUND, deviceId), SC_NOT_FOUND); } devices.add(deviceVO); if (deviceCommand == null) { throw new HiveException(Messages.EMPTY_COMMAND, SC_BAD_REQUEST); } final UserVO user = principal.getUser(); WebSocketResponse response = new WebSocketResponse(); for (DeviceVO device : devices) { commandService.insert(deviceCommand, device, user) .thenAccept(command -> { response.addValue(COMMAND, command, COMMAND_TO_CLIENT); clientHandler.sendMessage(request, response, session); }) .exceptionally(ex -> { logger.warn("Unable to insert notification.", ex); throw new HiveException(Messages.INTERNAL_SERVER_ERROR, SC_INTERNAL_SERVER_ERROR); }); } }
Source:
<code>public void testEmptyCreation() { String regex = ""; <START> RestResourceConcatenator rc = new RestResourceConcatenator(regex); <END> fail("An empty string should not produce " + rc.toString()); }</code><technical_language>Notice constructor is unable advertise is on. avoid work in constructors</technical_language>

Target:
public void testEmptyCreation() { thrown.expect(OseeArgumentException.class); thrown.expectMessage("xmlTag cannot be empty"); String regex = ""; RestResourceConcatenator rc = new RestResourceConcatenator(); rc.initialize(regex); fail("An empty string should not produce " + rc.toString()); }
Source:
<code><START> public List<Object> getEntityClassIds() <END> { return dataService.findAll(EntityTypeMetadata.ENTITY_TYPE_META_DATA).map(Entity::getIdValue).collect(toList()); }</code><technical_language>switch in createPermissions function is obsolete, is called else AUTHORITY_ENTITY_PREFIX</technical_language>

Target:
public List<Object> getEntityClassIds() { return getEntityTypes().map(EntityType::getId).collect(toList()); }
Source:
<code>private static com.vividsolutions.jts.geom.Geometry readGeoFromWkt(final String wkt) throws CatalogTransformerException { <START> WKTReader reader = new WKTReader(); <END> try { return reader.read(wkt); } catch (ParseException e) { throw new CatalogTransformerException("Unable to parse WKT to Geometry.", e); } }</code><technical_language>ThreadLocal avoid instantiate this call</technical_language>

Target:
private static com.vividsolutions.jts.geom.Geometry readGeoFromWkt(final String wkt) throws CatalogTransformerException { try { return WKT_READER_THREAD_LOCAL.get().read(wkt); } catch (ParseException e) { throw new CatalogTransformerException("Unable to parse WKT to Geometry.", e); } }
Source:
<code>protected final EntityClass<E> entityClass() { if (entityClass == null) { @SuppressWarnings("unchecked") final Class<E> cast = <START> (Class<E>)ENTITY.getArgumentIn(getClass()); <END> entityClass = getModelClass(cast); } return entityClass; }</code><technical_language>Please add a space (Class<E>)</technical_language>

Target:
protected final EntityClass<E> entityClass() { if (entityClass == null) { @SuppressWarnings("unchecked") Class<E> cast = (Class<E>) ENTITY.getArgumentIn(getClass()); entityClass = getModelClass(cast); } return entityClass; }
Source:
<code>protected void refreshFile(IFile file, IProgressMonitor monitor) throws CoreException { <START> if (file == null) { return; } <END> class RefreshFileOperation extends DocumentProviderOperation implements ISchedulingRuleProvider { @Override protected void execute(IProgressMonitor m) throws CoreException { try { file.refreshLocal(IResource.DEPTH_INFINITE, m); } catch (OperationCanceledException x) { } } @Override public ISchedulingRule getSchedulingRule() { return getRefreshRule(file); } } executeOperation(new RefreshFileOperation(), monitor); }</code><technical_language>'file' is allowed 'null'. Please remove code</technical_language>

Target:
protected void refreshFile(IFile file, IProgressMonitor monitor) throws CoreException { class RefreshFileOperation extends DocumentProviderOperation implements ISchedulingRuleProvider { @Override protected void execute(IProgressMonitor m) throws CoreException { try { file.refreshLocal(IResource.DEPTH_INFINITE, m); } catch (OperationCanceledException x) { } } @Override public ISchedulingRule getSchedulingRule() { return getRefreshRule(file); } } executeOperation(new RefreshFileOperation(), monitor); }
Source:
<code>public void close() { context = null; <START> memSpace = null; <END> address = null; }</code><technical_language>close kill memspace? if want reopen key</technical_language>

Target:
public void close() { context = null; address = null; memSpace = null; }
Source:
<code>public boolean visit(MethodInvocation node) { if (isInflateMethod(node)) { this.viewVariableDeclarationFragment = (VariableDeclarationFragment) getFirstAncestorOrNull(node, VariableDeclarationFragment.class); if (viewVariableDeclarationFragment != null) { this.viewVariable = viewVariableDeclarationFragment.getName(); this.viewAssignmentStatement = getAncestor(viewVariableDeclarationFragment, VariableDeclarationStatement.class); } else { this.viewVariableAssignment = (Assignment) getFirstAncestorOrNull(node, Assignment.class); if (viewVariableAssignment != null) { <START> this.viewVariable = (SimpleName) viewVariableAssignment.getLeftHandSide(); <END> this.viewAssignmentStatement = getAncestor(viewVariableAssignment, ExpressionStatement.class); } } return DO_NOT_VISIT_SUBTREE; } return VISIT_SUBTREE; }</code><technical_language>unchecked cast. this is a SimpleName here</technical_language>

Target:
public boolean visit(MethodInvocation node) { if (isInflateMethod(node)) { ASTNode ancestor = getFirstAncestorOrNull(node, VariableDeclarationFragment.class, Assignment.class); if (ancestor instanceof VariableDeclarationFragment) { viewVariableDeclarationFragment = (VariableDeclarationFragment) ancestor; viewVariable = viewVariableDeclarationFragment.getName(); viewAssignmentStmt = getAncestorOrNull(viewVariableDeclarationFragment, VariableDeclarationStatement.class); if (viewAssignmentStmt == null) { resetData(); return VISIT_SUBTREE; } } else if (ancestor instanceof Assignment) { viewVariableAssignment = (Assignment) ancestor; ASTNode leftHandSideNode = viewVariableAssignment.getLeftHandSide(); if (leftHandSideNode.getNodeType() == SIMPLE_NAME) { viewVariable = (SimpleName) leftHandSideNode; } else { resetData(); return VISIT_SUBTREE; } viewAssignmentStmt = getAncestorOrNull(viewVariableAssignment, ExpressionStatement.class); } return DO_NOT_VISIT_SUBTREE; } return VISIT_SUBTREE; }
Source:
<code>public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { try { testExecutor.configure() .init(defaultArguments()); } catch (WebDriverException ex) { } JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions.build(), (JavascriptStateValidator) (driver, output, events) -> { <START> assertThat(jsDriver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); <END> }); }</code><technical_language>Hopefully, is understandable I confuse more. I JS tests, lots of people struggling them. is done though, some nitpicks fix</technical_language>

Target:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { testExecutor.configure().init(defaultArguments()); JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> { assertThat(driver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); }
Source:
<code>public void rewriteContext(CubeQueryContext cubeql) throws SemanticException { if (cubeql.getCube() != null && !cubeql.getCandidateFactTables() .isEmpty()) { Map<CandidateFact, Double> factWeightMap = new HashMap<CandidateFact, Double>(); for (CandidateFact fact : cubeql.getCandidateFactTables()) { factWeightMap.put(fact, fact.fact.weight()); } double minWeight = Collections.min(factWeightMap.values()); for (Iterator<CandidateFact> i = cubeql.getCandidateFactTables().iterator(); i.hasNext();) { CandidateFact fact = i.next(); if (factWeightMap.get(fact) > minWeight) { LOG.info("Not considering fact:" + fact + " from candidate fact tables as it has more fact weight:" + factWeightMap.get(fact) + " minimum:" + minWeight); <START> cubeql.addFactPruningMsgs(fact.fact, "The fact " + fact + " has more weight."); <END> i.remove(); } } } }</code><technical_language>mention weight of fact minimum weight</technical_language>

Target:
public void rewriteContext(CubeQueryContext cubeql) throws SemanticException { if (cubeql.getCube() != null && !cubeql.getCandidateFactTables() .isEmpty()) { Map<CandidateFact, Double> factWeightMap = new HashMap<CandidateFact, Double>(); for (CandidateFact fact : cubeql.getCandidateFactTables()) { factWeightMap.put(fact, fact.fact.weight()); } double minWeight = Collections.min(factWeightMap.values()); for (Iterator<CandidateFact> i = cubeql.getCandidateFactTables().iterator(); i.hasNext();) { CandidateFact fact = i.next(); if (factWeightMap.get(fact) > minWeight) { LOG.info("Not considering fact:" + fact + " from candidate fact tables as it has more fact weight:" + factWeightMap.get(fact) + " minimum:" + minWeight); cubeql.addFactPruningMsgs(fact.fact, new CandidateTablePruneCause( fact.fact.getName(), CubeTableCause.MORE_WEIGHT)); i.remove(); } } } }
Source:
<code><START> public Boolean getCachedAuthorizationResult(DSpaceObject dspaceObject, int action, EPerson eperson) { <END> if(mode == Mode.READ_ONLY) { return authorizedActionsCache.get(buildAuthorizedActionKey(dspaceObject, action, eperson)); } else { return false; } }</code><technical_language>For a moment I thought if need able cache authorizations for groups too. a context is bundled a request is run EPerson only. Following, caching authorizations for groups anyone</technical_language>

Target:
public Boolean getCachedAuthorizationResult(DSpaceObject dspaceObject, int action, EPerson eperson) { if(isReadOnly()) { return readOnlyCache.getCachedAuthorizationResult(dspaceObject, action, eperson); } else { return null; } }
Source:
<code>public void onBecomeStandbyFromBootstrap(Message message, NotificationContext context) { String partitionName = message.getPartitionName(); logger.info("Partition in resource is becoming STANDBY from BOOTSTRAP", partitionName, message.getResourceName()); if (clusterMapConfig.clustermapEnableStateModelListener) { partitionStateChangeListener.onPartitionBecomeStandbyFromBootstrap(partitionName); } try { replicaSyncUpManager.waitBootstrapCompleted(partitionName); } catch (InterruptedException | IllegalStateException e) { <START> logger.info("Bootstrap failed or was interrupted on partition {}", partitionName); <END> throw new StateTransitionException("Bootstrap failed or was interrupted", StateTransitionException.TransitionErrorCode.BootstrapFailure); } }</code><technical_language>log exceptions ERROR level</technical_language>

Target:
public void onBecomeStandbyFromBootstrap(Message message, NotificationContext context) { String partitionName = message.getPartitionName(); logger.info("Partition in resource is becoming STANDBY from BOOTSTRAP", partitionName, message.getResourceName()); if (clusterMapConfig.clustermapEnableStateModelListener) { partitionStateChangeListener.onPartitionBecomeStandbyFromBootstrap(partitionName); } try { replicaSyncUpManager.waitBootstrapCompleted(partitionName); } catch (InterruptedException e) { logger.error("Bootstrap was interrupted on partition {}", partitionName); throw new StateTransitionException("Bootstrap failed or was interrupted", StateTransitionException.TransitionErrorCode.BootstrapFailure); } catch (StateTransitionException e) { logger.error("Bootstrap didn't complete.", e); throw e; } }
Source:
<code><START> public long getTransactionTime() <END> { return execConfig.get(Long.class, "transaction_time", 0L); }</code><technical_language>This method return org.embulk.time.Timestamp. precision (sec/msec/usec/usec) is ambiguous</technical_language>

Target:
public Timestamp getTransactionTime() { return execConfig.get(Timestamp.class, "transaction_time", sessionCreatedTime); }
Source:
<code>private ZapNumberSpinner getDurationNumberSpinner() { if (durationNumberSpinner == null) { <START> durationNumberSpinner = new ZapNumberSpinner(0, 60, Integer.MAX_VALUE); <END> } return durationNumberSpinner; }</code><technical_language>default 0, consistent default of persisted option</technical_language>

Target:
private ZapNumberSpinner getDurationNumberSpinner() { if (durationNumberSpinner == null) { durationNumberSpinner = new ZapNumberSpinner(0, 0, Integer.MAX_VALUE); } return durationNumberSpinner; }
Source:
<code>private CompletableFuture<JobResult> unwrapJobResultException( CompletableFuture<JobResult> jobResult) { return jobResult.thenApply(result -> { if (result.isSuccess()) { return result; } Optional<SerializedThrowable> serializedThrowable = result.getSerializedThrowable(); if (result.getApplicationStatus() == ApplicationStatus.CANCELED) { throw new CompletionException( new JobCancellationException( result.getJobId(), "Job was cancelled.", serializedThrowable.orElse(null))); } if (serializedThrowable.isPresent()) { Throwable throwable; try { throwable = serializedThrowable .get() .deserializeError(application.getUserCodeClassLoader()); <START> } catch (ProgramInvocationException e) { <END> LOG.info("Application getUserCodeClassLoader failed.", e); throw new RuntimeException(e.getMessage()); } throw new CompletionException(throwable); } throw new RuntimeException("Job execution failed for unknown reason."); }); }</code><technical_language>do catch this now</technical_language>

Target:
private CompletableFuture<JobResult> unwrapJobResultException( CompletableFuture<JobResult> jobResult) { return jobResult.thenApply(result -> { if (result.isSuccess()) { return result; } Optional<SerializedThrowable> serializedThrowable = result.getSerializedThrowable(); if (result.getApplicationStatus() == ApplicationStatus.CANCELED) { throw new CompletionException( new JobCancellationException( result.getJobId(), "Job was cancelled.", serializedThrowable.orElse(null))); } if (serializedThrowable.isPresent()) { Throwable throwable = serializedThrowable .get() .deserializeError(application.getUserCodeClassLoader()); throw new CompletionException(throwable); } throw new RuntimeException("Job execution failed for unknown reason."); }); }
Source:
<code>protected CloseableIterator<Map<String, Object>> intermediateRowIterator() throws IOException { final Closer closer = Closer.create(); final InputEntity.CleanableFile resultFile = closer.register(source.fetch(temporaryDirectory, null)); FileInputStream inputStream = new FileInputStream(resultFile.file()); <START> JsonIterator<Map<String, Object>> jsonIterator = new JsonIterator<>(new TypeReference<Map<String, Object>>() <END> { }, inputStream, closer, objectMapper); return new CloseableIterator<Map<String, Object>>() { @Override public void close() throws IOException { jsonIterator.close(); } @Override public boolean hasNext() { return jsonIterator.hasNext(); } @Override public Map<String, Object> next() { return jsonIterator.next(); } }; }</code><technical_language>nit: this done in this PR, making JsonIterator a CloseableIterator? implements Iterator Closeable pretty simple</technical_language>

Target:
protected CloseableIterator<Map<String, Object>> intermediateRowIterator() throws IOException { final Closer closer = Closer.create(); final InputEntity.CleanableFile resultFile = closer.register(source.fetch(temporaryDirectory, null)); FileInputStream inputStream = new FileInputStream(resultFile.file()); JsonIterator<Map<String, Object>> jsonIterator = new JsonIterator<>(new TypeReference<Map<String, Object>>() { }, inputStream, closer, objectMapper); return jsonIterator; }
Source:
<code>public void process() { PerformanceMonitor.startActivity("rendering/outline"); outlineMaterial.setFloat("viewingDistance", renderingConfig.getViewDistance().getChunkDistance().x * 8.0f, true); outlineMaterial.setFloat("daylight", backdropProvider.getDaylight(), true); outlineMaterial.setFloat("tick", worldRenderer.getMillisecondsSinceRenderingStart(), true); outlineMaterial.setFloat("sunlightValueAtPlayerPos", worldRenderer.getTimeSmoothedMainLightIntensity(), true); cameraDir = activeCamera.getViewingDirection(); cameraPosition = activeCamera.getPosition(); outlineMaterial.setFloat("swimming", activeCamera.isUnderWater() ? 1.0f : 0.0f, true); outlineMaterial.setFloat3("cameraPosition", cameraPosition.x, cameraPosition.y, cameraPosition.z, true); outlineMaterial.setFloat3("cameraDirection", cameraDir.x, cameraDir.y, cameraDir.z, true); outlineMaterial.setFloat3("cameraParameters", activeCamera.getzNear(), activeCamera.getzFar(), 0.0f, true); sunDirection = backdropProvider.getSunDirection(false); outlineMaterial.setFloat3("sunVec", sunDirection.x, sunDirection.y, sunDirection.z, true); <START> outlineMaterial.setFloat("time", worldProvider.getTime().getDays(), true); <END> outlineMaterial.setFloat("texelWidth", 1.0f / sceneOpaqueFboWidth); outlineMaterial.setFloat("texelHeight", 1.0f / sceneOpaqueFboHeight); outlineMaterial.setFloat("pixelOffsetX", pixelOffsetX); outlineMaterial.setFloat("pixelOffsetY", pixelOffsetY); renderFullscreenQuad(); PerformanceMonitor.endActivity(); }</code><technical_language>Please double-check shader parameters set here: unnecessary</technical_language>

Target:
public void process() { PerformanceMonitor.startActivity("rendering/outline"); outlineMaterial.setFloat("texelWidth", 1.0f / sceneOpaqueFboWidth); outlineMaterial.setFloat("texelHeight", 1.0f / sceneOpaqueFboHeight); outlineMaterial.setFloat("pixelOffsetX", pixelOffsetX); outlineMaterial.setFloat("pixelOffsetY", pixelOffsetY); renderFullscreenQuad(); PerformanceMonitor.endActivity(); }
Source:
<code>public static void init(int memCheckInterval) { File f = new File(MEMINFO_FILE); memCheckEnabled = f.exists() && !f.isDirectory(); if (memCheckEnabled) { readMemoryInfoFile(); logger.info(String.format("Scheduled thread to read /proc/meminfo every %d seconds", memCheckInterval)); scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); <START> scheduledExecutorService.scheduleAtFixedRate(new MemoryInfoReader(), 0, memCheckInterval, TimeUnit.SECONDS); <END> } }</code><technical_language>Add else condition for non-Linux system print out memory reader enabled</technical_language>

Target:
public static void init(int memCheckInterval) { File f = new File(MEMINFO_FILE); memCheckEnabled = f.exists() && !f.isDirectory(); if (memCheckEnabled) { readMemoryInfoFile(); logger.info(String.format("Scheduled thread to read /proc/meminfo every %d seconds", memCheckInterval)); scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleAtFixedRate(new MemoryInfoReader(), 0, memCheckInterval, TimeUnit.SECONDS); } else { logger.info("Cannot find /proc/meminfo, memory check will be disabled"); } }
Source:
<code>protected void run() throws Exception { if (createBranch) { final ObjectId head = db.resolve(Constants.HEAD); if (head == null) throw die(CLIText.get().onBranchToBeBorn); } try (Git git = new Git(db)) { CheckoutCommand command = git.checkout(); if (paths.size() > 0) { command.setStartPoint(name); if (paths.size() == 1 && paths.get(0).equals(".")) { command.setAllPaths(true); } else { <START> for (String path : paths) command.addPath(path); <END> } } else { command.setCreateBranch(createBranch); command.setName(name); command.setForce(force); command.setOrphan(orphan); } try { String oldBranch = db.getBranch(); Ref ref = command.call(); if (ref == null) return; if (Repository.shortenRefName(ref.getName()).equals(oldBranch)) { outw.println(MessageFormat.format( CLIText.get().alreadyOnBranch, name)); return; } if (createBranch || orphan) outw.println(MessageFormat.format( CLIText.get().switchedToNewBranch, name)); else outw.println(MessageFormat.format( CLIText.get().switchedToBranch, Repository.shortenRefName(ref.getName()))); } catch (RefNotFoundException e) { outw.println(MessageFormat.format( CLIText.get().pathspecDidNotMatch, name)); } catch (RefAlreadyExistsException e) { throw die(MessageFormat.format(CLIText.get().branchAlreadyExists, name)); } catch (CheckoutConflictException e) { outw.println(CLIText.get().checkoutConflict); for (String path : e.getConflictingPaths()) outw.println(MessageFormat.format( CLIText.get().checkoutConflictPathLine, path)); } } }</code><technical_language>Add missing braces here</technical_language>

Target:
protected void run() throws Exception { if (createBranch) { final ObjectId head = db.resolve(Constants.HEAD); if (head == null) throw die(CLIText.get().onBranchToBeBorn); } try (Git git = new Git(db)) { CheckoutCommand command = git.checkout(); if (paths.size() > 0) { command.setStartPoint(name); if (paths.size() == 1 && paths.get(0).equals(".")) { command.setAllPaths(true); } else { for (String path : paths) { command.addPath(path); } } } else { command.setCreateBranch(createBranch); command.setName(name); command.setForce(force); command.setOrphan(orphan); } try { String oldBranch = db.getBranch(); Ref ref = command.call(); if (ref == null) return; if (Repository.shortenRefName(ref.getName()).equals(oldBranch)) { outw.println(MessageFormat.format( CLIText.get().alreadyOnBranch, name)); return; } if (createBranch || orphan) outw.println(MessageFormat.format( CLIText.get().switchedToNewBranch, name)); else outw.println(MessageFormat.format( CLIText.get().switchedToBranch, Repository.shortenRefName(ref.getName()))); } catch (RefNotFoundException e) { outw.println(MessageFormat.format( CLIText.get().pathspecDidNotMatch, name)); } catch (RefAlreadyExistsException e) { throw die(MessageFormat.format(CLIText.get().branchAlreadyExists, name)); } catch (CheckoutConflictException e) { outw.println(CLIText.get().checkoutConflict); for (String path : e.getConflictingPaths()) outw.println(MessageFormat.format( CLIText.get().checkoutConflictPathLine, path)); } } }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getName()); selectionMap = new LinkedHashMap<String, PlayerSelectionOption>(); <START> selectionMap.put("Widevine DASH Stream", new PlayerSelectionOption("BjN213NzE6H-9WPurASHfKFOtEak5x6b", OoyalaSkinOPTPlayerActivity.class)); <END> selectionMap.put("Widevine DASH Downloader", new PlayerSelectionOption("BjN213NzE6H-9WPurASHfKFOtEak5x6b", OfflineDownloadActivity.class)); selectionMap.put("Widevine DASH Offline Player", new PlayerSelectionOption("BjN213NzE6H-9WPurASHfKFOtEak5x6b", OfflineSkinPlayerActivity.class)); setContentView(R.layout.list_activity_layout); selectionAdapter = new ArrayAdapter<String>(this, R.layout.list_activity_list_item); for(String key : selectionMap.keySet()) { selectionAdapter.add(key); } selectionAdapter.notifyDataSetChanged(); ListView selectionListView = (ListView) findViewById(R.id.mainActivityListView); selectionListView.setAdapter(selectionAdapter); selectionListView.setOnItemClickListener(this); if(Build.VERSION_CODES.M == Build.VERSION.SDK_INT) { showDevOptionsDialog(); } }</code><technical_language>assuming new embed codes. changing (is related title of this PR)</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getName()); selectionMap = new LinkedHashMap<String, PlayerSelectionOption>(); selectionMap.put("Widevine DASH Stream", new PlayerSelectionOption("tyb2g2NjE64BuIcLQyS0wEccq4fr5Y03", OoyalaSkinOPTPlayerActivity.class)); selectionMap.put("Widevine DASH Downloader", new PlayerSelectionOption("tyb2g2NjE64BuIcLQyS0wEccq4fr5Y03", OfflineDownloadActivity.class)); selectionMap.put("Widevine DASH Offline Player", new PlayerSelectionOption("tyb2g2NjE64BuIcLQyS0wEccq4fr5Y03", OfflineSkinPlayerActivity.class)); setContentView(R.layout.list_activity_layout); selectionAdapter = new ArrayAdapter<String>(this, R.layout.list_activity_list_item); for(String key : selectionMap.keySet()) { selectionAdapter.add(key); } selectionAdapter.notifyDataSetChanged(); ListView selectionListView = (ListView) findViewById(R.id.mainActivityListView); selectionListView.setAdapter(selectionAdapter); selectionListView.setOnItemClickListener(this); if(Build.VERSION_CODES.M == Build.VERSION.SDK_INT) { showDevOptionsDialog(); } }
Source:
<code>Mono<Response<DetectLanguageResult>> detectLanguageWithResponse(String text, String countryHint, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); List<DetectLanguageInput> languageInputs = Collections.singletonList(new DetectLanguageInput("0", text, countryHint)); <START> return detectBatchLanguageWithResponse(languageInputs, null, context) <END> .map(Transforms::processSingleResponseErrorResult); }</code><technical_language>consider renaming this detectLanguageBatchWithResponse consistent</technical_language>

Target:
Mono<Response<DetectedLanguage>> detectLanguageWithResponse(String text, String countryHint, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); List<DetectLanguageInput> languageInputs = Collections.singletonList(new DetectLanguageInput("0", text, countryHint)); return detectLanguageBatchWithResponse(languageInputs, null, context) .map(response -> new SimpleResponse<>(response, Transforms.processSingleResponseErrorResult(response).getValue().getPrimaryLanguage())); }
Source:
<code>private void verifyAuthConfig(AuthConfig config, String username, String password, String email, String auth) { assertNotNull(config); JsonObject params = gsonBuilder.create().fromJson(new String(Base64.decodeBase64(config.toHeaderValue().getBytes())), JsonObject.class); <START> assertEquals(username, params.get("username").getAsString()); <END> assertEquals(password, params.get("password").getAsString()); if (email != null) { assertEquals(email, params.get("email").getAsString()); } if (auth != null) { assertEquals(auth, params.get("auth").getAsString()); } }</code><technical_language>switch AuthCofig constants if other PR is merged</technical_language>

Target:
private void verifyAuthConfig(AuthConfig config, String username, String password, String email, String auth) { assertNotNull(config); JsonObject params = gsonBuilder.create().fromJson(new String(Base64.decodeBase64(config.toHeaderValue().getBytes())), JsonObject.class); assertEquals(username, params.get(AuthConfig.AUTH_USERNAME).getAsString()); assertEquals(password, params.get(AuthConfig.AUTH_PASSWORD).getAsString()); if (email != null) { assertEquals(email, params.get(AuthConfig.AUTH_EMAIL).getAsString()); } if (auth != null) { assertEquals(auth, params.get(AuthConfig.AUTH_AUTH).getAsString()); } }
Source:
<code>private void endDiskRelatedActions(VM vm) { <START> EndActionOnAllImageGroups(); <END> VmHandler.updateDisksFromDb(vm); VmDeviceUtils.setVmDevices(vm.getStaticData()); }</code><technical_language>previously this run if vm == null. Is a situation disks end action vm == null? (sounds odd, need code worked did)</technical_language>

Target:
private void endDiskRelatedActions(VM vm) { VmHandler.updateDisksFromDb(vm); VmDeviceUtils.setVmDevices(vm.getStaticData()); }
Source:
<code><START> public boolean isPattern() { <END> return false; }</code><technical_language>final</technical_language>

Target:
public final boolean isPattern() { return false; }
Source:
<code>public StateItem[] getStateTable() { <START> return STATES; <END> }</code><technical_language>need cache this one, this method is called taht often. STATE_LIST.toArray() here</technical_language>

Target:
public StateItem[] getStateTable() { return STATE_LIST.toArray(new StateItem[STATE_LIST.size()]); }
Source:
<code>public void shareState(final Map<CodePath, Object> toSend) { final Map<DeviceUID, Map<CodePath, Object>> msg = Stream.of( new AbstractMap.SimpleImmutableEntry<>(deviceUID, toSend) ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); <START> final ByteArrayOutputStream bos = new ByteArrayOutputStream(); <END> ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(msg); out.flush(); final MqttMessage message = new MqttMessage(bos.toByteArray()); neighbors.forEach(publish(message)); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>try-with-resources</technical_language>

Target:
public void shareState(final Map<CodePath, Object> toSend) { final Map<DeviceUID, Map<CodePath, Object>> msg = Stream.of( new AbstractMap.SimpleImmutableEntry<>(deviceUID, toSend) ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { final ObjectOutput out = new ObjectOutputStream(bos); out.writeObject(msg); out.flush(); final MqttMessage message = new MqttMessage(bos.toByteArray()); neighbors.forEach(publish(message)); } catch (IOException e) { throw new IllegalStateException(e); } }
Source:
<code>private void updateRateIfNeeded() { if (rateUpdateLimiter.tryAcquire()) { <START> long updatedRate = getUpdatedRate(); <END> if (currentRate != updatedRate) { createRateLimiterAtomically(updatedRate); } } }</code><technical_language>nice add network overhead a request, if time fetch a new limit. a background scheduled executor fetches new limits, updates rate limiter a change</technical_language>

Target:
private void updateRateIfNeeded() { long updatedRate = getUpdatedRate(); if (currentRate != updatedRate) { createRateLimiterAtomically(updatedRate); } }
Source:
<code>private boolean activeSDsExist(List<LUNs> luns, String vgId, Guid poolId) { if (poolId == null) { return true; } Set<Guid> storageIDs = new HashSet<>(luns.size()); for (LUNs lun : luns) { if (lun.getStorageDomainId() != null && !lun.getvolume_group_id().equals(vgId)) { storageIDs.add(lun.getStorageDomainId()); } } if (storageIDs.isEmpty()) { return false; } String ids = StringUtils.join(storageIDs, ","); List<StoragePoolIsoMap> isomaps = DbFacade.getInstance().getStoragePoolIsoMapDao().getAllForStorages(ids, poolId); for (StoragePoolIsoMap isomap : isomaps) { <START> if (isomap.getStatus() != StorageDomainStatus.Maintenance) { <END> return true; } } return false; }</code><technical_language>need PreparingForMaintenance status. please add a method StorageDomainStatus called "isDeactivated()" condition there</technical_language>

Target:
private boolean activeSDsExist(List<LUNs> luns, String vgId, Guid poolId) { if (poolId == null) { return true; } Set<Guid> storageIDs = new HashSet<>(luns.size()); for (LUNs lun : luns) { if (lun.getStorageDomainId() != null && !lun.getvolume_group_id().equals(vgId)) { storageIDs.add(lun.getStorageDomainId()); } } if (storageIDs.isEmpty()) { return false; } String ids = StringUtils.join(storageIDs, ","); List<StoragePoolIsoMap> isomaps = DbFacade.getInstance().getStoragePoolIsoMapDao().getAllForStorages(ids, poolId); for (StoragePoolIsoMap isomap : isomaps) { if (!isomap.getStatus().isStorageDomainDeactivated()) { return true; } } return false; }
Source:
<code>private void validateProject(int type, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, PDECoreMessages.ManifestConsistencyChecker_builderTaskName, getWorkAmount(type)); if ((type & STRUCTURE) != 0) { validateProjectStructure(type, <START> SubMonitor.convert(monitor, <END> 1).newChild(1)); } if ((type & MANIFEST | EXTENSIONS) != 0) { IProject project = getProject(); IFile file = PDEProject.getPluginXml(project); if (!file.exists()) file = PDEProject.getFragmentXml(project); if (file.exists()) { validateFiles(file, type, monitor); } else if ((type & MANIFEST) != 0) { IFile manifestFile = PDEProject.getManifest(project); if (manifestFile.exists()) validateManifestFile(manifestFile, subMonitor.newChild(1)); } } if ((type & BUILD) != 0) { validateBuildProperties(subMonitor.newChild(1)); } }</code><technical_language>Bug: call SubMonitor.convert(...) fully consumes input monitor. pass monitor instance calls convert. This code crash some implementations of IProgressMonitor throw exceptions if try call beginTask them. Change this subMonitor.newChild(1)</technical_language>

Target:
private void validateProject(int type, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, PDECoreMessages.ManifestConsistencyChecker_builderTaskName, getWorkAmount(type)); if ((type & STRUCTURE) != 0) { validateProjectStructure(type, subMonitor.newChild(1)); } if ((type & MANIFEST | EXTENSIONS) != 0) { IProject project = getProject(); IFile file = PDEProject.getPluginXml(project); if (!file.exists()) file = PDEProject.getFragmentXml(project); if (file.exists()) { validateFiles(file, type, monitor); } else if ((type & MANIFEST) != 0) { IFile manifestFile = PDEProject.getManifest(project); if (manifestFile.exists()) validateManifestFile(manifestFile, subMonitor.newChild(1)); } } if ((type & BUILD) != 0) { validateBuildProperties(subMonitor.newChild(1)); } }
Source:
<code>protected Optional<String> getVal(ItemStack stack) { if (!stack.hasTagCompound()) { return Optional.empty(); } NBTTagCompound mainCompound = stack.getTagCompound(); if (!mainCompound.hasKey(NbtDataUtil.BLOCK_ENTITY_TAG, NbtDataUtil.TAG_COMPOUND)) { return Optional.empty(); } <START> String lock = mainCompound.getString("Lock"); <END> return Optional.of(lock); }</code><technical_language>extract "Lock" NbtDataUtil</technical_language>

Target:
protected Optional<String> getVal(ItemStack stack) { if (!stack.hasTagCompound()) { return Optional.empty(); } NBTTagCompound mainCompound = stack.getTagCompound(); if (!mainCompound.hasKey(NbtDataUtil.BLOCK_ENTITY_TAG, NbtDataUtil.TAG_COMPOUND)) { return Optional.empty(); } NBTTagCompound tileCompound = mainCompound.getCompoundTag(NbtDataUtil.BLOCK_ENTITY_TAG); String lock = tileCompound.getString(NbtDataUtil.ITEM_LOCK); return Optional.of(lock); }
Source:
<code>private int[] generateIndicesWoR(int populationSize, int sampleSize) { Set<Integer> indices = new HashSet<Integer>(sampleSize); for (int i = populationSize - sampleSize; i < populationSize; i++) { int idx = rand.nextInt(i + 1); if (indices.contains(idx)) { indices.add(i); } else { indices.add(idx); } } <START> int[] indicesArr = new int[indices.size()]; <END> int i = 0; for (Integer val : indices) { indicesArr[i] = val; i++; } Arrays.sort(indicesArr); return indicesArr; }</code><technical_language>Guava, try Ints.toArray()</technical_language>

Target:
private int[] generateIndicesWoR(int populationSize, int sampleSize) { Set<Integer> indices = new HashSet<>(sampleSize); for (int i = populationSize - sampleSize; i < populationSize; i++) { int idx = rand.nextInt(i + 1); if (indices.contains(idx)) { indices.add(i); } else { indices.add(idx); } } int[] indicesArr = Ints.toArray(indices); Arrays.sort(indicesArr); return indicesArr; }