auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>TemporaryJobs(final Builder builder, final Config config) { if (builder.heliosDeployment != null) { this.heliosDeployment = builder.heliosDeployment; } else { <START> this.heliosDeployment = getOrCreateHeliosSoloDeployment(); <END> } client = checkNotNull(heliosDeployment.client(), "client"); this.prober = checkNotNull(builder.prober, "prober"); this.defaultHostFilter = checkNotNull(builder.hostFilter, "hostFilter"); this.env = checkNotNull(builder.env, "env"); this.jobPrefix = checkNotNull(builder.jobPrefix, "jobPrefix"); checkArgument(builder.deployTimeoutMillis >= 0, "deployTimeoutMillis"); this.undeployer = new DefaultUndeployer(client); this.deployer = fromNullable(builder.deployer).or( new DefaultDeployer(client, jobs, builder.hostPickingStrategy, builder.jobDeployedMessageFormat, builder.deployTimeoutMillis, undeployer)); final Config configWithPrefix = ConfigFactory.empty() .withValue("prefix", ConfigValueFactory.fromAnyRef(jobPrefix)); this.config = config.withFallback(configWithPrefix).resolve(); }</code><technical_language>this.heliosDeployment is of this constructor, need a field</technical_language>

Target:
private TemporaryJobs(final Builder builder, final Config config) { final HeliosDeployment heliosDeployment = builder.heliosDeployment == null ? singletonHeliosSoloDeployment() : builder.heliosDeployment; client = checkNotNull(heliosDeployment.client(), "client"); this.prober = checkNotNull(builder.prober, "prober"); this.defaultHostFilter = checkNotNull(builder.hostFilter, "hostFilter"); this.env = checkNotNull(builder.env, "env"); this.jobPrefix = checkNotNull(builder.jobPrefix, "jobPrefix"); checkArgument(builder.deployTimeoutMillis >= 0, "deployTimeoutMillis"); this.undeployer = new DefaultUndeployer(client); this.deployer = fromNullable(builder.deployer).or( new DefaultDeployer(client, jobs, builder.hostPickingStrategy, builder.jobDeployedMessageFormat, builder.deployTimeoutMillis, undeployer)); final Config configWithPrefix = ConfigFactory.empty() .withValue("prefix", ConfigValueFactory.fromAnyRef(jobPrefix)); this.config = config.withFallback(configWithPrefix).resolve(); }
Source:
<code>public CompletableFuture<Tuple<List<MapBean>, Integer>> getMatchmakerMapsWithPageCount(int matchmakerQueueId, int count, int page) { Tuple<List<MatchmakerQueueMapPool>, java.util.Map<String, ?>> tuple = fafApiAccessor.getMatchMakerPoolsWithMeta(matchmakerQueueId, count, page); return CompletableFuture.completedFuture(new Tuple<>(tuple.getFirst() .parallelStream() .map(MatchmakerQueueMapPool::getMapPool) <START> .flatMap(mapPool -> mapPool.getMapVersions().stream()) <END> .distinct() .map(MapBean::fromMapVersionDto) .collect(toList()), ((HashMap<String,Integer>) tuple.getSecond().get("page")).get("totalPages"))); }</code><technical_language>If want this structure implement pagination need do some .skip .limit functions</technical_language>

Target:
public CompletableFuture<Tuple<List<MapBean>, Integer>> getMatchmakerMapsWithPageCount(int matchmakerQueueId, int count, int page) { List<MapVersion> mapVersions = fafApiAccessor.getMatchmakerPools(matchmakerQueueId) .stream() .map(MatchmakerQueueMapPool::getMapPool) .flatMap(mapPool -> mapPool.getMapVersions().stream()) .distinct() .collect(toList()); int totalPages = (mapVersions.size() - 1) / count + 1; return CompletableFuture.completedFuture(new Tuple<>(mapVersions .stream() .skip((page - 1) * count) .limit(count) .map(MapBean::fromMapVersionDto) .collect(toList()), totalPages)); }
Source:
<code>public @Nonnull List<String> getVolumeSnapshotIdsFor(String nameOrId) { final Collection<VolumeSnapshot> sortedObjects = new TreeSet<>(VOLUMESNAPSHOT_DATE_COMPARATOR); final Map<String, Collection<VolumeSnapshot>> allVolumeSnapshots = getVolumeSnapshots(); final Collection<VolumeSnapshot> findByName = allVolumeSnapshots.get(nameOrId); if (findByName != null) { for (VolumeSnapshot o : findByName) { <START> if (o.getStatus() == Volume.Status.AVAILABLE) { <END> sortedObjects.add(o); } } } if (nameOrId.matches("[0-9a-f-]{36}")) { final VolumeSnapshot findById = clientProvider.get().blockStorage().snapshots().get(nameOrId); if (findById != null && findById.getStatus() == Volume.Status.AVAILABLE) { sortedObjects.add(findById); } } final List<String> ids = new ArrayList<>(); for (VolumeSnapshot i : sortedObjects) { ids.add(i.getId()); } return ids; }</code><technical_language>move this filtering getVolumeSnapshots? I do do care for snapshots in other state</technical_language>

Target:
public @Nonnull List<String> getVolumeSnapshotIdsFor(String nameOrId) { final Collection<VolumeSnapshot> sortedObjects = new TreeSet<>(VOLUMESNAPSHOT_DATE_COMPARATOR); final Map<String, Collection<VolumeSnapshot>> allVolumeSnapshots = getVolumeSnapshots(); final Collection<VolumeSnapshot> findByName = allVolumeSnapshots.get(nameOrId); if (findByName != null) { sortedObjects.addAll(findByName); } if (nameOrId.matches("[0-9a-f-]{36}")) { final VolumeSnapshot findById = clientProvider.get().blockStorage().snapshots().get(nameOrId); if (findById != null && findById.getStatus() == Status.AVAILABLE) { sortedObjects.add(findById); } } final List<String> ids = new ArrayList<>(); for (VolumeSnapshot i : sortedObjects) { ids.add(i.getId()); } return ids; }
Source:
<code>public String borrow(){ return String.join(" ", <START> "A borrower",name,"wants to get some money."); <END> }</code><technical_language>String.format cleaner</technical_language>

