auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<ModuleMetadata> findAllByContainerId(String containerId) { <START> Assert.hasLength(containerId, "containerId is required"); <END> List<ModuleMetadata> results = new ArrayList<ModuleMetadata>(); try { List<String> deployedModules = getDeployedModules(containerId); for (String moduleId : deployedModules) { results.add(findOne(containerId, moduleId)); } return (List<ModuleMetadata>) updateDeploymentStatus(results); } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } }</code><technical_language>Assert.hasText() more appropriate</technical_language>

Target:
public List<ModuleMetadata> findAllByContainerId(String containerId) { Assert.hasText(containerId, "containerId is required"); List<ModuleMetadata> results = new ArrayList<ModuleMetadata>(); try { List<String> deployedModules = getDeployedModules(containerId); for (String moduleId : deployedModules) { results.add(findOne(containerId, moduleId)); } return (List<ModuleMetadata>) updateDeploymentStatus(results); } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } }
Source:
<code>public String getFandomUrl(EnvType envType) { String hostname = FANDOM_HOSTNAME; if (!envType.equals(PROD)) { hostname = env + "." + hostname; } <START> return "http://" + hostname + "/"; <END> }</code><technical_language>this http_prefix variable</technical_language>

Target:
public String getFandomUrl(EnvType envType) { String hostname = FANDOM_HOSTNAME; if (!envType.equals(PROD)) { hostname = env + "." + hostname; } return HTTP_PREFIX + hostname + "/"; }
Source:
<code><START> public static long getPageSizeMs(Scan scan) { <END> long pageSizeMs = Long.MAX_VALUE; byte[] pageSizeMsBytes = scan.getAttribute(BaseScannerRegionObserver.SERVER_PAGE_SIZE_MS); if (pageSizeMsBytes != null) { pageSizeMs = Bytes.toLong(pageSizeMsBytes); } return pageSizeMs; }</code><technical_language>if scan's filter is a FilterList contains a PagedFilter</technical_language>

Target:
private static long getPageSizeMs(Scan scan) { long pageSizeMs = Long.MAX_VALUE; byte[] pageSizeMsBytes = scan.getAttribute(BaseScannerRegionObserver.SERVER_PAGE_SIZE_MS); if (pageSizeMsBytes != null) { pageSizeMs = Bytes.toLong(pageSizeMsBytes); } return pageSizeMs; }
Source:
<code>private static boolean isChildAndParent(String childContextId, String parentContextId) { <START> IContextService contextService = PlatformUI.getWorkbench().getService(IContextService.class); <END> try { for (String c = contextService.getContext(childContextId).getParentId(); c != null; c = contextService .getContext(c).getParentId()) { if (c.equals(parentContextId)) { return true; } } } catch (NotDefinedException e) { } return false; }</code><technical_language>want avoid PlatformUI.getWorkbench() (almost) costs. instead ContextModel, in case making multiple modifications</technical_language>

Target:
private boolean isChildAndParent(String childContextId, String parentContextId) { for (String c = getParentContextId(childContextId); c != null; c = getParentContextId(c)) { if (c.equals(parentContextId)) { return true; } } return false; }
Source:
<code>protected static void getExpiredJobs(HelixDataAccessor dataAccessor, HelixPropertyStore<ZNRecord> propertyStore, WorkflowConfig workflowConfig, WorkflowContext workflowContext, Set<String> expiredJobs, Set<String> jobsWithoutConfig) { if (workflowContext != null) { Map<String, TaskState> jobStates = workflowContext.getJobStates(); for (String job : workflowConfig.getJobDag().getAllNodes()) { JobConfig jobConfig = TaskUtil.getJobConfig(dataAccessor, job); JobContext jobContext = TaskUtil.getJobContext(propertyStore, job); <START> if (jobConfig != null) { <END> long expiry = jobConfig.getExpiry(); if (jobContext != null && jobStates.get(job) == TaskState.COMPLETED) { if (jobContext.getFinishTime() != WorkflowContext.UNFINISHED && System.currentTimeMillis() >= jobContext.getFinishTime() + expiry) { expiredJobs.add(job); } } } else { LOG.error(String.format( "Job %s exists in JobDAG but JobConfig is missing! Job might have been deleted manually from the JobQueue: %s, or left in the DAG due to a failed clean-up attempt from last purge.", job, workflowConfig.getWorkflowId())); jobsWithoutConfig.add(job); } } } }</code><technical_language>Nit: tip: If I I order of if conditions same. easier review code diff. I is, if (jobConfig == null) { ..</technical_language>

Target:
protected static void getExpiredJobs(HelixDataAccessor dataAccessor, HelixPropertyStore<ZNRecord> propertyStore, WorkflowConfig workflowConfig, WorkflowContext workflowContext, Set<String> expiredJobs, Set<String> jobsWithoutConfig) { if (workflowContext != null) { Map<String, TaskState> jobStates = workflowContext.getJobStates(); for (String job : workflowConfig.getJobDag().getAllNodes()) { JobConfig jobConfig = TaskUtil.getJobConfig(dataAccessor, job); JobContext jobContext = TaskUtil.getJobContext(propertyStore, job); if (jobConfig == null) { LOG.error(String.format( "Job %s exists in JobDAG but JobConfig is missing! Job might have been deleted manually from the JobQueue: %s, or left in the DAG due to a failed clean-up attempt from last purge.", job, workflowConfig.getWorkflowId())); jobsWithoutConfig.add(job); } else { long expiry = jobConfig.getExpiry(); if (jobContext != null && jobStates.get(job) == TaskState.COMPLETED) { if (jobContext.getFinishTime() != WorkflowContext.UNFINISHED && System.currentTimeMillis() >= jobContext.getFinishTime() + expiry) { expiredJobs.add(job); } } } } } }
Source:
<code>public void runTask() throws Exception { final Spreadsheet sheet = new Spreadsheet("Invoices"); process(sheet, new File(DIR)); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); sheet.exportToXLSSheet(stream); output("invoices.xls", stream.toByteArray()); final String subject = "Recibos passados a entidades terceiras"; final String body = "Listagem atualizada com os 'recibos' passados no Fénix entidades terceiras: " + new DateTime().toString("yyyy-MM-dd HH:mm"); <START> TaskUtils.sendErrorReport("invoices_" + new DateTime().toString("yyyy_MM_dd_HH_mm") + ".xls", stream.toByteArray(), subject, body); <END> }</code><technical_language>This method called sendReport, current name implies error report is is case</technical_language>

