auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { if (!AcidUtils.isAcidEnabled(context.hiveConf)) { context.log.error("Cannot load alloc write id event as acid is not enabled"); throw new SemanticException("Cannot load alloc write id event as acid is not enabled"); } AllocWriteIdMessage msg = deserializer.getAllocWriteIdMessage(context.dmd.getPayload()); String dbName = (context.dbName != null && !context.dbName.isEmpty() ? context.dbName : msg.getDbName()); String tableName = (context.tableName != null && !context.tableName.isEmpty() ? context.tableName : msg .getTableName()); Table tbl; try { tbl = context.db.getTable(dbName, tableName); } catch (InvalidTableException e) { <START> return new ArrayList<>(); <END> } catch (HiveException e) { throw new SemanticException("Cannot load alloc write id event as get table failed with error: " + e.getMessage()); } Map<String, String> params = tbl.getParameters(); if (params != null && (params.containsKey(ReplicationSpec.KEY.CURR_STATE_ID.toString()))) { String replLastId = params.get(ReplicationSpec.KEY.CURR_STATE_ID.toString()); if (Long.parseLong(replLastId) >= context.dmd.getEventTo()) { return new ArrayList<>(); } } ReplTxnWork work = new ReplTxnWork(dbName, context.tableName, ReplTxnWork.OperationType.REPL_ALLOC_WRITE_ID, msg.getTxnToWriteIdList()); work.setTableName(tableName); Task<? extends Serializable> allocWriteIdTask = TaskFactory.get(work, context.hiveConf); context.log.info("Added alloc write id task : {}", allocWriteIdTask.getId()); updatedMetadata.set(context.dmd.getEventTo().toString(), dbName, tableName, null); return Collections.singletonList(allocWriteIdTask); }</code><technical_language>If current dump create table allocate write id events, this table object missing in metastore. this is a valid scenario need allocate write id. refer repl ID if database object decide this</technical_language>

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { if (!AcidUtils.isAcidEnabled(context.hiveConf)) { context.log.error("Cannot load alloc write id event as acid is not enabled"); throw new SemanticException("Cannot load alloc write id event as acid is not enabled"); } AllocWriteIdMessage msg = deserializer.getAllocWriteIdMessage(context.dmd.getPayload()); String dbName = (context.dbName != null && !context.dbName.isEmpty() ? context.dbName : msg.getDB()); String tableName = (context.tableName != null && !context.tableName.isEmpty() ? context.tableName : msg .getTableName()); ReplTxnWork work = new ReplTxnWork(HiveUtils.getReplPolicy(dbName, context.tableName), dbName, tableName, ReplTxnWork.OperationType.REPL_ALLOC_WRITE_ID, msg.getTxnToWriteIdList(), context.eventOnlyReplicationSpec()); Task<? extends Serializable> allocWriteIdTask = TaskFactory.get(work, context.hiveConf); context.log.info("Added alloc write id task : {}", allocWriteIdTask.getId()); updatedMetadata.set(context.dmd.getEventTo().toString(), dbName, tableName, null); return Collections.singletonList(allocWriteIdTask); }
Source:
<code>public Collection<ColumnMeta> getOrderedColumns() { if (needCreator) { <START> List<String> params = new ArrayList<String>(); <END> List<ColumnMeta> orderedColumns = new ArrayList<ColumnMeta>(Collections.<ColumnMeta>nCopies(columns.size(), null)); for (VariableElement param : creator.getParameters()) { params.add(param.getSimpleName().toString()); } for (ColumnMeta column : columns.values()) { orderedColumns.set(params.indexOf(column.getRealElementName()), column); } return orderedColumns; } else { return columns.values(); } }</code><technical_language>add capacity for params</technical_language>

Target:
public Collection<ColumnMeta> getOrderedColumns() { if (needCreator) { List<String> params = new ArrayList<String>(columns.size()); List<ColumnMeta> orderedColumns = new ArrayList<ColumnMeta>(Collections.<ColumnMeta>nCopies(columns.size(), null)); for (VariableElement param : creator.getParameters()) { params.add(param.getSimpleName().toString()); } for (ColumnMeta column : columns.values()) { orderedColumns.set(params.indexOf(column.getRealElementName()), column); } return orderedColumns; } else { return columns.values(); } }
Source:
<code>public long[] transformToLongValuesSV(ProjectionBlock projectionBlock) { int[] selected = getSelectedArray(projectionBlock); long[] results = new long[DocIdSetPlanNode.MAX_DOC_PER_CALL]; for (int i = 0; i < _elseThenStatements.size(); i++) { TransformFunction transformFunction = _elseThenStatements.get(i); FieldSpec.DataType dataType = transformFunction.getResultMetadata().getDataType(); switch (dataType) { case INT: int[] evalInts = transformFunction.transformToIntValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = evalInts[j]; } } break; case LONG: long[] evalLongs = transformFunction.transformToLongValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { <START> results[j] = evalLongs[j]; <END> } } break; case FLOAT: float[] evalFloats = transformFunction.transformToFloatValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = (long) evalFloats[j]; } } break; case DOUBLE: double[] evalDoubles = transformFunction.transformToDoubleValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = (long) evalDoubles[j]; } } break; case STRING: String[] evalStrings = transformFunction.transformToStringValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = new BigDecimal(evalStrings[i]).longValue(); } } break; default: throw new IllegalStateException(String .format("Cannot convert result type [%s] to [LONG] for transform function [%s]", dataType, transformFunction)); } } return results; }</code><technical_language>check result metadata if is INT, call super. transformToIntValuesSV() do type casting. for other methods. need a separate switch method</technical_language>