Target:
public String borrow(){ return String.format("Borrower %s wants to get some money.",name); }
Source:
<code>public Shell getShell(TimePeriod timePeriod, Matcher<?>... matchers) { ShellMatchingMatcherIsAvailable shellCondition = new ShellMatchingMatcherIsAvailable(matchers); try{ new WaitUntil(shellCondition, timePeriod); }catch (WaitTimeoutExpiredException e) { <START> AndMatcher am = new AndMatcher(matchers); <END> String exceptionText = "No matching shell found with " + am; exceptionText += "\n" + new DiagnosticTool().getShellsDiagnosticInformation(); throw new CoreLayerException(exceptionText); } return shellCondition.getResult(); }</code><technical_language>a though. wait condition some matcher, create a layer in hierarchy of wait conditions method a wait condition getMatcher() return matcher(s). call in places shellCondition.getMatcher() instead of instantiating this - ShellMatchinMatcherIsAvailable internally AndMatcher. more transparent</technical_language>

Target:
public Shell getShell(TimePeriod timePeriod, Matcher<?>... matchers) { ShellMatchingMatcherIsAvailable shellCondition = new ShellMatchingMatcherIsAvailable(matchers); try{ new WaitUntil(shellCondition, timePeriod); }catch (WaitTimeoutExpiredException e) { String exceptionText = shellCondition.errorMessageUntil(); exceptionText += "\n" + new DiagnosticTool().getShellsDiagnosticInformation(); throw new CoreLayerException(exceptionText); } return shellCondition.getResult(); }
Source:
<code>public void mergeDiscoveredPackages(ContentDiscoveryReport report) { int resourceId = report.getResourceId(); long start = System.currentTimeMillis(); if (LOG.isDebugEnabled()) { LOG.debug("Merging [" + report.getDeployedPackages().size() + "] packages for Resource with id [" + resourceId + "]..."); } ResourceCriteria c = new ResourceCriteria(); c.addFilterId(resourceId); c.fetchInstalledPackages(true); List<Resource> result = resourceManager.findResourcesByCriteria(subjectManager.getOverlord(), c); if (result.isEmpty()) { LOG.error("Invalid resource ID specified for merge. Resource ID: " + resourceId); return; } Resource resource = result.get(0); Set<InstalledPackage> doomedPackages = new HashSet<InstalledPackage>(resource.getInstalledPackages()); long timestamp = System.currentTimeMillis(); for (ResourcePackageDetails discoveredPackage : report.getDeployedPackages()) { contentManager.handleDiscoveredPackage(resource, discoveredPackage, doomedPackages, timestamp); } contentManager.removeInstalledPackages(resource, doomedPackages, timestamp); if (LOG.isDebugEnabled()) { LOG.debug("Finished merging [" + report.getDeployedPackages().size() + "] packages in " + (System.currentTimeMillis() - start) + "ms"); } try{ <START> DataPurgeJob.purgeNow(); <END> }catch (Exception e){ LOG.warn("Error trying to schedule a purge job."); } }</code><technical_language>I guess is OK for quick testing, prefer wait for DataPurgeJob executed. AFAIK executes hour default. purgeNow throws exception a job is scheduled executed yet. users WARN/Error get concerned it</technical_language>

Target:
public void mergeDiscoveredPackages(ContentDiscoveryReport report) { int resourceId = report.getResourceId(); long start = System.currentTimeMillis(); if (LOG.isDebugEnabled()) { LOG.debug("Merging [" + report.getDeployedPackages().size() + "] packages for Resource with id [" + resourceId + "]..."); } ResourceCriteria c = new ResourceCriteria(); c.addFilterId(resourceId); c.fetchInstalledPackages(true); List<Resource> result = resourceManager.findResourcesByCriteria(subjectManager.getOverlord(), c); if (result.isEmpty()) { LOG.error("Invalid resource ID specified for merge. Resource ID: " + resourceId); return; } Resource resource = result.get(0); Set<InstalledPackage> doomedPackages = new HashSet<InstalledPackage>(resource.getInstalledPackages()); long timestamp = System.currentTimeMillis(); for (ResourcePackageDetails discoveredPackage : report.getDeployedPackages()) { contentManager.handleDiscoveredPackage(resource, discoveredPackage, doomedPackages, timestamp); } contentManager.removeInstalledPackages(resource, doomedPackages, timestamp); if (LOG.isDebugEnabled()) { LOG.debug("Finished merging [" + report.getDeployedPackages().size() + "] packages in " + (System.currentTimeMillis() - start) + "ms"); } }
Source:
<code>protected String getResource() { <START> return "taskmodel.bpmn"; <END> }</code><technical_language>Camel case</technical_language>

Target:
protected String getResource() { return "taskModel.bpmn"; }
Source:
<code>default ServerEvents getEvents() { Response response = execute(GET_EVENTS); <START> ArrayList<CommandEvent> commands = new ArrayList<>(); <END> ArrayList<ServerEvent> events = new ArrayList<>(); String jsonData = new Json().toJson(response.getValue()); Map<String, Object> value = (Map<String, Object>) response.getValue(); for (String name : value.keySet()) { if (name.equals("commands")) { ArrayList<Map<String, Object>> cmds = (ArrayList<Map<String, Object>>) value.get(name); for (Map<String, Object> cmd : cmds) { commands.add(new CommandEvent( (String) cmd.get("cmd"), ((Long) cmd.get("startTime")).intValue(), ((Long) cmd.get("endTime")).intValue() )); } } else { ArrayList<Long> timestamps = (ArrayList<Long>) value.get(name); List<Integer> intStamps = timestamps .stream() .map(Long::intValue) .collect(Collectors.toList()); events.add(new ServerEvent(name, intStamps)); } } return new ServerEvents(commands, events, jsonData); }</code><technical_language>basic type interface (List) concrete type (ArrayList)</technical_language>

