auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static long parseParamDate(final String diff) throws java.text.ParseException { String secs = "00"; String mins = "00"; String hours = "00"; String date = "01"; String month = "01"; String year = "0000"; final String[] units = diff.split("[.]"); for (final String unit : units) { if (unit.matches("[YMDhms][0-9]+")) { final char unitdesc = unit.charAt(0); switch (unitdesc) { case 's': secs = unit.replace("s", "00"); secs = secs.substring(secs.length()-2, secs.length()); break; case 'm': mins = unit.replace("m", "00"); mins = mins.substring(mins.length()-2, mins.length()); break; case 'h': hours = unit.replace("h", "0"); hours = hours.substring(hours.length()-2, hours.length()); break; case 'D': date = unit.replace("D", "00"); date = date.substring(date.length()-2, date.length()); break; case 'M': month = unit.replace("M", "00"); month = month.substring(month.length()-2, month.length()); break; case 'Y': year = unit.replace("Y", "0000"); year = year.substring(year.length()-4, year.length()); break; } } } final StringBuilder dateString = new StringBuilder(year); dateString.append("-"); dateString.append(month); dateString.append("-"); dateString.append(date); dateString.append("T"); dateString.append(hours); dateString.append(":"); dateString.append(mins); dateString.append(":"); dateString.append(secs); <START> dateString.append(".000Z"); <END> return Constants.DATE_FORMAT.parse(dateString.toString()).getTime(); }</code><technical_language>string appends do dateString.append("-").append(month).append("-")</technical_language>

Target:
public static long parseParamDate(final String diff) throws java.text.ParseException { String secs = "00"; String mins = "00"; String hours = "00"; String date = "01"; String month = "01"; String year = "0000"; final String[] units = diff.split("[.]"); for (final String unit : units) { if (unit.matches("[YMDhms][0-9]+")) { final char unitdesc = unit.charAt(0); switch (unitdesc) { case 's': secs = unit.replace("s", "00"); secs = secs.substring(secs.length()-2, secs.length()); break; case 'm': mins = unit.replace("m", "00"); mins = mins.substring(mins.length()-2, mins.length()); break; case 'h': hours = unit.replace("h", "0"); hours = hours.substring(hours.length()-2, hours.length()); break; case 'D': date = unit.replace("D", "00"); date = date.substring(date.length()-2, date.length()); break; case 'M': month = unit.replace("M", "00"); month = month.substring(month.length()-2, month.length()); break; case 'Y': year = unit.replace("Y", "0000"); year = year.substring(year.length()-4, year.length()); break; } } } final StringBuilder dateString = new StringBuilder(year) .append("-") .append(month) .append("-") .append(date) .append("T") .append(hours) .append(":") .append(mins) .append(":") .append(secs) .append(".000Z"); return Constants.DATE_FORMAT.parse(dateString.toString()).getTime(); }
Source:
<code>public void close() { log.info("Calling close on snapshot transaction manager"); if (!isClosed.compareAndSet(false, true)) { log.info("Snapshot transaction manager has already been closed, performing no action"); return; <START> } <END> try (ShutdownRunner shutdownRunner = new ShutdownRunner()) { shutdownRunner.shutdownSafely(super::close); shutdownRunner.shutdownSafely(cleaner::close); shutdownRunner.shutdownSafely(keyValueService::close); shutdownRunner.shutdownSafely(() -> shutdownExecutor(deleteExecutor)); shutdownRunner.shutdownSafely(() -> shutdownExecutor(getRangesExecutor)); shutdownRunner.shutdownSafely(this::closeLockServiceIfPossible); for (Runnable callback : Lists.reverse(closingCallbacks)) { shutdownRunner.shutdownSafely(callback); } shutdownRunner.shutdownSafely(metricsManager::deregisterMetrics); } }</code><technical_language>logging end of method exit</technical_language>

Target:
public void close() { log.info("Calling close on snapshot transaction manager"); if (!isClosed.compareAndSet(false, true)) { log.info("Snapshot transaction manager has already been closed, performing no action"); return; } try (ShutdownRunner shutdownRunner = new ShutdownRunner()) { shutdownRunner.shutdownSafely(super::close); shutdownRunner.shutdownSafely(cleaner::close); shutdownRunner.shutdownSafely(keyValueService::close); shutdownRunner.shutdownSafely(() -> shutdownExecutor(deleteExecutor)); shutdownRunner.shutdownSafely(() -> shutdownExecutor(getRangesExecutor)); shutdownRunner.shutdownSafely(this::closeLockServiceIfPossible); for (Runnable callback : Lists.reverse(closingCallbacks)) { shutdownRunner.shutdownSafely(callback); } shutdownRunner.shutdownSafely(metricsManager::deregisterMetrics); log.info("Close callbacks complete in snapshot transaction manager"); } log.info("Closed snapshot transaction manager without any errors"); }
Source:
<code>public void move(Collection<Path> pathsToDelete, <START> Collection<PathMetadata> pathsToCreate, ITtlTimeProvider ttlTimeProvider) throws IOException { <END> if (pathsToDelete == null && pathsToCreate == null) { return; } LOG.debug("Moving paths of table in region {}: paths to delete and {}" + " paths to create", tableName, region, pathsToDelete == null ? 0 : pathsToDelete.size(), pathsToCreate == null ? 0 : pathsToCreate.size()); LOG.trace("move: pathsToDelete = {}, pathsToCreate = {}", pathsToDelete, pathsToCreate); Collection<DDBPathMetadata> newItems = new ArrayList<>(); if (pathsToCreate != null) { newItems.addAll(completeAncestry(pathMetaToDDBPathMeta(pathsToCreate))); } if (pathsToDelete != null) { for (Path meta : pathsToDelete) { final PathMetadata pmTombstone = PathMetadata.tombstone(meta); pmTombstone.setLastUpdated(ttlTimeProvider.getNow()); newItems.add(new DDBPathMetadata(pmTombstone)); } } processBatchWriteRequest(null, pathMetadataToItem(newItems)); }</code><technical_language>nit: line width</technical_language>