Target:
public long[] transformToLongValuesSV(ProjectionBlock projectionBlock) { if (_resultMetadata.getDataType() != FieldSpec.DataType.LONG) { return super.transformToLongValuesSV(projectionBlock); } int[] selected = getSelectedArray(projectionBlock); if (_longResults == null) { _longResults = new long[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } for (int i = 0; i < _elseThenStatements.size(); i++) { TransformFunction transformFunction = _elseThenStatements.get(i); FieldSpec.DataType dataType = transformFunction.getResultMetadata().getDataType(); int blockNumDocs = projectionBlock.getNumDocs(); long[] evalLongs; if (dataType == FieldSpec.DataType.LONG) { evalLongs = transformFunction.transformToLongValuesSV(projectionBlock); } else { evalLongs = new long[blockNumDocs]; ArrayCopyUtils.copy(transformFunction.transformToIntValuesSV(projectionBlock), evalLongs, blockNumDocs); } for (int j = 0; j < blockNumDocs; j++) { if (selected[j] == i) { _longResults[j] = evalLongs[j]; } } } return _longResults; }
Source:
<code>String getMatchIdxFileName(@NonNull String moduleName) { <START> return ("dld_match_" + moduleName + ".idx").toLowerCase(); <END> }</code><technical_language>more efficient case moduleName</technical_language>

Target:
String getMatchIdxFileName(@NonNull String moduleName) { return "dld_match_" + moduleName.toLowerCase() + ".idx"; }
Source:
<code>private byte[] _save() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); HashMap<String,Integer> symbolTable = new HashMap<>(); ArrayList<String> symbols = new ArrayList<>(); for (LgBuilder lg : locGroups) { for (SummaryInfo si : lg.summaries) { for (String symbol : si.summary.keySet()) { if (!symbolTable.containsKey(symbol)) { symbolTable.put(symbol, symbols.size()); symbols.add(symbol); } } } } WritableUtils.writeVInt(dos, symbols.size()); for (String symbol : symbols) { dos.writeUTF(symbol); } WritableUtils.writeVInt(dos, locGroups.size()); for (LgBuilder lg : locGroups) { lg.save(dos, symbolTable); } <START> dos.close(); <END> return baos.toByteArray(); }</code><technical_language>try/finally (even matter)</technical_language>

