auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> protected long getImmutableTimestampInternal(long ts) { <END> Long minLocked = lockService.getMinLockedInVersionId(immutableTsLockClient.getClientId()); return minLocked == null ? ts : minLocked; }</code><technical_language>nit: this private</technical_language>

Target:
private long getImmutableTimestampInternal(long ts) { Long minLocked = lockService.getMinLockedInVersionId(immutableTsLockClient.getClientId()); return minLocked == null ? ts : minLocked; }
Source:
<code>protected void executeVmCommand() { getParameters().setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); if (getVm().getStatus() == VMStatus.Suspended || StringUtils.isNotEmpty(getVm().getHibernationVolHandle())) { suspendedVm = true; setSucceeded(stopSuspendedVm()); <START> if (getSucceeded() && getTaskIdList().isEmpty()) { <END> endVmCommand(); setCommandShouldBeLogged(true); } } else { super.executeVmCommand(); } }</code><technical_language>set succeeded true flow is over, for example in error happen endVmCommand() command finish succeeded. please set succeeded end</technical_language>

Target:
protected void executeVmCommand() { getParameters().setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); if (getVm().getStatus() == VMStatus.Suspended || StringUtils.isNotEmpty(getVm().getHibernationVolHandle())) { suspendedVm = true; boolean syncPartSucceeded = stopSuspendedVm(); if (!syncPartSucceeded) { return; } if (getTaskIdList().isEmpty()) { endVmCommand(); setCommandShouldBeLogged(true); } else { setSucceeded(true); } } else { super.executeVmCommand(); } }
Source:
<code><START> BaseRealm(SharedRealm sharedRealm) { <END> this.threadId = Thread.currentThread().getId(); this.configuration = sharedRealm.getConfiguration(); this.realmCache = null; this.sharedRealm = sharedRealm; this.shouldCloseSharedRealm = false; this.schema = new RealmSchema(this); }</code><technical_language>Please convert this constructor constructors delegate a single, third, constructor</technical_language>

Target:
BaseRealm(SharedRealm sharedRealm) { this.threadId = Thread.currentThread().getId(); this.configuration = sharedRealm.getConfiguration(); this.realmCache = null; this.sharedRealm = sharedRealm; this.shouldCloseSharedRealm = false; }
Source:
<code><START> public void spongeImpl$readFromSpongeCompound(CompoundNBT compound) { <END> super.spongeImpl$readFromSpongeCompound(compound); if (compound.contains("ignorePhysics")) { this.impl$ignorePhysics = compound.getBoolean("ignorePhysics"); } }</code><technical_language>s/spongeImpl/impl</technical_language>