Target:
default ServerEvents getEvents() { Response response = execute(GET_EVENTS); String jsonData = new Json().toJson(response.getValue()); Map<String, Object> value = (Map<String, Object>) response.getValue(); List<CommandEvent> commands = ((List<Map<String, Object>>) value.get("commands")) .stream() .map((Map<String, Object> cmd) -> new CommandEvent( (String) cmd.get("cmd"), ((Long) cmd.get("startTime")), ((Long) cmd.get("endTime")) )) .collect(Collectors.toList()); List<TimedEvent> events = value.keySet().stream() .filter((String name) -> !name.equals("commands")) .map((String name) -> { return new TimedEvent(name, (List<Long>) value.get(name)); }) .collect(Collectors.toList()); return new ServerEvents(commands, events, jsonData); }
Source:
<code>protected void tick(Block b) { Block fluid = b.getRelative(BlockFace.DOWN); Optional<ItemStack> bucket = getFilledBucket(fluid); if (bucket.isPresent() && getCharge(b.getLocation()) >= ENERGY_CONSUMPTION) { BlockMenu menu = BlockStorage.getInventory(b); for (int slot : getInputSlots()) { if (SlimefunUtils.isItemSimilar(menu.getItemInSlot(slot), new ItemStack(Material.BUCKET), true, false)) { if (!menu.fits(bucket.get(), getOutputSlots())) { return; } <START> Block consume = findFluid(fluid); <END> if (consume == null) return; removeCharge(b.getLocation(), ENERGY_CONSUMPTION); menu.consumeItem(slot); menu.pushItem(bucket.get().clone(), getOutputSlots()); consume.setType(Material.AIR); return; } } } }</code><technical_language>Please give this variable a more meaningful name. nextBlock maybe</technical_language>

Target:
protected void tick(Block b) { Block fluid = b.getRelative(BlockFace.DOWN); Optional<ItemStack> bucket = getFilledBucket(fluid); if (bucket.isPresent() && getCharge(b.getLocation()) >= ENERGY_CONSUMPTION) { BlockMenu menu = BlockStorage.getInventory(b); for (int slot : getInputSlots()) { if (SlimefunUtils.isItemSimilar(menu.getItemInSlot(slot), new ItemStack(Material.BUCKET), true, false)) { if (!menu.fits(bucket.get(), getOutputSlots())) { return; } Block nextFluid = findNextFluid(fluid); if (nextFluid == null) return; removeCharge(b.getLocation(), ENERGY_CONSUMPTION); menu.consumeItem(slot); menu.pushItem(bucket.get().clone(), getOutputSlots()); nextFluid.setType(Material.AIR); return; } } } }
Source:
<code>public Stream<RDF4JQuad> stream(Optional<BlankNodeOrIRI> graphName, BlankNodeOrIRI subject, IRI predicate, RDFTerm object) { Resource subj = (Resource) rdf4jTermFactory.asValue(subject); org.eclipse.rdf4j.model.IRI pred = (org.eclipse.rdf4j.model.IRI) rdf4jTermFactory.asValue(predicate); Value obj = rdf4jTermFactory.asValue(object); Resource[] contexts = asContexts(graphName); RepositoryConnection conn = getRepositoryConnection(); <START> RepositoryResult<Statement> statements = conn.getStatements(subj, pred, obj, includeInferred, contexts); <END> return Iterations.stream(statements).map(this::asTripleLike); }</code><technical_language>need reliably close this RepositoryResult in case iteration fails complete. try-with-resources RepositoryResult implements AutoCloseable</technical_language>

Target:
public Stream<RDF4JQuad> stream(Optional<BlankNodeOrIRI> graphName, BlankNodeOrIRI subject, IRI predicate, RDFTerm object) { Resource subj = (Resource) rdf4jTermFactory.asValue(subject); org.eclipse.rdf4j.model.IRI pred = (org.eclipse.rdf4j.model.IRI) rdf4jTermFactory.asValue(predicate); Value obj = rdf4jTermFactory.asValue(object); Resource[] contexts = asContexts(graphName); RepositoryConnection conn = getRepositoryConnection(); Stream<RDF4JQuad> stream = null; try { RepositoryResult<Statement> statements = conn.getStatements(subj, pred, obj, includeInferred, contexts); stream = Iterations.stream(statements).map(rdf4jTermFactory::asQuad); } finally { if (stream == null) { conn.close(); } } return stream.onClose(conn::close); }
Source:
<code>public void run() { log.info( <START> "Starting deletion of dangling service accounts ({})", this.getClass().getSimpleName()); <END> Set<String> serviceAccountsToKeep = pipelineDAO .all() .parallelStream() .flatMap( pipeline -> pipeline.getTriggers().stream() .map(trigger -> (String) trigger.get(RUN_AS_USER)) .filter(isManagedServiceAccount()) .distinct()) .collect(Collectors.toSet()); serviceAccountDAO .all() .parallelStream() .map(ServiceAccount::getName) .filter(isManagedServiceAccount()) .filter(serviceAccount -> !serviceAccountsToKeep.contains(serviceAccount)) .forEach(serviceAccountDAO::delete); }</code><technical_language>add a similar info block end notifies of completion</technical_language>

Target:
public void run() { log.info( "Starting deletion of dangling service accounts ({})", this.getClass().getSimpleName()); Set<String> serviceAccountsToKeep = pipelineDAO .all() .parallelStream() .flatMap( pipeline -> pipeline.getTriggers().stream() .map(trigger -> (String) trigger.get(RUN_AS_USER)) .filter(isManagedServiceAccount()) .distinct()) .collect(Collectors.toSet()); serviceAccountDAO .all() .parallelStream() .map(ServiceAccount::getName) .filter(isManagedServiceAccount()) .filter(serviceAccount -> !serviceAccountsToKeep.contains(serviceAccount)) .peek( serviceAccount -> log.info( "Deleting managed service account '{}' because it is not in use", serviceAccount)) .forEach(serviceAccountDAO::delete); log.info("Finished deletion of dangling service accounts "); }
Source:
<code>public boolean setExpiryPolicy(K key, ExpiryPolicy expiryPolicy) { if (isClusterVersionLessThan(Versions.V3_11)) { throw new UnsupportedOperationException("setExpiryPolicy operation is available" + "when cluster version is 3.11 or higher"); } try { ensureOpen(); validateNotNull(key); validateNotNull(expiryPolicy); Data keyData = serializationService.toData(key); Data expiryPolicyData = serializationService.toData(expiryPolicy); List<Data> list = Collections.singletonList(keyData); Operation operation = operationProvider.createSetExpiryPolicyOperation(list, expiryPolicyData); Future<Boolean> future = invoke(operation, keyData, true); return future.get(); <START> } catch (Exception e) { <END> throw rethrowAllowedTypeFirst(e, CacheException.class); } }</code><technical_language>catch Throwable</technical_language>

