auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private String getCurrentUser() { Account[] accountList = mAcctManager .getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE); <START> return accountList[0].name; <END> }</code><technical_language>account list null empty here</technical_language>

Target:
private String getCurrentUser() { Account[] accountList = mAcctManager .getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE); if (accountList != null && accountList.length > 0) { return accountList[0].name; } return null; }
Source:
<code><START> public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { <END> ListResponse<KubernetesSupportedVersionResponse> response = kubernetesVersionService.listKubernetesSupportedVersions(this); response.setResponseName(getCommandName()); setResponseObject(response); }</code><technical_language>exceptions unacceptable (intended pun miserably failed) listing clusters, resource-, allocation-, change related exception occur. a entity kind of thing</technical_language>

Target:
public void execute() throws ServerApiException, ConcurrentOperationException { ListResponse<KubernetesSupportedVersionResponse> response = kubernetesVersionService.listKubernetesSupportedVersions(this); response.setResponseName(getCommandName()); setResponseObject(response); }
Source:
<code>Submit(@GerritPersonIdent PersonIdent serverIdent, Provider<ReviewDb> dbProvider, GitRepositoryManager repoManager, IdentifiedUser.GenericFactory userFactory, ChangeUpdate.Factory updateFactory, ApprovalsUtil approvalsUtil, MergeQueue mergeQueue, AccountsCollection accounts, ChangesCollection changes, ChangeIndexer indexer, LabelNormalizer labelNormalizer, @GerritServerConfig Config cfg) { this.serverIdent = serverIdent; this.dbProvider = dbProvider; this.repoManager = repoManager; this.userFactory = userFactory; this.updateFactory = updateFactory; this.approvalsUtil = approvalsUtil; this.mergeQueue = mergeQueue; this.accounts = accounts; this.changes = changes; this.indexer = indexer; this.labelNormalizer = labelNormalizer; this.label = Objects.firstNonNull(cfg.getString( "change", null, "submitLabel"), "Submit"); this.tooltipPattern = new <START> ParameterizedString(Objects.firstNonNull(cfg.getString( <END> "change", null, "submitTooltip"), DEFAULT_TOOLTIP)); }</code><technical_language>Break this line a bit earlier</technical_language>

Target:
Submit(@GerritPersonIdent PersonIdent serverIdent, Provider<ReviewDb> dbProvider, GitRepositoryManager repoManager, IdentifiedUser.GenericFactory userFactory, ChangeUpdate.Factory updateFactory, ApprovalsUtil approvalsUtil, MergeQueue mergeQueue, AccountsCollection accounts, ChangesCollection changes, ChangeIndexer indexer, LabelNormalizer labelNormalizer, @GerritServerConfig Config cfg) { this.serverIdent = serverIdent; this.dbProvider = dbProvider; this.repoManager = repoManager; this.userFactory = userFactory; this.updateFactory = updateFactory; this.approvalsUtil = approvalsUtil; this.mergeQueue = mergeQueue; this.accounts = accounts; this.changes = changes; this.indexer = indexer; this.labelNormalizer = labelNormalizer; this.label = Objects.firstNonNull( Strings.emptyToNull(cfg.getString("change", null, "submitLabel")), "Submit"); this.titlePattern = new ParameterizedString(Objects.firstNonNull( cfg.getString("change", null, "submitTooltip"), DEFAULT_TOOLTIP)); }
Source:
<code>protected static File createSampleZip(boolean addMarker) throws IOException { String sourceDirPath = "data/sample_export"; File zip = new File(downloadDir, "distrib-apidoc.zip"); FileUtils.deleteQuietly(zip); Path p = Files.createFile(Paths.get(zip.getPath())); try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) { if (addMarker) { ZipEntry zipEntry = new ZipEntry(".nuxeo-archive"); zs.putNextEntry(zipEntry); zs.closeEntry(); } Path epath = Paths.get(sourceDirPath, "entries.txt"); List<String> lines = IOUtils.readLines(AbstractExplorerTest.getReferenceStream(epath), <START> StandardCharsets.UTF_8); <END> for (Iterator<String> lineIter = lines.iterator(); lineIter.hasNext();) { String path = lineIter.next(); if (StringUtils.isEmpty(path)) { continue; } ZipEntry entry = new ZipEntry(path); if (path.endsWith("/")) { entry.setExtra(new DWord(Integer.valueOf(lineIter.next())).getBytes()); zs.putNextEntry(entry); } else { zs.putNextEntry(entry); Path ppath = Paths.get(sourceDirPath, path); IOUtils.copy(AbstractExplorerTest.getReferenceStream(ppath), zs); } zs.closeEntry(); } } return zip; }</code><technical_language>UTF_8 statically imported if a one-line declaration</technical_language>

Target:
protected static File createSampleZip(boolean addMarker) throws IOException { String sourceDirPath = "data/sample_export"; File zip = new File(downloadDir, "distrib-apidoc.zip"); FileUtils.deleteQuietly(zip); Path p = Files.createFile(Paths.get(zip.getPath())); try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) { if (addMarker) { ZipEntry zipEntry = new ZipEntry(".nuxeo-archive"); zs.putNextEntry(zipEntry); zs.closeEntry(); } Path epath = Paths.get(sourceDirPath, "entries.txt"); List<String> lines; try (InputStream stream = AbstractExplorerTest.getReferenceStream(epath)) { lines =IOUtils.readLines(stream, StandardCharsets.UTF_8); } for (Iterator<String> lineIter = lines.iterator(); lineIter.hasNext();) { String path = lineIter.next(); if (StringUtils.isEmpty(path)) { continue; } ZipEntry entry = new ZipEntry(path); if (path.endsWith("/")) { entry.setExtra(new DWord(Integer.valueOf(lineIter.next())).getBytes()); zs.putNextEntry(entry); } else { zs.putNextEntry(entry); Path ppath = Paths.get(sourceDirPath, path); try (InputStream stream = getReferenceStream(ppath)) { IOUtils.copy(stream, zs); } } zs.closeEntry(); } } return zip; }
Source:
<code><START> public Mono<ServiceBusTransactionContext> createTransaction() { <END> if (isDisposed.get()) { return monoError(logger, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return connectionProcessor .flatMap(connection -> connection.getTransactionManager()) .flatMap(transactionManager -> transactionManager.createTransaction()) .map(byteBuffer -> new ServiceBusTransactionContext(byteBuffer)); }</code><technical_language>visibility</technical_language>

Target:
public Mono<ServiceBusTransactionContext> createTransaction() { if (isDisposed.get()) { return monoError(logger, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.createTransaction()) .map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId())); }
Source:
<code>protected ToolDescriptor() { <START> super(); <END> }</code><technical_language>omitted: java protected ToolDescriptor() {}</technical_language>

Target:
protected ToolDescriptor() { }
Source:
<code>public <T> T[] toArray(final T[] a) { final T[] copy = a.length < table.size() ? (T[]) java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), table.size()) : a; for (int i = 0; i < copy.length; i++) { <START> if (i >= table.size()) copy[i] = null; <END> else { if (checkString(i)) copy[i] = (T) table.getStringValue(col, i); else copy[i] = (T) Double.valueOf(table.getValueAsDouble(col, i)); } } return copy; }</code><technical_language>Oh, I guess if a.length is larger table.size(). put for loop bounds directly</technical_language>