Target:
public void impl$readFromSpongeCompound(CompoundNBT compound) { super.impl$readFromSpongeCompound(compound); if (compound.contains("ignorePhysics")) { this.impl$ignorePhysics = compound.getBoolean("ignorePhysics"); } }
Source:
<code>private static void cleanDirectory(File dir) { try { FileUtils.deleteDirectory(dir); } catch (IOException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>log this instead of printing</technical_language>

Target:
private static void cleanDirectory(File dir) { try { FileUtils.deleteDirectory(dir); } catch (IOException e) { Activator.getDefault().logError("Unable to delete: " + dir.toString(), e); } }
Source:
<code>public Option<Angle> calculateParallacticAngle(final ISPObservation obs) { return ImOption.fromScalaOpt(ObsTargetCalculatorService.targetCalculation(obs)) .flatMap(targetCalculator -> ImOption.fromScalaOpt(targetCalculator.weightedMeanParallacticAngle())) .map(angleObj -> (double) angleObj) <START> .map(angle -> (new edu.gemini.skycalc.Angle(angle, edu.gemini.skycalc.Angle.Unit.DEGREES)).toPositive()); <END> }</code><technical_language>new target model Angle here</technical_language>

Target:
public Option<Angle> calculateParallacticAngle(final ISPObservation obs) { return ImOption.fromScalaOpt(ObsTargetCalculatorService.targetCalculation(obs)) .flatMap(targetCalculator -> ImOption.fromScalaOpt(targetCalculator.weightedMeanParallacticAngle())) .map(angleObj -> Angle$.MODULE$.fromDegrees((double)angleObj)); }
Source:
<code>protected boolean validateSingle(MaintenanceDocument maintDoc, CustomerLoadBatchErrors batchErrors, String customerName) { boolean result = true; <START> CuCustomerRule rule = new CuCustomerRule(); <END> result &= rule.processRouteDocument(maintDoc); extractGlobalVariableErrors(batchErrors, customerName); return result; }</code><technical_language>do need CuCustomerLoadServiceImpl? difference is CuCustomerRule instead of CustomerRule. CuCustomerRule extends CustomerRule, caste correctly in parent, right</technical_language>

Target:
protected boolean validateSingle(MaintenanceDocument maintDoc, CustomerLoadBatchErrors batchErrors, String customerName) { boolean result = true; CustomerRule rule = new CuCustomerRule(); result &= rule.processRouteDocument(maintDoc); extractGlobalVariableErrors(batchErrors, customerName); return result; }
Source:
<code>public int numberOfUpdates() { final Integer cachedValue = numberOfUpdatesCache; if (cachedValue != null) { return cachedValue; } int numberOfUpdates = 0; for (T object : results.keySet()) { final PutResult putResult = results.get(object); <START> if (putResult != null && putResult.wasUpdated() && putResult.numberOfRowsUpdated() != null) { <END> numberOfUpdates += putResult.numberOfRowsUpdated(); } } numberOfUpdatesCache = numberOfUpdates; return numberOfUpdates; }</code><technical_language>result null, need this != null</technical_language>

Target:
public int numberOfUpdates() { final Integer cachedValue = numberOfUpdatesCache; if (cachedValue != null) { return cachedValue; } int numberOfUpdates = 0; for (T object : results.keySet()) { final PutResult putResult = results.get(object); assert putResult != null; if (putResult.wasUpdated()) { assert putResult.numberOfRowsUpdated() != null; numberOfUpdates += putResult.numberOfRowsUpdated(); } } numberOfUpdatesCache = numberOfUpdates; return numberOfUpdates; }
Source:
<code>public static DrlxParseResult normalizeConstraint(DrlxParseResult drlxParseResult) { if (!ENABLE_NORMALIZE) { return drlxParseResult; } if (drlxParseResult instanceof SingleDrlxParseSuccess) { <START> SingleDrlxParseSuccess s = new SingleDrlxParseSuccess((SingleDrlxParseSuccess) drlxParseResult); <END> Expression expr = s.getExpr(); if (expr == null) { return drlxParseResult; } if (expr instanceof MethodCallExpr) { processTopLevelExpression(s, (MethodCallExpr) expr); } else if (expr instanceof EnclosedExpr) { Expression inner = stripEnclosedExpr((EnclosedExpr) expr); if (inner instanceof MethodCallExpr) { processTopLevelExpression(s, (MethodCallExpr) inner); } else { processExpression(expr); } } else { processExpression(expr); } return s; } return drlxParseResult; }</code><technical_language>I avoiding naming variables a single character code more readable. more places this in PR</technical_language>

Target:
public static DrlxParseResult normalizeConstraint(DrlxParseResult drlxParseResult) { if (!ENABLE_NORMALIZE) { return drlxParseResult; } if (drlxParseResult instanceof SingleDrlxParseSuccess) { SingleDrlxParseSuccess drlx = new SingleDrlxParseSuccess((SingleDrlxParseSuccess) drlxParseResult); Expression expr = drlx.getExpr(); if (expr == null) { return drlxParseResult; } if (expr instanceof MethodCallExpr) { processTopLevelExpression(drlx, (MethodCallExpr) expr); } else if (expr instanceof EnclosedExpr) { Expression inner = stripEnclosedExpr((EnclosedExpr) expr); if (inner instanceof MethodCallExpr) { processTopLevelExpression(drlx, (MethodCallExpr) inner); } else { processExpression(expr); } } else { processExpression(expr); } return drlx; } return drlxParseResult; }
Source:
<code>public static PaymentDetailsEnteredEvent from(ChargeEntity charge) { ZonedDateTime lastEventDate = charge.getEvents().stream() .map(ChargeEventEntity::getUpdated) .max(ZonedDateTime::compareTo) <START> .orElse(null); <END> return new PaymentDetailsEnteredEvent( charge.getExternalId(), PaymentDetailsEnteredEventDetails.from(charge), lastEventDate); }</code><technical_language>this exception. want publish events timestamp, is reason events for a charge this point in lifecycle</technical_language>

Target:
public static PaymentDetailsEnteredEvent from(ChargeEntity charge) { ZonedDateTime lastEventDate = charge.getEvents().stream() .filter(e -> e.getStatus() == ChargeStatus.fromString(charge.getStatus())) .map(ChargeEventEntity::getUpdated) .max(ZonedDateTime::compareTo) .orElseThrow(() -> new ChargeEventNotFoundRuntimeException(charge.getExternalId())); return new PaymentDetailsEnteredEvent( charge.getExternalId(), PaymentDetailsEnteredEventDetails.from(charge), lastEventDate); }
Source:
<code>public JsonObject aggregateDocuments(String query, String aggregation) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.aggregateDocuments(overrideNullQuery(query), aggregation); if (!response.equals("")) { <START> JsonReader jsonReader = Json.createReader(new StringReader(response)); <END> JsonObject result = jsonReader.readObject(); return result.getJsonObject("aggregations"); } else { return Json.createObjectBuilder().build(); } }</code><technical_language>here. JsonReader is closeable a try-with-resources statement for closing object is a good idea</technical_language>

Target:
public JsonObject aggregateDocuments(String query, String aggregation) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.aggregateDocuments(overrideNullQuery(query), aggregation); if (!response.equals("")) { try (JsonReader jsonReader = Json.createReader(new StringReader(response))) { JsonObject result = jsonReader.readObject(); return result.getJsonObject("aggregations"); } } else { return Json.createObjectBuilder().build(); } }
Source:
<code>private void attachToProcess(final ICommandControlDMContext context, final String pid, RequestMonitor rm) { BundleContext c = GdbUIPlugin.getDefault().getBundle().getBundleContext(); DsfServicesTracker tracker = new DsfServicesTracker(c, context.getSessionId()); try { final IGDBProcesses procService = tracker.getService(IGDBProcesses.class); <START> final IGDBBackend backend = tracker.getService(IGDBBackend.class); <END> if (procService != null && backend != null) { IProcessDMContext procDmc = procService.createProcessContext(context, pid); procService.attachDebuggerToProcess(procDmc, new DataRequestMonitor<IDMContext>( DsfSession.getSession(context.getSessionId()).getExecutor(), rm) { @Override protected void handleErrorOrWarning() { IStatus status = getStatus(); if (status != null && !status.isOK()) { IStatusHandler statusHandler = DebugPlugin.getDefault().getStatusHandler(status); if (statusHandler != null) { try { statusHandler.handleStatus(status, null); } catch (CoreException ex) { GdbUIPlugin.getDefault().getLog().log(ex.getStatus()); } } else { GdbUIPlugin.getDefault().getLog().log(status); } } handleSuccess(); } }); } else { rm.done(); GdbUIPlugin.logErrorMessage("Could not retreive process service for context" + context); } } finally { tracker.dispose(); } }</code><technical_language>"backend" used, other checked for null. intended</technical_language>