Target:
public void move(Collection<Path> pathsToDelete, Collection<PathMetadata> pathsToCreate, ITtlTimeProvider ttlTimeProvider) throws IOException { if (pathsToDelete == null && pathsToCreate == null) { return; } LOG.debug("Moving paths of table in region {}: paths to delete and {}" + " paths to create", tableName, region, pathsToDelete == null ? 0 : pathsToDelete.size(), pathsToCreate == null ? 0 : pathsToCreate.size()); LOG.trace("move: pathsToDelete = {}, pathsToCreate = {}", pathsToDelete, pathsToCreate); Collection<DDBPathMetadata> newItems = new ArrayList<>(); if (pathsToCreate != null) { newItems.addAll(completeAncestry(pathMetaToDDBPathMeta(pathsToCreate))); } if (pathsToDelete != null) { for (Path meta : pathsToDelete) { Preconditions.checkArgument(ttlTimeProvider != null, "ttlTimeProvider" + " must not be null"); final PathMetadata pmTombstone = PathMetadata.tombstone(meta); pmTombstone.setLastUpdated(ttlTimeProvider.getNow()); newItems.add(new DDBPathMetadata(pmTombstone)); } } processBatchWriteRequest(null, pathMetadataToItem(newItems)); }
Source:
<code>private void validate() { <START> inOrderOrEqual(expiryDate, paymentCurrencyAmount.getDate().getUnadjusted(), "expiryDate", "underlying.paymentDate"); <END> }</code><technical_language>Need check Currency in AdjustablePayment is of currency pair</technical_language>

Target:
private void validate() { inOrderOrEqual(expiryDate, paymentCurrencyAmount.getDate().getUnadjusted(), "expiryDate", "underlying.paymentDate"); ArgChecker.isTrue(index.getCurrencyPair().contains(paymentCurrencyAmount.getCurrency()), "The payment currency must be one of the underlying currency pairs"); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Partition partition = (Partition) o; <START> if (id == null ^ partition.id == null){ <END> return false; } return id.equals(partition.id); }</code><technical_language>I this check is unnecessary omitted. id is supposed non-null, construction of Partition fail otherwise</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Partition partition = (Partition) o; return id.equals(partition.id); }
Source:
<code>public Plan createPlan(Session session, @Language("SQL") String sql, List<PlanOptimizer> optimizers, LogicalPlanner.Stage stage) { Statement wrapped = sqlParser.createStatement(sql, createParsingOptions(session)); Statement statement = unwrapExecuteStatement(wrapped, sqlParser, session); List<Expression> parameters = emptyList(); if (wrapped instanceof Execute) { parameters = ((Execute) wrapped).getParameters(); } validateParameters(statement, parameters); assertFormattedSql(sqlParser, createParsingOptions(session), statement); PlanNodeIdAllocator idAllocator = new PlanNodeIdAllocator(); QueryExplainer queryExplainer = new QueryExplainer( optimizers, planFragmenter, metadata, nodePartitioningManager, accessControl, sqlParser, statsCalculator, costCalculator, nodeManager, <START> new NodeSchedulerConfig().setIncludeCoordinator(true), <END> dataDefinitionTask); Analyzer analyzer = new Analyzer(session, metadata, sqlParser, accessControl, Optional.of(queryExplainer), parameters); LogicalPlanner logicalPlanner = new LogicalPlanner(session, optimizers, new PlanSanityChecker(true), idAllocator, metadata, sqlParser); Analysis analysis = analyzer.analyze(statement); return logicalPlanner.plan(analysis, stage); }</code><technical_language>This config is created in this class. Create in in LocalQueryRunner constructor store a field, is same</technical_language>

Target:
public Plan createPlan(Session session, @Language("SQL") String sql, List<PlanOptimizer> optimizers, LogicalPlanner.Stage stage) { Statement wrapped = sqlParser.createStatement(sql, createParsingOptions(session)); Statement statement = unwrapExecuteStatement(wrapped, sqlParser, session); List<Expression> parameters = emptyList(); if (wrapped instanceof Execute) { parameters = ((Execute) wrapped).getParameters(); } validateParameters(statement, parameters); assertFormattedSql(sqlParser, createParsingOptions(session), statement); PlanNodeIdAllocator idAllocator = new PlanNodeIdAllocator(); QueryExplainer queryExplainer = new QueryExplainer( optimizers, planFragmenter, metadata, nodePartitioningManager, accessControl, sqlParser, statsCalculator, costCalculator, nodeManager, nodeSchedulerConfig, dataDefinitionTask); Analyzer analyzer = new Analyzer(session, metadata, sqlParser, accessControl, Optional.of(queryExplainer), parameters); LogicalPlanner logicalPlanner = new LogicalPlanner(session, optimizers, new PlanSanityChecker(true), idAllocator, metadata, sqlParser); Analysis analysis = analyzer.analyze(statement); return logicalPlanner.plan(analysis, stage); }
Source:
<code>protected TaskResult callExecutor(Path projectPath, String type, TaskRequest mergedRequest) { OperatorFactory factory = registry.get(mergedRequest, type); if (factory == null) { throw new ConfigException("Unknown task type: " + type); } SecretStore secretStore = secretStoreManager.getSecretStore(mergedRequest.getSiteId()); Config grants = mergedRequest.getConfig().getNestedOrGetEmpty("_secrets"); SecretAccessList secretAccessList = factory.getSecretAccessList(); final Set<String> declaredSecretKeys = ImmutableSet.copyOf(secretAccessList.getSecretKeys()); SecretAccessContext secretContext = SecretAccessContext.builder() .siteId(mergedRequest.getSiteId()) .projectId(mergedRequest.getProjectId()) .revision(mergedRequest.getRevision().get()) .workflowName(mergedRequest.getWorkflowName()) .taskName(mergedRequest.getTaskName()) .operatorType(type) .build(); DefaultSecretProvider secretProvider = new DefaultSecretProvider( secretContext, secretAccessPolicy, grants, (key) -> declaredSecretKeys.contains(key), secretStore); PrivilegedVariables privilegedVariables = GrantedPrivilegedVariables.build( <START> mergedRequest.getConfig().getNestedOrGetEmpty("_env"), <END> mergedRequest.getConfig(), GrantedPrivilegedVariables.privilegedSecretProvider(secretContext, secretAccessPolicy, secretStore)); OperatorContext context = new DefaultOperatorContext( projectPath, mergedRequest, secretProvider, privilegedVariables); Operator operator = factory.newOperator(context); return operator.run(); }</code><technical_language>Is _env a valid configuration key for operators? "environment" in system environment variables</technical_language>