Target:
public <T> T[] toArray(final T[] a) { final T[] copy = a.length < table.size() ? (T[]) java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), table.size()) : a; for (int i = 0; i < table.size(); i++) { if (checkString(i)) copy[i] = (T) table.getStringValue(col, i); else copy[i] = (T) Double.valueOf(table.getValueAsDouble(col, i)); } if (copy.length > table.size()) copy[table.size()] = null; return copy; }
Source:
<code>protected List<String> getLayerNames(String workspaceName) { SortedSet<String> resultSet = new TreeSet<String>(); if (workspaceName != null) { <START> for (ResourceInfo r : getCatalog().getResources(ResourceInfo.class)) { <END> if (r.getStore().getWorkspace().getName().equals(workspaceName)) { resultSet.add(r.getName()); } } } return new ArrayList(resultSet); }</code><technical_language>This is a full catalog scan, terrible JDBCConfig. specific method advantage of catalog filter. @smithkm suggest a replacement here</technical_language>

Target:
protected List<String> getLayerNames(String workspaceName) { List<String> resultSet = new ArrayList<String>(); if (workspaceName != null) { FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); try(CloseableIterator<ResourceInfo> it = getCatalog().getFacade().list(ResourceInfo.class, Predicates.equal("store.workspace.name", workspaceName), null, null, ff.sort("name", SortOrder.ASCENDING))) { while(it.hasNext()) { resultSet.add(it.next().getName()); } } } return resultSet; }
Source:
<code>public void FBButton_004_ForcedLoginButton_Visible() { WikiBasePageObject base = new WikiBasePageObject(driver); SpecialNewFilesPageObject specialPage = base.openSpecialNewFiles(wikiURL); <START> specialPage.verifyPageHeader(NEW_FILES_SPECIAL_PAGE_TITLE); <END> specialPage.addPhoto(); specialPage.verifyModalLoginAppeared(); specialPage.verifyModalFBButtonVisible(); }</code><technical_language>specialPage.verifyPageHeader(specialPage.getNewFilesSpecialPageTitle());</technical_language>

Target:
public void FBButton_004_ForcedLoginButton_Visible() { WikiBasePageObject base = new WikiBasePageObject(driver); SpecialNewFilesPageObject specialPage = base.openSpecialNewFiles(wikiURL); specialPage.verifyPageHeader(specialPage.getNewFilesSpecialPageTitle()); specialPage.addPhoto(); specialPage.verifyModalLoginAppeared(); specialPage.verifyModalFBButtonVisible(); }
Source:
<code>public void onTrailers(HttpFields trailers) { if (LOG.isDebugEnabled()) LOG.debug("onTrailers {}", this, trailers); <START> _request.getMetaData().setTrailers(trailers.asImmutable()); <END> _combinedListener.onRequestTrailers(_request); }</code><technical_language>Remove asImmutable()</technical_language>

Target:
public void onTrailers(HttpFields trailers) { if (LOG.isDebugEnabled()) LOG.debug("onTrailers {}", this, trailers); _request.setTrailerHttpFields(trailers); _combinedListener.onRequestTrailers(_request); }
Source:
<code>private void pollQueue() { do { FastList vs; synchronized (this) { vs = queue; queue = new FastList(); } for (Object v : vs.array) { if (v == null) { break; } <START> switch (on.kind(v)) { <END> case OnNext: case OnCompleted: synchronized (scheduledUnsubscribe) { if (scheduledUnsubscribe.isUnsubscribed()) { break; } on.accept(observer, v); } break; default: on.accept(observer, v); break; } } if (COUNTER_UPDATER.addAndGet(this, -vs.size) <= 0) { break; } } while (true); }</code><technical_language>This kind switch adds 20% overhead delivery. on.isError on.isCompleted instead</technical_language>

Target:
private void pollQueue() { do { FastList vs; synchronized (this) { vs = queue; queue = new FastList(); } for (Object v : vs.array) { if (v == null) { break; } on.accept(observer, v); } if (COUNTER_UPDATER.addAndGet(this, -vs.size) <= 0) { break; } } while (true); }
Source:
<code>public @Nullable SegmentStoreStatistics getTotalStatsForRange(long start, long end, IProgressMonitor monitor) { <START> if (start == ETERNITY.getStartTime().toNanos() && end == ETERNITY.getEndTime().toNanos()) { <END> waitForCompletion(); return getTotalStats(); } return getTotalStats(start, end, monitor); }</code><technical_language>this is a good initiative. checking start time, a valid case Marc-Andre's birthday. start time = [removed] end time = eternity</technical_language>

Target:
public @Nullable SegmentStoreStatistics getTotalStatsForRange(long start, long end, IProgressMonitor monitor) { @Nullable ITmfTrace trace = getTrace(); if (trace != null && (start == TmfTimeRange.ETERNITY.getStartTime().toNanos() && end == TmfTimeRange.ETERNITY.getEndTime().toNanos()) && (start <= trace.getStartTime().toNanos() && end >= trace.getEndTime().toNanos())) { waitForCompletion(); return getTotalStats(); } return getTotalStats(start, end, monitor); }
Source:
<code>private static <T extends Annotation> T getClassAnnotation(Class<?> clazz, Class<T> annotationClass) { <START> if (clazz == null) { return null; } T annot = clazz.getAnnotation(annotationClass); if (annot == null) { annot = getClassAnnotation(clazz.getSuperclass(), annotationClass); if (annot != null) { return annot; } } return annot; <END> }</code><technical_language>This written a loop: for (; clazz != null; clazz = clazz.getSuperclass()) { T t = clazz.getAnnotation(annotationClass); if (t != null) { return t; } } return null;</technical_language>