Target:
public void runTask() throws Exception { final Spreadsheet sheet = new Spreadsheet("Invoices"); process(sheet, new File(DIR)); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); sheet.exportToXLSSheet(stream); output("invoices.xls", stream.toByteArray()); final String subject = "Recibos passados a entidades terceiras"; final String body = "Listagem atualizada com os 'recibos' passados no Fénix entidades terceiras: " + new DateTime().toString("yyyy-MM-dd HH:mm"); TaskUtils.sendReport("invoices_" + new DateTime().toString("yyyy_MM_dd_HH_mm") + ".xls", stream.toByteArray(), subject, body); }
Source:
<code>public void render(Context context, ImageResource value, SafeHtmlBuilder sb) { if (value != null) { sb.append(template.imageContainerWithStyleClass( <START> styleClass == null ? style : "", END> styleClass == null ? "" : styleClass, SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(value).getHTML()))); } }</code><technical_language>more sense this in setters? for a pain. I there</technical_language>

Target:
public void render(Context context, ImageResource value, SafeHtmlBuilder sb) { if (value != null) { sb.append(template.imageContainerWithStyleClass( style, styleClass, SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(value).getHTML()))); } }
Source:
<code>public void persistInfraVariables() { logger.info("persist start"); if (!nodeSource.getName().equals(NodeSource.DEFAULT_LOCAL_NODES_NODE_SOURCE_NAME)) { readLock.lock(); logger.info("lock acquired start"); try { if (dbManager == null) { setRmDbManager(RMDBManager.getInstance()); } <START> logger.info("get node source start"); <END> logger.info("get node source end"); if (nodeSourceData != null) { nodeSourceData.setInfrastructureVariables(persistedInfraVariables); dbManager.updateNodeSource(nodeSourceData); logger.info("update node source end"); } } catch (RuntimeException e) { logger.error("Exception while persisting runtime variables: " + e.getMessage()); throw e; } finally { readLock.unlock(); logger.info("lock released"); } } logger.info("persist end"); }</code><technical_language>loggers sanitized</technical_language>

Target:
public void persistInfraVariables() { if (!nodeSource.getName().equals(NodeSource.DEFAULT_LOCAL_NODES_NODE_SOURCE_NAME)) { readLock.lock(); try { if (dbManager == null) { setRmDbManager(RMDBManager.getInstance()); } if (nodeSourceData != null) { nodeSourceData.setInfrastructureVariables(persistedInfraVariables); dbManager.updateNodeSource(nodeSourceData); } } catch (RuntimeException e) { logger.error("Exception while persisting runtime variables: " + e.getMessage()); throw e; } finally { readLock.unlock(); } } }
Source:
<code>public void processes(WebContext ctx) { ElasticQuery<Process> query = elastic.select(Process.class).orderDesc(Process.STARTED); UserInfo user = UserContext.getCurrentUser(); if (!user.hasPermission(PERMISSION_MANAGE_ALL_PROCESSES)) { query.eq(Process.TENANT_ID, user.getTenantId()); } if (!user.hasPermission(PERMISSION_MANAGE_PROCESSES)) { query.eq(Process.USER_ID, user.getUserId()); } query.where(Elastic.FILTERS.oneInField(Process.REQUIRED_PERMISSION, new ArrayList<>(user.getPermissions())) .orEmpty() .build()); ElasticPageHelper<Process> ph = ElasticPageHelper.withQuery(query); ph.withContext(ctx); ph.addTermAggregation(Process.STATE, ProcessState.class); <START> ph.addParameterFacet("reference", <END> "reference-label", Process.REFERENCES, NLS.get("ProcessController.reference"), null); ph.addTermAggregation(Process.PROCESS_TYPE, value -> NLS.getIfExists(value, null).orElse(null)); ph.addTimeAggregation(Process.STARTED, DateRange.lastFiveMinutes(), DateRange.lastFiveteenMinutes(), DateRange.lastTwoHours(), DateRange.today(), DateRange.yesterday(), DateRange.thisWeek(), DateRange.lastWeek()); ph.withSearchFields(QueryField.contains(ProcessLog.SEARCH_FIELD)); ctx.respondWith().template("templates/biz/process/processes.html.pasta", ph.asPage()); }</code><technical_language>ph > pageHelper</technical_language>

Target:
public void processes(WebContext ctx) { ElasticQuery<Process> query = elastic.select(Process.class).orderDesc(Process.STARTED); UserInfo user = UserContext.getCurrentUser(); if (!user.hasPermission(PERMISSION_MANAGE_ALL_PROCESSES)) { query.eq(Process.TENANT_ID, user.getTenantId()); } if (!user.hasPermission(PERMISSION_MANAGE_PROCESSES)) { query.eq(Process.USER_ID, user.getUserId()); } query.where(Elastic.FILTERS.oneInField(Process.REQUIRED_PERMISSION, new ArrayList<>(user.getPermissions())) .orEmpty() .build()); ElasticPageHelper<Process> pageHelper = ElasticPageHelper.withQuery(query); pageHelper.withContext(ctx); pageHelper.addTermAggregation(Process.STATE, ProcessState.class); pageHelper.addParameterFacet("reference", "reference-label", Process.REFERENCES, NLS.get("ProcessController.reference"), null); pageHelper.addTermAggregation(Process.PROCESS_TYPE, value -> NLS.getIfExists(value, null).orElse(null)); pageHelper.addTimeAggregation(Process.STARTED, DateRange.lastFiveMinutes(), DateRange.lastFiveteenMinutes(), DateRange.lastTwoHours(), DateRange.today(), DateRange.yesterday(), DateRange.thisWeek(), DateRange.lastWeek()); pageHelper.withSearchFields(QueryField.contains(ProcessLog.SEARCH_FIELD)); ctx.respondWith().template("templates/biz/process/processes.html.pasta", pageHelper.asPage()); }
Source:
<code>public Map<String, Response> getResponses() { <START> return responses; <END> }</code><technical_language>this needs return responsesObject (converted Map) responses depending null status of two. this is achieved for responseSchema schema in response</technical_language>