Target:
private void attachToProcess(final ICommandControlDMContext context, final String pid, RequestMonitor rm) { BundleContext c = GdbUIPlugin.getDefault().getBundle().getBundleContext(); DsfServicesTracker tracker = new DsfServicesTracker(c, context.getSessionId()); try { IGDBProcesses procService = tracker.getService(IGDBProcesses.class); if (procService != null) { IProcessDMContext procDmc = procService.createProcessContext(context, pid); procService.attachDebuggerToProcess(procDmc, new DataRequestMonitor<IDMContext>( DsfSession.getSession(context.getSessionId()).getExecutor(), rm) { @Override protected void handleErrorOrWarning() { IStatus status = getStatus(); if (status != null && !status.isOK()) { IStatusHandler statusHandler = DebugPlugin.getDefault().getStatusHandler(status); if (statusHandler != null) { try { statusHandler.handleStatus(status, null); } catch (CoreException ex) { GdbUIPlugin.getDefault().getLog().log(ex.getStatus()); } } else { GdbUIPlugin.getDefault().getLog().log(status); } } handleSuccess(); } }); } else { rm.done(); GdbUIPlugin.log(new Throwable("Could not retreive process service for context" + context)); } } finally { tracker.dispose(); } }
Source:
<code><START> private InitializationManager(Project project) { <END> File baseFolder = new File(PluginManager.getPlugin(PluginId.findId("nl.tudelft.watchdog.intellij")).getPath().getPath()); File toTransferDatabaseFile = new File(baseFolder, WatchDogUtils.getProjectName() + "watchdog.mapdb"); File statisticsDatabaseFile = new File(baseFolder, WatchDogUtils.getProjectName() + "watchdogStatistics.mapdb"); toTransferPersister = new Persister( toTransferDatabaseFile); statisticsPersister = new Persister( statisticsDatabaseFile); intervalManager = new IntervalManager(toTransferPersister, statisticsPersister); debugEventManager = new DebugEventManager(toTransferPersister, statisticsPersister); debugEventManager.setSessionSeed(intervalManager.getSessionSeed()); watchDogEventManager = new WatchDogEventManager(intervalManager, USER_ACTIVITY_TIMEOUT); new TimeSynchronityChecker(intervalManager, watchDogEventManager); transferManager = new TransferManagerBase(toTransferPersister, WatchDogUtils.getProjectName()); intelliJListener = new IntelliJListener(watchDogEventManager, debugEventManager, project); intelliJListener.attachListeners(); }</code><technical_language>This is a problem for accessing local settings + database of legacy users</technical_language>

Target:
private InitializationManager(Project project) { File baseFolder = new File(PluginManager.getPlugin(PluginId.findId("nl.tudelft.watchdog")).getPath().getPath()); File toTransferDatabaseFile = new File(baseFolder, WatchDogUtils.getProjectName() + "watchdog.mapdb"); File statisticsDatabaseFile = new File(baseFolder, WatchDogUtils.getProjectName() + "watchdogStatistics.mapdb"); toTransferPersister = new Persister( toTransferDatabaseFile); statisticsPersister = new Persister( statisticsDatabaseFile); intervalManager = new IntervalManager(toTransferPersister, statisticsPersister); debugEventManager = new DebugEventManager(toTransferPersister, statisticsPersister); debugEventManager.setSessionSeed(intervalManager.getSessionSeed()); watchDogEventManager = new WatchDogEventManager(intervalManager, USER_ACTIVITY_TIMEOUT); new TimeSynchronityChecker(intervalManager, watchDogEventManager); transferManager = new TransferManagerBase(toTransferPersister, WatchDogUtils.getProjectName()); intelliJListener = new IntelliJListener(watchDogEventManager, debugEventManager, project); intelliJListener.attachListeners(); }
Source:
<code>public Optional<Stream<String>> getChanges(@Nullable User user, String ownerId, String dataSetId, String fileId) { Optional<DataSet> maybeDataSet = dataSetRepository.getDataSet(user, ownerId, dataSetId); if (maybeDataSet.isPresent()) { DataSet dataSet = maybeDataSet.get(); DataSetMetaData dataSetMetaData = dataSet.getMetadata(); UpdatedPerPatchStore updatedPerPatchStore = dataSet.getUpdatedPerPatchStore(); ChangeListBuilder changeListBuilder = new ChangeListBuilder( updatedPerPatchStore, dataSet.getTruePatchStore(), dataSetMetaData.getBaseUri() ); Integer version = getVersionFromFileId(fileId); Supplier<List<String>> subjectsSupplier = () -> { try (Stream<String> subjects = updatedPerPatchStore.ofVersion(version)) { return subjects.collect(Collectors.toList()); <START> } <END> }; return Optional.of(changeListBuilder.retrieveChanges(version, subjectsSupplier).stream()); } return Optional.empty(); }</code><technical_language>Move supplier ChangesRetriever</technical_language>

Target:
public Optional<Stream<String>> getChanges(@Nullable User user, String ownerId, String dataSetId, String fileId) { Optional<DataSet> maybeDataSet = dataSetRepository.getDataSet(user, ownerId, dataSetId); if (maybeDataSet.isPresent()) { DataSet dataSet = maybeDataSet.get(); DataSetMetaData dataSetMetaData = dataSet.getMetadata(); ChangeListBuilder changeListBuilder = new ChangeListBuilder(dataSetMetaData.getBaseUri()); ChangesRetriever changesRetriever = dataSet.getChangesRetriever(); Integer version = getVersionFromFileId(fileId); Supplier<List<String>> subjectsSupplier = changesRetriever.getSubjects(version); return Optional.of(changeListBuilder.retrieveChanges(dataSet.getChangesRetriever(), version, subjectsSupplier) .stream()); } return Optional.empty(); }
Source:
<code>public abstract void killAll(Map<String, String> modelEnvVars) throws InterruptedException; private static List<String> classPath; private final int softkillWaitSeconds = 2 * 60; public static void init(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); final Set<String> resourcePaths = servletContext.getResourcePaths("/WEB-INF/lib/"); classPath = new ArrayList<String>(); for (final String resourcePath : resourcePaths) { if (resourcePath.contains("jenkins-core") && resourcePath.endsWith(".jar")) { <START> String jarPath = servletContext.getRealPath(resourcePath); <END> classPath.add(jarPath); } } }</code><technical_language>This smell right. tested this remote agents</technical_language>