Target:
public boolean setExpiryPolicy(K key, ExpiryPolicy expiryPolicy) { if (isClusterVersionLessThan(Versions.V3_11)) { throw new UnsupportedOperationException("setExpiryPolicy operation is available" + "when cluster version is 3.11 or higher"); } try { ensureOpen(); validateNotNull(key); validateNotNull(expiryPolicy); Data keyData = serializationService.toData(key); Data expiryPolicyData = serializationService.toData(expiryPolicy); List<Data> list = Collections.singletonList(keyData); Operation operation = operationProvider.createSetExpiryPolicyOperation(list, expiryPolicyData); Future<Boolean> future = invoke(operation, keyData, true); return future.get(); } catch (Throwable e) { throw rethrowAllowedTypeFirst(e, CacheException.class); } }
Source:
<code>public BatchIterator<Row> apply(BatchIterator<Row> batchIterator) { return CollectingBatchIterator .newInstance(batchIterator, Collector.of( () -> new State(rowWriter), (state, row) -> { Object sysNodeCheckId = row.get(0); state.rowWriter.accept(sysNodeCheckId); SysNodeCheck sysNodeCheck = (SysNodeCheck) sysRowUpdater.getRow(sysNodeCheckId); <START> expressions.forEach(x -> x.setNextRow(sysNodeCheck)); <END> Object[] result = new Object[inputs.size()]; for (int i = 0; i < result.length; i++) { result[i] = inputs.get(i).value(); } state.resultRows.add(result); }, (state1, state2) -> { throw new UnsupportedOperationException( "Combine not supported"); }, state -> new CollectionBucket(state.resultRows) )); }</code><technical_language>current implementation / usage is safe. extract logic a class function. (To reduce amount of indentation here)</technical_language>

Target:
public BatchIterator<Row> apply(BatchIterator<Row> batchIterator) { return CollectingBatchIterator .newInstance(batchIterator, Collector.of( ArrayList<Object[]>::new, (acc, row) -> { Object[] returnValues = evaluateReturnValues(row); acc.add(returnValues); }, (state1, state2) -> { throw new UnsupportedOperationException( "Combine not supported"); }, CollectionBucket::new )); }
Source:
<code>private Map<String, Map<String, String>> parsePluginConfigValues( List<String> pluginConfigValues) throws UnloggedFailure { Map<String, Map<String, String>> m = new HashMap<>(); for (String pluginConfigValue : pluginConfigValues) { String[] s = pluginConfigValue.split("="); <START> if (s.length != 2) { throw new UnloggedFailure(1, "Invalid plugin config value '" + pluginConfigValue + "', expected format '<plugin-name>.<parameter-name>=<value>'"); } <END> String value = s[1]; s = s[0].split("\\."); if (s.length != 2) { throw new UnloggedFailure(1, "Invalid plugin config value '" + pluginConfigValue + "', expected format '<plugin-name>.<parameter-name>=<value>'"); } String pluginName = s[0]; String paramName = s[1]; Map<String, String> l = m.get(pluginName); if (l == null) { l = new HashMap<>(); m.put(pluginName, l); } l.put(paramName, value); } return m; }</code><technical_language>Code duplication</technical_language>

Target:
private Map<String, Map<String, String>> parsePluginConfigValues( List<String> pluginConfigValues) throws UnloggedFailure { Map<String, Map<String, String>> m = new HashMap<>(); for (String pluginConfigValue : pluginConfigValues) { String[] s = pluginConfigValue.split("="); String[] s2 = s[0].split("\\."); if (s.length != 2 || s2.length != 2) { throw new UnloggedFailure(1, "Invalid plugin config value '" + pluginConfigValue + "', expected format '<plugin-name>.<parameter-name>=<value>'"); } String value = s[1]; String pluginName = s2[0]; String paramName = s2[1]; Map<String, String> l = m.get(pluginName); if (l == null) { l = new HashMap<>(); m.put(pluginName, l); } l.put(paramName, value); } return m; }
Source:
<code>private Address makeAddress() { Address address = new Address(Locale.getDefault()); <START> ((ShadowAddress) ShadowExtractor.extract(address)).setSimulatedHasLatLong(hasLatitude, hasLongitude); <END> return address; }</code><technical_language>do need this change? prefer autogenerated Shadows.shadowOf()</technical_language>

Target:
private Address makeAddress() { Address address = new Address(Locale.getDefault()); address.setLatitude(simulatedLatitude); address.setLongitude(simulatedLongitude); ReflectionHelpers.setField(address, "mHasLatitude", hasLatitude); ReflectionHelpers.setField(address, "mHasLongitude", hasLongitude); return address; }
Source:
<code>public void saveAccessTokenResponse(@NonNull String handle, @Nullable AccessTokenResponse pAccessTokenResponse) { AccessTokenResponse accessTokenResponse = pAccessTokenResponse; String storageKeyAccessToken = ACCESS_TOKEN_RESPONSE.getKey(handle); if (accessTokenResponse == null) { accessTokenResponse = new AccessTokenResponse(); } AccessTokenResponse encryptedToken; try { encryptedToken = encryptToken(accessTokenResponse); } catch (GeneralSecurityException e) { <START> logger.error("Unable to encrypt token, storing as-is", e); <END> encryptedToken = accessTokenResponse; } storageFacade.put(handle, encryptedToken); }</code><technical_language>a fallback logic, a WARN enough</technical_language>

Target:
public void saveAccessTokenResponse(@NonNull String handle, @Nullable AccessTokenResponse pAccessTokenResponse) { AccessTokenResponse accessTokenResponse = pAccessTokenResponse; String storageKeyAccessToken = ACCESS_TOKEN_RESPONSE.getKey(handle); if (accessTokenResponse == null) { accessTokenResponse = new AccessTokenResponse(); } AccessTokenResponse encryptedToken; try { encryptedToken = encryptToken(accessTokenResponse); } catch (GeneralSecurityException e) { logger.warn("Unable to encrypt token, storing as-is", e); encryptedToken = accessTokenResponse; } storageFacade.put(handle, encryptedToken); }
Source:
<code>public CollectResultIterator( CompletableFuture<OperatorID> operatorIdFuture, TypeSerializer<T> serializer, String accumulatorName, CheckpointConfig checkpointConfig) { if (checkpointConfig.getCheckpointingMode() == CheckpointingMode.EXACTLY_ONCE) { if (checkpointConfig.getCheckpointInterval() >= CheckpointCoordinatorConfiguration.MINIMAL_CHECKPOINT_TIME) { this.fetcher = new CollectResultFetcher<>( new CheckpointedCollectResultBuffer<>(serializer), operatorIdFuture, accumulatorName); } else { <START> this.fetcher = new CollectResultFetcher<>( new UncheckpointedCollectResultBuffer<>(serializer, false), operatorIdFuture, accumulatorName); } <END> } else { this.fetcher = new CollectResultFetcher<>( new UncheckpointedCollectResultBuffer<>(serializer, true), operatorIdFuture, accumulatorName); } this.bufferedResult = null; }</code><technical_language>I this branch is unnecessary, illegal checkpoint interval is MINIMAL_CHECKPOINT_TIME, places validation, e.g. CheckpointConfig.setCheckpointInterval</technical_language>