Target:
private byte[] _save() throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos)) { HashMap<String,Integer> symbolTable = new HashMap<>(); ArrayList<String> symbols = new ArrayList<>(); for (LgBuilder lg : locGroups) { for (SummaryInfo si : lg.summaries) { for (String symbol : si.summary.keySet()) { if (!symbolTable.containsKey(symbol)) { symbolTable.put(symbol, symbols.size()); symbols.add(symbol); } } } } WritableUtils.writeVInt(dos, symbols.size()); for (String symbol : symbols) { dos.writeUTF(symbol); } WritableUtils.writeVInt(dos, locGroups.size()); for (LgBuilder lg : locGroups) { lg.save(dos, symbolTable); } dos.close(); return baos.toByteArray(); } }
Source:
<code>public boolean createHook() { if (ghRepository == null) { logger.log(Level.INFO, "Repository not available, cannot set pull request hook for repository {0}", reponame); return false; } try { if (hookExist()) { return true; } Map<String, String> config = new HashMap<String, String>(); String secret = getSecret(); config.put("url", new URL(getHookUrl()).toExternalForm()); config.put("insecure_ssl", "1"); if (secret != null && !secret.equals("")) { <START> config.put("secret", secret); <END> } ghRepository.createHook("web", config, HOOK_EVENTS, true); return true; } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn''t create web hook for repository {0}. Does the user (from global configuration) have admin rights to the repository?", reponame); return false; } }</code><technical_language>preference is StringUtils.isEmpty()</technical_language>

Target:
public boolean createHook() { if (ghRepository == null) { logger.log(Level.INFO, "Repository not available, cannot set pull request hook for repository {0}", reponame); return false; } try { if (hookExist()) { return true; } Map<String, String> config = new HashMap<String, String>(); String secret = getSecret(); config.put("url", new URL(getHookUrl()).toExternalForm()); config.put("insecure_ssl", "1"); if (!StringUtils.isEmpty(secret)) { config.put("secret", secret); } ghRepository.createHook("web", config, HOOK_EVENTS, true); return true; } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn''t create web hook for repository {0}. Does the user (from global configuration) have admin rights to the repository?", reponame); return false; } }
Source:
<code>@Override public boolean canHandleSource(@NonNull BufferedSource source) { try { if (Utils.isWebPFile(source)) { return true; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(source.peek().inputStream(), null, options); return options.outWidth > 0 && options.outHeight > 0; } catch (IOException e) { <START> return false; <END> } }</code><technical_language>mmm, i this method true. I/O problem other able handle request</technical_language>

Target:
@Override public boolean canHandleSource(@NonNull BufferedSource source) { try { if (Utils.isWebPFile(source)) { return true; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(source.inputStream(), null, options); return options.outWidth > 0 && options.outHeight > 0; } catch (IOException e) { return false; } }
Source:
<code>private String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table, String simpleName) { logger.debug("JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}", filter.toString(), numberDecimalcount, table, simpleName); <START> SimpleDateFormat jdbcDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); <END> String filterString = ""; if (filter.getBeginDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME>'" + jdbcDateFormat.format(filter.getBeginDate()) + "'"; } if (filter.getEndDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME<'" + jdbcDateFormat.format(filter.getEndDate().getTime()) + "'"; } filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC"; if (filter.getPageSize() != 0x7fffffff) { filterString += " OFFSET " + filter.getPageNumber() * filter.getPageSize() + " LIMIT " + filter.getPageSize(); } String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1 ? "SELECT time, ROUND(CAST (value AS numeric)," + numberDecimalcount + ") FROM " + table : "SELECT time, value FROM " + table; if (!filterString.isEmpty()) { queryString += filterString; } logger.debug("JDBC::query queryString = {}", queryString); return queryString; }</code><technical_language>This DateFormat object changes. static final in class scope save a bit of performance</technical_language>

Target:
private String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table, String simpleName) { logger.debug( "JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}", filter.toString(), numberDecimalcount, table, simpleName); String filterString = ""; if (filter.getBeginDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME>'" + jdbcDateFormat.print(new DateTime(filter.getBeginDate().getTime())) + "'"; } if (filter.getEndDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME<'" + jdbcDateFormat.print(new DateTime(filter.getEndDate().getTime())) + "'"; } filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC"; if (filter.getPageSize() != 0x7fffffff) { filterString += " OFFSET " + filter.getPageNumber() * filter.getPageSize() + " LIMIT " + filter.getPageSize(); } String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1 ? "SELECT time, ROUND(CAST (value AS numeric)," + numberDecimalcount + ") FROM " + table : "SELECT time, value FROM " + table; if (!filterString.isEmpty()) { queryString += filterString; } logger.debug("JDBC::query queryString = {}", queryString); return queryString; }
Source:
<code>private String buildConnectorUri(Account account, String path) { <START> return buildConnectorUri(account, path, Maps.newHashMap()); <END> }</code><technical_language>I Collections.emptyMap() work</technical_language>

Target:
private String buildConnectorUri(Account account, String path) { return buildConnectorUri(account, path, Collections.emptyMap()); }
Source:
<code>public void terminate(int count) throws IllegalStateException{ if (count > addresses.size()) { count = addresses.size(); } echoImportant(format("Terminating %s %s machines (can take some time)", count, props.get("CLOUD_PROVIDER"))); echo("Current number of machines: " + addresses.size()); echo("Desired number of machines: " + (addresses.size() - count)); long startMs = System.currentTimeMillis(); ComputeService compute = new ComputeServiceBuilder(props).build(); int destroyedCount=0; for (int batchSize : calcBatches(count)) { final Map<String, AgentAddress> terminateMap = new HashMap<String, AgentAddress>(); for (AgentAddress address : addresses.subList(0, batchSize)) { terminateMap.put(address.publicAddress, address); } destroyedCount += destroyNodes(compute, terminateMap); } log.info("Updating " + agentsFile.getAbsolutePath()); AgentsFile.save(agentsFile, addresses); long durationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startMs); echo("Duration: " + secondsToHuman(durationSeconds)); echoImportant("Terminated %s of %s, remaining=%s", destroyedCount, count, addresses.size()); if(destroyedCount!=count){ <START> throw new IllegalStateException("Terminated "+destroyedCount+" of "+count); <END> } }</code><technical_language>a nicer explanation appreciated. hints wrong. (Harakiri? else?)</technical_language>

Target:
public void terminate(int count){ if (count > addresses.size()) { count = addresses.size(); } echoImportant(format("Terminating %s %s machines (can take some time)", count, props.get("CLOUD_PROVIDER"))); echo("Current number of machines: " + addresses.size()); echo("Desired number of machines: " + (addresses.size() - count)); long startMs = System.currentTimeMillis(); ComputeService compute = new ComputeServiceBuilder(props).build(); int destroyedCount=0; for (int batchSize : calcBatches(count)) { final Map<String, AgentAddress> terminateMap = new HashMap<String, AgentAddress>(); for (AgentAddress address : addresses.subList(0, batchSize)) { terminateMap.put(address.publicAddress, address); } destroyedCount += destroyNodes(compute, terminateMap); } log.info("Updating " + agentsFile.getAbsolutePath()); AgentsFile.save(agentsFile, addresses); long durationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startMs); echo("Duration: " + secondsToHuman(durationSeconds)); echoImportant("Terminated %s of %s, remaining=%s", destroyedCount, count, addresses.size()); if(destroyedCount!=count){ throw new IllegalStateException("Terminated "+destroyedCount+" of "+count+ "\n1) You are trying to terminate physical hardware that you own (unsupported feature)"+ "\n2) if and only if you are using AWS, our Harakiri Monitor might have terminated them"+ "\n3) You have not payed you bill and your instances have been terminated by your provider"+ "\n4) You have terminated our own instances perhaps vai some console interface"+ "\n5) Someone else has terminated your instances"+ "\n5) elves ?"+ "\n5) try again"); } }
Source:
<code>public <T> T data(LightblueRequest lightblueRequest, Class<T> type) throws IOException { try{ LightblueResponse response = data(lightblueRequest); JsonNode objectNode = response.getJson().path("processed"); try { return mapper.readValue(objectNode.traverse(), type); <START> } catch (JsonMappingException e) { <END> throw new RuntimeException("Error parsing lightblue response: " + response.getJson().toString(), e); } } catch(RuntimeException e){ throw new LightblueHttpClientException("Error sending lightblue request: " + lightblueRequest.getBody(), e); } }</code><technical_language>this caught handled in outer try/catch? overhead creating exception. In this case, exception is caught wrapped in another exception</technical_language>

Target:
public <T> T data(LightblueRequest lightblueRequest, Class<T> type) throws IOException { LightblueResponse response = null; try{ response = data(lightblueRequest); JsonNode objectNode = response.getJson().path("processed"); return mapper.readValue(objectNode.traverse(), type); } catch(RuntimeException | JsonMappingException e) { StringBuilder buff = new StringBuilder(); if (e instanceof JsonMappingException) { buff.append("Error parsing lightblue response: " + ((response == null) ? "null" : response.getJson().toString() + "\n")); } buff.append("Error sending lightblue request: " + lightblueRequest.getBody()); throw new LightblueHttpClientException(buff.toString(), e); } }
Source:
<code>public List<ResourceState> getResourcesState(PerunSession session, Vo vo) throws PrivilegeException, VoNotExistsException, InternalErrorException { <START> TaskManager taskManager = new TaskManagerImpl(); <END> List<Resource> resources = perun.getResourcesManager().getResources(session, vo); List<ResourceState> resourceStateList = new ArrayList<ResourceState>(); for (Resource resource : resources) { List<Task> taskList = taskManager.listAllTasksForFacility(resource.getFacilityId()); END tasks Iterator<Task> iterator = taskList.iterator(); while (iterator.hasNext()) { if ( !(iterator.next().getExecService().getExecServiceType().name().equals("SEND")) ) { iterator.remove(); } } ResourceState resourceState = new ResourceState(); resourceState.setResource(resource); resourceState.setTaskList(taskList); resourceStateList.add(resourceState); } return resourceStateList; }</code><technical_language>dependencies injection for tasks. e.g.: @Autowired private TaskManager taskManager;</technical_language>

Target:
public List<ResourceState> getResourcesState(PerunSession session, Vo vo) throws PrivilegeException, VoNotExistsException, InternalErrorException { List<Resource> resources = perun.getResourcesManager().getResources(session, vo); List<ResourceState> resourceStateList = new ArrayList<ResourceState>(); for (Resource resource : resources) { List<Task> taskList = taskManager.listAllTasksForFacility(resource.getFacilityId()); END tasks Iterator<Task> iterator = taskList.iterator(); while (iterator.hasNext()) { if ( !(iterator.next().getExecService().getExecServiceType().equals(ExecService.ExecServiceType.SEND)) ) { iterator.remove(); } } ResourceState resourceState = new ResourceState(); resourceState.setResource(resource); resourceState.setTaskList(taskList); resourceStateList.add(resourceState); } return resourceStateList; }
Source:
<code>public synchronized double getDuration() { <START> return (fEndTime - fStartTime) / 1000000000.0; <END> }</code><technical_language>matter, static defines for those, private static final double NANOSECONDS_IN_SECONDS = ... prevent easy mistakes zero</technical_language>

Target:
public synchronized double getDuration() { return (fEndTime - fStartTime) / SECOND_TO_NANOSECOND; }
Source:
<code>public Object get(String key) throws JSONException { if (key == null) { } Object object = this.opt(key); if (object == null) { <START> } <END> return object; }</code><technical_language>org/json library. Edits this recommended</technical_language>

Target:
public Object get(String key) throws JSONException { if (key == null) { throw new JSONException("Null key."); } Object object = this.opt(key); if (object == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return object; }
Source:
<code>public static void closeIfNeeded(Handle handle) { <START> if (UNMANAGED_HANDLES.contains(handle)) <END> { handle.close(); } }</code><technical_language>this a memory leak, this remove</technical_language>

Target:
public static void closeIfNeeded(Handle handle) { if (UNMANAGED_HANDLES.contains(handle)) { try { handle.close(); } finally { UNMANAGED_HANDLES.remove(handle); } } }
Source:
<code>public ServerEndpointMetadata getServerEndpointMetadata(final Class<?> endpoint, final ServerEndpointConfig config) throws DeploymentException { try { ServerEndpointMetadata metadata; ServerEndpoint anno = endpoint.getAnnotation(ServerEndpoint.class); if (anno != null) { AnnotatedServerEndpointMetadata ametadata = new AnnotatedServerEndpointMetadata(this, endpoint, config); AnnotatedEndpointScanner<ServerEndpoint, ServerEndpointConfig> scanner = new AnnotatedEndpointScanner<>(ametadata); metadata = ametadata; scanner.scan(); } else if (Endpoint.class.isAssignableFrom(endpoint)) { @SuppressWarnings("unchecked") Class<? extends Endpoint> eendpoint = (Class<? extends Endpoint>)endpoint; metadata = new SimpleServerEndpointMetadata(eendpoint, config); } else { <START> throw new DeploymentException("Unable to identify as valid Endpoint: " + endpoint); <END> } return metadata; } catch (RuntimeException e) { throw new DeploymentException(e.getMessage(), e); } }</code><technical_language>Please long form exception message here. (see lines 214 219 code)</technical_language>

Target:
public ServerEndpointMetadata getServerEndpointMetadata(final Class<?> endpoint, final ServerEndpointConfig config) throws DeploymentException { try { ServerEndpointMetadata metadata; ServerEndpoint anno = endpoint.getAnnotation(ServerEndpoint.class); if (anno != null) { AnnotatedServerEndpointMetadata ametadata = new AnnotatedServerEndpointMetadata(this, endpoint, config); AnnotatedEndpointScanner<ServerEndpoint, ServerEndpointConfig> scanner = new AnnotatedEndpointScanner<>(ametadata); metadata = ametadata; scanner.scan(); } else if (Endpoint.class.isAssignableFrom(endpoint)) { @SuppressWarnings("unchecked") Class<? extends Endpoint> eendpoint = (Class<? extends Endpoint>)endpoint; metadata = new SimpleServerEndpointMetadata(eendpoint, config); } else { String err = "Not a recognized websocket [" + endpoint.getName() + "] does not extend @" + ServerEndpoint.class.getName() + " or extend from " + Endpoint.class.getName(); throw new DeploymentException(err); } return metadata; } catch (DeploymentException e) { throw e; } catch (Throwable t) { throw new DeploymentException(t.getMessage(), t); } }
Source:
<code>public Container and(BitmapContainer x) { int card = this.getCardinality(); if (card <= ArrayContainer.DEFAULT_MAX_SIZE) { if (card > x.cardinality) { card = x.cardinality; } ArrayContainer answer = new ArrayContainer(card); answer.cardinality = 0; for (int rlepos = 0; rlepos < this.nbrruns; ++rlepos) { int runStart = Util.toIntUnsigned(this.getValue(rlepos)); int runEnd = runStart + Util.toIntUnsigned(this.getLength(rlepos)); for (int runValue = runStart; runValue <= runEnd; ++runValue) { if (x.contains((short) runValue)) { answer.content[answer.cardinality++] = (short) runValue; } } } return answer; } BitmapContainer answer = x.clone(); int start = 0; for (int rlepos = 0; rlepos < this.nbrruns; ++rlepos) { int end = Util.toIntUnsigned(this.getValue(rlepos)); int prevOnes = Util.cardinalityInBitmapRange(answer.bitmap, start, end); Util.resetBitmapRange(answer.bitmap, start, end); answer.updateCardinality(prevOnes, 0); start = end + Util.toIntUnsigned(this.getLength(rlepos)) + 1; } int ones = Util.cardinalityInBitmapRange(answer.bitmap, start, BitmapContainer.MAX_CAPACITY); <START> Util.resetBitmapRange(answer.bitmap, start, BitmapContainer.MAX_CAPACITY); END> answer.updateCardinality(ones, 0); if (answer.getCardinality() > ArrayContainer.DEFAULT_MAX_SIZE) { return answer; } else { return answer.toArrayContainer(); } }</code><technical_language>Yes. I replaced 0xFFFF + 1 1<<16, is fine</technical_language>

Target:
public Container and(BitmapContainer x) { int card = this.getCardinality(); if (card <= ArrayContainer.DEFAULT_MAX_SIZE) { if (card > x.cardinality) { card = x.cardinality; } ArrayContainer answer = new ArrayContainer(card); answer.cardinality = 0; for (int rlepos = 0; rlepos < this.nbrruns; ++rlepos) { int runStart = Util.toIntUnsigned(this.getValue(rlepos)); int runEnd = runStart + Util.toIntUnsigned(this.getLength(rlepos)); for (int runValue = runStart; runValue <= runEnd; ++runValue) { if (x.contains((short) runValue)) { answer.content[answer.cardinality++] = (short) runValue; } } } return answer; } BitmapContainer answer = x.clone(); int start = 0; for (int rlepos = 0; rlepos < this.nbrruns; ++rlepos) { int end = Util.toIntUnsigned(this.getValue(rlepos)); int prevOnes = answer.cardinalityInRange(start, end); Util.resetBitmapRange(answer.bitmap, start, end); answer.updateCardinality(prevOnes, 0); start = end + Util.toIntUnsigned(this.getLength(rlepos)) + 1; } int ones = answer.cardinalityInRange(start, BitmapContainer.MAX_CAPACITY); Util.resetBitmapRange(answer.bitmap, start, BitmapContainer.MAX_CAPACITY); answer.updateCardinality(ones, 0); if (answer.getCardinality() > ArrayContainer.DEFAULT_MAX_SIZE) { return answer; } else { return answer.toArrayContainer(); } }
Source:
<code>public void deleteHybridRole(String roleName) throws UserStoreException { if (UserCoreUtil.isEveryoneRole(roleName, realmConfig)) { throw new UserStoreException("Invalid operation"); } Connection dbConnection = null; try { dbConnection = getDBConnection(); DatabaseUtil.updateDatabase(dbConnection, <START> HybridJDBCConstants.ON_DELETE_ROLE_REMOVE_USER_ROLE_SQL, roleName, tenantId, <END> tenantId); DatabaseUtil.updateDatabase(dbConnection, HybridJDBCConstants.DELETE_ROLE_SQL, roleName, tenantId); dbConnection.commit(); } catch (SQLException e) { String errorMessage = "Error occurred while deleting Hybrid role :"+roleName; throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection); } userRealm.getAuthorizationManager().clearRoleAuthorization(roleName); }</code><technical_language>add debug log, correct spacing</technical_language>

Target:
public void deleteHybridRole(String roleName) throws UserStoreException { if (UserCoreUtil.isEveryoneRole(roleName, realmConfig)) { throw new UserStoreException("Invalid operation"); } Connection dbConnection = null; try { dbConnection = getDBConnection(); DatabaseUtil.updateDatabase(dbConnection, HybridJDBCConstants.ON_DELETE_ROLE_REMOVE_USER_ROLE_SQL, roleName, tenantId, tenantId); DatabaseUtil.updateDatabase(dbConnection, HybridJDBCConstants.DELETE_ROLE_SQL, roleName, tenantId); dbConnection.commit(); } catch (SQLException e) { String errorMessage = "Error occurred while deleting Hybrid role : " + roleName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection); } userRealm.getAuthorizationManager().clearRoleAuthorization(roleName); }
Source:
<code>public void testForceRefreshWithAutoRefresh() throws Exception { genericSetUp(SEMANTIC_MODEL_PATH_FOR_NULL_VALUE, MODELER_DESCRIPTION_PATH_FOR_NULL_VALUE, SESSION_PATH_FOR_NULL_VALUE); changeSiriusPreference(SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), true); Iterator<DRepresentation> iterator = getRepresentations("PackageDiag").iterator(); DDiagram firstDiag = (DDiagram) iterator.next(); DiagramEditor diagramEditor = (DiagramEditor) DialectUIManager.INSTANCE.openEditor(session, firstDiag, new NullProgressMonitor()); DDiagram secondDiag = (DDiagram) iterator.next(); diagramEditor = (DiagramEditor) DialectUIManager.INSTANCE.openEditor(session, secondDiag, new NullProgressMonitor()); assertTrue("Diagram should be empty", firstDiag.getOwnedDiagramElements().isEmpty()); assertTrue("Diagram should be empty", secondDiag.getOwnedDiagramElements().isEmpty()); try { applyNodeCreationTool("createPackageWithRefresh", secondDiag, secondDiag); assertEquals("Diagram should not be empty", 1, secondDiag.getOwnedDiagramElements().size()); assertEquals("Diagram should not be empty", 1, firstDiag.getOwnedDiagramElements().size()); <START> } catch (NullPointerException exception) { Assert.fail("No expcetion should have been raised during Node creation. This is a regression."); } <END> }</code><technical_language>idem, remove</technical_language>