Target:
protected TaskResult callExecutor(Path projectPath, String type, TaskRequest mergedRequest) { OperatorFactory factory = registry.get(mergedRequest, type); if (factory == null) { throw new ConfigException("Unknown task type: " + type); } SecretStore secretStore = secretStoreManager.getSecretStore(mergedRequest.getSiteId()); Config grants = mergedRequest.getConfig().getNestedOrGetEmpty("_secrets"); SecretAccessList secretAccessList = factory.getSecretAccessList(); final Set<String> declaredSecretKeys = ImmutableSet.copyOf(secretAccessList.getSecretKeys()); SecretAccessContext secretContext = SecretAccessContext.builder() .siteId(mergedRequest.getSiteId()) .projectId(mergedRequest.getProjectId()) .revision(mergedRequest.getRevision().get()) .workflowName(mergedRequest.getWorkflowName()) .taskName(mergedRequest.getTaskName()) .operatorType(type) .build(); DefaultSecretProvider secretProvider = new DefaultSecretProvider( secretContext, secretAccessPolicy, grants, (key) -> declaredSecretKeys.contains(key), secretStore); PrivilegedVariables privilegedVariables = GrantedPrivilegedVariables.build( mergedRequest.getLocalConfig().getNestedOrGetEmpty("_env"), mergedRequest.getConfig(), GrantedPrivilegedVariables.privilegedSecretProvider(secretContext, secretAccessPolicy, secretStore)); OperatorContext context = new DefaultOperatorContext( projectPath, mergedRequest, secretProvider, privilegedVariables); Operator operator = factory.newOperator(context); return operator.run(); }
Source:
<code>public void onSettingsRead(final ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception { if (outstandingRemoteSettingsQueue == null) { encoder.writeSettingsAck(ctx, ctx.newPromise()); encoder.remoteSettings(settings); } else { <START> outstandingRemoteSettingsQueue.add(settings); <END> } listener.onSettingsRead(ctx, settings); }</code><technical_language>@Scottmitch consider a queue a callback return a Future notified ack written ? a quick thought this "cleaner"</technical_language>

Target:
public void onSettingsRead(final ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception { if (settingsReceivedConsumer == null) { encoder.writeSettingsAck(ctx, ctx.newPromise()); encoder.remoteSettings(settings); } else { settingsReceivedConsumer.consumeReceivedSettings(settings); } listener.onSettingsRead(ctx, settings); }
Source:
<code>private Provider getCurrentProvider() { UserContext userContext = Context.getUserContext(); Provider currentProvider = null; if (userContext != null && userContext.getAuthenticatedUser() != null) { User currentUser = userContext.getAuthenticatedUser(); Collection<Provider> providers = new HashSet<Provider>(); try { Context.addProxyPrivilege(PrivilegeConstants.VIEW_PROVIDERS); if (currentUser.getPerson() != null) { providers = Context.getProviderService().getProvidersByPerson(currentUser.getPerson(), false); } } finally { Context.removeProxyPrivilege(PrivilegeConstants.VIEW_PROVIDERS); } if (providers.size() > 1) { <START> throw new IllegalStateException("Can't handle users with multiple provider accounts"); <END> } else if (providers.size() == 1) { currentProvider = providers.iterator().next(); } } return currentProvider; }</code><technical_language>smarter simply log error throw exception. I think, start, majority of users of this method care provider, want break a user muliple provider accounts</technical_language>

Target:
private Provider getCurrentProvider() { UserContext userContext = Context.getUserContext(); Provider currentProvider = null; if (userContext != null && userContext.getAuthenticatedUser() != null) { User currentUser = userContext.getAuthenticatedUser(); Collection<Provider> providers = new HashSet<Provider>(); try { Context.addProxyPrivilege(PrivilegeConstants.VIEW_PROVIDERS); if (currentUser.getPerson() != null) { providers = Context.getProviderService().getProvidersByPerson(currentUser.getPerson(), false); } } finally { Context.removeProxyPrivilege(PrivilegeConstants.VIEW_PROVIDERS); } if (providers.size() > 1) { log.warn("Can't handle users with multiple provider accounts"); } else if (providers.size() == 1) { currentProvider = providers.iterator().next(); } } return currentProvider; }
Source:
<code>private static void writeBaseAspect(File f) throws IOException { final PrintWriter writer = new PrintWriter(f); writer.println("package mop;"); writer.println("public aspect BaseAspect {"); writer.println(" pointcut notwithin() :"); writer.println(" !within(sun..*) &&"); writer.println(" !within(java..*) &&"); writer.println(" !within(javax..*) &&"); writer.println(" !within(com.sun..*) &&"); writer.println(" !within(org.dacapo.harness..*) &&"); writer.println(" !within(org.apache.commons..*) &&"); writer.println(" !within(org.apache.geronimo..*) &&"); writer.println(" !within(net.sf.cglib..*) &&"); writer.println(" !within(mop..*) &&"); writer.println(" !within(javamoprt..*) &&"); writer.println(" !within(rvmonitorrt..*) &&"); writer.println(" !within(com.runtimeverification..*);"); writer.println("}"); writer.flush(); writer.close(); <START> } <END></code><technical_language>For now, urgency of task, hardcode generation of manifest file in writeAgentManifest(File f) above. However, I hardcoding generation of BaseAspect.aj file in is a good idea. In work, I add more file in ways for projects. For example, while monitoring projects junit, I add !within(org.junit..*) BaseAspect.aj file, is I want do while monitoring junit itself. point is: I is generate this file JavaMOP this users need change for monitoring projects, want building source weverytime want do that</technical_language>

Target:
private static void writeBaseAspect(File f) throws IOException { final PrintWriter writer = new PrintWriter(f); try { writer.println("package mop;"); writer.println("public aspect BaseAspect {"); writer.println(" pointcut notwithin() :"); writer.println(" !within(sun..*) &&"); writer.println(" !within(java..*) &&"); writer.println(" !within(javax..*) &&"); writer.println(" !within(com.sun..*) &&"); writer.println(" !within(org.dacapo.harness..*) &&"); writer.println(" !within(org.apache.commons..*) &&"); writer.println(" !within(org.apache.geronimo..*) &&"); writer.println(" !within(net.sf.cglib..*) &&"); writer.println(" !within(mop..*) &&"); writer.println(" !within(javamoprt..*) &&"); writer.println(" !within(rvmonitorrt..*) &&"); writer.println(" !within(com.runtimeverification..*);"); writer.println("}"); writer.flush(); } finally { writer.close(); } }
Source:
<code>private void runPatchMetadataTests(EPerson asUser, int expectedStatus) throws Exception { context.turnOffAuthorisationSystem(); <START> Group group = GroupBuilder.createGroup(context).withName("Group").build(); <END> String token = getAuthToken(asUser.getEmail(), password); new MetadataPatchSuite().runWith(getClient(token), "/api/eperson/groups/" + group.getID(), expectedStatus); }</code><technical_language>Again, needs a context.restoreAuthSystemState();</technical_language>

Target:
private void runPatchMetadataTests(EPerson asUser, int expectedStatus) throws Exception { context.turnOffAuthorisationSystem(); Group group = GroupBuilder.createGroup(context).withName("Group").build(); context.restoreAuthSystemState(); String token = getAuthToken(asUser.getEmail(), password); new MetadataPatchSuite().runWith(getClient(token), "/api/eperson/groups/" + group.getID(), expectedStatus); }
Source:
<code>public I_R_Request createRequest(@NonNull final RequestCandidate candidate) { final I_R_Request request = newInstance(I_R_Request.class); ; request.setSummary(candidate.getSummary()); request.setConfidentialType(candidate.getConfidentialType()); request.setAD_Org_ID(candidate.getOrgId().getRepoId()); request.setM_Product_ID(ProductId.toRepoId(candidate.getProductId())); request.setAD_Table_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getAD_Table_ID() : -1); request.setRecord_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getRecord_ID() : -1); request.setC_BPartner_ID(BPartnerId.toRepoId(candidate.getPartnerId())); <START> request.setC_Order_ID(candidate.getOrderId() != null ? candidate.getOrderId().getRepoId() : 0); <END> request.setAD_User_ID(UserId.toRepoId(candidate.getUserId())); request.setR_RequestType_ID(candidate.getRequestTypeId().getRepoId()); request.setM_QualityNote_ID(QualityNoteId.toRepoId(candidate.getQualityNoteId())); request.setPerformanceType(candidate.getPerformanceType()); request.setDateDelivered(TimeUtil.asTimestamp(candidate.getDateDelivered())); saveRecord(request); return request; }</code><technical_language>check if canddiate.getRecordRef().getTableName() equals C_Order => if yes, setC_Order_ID(recordRef's record_ID)</technical_language>

Target:
public I_R_Request createRequest(@NonNull final RequestCandidate candidate) { final I_R_Request request = newInstance(I_R_Request.class); ; request.setSummary(candidate.getSummary()); request.setConfidentialType(candidate.getConfidentialType()); request.setAD_Org_ID(candidate.getOrgId().getRepoId()); request.setM_Product_ID(ProductId.toRepoId(candidate.getProductId())); request.setAD_Table_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getAD_Table_ID() : -1); request.setRecord_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getRecord_ID() : -1); request.setC_BPartner_ID(BPartnerId.toRepoId(candidate.getPartnerId())); request.setC_Order_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getTableName().equals(I_C_Order.Table_Name) ? candidate.getRecordRef().getRecord_ID() : -1 : -1); request.setAD_User_ID(UserId.toRepoId(candidate.getUserId())); request.setR_RequestType_ID(candidate.getRequestTypeId().getRepoId()); request.setM_QualityNote_ID(QualityNoteId.toRepoId(candidate.getQualityNoteId())); request.setPerformanceType(candidate.getPerformanceType()); request.setDateDelivered(TimeUtil.asTimestamp(candidate.getDateDelivered())); saveRecord(request); return request; }
Source:
<code>public LookupDto toDto() { List<LookupFieldDto> lookupFields = new ArrayList<>(); for (String lookupFieldName : getFieldsOrder()) { Field field = getLookupFieldByName(LookupName.getFieldName(lookupFieldName)); LookupFieldType lookupFieldType = LookupFieldType.VALUE; if (isRangeParam(lookupFieldName)) { lookupFieldType = LookupFieldType.RANGE; } else if (isSetParam(lookupFieldName)) { lookupFieldType = LookupFieldType.SET; } String customOperator = getCustomOperators().get(lookupFieldName); boolean useGenericParam = toBoolean(getUseGenericParams().get(lookupFieldName)); if (field != null) { LookupFieldDto lookupField = new LookupFieldDto(field.getId(), field.getName(), lookupFieldType, customOperator, useGenericParam, LookupName.getRelatedFieldName(lookupFieldName)); lookupFields.add(lookupField); } else { <START> LOGGER.info("Can't create LookupFieldDto from field with name {}", lookupFieldName); <END> } } return new LookupDto(id, lookupName, singleObjectReturn, exposedViaRest, lookupFields, readOnly, methodName, fieldsOrder, indexRequired); }</code><technical_language>I exception in this case - correct message. Proceeding in this case</technical_language>