Target:
public CollectResultIterator( CompletableFuture<OperatorID> operatorIdFuture, TypeSerializer<T> serializer, String accumulatorName, CheckpointConfig checkpointConfig) { AbstractCollectResultBuffer<T> buffer = createBuffer(serializer, checkpointConfig); this.fetcher = new CollectResultFetcher<>(buffer, operatorIdFuture, accumulatorName); this.bufferedResult = null; }
Source:
<code>private List<Map<String, String>> getTargets(Long hostId, long vmId) { List<Map<String, String>> targets = new ArrayList<>(); HostVO hostVO = _hostDao.findById(hostId); if (hostVO != null && hostVO.getHypervisorType() == HypervisorType.VMware) { List<VolumeVO> volumes = _volsDao.findByInstance(vmId); <START> if (volumes != null) { <END> for (VolumeVO volume : volumes) { StoragePoolVO storagePoolVO = _storagePoolDao.findById(volume.getPoolId()); if (storagePoolVO != null && storagePoolVO.isManaged()) { Map<String, String> target = new HashMap<>(); target.put(ModifyTargetsCommand.STORAGE_HOST, storagePoolVO.getHostAddress()); target.put(ModifyTargetsCommand.STORAGE_PORT, String.valueOf(storagePoolVO.getPort())); target.put(ModifyTargetsCommand.IQN, volume.get_iScsiName()); targets.add(target); } } } } return targets; }</code><technical_language>if invert this here? if (CollectionUtils.isEmpty(volumes)), return targets. This allow remove other for IF statement conditional. Rule of thumb: nested things, read</technical_language>

Target:
private List<Map<String, String>> getTargets(Long hostId, long vmId) { List<Map<String, String>> targets = new ArrayList<>(); HostVO hostVO = _hostDao.findById(hostId); if (hostVO == null || hostVO.getHypervisorType() != HypervisorType.VMware) { return targets; } List<VolumeVO> volumes = _volsDao.findByInstance(vmId); if (CollectionUtils.isEmpty(volumes)) { return targets; } for (VolumeVO volume : volumes) { StoragePoolVO storagePoolVO = _storagePoolDao.findById(volume.getPoolId()); if (storagePoolVO != null && storagePoolVO.isManaged()) { Map<String, String> target = new HashMap<>(); target.put(ModifyTargetsCommand.STORAGE_HOST, storagePoolVO.getHostAddress()); target.put(ModifyTargetsCommand.STORAGE_PORT, String.valueOf(storagePoolVO.getPort())); target.put(ModifyTargetsCommand.IQN, volume.get_iScsiName()); targets.add(target); } } return targets; }
Source:
<code>private void displayDirPage(FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-browser.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); getPathSegments(path, paths, segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); page.add("homedir", getHomeDir(fs)); try { FileStatus[] subdirs = fs.listStatus(path); page.add("subdirs", subdirs); long size = 0; for (int i = 0; i < subdirs.length; ++i) { if (subdirs[i].isDir()) { continue; } size += subdirs[i].getLen(); } page.add("dirsize", size); } catch (AccessControlException e) { <START> String error_message = props.getString("configurable.error.access.message"); <END> page.add("error_message", "Permission denied: " + error_message); page.add("no_fs", "true"); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); }</code><technical_language>Define key name in a central location a constant? Please follow config key naming conventions. new keys added for examples</technical_language>

Target:
private void displayDirPage(FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-browser.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); getPathSegments(path, paths, segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); page.add("homedir", getHomeDir(fs)); try { FileStatus[] subdirs = fs.listStatus(path); page.add("subdirs", subdirs); long size = 0; for (int i = 0; i < subdirs.length; ++i) { if (subdirs[i].isDir()) { continue; } size += subdirs[i].getLen(); } page.add("dirsize", size); } catch (AccessControlException e) { String error_message = props.getString(HDFSVIEWER_ACCESS_DENIED_MESSAGE); page.add("error_message", "Permission denied: " + error_message); page.add("no_fs", "true"); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); }
Source:
<code>public PluginOperationResult execute() throws OperationException { result.setAction(options.getAction()); switch (options.getAction()) { case LIST: try { <START> return executeList(); <END> } catch (DeserializableException | IOException e) { throw new OperationException(e); } case INSTALL: try { return executeInstall(); } catch (ChecksumMismatchException | UninstallablePluginException | IOException | CryptoException e) { throw new OperationException(e); } case REMOVE: try { return executeRemove(); } catch (PluginNotInstalledException | IOException e) { throw new OperationException(e); } case UPDATE: try { return executeUpdate(); } catch (DeserializableException | PluginException | IOException | CryptoException | ChecksumMismatchException e) { throw new OperationException(e); } default: throw new IllegalArgumentException("Unknown action: " + options.getAction()); } }</code><technical_language>DaemonOp: Awkward construction try/catch+switch/case</technical_language>

Target:
public PluginOperationResult execute() throws OperationException { result.setAction(options.getAction()); switch (options.getAction()) { case LIST: return executeList(); case INSTALL: return executeInstall(); case REMOVE: return executeRemove(); case UPDATE: return executeUpdate(); default: throw new IllegalArgumentException("Unknown action: " + options.getAction()); } }
Source:
<code>protected void refreshComponents() { <START> String reloadStrategy = Framework.getProperty(RELOAD_STRATEGY_PARAMETER, RELOAD_STRATEGY_VALUE_STANDBY); <END> if (log.isInfoEnabled()) { log.info("Refresh components. Strategy: " + reloadStrategy); } ComponentManager mgr = Framework.getRuntime().getComponentManager(); switch(reloadStrategy) { case RELOAD_STRATEGY_VALUE_UNSTASH: mgr.unstash(); break; case RELOAD_STRATEGY_VALUE_STANDBY: mgr.standby(); mgr.unstash(); mgr.resume(); break; case RELOAD_STRATEGY_VALUE_RESTART: default: mgr.refresh(false); break; } }</code><technical_language>I do: public static final String RELOAD_STRATEGY_VALUE_DEFAULT = RELOAD_STRATEGY_VALUE_STANDBY; ... Framework.getProperty(RELOAD_STRATEGY_PARAMETER, RELOAD_STRATEGY_VALUE_DEFAULT);</technical_language>