Target:
public void testForceRefreshWithAutoRefresh() throws Exception { changeSiriusPreference(SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), true); assertTrue("Diagram should be empty", firstDiag.getOwnedDiagramElements().isEmpty()); assertTrue("Diagram should be empty", secondDiag.getOwnedDiagramElements().isEmpty()); applyNodeCreationTool("createPackageWithRefresh", secondDiag, secondDiag); assertEquals("Force refresh diagram has not been refreshed", 1, secondDiag.getOwnedDiagramElements().size()); assertEquals("Non 'Force refresh' diagram has not been refreshed.", 1, firstDiag.getOwnedDiagramElements().size()); }
Source:
<code>protected XBeeMode determineConnectionMode() { <START> dataReader = new DataReader(connectionInterface); <END> dataReader.start(); try { operatingMode = XBeeMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null) { if (response.getResponse()[0] == 0x01) return XBeeMode.API; else return XBeeMode.API_ESCAPE; } } catch (XBeeException e) { e.printStackTrace(); return XBeeMode.UNKNOWN; } catch (InvalidOperatingModeException e) { return XBeeMode.UNKNOWN; } return XBeeMode.UNKNOWN; }</code><technical_language>Data Reader initialization moved connect method this method called once</technical_language>

Target:
protected OperatingMode determineConnectionMode() { try { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null) { if (response.getResponse()[0] == OperatingMode.API.getID()) return OperatingMode.API; else return OperatingMode.API_ESCAPE; } } catch (XBeeException e) { e.printStackTrace(); return OperatingMode.UNKNOWN; } catch (InvalidOperatingModeException e) { return OperatingMode.UNKNOWN; } return OperatingMode.UNKNOWN; }
Source:
<code>public int getMaxConcurrency() throws IOException { return Integer.parseInt( <START> this.client.getConfig().get(LuaConfigParameter.MAX_CONCURRENCY.toString()) <END> .toString()); }</code><technical_language>Config overloaded get method takes a LuaConfigParameter instance calls toString internally delegates String version of get</technical_language>