Target:
private static <T extends Annotation> T getClassAnnotation(Class<?> clazz, Class<T> annotationClass) { for (; clazz != null; clazz = clazz.getSuperclass()) { T t = clazz.getAnnotation(annotationClass); if (t != null) { return t; } } return null; }
Source:
<code>private int getCurrentPostStatusIndex() { switch (PostStatus.fromPost(getPost())) { case DRAFT: return 1; case PENDING: return 2; case PRIVATE: return 3; case TRASHED: case UNKNOWN: case PUBLISHED: case SCHEDULED: return 0; } if (BuildConfig.DEBUG) { <START> throw new IllegalStateException("Missing switch case."); <END> } return 0; }</code><technical_language>I a lint rule for this. I assume do right some switch statements branches, fix enable lint rule afterwards. if this is approach decide take, a part of unrelated PR instead try add for switch statement a single PR</technical_language>

Target:
private int getCurrentPostStatusIndex() { switch (PostStatus.fromPost(getPost())) { case DRAFT: return 1; case PENDING: return 2; case PRIVATE: return 3; case TRASHED: case UNKNOWN: case PUBLISHED: case SCHEDULED: return 0; } return 0; }
Source:
<code><START> public boolean skipValue() throws IOException { <END> int remainingValues = 1; while(remainingValues > 0) { MessageFormat f = getNextFormat(); if(f == MessageFormat.EOF) return false; remainingValues += f.skip(this); remainingValues--; } return true; }</code><technical_language>this method check if skip? If so, "canSkipValue()" is a method name</technical_language>