Target:
protected void refreshComponents() { String reloadStrategy = Framework.getProperty(RELOAD_STRATEGY_PARAMETER, RELOAD_STRATEGY_VALUE_DEFAULT); if (log.isInfoEnabled()) { log.info("Refresh components. Strategy: " + reloadStrategy); } ComponentManager mgr = Framework.getRuntime().getComponentManager(); switch(reloadStrategy) { case RELOAD_STRATEGY_VALUE_UNSTASH: mgr.unstash(); break; case RELOAD_STRATEGY_VALUE_STANDBY: mgr.standby(); mgr.unstash(); mgr.resume(); break; case RELOAD_STRATEGY_VALUE_RESTART: default: mgr.refresh(false); break; } }
Source:
<code>public static Map<String, Change> build(Repository repo) { try (TreeWalk tw = new TreeWalk(repo)) { tw.addTree(new DirCacheIterator(repo.readDirCache())); ObjectId headId = repo.resolve(HEAD); RevCommit headCommit; <START> if (headId != null) { try (RevWalk rw = new RevWalk(repo)) { headCommit = rw.parseCommit(headId); } } else { headCommit = null; } <END> AbbreviatedObjectId commitId; if (headCommit != null) { tw.addTree(headCommit.getTree()); commitId = AbbreviatedObjectId.fromObjectId(headCommit); } else { tw.addTree(new EmptyTreeIterator()); commitId =AbbreviatedObjectId.fromObjectId(zeroId()); } tw.setRecursive(true); headCommit = null; MutableObjectId idBuf = new MutableObjectId(); Map<String, Change> result = new HashMap<String, Change>(); while(tw.next()) { if (!shouldIncludeEntry(tw)) continue; Change change = new Change(); change.name = tw.getNameString(); change.remoteCommitId = commitId; tw.getObjectId(idBuf, 0); change.objectId = AbbreviatedObjectId.fromObjectId(idBuf); tw.getObjectId(idBuf, 1); change.remoteObjectId = AbbreviatedObjectId.fromObjectId(idBuf); calculateAndSetChangeKind(RIGHT, change); result.put(tw.getPathString(), change); } return result; } catch (IOException e) { Activator.error(e.getMessage(), e); return new HashMap<String, Change>(0); } }</code><technical_language>instead of complete if-else clause: RevCommit headCommit = null; if (headId != null) { try (RevWalk rw = new RevWalk(repo)) { headCommit = rw.parseCommit(headId); } }</technical_language>

Target:
public static Map<String, Change> build(Repository repo) { try (TreeWalk tw = new TreeWalk(repo)) { tw.addTree(new DirCacheIterator(repo.readDirCache())); ObjectId headId = repo.resolve(HEAD); RevCommit headCommit = null; if (headId != null) { try (RevWalk rw = new RevWalk(repo)) { headCommit = rw.parseCommit(headId); } } AbbreviatedObjectId commitId; if (headCommit != null) { tw.addTree(headCommit.getTree()); commitId = AbbreviatedObjectId.fromObjectId(headCommit); } else { tw.addTree(new EmptyTreeIterator()); commitId =AbbreviatedObjectId.fromObjectId(zeroId()); } tw.setRecursive(true); headCommit = null; MutableObjectId idBuf = new MutableObjectId(); Map<String, Change> result = new HashMap<String, Change>(); while(tw.next()) { if (!shouldIncludeEntry(tw)) continue; Change change = new Change(); change.name = tw.getNameString(); change.remoteCommitId = commitId; tw.getObjectId(idBuf, 0); change.objectId = AbbreviatedObjectId.fromObjectId(idBuf); tw.getObjectId(idBuf, 1); change.remoteObjectId = AbbreviatedObjectId.fromObjectId(idBuf); calculateAndSetChangeKind(RIGHT, change); result.put(tw.getPathString(), change); } return result; } catch (IOException e) { Activator.error(e.getMessage(), e); return new HashMap<String, Change>(0); } }
Source:
<code>protected void run() throws Exception { if ("split".equals(subtreeCmd)) { SubtreeSplitCommand split = new SubtreeSplitCommand(db); if (args != null) { for (String path : args) { split.addSplitPath(path); } } ObjectId head = db.resolve("HEAD"); if (rewriteAll) { split.setRewriteAll(); } else if (rewrite) { split.addCommitToRewrite(head); } split.setStart(head); SubtreeSplitResult result = split.call(); if (rewrite || rewriteAll) { out.println(result.getRewrittenCommits().get(head).name()); } for (SubtreeContext c : result.getSubtreeContexts()) { out.println(c.getSplitCommit(head).name() + " " + c.getId()); } } else { throw new CmdLineException(MessageFormat.format( <START> CLIText.get().notAJgitCommand, subtreeCmd)); <END> } }</code><technical_language>split is a subcommand of subtree, a jgit command itself, is misleading. stranger is do supply a subcommand</technical_language>