Target:
public abstract void killAll(Map<String, String> modelEnvVars) throws InterruptedException; private final long softKillWaitSeconds = Integer.getInteger("SoftKillWaitSeconds", 2 * 60); public void killAll(Process proc, Map<String, String> modelEnvVars) throws InterruptedException { LOGGER.fine("killAll: process="+proc+" and envs="+modelEnvVars); OSProcess p = get(proc); if(p!=null) p.killRecursively(); if(modelEnvVars!=null) killAll(modelEnvVars); }
Source:
<code>public IterableQueryResult queryAndFetch(String query, String queryType, boolean distinctDocuments, Object... params) { Span span = Tracing.getTracer().getCurrentSpan(); Map<String, AttributeValue> attributes = new HashMap<>(); attributes.put("nxql", AttributeValue.stringAttributeValue(query)); span.addAnnotation("queryAndFetch", attributes); try { SecurityService securityService = getSecurityService(); NuxeoPrincipal principal = getPrincipal(); String[] principals = getPrincipalsToCheck(); String[] permissions = securityService.getPermissionsToCheck(BROWSE); Collection<Transformer> transformers = getPoliciesQueryTransformers(queryType); QueryFilter queryFilter = new QueryFilter(principal, principals, permissions, null, transformers, 0, 0); IterableQueryResult result = getSession().queryAndFetch(query, queryType, queryFilter, distinctDocuments, params); attributes.clear(); <START> attributes.put("match", AttributeValue.longAttributeValue(result.size())); <END> span.addAnnotation("queryAndFetch.done", attributes); return result; } catch (QueryParseException e) { e.addInfo("Failed to execute query: " + queryType + ": " + query); throw e; } }</code><technical_language>match -> count</technical_language>

Target:
public IterableQueryResult queryAndFetch(String query, String queryType, boolean distinctDocuments, Object... params) { Span span = Tracing.getTracer().getCurrentSpan(); Map<String, AttributeValue> map = new HashMap<>(); map.put("nxql", AttributeValue.stringAttributeValue(query)); map.put("distinct", AttributeValue.booleanAttributeValue(distinctDocuments)); span.addAnnotation("AbstractSession#queryAndFetch", map); try { SecurityService securityService = getSecurityService(); NuxeoPrincipal principal = getPrincipal(); String[] principals = getPrincipalsToCheck(); String[] permissions = securityService.getPermissionsToCheck(BROWSE); Collection<Transformer> transformers = getPoliciesQueryTransformers(queryType); QueryFilter queryFilter = new QueryFilter(principal, principals, permissions, null, transformers, 0, 0); IterableQueryResult result = getSession().queryAndFetch(query, queryType, queryFilter, distinctDocuments, params); map.clear(); map.put("totalSize", AttributeValue.longAttributeValue(result.size())); span.addAnnotation("AbstractSession#queryAndFetch.done", map); return result; } catch (QueryParseException e) { e.addInfo("Failed to execute query: " + queryType + ": " + query); throw e; } }
Source:
<code>public static boolean recoverOnChunkedUploadFailed(Throwable t) { if (t instanceof ChannelOutputShutdownException) { try { for (StackTraceElement element : t.getStackTrace()) { String className = element.getClassName(); String methodName = element.getMethodName(); if (className.contains("ChunkedWriteHandler") && (methodName.equals("flush") || methodName.equals("write"))) return true; } <START> } catch (Throwable ignore) { <END> } } return t.getCause() != null && recoverOnChunkedUploadFailed(t.getCause()); }</code><technical_language>this try/catch for? want catch Throwable??</technical_language>

Target:
public static boolean recoverOnChunkedUploadFailed(Throwable t) { return t instanceof ChannelOutputShutdownException && exceptionInMethod(t, "io.netty.handler.stream.ChunkedWriteHandler", "flush"); }
Source:
<code>public static ByteBuf encode( ByteBufAllocator allocator, int streamId, int extendedType, @Nullable ByteBuf metadata, ByteBuf data) { int flags = FrameHeaderFlyweight.FLAGS_I; <START> if (metadata != null && metadata != Unpooled.EMPTY_BUFFER) { <END> flags |= FrameHeaderFlyweight.FLAGS_M; } ByteBuf header = FrameHeaderFlyweight.encode(allocator, streamId, FrameType.EXT, flags); header.writeInt(extendedType); if ((data == null || data == Unpooled.EMPTY_BUFFER) && (metadata == null || metadata == Unpooled.EMPTY_BUFFER)) { return header; } else if (metadata != null && metadata != Unpooled.EMPTY_BUFFER) { return DataAndMetadataFlyweight.encode(allocator, header, metadata, data); } else { return DataAndMetadataFlyweight.encodeOnlyData(allocator, header, data); } }</code><technical_language>change of frame logic this pull request expect switching TupleByteBuf - branch original older branch defer framing logic develop branch</technical_language>

Target:
public static ByteBuf encode( ByteBufAllocator allocator, int streamId, int extendedType, @Nullable ByteBuf metadata, ByteBuf data) { int flags = FrameHeaderFlyweight.FLAGS_I; if (metadata != null) { flags |= FrameHeaderFlyweight.FLAGS_M; } ByteBuf header = FrameHeaderFlyweight.encode(allocator, streamId, FrameType.EXT, flags); header.writeInt(extendedType); if (data == null && metadata == null) { return header; } else if (metadata != null) { return DataAndMetadataFlyweight.encode(allocator, header, metadata, data); } else { return DataAndMetadataFlyweight.encodeOnlyData(allocator, header, data); } }
Source:
<code>@Override public boolean checkOperandTypes( SqlCallBinding callBinding, boolean throwOnFailure) { final SqlNode left = callBinding.operand(0); final SqlNode right = callBinding.operand(1); if (!ARRAY_OR_MAP.checkSingleOperandType(callBinding, left, 0, throwOnFailure)) { return false; } final RelDataType operandType = callBinding.getOperandType(0); final SqlSingleOperandTypeChecker checker = getChecker(operandType); if (checker == null) { <START> SqlNode node = callBinding.getCall() <END> .getOperandList() .get(0); throw callBinding.getValidator() .newValidationError(node, RESOURCE.illegalTypeForItemOperator(node.toString(), operandType.getSqlTypeName() .getName()) ); } return checker.checkSingleOperandType(callBinding, right, 0, throwOnFailure); }</code><technical_language>is a util method for generating readable signature error: <LINK_0> Is enough method manually create new error messages</technical_language>