Target:
public LookupDto toDto() { List<LookupFieldDto> lookupFields = new ArrayList<>(); for (String lookupFieldName : getFieldsOrder()) { Field field = getLookupFieldByName(LookupName.getFieldName(lookupFieldName)); LookupFieldType lookupFieldType = LookupFieldType.VALUE; if (isRangeParam(lookupFieldName)) { lookupFieldType = LookupFieldType.RANGE; } else if (isSetParam(lookupFieldName)) { lookupFieldType = LookupFieldType.SET; } String customOperator = getCustomOperators().get(lookupFieldName); boolean useGenericParam = toBoolean(getUseGenericParams().get(lookupFieldName)); if (field != null) { LookupFieldDto lookupField = new LookupFieldDto(field.getId(), field.getName(), lookupFieldType, customOperator, useGenericParam, LookupName.getRelatedFieldName(lookupFieldName)); lookupFields.add(lookupField); } else { throw new LookupWrongFieldNameException(String.format("Can't create LookupFieldDto. Field with given name %s does not exist in %s lookup", lookupFieldName, lookupName)); } } return new LookupDto(id, lookupName, singleObjectReturn, exposedViaRest, lookupFields, readOnly, methodName, fieldsOrder, indexRequired); }
Source:
<code>public List<Type> getTypeParameters() { List<Type> parameters = new ArrayList<>(argumentTypes.size() + 1); <START> argumentTypes.stream() <END> .forEach(parameters::add); parameters.add(returnType); return unmodifiableList(parameters); }</code><technical_language>line</technical_language>