Target:
public Map<String, Response> getResponses() { if (this.responsesObject == null && responses != null) { this.responsesObject = new Responses(); for (String key : responses.keySet()) { this.responsesObject.put(key, responses.get(key)); } } return responses; }
Source:
<code>public void onDelete() { try { <START> fileUtilities.remove(this.localFolder.getAbsolutePath()); <END> LOGGER.info("Deleted " + this); } catch (IOException e) { LOGGER.error("Couldn't delete " + this, e); } }</code><technical_language>I required</technical_language>

Target:
public void onDelete() { try { FileUtils.deleteDirectory(this.localFolder); LOGGER.info("Deleted " + this); } catch (IOException e) { LOGGER.error("Couldn't delete " + this, e); } }
Source:
<code>public String getId() { <START> return this.difficultyResourceKey.replace("options.difficulty.", ""); <END> }</code><technical_language>need do this time, a field in constructor</technical_language>

Target:
public String getId() { return this.id; }
Source:
<code>public List<SearchSuggestion> getSuggestions(String namespace, String input) { <START> return graphSearchService.getSuggestions(namespace, input); <END> }</code><technical_language>In order consistent behaviour, if is empty result, return a 204 CONTENT response instead of empty 200 OK</technical_language>

Target:
public Response getSuggestions(String namespace, String input) { List<SearchSuggestion> result = graphSearchService.getSuggestions(namespace, input); if(result.size() < 1) { return Response.noContent().build(); } return Response.ok(result).type(MediaType.APPLICATION_JSON_TYPE).build(); }
Source:
<code>public Class getLambdaInterface() <START> { <END> checkState(!isValueTypeArgument(), "lambdaInterface only applies to function type argument"); return lambdaInterface.get(); }</code><technical_language>enum instead of boolean</technical_language>

Target:
public Class getLambdaInterface() { checkState(getArgumentType() == FUNCTION_TYPE, "lambdaInterface only applies to function type argument"); return lambdaInterface.get(); }
Source:
<code>private CompletableFuture<Void> handleDataReadCommand(InvocationContext ctx, DataCommand command) { return ctx.onReturn((rCtx, rCommand, rv, throwable) -> { DataCommand dataCommand = (DataCommand) rCommand; if (throwable != null) { if (throwable instanceof RpcException && performPartitionCheck(rCtx, dataCommand)) { throw log.degradedModeKeyUnavailable(dataCommand.getKey()); } else { <START> if (throwable instanceof TimeoutException && performPartitionCheck(rCtx, dataCommand)) { <END> List<Address> owners = distributionManager.locate(dataCommand.getKey()); if (!InfinispanCollections.containsAny(transport.getMembers(), owners)) { throw log.degradedModeKeyUnavailable(dataCommand.getKey()); } } throw throwable; } } postOperationPartitionCheck(rCtx, dataCommand, dataCommand.getKey()); return null; }); }</code><technical_language>TimeoutException eliminated previous commit? If instead this is a real timeout, I change exception - availability exceptions immediate, a 15s timeout</technical_language>

Target:
private CompletableFuture<Void> handleDataReadCommand(InvocationContext ctx, DataCommand command) { return ctx.onReturn((rCtx, rCommand, rv, throwable) -> { DataCommand dataCommand = (DataCommand) rCommand; if (throwable != null) { if (throwable instanceof RpcException && performPartitionCheck(rCtx, dataCommand)) { throw log.degradedModeKeyUnavailable(dataCommand.getKey()); } else { throw throwable; } } postOperationPartitionCheck(rCtx, dataCommand, dataCommand.getKey()); return null; }); }
Source:
<code><START> public Seat getCurrentUserSeat(Authentication auth) { <END> User user = (User) auth.getPrincipal(); return seatService.getSeatByUsername(user.getUsername()); }</code><technical_language>decided seats linked tickets. this work if 1 user multiple tickets</technical_language>

Target:
public List<Seat> getCurrentUserSeat(Authentication auth) { User user = (User) auth.getPrincipal(); return seatService.getSeatsByUsername(user.getUsername()); }
Source:
<code>public FixedDoubleHistogram(int bucketCount, double min, double max) { this.bucketCount = bucketCount; this.min = min; this.max = max; <START> FixedHistogramUtils.verifyParams(bucketCount, min, max); <END> this.weights = new double[bucketCount]; }</code><technical_language>static import sorts of</technical_language>

Target:
public FixedDoubleHistogram(int bucketCount, double min, double max) { this.bucketCount = bucketCount; this.min = min; this.max = max; verifyParameters(bucketCount, min, max); this.weights = new double[bucketCount]; }
Source:
<code>public static void fhirResourceGetHistory(String resourceName, String versionId) throws IOException, URISyntaxException { CloudHealthcare client = createClient(); HttpClient httpClient = HttpClients.createDefault(); String uri = String.format( <START> "%sv1beta1/%s/_history/%s", client.getRootUrl(), resourceName, versionId); <END> URIBuilder uriBuilder = new URIBuilder(uri) .setParameter("access_token", getAccessToken()); HttpUriRequest request = RequestBuilder .get() .setUri(uriBuilder.build()) .addHeader("Content-Type", "application/fhir+json") .addHeader("Accept-Charset", "utf-8") .addHeader("Accept", "application/fhir+json; charset=utf-8") .build(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.print(String.format( "Exception retrieving FHIR history: %s\n", response.getStatusLine().toString())); responseEntity.writeTo(System.err); throw new RuntimeException(); } System.out.println("FHIR resource history list retrieved: "); responseEntity.writeTo(System.out); }</code><technical_language>v1, v1beta1</technical_language>