Target:
@Override public boolean checkOperandTypes( SqlCallBinding callBinding, boolean throwOnFailure) { final SqlNode left = callBinding.operand(0); final SqlNode right = callBinding.operand(1); if (!ARRAY_OR_MAP.checkSingleOperandType(callBinding, left, 0, throwOnFailure)) { return false; } final SqlSingleOperandTypeChecker checker = getChecker(callBinding); return checker.checkSingleOperandType(callBinding, right, 0, throwOnFailure); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DatastreamProducerRecord record = (DatastreamProducerRecord) o; return Objects.equals(_partition, record._partition) && Objects.equals(_events, record._events) && Objects.equals( <START> _checkpoint, record._checkpoint); <END> }</code><technical_language>partitionKey</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DatastreamProducerRecord record = (DatastreamProducerRecord) o; return Objects.equals(_partition, record._partition) && Objects.equals(_partitionKey, record._partitionKey) && Objects.equals(_events, record._events) && Objects.equals(_checkpoint, record._checkpoint); }
Source:
<code>public JobSubjectEntity() { <START> super(); <END> }</code><technical_language>please remove empty c'tor</technical_language>

Target:
public JobSubjectEntity() { }
Source:
<code>public void add(Entry entry) { <START> if (queue.size() >= maxSize) { <END> queue.poll(); } queue.add(entry); }</code><technical_language>IMO while</technical_language>

Target:
public void add(Entry entry) { while (queue.size() >= maxSize) { queue.poll(); } queue.add(entry); }
Source:
<code>public void testPromotionEnvironmentShouldIncludeTargetParameters() throws Exception { String paramName = "param"; InheritanceProjectsPair inheritanceProjectPair = j.createInheritanceProjectDerivedWithBase(); JobPropertyImpl promotion = new JobPropertyImpl(inheritanceProjectPair.getBase()); inheritanceProjectPair.getBase().addProperty(promotion); inheritanceProjectPair.getBase().addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(paramName, ""))); <START> inheritanceProjectPair.getDerived().addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(paramName, ""))); <END> PromotionProcess promo1 = promotion.addProcess("promo1"); promo1.conditions.add(new SelfPromotionCondition(false)); for (ItemListener l : ItemListener.all()) { l.onLoaded(); } String paramValue = "someString"; j.assertBuildStatusSuccess(inheritanceProjectPair.getDerived().scheduleBuild2(0, new Cause.UserCause(), new ParametersAction(new StringParameterValue(paramName, paramValue)))); j.waitUntilNoActivity(); promotion = inheritanceProjectPair.getDerived().getProperty(JobPropertyImpl.class, IMode.INHERIT_FORCED); promo1 = promotion.getItem("promo1"); Promotion pb = promo1.getBuildByNumber(1); assertEquals(paramValue, pb.getEnvironment(TaskListener.NULL).get(paramName, null)); }</code><technical_language>Is SECURITY-170 again</technical_language>

Target:
public void testPromotionEnvironmentShouldIncludeTargetParameters() throws Exception { String paramName = "param"; InheritanceProjectsPair inheritanceProjectPair = j.createInheritanceProjectDerivedWithBase(); JobPropertyImpl promotion = new JobPropertyImpl(inheritanceProjectPair.getBase()); inheritanceProjectPair.getBase().addProperty(promotion); inheritanceProjectPair.getBase().addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(paramName, ""))); inheritanceProjectPair.getDerived().addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(paramName, ""))); PromotionProcess promo1 = promotion.addProcess("promo1"); promo1.conditions.add(new SelfPromotionCondition(false)); fireItemListeners(); String paramValue = "someString"; j.assertBuildStatusSuccess(inheritanceProjectPair.getDerived().scheduleBuild2(0, new Cause.UserCause(), new ParametersAction(new StringParameterValue(paramName, paramValue)))); j.waitUntilNoActivity(); promotion = inheritanceProjectPair.getDerived().getProperty(JobPropertyImpl.class, IMode.INHERIT_FORCED); promo1 = promotion.getItem("promo1"); Promotion pb = promo1.getBuildByNumber(1); assertEquals(paramValue, pb.getEnvironment(TaskListener.NULL).get(paramName, null)); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String xAuth = ((HttpServletRequest) request).getHeader("X-Auth-Token"); if (!Strings.isNullOrEmpty(xAuth)) { AuthenticationToken authenticationToken = authenticationTokenRepository.findByToken(xAuth) .orElseThrow(() -> new TokenNotFoundException(xAuth)); if (authenticationToken.isValid()) { User user = authenticationToken.getUser(); SecurityContextHolder.getContext() .setAuthentication(new PreAuthenticatedAuthenticationToken(user, "N/A", user.getAuthorities())); } else { <START> throw new NonceExpiredException("Token expired!"); <END> } } chain.doFilter(request, response); }</code><technical_language>Nonce</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String xAuth = ((HttpServletRequest) request).getHeader("X-Auth-Token"); if (!Strings.isNullOrEmpty(xAuth)) { AuthenticationToken authenticationToken = extractOptional(authenticationTokenRepository.findByToken(xAuth), response); if (authenticationToken.isValid()) { User user = authenticationToken.getUser(); SecurityContextHolder.getContext() .setAuthentication(new PreAuthenticatedAuthenticationToken(user, "N/A", user.getAuthorities())); } else { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token Expired"); } } chain.doFilter(request, response); }
Source:
<code>private HttpResponse executeRequest(HttpRequestBase request) { try { if (authHeaderValue != null) { request.addHeader("Authorization", authHeaderValue); } logger.info(request.toString()); HttpResponse response = httpClient.execute(request, context); validate(request, response); logger.info(response.getStatusLine().toString()); for(Header h: response.getAllHeaders()){ logger.finer(h.toString()); <START> } <END> return response; } catch (IOException e) { logger.log(Level.SEVERE,"Aborting request",e); request.abort(); throw new ServerException(e); } }</code><technical_language>wrap in a logger.getLevel() check avoid loop if level is higher finer</technical_language>

Target:
private HttpResponse executeRequest(HttpRequestBase request) { try { if (authHeaderValue != null) { request.addHeader("Authorization", authHeaderValue); } logger.info(request.toString()); HttpResponse response = httpClient.execute(request, context); validate(request, response); logger.info(response.getStatusLine().toString()); if(logger.isLoggable(Level.FINER)) { for (Header h : response.getAllHeaders()) { logger.finer(h.toString()); } } return response; } catch (IOException e) { logger.log(Level.SEVERE, "Aborting request", e); request.abort(); throw new ServerException(e); } }
Source:
<code>@Override public void onDisplayPreferenceDialog(Preference preference) { final DialogFragment f; if (preference instanceof FontPreference) f = FontPreference.FontPreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof ThemePreference) f = ThemePreference.ThemePreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof EditTextPreferenceFix) f = EditTextPreferenceFix.EditTextPreferenceFixFragment.newInstance(preference.getKey()); <START> else if (preference instanceof ClearCertPreference) <END> f = ClearCertPreference.ClearCertPreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof RingtonePreferenceFix) { Intent intent = ((RingtonePreferenceFix) preference).makeRingtoneRequestIntent(); startActivityForResult(intent, 0); return; } else { super.onDisplayPreferenceDialog(preference); return; } f.setTargetFragment(this, 0); f.show(getFragmentManager(), FRAGMENT_DIALOG_TAG); }</code><technical_language>Nice, I this</technical_language>