Target:
public List<Type> getTypeParameters() { List<Type> parameters = new ArrayList<>(argumentTypes.size() + 1); parameters.addAll(argumentTypes); parameters.add(returnType); return unmodifiableList(parameters); }
Source:
<code>protected R setUpdateTasks(BoxArray<BoxMetadataUpdateTask> updateTasks) { <START> mBodyMap.put(BoxArray.PUT_ARRAY, updateTasks); <END> return (R) this; }</code><technical_language>Ah. I c called PUT_ARRAY now... I a name "OBJECT" "JSON_OBJECT" string part of BoxRequest. Essentially, this key is telling converting map for request, instead a json object</technical_language>

Target:
protected R setUpdateTasks(BoxArray<BoxMetadataUpdateTask> updateTasks) { mBodyMap.put(BoxRequest.JSON_OBJECT, updateTasks); return (R) this; }
Source:
<code>private void cleanupTimedOutTransactions() { List<TransactionEdit> invalidEdits = null; this.logReadLock.lock(); try { synchronized (this) { if (!isRunning()) { return; } long currentTime = System.currentTimeMillis(); List<Long> timedOut = Lists.newArrayList(); for (Map.Entry<Long, InProgressTx> tx : inProgress.entrySet()) { long expiration = tx.getValue().getExpiration(); if (expiration >= 0L && currentTime > expiration) { timedOut.add(tx.getKey()); LOG.info("Tx invalid list: added tx because of timeout", tx.getKey()); } else if (expiration < 0) { <START> LOG.warn("Transaction has negative expiration time {}. " + <END> "Likely cause is the transaction was not migrated correctly, this transaction cannot be expired", tx.getKey(), expiration); } } if (!timedOut.isEmpty()) { invalidEdits = Lists.newArrayListWithCapacity(timedOut.size()); invalid.addAll(timedOut); for (long tx : timedOut) { committingChangeSets.remove(tx); inProgress.remove(tx); invalidEdits.add(TransactionEdit.createInvalid(tx)); } Collections.sort(invalid); invalidArray = invalid.toLongArray(); LOG.info("Invalidated transactions due to timeout.", timedOut.size()); } } if (invalidEdits != null) { appendToLog(invalidEdits); } } finally { this.logReadLock.unlock(); } }</code><technical_language>in this case expire transaction? a transaction sit good. If due a problem in migration, want log a fatal error abort service running invalid data. problem is need a of clearing state startup succeed. based I expire transaction</technical_language>

Target:
private void cleanupTimedOutTransactions() { List<TransactionEdit> invalidEdits = null; this.logReadLock.lock(); try { synchronized (this) { if (!isRunning()) { return; } long currentTime = System.currentTimeMillis(); List<Long> timedOut = Lists.newArrayList(); for (Map.Entry<Long, InProgressTx> tx : inProgress.entrySet()) { long expiration = tx.getValue().getExpiration(); if (expiration >= 0L && currentTime > expiration) { timedOut.add(tx.getKey()); LOG.info("Tx invalid list: added tx because of timeout", tx.getKey()); } else if (expiration < 0) { LOG.warn("Transaction has negative expiration time {}. Likely cause is the transaction was not " + "migrated correctly, this transaction will be expired immediately", tx.getKey(), expiration); timedOut.add(tx.getKey()); } } if (!timedOut.isEmpty()) { invalidEdits = Lists.newArrayListWithCapacity(timedOut.size()); invalid.addAll(timedOut); for (long tx : timedOut) { committingChangeSets.remove(tx); inProgress.remove(tx); invalidEdits.add(TransactionEdit.createInvalid(tx)); } Collections.sort(invalid); invalidArray = invalid.toLongArray(); LOG.info("Invalidated transactions due to timeout.", timedOut.size()); } } if (invalidEdits != null) { appendToLog(invalidEdits); } } finally { this.logReadLock.unlock(); } }
Source:
<code>public String readString() throws IOException { int len = readLength(); if (len == 0) { <START> log.info("flush <END> packet"); return END; } len -= 4; if (len == 0) { log.info(""); return ""; } byte[] raw; if (len <= lineBuffer.length) raw = lineBuffer; else raw = new byte[len]; IO.readFully(in, raw, 0, len); if (raw[len - 1] == '\n') len--; String decodedBuffer = RawParseUtils.decode(Constants.CHARSET, raw, 0, len); log.info(decodedBuffer); return decodedBuffer; }</code><technical_language>this get output? If frequently debug level spam console. for other log.info calls added in this file</technical_language>

Target:
public String readString() throws IOException { int len = readLength(); if (len == 0) { log.debug("flush-pkt"); return END; } len -= 4; if (len == 0) { log.debug(""); return ""; } byte[] raw; if (len <= lineBuffer.length) raw = lineBuffer; else raw = new byte[len]; IO.readFully(in, raw, 0, len); if (raw[len - 1] == '\n') len--; String decodedBuffer = RawParseUtils.decode(Constants.CHARSET, raw, 0, len); log.debug(decodedBuffer); return decodedBuffer; }
Source:
<code><START> private Node getSourceNode(Diagram diagram, String edgeUuid) { <END> final Iterator<Node> nodes = diagram.getGraph().nodes().iterator(); Node<?, ? extends Edge> sourceNode; while (nodes.hasNext()) { sourceNode = nodes.next(); if (sourceNode.getOutEdges().stream() .filter(edge -> edge.getUUID().equals(edgeUuid)).findFirst() .isPresent()) { return sourceNode; } } return null; }</code><technical_language>condition simplified java sourceNode.getOutEdges().stream() .anyMatch(edge -> edge.getUUID().equals(edgeUuid))</technical_language>