Target:
public boolean skipValue() throws IOException { int remainingValues = 1; while(remainingValues > 0) { MessageFormat f = getNextFormat(); remainingValues += f.skip(this); remainingValues--; } return true; }
Source:
<code>public void evolve(){ temp_cells.clear(); <START> for(int i=0; i<Properties.POPULATION; i++){ <END> List<T> neighbors = this.getNeighbors(population, i); if (Properties.SHUFFLE_GOALS) Randomness.shuffle(neighbors); if (getFitnessFunction().isMaximizationFunction()) { Collections.sort(neighbors, Collections.reverseOrder()); } else { Collections.sort(neighbors); } List<T> parents = selectionFunction.select(neighbors,2); T parent1 = parents.get(0); T parent2 = parents.get(1); @SuppressWarnings("unchecked") T offspring1 = (T)parent1.clone(); @SuppressWarnings("unchecked") T offspring2 = (T)parent2.clone(); try { if (Randomness.nextDouble() <= Properties.CROSSOVER_RATE) { crossoverFunction.crossOver(offspring1, offspring2); } } catch (ConstructionFailedException e) { logger.info("CrossOver failed"); continue; } T bestOffspring = getBestOffspring(offspring1, offspring2); notifyMutation(bestOffspring); bestOffspring.mutate(); if (bestOffspring.isChanged()) { bestOffspring.updateAge(currentIteration); } if (!isTooLong(bestOffspring) && bestOffspring.size() != 0) temp_cells.add(bestOffspring); else temp_cells.add(population.get(i)); } }</code><technical_language>avoid potential array exceptions null pointer exceptions in future, replace this line for (int i = 0; i < this.population.size(); i++) {</technical_language>

Target:
public void evolve(){ temp_cells.clear(); for(int i=0; i<this.population.size(); i++){ List<T> neighbors = neighb.getNeighbors(population, i); if (getFitnessFunction().isMaximizationFunction()) { Collections.sort(neighbors, Collections.reverseOrder()); } else { Collections.sort(neighbors); } List<T> parents = selectionFunction.select(neighbors,2); T parent1 = parents.get(0); T parent2 = parents.get(1); @SuppressWarnings("unchecked") T offspring1 = (T)parent1.clone(); @SuppressWarnings("unchecked") T offspring2 = (T)parent2.clone(); try { if (Randomness.nextDouble() <= Properties.CROSSOVER_RATE) { crossoverFunction.crossOver(offspring1, offspring2); } } catch (ConstructionFailedException e) { logger.info("CrossOver failed"); continue; } T bestOffspring = getBestOffspring(offspring1, offspring2); notifyMutation(bestOffspring); bestOffspring.mutate(); if (bestOffspring.isChanged()) { bestOffspring.updateAge(currentIteration); } if (!isTooLong(bestOffspring) && bestOffspring.size() != 0) temp_cells.add(bestOffspring); else temp_cells.add(population.get(i)); } }
Source:
<code>public synchronized void close() throws IOException { if (channelPools.isEmpty()) { return; } List<ListenableFuture<Void>> closingChannelsFutures = new ArrayList<>(); ListeningExecutorService listenableBatchPool = BigtableSessionSharedThreadPools.getInstance().getListeningExecutorService(); for (ChannelPool channelPool : channelPools) { <START> closingChannelsFutures.add(listenableBatchPool.submit(createCallable(channelPool))); <END> } channelPools.clear(); get(Futures.allAsList(closingChannelsFutures), "waiting for channels to be closed"); }</code><technical_language>createCallable -> createCloseCallable</technical_language>

Target:
public synchronized void close() throws IOException { if (managedChannels.isEmpty()) { return; } long timeoutNanos = TimeUnit.SECONDS.toNanos(10); long endTimeNanos = System.nanoTime() + timeoutNanos; for (ManagedChannel channel : managedChannels) { channel.shutdown(); } for (ManagedChannel channel : managedChannels) { long awaitTimeNanos = endTimeNanos - System.nanoTime(); if (awaitTimeNanos <= 0) { break; } try { channel.awaitTermination(awaitTimeNanos, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { throw new IOException("Interrupted while closing the channelPools"); } } for (ManagedChannel channel : managedChannels) { if (!channel.isTerminated()) { LOG.info("Could not close the channel after 10 seconds."); break; } } managedChannels.clear(); }
Source:
<code><START> public int hashCode() <END> { return HashUtil.combineHashCodes(getGraph().hashCode(),getMetadata().hashCode(),getName().hashCode()); }</code><technical_language>This hashCode() equals() kind of suspicious for me. getGraph() returns null value? question getMetadata() getName()</technical_language>

Target:
public int hashCode() { int graphHash = (null != getGraph()) ? getGraph().hashCode() : 0; int metadataHash = (null != getMetadata()) ? getMetadata().hashCode() : 0; int nameHash = (null != getName()) ? getName().hashCode() : 0; return HashUtil.combineHashCodes(graphHash, metadataHash, nameHash); }
Source:
<code>public List<Alert> getExampleAlerts() { List<Alert> alerts = new ArrayList<Alert>(); for (VulnType vulnType : VulnType.values()) { alerts.add( newAlert() .setName(getAlertElement(vulnType, "name")) <START> .setRisk(Alert.RISK_MEDIUM) .setConfidence(Alert.CONFIDENCE_MEDIUM) <END> .setDescription(getAlertElement(vulnType, "desc")) .setParam(HttpHeader.X_FRAME_OPTION) .setSolution(getAlertElement(vulnType, "soln")) .setReference(getAlertElement(vulnType, "refs")) .setCweId(16) .setWascId(15) .build()); } return alerts; }</code><technical_language>Do care this account for: <LINK_0> Is "Other Info" included in docs</technical_language>

Target:
public List<Alert> getExampleAlerts() { List<Alert> alerts = new ArrayList<Alert>(); for (VulnType vulnType : VulnType.values()) { alerts.add(buildAlert("", vulnType).build()); } return alerts; }
Source:
<code>public GenericEntity<List<Branch>> branchList(@QueryParam("listMode") String listMode) throws ApiException { try (GitConnection gitConnection = getGitConnection()) { <START> return new GenericEntity<List<Branch>>(gitConnection.branchList(listMode == null ? null : BranchListMode.valueOf(listMode))) { <END> }; } }</code><technical_language>BranchListMode.valueOf(listMode) throw IllegalArgumentException. Mb wrap BadRequestException</technical_language>

Target:
public List<Branch> branchList(@QueryParam("listMode") String listMode) throws ApiException { try (GitConnection gitConnection = getGitConnection()) { return gitConnection.branchList(listMode == null ? null : BranchListMode.valueOf(listMode)); } catch (IllegalArgumentException exception) { throw new BadRequestException(exception.getMessage()); } }
Source:
<code>public static TmfExperimentElement addExperiment(TmfProjectElement projectElement, String experimentName) { IFolder experimentFolder = projectElement.getExperimentsFolder().getResource(); IWorkspaceRoot workspaceRoot = experimentFolder.getWorkspace().getRoot(); IPath folderPath = experimentFolder.getFullPath().append(experimentName); <START> final IFolder folder = workspaceRoot.getFolder(folderPath); <END> WorkspaceModifyOperation operation = new WorkspaceModifyOperation() { @Override public void execute(IProgressMonitor monitor) throws CoreException { monitor.beginTask("", 1000); folder.create(false, true, monitor); monitor.done(); } }; try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile(operation); } catch (InterruptedException exception) { } catch (InvocationTargetException exception) { } catch (RuntimeException exception) { } TmfImportHelper.forceFolderRefresh(experimentFolder); for (ITmfProjectModelElement el : projectElement.getExperimentsFolder().getChildren()) { if (el.getName().equals(experimentName) && (el instanceof TmfExperimentElement)) { return (TmfExperimentElement) el; } } return null; }</code><technical_language>I this simplified experimentFolder.getFolder(experimentName);</technical_language>

Target:
public static TmfExperimentElement addExperiment(TmfProjectElement projectElement, String experimentName) { IFolder experimentFolder = projectElement.getExperimentsFolder().getResource(); final IFolder folder = experimentFolder.getFolder(experimentName); WorkspaceModifyOperation operation = new WorkspaceModifyOperation() { @Override public void execute(IProgressMonitor monitor) throws CoreException { monitor.beginTask("", 1000); folder.create(false, true, monitor); monitor.done(); } }; try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile(operation); } catch (InterruptedException exception) { } catch (InvocationTargetException exception) { } catch (RuntimeException exception) { } TmfImportHelper.forceFolderRefresh(experimentFolder); for (ITmfProjectModelElement el : projectElement.getExperimentsFolder().getChildren()) { if (el.getName().equals(experimentName) && (el instanceof TmfExperimentElement)) { return (TmfExperimentElement) el; } } return null; }
Source:
<code>private boolean shouldCheckFilter(List<FilterSet> filterSetList, int index, int step) { boolean result = false; if (index < filterSetList.size() && filterSetList.get(index).getActionFilterOrder() == step) { result = true; } <START> return result; <END> }</code><technical_language>return index < filterSetList.size() && filterSetList.get(index).getActionFilterOrder() == step</technical_language>

Target:
private boolean shouldCheckFilter(List<FilterSet> filterSetList, int index, int step) { return index < filterSetList.size() && filterSetList.get(index).getActionFilterOrder() == step; }
Source:
<code>private String sign() throws SignatureGenerationException { <START> String header = Base64.encodeBase64URLSafeString(headerJson.getBytes(Charset.forName("UTF-8"))); <END> String payload = Base64.encodeBase64URLSafeString(payloadJson.getBytes(Charset.forName("UTF-8"))); String content = String.format("%s.%s", header, payload); byte[] signatureBytes = algorithm.sign(content.getBytes(Charset.forName("UTF-8"))); String signature = Base64.encodeBase64URLSafeString((signatureBytes)); return String.format("%s.%s", content, signature); }</code><technical_language>Create interface com.auth0.jwt.interfaces package a constant reference instead of hardcoding string value</technical_language>

Target:
private String sign() throws SignatureGenerationException { String header = Base64.encodeBase64URLSafeString(headerJson.getBytes(Charset.forName(Charsets.UTF_8))); String payload = Base64.encodeBase64URLSafeString(payloadJson.getBytes(Charset.forName(Charsets.UTF_8))); String content = String.format("%s.%s", header, payload); byte[] signatureBytes = algorithm.sign(content.getBytes(Charset.forName(Charsets.UTF_8))); String signature = Base64.encodeBase64URLSafeString((signatureBytes)); return String.format("%s.%s", content, signature); }
Source:
<code>public DynamicUrlContentTabView() { initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); <START> frame.addLoadHandler((e) -> { resizeFrame(); }); <END> Window.addResizeHandler((e) -> { resizeFrame(); }); }</code><technical_language>need for ( ) a single parameter. frame.addLoadHandler(e -> resizeFrame()); work</technical_language>