Target:
@Override public void onDisplayPreferenceDialog(Preference preference) { final DialogFragment f; if (preference instanceof FontPreference) f = FontPreference.FontPreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof ThemePreference) f = ThemePreference.ThemePreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof FilePreference) f = FilePreference.FilePreferenceFragment.newInstance(preference.getKey(), PREF_SSH_KEY.equals(preference.getKey()) ? 1 : 2); else if (preference instanceof EditTextPreferenceFix) f = EditTextPreferenceFix.EditTextPreferenceFixFragment.newInstance(preference.getKey()); else if (preference instanceof ClearCertPreference) f = ClearCertPreference.ClearCertPreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof RingtonePreferenceFix) { Intent intent = ((RingtonePreferenceFix) preference).makeRingtoneRequestIntent(); startActivityForResult(intent, 0); return; } else { super.onDisplayPreferenceDialog(preference); return; } f.setTargetFragment(this, 0); f.show(getFragmentManager(), FRAGMENT_DIALOG_TAG); }
Source:
<code>public void shouldPropagateRuntimeException() throws AuthenticationException { final RuntimeException e = new NullPointerException(); when(underlying.authorize(principal, role)).thenThrow(e); <START> expected.expect(CoreMatchers.sameInstance(e)); <END> cached.authorize(principal, role); }</code><technical_language>I AssertJ's exception assertion, concise provide a more wide range of assertions ExpectedException rule. that: java assertThatNullPointerException() .isThrownBy(() -> cached.authorize(principal, role)) .isSameAs(e);</technical_language>

Target:
public void shouldPropagateRuntimeException() throws AuthenticationException { final RuntimeException e = new NullPointerException(); when(underlying.authorize(principal, role)).thenThrow(e); assertThatNullPointerException() .isThrownBy(() -> cached.authorize(principal, role)) .isSameAs(e); }
Source:
<code>@Override public boolean equalsDeep(SqlNode node, Litmus litmus) { if (node == this) { return true; } if (!(node instanceof SqlCall)) { return litmus.fail("{} != {}", this, node); } SqlCall that = (SqlCall) node; if (!equalDeep(this.getFunctionQuantifier(), that.getFunctionQuantifier(), litmus)) { <START> return litmus.fail("{} != {}", this, node); <END> } if (!this.getOperator().getName().equalsIgnoreCase(that.getOperator().getName())) { return litmus.fail("{} != {}", this, node); } return equalDeep(this.getOperandList(), that.getOperandList(), litmus); }</code><technical_language>suggestion return litmus.fail("{} != (functionQualifier differs)", this, node);</technical_language>

Target:
@Override public boolean equalsDeep(SqlNode node, Litmus litmus) { if (node == this) { return true; } if (!(node instanceof SqlCall)) { return litmus.fail("{} != {}", this, node); } SqlCall that = (SqlCall) node; if (!this.getOperator().getName().equalsIgnoreCase(that.getOperator().getName())) { return litmus.fail("{} != {}", this, node); } if (!equalDeep(this.getFunctionQuantifier(), that.getFunctionQuantifier(), litmus)) { return litmus.fail("{} != (function quantifier differs)", this, node); } return equalDeep(this.getOperandList(), that.getOperandList(), litmus); }
Source:
<code>public void setUp() throws IOException { validator = new VariantLoaderStepParametersValidator(); final File dir = TestFileUtils.getResource("/parameters-validation/"); <START> final File inputVcf = TestFileUtils.getResource("/parameters-validation/file.vcf.gz"); <END> dir.setReadable(true); dir.setWritable(true); inputVcf.setReadable(true); parameters = new TreeMap<>(); parameters.put(JobParametersNames.DB_NAME, new JobParameter("database")); parameters.put(JobParametersNames.DB_COLLECTIONS_VARIANTS_NAME, new JobParameter("variants")); parameters.put(JobParametersNames.DB_COLLECTIONS_FILES_NAME, new JobParameter("files")); parameters.put(JobParametersNames.INPUT_STUDY_ID, new JobParameter("inputStudyId")); parameters.put(JobParametersNames.INPUT_VCF_ID, new JobParameter("inputVcfId")); parameters.put(JobParametersNames.INPUT_VCF, new JobParameter(inputVcf.getCanonicalPath())); optionalParameters = new TreeMap<>(); optionalParameters.put(JobParametersNames.INPUT_VCF_AGGREGATION, new JobParameter("NONE")); optionalParameters.put(JobParametersNames.CONFIG_CHUNK_SIZE, new JobParameter("100")); }</code><technical_language>temporaryFolderRule temporaryFolderRule.newFile(), need set flags true. prevent interactions concurrent tests, some set false others true. Finally, if validations run temporary folders need parameters-validation folder. applies VepAnnotationGeneratorStepParametersValidatorTest</technical_language>