Target:
public static void fhirResourceGetHistory(String resourceName, String versionId) throws IOException, URISyntaxException { CloudHealthcare client = createClient(); HttpClient httpClient = HttpClients.createDefault(); String uri = String.format( "%sv1/%s/_history/%s", client.getRootUrl(), resourceName, versionId); URIBuilder uriBuilder = new URIBuilder(uri) .setParameter("access_token", getAccessToken()); HttpUriRequest request = RequestBuilder .get() .setUri(uriBuilder.build()) .addHeader("Content-Type", "application/fhir+json") .addHeader("Accept-Charset", "utf-8") .addHeader("Accept", "application/fhir+json; charset=utf-8") .build(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.print(String.format( "Exception retrieving FHIR history: %s\n", response.getStatusLine().toString())); responseEntity.writeTo(System.err); throw new RuntimeException(); } System.out.println("FHIR resource history list retrieved: "); responseEntity.writeTo(System.out); }
Source:
<code>public ModelBuilderTest() { dictionary = new EntityDictionary(Collections.EMPTY_MAP); <START> dictionary.bindEntity(getType(Book.class)); <END> dictionary.bindEntity(getType(Author.class)); dictionary.bindEntity(getType(Publisher.class)); }</code><technical_language>necessary</technical_language>

Target:
public ModelBuilderTest() { dictionary = new EntityDictionary(Collections.EMPTY_MAP); dictionary.bindEntity(Book.class); dictionary.bindEntity(Author.class); dictionary.bindEntity(Publisher.class); }
Source:
<code>private void setupConfForSparkR(SparkConf conf) { String sparkRBasePath = new InterpreterProperty("SPARK_HOME", null, null, null).getValue(); File sparkRPath; if (null == sparkRBasePath) { sparkRBasePath = new InterpreterProperty("ZEPPELIN_HOME", "zeppelin.home", "../", null).getValue(); sparkRPath = new File(sparkRBasePath, "interpreter" + File.separator + "spark" + File.separator + "R"); } else { sparkRPath = new File(sparkRBasePath, "R" + File.separator + "lib"); } sparkRPath = new File(sparkRPath, "sparkr.zip"); if (sparkRPath.exists() && sparkRPath.isFile()) { String archives = null; if (conf.contains("spark.yarn.dist.archives")) { archives = conf.get("spark.yarn.dist.archives"); } if (archives != null) { <START> archives = archives + "," + "file:/" + sparkRPath + "#sparkr"; <END> } else { archives = "file:/" + sparkRPath + "#sparkr"; } conf.set("spark.yarn.dist.archives", archives); } else { logger.warn("sparkr.zip is not found, sparkr may not work."); } }</code><technical_language>is this related this JIRA</technical_language>

Target:
private void setupConfForSparkR(SparkConf conf) { String sparkRBasePath = new InterpreterProperty("SPARK_HOME", null, null, null).getValue(); File sparkRPath; if (null == sparkRBasePath) { sparkRBasePath = new InterpreterProperty("ZEPPELIN_HOME", "zeppelin.home", "../", null).getValue(); sparkRPath = new File(sparkRBasePath, "interpreter" + File.separator + "spark" + File.separator + "R"); } else { sparkRPath = new File(sparkRBasePath, "R" + File.separator + "lib"); } sparkRPath = new File(sparkRPath, "sparkr.zip"); if (sparkRPath.exists() && sparkRPath.isFile()) { String archives = null; if (conf.contains("spark.yarn.dist.archives")) { archives = conf.get("spark.yarn.dist.archives"); } if (archives != null) { archives = archives + "," + sparkRPath + "#sparkr"; } else { archives = sparkRPath + "#sparkr"; } conf.set("spark.yarn.dist.archives", archives); } else { logger.warn("sparkr.zip is not found, sparkr may not work."); } }
Source:
<code>public void setStepProperties(Map<String, Properties> properties) { Assert.notNull(properties, "Step properties cannot be null"); for(Map.Entry<String, Properties> propertiesEntry : properties.entrySet()) { String stepName = propertiesEntry.getKey(); if (!propertiesEntry.getValue().isEmpty()) { if (this.stepProperties.containsKey(stepName)) { Properties existingStepProperties = this.stepProperties.get(stepName); <START> existingStepProperties.putAll(propertiesEntry.getValue()); <END> this.stepProperties.put(stepName, existingStepProperties); } else { this.stepProperties.put(stepName, propertiesEntry.getValue()); } } } }</code><technical_language>This work. Map#addAll method a Properties object pull defaults defined in Properties object added</technical_language>

Target:
public void setStepProperties(Map<String, Properties> properties) { Assert.notNull(properties, "Step properties cannot be null"); for(Map.Entry<String, Properties> propertiesEntry : properties.entrySet()) { String stepName = propertiesEntry.getKey(); Properties stepProperties = propertiesEntry.getValue(); if (!stepProperties.isEmpty()) { if (this.stepProperties.containsKey(stepName)) { Properties existingStepProperties = this.stepProperties.get(stepName); Enumeration<?> stepPropertyNames = stepProperties.propertyNames(); while(stepPropertyNames.hasMoreElements()) { String propertyEntryName = (String) stepPropertyNames.nextElement(); existingStepProperties.put(propertyEntryName, stepProperties.getProperty(propertyEntryName)); } this.stepProperties.put(stepName, existingStepProperties); } else { this.stepProperties.put(stepName, propertiesEntry.getValue()); } } } }
Source:
<code>public Response remove() { get(); RemoveDiskParameters parameters = new RemoveDiskParameters(); <START> parameters.setDiskId(guid); <END> parameters.setStorageDomainId(asGuid(storageDomainId)); return performAction(VdcActionType.RemoveDisk, parameters); }</code><technical_language>combine 2 lines constructor receives disk-id</technical_language>