Target:
private Node getSourceNode(Diagram diagram, String edgeUuid) { final Iterator<Node> nodes = diagram.getGraph().nodes().iterator(); Node<?, ? extends Edge> sourceNode; while (nodes.hasNext()) { sourceNode = nodes.next(); if (sourceNode.getOutEdges().stream() .anyMatch(edge -> edge.getUUID().equals(edgeUuid))) { return sourceNode; } } return null; }
Source:
<code>public Status delete(String keyspace, String key) { try { ClientResponse response = mclient.callProcedure("STORE.delete", key, keyspace.getBytes(UTF8)); return response.getStatus() == ClientResponse.SUCCESS ? Status.OK : Status.ERROR; } catch (Exception e) { <START> e.printStackTrace(); <END> return Status.ERROR; } }</code><technical_language>Please log a logging framework instead of printStackTrace</technical_language>

Target:
public Status delete(String keyspace, String key) { try { ClientResponse response = mclient.callProcedure("STORE.delete", key, keyspace.getBytes(UTF8)); return response.getStatus() == ClientResponse.SUCCESS ? Status.OK : Status.ERROR; } catch (Exception e) { logger.error("Error while deleting row", e); return Status.ERROR; } }
Source:
<code>public void validate(Element element, ElementValidation validation) { <START> injectHelper.validate(RootFragment.class, element, validation); <END> if (!validation.isValid()) { return; } validatorHelper.isNotPrivate(element, validation); }</code><technical_language>I wondering allow Fragment extending types, i deliberately want inject custom interfaces well. @RootContext allows types extending Context injected. I do similar here</technical_language>