Target:
public DynamicUrlContentTabView() { initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); frame.addLoadHandler(e -> { resizeFrame(); }); Window.addResizeHandler(e -> { resizeFrame(); }); }
Source:
<code>public Builder withCacheSize(int maxByteCount) { if (maxByteCount < 0) { throw new IllegalArgumentException("maxByteCount < 0: " + maxByteCount); } <START> cache = new PlatformLruCache(maxByteCount != 0 ? maxByteCount : 1); <END> return this; }</code><technical_language>move this ternary PlatformLruCache implementation detail of type</technical_language>

Target:
public Builder withCacheSize(int maxByteCount) { if (maxByteCount < 0) { throw new IllegalArgumentException("maxByteCount < 0: " + maxByteCount); } cache = new PlatformLruCache(maxByteCount); return this; }
Source:
<code>public void run() { try { while (isRunning()) { final RecordPublisherRunResult result = recordPublisher.run(startingPosition, batch -> { for (UserRecord userRecord : batch.getDeaggregatedRecords()) { if (filterDeaggregatedRecord(userRecord)) { deserializeRecordForCollectionAndUpdateState(userRecord); } } shardConsumerMetricsReporter.setAverageRecordSizeBytes(batch.getAverageRecordSizeBytes()); shardConsumerMetricsReporter.setNumberOfAggregatedRecords(batch.getAggregatedRecordSize()); shardConsumerMetricsReporter.setNumberOfDeaggregatedRecords(batch.getDeaggregatedRecordSize()); ofNullable(batch.getMillisBehindLatest()).ifPresent(shardConsumerMetricsReporter::setMillisBehindLatest); }); if (result == COMPLETE) { fetcherRef.updateState(subscribedShardStateIndex, SentinelSequenceNumber.SENTINEL_SHARD_ENDING_SEQUENCE_NUM.get()); break; } else { <START> startingPosition = StartingPosition.continueFromSequenceNumber(lastSequenceNum); <END> } } } catch (Throwable t) { fetcherRef.stopWithError(t); } }</code><technical_language>ShardConsumer need track update startingPosition? feels this internal state record publisher, I understand it, record publisher respects nextShardItr maintains</technical_language>

Target:
public void run() { try { while (isRunning()) { final RecordPublisherRunResult result = recordPublisher.run(batch -> { for (UserRecord userRecord : batch.getDeaggregatedRecords()) { if (filterDeaggregatedRecord(userRecord)) { deserializeRecordForCollectionAndUpdateState(userRecord); } } shardConsumerMetricsReporter.setAverageRecordSizeBytes(batch.getAverageRecordSizeBytes()); shardConsumerMetricsReporter.setNumberOfAggregatedRecords(batch.getAggregatedRecordSize()); shardConsumerMetricsReporter.setNumberOfDeaggregatedRecords(batch.getDeaggregatedRecordSize()); ofNullable(batch.getMillisBehindLatest()).ifPresent(shardConsumerMetricsReporter::setMillisBehindLatest); return lastSequenceNum; }); if (result == COMPLETE) { fetcherRef.updateState(subscribedShardStateIndex, SentinelSequenceNumber.SENTINEL_SHARD_ENDING_SEQUENCE_NUM.get()); break; } } } catch (Throwable t) { fetcherRef.stopWithError(t); } }
Source:
<code>private Quota fetchQuotaFromDB(Guid quotaId) { if (quotaId != null && quotaId != Guid.Empty) { if (!directQuotaMap.contains(quotaId)) { Quota quota = getQuotaDAO().getById(quotaId); directQuotaMap.put(quotaId, quota); <START> storagePoolQuotaMap.putIfAbsent(quota.getStoragePoolId(), new HashMap<Guid, Quota>()); <END> storagePoolQuotaMap.get(quota.getStoragePoolId()).put(quotaId, quota); } return directQuotaMap.get(quotaId); } return null; }</code><technical_language>I hope realize lines atomic. want - if fine - cool</technical_language>

Target:
private Quota fetchQuotaFromDB(Guid quotaId) { if (quotaId != null && quotaId != Guid.Empty) { if (!directQuotaMap.contains(quotaId)) { Quota quota = getQuotaDAO().getById(quotaId); lock.readLock().lock(); directQuotaMap.put(quotaId, quota); storagePoolQuotaMap.putIfAbsent(quota.getStoragePoolId(), new HashMap<Guid, Quota>()); storagePoolQuotaMap.get(quota.getStoragePoolId()).put(quotaId, quota); lock.readLock().unlock(); } return directQuotaMap.get(quotaId); } return null; }
Source:
<code>protected <T> T resolveTypeFromMap(List<Attachment> inputDataMap, String key, Class<T> clazz, T defaultValue) throws ApiException { try { String att = this.getAttributeValue(key, inputDataMap).orElse(null); if (null != att) { <START> return (T) att; <END> } } catch (Exception e) { log.debug("Failed to parse parameter ["+key+"]", e); } if(defaultValue != null) { return defaultValue; } throw new ApiException("Key +key+ not defined", 400); }</code><technical_language>cast a String object</technical_language>