Target:
public Response remove() { get(); return performAction(VdcActionType.RemoveDisk, new RemoveDiskParameters(guid, asGuid(storageDomainId))); }
Source:
<code>public final Response listAvailableServices(@Context final HttpServletRequest request, @Context final HttpServletResponse response ) { try { final InitDataObject initData = new WebResource.InitBuilder(webResource) .requiredBackendUser(true) .requiredFrontendUser(false) .requestAndResponse(request, response) .rejectWhenNoUser(true) .init(); final User user = initData.getUser(); final List<ServiceIntegrationView> integrationViews = helper.getAvailableDescriptorViews(user); if(!integrationViews.isEmpty()){ return Response.ok(new ResponseEntityView(integrationViews)).build(); } throw new DoesNotExistException("Nope. No service integration is available to configure. Try uploading a file!"); <START> } catch (Exception e) { <END> Logger.error(this.getClass(), "Exception on listing available service integration descriptors.", e); return ResponseUtil.mapExceptionResponse(e); } }</code><technical_language>catch Exception Resource, exception handling Mappers class</technical_language>

Target:
public final Response listAvailableServices(@Context final HttpServletRequest request, @Context final HttpServletResponse response ) { try { final InitDataObject initData = new WebResource.InitBuilder(webResource) .requiredBackendUser(true) .requiredFrontendUser(false) .requestAndResponse(request, response) .rejectWhenNoUser(true) .init(); final User user = initData.getUser(); final List<ServiceIntegrationView> integrationViews = helper.getAvailableDescriptorViews(user); if(!integrationViews.isEmpty()){ return Response.ok(new ResponseEntityView(integrationViews)).build(); } throw new DoesNotExistException("No service integration is available to configure. Try uploading a file!"); } catch (Exception e) { Logger.error(this.getClass(), "Exception on listing all available service-integrations.", e); return ResponseUtil.mapExceptionResponse(e); } }
Source:
<code>public Object getResponseValue() { <START> return null; END> }</code><technical_language>throw new UnsupportedOperationException(); in UnsureResponse called</technical_language>

Target:
public Object getResponseValue() { throw new UnsupportedOperationException(); }
Source:
<code>private void getRetriesFromSettings(Task task, Map<String, Object> params, Map<String, Object> metadata) { Map<String, String> taskRetries = new HashMap<>(); List<Integer> retryInterval = new ArrayList<>(); int numberOfRetries; try { InputStream retries = settings.getRawConfig(TASK_PROPERTIES_FILE_NAME); if(retries != null) { Properties props = new Properties(); props.load(retries); <START> if (props != null) { <END> for (Map.Entry<Object, Object> entry : props.entrySet()) { taskRetries.put((String) entry.getKey(), (String) entry.getValue()); retryInterval.add(0, Integer.valueOf(entry.getValue().toString())); } } numberOfRetries = taskRetries.size(); } else { numberOfRetries = 0; } if (retries != null) { retries.close(); } } catch (IOException e) { throw new MotechException("Error loading raw file config to properties", e); } setRetryParameters(task, metadata, params, retryInterval, numberOfRetries); }</code><technical_language>props != null</technical_language>

Target:
private void getRetriesFromSettings(Task task, Map<String, Object> params, Map<String, Object> metadata) { List<Integer> retryInterval = new ArrayList<>(); int numberOfRetries; try (InputStream retries = settings.getRawConfig(TASK_PROPERTIES_FILE_NAME)){ if(retries != null) { Properties props = new Properties(); props.load(retries); for (Map.Entry<Object, Object> entry : props.entrySet()) { retryInterval.add(0, Integer.valueOf(entry.getValue().toString())); } numberOfRetries = retryInterval.size(); } else { numberOfRetries = 0; } } catch (IOException e) { throw new MotechException("Error loading raw file config to properties", e); } setRetryParameters(task, metadata, params, retryInterval, numberOfRetries); }
Source:
<code>public boolean isFileResolverCachingEnabled() { <START> return fileSystemOptions.isFileResolverCachingEnabled(); <END> }</code><technical_language>missing null check</technical_language>

Target:
public boolean isFileResolverCachingEnabled() { if (fileSystemOptions == null) { return DEFAULT_FILE_CACHING_ENABLED; } return fileSystemOptions.isFileResolverCachingEnabled(); }
Source:
<code>private Resource newResourceFrom(final ItemReference reference) { final Path path = Path.valueOf(reference.getPath()); switch (reference.getType()) { case "file": <START> return resourceFactory.newFileImpl(path, urlModifier.modify(ps.getFileContentUrl(path)), this); <END> case "folder": return resourceFactory.newFolderImpl(path, this); case "project": final Optional<ProjectConfigDto> config = findProjectConfigDto(path); if (config.isPresent()) { return resourceFactory.newProjectImpl(config.get(), this); } else { return resourceFactory.newFolderImpl(path, this); } default: throw new IllegalArgumentException("Failed to recognize resource type to create."); } }</code><technical_language>link reference provided server-side</technical_language>

Target:
private Resource newResourceFrom(final ItemReference reference) { final Path path = Path.valueOf(reference.getPath()); switch (reference.getType()) { case "file": final Link link = reference.getLink(GET_CONTENT_REL); return resourceFactory.newFileImpl(path, link.getHref(), this); case "folder": return resourceFactory.newFolderImpl(path, this); case "project": final Optional<ProjectConfigDto> config = findProjectConfigDto(path); if (config.isPresent()) { return resourceFactory.newProjectImpl(config.get(), this); } else { return resourceFactory.newFolderImpl(path, this); } default: throw new IllegalArgumentException("Failed to recognize resource type to create."); } }
Source:
<code>public void shouldSaveCondition() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Rule rule = new RuleDataGen().host(host).nextPersisted(); final ConditionGroup conditionGroup = new ConditionGroupDataGen().rule(rule).next(); <START> this.addRulesPermission(role, host, true); <END> rulesAPI.saveConditionGroup(conditionGroup, user, false); List<Rule> allRules = rulesAPI.getAllRules(user, false); checkCondition(user, conditionGroup, allRules); }</code><technical_language>create a variable for parameter understand boolean addPublishPermsForRules = true;</technical_language>