Target:
public int getMaxConcurrency() throws IOException { return Integer.parseInt( this.client.getConfig().get(LuaConfigParameter.MAX_CONCURRENCY) .toString()); }
Source:
<code>private void compareCompiledPlans(CompiledPlan calcitePlan, CompiledPlan voltdbPlan) { <START> assertEquals(voltdbPlan.hasLimitOrOffset(), calcitePlan.hasLimitOrOffset()); <END> assertEquals(voltdbPlan.hasDeterministicStatement(), calcitePlan.hasDeterministicStatement()); ParameterValueExpression[] voltdbParams = voltdbPlan.getParameters(); ParameterValueExpression[] calciteParams = calcitePlan.getParameters(); assertEquals(voltdbParams.length, calciteParams.length); for (int i = 0; i < voltdbParams.length; ++i) { assertEquals(voltdbParams[i].getParameterIndex(), calciteParams[i].getParameterIndex()); } }</code><technical_language>I prefer putting some informative texts in case of failure: assertEquals("Plans limit offset", voltdbPlan.hasLimitOrOffset(), ...);</technical_language>

Target:
private void compareCompiledPlans(CompiledPlan calcitePlan, CompiledPlan voltdbPlan) { assertEquals("Plans with different limit or offset", voltdbPlan.hasLimitOrOffset(), calcitePlan.hasLimitOrOffset()); assertEquals("Plans with different determinism", voltdbPlan.hasDeterministicStatement(), calcitePlan.hasDeterministicStatement()); ParameterValueExpression[] voltdbParams = voltdbPlan.getParameters(); ParameterValueExpression[] calciteParams = calcitePlan.getParameters(); assertEquals("Plans with different parameter number", voltdbParams.length, calciteParams.length); for (int i = 0; i < voltdbParams.length; ++i) { assertEquals("The " + i + "-th parameter differ", voltdbParams[i].getParameterIndex(), calciteParams[i].getParameterIndex()); } }
Source:
<code>public HeaderViewHolder(View itemView) { super(itemView); instructionbutton = (Button) itemView.findViewById(R.id.instruction_button); dismissImageButton = (ImageButton) itemView.findViewById(R.id.dismiss_image_button); viewPager = (ViewPager) itemView.findViewById(R.id.view_pager); viewPager.setAdapter(new BannerOnboardingAdapter()); <START> viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { <END> @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { if(!isRunning) { startSlidingViewPager(); } } @Override public void onPageScrollStateChanged(int i) { if(isRunning && i == ViewPager.SCROLL_STATE_DRAGGING) { stopSlidingViewPager(); } } }); pageIndicator = (BannerOnboardingPageIndicator) itemView.findViewById(R.id.page_indicator); pageIndicator.setViewPager(viewPager); handler = new Handler(); slideRunnable = new Runnable() { @Override public void run() { int nextItem = viewPager.getCurrentItem() + 1; if(nextItem == viewPager.getAdapter().getCount()) nextItem = 0; viewPager.setCurrentItem(nextItem, true); handler.postDelayed(this, SLIDE_TIME); } }; }</code><technical_language>changed worth mentioning. call addOnPageChangeListener this line (and a others in project) is api 9 call minimum api is 8. devices api 8 google longer supporting it, bump project 9. stats if this in new app</technical_language>