Target:
protected <T> T resolveTypeFromMap(List<Attachment> inputDataMap, String key, Class<T> clazz, T defaultValue) throws ApiException { T obj = defaultValue; try { obj = this.getAttributeValue(key, inputDataMap).map(a -> { return this.castAttribute(a, clazz); }).orElseGet(() -> { return defaultValue; }); } catch (Exception e) { log.debug("Failed to parse parameter ["+key+"]", e); } if (obj == null) { throw new ApiException("Key +key+ not defined", 400); } return obj; }
Source:
<code>public ModifierKeywordTreeImpl MODIFIER_KEYWORD() { return b.<ModifierKeywordTreeImpl>nonterminal().is( f.modifierKeyword( b.firstOf( b.token(JavaKeyword.PUBLIC), b.token(JavaKeyword.PROTECTED), b.token(JavaKeyword.PRIVATE), b.token(JavaKeyword.ABSTRACT), b.token(JavaKeyword.STATIC), b.token(JavaKeyword.FINAL), b.token(JavaKeyword.TRANSIENT), b.token(JavaKeyword.VOLATILE), b.token(JavaKeyword.SYNCHRONIZED), b.token(JavaKeyword.NATIVE), b.token(JavaKeyword.DEFAULT), b.token(JavaKeyword.STRICTFP), <START> b.token(JavaRestrictedKeyword.TRANSITIVE)))); <END> }</code><technical_language>is a problem transitive a general modifier, transitive a type name this variables of type fail parse. valid Java class is example of class transitive { transitive t; }</technical_language>

Target:
public ModifierKeywordTreeImpl MODIFIER_KEYWORD() { return b.<ModifierKeywordTreeImpl>nonterminal().is( f.modifierKeyword( b.firstOf( b.token(JavaKeyword.PUBLIC), b.token(JavaKeyword.PROTECTED), b.token(JavaKeyword.PRIVATE), b.token(JavaKeyword.ABSTRACT), b.token(JavaKeyword.STATIC), b.token(JavaKeyword.FINAL), b.token(JavaKeyword.TRANSIENT), b.token(JavaKeyword.VOLATILE), b.token(JavaKeyword.SYNCHRONIZED), b.token(JavaKeyword.NATIVE), b.token(JavaKeyword.DEFAULT), b.token(JavaKeyword.STRICTFP)))); }
Source:
<code>public static boolean isTestModeSet() { String testModeCacheDisabled = System.getProperty(NUXEO_TESTING_PROP_CACHE_DISABLED); <START> if (Boolean.FALSE.equals(Boolean.parseBoolean(testModeCacheDisabled))) { <END> if (testModeSet == null) { testModeSet = isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP); } return testModeSet; } return isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP); }</code><technical_language>Note parseBoolean returns a boolean, a Boolean. Boolean.getBoolean(syspropname) instead of System.getProperty + Boolean.parseBoolean</technical_language>

Target:
public static boolean isTestModeSet() { return isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP); }
Source:
<code>public List<ScriptResult<Object>> executeNodeSourceScript(@HeaderParam("sessionid") String sessionId, @FormParam("nodesource") String nodeSource, @FormParam("script") String script, @FormParam("scriptEngine") String scriptEngine) throws Throwable { RMProxyUserInterface rm = checkAccess(sessionId); List<ScriptResult<Object>> results = rm.executeScript(script, scriptEngine, TargetType.NODESOURCE_NAME.name(), Collections.singleton(nodeSource)); List<ScriptResult<Object>> awaitedResults = new LinkedList<>(); <START> for (ScriptResult result : results) { <END> awaitedResults.add(PAFuture.getFutureValue(result)); } checkEmptyScriptResults(awaitedResults); return awaitedResults; }</code><technical_language>more modern this is ok : results.stream().map(result -> PAFuture.getFutureValue(result)).collect(Collectors.toLists());</technical_language>

Target:
public List<ScriptResult<Object>> executeNodeSourceScript(@HeaderParam("sessionid") String sessionId, @FormParam("nodesource") String nodeSource, @FormParam("script") String script, @FormParam("scriptEngine") String scriptEngine) throws Throwable { RMProxyUserInterface rm = checkAccess(sessionId); List<ScriptResult<Object>> results = rm.executeScript(script, scriptEngine, TargetType.NODESOURCE_NAME.name(), Collections.singleton(nodeSource)); List<ScriptResult<Object>> awaitedResults = results.stream() .map(result -> PAFuture.getFutureValue(result)) .collect(Collectors.toList()); checkEmptyScriptResults(awaitedResults); return awaitedResults; }
Source:
<code>public void update(UpdateOptions updateOptions) { updateOptions.newEmailOption.ifPresent(s -> email = s); updateOptions.nameOption.ifPresent(s -> { name = s; lastName = StringHelper.splitName(s)[1]; }); updateOptions.lastNameOption.ifPresent(s -> lastName = s); updateOptions.commentOption.ifPresent(s -> comments = s); updateOptions.googleIdOption.ifPresent(s -> googleId = s); updateOptions.teamNameOption.ifPresent(s -> team = s); <START> updateOptions.sectionNameOption.ifPresent(s -> section = s.isEmpty() ? Const.DEFAULT_SECTION : s); <END> }</code><technical_language>change logic of updating student. problem exist enroll a new student. previously I modify DB layer (but note this StudentAttributes is DB layer), isolate this issue, is fix this problem in API layer. i.e. change studentEnrollRequest settle default section name if empty</technical_language>

Target:
public void update(UpdateOptions updateOptions) { updateOptions.newEmailOption.ifPresent(s -> email = s); updateOptions.nameOption.ifPresent(s -> { name = s; lastName = StringHelper.splitName(s)[1]; }); updateOptions.lastNameOption.ifPresent(s -> lastName = s); updateOptions.commentOption.ifPresent(s -> comments = s); updateOptions.googleIdOption.ifPresent(s -> googleId = s); updateOptions.teamNameOption.ifPresent(s -> team = s); updateOptions.sectionNameOption.ifPresent(s -> section = s); }
Source:
<code>public void invalid_wrongType() { @Indexed(index = INDEX_NAME) class IndexedEntity { Integer id; String text; String invalid; @DocumentId public Integer getId() { return id; } @GenericField public String getText() { return text; } @IndexedEmbedded public String getInvalid() { return invalid; } } SubTest.expectException( () -> setupHelper.start() .withAnnotatedEntityTypes( IndexedEntity.class ) .setup() ) .assertThrown() .isInstanceOf( SearchException.class ) <START> .hasMessageContaining( "HSEARCH700060: The indexed embedded property 'invalid' of type 'java.lang.String' does not provide any valid field." ); <END> }</code><technical_language>Please mention error code ("HSEARCH700060") in assertions, change release (upon merging PR, for example) honest care exact code</technical_language>