Target:
public void shouldSaveCondition() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Rule rule = new RuleDataGen().host(host).nextPersisted(); final ConditionGroup conditionGroup = new ConditionGroupDataGen().rule(rule).next(); addRulesPublishPermissions(role, host); rulesAPI.saveConditionGroup(conditionGroup, user, false); List<Rule> allRules = rulesAPI.getAllRules(user, false); createConditionAndCheck(user, conditionGroup, allRules); }
Source:
<code>public String toString() { try { return objectMapper.writeValueAsString(this.clientSideRequestStatistics); }catch (JsonProcessingException e) { <START> logger.error("Error while parsing diagnostics " + e.getOriginalMessage()); <END> } return StringUtils.EMPTY; }</code><technical_language>errors logged pattern logger.error("Error while parsing diagnostics", e) reason else</technical_language>

Target:
public String toString() { try { return objectMapper.writeValueAsString(this.clientSideRequestStatistics); }catch (JsonProcessingException e) { logger.error("Error while parsing diagnostics " + e); } return StringUtils.EMPTY; }
Source:
<code>public AbstractApplicationRunner(Config config) { super(config); <START> this.streamGraph = new StreamGraphImpl(this, config); <END> this.systemAdmins = new SystemAdmins(config); this.streamManager = new StreamManager(systemAdmins); }</code><technical_language>love some docs scope of AppRunner - currently, appRunner.run(app) allows for multiple applications run instance of runner (atleast api disallow it). this change of instantiating StreamGraph in constructor, restricting scope running a single application? If not, do distinguish StreamGraphs of 2 apps runner</technical_language>

Target:
public AbstractApplicationRunner(Config config) { super(config); this.graphSpec = new StreamGraphSpec(this, config); this.systemAdmins = new SystemAdmins(config); this.streamManager = new StreamManager(systemAdmins); }
Source:
<code>public void initialise() { CoreRegistry.put(BehaviorSystem.class, this); List<BehaviorNodeComponent> items = Lists.newArrayList(); Collection<Prefab> prefabs = CoreRegistry.get(PrefabManager.class).listPrefabs(BehaviorNodeComponent.class); for (Prefab prefab : prefabs) { <START> EntityRef entityRef = CoreRegistry.get(EntityManager.class).create(prefab); <END> items.add(entityRef.getComponent(BehaviorNodeComponent.class)); } CoreRegistry.put(BehaviorNodeFactory.class, new BehaviorNodeFactory(items)); }</code><technical_language>@In'ed entityManager here. (and @In PrefabManager)</technical_language>

Target:
public void initialise() { CoreRegistry.put(BehaviorSystem.class, this); List<BehaviorNodeComponent> items = Lists.newArrayList(); Collection<Prefab> prefabs = prefabManager.listPrefabs(BehaviorNodeComponent.class); for (Prefab prefab : prefabs) { EntityRef entityRef = entityManager.create(prefab); items.add(entityRef.getComponent(BehaviorNodeComponent.class)); } CoreRegistry.put(BehaviorNodeFactory.class, new BehaviorNodeFactory(items)); }
Source:
<code><START> public SavedAttachment(String name, long revpos, long seq, byte[] key, String type, File file) { <END> this.name = name; this.revpos = revpos; this.seq = seq; this.key = key; this.type = type; this.file = file; }</code><technical_language>long enough tempted a small Builder, pretty easy switch revpos seq accident in Java's world of unnamed arguments</technical_language>

Target:
protected SavedAttachment(String name, long revpos, long seq, byte[] key, String type, File file) { this.name = name; this.revpos = revpos; this.seq = seq; this.key = key; this.type = type; this.file = file; }
Source:
<code>protected File createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); <START> File chmodFile = getChmodFile(); <END> if (chmodFile == null) { throw new IOException("Can't find the chmod command in order to change the permissions of file \"" + filePath + "\"."); } Process chmodProcess = Runtime.getRuntime().exec(chmodFile.getAbsolutePath() + " 600 " + filePath); try { int chmodExitCode = chmodProcess.waitFor(); if (chmodExitCode != 0) { throw new IOException("Failed to change permissions for file \"" + filePath + "\", the chmod command returns exit code " + chmodExitCode + "\"."); } } catch (InterruptedException ie) { throw new IOException("Failed to change permissions for file \"" + filePath + "\"", ie); } BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.flush(); return temp; }</code><technical_language>Lets this simple, put "/bin/chmod" "chmod" try check if file exists. If execution fail get error anyway, this: java.io.IOException: run program "chmod": error=2, file directory java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) java.lang.Runtime.exec(Runtime.java:615) java.lang.Runtime.exec(Runtime.java:448) java.lang.Runtime.exec(Runtime.java:345)</technical_language>

Target:
protected File createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); Process chmodProcess = Runtime.getRuntime().exec("chmod 600 " + filePath); try { int chmodExitCode = chmodProcess.waitFor(); if (chmodExitCode != 0) { throw new IOException("Failed to change permissions for file \"" + filePath + "\", the chmod command returns exit code " + chmodExitCode + "\"."); } } catch (InterruptedException ie) { throw new IOException("Failed to change permissions for file \"" + filePath + "\"", ie); } BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.flush(); return temp; }
Source:
<code>public void onModified(List<KubernetesConfigMap> configMaps) { final KubernetesConfigMap configMap = checkConfigMaps(configMaps, configMapName); if (!configMap.getData().equals(previousData)) { if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { synchronized (lock) { if (running) { <START> leaderElectionEventHandler.onLeaderInformationChange( getLeaderInformationFromConfigMap(configMap)); <END> } } } previousData.clear(); previousData.putAll(configMap.getData()); } }</code><technical_language>a configMap this for storing completed checkpoint pointers? I no, onModified called added a new checkpoint pointer</technical_language>