Target:
public HeaderViewHolder(View itemView) { super(itemView); instructionbutton = (Button) itemView.findViewById(R.id.instruction_button); dismissImageButton = (ImageButton) itemView.findViewById(R.id.dismiss_image_button); viewPager = (ViewPager) itemView.findViewById(R.id.view_pager); viewPager.setAdapter(new OnboardingBannerAdapter()); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { if(!isRunning) { startSlidingViewPager(); } } @Override public void onPageScrollStateChanged(int i) { if(isRunning && i == ViewPager.SCROLL_STATE_DRAGGING) { stopSlidingViewPager(); } } }); pageIndicator = (BannerOnboardingPageIndicator) itemView.findViewById(R.id.page_indicator); pageIndicator.setViewPager(viewPager); handler = new Handler(); slideRunnable = new Runnable() { @Override public void run() { int nextItem = viewPager.getCurrentItem() + 1; if(nextItem == viewPager.getAdapter().getCount()) nextItem = 0; viewPager.setCurrentItem(nextItem, true); handler.postDelayed(this, SLIDE_TIME); } }; }
Source:
<code>public void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); thumbnailLoadToggleKey = getString(R.string.download_thumbnail_key); youtubeRestrictedModeEnabledKey = getString(R.string.youtube_restricted_mode_enabled); initialSelectedLocalization = org.schabi.newpipe.util.Localization .getPreferredLocalization(requireContext()); initialSelectedContentCountry = org.schabi.newpipe.util.Localization .getPreferredContentCountry(requireContext()); initialLanguage = PreferenceManager .getDefaultSharedPreferences(requireContext()).getString("app_language_key", "en"); findPreference(getString(R.string.clear_cookie_key)) .setOnPreferenceClickListener(preference -> { defaultPreferences.edit() .putString(getString(R.string.recaptcha_cookies_key), "").apply(); Toast.makeText(getActivity(), R.string.recaptcha_cookies_cleared, Toast.LENGTH_SHORT).show(); <START> return true; <END> }); }</code><technical_language>clear downloader's cookies: DownloaderImpl.getInstance().setCookie(ReCaptchaActivity.RECAPTCHA_COOKIES_KEY, "");</technical_language>