Target:
public void setUp() throws IOException { validator = new VariantLoaderStepParametersValidator(); requiredParameters = new TreeMap<>(); requiredParameters.put(JobParametersNames.DB_NAME, new JobParameter("database")); requiredParameters.put(JobParametersNames.DB_COLLECTIONS_VARIANTS_NAME, new JobParameter("variants")); requiredParameters.put(JobParametersNames.INPUT_STUDY_ID, new JobParameter("inputStudyId")); requiredParameters.put(JobParametersNames.INPUT_VCF_ID, new JobParameter("inputVcfId")); requiredParameters.put(JobParametersNames.INPUT_VCF_AGGREGATION, new JobParameter("NONE")); requiredParameters.put(JobParametersNames.INPUT_VCF, new JobParameter(temporaryFolderRule.newFile().getCanonicalPath())); optionalParameters = new TreeMap<>(); optionalParameters.put(JobParametersNames.CONFIG_CHUNK_SIZE, new JobParameter("100")); }
Source:
<code>public void if_with_nested_foreach_nested_do_while() { verifyBlockCfg("" + <START> "ifCond(succ = [forCond, END]);" + <END> "if (a) {" + " foreach ( forCond(succ = [innerIfCond, END]) as $key) {" + " innerIfCond(succ = [ifBody, doBody]);" + " if (a) {" + " ifBody( succ = [doBody] );" + " }" + " do {" + " doBody( succ = [doCond] );" + " } while (doCond( succ = [doBody, forCond] ));" + " }" + "}"); }</code><technical_language>increase readability of this test I drop this statement, move ifCond block if condition</technical_language>

Target:
public void if_with_nested_foreach_nested_do_while() { verifyBlockCfg("" + "if (ifCond(succ = [forCond, END])) {" + " foreach ( forCond(succ = [innerIfCond, END]) as $foo) {" + " innerIfCond(succ = [ifBody, doBody]);" + " if (a) {" + " ifBody( succ = [doBody] );" + " }" + " do {" + " doBody( succ = [doCond] );" + " } while (doCond( succ = [doBody, forCond] ));" + " }" + "}"); }
Source:
<code>private static RunCondition getIgnoreConditionOnMethod(Description aDescription) { try { <START> ConditionalRun[] annotation = aDescription.getTestClass().getMethod(aDescription.getMethodName()).getAnnotationsByType(ConditionalRun.class); <END> return new IgnoreConditionCreator(aDescription.getTestClass(), annotation).create(); } catch (NoSuchMethodException | SecurityException ex) { throw new RuntimeException(ex); } }</code><technical_language>annotations</technical_language>

Target:
private static RunCondition getIgnoreConditionOnMethod(Description aDescription) { try { ConditionalRun[] annotations = aDescription.getTestClass().getMethod(aDescription.getMethodName()).getAnnotationsByType(ConditionalRun.class); return new IgnoreConditionCreator(aDescription.getTestClass(), annotations).create(); } catch (NoSuchMethodException | SecurityException ex) { throw new RuntimeException(ex); } }
Source:
<code>private ArrayList<Map<String, String>> formatDepictions(JsonObject mediaResponse) { try { JsonArray depictionArray = (JsonArray) mediaResponse.get("Depiction"); ArrayList<Map<String, String>> depictedItemList = new ArrayList<>(); try { for (int i = 0; i <depictionArray.size() ; i++) { JsonObject depictedItem = (JsonObject) depictionArray.get(i); Map <String, String> depictedObject = new HashMap<>(); <START> depictedObject.put("label", depictedItem.get("label").toString().substring(3, depictedItem.get("label").toString().length()-3)); END> depictedObject.put("id", depictedItem.get("id").toString().substring(1, depictedItem.get("id").toString().length() - 1)); depictedItemList.add(depictedObject); } return depictedItemList; } catch (NullPointerException e) { return new ArrayList<>(); } } catch (ClassCastException c) { return new ArrayList<>(); } }</code><technical_language>computation is a bit complex, please set a variable (String = ...) in put("label", value);. Also, please add example of depictedItem.get("label") resulting value. This code more understandable. Thanks</technical_language>

Target:
private ArrayList<Map<String, String>> formatDepictions(JsonObject mediaResponse) { try { JsonArray depictionArray = (JsonArray) mediaResponse.get("Depiction"); ArrayList<Map<String, String>> depictedItemList = new ArrayList<>(); try { for (int i = 0; i <depictionArray.size() ; i++) { JsonObject depictedItem = (JsonObject) depictionArray.get(i); Map <String, String> depictedObject = new HashMap<>(); String label = depictedItem.get("label").toString(); String id = depictedItem.get("id").toString(); String transformedLabel = label.substring(3, label.length()-3); String transformedId = id.substring(1,id.length() - 1); depictedObject.put("label", transformedLabel); depictedObject.put("id", transformedId); depictedItemList.add(depictedObject); } return depictedItemList; } catch (NullPointerException e) { return new ArrayList<>(); } } catch (ClassCastException c) { return new ArrayList<>(); } }
Source:
<code>public void initialize(ScriptContext context) { Object attr = context.getAttribute(OUTPUT_ATTR); if (attr != null) { attribute = String.valueOf(attr); } <START> Object sum = context.getAttribute(OUTPUT_SUM); <END> doSum = Boolean.parseBoolean(String.valueOf(sum)); Object count = context.getAttribute(OUTPUT_COUNT); doCount = Boolean.parseBoolean(String.valueOf(count)); Object average = context.getAttribute(OUTPUT_AVG); doAverage = Boolean.parseBoolean(String.valueOf(average)); Object max = context.getAttribute(OUTPUT_MAX); doMax = Boolean.parseBoolean(String.valueOf(max)); Object min = context.getAttribute(OUTPUT_MIN); doMin = Boolean.parseBoolean(String.valueOf(min)); attributeValues = new LinkedList<Double>(); }</code><technical_language>move rest of statements in this method if block</technical_language>