Target:
public void invalid_wrongType() { @Indexed(index = INDEX_NAME) class IndexedEntity { Integer id; String text; String invalid; @DocumentId public Integer getId() { return id; } @GenericField public String getText() { return text; } @IndexedEmbedded public String getInvalid() { return invalid; } } SubTest.expectException( () -> setupHelper.start() .withAnnotatedEntityTypes( IndexedEntity.class ) .setup() ) .assertThrown() .isInstanceOf( SearchException.class ) .hasMessageMatching( FailureReportUtils.buildFailureReportPattern() .typeContext( IndexedEntity.class.getName() ) .pathContext( ".invalid" ) .failure( "Type '" + String.class.getName() + "' cannot be indexed-embedded, because no index mapping (@GenericField, @FullTextField, ...) is defined for that type." ) .build() ); }
Source:
<code>public void testFromByteArraySummerTime() throws Exception { <START> final com.alliander.osgp.dto.valueobjects.smartmetering.CosemDateTimeDto cosemDateTime = this.dlmsHelperService <END> .fromDateTimeValue(this.byteArraySummerTime()); assertTrue(cosemDateTime.isDateTimeSpecified()); final DateTime dateInSummerTime = cosemDateTime.asDateTime(); assertEquals("2015-07-21T14:53:07.230+02:00", ISODateTimeFormat.dateTime().print(dateInSummerTime)); }</code><technical_language>CosemDateTimeDto longer needs referenced fully qualified class name, name collision CosemDateTime jDLMS data types longer is present refactoring. Adding import statement for DTO class removing (now) unnecessary package places CosemDateTimeDto is clean code some more</technical_language>

Target:
public void testFromByteArraySummerTime() throws Exception { final CosemDateTimeDto cosemDateTime = this.dlmsHelperService.fromDateTimeValue(this.byteArraySummerTime()); assertTrue(cosemDateTime.isDateTimeSpecified()); final DateTime dateInSummerTime = cosemDateTime.asDateTime(); assertEquals("2015-07-21T14:53:07.230+02:00", ISODateTimeFormat.dateTime().print(dateInSummerTime)); }
Source:
<code>public ExecutationType solutionFound(ThreadContext context, Solution solution) { <START> if (solution == null) { <END> return ExecutationType.CONTINUE; } return ExecutationType.STOP_ALL; }</code><technical_language>is solution allowed null</technical_language>

Target:
public ExecutationType solutionFound(ThreadContext context, Solution solution) { return ExecutationType.STOP_ALL; }
Source:
<code>public Collection<Partition<AbstractKuduInputOperator>> definePartitions( Collection<Partition<AbstractKuduInputOperator>> partitions, PartitioningContext context) { List<Partition<AbstractKuduInputOperator>> partitionsForInputOperator = new ArrayList<>(); List<KuduPartitionScanAssignmentMeta> assignmentMetaList = new ArrayList<>(); try { assignmentMetaList.addAll(getListOfPartitionAssignments(partitions,context)); } catch (Exception e) { <START> LOG.error(" Aborting partition planning as Kudu meta data could not be obtained"); <END> DTThrowable.rethrow(e); } LOG.info("Maximum possible Kudu input operator partition count is " + assignmentMetaList.size()); Map<Integer,List<KuduPartitionScanAssignmentMeta>> assignments = assign(assignmentMetaList,context); if ( partitions == null || ( assignments.size() != partitions.size()) ) { LOG.info("Clearing all of the current partitions and setting up new ones"); partitions.clear(); for ( int i = 0; i < assignments.size(); i++) { partitionsForInputOperator.add(clonePartitionAndAssignScanMeta(assignments.get(i))); } return partitionsForInputOperator; } else { LOG.info("Not making any changes to the partitions"); return partitions; } }</code><technical_language>wrap exception this message instead of logging it</technical_language>

Target:
public Collection<Partition<AbstractKuduInputOperator>> definePartitions( Collection<Partition<AbstractKuduInputOperator>> partitions, PartitioningContext context) { if ( partitions != null) { LOG.info("The current partitioner plan has " + partitions.size() + " operators before redefining"); } List<Partition<AbstractKuduInputOperator>> partitionsForInputOperator = new ArrayList<>(); List<KuduPartitionScanAssignmentMeta> assignmentMetaList = new ArrayList<>(); try { assignmentMetaList.addAll(getListOfPartitionAssignments(partitions,context)); } catch (Exception e) { throw new RuntimeException("Aborting partition planning as Kudu meta data could not be obtained", e); } LOG.info("Maximum possible Kudu input operator partition count is " + assignmentMetaList.size()); Map<Integer,List<KuduPartitionScanAssignmentMeta>> assignments = assign(assignmentMetaList,context); boolean requiresRepartitioning = false; if ( partitions == null) { requiresRepartitioning = true; } else { for ( Partition<AbstractKuduInputOperator> aPartition : partitions) { if ( !aPartition.getPartitionedInstance().isPartitioned()) { requiresRepartitioning = true; break; } } } if ( requiresRepartitioning ) { partitions.clear(); LOG.info("Clearing all of the current partitions and setting up new ones"); partitions.clear(); for ( int i = 0; i < assignments.size(); i++) { List<KuduPartitionScanAssignmentMeta> assignmentForThisOperator = assignments.get(i); partitionsForInputOperator.add(clonePartitionAndAssignScanMeta(assignmentForThisOperator)); LOG.info("Assigned apex operator " + i + " with " + assignmentForThisOperator.size() + " kudu mappings"); } LOG.info("Returning " + partitionsForInputOperator.size() + " partitions for the input operator"); return partitionsForInputOperator; } else { LOG.info("Not making any changes to the partitions"); return partitions; } }
Source:
<code>AdvancedCache<K, V> cacheToUse(boolean isWrite) { <START> return isWrite ? optimisticTransaction ? cache : cache.withFlags(Flag.SKIP_LOCKING) : cache.withFlags(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT); <END> }</code><technical_language>Some parentheses improve readability please</technical_language>