Target:
public void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); thumbnailLoadToggleKey = getString(R.string.download_thumbnail_key); youtubeRestrictedModeEnabledKey = getString(R.string.youtube_restricted_mode_enabled); initialSelectedLocalization = org.schabi.newpipe.util.Localization .getPreferredLocalization(requireContext()); initialSelectedContentCountry = org.schabi.newpipe.util.Localization .getPreferredContentCountry(requireContext()); initialLanguage = PreferenceManager .getDefaultSharedPreferences(requireContext()).getString("app_language_key", "en"); final Preference clearCookiePref = findPreference(getString(R.string.clear_cookie_key)); clearCookiePref.setOnPreferenceClickListener(preference -> { defaultPreferences.edit() .putString(getString(R.string.recaptcha_cookies_key), "").apply(); DownloaderImpl.getInstance().setCookie(ReCaptchaActivity.RECAPTCHA_COOKIES_KEY, ""); Toast.makeText(getActivity(), R.string.recaptcha_cookies_cleared, Toast.LENGTH_SHORT).show(); clearCookiePref.setVisible(false); return true; }); if (defaultPreferences.getString(getString(R.string.recaptcha_cookies_key), "").isEmpty()) { clearCookiePref.setVisible(false); } }
Source:
<code>public MsgpackGZFileBuilder(MessagePack msgpack, File file) throws IOException { <START> this.log = Exec.getLogger(getClass()); <END> this.file = checkNotNull(file); this.out = new DataSizeFilter(new BufferedOutputStream(new FileOutputStream(file))); this.gzout = new GZIPOutputStream(this.out); this.packer = msgpack.createPacker(this.gzout); this.recordCount = 0; }</code><technical_language>need this line</technical_language>

Target:
public MsgpackGZFileBuilder(MessagePack msgpack, File file) throws IOException { this.file = checkNotNull(file); this.out = new DataSizeFilter(new BufferedOutputStream(new FileOutputStream(file))); this.gzout = new GZIPOutputStream(this.out); this.packer = msgpack.createPacker(this.gzout); this.recordCount = 0; }
Source:
<code>public InfoPanel(SearchBox searchBox) { setId(ID); addStyleName(ID); addStyleName("v-scrollable"); toggleButton = new CssLayout(); toggleButton.setStyleName("toggle-button"); toggleButton.setDescription(HIDE_TOOLTIP); toggleButton.addLayoutClickListener((event) -> { expanded = !expanded; if (expanded) { toggleButton.removeStyleName("info-panel-collapsed"); toggleButton.setDescription(HIDE_TOOLTIP); } else { toggleButton.addStyleName("info-panel-collapsed"); toggleButton.setDescription(SHOW_TOOLTIP); } refreshInfoArea(); }); staticComponents.add(searchBox); staticComponents.add(toggleButton); <START> graphRenderContainer = new InlineGraphContainer(); <END> staticComponents.add(graphRenderContainer); }</code><technical_language>If graphRenderContainer is used, declaring all</technical_language>

Target:
public InfoPanel(SearchBox searchBox) { setId(ID); addStyleName(ID); addStyleName("v-scrollable"); toggleButton = new CssLayout(); toggleButton.setStyleName("toggle-button"); toggleButton.setDescription(HIDE_TOOLTIP); toggleButton.addLayoutClickListener((event) -> { expanded = !expanded; if (expanded) { toggleButton.removeStyleName("info-panel-collapsed"); toggleButton.setDescription(HIDE_TOOLTIP); } else { toggleButton.addStyleName("info-panel-collapsed"); toggleButton.setDescription(SHOW_TOOLTIP); } refreshInfoArea(); }); staticComponents.add(searchBox); staticComponents.add(toggleButton); staticComponents.add(new InlineGraphContainer()); }
Source:
<code>public void equalsAndHashCodeTest() { Offset o1 = new Offset("test", 2); Offset o2 = new Offset("test", 2); Offset o3 = new Offset("test", 3); Offset o4 = new Offset("test_more", 2); assertTrue("Offset should be equal to itself", o1.equals(o1)); assertFalse("Offset should not be equal to null", o1.equals(null)); assertFalse("Offset should not be equal to random Object", o1.equals(new Object())); assertTrue("Offsets should be declared equal", o1.equals(o2)); assertEquals("Hashcode mismatch", o1.hashCode(), o2.hashCode()); assertFalse("Offsets should be declared unequal", o1.equals(o3)); <START> assertFalse("Hashcode should be declared unequal", o1.equals(o3)); <END> assertFalse("Offsets should be declared unequal", o1.equals(o4)); assertFalse("Hashcode should be declared unequal", o1.equals(o4)); }</code><technical_language>hashCode()</technical_language>