Target:
protected void run() throws Exception { if ("split".equals(subtreeCmd)) { SubtreeSplitCommand split = new SubtreeSplitCommand(db); if (args != null) { File workDir = db.getWorkTree(); if (workDir == null) { throw new CmdLineException( "No working directory, can not split paths"); } for (String path : args) { File dirCandidate = new File(path); if (!dirCandidate.isDirectory()) { throw new CmdLineException(dirCandidate + " is not a directory"); } split.addSplitPath(workDir.toURI() .relativize(dirCandidate.toURI()).getPath()); } } ObjectId head = db.resolve("HEAD"); if (rewriteAll) { split.setRewriteAll(); } else if (rewrite) { split.addCommitToRewrite(head); } split.setStart(head); SubtreeSplitResult result = split.call(); if (rewrite || rewriteAll) { out.println(result.getRewrittenCommits().get(head).name()); } for (SubtreeContext c : result.getSubtreeContexts().values()) { out.println(c.getSplitCommit(head).name() + " " + c.getId()); } } else { throw new CmdLineException(MessageFormat.format( CLIText.get().notAJgitCommand, subtreeCmd)); } }
Source:
<code>public AccountInfo getAccountInfo() throws IOException { Set<Wallet.WalletFeature> walletFeatures = new HashSet<>(); walletFeatures.add(Wallet.WalletFeature.FUNDING); walletFeatures.add(Wallet.WalletFeature.MARGIN_TRADING); KrakenTradeBalanceInfo krakenTradeBalanceInfo = getKrakenTradeBalance(); Wallet tradingWallet = KrakenAdapters.adaptWallet(getKrakenBalance()); Wallet marginWallet = Wallet.Builder.from(tradingWallet.getBalances().values()) .id("margin") <START> .features(walletFeatures) <END> .maxLeverage(BigDecimal.valueOf(5)) .currentLeverage(BigDecimal.valueOf(krakenTradeBalanceInfo.getCostBasis().doubleValue()/krakenTradeBalanceInfo.getTradeBalance().doubleValue())) .build(); return new AccountInfo(exchange.getExchangeSpecification().getUserName(), tradingWallet,marginWallet); }</code><technical_language>cleaner code do: .features(EnumSet.of(FUNDING, MARGIN_TRADING))</technical_language>