Target:
AdvancedCache<K, V> cacheToUse(boolean isWrite) { return isWrite ? (optimisticTransaction ? cache : cache.withFlags(Flag.SKIP_LOCKING)) : cache.withFlags(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT); }
Source:
<code>private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } final byte[] bytes = buffer; final int bytesLength = bufferIndex; bufferIndex = 0; final long offset = position; position += bytesLength; if (Runtime.getRuntime().freeMemory() < MIN_MEMORY_THRESHOLD && buffersToBeReturned.get() > 0) { <START> LOG.debug("Low memory"); <END> waitForTaskToComplete(); } if (BYTE_BUFFER_POOL.size(false) < 1 && buffersToBeReturned.get() >= maxBufferCount) { waitForTaskToComplete(); } buffer = BYTE_BUFFER_POOL.getBuffer(false, bufferSize).array(); buffersToBeReturned.incrementAndGet(); final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, bytes, 0, bytesLength); perfInfo.registerResult(op.getResult()); BYTE_BUFFER_POOL.putBuffer(ByteBuffer.wrap(bytes)); buffersToBeReturned.decrementAndGet(); perfInfo.registerSuccess(true); return null; } } }); writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }</code><technical_language>if Runtime.getRuntime().freeMemory() < MIN_MEMORY_THRESHOLD buffersToBeReturned.get() is 0? LOG more meaningful "Low memory, 100 MB is available, existing read tasks consumes 2048 MB, waiting for completion."</technical_language>

Target:
private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } final byte[] byteArray = buffer; final int bytesLength = bufferIndex; buffer = writeBufferPool.get(); bufferIndex = 0; final long offset = position; position += bytesLength; final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, byteArray, 0, bytesLength); perfInfo.registerResult(op.getResult()); writeBufferPool.release(byteArray); perfInfo.registerSuccess(true); return null; } } }); writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }
Source:
<code>private boolean validateAndCompleteParameters(QuotaConsumptionParametersWrapper parameters) { <START> <END> if (QuotaEnforcementTypeEnum.DISABLED.equals(parameters.getAuditLogable().getStoragePool().getQuotaEnforcementType())) { return true; } boolean hardEnforcement = QuotaEnforcementTypeEnum.HARD_ENFORCEMENT.equals(parameters.getAuditLogable().getStoragePool().getQuotaEnforcementType()); for (QuotaConsumptionParameter param : parameters.getParameters()) { boolean validQuotaId = checkAndFetchQuota(parameters, param); boolean validVdsGroup = true; if (param instanceof QuotaVdsGroupConsumptionParameter) { validVdsGroup = checkVdsGroupMatchQuota(parameters, param); } boolean validStorageDomain = true; if (param instanceof QuotaStorageConsumptionParameter) { validStorageDomain = checkStoragePoolMatchQuota(parameters, param); } if (!validQuotaId || !validVdsGroup || !validStorageDomain) { if (hardEnforcement) { return false; } else { quotaManagerAuditLogger.auditLog(parameters.getAuditLogable(), AuditLogType.MISSING_QUOTA_STORAGE_PARAMETERS_PERMISSIVE_MODE); parameters.getCanDoActionMessages().clear(); return true; } } } return true; }</code><technical_language>Enums == instead of equals</technical_language>

Target:
private boolean validateAndCompleteParameters(QuotaConsumptionParametersWrapper parameters) { if (QuotaEnforcementTypeEnum.DISABLED == parameters.getAuditLogable().getStoragePool().getQuotaEnforcementType()) { return true; } boolean hardEnforcement = QuotaEnforcementTypeEnum.HARD_ENFORCEMENT == parameters.getAuditLogable().getStoragePool().getQuotaEnforcementType(); for (QuotaConsumptionParameter param : parameters.getParameters()) { boolean validQuotaId = checkAndFetchQuota(parameters, param); boolean validVdsGroup = true; if (param instanceof QuotaVdsGroupConsumptionParameter) { validVdsGroup = checkVdsGroupMatchQuota(parameters, param); } boolean validStorageDomain = true; if (param instanceof QuotaStorageConsumptionParameter) { validStorageDomain = checkStoragePoolMatchQuota(parameters, param); } if (!validQuotaId || !validVdsGroup || !validStorageDomain) { if (hardEnforcement) { return false; } else { quotaManagerAuditLogger.auditLog(parameters.getAuditLogable(), AuditLogType.MISSING_QUOTA_STORAGE_PARAMETERS_PERMISSIVE_MODE); parameters.getCanDoActionMessages().clear(); return true; } } } return true; }
Source:
<code>private Vector3f findSpawnPos(Vector3f targetPos, float entityHeight) { int targetBlockX = TeraMath.floorToInt(targetPos.x); int targetBlockY = TeraMath.floorToInt(targetPos.y); int targetBlockZ = TeraMath.floorToInt(targetPos.z); Vector2i center = new Vector2i(targetBlockX, targetBlockZ); <START> for (BaseVector2i pos : SpiralIterable.clockwise(center).maxRadius(250).scale(2).build()) { <END> Vector3i testPos = new Vector3i(pos.getX(), targetBlockY, pos.getY()); Vector3i spawnPos = findOpenVerticalPosition(testPos, entityHeight); if (spawnPos != null) { return new Vector3f(spawnPos.getX(), spawnPos.getY() + entityHeight, spawnPos.getZ()); } } return targetPos; }</code><technical_language>3 a bit low, 250 high. 16 32 is a compromise? is default chunk size nowadays</technical_language>

Target:
private Optional<Vector3f> findSpawnPos(Vector3f targetPos, float entityHeight) { int targetBlockX = TeraMath.floorToInt(targetPos.x); int targetBlockY = TeraMath.floorToInt(targetPos.y); int targetBlockZ = TeraMath.floorToInt(targetPos.z); Vector2i center = new Vector2i(targetBlockX, targetBlockZ); for (BaseVector2i pos : SpiralIterable.clockwise(center).maxRadius(32).scale(2).build()) { Vector3i testPos = new Vector3i(pos.getX(), targetBlockY, pos.getY()); Vector3i spawnPos = findOpenVerticalPosition(testPos, entityHeight); if (spawnPos != null) { return Optional.of(new Vector3f(spawnPos.getX(), spawnPos.getY() + entityHeight, spawnPos.getZ())); } } return Optional.empty(); }