Target:
public void equalsAndHashCodeTest() { Offset o1 = new Offset("test", 2); Offset o2 = new Offset("test", 2); Offset o3 = new Offset("test", 3); Offset o4 = new Offset("test_more", 2); assertTrue("Offset should be equal to itself", o1.equals(o1)); assertFalse("Offset should not be equal to null", o1.equals(null)); assertFalse("Offset should not be equal to random Object", o1.equals(new Object())); assertTrue("Offsets should be declared equal", o1.equals(o2)); assertEquals("Hashcode mismatch", o1.hashCode(), o2.hashCode()); assertFalse("Offsets should be declared unequal", o1.equals(o3)); }
Source:
<code>public void setup() { when(mockKvs.getMetadataForTable(TABLE_REF)) .thenReturn(SweepQueueTestUtils.metadataBytes(TableMetadataPersistence.SweepStrategy.CONSERVATIVE)); when(mockKvs.getMetadataForTable(TABLE_REF2)) .thenReturn(SweepQueueTestUtils.metadataBytes(TableMetadataPersistence.SweepStrategy.THOROUGH)); partitioner = new WriteInfoPartitioner(mockKvs); writer = new SweepableTimestampsWriter(kvs, partitioner); reader = new SweepableTimestampsReader(kvs, provider); progress = new KvsSweepQueueProgress(kvs); provider = new SweepTimestampProvider(() -> unreadableTs, () -> immutableTs); <START> shard = writeTs(writer, TS, true); <END> shard2 = writeTs(writer, TS2, false); immutableTs = 10 * TS; unreadableTs = 10 * TS; }</code><technical_language>I recommend conservativeShard thoroughShard, for readability. similar names for TS/TS2</technical_language>

Target:
public void setup() { when(mockKvs.getMetadataForTable(TABLE_REF)) .thenReturn(SweepQueueTestUtils.metadataBytes(TableMetadataPersistence.SweepStrategy.CONSERVATIVE)); when(mockKvs.getMetadataForTable(TABLE_REF2)) .thenReturn(SweepQueueTestUtils.metadataBytes(TableMetadataPersistence.SweepStrategy.THOROUGH)); partitioner = new WriteInfoPartitioner(mockKvs); provider = new SweepTimestampProvider(() -> unreadableTs, () -> immutableTs); writer = new SweepableTimestampsWriter(kvs, partitioner); reader = new SweepableTimestampsReader(kvs, provider); progress = new KvsSweepQueueProgress(kvs); shard = writeTs(writer, TS, true); shard2 = writeTs(writer, TS2, false); immutableTs = 10 * TS; unreadableTs = 10 * TS; }
Source:
<code>private List<ConsumedEvent> extractTimespan(final long batchWindowEndTimestamp) { int count = 1; <START> while (count < nakadiEvents.size() && nakadiEvents.get(count).getTimestamp() < batchWindowEndTimestamp) { <END> count++; } return extract(count); }</code><technical_language>I optimize, another sorted data structure cost more iterative approach</technical_language>

Target:
private List<ConsumedEvent> extractTimespan(final long batchWindowEndTimestamp) { batchWindowStartTimestamp = batchWindowEndTimestamp; return extract((i) -> nakadiEvents.get(0).getTimestamp() < batchWindowEndTimestamp); }
Source:
<code>public static void writeIndex(final Index idx, final File idxFile) throws IOException { LittleEndianOutputStream stream = null; try { final OutputStream underlyingStream = (idx instanceof TabixIndex) ? <START> new BlockCompressedOutputStream(idxFile) : new FileOutputStream(idxFile); <END> stream = new LittleEndianOutputStream(new BufferedOutputStream(underlyingStream)); idx.write(stream); } finally { if(stream != null) { stream.close(); } } }</code><technical_language>for index type of outputstream needs open for factory, write stream (given a file). more give decision index factory. also: tests please</technical_language>

Target:
public static void writeIndex(final Index idx, final File idxFile) throws IOException { idx.write(idxFile); }
Source:
<code>private static CompletableFuture<Boolean> copyAllChunks(boolean includeFirst, AbsoluteCapability currentCap, SigningPrivateKeyAndPublicHash targetSigner, TransactionId tid, NetworkAccess network) { return network.getMetadata(currentCap.getLocation()) .thenCompose(mOpt -> { if (! mOpt.isPresent()) { return CompletableFuture.completedFuture(true); } return (includeFirst ? network.uploadChunk(mOpt.get(), currentCap.owner, currentCap.getMapKey(), targetSigner, tid) : <START> CompletableFuture.completedFuture(true)) <END> .thenCompose(b -> { CryptreeNode chunk = mOpt.get(); Optional<byte[]> nextChunkMapKey = chunk.getNextChunkLocation(currentCap.rBaseKey); if (! nextChunkMapKey.isPresent()) return CompletableFuture.completedFuture(true); return copyAllChunks(true, currentCap.withMapKey(nextChunkMapKey.get()), targetSigner, tid, network); }) .thenCompose(b -> { if (! (mOpt.get() instanceof DirAccess)) return CompletableFuture.completedFuture(true); Set<AbsoluteCapability> childCaps = ((DirAccess) mOpt.get()).getChildrenCapabilities(currentCap); return Futures.reduceAll(childCaps, true, (x, cap) -> copyAllChunks(true, cap, targetSigner, tid, network), (x, y) -> x && y); }); }); }</code><technical_language>odd construction, i</technical_language>

Target:
private static CompletableFuture<Boolean> copyAllChunks(boolean includeFirst, AbsoluteCapability currentCap, SigningPrivateKeyAndPublicHash targetSigner, TransactionId tid, NetworkAccess network) { return network.getMetadata(currentCap.getLocation()) .thenCompose(mOpt -> { if (! mOpt.isPresent()) { return CompletableFuture.completedFuture(true); } return (includeFirst ? network.addPreexistingChunk(mOpt.get(), currentCap.owner, currentCap.getMapKey(), targetSigner, tid) : CompletableFuture.completedFuture(true)) .thenCompose(b -> { CryptreeNode chunk = mOpt.get(); Optional<byte[]> nextChunkMapKey = chunk.getNextChunkLocation(currentCap.rBaseKey); if (! nextChunkMapKey.isPresent()) return CompletableFuture.completedFuture(true); return copyAllChunks(true, currentCap.withMapKey(nextChunkMapKey.get()), targetSigner, tid, network); }) .thenCompose(b -> { if (! (mOpt.get() instanceof DirAccess)) return CompletableFuture.completedFuture(true); Set<AbsoluteCapability> childCaps = ((DirAccess) mOpt.get()).getChildrenCapabilities(currentCap); return Futures.reduceAll(childCaps, true, (x, cap) -> copyAllChunks(true, cap, targetSigner, tid, network), (x, y) -> x && y); }); }); }