Target:
public AccountInfo getAccountInfo() throws IOException { KrakenTradeBalanceInfo krakenTradeBalanceInfo = getKrakenTradeBalance(); Wallet tradingWallet = KrakenAdapters.adaptWallet(getKrakenBalance()); Wallet marginWallet = Wallet.Builder.from(tradingWallet.getBalances().values()) .id("margin") .features(EnumSet.of(Wallet.WalletFeature.FUNDING, Wallet.WalletFeature.MARGIN_TRADING)) .maxLeverage(BigDecimal.valueOf(5)) .currentLeverage( (krakenTradeBalanceInfo.getTradeBalance().equals(BigDecimal.ZERO)) ? BigDecimal.ZERO : krakenTradeBalanceInfo .getCostBasis() .divide(krakenTradeBalanceInfo.getTradeBalance(), MathContext.DECIMAL32)) .build(); return new AccountInfo( exchange.getExchangeSpecification().getUserName(), tradingWallet, marginWallet); }
Source:
<code>public static DateTime of(String instant) { try { return new DateTime(instant, ISOChronology.getInstanceUTC()); } catch (IllegalArgumentException ex) { <START> return new DateTime(Long.valueOf(instant), ISOChronology.getInstanceUTC()); <END> } }</code><technical_language>This obscure original exception, reporting "java.lang.NumberFormatException: For input string" original DateTime String parsing exception. this instead: java try { return new DateTime(instant, ISOChronology.getInstanceUTC()); } catch (IllegalArgumentException ex) { try { return new DateTime(Long.valueOf(instant), ISOChronology.getInstanceUTC()); } catch (IllegalArgumentException ex2) { // Throw original exception, is more meaningful user. throw ex; } }</technical_language>

Target:
public static DateTime of(String instant) { try { return new DateTime(instant, ISOChronology.getInstanceUTC()); } catch (IllegalArgumentException ex) { try { return new DateTime(Long.valueOf(instant), ISOChronology.getInstanceUTC()); } catch (IllegalArgumentException ex2) { throw ex; } } }
Source:
<code>public String format() { try { this.props.load( Thread.currentThread().getContextClassLoader() .getResourceAsStream(this.name) ); } catch (final IOException ex) { throw new IllegalStateException( <START> "IOException when loading jcabigithub.properties", <END> ex ); } return String.format( "jcabi-github %s %s %s", this.props.getProperty(FromProperties.JCABI_VERSION), this.props.getProperty(FromProperties.JCABI_BUILD), this.props.getProperty(FromProperties.JCABI_DATE) ); }</code><technical_language>@amihaiemil file's name this.name</technical_language>

Target:
public String format() { try { this.props.load( Thread.currentThread().getContextClassLoader() .getResourceAsStream(this.name) ); } catch (final IOException ex) { throw new IllegalStateException( String.format("IOException when loading %s", this.name), ex ); } return String.format( "jcabi-github %s %s %s", this.props.getProperty(FromProperties.JCABI_VERSION), this.props.getProperty(FromProperties.JCABI_BUILD), this.props.getProperty(FromProperties.JCABI_DATE) ); }
Source:
<code>public void testPutNodeReferenceObjectType() { for (Storage storage : TestConfig.STORAGES_TO_TEST_AGAINST) { <START> storage.createNode().put(Mods.NAME, storage.createLeaf("Wilhelm Busch", "de")); <END> } }</code><technical_language>testing here</technical_language>

Target:
public void testPutNodeReferenceObjectType() { for (Storage storage : TestConfig.STORAGES_TO_TEST_AGAINST) { storage.createNode().put(MODS_NAME, storage.createLeaf("Wilhelm Busch", "de")); } }
Source:
<code>private void onHistoryAdded() { if (fullHistSize.incrementAndGet() > MAX_HIST_SIZE) { <START> Iterator<HistoryAffinityAssignment> it = affCache.values().iterator(); <END> int rmvCnt = MAX_HIST_SIZE / 2; Collection<AffinityTopologyVersion> topVerRmv = new HashSet<>(rmvCnt); while (it.hasNext() && rmvCnt > 0) { AffinityAssignment aff0 = it.next(); it.remove(); rmvCnt--; fullHistSize.decrementAndGet(); topVerRmv.add(aff0.topologyVersion()); } ctx.affinity().removeCachedAffinity(topVerRmv); } }</code><technical_language>code style, blank lines code lines { } block</technical_language>

Target:
private void onHistoryAdded() { if (fullHistSize.incrementAndGet() > MAX_HIST_SIZE) { Iterator<HistoryAffinityAssignment> it = affCache.values().iterator(); int rmvCnt = MAX_HIST_SIZE / 2; AffinityTopologyVersion topVerRmv = null; while (it.hasNext() && rmvCnt > 0) { AffinityAssignment aff0 = it.next(); it.remove(); rmvCnt--; fullHistSize.decrementAndGet(); topVerRmv = aff0.topologyVersion(); } topVerRmv = it.hasNext() ? it.next().topologyVersion() : topVerRmv; ctx.affinity().removeCachedAffinity(topVerRmv); } }
Source:
<code>public void filter(ContainerRequestContext requestContext) throws IOException { String path = Optional.ofNullable(uriInfo) .flatMap(info -> Optional.ofNullable(info.getMatchedModelResource())) <START> .flatMap(resource -> Optional.ofNullable(resource.getPath())) <END> .orElse("(unknown)"); String operation = requestContext.getMethod() + " " + path; String traceId = requestContext.getHeaderString(TraceHttpHeaders.TRACE_ID); String spanId = requestContext.getHeaderString(TraceHttpHeaders.SPAN_ID); if (Strings.isNullOrEmpty(traceId)) { Tracer.initTrace(Optional.empty(), Tracers.randomId()); Tracer.startSpan(operation, SpanType.SERVER_INCOMING); } else { Tracer.initTrace(hasSampledHeader(requestContext), traceId); if (spanId == null) { Tracer.startSpan(operation, SpanType.SERVER_INCOMING); } else { Tracer.startSpan(operation, spanId, SpanType.SERVER_INCOMING); } } requestContext.setProperty("com.palantir.remoting3.traceId", Tracer.getTraceId()); }</code><technical_language>Optional#map. returns empty optional mapping function returns null</technical_language>

Target:
public void filter(ContainerRequestContext requestContext) throws IOException { String path = Optional.ofNullable(uriInfo) .map(ExtendedUriInfo::getMatchedModelResource) .map(Resource::getPath) .orElse("(unknown)"); String operation = requestContext.getMethod() + " " + path; String traceId = requestContext.getHeaderString(TraceHttpHeaders.TRACE_ID); String spanId = requestContext.getHeaderString(TraceHttpHeaders.SPAN_ID); if (Strings.isNullOrEmpty(traceId)) { Tracer.initTrace(Optional.empty(), Tracers.randomId()); Tracer.startSpan(operation, SpanType.SERVER_INCOMING); } else { Tracer.initTrace(hasSampledHeader(requestContext), traceId); if (spanId == null) { Tracer.startSpan(operation, SpanType.SERVER_INCOMING); } else { Tracer.startSpan(operation, spanId, SpanType.SERVER_INCOMING); } } requestContext.setProperty("com.palantir.remoting3.traceId", Tracer.getTraceId()); }
Source:
<code>public void onDisconnect(IClient client) { try{ <START> KalturaEntryIdKey entryIdKey = null; <END> WMSProperties properties = client.getProperties(); synchronized (properties) { entryIdKey = (KalturaEntryIdKey) properties.getProperty(Constants.KALTURA_ENTRY_DATA_PERSISTENCY_KEY); } KalturaLiveEntry liveEntry = (KalturaLiveEntry) KalturaStreamsDataPersistence.getEntry(entryIdKey, Constants.CLIENT_PROPERTY_KALTURA_LIVE_ENTRY, String.valueOf(client.getClientId())); logger.info("Entry removed [" + liveEntry.id + "]"); } catch (Exception e){ logger.info("Error" + e.getMessage()); } }</code><technical_language>suppose remove KALTURA_ENTRY_DATA_PERSISTENCY_KEY this code</technical_language>

Target:
public void onDisconnect(IClient client) { try{ WMSProperties properties = client.getProperties(); String entryId = Utils.getEntryIdFromClient(client); synchronized (properties) { properties.setProperty(Constants.KALTURA_ENTRY_DATA_PERSISTENCY_KEY, null); } logger.info("Entry removed [" + entryId + "]"); } catch (Exception e){ logger.info("Error" + e.getMessage()); } }
Source:
<code>public boolean close(int waitForShutdownTimeoutMs) throws InterruptedException { close(); <START> if (waitForShutdownTimeoutMs > 0) { <END> return testableWaitForShutdown(waitForShutdownTimeoutMs); } return false; }</code><technical_language>I this check is needed - actually, sounds remove this check a negative trigger illegal argument exception is wrong in upstream code, hard if negative is passed purpose, is accident</technical_language>

Target:
public boolean close(int waitForShutdownTimeoutMs) throws InterruptedException { close(); return testableWaitForShutdown(waitForShutdownTimeoutMs); }
Source:
<code>protected void executeQueryCommand() { List<ExtensionProxy> extensions = getExtensionsManager().getExtensionsByService(Authz.class.getName()); List<String> names = new ArrayList<>(extensions.size()); for (ExtensionProxy extension : extensions) { names.add(AuthzUtils.getName(extension)); } if (getParameters().getFilterInternalDomain()) { <START> names.remove(INTERNAL); <END> } sort(names); getQueryReturnValue().setReturnValue(names); }</code><technical_language>do remove internal? internal other</technical_language>

Target:
protected void executeQueryCommand() { List<ExtensionProxy> extensions = getExtensionsManager().getExtensionsByService(Authz.class.getName()); List<String> names = new ArrayList<>(extensions.size()); for (ExtensionProxy extension : extensions) { names.add(AuthzUtils.getName(extension)); } sort(names); getQueryReturnValue().setReturnValue(names); }
Source:
<code>public double ticsCalc(int pixelDistance, RectangleWrap field, double deltaRange) { double noTicks = field.height / pixelDistance; double delta = (deltaRange) / noTicks, <START> dec = Math.floor(Math.log(delta) / Math.log(10)); <END> double magn = Math.pow(10, dec), norm = delta / magn; double size; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; if (norm > 2.25) { size = 2.5; } } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; Timber.d("ChartBuilder ticksCalc : pixelDistance: %d, ticks: %,.2f, deltaRange: %,.2f, height: %d", pixelDistance, size, deltaRange, field.height); return size; }</code><technical_language>do this in AnkiDroid code, please change do double delta = double dec =? for other variables</technical_language>

Target:
public double ticsCalc(int pixelDistance, RectangleWrap field, double deltaRange) { double numTicks = field.height / pixelDistance; double delta = deltaRange / numTicks; double dec = Math.floor(Math.log(delta) / Math.log(10)); double magn = Math.pow(10, dec); double norm = delta / magn; double size; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; if (norm > 2.25) { size = 2.5; } } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; Timber.d("ChartBuilder ticksCalc : pixelDistance: %d, ticks: %,.2f, deltaRange: %,.2f, height: %d", pixelDistance, size, deltaRange, field.height); return size; }