Target:
public void validate(Element element, ElementValidation validation) { injectHelper.validate(RootFragment.class, element, validation); if (!validation.isValid()) { return; } Element param = injectHelper.getParam(element); validatorHelper.extendsFragment(param, validation); validatorHelper.isNotPrivate(element, validation); }
Source:
<code>public void testTableNames() throws IOException { String[] goodNames = { "a", "1", "_", "_x", "a-._5x", "_a-._5x", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi", "jklmnopqrstuvwxyz1234567890_-." }; String[] badNames = { "-x", ".x", "a!", "a@", "a#", "a$", "a%", "a^", "a&", "a*", "a(", "a+", "a=", "a~", "a`", "a{", "a[", "a|", "a\\", "a/", "a<", "a,", "a?", "a" + RandomStringUtils.random(10, false, false) }; Admin admin = getConnection().getAdmin(); for (String badName : badNames) { boolean failed = false; try { HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(badName)); descriptor.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); admin.createTable(descriptor); } catch (IllegalArgumentException e) { failed = true; } Assert.assertTrue("Should fail as table name: '" + badName + "'", failed); } for(String goodName : goodNames) { TableName tableName = TableName.valueOf(goodName); HTableDescriptor descriptor = new HTableDescriptor(tableName); descriptor.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); try { <START> admin.createTable(descriptor); <END> } finally { try { admin.disableTable(tableName); admin.deleteTable(tableName); } catch (Throwable t) { t.printStackTrace(); } } } }</code><technical_language>test needs fail if exception occurs. fail build if create fails in a legit way. Reporting console do that, unfortunately</technical_language>

Target:
public void testTableNames() throws IOException { String[] goodNames = { "a", "1", "_", "_x", "a-._5x", "_a-._5x", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi", "jklmnopqrstuvwxyz1234567890_-." }; String[] badNames = { "-x", ".x", "a!", "a@", "a#", "a$", "a%", "a^", "a&", "a*", "a(", "a+", "a=", "a~", "a`", "a{", "a[", "a|", "a\\", "a/", "a<", "a,", "a?", "a" + RandomStringUtils.random(10, false, false) }; Admin admin = getConnection().getAdmin(); for (String badName : badNames) { boolean failed = false; try { HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(badName)); descriptor.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); admin.createTable(descriptor); } catch (IllegalArgumentException e) { failed = true; } Assert.assertTrue("Should fail as table name: '" + badName + "'", failed); } for(String goodName : goodNames) { TableName tableName = TableName.valueOf(goodName); HTableDescriptor descriptor = new HTableDescriptor(tableName); descriptor.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); try { if (admin.tableExists(tableName)) { LOG.warn("Not creating the table since it exists: %s", tableName); } else { admin.createTable(descriptor); } } finally { try { admin.disableTable(tableName); admin.deleteTable(tableName); } catch (Throwable t) { LOG.warn("Error cleaning up the table", t); } } } }
Source:
<code>private boolean isValidTransactionEntry(@NonNull OpaqueEntry entry) { Set<UUID> txEntryStreamIds = new HashSet<>(entry.getEntries().keySet()); if (txEntryStreamIds.isEmpty()) { log.info("Log Entry Reader, TX stream Opaque entry is EMPTY, streams_to_replicate={}, empty entry ts={}", streamUUIDs.size(), entry.getVersion()); return false; } if (Collections.disjoint(streamUUIDs, txEntryStreamIds)) { log.debug("Log Entry Reader, TX entry[{}] contains none of the streams of interest, streams={}", entry.getVersion(), txEntryStreamIds); <START> return false; <END> } else { log.debug("Log Entry Reader, valid TX entry[{}] streams={}, ignored streams={}, ", entry.getVersion(), txEntryStreamIds, txEntryStreamIds.removeAll(streamUUIDs)); return true; } }</code><technical_language>need of else</technical_language>

Target:
private boolean isValidTransactionEntry(@NonNull OpaqueEntry entry) { Set<UUID> txEntryStreamIds = new HashSet<>(entry.getEntries().keySet()); if (txEntryStreamIds.isEmpty()) { log.debug("TX Stream entry[{}] :: EMPTY [ignored]", entry.getVersion()); return false; } if (Collections.disjoint(streamUUIDs, txEntryStreamIds)) { log.trace("TX Stream entry[{}] :: contains none of the streams of interest, streams={} [ignored]", entry.getVersion(), txEntryStreamIds); return false; } else { Set<UUID> ignoredTxStreams = txEntryStreamIds.stream().filter(id -> !streamUUIDs.contains(id)) .collect(Collectors.toSet()); txEntryStreamIds.removeAll(ignoredTxStreams); log.debug("TX Stream entry[{}] :: replicate[{}]={}, ignore[{}]={} [valid]", entry.getVersion(), txEntryStreamIds.size(), txEntryStreamIds, ignoredTxStreams.size(), ignoredTxStreams); return true; } }
Source:
<code>public Concat_ws() { super(new Column[] { <START> new Column("org/apache/tajo/storage/text", TajoDataTypes.Type.TEXT), <END> new Column("org/apache/tajo/storage/text", TajoDataTypes.Type.TEXT), new Column("org/apache/tajo/storage/text", TajoDataTypes.Type.TEXT), }); }</code><technical_language>This changed while refactor 'text'</technical_language>

Target:
public Concat_ws() { super(new Column[] { new Column("text", TajoDataTypes.Type.TEXT), new Column("text", TajoDataTypes.Type.TEXT), new Column("text", TajoDataTypes.Type.TEXT), }); }
Source:
<code>private List<RowGroup> createRowGroups( int rowsInStripe, Map<StreamId, Stream> streams, Map<StreamId, ValueInputStream<?>> valueStreams, Map<Integer, List<RowGroupIndex>> columnIndexes, Set<Integer> selectedRowGroups, List<ColumnEncoding> encodings) throws InvalidCheckpointException { ImmutableList.Builder<RowGroup> rowGroupBuilder = ImmutableList.builder(); for (int rowGroupId : selectedRowGroups) { Map<StreamId, StreamCheckpoint> checkpoints = getStreamCheckpoints(includedOrcColumns, types, decompressor.isPresent(), rowGroupId, encodings, streams, columnIndexes); int rowOffset = rowGroupId * rowsInRowGroup; int rowsInGroup = Math.min(rowsInStripe - rowOffset, rowsInRowGroup); <START> rowGroupBuilder.add(createRowGroup(rowGroupId, rowOffset, rowsInGroup, columnIndexes.entrySet().stream().mapToLong(e -> e.getValue().get(rowGroupId).getColumnStatistics().getMinAverageValueSizeInBytes()).sum(), valueStreams, checkpoints)); <END> } return rowGroupBuilder.build(); }</code><technical_language>extract a variable for this large chunk of new code wrap multiple lines</technical_language>

Target:
private List<RowGroup> createRowGroups( int rowsInStripe, Map<StreamId, Stream> streams, Map<StreamId, ValueInputStream<?>> valueStreams, Map<Integer, List<RowGroupIndex>> columnIndexes, Set<Integer> selectedRowGroups, List<ColumnEncoding> encodings) throws InvalidCheckpointException { ImmutableList.Builder<RowGroup> rowGroupBuilder = ImmutableList.builder(); for (int rowGroupId : selectedRowGroups) { Map<StreamId, StreamCheckpoint> checkpoints = getStreamCheckpoints(includedOrcColumns, types, decompressor.isPresent(), rowGroupId, encodings, streams, columnIndexes); int rowOffset = rowGroupId * rowsInRowGroup; int rowsInGroup = Math.min(rowsInStripe - rowOffset, rowsInRowGroup); long minAverageRowBytes = columnIndexes .entrySet() .stream() .mapToLong(e -> e.getValue() .get(rowGroupId) .getColumnStatistics() .getMinAverageValueSizeInBytes()) .sum(); rowGroupBuilder.add(createRowGroup(rowGroupId, rowOffset, rowsInGroup, minAverageRowBytes, valueStreams, checkpoints)); } return rowGroupBuilder.build(); }
Source:
<code>public GameDetails getGameDetails(@RequestParam(value = "token", required = false) String token, @RequestParam("gameId") String gameId) throws AuthenticationException, GameException { UserBean user = authenticationService.authenticateUserByToken(token); GameBean game = gameService.getGameByGameIdWithJoinedUser(user, gameId); int userId = user.getId(); <START> return new GameDetails(game, userId); <END> }</code><technical_language>I this is place need get list of resources</technical_language>

Target:
public GameDetails getGameDetails(@RequestParam(value = "token", required = false) String token, @RequestParam("gameId") String gameId) throws AuthenticationException, GameException { UserBean detailsRequester = authenticationService.authenticateUserByToken(token); GameBean game = gameService.getGameByGameIdWithJoinedUser(detailsRequester, gameId); return new GameDetails(game, detailsRequester.getId()); }
Source:
<code>public void executionFinished(final TestIdentifier testIdentifier, final TestExecutionResult testExecutionResult) { <START> if (!testIdentifier.isContainer()) { <END> final Status status = testExecutionResult.getStatus(); switch (status) { case SUCCESSFUL: listener.onTestPassed(); break; case FAILED: case ABORTED: listener.onTestFailed(); break; } listener.onTestEnd(); } }</code><technical_language>do early return</technical_language>

Target:
public void executionFinished(final TestIdentifier testIdentifier, final TestExecutionResult testExecutionResult) { if (testIdentifier.isContainer()) { return; } final Status status = testExecutionResult.getStatus(); switch (status) { case SUCCESSFUL: listener.onTestPassed(); break; case FAILED: case ABORTED: listener.onTestFailed(); break; } listener.onTestEnd(); }
Source:
<code>private void performAquire(Subscriber<? super ObservableConnection<I, O>> subscriber) { <START> logger.trace("Started to aquire connection"); <END> long startTimeMillis = Clock.newStartTimeMillis(); try { metricEventsSubject.onEvent(ClientMetricsEvent.POOL_ACQUIRE_START); PooledConnection<I, O> idleConnection = getAnIdleConnection(true); if (null != idleConnection) { idleConnection.beforeReuse(); channelFactory.onNewConnection(idleConnection, subscriber); long endTime = Clock.onEndMillis(startTimeMillis); metricEventsSubject.onEvent(ClientMetricsEvent.POOLED_CONNECTION_REUSE, endTime); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_ACQUIRE_SUCCESS, endTime); logger.trace("Returned reused connection"); aquiredConnectionsCounter.incrementAndGet(); } else if (limitDeterminationStrategy.acquireCreationPermit(startTimeMillis, TimeUnit.MILLISECONDS)) { logger.trace("Start to create new connection"); connectionsInCreation.incrementAndGet(); Subscriber<? super ObservableConnection<I, O>> newConnectionSubscriber = newConnectionSubscriber(subscriber, startTimeMillis); try { channelFactory.connect(newConnectionSubscriber, serverInfo, connectionFactory); } catch (Throwable throwable) { newConnectionSubscriber.onError(throwable); } } else { PoolExhaustedException e = new PoolExhaustedException(); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_ACQUIRE_FAILED, Clock.onEndMillis(startTimeMillis), e); subscriber.onError(e); } } catch (Throwable throwable) { metricEventsSubject.onEvent(ClientMetricsEvent.POOL_ACQUIRE_FAILED, Clock.onEndMillis(startTimeMillis), throwable); subscriber.onError(throwable); } }</code><technical_language>I need trace logs</technical_language>

Target:
private void performAquire(Subscriber<? super ObservableConnection<I, O>> subscriber) { long startTimeMillis = Clock.newStartTimeMillis(); try { metricEventsSubject.onEvent(ClientMetricsEvent.POOL_ACQUIRE_START); PooledConnection<I, O> idleConnection = getAnIdleConnection(true); if (null != idleConnection) { idleConnection.beforeReuse(); channelFactory.onNewConnection(idleConnection, subscriber); long endTime = Clock.onEndMillis(startTimeMillis); metricEventsSubject.onEvent(ClientMetricsEvent.POOLED_CONNECTION_REUSE, endTime); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_ACQUIRE_SUCCESS, endTime); aquiredConnectionsCounter.incrementAndGet(); } else if (limitDeterminationStrategy.acquireCreationPermit(startTimeMillis, TimeUnit.MILLISECONDS)) { aquiredConnectionsCounter.incrementAndGet(); Subscriber<? super ObservableConnection<I, O>> newConnectionSubscriber = newConnectionSubscriber(subscriber, startTimeMillis); try { channelFactory.connect(newConnectionSubscriber, serverInfo, connectionFactory); } catch (Throwable throwable) { newConnectionSubscriber.onError(throwable); } } else { PoolExhaustedException e = new PoolExhaustedException(); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_ACQUIRE_FAILED, Clock.onEndMillis(startTimeMillis), e); subscriber.onError(e); } } catch (Throwable throwable) { metricEventsSubject.onEvent(ClientMetricsEvent.POOL_ACQUIRE_FAILED, Clock.onEndMillis(startTimeMillis), throwable); subscriber.onError(throwable); } }
Source:
<code>protected boolean check(final WebContext context, final U profile, final String element) throws HttpAction { if (!profile.containsAttribute(element)) { return false; } <START> if (StringUtils.isEmpty(this.valueToMatch)) { <END> return true; } final Object attributeValues = profile.getAttribute(element); if (attributeValues instanceof Collection) { return Collection.class.cast(attributeValues) .stream() .filter(v -> v.toString().matches(this.valueToMatch)) .findAny() .isPresent(); } return attributeValues.toString().matches(this.valueToMatch); }</code><technical_language>Spring framework is optional dependency. CommonHelper component here</technical_language>