Target:
public void onModified(List<KubernetesConfigMap> configMaps) { final KubernetesConfigMap configMap = checkConfigMaps(configMaps, configMapName); if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { leaderElectionEventHandler.onLeaderInformationChange(getLeaderInformationFromConfigMap(configMap)); } }
Source:
<code>public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.inflate(parent.getContext(), R.layout.menu_spinner, null); } if (mIconResource > 0) { ImageView iconView = (ImageView) convertView.findViewById(R.id.menu_spinner_icon); iconView.setImageResource(mIconResource); } TextView titleView = (TextView) convertView.findViewById(R.id.menu_spinner_title); <START> titleView.setText(String.format(mTitle, getCount() - 2)); <END> if (hasItems() && position < mItems.size()) { TextView nameView = (TextView) convertView.findViewById(R.id.menu_spinner_name); nameView.setText(mItems.get(position).getName()); } return convertView; }</code><technical_language>Oops, missed one! Good catch</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.inflate(parent.getContext(), R.layout.menu_spinner, null); } if (mIconResource > 0) { ImageView iconView = (ImageView) convertView.findViewById(R.id.menu_spinner_icon); iconView.setImageResource(mIconResource); } TextView titleView = (TextView) convertView.findViewById(R.id.menu_spinner_title); titleView.setText(String.format(mTitle, getCount() + mDisplayBaseCount)); if (hasItems() && position < mItems.size()) { TextView nameView = (TextView) convertView.findViewById(R.id.menu_spinner_name); nameView.setText(mItems.get(position).getName()); } return convertView; }
Source:
<code>private IStatus runWait(IProgressMonitor monitor) { boolean allStarted = false; long startTime = System.currentTimeMillis(); long endTime = startTime + maxWait; IModule[] modules = server.getModules(); <START> monitor.beginTask("Verifying Module States for " + server.getName(), maxWait * 1000); END> while( !allStarted && System.currentTimeMillis() < endTime) { allStarted = true; long thisLoopStart = System.currentTimeMillis(); for( int i = 0; i < modules.length; i++ ) { IModule[] temp = new IModule[]{modules[i]}; int state = verifier.getModuleState(server, temp, new SubProgressMonitor(monitor, 1000)); ((Server)server).setModuleState(temp, state); boolean started = state == IServer.STATE_STARTED; allStarted = allStarted && started; ((Server)server).setModuleState(temp, state); } try { Thread.sleep(500); } catch(InterruptedException ie) { } long timeDif = System.currentTimeMillis() - thisLoopStart; monitor.worked((int)timeDif - (modules.length * 100)); } return Status.OK_STATUS; }</code><technical_language>"Checking module states for " + server.getName() progress/job name wording</technical_language>

Target:
private IStatus runWait(IProgressMonitor monitor) { boolean allStarted = false; long startTime = System.currentTimeMillis(); long endTime = startTime + maxWait; IModule[] modules = server.getModules(); monitor.beginTask("Checking module states for " + server.getName(), maxWait * 1000); while( !allStarted && System.currentTimeMillis() < endTime) { allStarted = true; long thisLoopStart = System.currentTimeMillis(); for( int i = 0; i < modules.length; i++ ) { IModule[] temp = new IModule[]{modules[i]}; int state = verifier.getModuleState(server, temp, new SubProgressMonitor(monitor, 1000)); ((Server)server).setModuleState(temp, state); boolean started = state == IServer.STATE_STARTED; allStarted = allStarted && started; ((Server)server).setModuleState(temp, state); } try { Thread.sleep(500); } catch(InterruptedException ie) { } long timeDif = System.currentTimeMillis() - thisLoopStart; monitor.worked((int)timeDif - (modules.length * 100)); } return Status.OK_STATUS; }
Source:
<code>Set<AgentInfo> selectAgent(User user, Set<AgentInfo> allFreeAgents, int agentCount) { <START> Set<AgentInfo> recentlyUsedAgents = hazelcastService.getOrDefault(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), emptySet()); <END> Stream<AgentInfo> ownedFreeAgentStream = getFreeAgentStream(recentlyUsedAgents, allFreeAgents, agentInfo -> isOwnedAgent(agentInfo, user.getUserId())); Stream<AgentInfo> freeAgentStream = getFreeAgentStream(recentlyUsedAgents, allFreeAgents, this::isCommonAgent); return concat(ownedFreeAgentStream, freeAgentStream).limit(agentCount).collect(toSet()); }</code><technical_language>~~How stream style before? Get recentlyUsedAgents a stream then, concat streams limit agentCount.~~ I understand expected. complicate agent... extract a comparator for AgentInfo getFreeAgentStream method</technical_language>

Target:
Set<AgentInfo> selectAgent(User user, Set<AgentInfo> allFreeAgents, int agentCount) { Set<AgentInfo> recentlyUsedAgents = hazelcastService.getOrDefault(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), emptySet()); Comparator<AgentInfo> recentlyUsedPriorityComparator = (agent1, agent2) -> { if (recentlyUsedAgents.contains(agent1)) { return -1; } if (recentlyUsedAgents.contains(agent2)) { return 1; } return 0; }; Stream<AgentInfo> ownedFreeAgentStream = allFreeAgents .stream() .filter(agentInfo -> isOwnedAgent(agentInfo, user.getUserId())) .sorted(recentlyUsedPriorityComparator); Stream<AgentInfo> freeAgentStream = allFreeAgents .stream() .filter(this::isCommonAgent) .sorted(recentlyUsedPriorityComparator); return concat(ownedFreeAgentStream, freeAgentStream) .limit(agentCount) .collect(toSet()); }
Source:
<code>public void cancelResourceRequest(SamzaResourceRequest request) { <START> synchronized (lock) { <END> requestsQueue.remove(request); if (hostAffinityEnabled) { requestsToCountMap.get(request.getPreferredHost()).decrementAndGet(); } manager.cancelResourceRequest(request); } }</code><technical_language>Log a message describing is cancelled</technical_language>