Target:
public void initialize(ScriptContext context) { Object attr = context.getAttribute(OUTPUT_ATTR); if (attr != null) { attribute = String.valueOf(attr); Object sum = context.getAttribute(OUTPUT_SUM); doSum = Boolean.parseBoolean(String.valueOf(sum)); Object count = context.getAttribute(OUTPUT_COUNT); doCount = Boolean.parseBoolean(String.valueOf(count)); Object average = context.getAttribute(OUTPUT_AVG); doAverage = Boolean.parseBoolean(String.valueOf(average)); Object max = context.getAttribute(OUTPUT_MAX); doMax = Boolean.parseBoolean(String.valueOf(max)); Object min = context.getAttribute(OUTPUT_MIN); doMin = Boolean.parseBoolean(String.valueOf(min)); attributeValues = new LinkedList<Double>(); } }
Source:
<code>public Object setCaller(InvocationContext ctx) throws Exception { Subject caller=null; java.security.Principal p = ejbContext.getCallerPrincipal(); if (!startupBean.isInitialized()) { String notInitMessage = "Tried to call REST endpoint but the server has not finished to startup"; <START> log.warn(notInitMessage); <END> Response.ResponseBuilder builder; builder = Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(notInitMessage); return builder.build(); } if (p!=null) { caller = subjectManager.getSubjectByName(p.getName()); } if (caller==null) { throw new IllegalAccessException("No calling principal provided"); } caller = sessionManager.put(caller); AbstractRestBean target = (AbstractRestBean) ctx.getTarget(); target.caller = caller; Object result = ctx.proceed(); if (result instanceof StreamingOutput) { return new SecureStreamingOutput((StreamingOutput) result, caller); } sessionManager.invalidate(caller.getSessionId()); return result; }</code><technical_language>Do want log this? If feel this message useful, get logged DEBUG level? "expected" failures "I'm running yet" warrant a log message in log of "is running yet." Log messages considered valid in exceptional informational state change events. "I starting..." "I started." "I start due failure..." etc. If is server started context of surrounding log messages a DEBUG message helpful in rare cases figure out REST service is unavailable server is running</technical_language>

Target:
public Object setCaller(InvocationContext ctx) throws Exception { Subject caller=null; java.security.Principal p = ejbContext.getCallerPrincipal(); if (!startupBean.isInitialized()) { String notInitMessage = "Tried to call REST endpoint but the server is not ready - still booting up"; log.debug(notInitMessage); return Response.status(Response.Status.SERVICE_UNAVAILABLE) .header("Retry-After", "30").entity(notInitMessage).build(); } if (p!=null) { caller = subjectManager.getSubjectByName(p.getName()); } if (caller==null) { throw new IllegalAccessException("No calling principal provided"); } caller = sessionManager.put(caller); AbstractRestBean target = (AbstractRestBean) ctx.getTarget(); target.caller = caller; Object result = ctx.proceed(); if (result instanceof StreamingOutput) { return new SecureStreamingOutput((StreamingOutput) result, caller); } sessionManager.invalidate(caller.getSessionId()); return result; }
Source:
<code>public void testTempAuthRequest() throws Exception { Properties overrides = null; test(overrides); overrides = new Properties(); overrides.setProperty(SwiftAuthenticationModule.TEMP_AUTH_HEADER_USER , "X-Auth-User"); overrides.setProperty(SwiftAuthenticationModule.TEMP_AUTH_HEADER_PASS , "X-Auth-Pass"); <START> test(overrides); <END> }</code><technical_language>move this another test named testTempAuthRequestWithCustomHeaders similar, properly qualify isolate test verifies this change</technical_language>

Target:
public void testTempAuthRequest() throws Exception { Properties overrides = new Properties(); test(overrides, "X-Storage-User", "X-Storage-Pass"); }
Source:
<code>private List<CassandraPartition> getCassandraPartitions(CassandraTable table, TupleDomain<ColumnHandle> tupleDomain) { if (tupleDomain.isNone()) { return ImmutableList.of(); } List<Set<Object>> partitionKeysList = getPartitionKeysList(table, tupleDomain); Set<List<Object>> filterList = Sets.cartesianProduct(partitionKeysList); if (filterList.isEmpty()) { return cassandraSession.getPartitions(table, ImmutableList.of()); } <START> return ImmutableList.copyOf(cassandraSession.getPartitions(table, partitionKeysList)); <END> }</code><technical_language>do copy in 122</technical_language>

Target:
private List<CassandraPartition> getCassandraPartitions(CassandraTable table, TupleDomain<ColumnHandle> tupleDomain) { if (tupleDomain.isNone()) { return ImmutableList.of(); } List<Set<Object>> partitionKeysList = getPartitionKeysList(table, tupleDomain); Set<List<Object>> filterList = Sets.cartesianProduct(partitionKeysList); if (filterList.isEmpty()) { return cassandraSession.getPartitions(table, ImmutableList.of()); } return cassandraSession.getPartitions(table, partitionKeysList); }
Source:
<code>private Group(@JsonProperty("id") String id, @JsonProperty("externalId") String externalId, @JsonProperty("meta") Meta meta, @JsonProperty(value = "schemas", required = true) Set<String> schemas, @JsonProperty("displayName") String displayName, @JsonProperty("members") Set<MemberRef> members) { super(id, externalId, meta, schemas); this.displayName = displayName; <START> this.members = (members != null ? members : new HashSet<MemberRef>()); <END> }</code><technical_language>Is a reason [Collections.emptySet()](<LINK_0> here</technical_language>

Target:
private Group(@JsonProperty("id") String id, @JsonProperty("externalId") String externalId, @JsonProperty("meta") Meta meta, @JsonProperty(value = "schemas", required = true) Set<String> schemas, @JsonProperty("displayName") String displayName, @JsonProperty("members") Set<MemberRef> members) { super(id, externalId, meta, schemas); this.displayName = displayName; this.members = (members != null ? members : Collections.<MemberRef>emptySet()); }