Target:
protected boolean check(final WebContext context, final U profile, final String element) throws HttpAction { if (!profile.containsAttribute(element)) { return false; } if (CommonHelper.isBlank(this.valueToMatch)) { return true; } final Object attributeValues = profile.getAttribute(element); if (attributeValues instanceof Collection) { return Collection.class.cast(attributeValues) .stream() .filter(v -> v.toString().matches(this.valueToMatch)) .findAny() .isPresent(); } return attributeValues.toString().matches(this.valueToMatch); }
Source:
<code>public List<Sample> getLast24hours( @Scope({OAuthScope.SENSORS_BASIC}) final AccessToken accessToken, @PathParam("sensor") String sensor, @QueryParam("from_utc") Long queryEndTimestampUTC) { if (hiddenSensors.contains(sensor)) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } validateQueryRange(queryEndTimestampUTC, DateTime.now(), accessToken.accountId, allowedRangeInSeconds); final int slotDurationInMinutes = 5; final long queryStartTimeUTC = new DateTime(queryEndTimestampUTC, DateTimeZone.UTC).minusHours(24).getMillis(); final Optional<DeviceAccountPair> deviceIdPair = deviceDAO.getMostRecentSensePairByAccountId(accessToken.accountId); if(!deviceIdPair.isPresent()) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } Optional<Device.Color> color = Optional.absent(); if (this.hasColorCompensationEnabled(accessToken.accountId)) { color = senseColorDAO.getColorForSense(deviceIdPair.get().externalDeviceId); } final Optional<Calibration> calibrationOptional = getCalibrationStrict(deviceIdPair.get().externalDeviceId); final List<Sample> timeSeries = deviceDataDAO.generateTimeSeriesByUTCTime(queryStartTimeUTC, queryEndTimestampUTC, accessToken.accountId, deviceIdPair.get().internalDeviceId, slotDurationInMinutes, sensor, missingDataDefaultValue(accessToken.accountId), color, calibrationOptional); if (this.hasDustSmoothEnabled(deviceIdPair.get().externalDeviceId)){ <START> <END> }; return timeSeries; }</code><technical_language>typo</technical_language>

Target:
public List<Sample> getLast24hours( @Scope({OAuthScope.SENSORS_BASIC}) final AccessToken accessToken, @PathParam("sensor") String sensor, @QueryParam("from_utc") Long queryEndTimestampUTC) { if (hiddenSensors.contains(sensor)) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } validateQueryRange(queryEndTimestampUTC, DateTime.now(), accessToken.accountId, allowedRangeInSeconds); final int slotDurationInMinutes = 5; final long queryStartTimeUTC = new DateTime(queryEndTimestampUTC, DateTimeZone.UTC).minusHours(24).getMillis(); final Optional<DeviceAccountPair> deviceIdPair = deviceDAO.getMostRecentSensePairByAccountId(accessToken.accountId); if(!deviceIdPair.isPresent()) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } Optional<Device.Color> color = Optional.absent(); if (this.hasColorCompensationEnabled(accessToken.accountId)) { color = senseColorDAO.getColorForSense(deviceIdPair.get().externalDeviceId); } final Optional<Calibration> calibrationOptional = getCalibrationStrict(deviceIdPair.get().externalDeviceId); final List<Sample> timeSeries = deviceDataDAO.generateTimeSeriesByUTCTime(queryStartTimeUTC, queryEndTimestampUTC, accessToken.accountId, deviceIdPair.get().internalDeviceId, slotDurationInMinutes, sensor, missingDataDefaultValue(accessToken.accountId), color, calibrationOptional); return adjustTimeSeries(timeSeries, sensor, deviceIdPair.get().externalDeviceId); }