Target:
public void cancelResourceRequest(SamzaResourceRequest request) { log.info("Canceling resource request on for {}", request.getPreferredHost(), request.getContainerID()); synchronized (lock) { requestsQueue.remove(request); if (hostAffinityEnabled) { requestsToCountMap.get(request.getPreferredHost()).decrementAndGet(); } manager.cancelResourceRequest(request); } }
Source:
<code>private static boolean causedByLocalizationException(Throwable ex) { if (ex == null) { return false; } if (ex instanceof NoLocalizedTextException) { return true; } <START> return causedByLocalizationException(ex.getCause()); <END> }</code><technical_language>collapse conditional branches a single boolean expression</technical_language>

Target:
private static boolean causedByLocalizationException(Throwable ex) { return ex != null && (ex instanceof NoLocalizedTextException || causedByLocalizationException(ex.getCause())); }
Source:
<code>public WorkspaceProject resolveProject(final Space space, final String projectName, final String branchName) { <START> WorkspaceProject workspaceProject = resolveProject(space, projectName); <END> if (branchName == null) { return workspaceProject; } if (workspaceProject != null) { for (final Branch branch : workspaceProject.getRepository().getBranches()) { if (branch.getName().equals(branchName)) { return resolveProject(space, branch); } } } return new WorkspaceProject(workspaceProject.getOrganizationalUnit(), workspaceProject.getRepository(), workspaceProject.getBranch(), null); }</code><technical_language>Missing indentation in this method</technical_language>

Target:
public WorkspaceProject resolveProject(final Space space, final String projectName, final String branchName) { WorkspaceProject workspaceProject = resolveProject(space, projectName); if (workspaceProject == null) { throw new IllegalArgumentException("project " + projectName + " not found."); } if (branchName == null) { return workspaceProject; } for (final Branch branch : workspaceProject.getRepository().getBranches()) { if (branch.getName().equals(branchName)) { return resolveProject(space, branch); } } throw new IllegalArgumentException("branch " + branchName + " not found."); }
Source:
<code>public Row next() { <START> setNextBatchIfNeeded(); <END> if (batch == null) { throw new NoSuchElementException(); } Row res = batch.get(position++); if (position == batch.size()) { batch = null; position = 0; requestNextBatch(); } return res; }</code><technical_language>implies next called preceding hasNext call, is possible</technical_language>

Target:
public Row next() { if (!hasNext()) { throw new NoSuchElementException(); } assert batch != null; Row res = batch.get(position++); if (position == batch.size()) { batch = null; position = 0; requestNextBatch(); } return res; }
Source:
<code>public static void until(Callable<Boolean> condition, long timeout, TimeUnit timeUnit) { <START> until(condition, 10, TimeUnit.SECONDS, 50); <END> }</code><technical_language>this passing parameters 'timeout' 'timeUnit'</technical_language>

Target:
public static void until(Callable<Boolean> condition, long timeout, TimeUnit timeUnit) { until(condition, timeout, timeUnit, 50); }
Source:
<code>public Response execute() throws IOException { try { return super.execute(); } catch (QosIoException e) { ListenableFuture<Response> futureResponse = exceptionHandler.handle(this, e); try { return futureResponse.get(); } catch (ExecutionException executionException) { Throwable cause = executionException.getCause(); if (cause instanceof QosIoException) { <START> throw (QosIoException) cause; <END> } else { throw new IOException("Failed to execute request", cause); } } catch (InterruptedException interruptedException) { throw new IOException("Failed to execute request (interrupted?)", interruptedException); } } }</code><technical_language>Throwing unwrapped exceptions another thread leads weird stack traces. clone exception here? original QosException original thread's stack trace, preserve trace user need</technical_language>

Target:
public Response execute() throws IOException { try { return super.execute(); } catch (QosIoException e) { ListenableFuture<Response> futureResponse = exceptionHandler.handle(this, e); try { return futureResponse.get(); } catch (ExecutionException executionException) { Throwable cause = executionException.getCause(); if (cause instanceof QosIoException) { QosIoException qosIoException = (QosIoException) cause; throw new QosIoException(qosIoException.getQosException(), qosIoException.getResponse()); } else { throw new IOException("Failed to execute request", cause); } } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); throw new IOException("Failed to execute request (interrupted?)", interruptedException); } } }
Source:
<code>public void deleteTest() { try { String insertBeforeKey = "user0"; HashMap<String, ByteIterator> insertBeforeMap = insertRow(insertBeforeKey); String deleteKey = "user1"; insertRow(deleteKey); String insertAfterKey = "user2"; <START> HashMap<String, ByteIterator> insertAfterMap = insertRow(insertAfterKey); <END> jdbcDBClient.delete(TABLE_NAME, deleteKey); ResultSet resultSet = jdbcConnection.prepareStatement( String.format("SELECT * FROM %s", TABLE_NAME) ).executeQuery(); int totalRows = 0; while (resultSet.next()) { assertNotEquals("Assert this is not the deleted row key", deleteKey, resultSet.getString(KEY_FIELD)); totalRows++; } assertEquals("Assert we ended with the correct number of rows", totalRows, 2); resultSet.close(); } catch (SQLException e) { e.printStackTrace(); fail("Failed deleteTest"); } }</code><technical_language>used</technical_language>

Target:
public void deleteTest() { try { insertRow("user0"); String deleteKey = "user1"; insertRow(deleteKey); insertRow("user2"); jdbcDBClient.delete(TABLE_NAME, deleteKey); ResultSet resultSet = jdbcConnection.prepareStatement( String.format("SELECT * FROM %s", TABLE_NAME) ).executeQuery(); int totalRows = 0; while (resultSet.next()) { assertNotEquals("Assert this is not the deleted row key", deleteKey, resultSet.getString(KEY_FIELD)); totalRows++; } assertEquals("Assert we ended with the correct number of rows", totalRows, 2); resultSet.close(); } catch (SQLException e) { e.printStackTrace(); fail("Failed deleteTest"); } }