auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static DynamicFilter from(Expression expression) { checkArgument(expression instanceof ComparisonExpression, "Unexpected expression: %s", expression); ComparisonExpression comparison = (ComparisonExpression) expression; Expression sourceExpression; DeferredSymbolReference deferredReference; if (comparison.getLeft() instanceof DeferredSymbolReference) { sourceExpression = comparison.getRight(); deferredReference = (DeferredSymbolReference) comparison.getLeft(); } else if (comparison.getRight() instanceof DeferredSymbolReference) { sourceExpression = comparison.getLeft(); deferredReference = (DeferredSymbolReference) comparison.getRight(); } else { throw new IllegalArgumentException(format("Unexpected expression: %s", expression.toString())); <START> } <END> return new DynamicFilter( sourceExpression, deferredReference.getSourceId(), deferredReference.getSymbol(), comparison.getType()); }</code><technical_language>a checkState side is DeferredSymbolReference</technical_language>

Target:
public static DynamicFilter from(Expression expression) { checkArgument(expression instanceof ComparisonExpression, "Unexpected expression: %s", expression); ComparisonExpression comparison = (ComparisonExpression) expression; Expression sourceExpression = null; DeferredSymbolReference deferredReference = null; checkState(comparison.getLeft() instanceof DeferredSymbolReference ^ comparison.getRight() instanceof DeferredSymbolReference, "Exactly one deferred symbol per expression is required"); if (comparison.getLeft() instanceof DeferredSymbolReference) { sourceExpression = comparison.getRight(); deferredReference = (DeferredSymbolReference) comparison.getLeft(); } else if (comparison.getRight() instanceof DeferredSymbolReference) { sourceExpression = comparison.getLeft(); deferredReference = (DeferredSymbolReference) comparison.getRight(); } return new DynamicFilter( sourceExpression, deferredReference.getSourceId(), deferredReference.getSymbol(), comparison.getType()); }
Source:
<code>public List<MessageHandlingMember<? super T>> findHandlerMethods(EventMessage<?> eventMessage) { return handlers.stream().filter(h -> h.canHandle(eventMessage)) <START> .collect(Collectors.toCollection(ArrayList::new)); <END> }</code><technical_language>Ah yeah good one. I removed some function here, adjusting actual call</technical_language>

Target:
public List<MessageHandlingMember<? super T>> findHandlerMethods(EventMessage<?> eventMessage) { return handlers.stream().filter(h -> h.canHandle(eventMessage)) .collect(Collectors.toList()); }
Source:
<code>public void testUnrecognizedSpec() { when(authentication.getAttributes().get(any(String.class))).thenReturn("strong_two_factor"); spec.setAuthenticationMethod("weak_two_factor"); <START> assertTrue(this.spec.isSatisfiedBy(this.assertion)); <END> }</code><technical_language>Is this idiomatic? In fact expect true, interrupted assertTrue returns? clearer omit assertTrue</technical_language>

Target:
public void testUnrecognizedSpec() { when(authentication.getAttributes().get(any(String.class))).thenReturn("strong_two_factor"); spec.setAuthenticationMethod("weak_two_factor"); spec.isSatisfiedBy(this.assertion); }
Source:
<code>private void createIndexDocument(File2Index file2Index) { RegistryContext registryContext = null; boolean skipCache = false; String resourcePath = file2Index.path;; try { skipCache = IndexingManager.getInstance().isCacheSkipped(); Registry registry = IndexingManager.getInstance().getRegistry(file2Index.tenantId); registryContext = registry.getRegistryContext(); if (resourcePath != null) { if (skipCache) { registryContext.registerNoCachePath(resourcePath); if (log.isDebugEnabled()) { log.debug("Resource at path \"" + resourcePath + "\" is added as a no cache path"); } } Resource resource; if (registry.resourceExists(resourcePath) && (resource = registry.get(resourcePath)) != null) { IndexDocumentCreator indexDocumentCreator = new IndexDocumentCreator(file2Index, resource); indexDocumentCreator.createIndexDocument(); String symlinkPath = resource.getProperty("registry.resource.symlink.path"); if (symlinkPath != null) { file2Index.path = symlinkPath; indexDocumentCreator = new IndexDocumentCreator(file2Index, resource); indexDocumentCreator.createIndexDocument(); } } } } catch (RegistryException | IndexerException e) { <START> log.error("Error while indexing.", e); <END> } finally { if (skipCache && registryContext != null) { registryContext.removeNoCachePath(resourcePath); if (log.isDebugEnabled()) { log.debug("Resource at path \"" + resourcePath + "\" is removed from no cache path"); } } } }</code><technical_language>Context information is missing in error log message</technical_language>

Target:
private void createIndexDocument(File2Index file2Index) { RegistryContext registryContext = null; boolean skipCache = false; String resourcePath = file2Index.path; try { skipCache = IndexingManager.getInstance().isCacheSkipped(); Registry registry = IndexingManager.getInstance().getRegistry(file2Index.tenantId); registryContext = registry.getRegistryContext(); if (resourcePath != null) { if (skipCache) { registryContext.registerNoCachePath(resourcePath); if (log.isDebugEnabled()) { log.debug("Resource at path \"" + resourcePath + "\" is added as a no cache path"); } } Resource resource; if (registry.resourceExists(resourcePath) && (resource = registry.get(resourcePath)) != null) { IndexDocumentCreator indexDocumentCreator = new IndexDocumentCreator(file2Index, resource); indexDocumentCreator.createIndexDocument(); String symlinkPath = resource.getProperty(REGISTRY_RESOURCE_SYMLINK_PATH); if (symlinkPath != null) { file2Index.path = symlinkPath; indexDocumentCreator = new IndexDocumentCreator(file2Index, resource); indexDocumentCreator.createIndexDocument(); } } } } catch (RegistryException | IndexerException e) { log.error("Error while indexing. Resource at path " + "\"" + resourcePath + "\"" + "could not be " + "indexed" + e); } finally { if (skipCache && registryContext != null) { registryContext.removeNoCachePath(resourcePath); if (log.isDebugEnabled()) { log.debug("Resource at path \"" + resourcePath + "\" is removed from no cache path"); } } } }
Source:
<code>static void waitForQueryCount(DistributedQueryRunner queryRunner, Set<QueryState> countingStates, int expectedCount) throws InterruptedException { QueryManager queryManager = queryRunner.getCoordinator().getQueryManager(); <START> while (queryManager.getAllQueryInfo().stream().filter(q -> countingStates.contains(q.getState())).count() != expectedCount) { <END> MILLISECONDS.sleep(500); } }</code><technical_language>Split multiple lines</technical_language>

Target:
public static void waitForQueryCount(DistributedQueryRunner queryRunner, Set<QueryState> countingStates, int expectedCount) throws InterruptedException { QueryManager queryManager = queryRunner.getCoordinator().getQueryManager(); while (queryManager.getAllQueryInfo().stream() .filter(q -> countingStates.contains(q.getState())).count() != expectedCount) { MILLISECONDS.sleep(500); } }
Source:
<code>public ElasticHashinatorCleanerJRE9() { System.out.println("JAVA version " + ManagementFactory.getRuntimeMXBean().getSpecVersion()); try { createMtd = Class.forName("java.lang.ref.Cleaner").getMethod("create"); <START> registerMtd = Class.forName("java.lang.ref.Cleaner").getMethod("register", Object.class, Runnable.class); <END> } catch (ClassNotFoundException | NoSuchMethodException e) { throw new RuntimeException("Reflection failure: no java.lang.ref.Cleaner found", e); } }</code><technical_language>class once</technical_language>

Target:
public ElasticHashinatorCleanerJRE9() { try { Class<?> cleanerClass = Class.forName("java.lang.ref.Cleaner"); createMtd = cleanerClass.getMethod("create"); registerMtd = cleanerClass.getMethod("register", Object.class, Runnable.class); } catch (ClassNotFoundException | NoSuchMethodException e) { throw new RuntimeException("Reflection failure: no java.lang.ref.Cleaner found", e); } }
Source:
<code>public T nextDataRecord(String key) { try { <START> while (results.hasNext()) { <END> JsonNode dataNode = results.next(); T t = dataNode.has(key) ? mapper.treeToValue(dataNode.get(key), resultClass) : null; return t; } } catch (IOException e) { throw new ResultProcessingException("Error processing results", e); } return null; }</code><technical_language>This loop is needed if-statement, or? t returned if is a next</technical_language>

Target:
T nextDataRecord(String key) { try { if (results.hasNext()) { JsonNode dataNode = results.next(); T t = dataNode.has(key) ? mapper.treeToValue(dataNode.get(key), resultClass) : null; return t; } } catch (IOException e) { throw new ResultProcessingException("Error processing results", e); } return null; }
Source:
<code>private void browseDirectory(final LocalFileLocation dir) { if (dir.isRootDir()) { parentDirectory = dir.fullPath; } else { String rootPath = null; String path; for (LocalFileLocation fl : rootFileLocation) { path = fl.fullPath; if ((path != null) && (dir.fullPath != null) && (dir.fullPath.contentEquals(path))) { rootPath = fl.fullPath; break; } } if (rootPath != null) { parentDirectory = rootPath; dir.setRootDir(true); } else if (dir.fullPath != null) { parentDirectory = getParentDirectory(dir.fullPath); } } currentDirectory = dir; File[] files = (new File(dir.fullPath)).listFiles(); if (files == null) { <START> Toast.makeText( getContext(), String.format(getString(R.string.error_getting_source_info), "listFiles() failed"), Toast.LENGTH_LONG); <END> return; } Arrays.sort(files); ArrayList<LocalFileLocation> dir_list = new ArrayList<>(); ArrayList<LocalFileLocation> file_list = new ArrayList<>(); if (dir.hasParent) { parentDirectory = getParentDirectory(dir.fullPath); LocalFileLocation fl = new LocalFileLocation("..", parentDirectory, true); fl.setRootDir(dir.isRootDir()); dir_list.add(0, fl); } for (File file : files) { LocalFileLocation fl = new LocalFileLocation(file.getName(), file.getAbsolutePath(), file.isDirectory()); if (fl.isDirectory) { dir_list.add(fl); } else { file_list.add(fl); } } ArrayList<LocalFileLocation> full_list = new ArrayList<>(); full_list.addAll(dir_list); full_list.addAll(file_list); ((MediaPictureListAdapter) getAdapter()).setFilelistItems(full_list); browseRootAlready = false; }</code><technical_language>Missing call .show()</technical_language>

Target:
private void browseDirectory(final LocalFileLocation dir) { if (dir.isRootDir()) { parentDirectory = dir.fullPath; } else { String rootPath = null; String path; for (LocalFileLocation fl : rootFileLocation) { path = fl.fullPath; if ((path != null) && (dir.fullPath != null) && (dir.fullPath.contentEquals(path))) { rootPath = fl.fullPath; break; } } if (rootPath != null) { parentDirectory = rootPath; dir.setRootDir(true); } else if (dir.fullPath != null) { parentDirectory = getParentDirectory(dir.fullPath); } } currentDirectory = dir; File[] files = (new File(dir.fullPath)).listFiles(); if (files == null) { Toast.makeText( getContext(), String.format(getString(R.string.error_getting_source_info), "listFiles() failed"), Toast.LENGTH_LONG).show(); return; } Arrays.sort(files); ArrayList<LocalFileLocation> dir_list = new ArrayList<>(); ArrayList<LocalFileLocation> file_list = new ArrayList<>(); if (dir.hasParent) { parentDirectory = getParentDirectory(dir.fullPath); LocalFileLocation fl = new LocalFileLocation("..", parentDirectory, true); fl.setRootDir(dir.isRootDir()); dir_list.add(0, fl); } for (File file : files) { LocalFileLocation fl = new LocalFileLocation(file.getName(), file.getAbsolutePath(), file.isDirectory()); if (fl.isDirectory) { dir_list.add(fl); } else { file_list.add(fl); } } ArrayList<LocalFileLocation> full_list = new ArrayList<>(); full_list.addAll(dir_list); full_list.addAll(file_list); ((MediaPictureListAdapter) getAdapter()).setFilelistItems(full_list); browseRootAlready = false; }
Source:
<code>private PlanNodeCostEstimate calculateRemoteSourceNodeCost(RemoteSourceNode node, StatsProvider stats, TypeProvider types) { PlanNodeCostEstimate costEstimate = PlanNodeCostEstimate.ZERO_COST; for (PlanFragment fragment : sourceProvider.getSourceFragments(node)) { PartitioningHandle handle = fragment.getPartitioning(); ExchangeNode.Type exchangeType; <START> if (handle.equals(FIXED_BROADCAST_DISTRIBUTION)) { <END> exchangeType = REPLICATE; } else if (handle.equals(SINGLE_DISTRIBUTION)) { exchangeType = GATHER; } else { exchangeType = REPARTITION; } PlanNodeCostEstimate exchangeCost = calculateExchangeCost(numberOfNodes.getAsInt(), stats.getStats(node), node.getOutputSymbols(), exchangeType, REMOTE, types); costEstimate.add(exchangeCost); } return costEstimate; }</code><technical_language>This fragile. storing exchange type in RemoteSourceNode? easy change</technical_language>

Target:
private PlanNodeCostEstimate calculateRemoteSourceNodeCost(RemoteSourceNode node, StatsProvider stats, TypeProvider types) { PlanNodeCostEstimate costEstimate = PlanNodeCostEstimate.ZERO_COST; ExchangeNode.Type exchangeType = node.getExchangeType(); for (PlanNode source : sourceProvider.getSources(node)) { PlanNodeCostEstimate exchangeCost = calculateExchangeCost(numberOfNodes.getAsInt(), stats.getStats(source), node.getOutputSymbols(), exchangeType, REMOTE, types); costEstimate.add(exchangeCost); } return costEstimate; }
Source:
<code><START> @Before public void setup() throws SQLException { <END> generateUniqueTableNames(); createTestTable(getUrl(), String.format(dataTableDdl, dataTableFullName)); if (!Strings.isNullOrEmpty(viewDdl)) { createTestTable(getUrl(), String.format(viewDdl, viewFullName, dataTableFullName)); createTestTable(getUrl(), String.format(indexTableDdl, indexTableName, viewFullName)); } else { createTestTable(getUrl(), String.format(indexTableDdl, indexTableName, dataTableFullName)); } props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String dataTableUpsert = String.format(UPSERT_SQL, dataTableFullName); dataTableUpsertStmt = conn.prepareStatement(dataTableUpsert); String viewUpsert = String.format(UPSERT_SQL, viewFullName); viewUpsertStmt = conn.prepareStatement(viewUpsert); conn.setAutoCommit(false); testTime = EnvironmentEdgeManager.currentTimeMillis() - 1000; }</code><technical_language>nit: start access modifiers new line</technical_language>

Target:
public void setup() throws SQLException { generateUniqueTableNames(); createTestTable(getUrl(), String.format(dataTableDdl, dataTableFullName)); if (!Strings.isNullOrEmpty(viewDdl)) { createTestTable(getUrl(), String.format(viewDdl, viewFullName, dataTableFullName)); createTestTable(getUrl(), String.format(indexTableDdl, indexTableName, viewFullName)); } else { createTestTable(getUrl(), String.format(indexTableDdl, indexTableName, dataTableFullName)); } props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String dataTableUpsert = String.format(UPSERT_SQL, dataTableFullName); dataTableUpsertStmt = conn.prepareStatement(dataTableUpsert); String viewUpsert = String.format(UPSERT_SQL, viewFullName); viewUpsertStmt = conn.prepareStatement(viewUpsert); conn.setAutoCommit(false); testTime = EnvironmentEdgeManager.currentTimeMillis() - 1000; }
Source:
<code>public static Cursor getJpSettings(long id) { if (id < 0) return null; <START> String sqlCommand = sqlSelectAllJpSettings() + sqlWhere(JetpackSettingsModel.ID_COLUMN_NAME, Long.toString(id)) + ";"; <END> return WordPress.wpDB.getDatabase().rawQuery(sqlCommand, null); }</code><technical_language>Nitpick: cut this 120 chars</technical_language>

Target:
public static Cursor getJpSettings(long id) { if (id < 0) return null; String whereClause = sqlWhere(ID_COLUMN_NAME, Long.toString(id)); String sqlCommand = sqlSelectAllJpSettings() + whereClause + ";"; return WordPress.wpDB.getDatabase().rawQuery(sqlCommand, null); }
Source:
<code>public static String buildUrlWithQueryParams(@NonNull Logger logger, @NonNull String baseUrl, @NonNull Map<String, String> queryParams) { <START> StringBuilder finalUrl = new StringBuilder(baseUrl); <END> for (Map.Entry<String, String> entry : queryParams.entrySet()) { String encodedParamValue = null; try { encodedParamValue = URLEncoder.encode(entry.getValue(), "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error(e); } final String queryParam = entry.getKey() + "=" + encodedParamValue; if (finalUrl.toString().contains("?")) { finalUrl.append("&").append(queryParam); } else { finalUrl.append("?").append(queryParam); } } return finalUrl.toString(); }</code><technical_language>final</technical_language>

Target:
public static String buildUrlWithQueryParams(@NonNull Logger logger, @NonNull String baseUrl, @NonNull Map<String, String> queryParams) { final Uri.Builder uriBuilder = Uri.parse(baseUrl).buildUpon(); for (Map.Entry<String, String> entry : queryParams.entrySet()) { uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue()); } final String finalUrl = uriBuilder.build().toString(); logger.debug("URL: " + finalUrl); return finalUrl; }
Source:
<code>public static SubjectEntity[] getStorageEntitiesForCoco(List<CinderDisk> cinderDisks) { List<SubjectEntity> storageSubjects = new ArrayList<>(); for (final CinderDisk cinderDisk : cinderDisks) { <START> SubjectEntity subjectStorage = LinqUtils.firstOrNull(storageSubjects, new Predicate<SubjectEntity>() { <END> @Override public boolean eval(SubjectEntity storageSubject) { return storageSubject.getEntityId().equals(cinderDisk.getStorageIds().get(0)); } }); if (subjectStorage == null) { SubjectEntity se = new SubjectEntity(VdcObjectType.Storage, cinderDisk.getStorageIds().get(0)); storageSubjects.add(se); } } SubjectEntity[] subjectEntities = new SubjectEntity[storageSubjects.size()]; storageSubjects.toArray(subjectEntities); return subjectEntities; }</code><technical_language>For readability, consider refactoring unique storage domains first, then, create list of SubjectEntities</technical_language>

Target:
public static SubjectEntity[] getStorageEntitiesForCoco(List<CinderDisk> cinderDisks) { Set<SubjectEntity> storageSubjects = new HashSet<>(); for (final CinderDisk cinderDisk : cinderDisks) { SubjectEntity se = new SubjectEntity(VdcObjectType.Storage, cinderDisk.getStorageIds().get(0)); storageSubjects.add(se); } SubjectEntity[] subjectEntities = new SubjectEntity[storageSubjects.size()]; storageSubjects.toArray(subjectEntities); return subjectEntities; }
Source:
<code>private static Boolean isUserCause(Cause cause) { if (Cause.UserIdCause.class.isInstance(cause)) { return true; <START> } <END> return false; }</code><technical_language>please format changed code properly</technical_language>

Target:
private static Boolean isUserCause(Cause cause) { if (cause instanceof UserCause || cause instanceof UserIdCause){ return true; } return false; }
Source:
<code>private boolean containsOuter() { for (JoinRelType joinType : joinTypes) { <START> if (joinType != JoinRelType.INNER && joinType != JoinRelType.SEMI) { <END> return true; } } return false; }</code><technical_language>whitelist this for outer types (FULL, LEFT, RIGHT). @scarlin-cloudera create separate jira change this patch..upto you</technical_language>

Target:
private boolean containsOuter() { for (JoinRelType joinType : joinTypes) { if (joinType.isOuterJoin()) { return true; } } return false; }
Source:
<code>private void reconnectEdge(String source, String target, String newTargetName) { SWTBotGefEditPart sourceEditPartBot = getEditPart(source, AbstractBorderItemEditPart.class); SWTBotGefEditPart targetEditPartBot = getEditPart(target, AbstractBorderItemEditPart.class); SWTBotGefEditPart newtargetEditPartBot = getEditPart(newTargetName, AbstractBorderItemEditPart.class); SWTBotGefConnectionEditPart connectionEditPartBot = editor.getConnectionEditPart(sourceEditPartBot, targetEditPartBot).get(0); editor.reveal(connectionEditPartBot.part()); connectionEditPartBot.select(); <START> SWTBotUtils.waitAllUiEvents(); <END> PointList connection1Points = ((AbstractConnectionEditPart) connectionEditPartBot.part()).getConnectionFigure().getPoints().getCopy(); Point from = connection1Points.getLastPoint(); ((AbstractConnectionEditPart) connectionEditPartBot.part()).getFigure().translateToAbsolute(from); Point to = editor.getBounds(newtargetEditPartBot).getLocation(); editor.drag(from, to); }</code><technical_language>CheckSelectedCondition</technical_language>

Target:
private void reconnectEdge(String source, String target, String newTargetName) { SWTBotGefEditPart sourceEditPartBot = getEditPart(source, AbstractBorderItemEditPart.class); SWTBotGefEditPart targetEditPartBot = getEditPart(target, AbstractBorderItemEditPart.class); SWTBotGefEditPart newtargetEditPartBot = getEditPart(newTargetName, AbstractBorderItemEditPart.class); SWTBotGefConnectionEditPart connectionEditPartBot = editor.getConnectionEditPart(sourceEditPartBot, targetEditPartBot).get(0); editor.reveal(connectionEditPartBot.part()); connectionEditPartBot.select(); bot.waitUntil(new CheckSelectedCondition(editor, connectionEditPartBot.part())); PointList connection1Points = ((AbstractConnectionEditPart) connectionEditPartBot.part()).getConnectionFigure().getPoints().getCopy(); Point from = connection1Points.getLastPoint(); ((AbstractConnectionEditPart) connectionEditPartBot.part()).getFigure().translateToAbsolute(from); Point to = editor.getBounds(newtargetEditPartBot).getLocation(); editor.drag(from, to); }
Source:
<code>private EuclideanValues polarToEuclidean(float r, float rDeviation, float theta, float thetaDeviation) { double thetaVariance = Math.pow(thetaDeviation, 2.0); double rVariance = Math.pow(rDeviation, 2.0); double halfPi = Math.PI / 2; double thetaVarianceFactorX = -1 * (halfPi * r) * Math.pow((1 + Math.tan(halfPi * theta)), -2) * (1 / Math.pow(Math.cos(halfPi * theta), 2)); double rVarianceFactorX = 1 / (1 + Math.tan(halfPi * theta)); double varianceX = (Math.pow(thetaVarianceFactorX, 2) * thetaVariance) + (Math.pow(rVarianceFactorX, 2) * rVariance); double thetaVarianceFactorY = -1 * thetaVarianceFactorX; double rVarianceFactorY = 1 - rVarianceFactorX; double varianceY = (Math.pow(thetaVarianceFactorY, 2) * thetaVariance) + (Math.pow(rVarianceFactorY, 2) * rVariance); double meanX = r / (1 + Math.tan(theta * halfPi)); <START> double meanY = r - (r / (1 + Math.tan(theta * halfPi))); <END> double devX = Math.pow(varianceX, 0.5); double devY = Math.pow(varianceY, 0.5); return new EuclideanValues((float) meanX, (float) meanY, (float) devX, (float) devY); }</code><technical_language>simpler meanY=r-meanX recompute tan</technical_language>

Target:
EuclideanValues polarToEuclidean(float r, float rDeviation, float theta, float thetaDeviation) { final double thetaVariance = Math.pow(thetaDeviation, 2.0); final double rVariance = Math.pow(rDeviation, 2.0); final double halfPi = Math.PI / 2; final double normalizedTheta = halfPi * theta; final double rOverX = (1 + Math.tan(normalizedTheta)); final double thetaVarianceFactorX = -1 * (halfPi * r) * Math.pow(rOverX * Math.cos(normalizedTheta), -2); final double rVarianceFactorX = 1 / rOverX; final double varianceX = (Math.pow(thetaVarianceFactorX, 2) * thetaVariance) + (Math.pow(rVarianceFactorX, 2) * rVariance); final double thetaVarianceFactorY = -1 * thetaVarianceFactorX; final double rVarianceFactorY = 1 - rVarianceFactorX; final double varianceY = (Math.pow(thetaVarianceFactorY, 2) * thetaVariance) + (Math.pow(rVarianceFactorY, 2) * rVariance); final double meanX = r / rOverX; final double meanY = r - meanX; final double devX = Math.pow(varianceX, 0.5); final double devY = Math.pow(varianceY, 0.5); return new EuclideanValues((float) meanX, (float) meanY, (float) devX, (float) devY); }
Source:
<code>public static File createTempDir() throws IOException { <START> return Files.createTempDirectory("jenkins").toFile(); <END> }</code><technical_language>I POSIX systems Files.createTempDirectory create a directory 0700&(~umask) permissions while previous code create a directory 0777&(~umask) permissions. good confirm prevent another [JENKINS-48407 ](<LINK_0></technical_language>

Target:
public static File createTempDir() throws IOException { final Path tempPath; final String tempDirNamePrefix = "jenkins"; if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) { tempPath = Files.createTempDirectory(tempDirNamePrefix, PosixFilePermissions.asFileAttribute(EnumSet.allOf(PosixFilePermission.class))); } else { tempPath = Files.createTempDirectory(tempDirNamePrefix); } return tempPath.toFile(); }
Source:
<code>public void build(DefaultGoPublisher publisher, EnvironmentVariableContext environmentVariableContext, TaskExtension taskExtension, ArtifactExtension artifactExtension, PluginRequestProcessorRegistry pluginRequestProcessorRegistry) { downloadMetadataFile(publisher); try { <START> pluginRequestProcessorRegistry.registerProcessorFor(CONSOLE_LOG.requestName(), new ArtifactRequestProcessor(publisher)); <END> final String message = format("[%s] Fetching pluggable artifact using plugin %s.", GoConstants.PRODUCT_NAME, artifactStore.getPluginId()); LOGGER.info(message); publisher.taggedConsumeLine(TaggedStreamConsumer.OUT, message); artifactExtension.fetchArtifact(artifactStore.getPluginId(), artifactStore, configuration, artifactId, getMetadataFromFile(), agentWorkingDirectory()); } catch (Exception e) { publisher.taggedConsumeLine(TaggedStreamConsumer.ERR, e.getMessage()); LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } finally { pluginRequestProcessorRegistry.removeProcessorFor(CONSOLE_LOG.requestName()); } }</code><technical_language>extract a variable for CONSOLE_LOG.requestName()</technical_language>

Target:
public void build(DefaultGoPublisher publisher, EnvironmentVariableContext environmentVariableContext, TaskExtension taskExtension, ArtifactExtension artifactExtension, PluginRequestProcessorRegistry pluginRequestProcessorRegistry) { downloadMetadataFile(publisher); try { pluginRequestProcessorRegistry.registerProcessorFor(CONSOLE_LOG.requestName(), new ArtifactRequestProcessor(publisher)); final String message = format("[%s] Fetching pluggable artifact using plugin %s.", GoConstants.PRODUCT_NAME, artifactStore.getPluginId()); LOGGER.info(message); publisher.taggedConsumeLine(TaggedStreamConsumer.OUT, message); artifactExtension.fetchArtifact(artifactStore.getPluginId(), artifactStore, configuration, getMetadataFromFile(artifactId), agentWorkingDirectory()); } catch (Exception e) { publisher.taggedConsumeLine(TaggedStreamConsumer.ERR, e.getMessage()); LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } finally { pluginRequestProcessorRegistry.removeProcessorFor(CONSOLE_LOG.requestName()); } }
Source:
<code>public void encode(ActiveMQBuffer buffer, Message record) { super.encode(buffer, record); AMQPLargeMessage msgEncode = (AMQPLargeMessage) record; buffer.writeLong(record.getMessageID()); buffer.writeBoolean(record.isDurable()); buffer.writeLong(msgEncode.getMessageFormat()); buffer.writeNullableSimpleString(record.getAddressSimpleString()); TypedProperties properties = ((AMQPMessage) record).getExtraProperties(); if (properties == null) { buffer.writeInt(0); } else { buffer.writeInt(properties.getEncodeSize()); properties.encode(buffer.byteBuf()); } ByteBuf savedEncodeBuffer = msgEncode.getSavedEncodeBuffer(); buffer.writeBytes(savedEncodeBuffer, 0, savedEncodeBuffer.writerIndex()); msgEncode.releaseEncodedBuffer(); <START> msgEncode.releaseEncodedBuffer(); END> }</code><technical_language>2 separate releases is prone future errors: I this simplified esplicit in method names happening</technical_language>

Target:
public void encode(ActiveMQBuffer buffer, Message record) { super.encode(buffer, record); AMQPLargeMessage msgEncode = (AMQPLargeMessage) record; buffer.writeLong(record.getMessageID()); buffer.writeBoolean(record.isDurable()); buffer.writeLong(msgEncode.getMessageFormat()); buffer.writeNullableSimpleString(record.getAddressSimpleString()); TypedProperties properties = ((AMQPMessage) record).getExtraProperties(); if (properties == null) { buffer.writeInt(0); } else { buffer.writeInt(properties.getEncodeSize()); properties.encode(buffer.byteBuf()); } ByteBuf savedEncodeBuffer = msgEncode.getSavedEncodeBuffer(); buffer.writeBytes(savedEncodeBuffer, 0, savedEncodeBuffer.writerIndex()); msgEncode.releaseEncodedBufferAfterWrite(); }
Source:
<code>public void singleOpenBracket() { <START> formatter.format("Hello {{1}} {0:.3 world!", (float) 3.1415926); <END> }</code><technical_language>(float) 3.1415926 == 3.1415926f</technical_language>

Target:
public void singleOpenBracket() { formatter.format("Hello {{1}} {0:.3f world!", 3.1415926f); }
Source:
<code><START> public static Consumer<PreparedStatement> createPreparedStatementConsumer(Integer[] indexes, <END> DataContext context) { return pstm -> { int dynamicParamIndex = 1; for (int index : indexes) { setDynamicParam(dynamicParamIndex, context.get("?" + index), pstm); dynamicParamIndex++; } }; }</code><technical_language>this method receive List<RelDataType>? (e.g. for proper null binding)</technical_language>

Target:
public static ResultSetEnumerable.PreparedStatementEnricher createPreparedStatementConsumer( Integer[] indexes, DataContext context) { return pstm -> { int dynamicParamIndex = 1; for (int index : indexes) { setDynamicParam(dynamicParamIndex, context.get("?" + index), pstm); dynamicParamIndex++; } }; }
Source:
<code>private void addNeutralExceptions(Faction faction, Node node) throws DOMException, ParseException { <START> final String METHOD_NAME = "addNeutralExceptions(String,Node)"; END> SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date start = null; Date end = null; if (node.getAttributes().getNamedItem("end") != null) { end = df.parse(node.getAttributes().getNamedItem("end").getTextContent().trim()); } for (int n = 0; n < node.getChildNodes().getLength(); n++) { Node wn = node.getChildNodes().item(n); if (wn.getNodeName().equalsIgnoreCase("exceptions")) { Date localStart = start; Date localEnd = end; if (wn.getAttributes().getNamedItem("start") != null) { localStart = df.parse(wn.getAttributes().getNamedItem("start").getTextContent().trim()); } if (wn.getAttributes().getNamedItem("end") != null) { localEnd = df.parse(wn.getAttributes().getNamedItem("end").getTextContent().trim()); } String[] parties = wn.getTextContent().trim().split(","); for (int i = 0; i < parties.length; i++) { final Faction f = Faction.getFaction(parties[i]); if (null == f) { MekHQ.getLogger().error(getClass(), METHOD_NAME, "Invalid faction code in factionhints.xml: " + parties[i]); continue; } addNeutralExceptions("", localStart, localEnd, faction, f); } } } }</code><technical_language>minor: arg type mismatch in string</technical_language>

Target:
private void addNeutralExceptions(Faction faction, Node node) throws DOMException, ParseException { final String METHOD_NAME = "addNeutralExceptions(Faction,Node)"; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date start = null; Date end = null; if (node.getAttributes().getNamedItem("end") != null) { end = df.parse(node.getAttributes().getNamedItem("end").getTextContent().trim()); } for (int n = 0; n < node.getChildNodes().getLength(); n++) { Node wn = node.getChildNodes().item(n); if (wn.getNodeName().equals("exceptions")) { Date localStart = start; Date localEnd = end; if (wn.getAttributes().getNamedItem("start") != null) { localStart = df.parse(wn.getAttributes().getNamedItem("start").getTextContent().trim()); } if (wn.getAttributes().getNamedItem("end") != null) { localEnd = df.parse(wn.getAttributes().getNamedItem("end").getTextContent().trim()); } String[] parties = wn.getTextContent().trim().split(","); for (int i = 0; i < parties.length; i++) { final Faction f = Faction.getFaction(parties[i]); if (null == f) { MekHQ.getLogger().error(getClass(), METHOD_NAME, "Invalid faction code in factionhints.xml: " + parties[i]); continue; } addNeutralExceptions("", localStart, localEnd, faction, f); } } } }
Source:
<code>private static TableDescriptor getTableDescriptor(String schemaName, String tableName) throws Exception { EmbedConnection defaultConn=(EmbedConnection) SpliceAdmin.getDefaultConn(); Activation lastActivation=defaultConn.getLanguageConnection().getLastActivation(); LanguageConnectionContext lcc = lastActivation.getLanguageConnectionContext(); SpliceTransactionManager tc = (SpliceTransactionManager)lcc.getTransactionExecute(); DataDictionary dd = lcc.getDataDictionary(); if (schemaName == null) { schemaName = lcc.getCurrentSchemaName(); } else { <START> schemaName = schemaName.toUpperCase(); <END> } if (tableName != null) { tableName = tableName.toUpperCase(); } else { throw StandardException.newException(SQLState.TABLE_NAME_CANNOT_BE_NULL); } SchemaDescriptor sd = dd.getSchemaDescriptor(schemaName, tc, true); if (sd == null){ throw StandardException.newException(SQLState.LANG_SCHEMA_DOES_NOT_EXIST, schemaName); } TableDescriptor td = dd.getTableDescriptor(tableName, sd, tc); if (td == null) { throw StandardException.newException(SQLState.TABLE_NOT_FOUND, tableName); } return td; }</code><technical_language>Do handle case-sensitive schemas? create schema "thisIsCaseSensitive";</technical_language>

Target:
private static TableDescriptor getTableDescriptor(String schemaName, String tableName) throws Exception { EmbedConnection defaultConn=(EmbedConnection) SpliceAdmin.getDefaultConn(); Activation lastActivation=defaultConn.getLanguageConnection().getLastActivation(); LanguageConnectionContext lcc = lastActivation.getLanguageConnectionContext(); SpliceTransactionManager tc = (SpliceTransactionManager)lcc.getTransactionExecute(); DataDictionary dd = lcc.getDataDictionary(); if (schemaName == null) { schemaName = lcc.getCurrentSchemaName(); } else { schemaName = schemaName.trim(); } if (tableName != null) { tableName = tableName.trim(); } else { throw StandardException.newException(SQLState.TABLE_NAME_CANNOT_BE_NULL); } SchemaDescriptor sd = dd.getSchemaDescriptor(schemaName, tc, true); if (sd == null){ throw StandardException.newException(SQLState.LANG_SCHEMA_DOES_NOT_EXIST, schemaName); } TableDescriptor td = dd.getTableDescriptor(tableName, sd, tc); if (td == null) { throw StandardException.newException(SQLState.TABLE_NOT_FOUND, tableName); } return td; }
Source:
<code>public void validateConfig(WorkspaceConfig config) throws ValidationException, NotFoundException, ServerException { checkNotNull(config.getName(), "Workspace name required"); check( WS_NAME.matcher(config.getName()).matches(), "Incorrect workspace name, it must be between 3 and 100 characters and may contain digits, " + "latin letters, underscores, dots, dashes and must start and end only with digits, " + "latin letters or underscores"); check(!isNullOrEmpty(config.getDefaultEnv()), "Workspace default environment name required"); checkNotNull(config.getEnvironments(), "Workspace must contain at least one environment"); check( config.getEnvironments().containsKey(config.getDefaultEnv()), "Workspace default environment configuration required"); for (Environment environment : config.getEnvironments().values()) { checkNotNull(environment, "Environment must not be null"); Recipe recipe = environment.getRecipe(); checkNotNull(recipe, "Environment recipe must not be null"); checkNotNull(recipe.getType(), "Environment recipe type must not be null"); for (Entry<String, ? extends MachineConfig> machineEntry : environment.getMachines().entrySet()) { validateMachine(machineEntry.getKey(), machineEntry.getValue()); } } for (Command command : config.getCommands()) { check( !isNullOrEmpty(command.getName()), "Workspace %s contains command with null or empty name", config.getName()); check( !isNullOrEmpty(command.getCommandLine()), "Command line required for command '%s' in workspace '%s'", <START> command.getName(), <END> config.getName()); } }</code><technical_language>Java doc updated changes <LINK_0></technical_language>

Target:
public void validateConfig(WorkspaceConfig config) throws ValidationException, ServerException { checkNotNull(config.getName(), "Workspace name required"); check( WS_NAME.matcher(config.getName()).matches(), "Incorrect workspace name, it must be between 3 and 100 characters and may contain digits, " + "latin letters, underscores, dots, dashes and must start and end only with digits, " + "latin letters or underscores"); check(!isNullOrEmpty(config.getDefaultEnv()), "Workspace default environment name required"); checkNotNull(config.getEnvironments(), "Workspace must contain at least one environment"); check( config.getEnvironments().containsKey(config.getDefaultEnv()), "Workspace default environment configuration required"); for (Environment environment : config.getEnvironments().values()) { checkNotNull(environment, "Environment must not be null"); Recipe recipe = environment.getRecipe(); checkNotNull(recipe, "Environment recipe must not be null"); checkNotNull(recipe.getType(), "Environment recipe type must not be null"); for (Entry<String, ? extends MachineConfig> machineEntry : environment.getMachines().entrySet()) { validateMachine(machineEntry.getKey(), machineEntry.getValue()); } } for (Command command : config.getCommands()) { check( !isNullOrEmpty(command.getName()), "Workspace %s contains command with null or empty name", config.getName()); check( !isNullOrEmpty(command.getCommandLine()), "Command line required for command '%s' in workspace '%s'", command.getName(), config.getName()); } }
Source:
<code>public void unparse(SqlWriter writer, int leftPrec, int rightPrec) { writer.keyword("DROP"); writer.keyword("CATALOG"); <START> catalogName.unparse(writer, leftPrec, rightPrec); <END> }</code><technical_language>IF EXISTS reflected in unparse</technical_language>

Target:
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) { writer.keyword("DROP"); writer.keyword("CATALOG"); if (ifExists) { writer.keyword("IF EXISTS"); } catalogName.unparse(writer, leftPrec, rightPrec); }
Source:
<code>public BindOsSupport getOsSupport() { BindOsSupport result = osSupport; if (result == null) { <START> synchronized(this) { <END> result = osSupport; if (result == null) { boolean yumExists = newScript("testing for yum") .body.append(BashCommands.requireExecutable("yum")) .execute() == 0; osSupport = result = yumExists ? BindOsSupport.forRhel() : BindOsSupport.forDebian(); } } } return result; }</code><technical_language>Create a specific Object mutex for synchronization, this</technical_language>

Target:
public BindOsSupport getOsSupport() { BindOsSupport result = osSupport; if (result == null) { synchronized (osSupportMutex) { result = osSupport; if (result == null) { boolean yumExists = newScript("testing for yum") .body.append(BashCommands.requireExecutable("yum")) .execute() == 0; osSupport = result = yumExists ? BindOsSupport.forRhel() : BindOsSupport.forDebian(); } } } return result; }
Source:
<code><START> public void testDecisionServerSecondContainerAMQ() throws Exception { <END> checkDecisionServerSecondContainerAMQ(); }</code><technical_language>throwing a generic Exception is a good practice in Java. Is a strong reason for that</technical_language>

Target:
public void testDecisionServerSecondContainerAMQ() throws UnsupportedEncodingException, NamingException, NoSuchAlgorithmException { checkDecisionServerSecondContainerAMQ(); }
Source:
<code>public GradientDescent withMaxIterations(int maxIterations) { <START> if (maxIterations < 0) <END> throw new IllegalArgumentException("Number of iterations must be non-negative but got " + maxIterations); this.maxIterations = maxIterations; return this; }</code><technical_language>asserts check input arguments, discuss @ybabak @YuriBabak</technical_language>

Target:
public GradientDescent withMaxIterations(int maxIterations) { assert maxIterations >= 0; this.maxIterations = maxIterations; return this; }
Source:
<code>public void listen(@SuppressWarnings("unused") AutosaveEvent event) { if (timer != null) { timer.cancel(); } timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { new SaveDatabaseAction(panel, Globals.prefs, Globals.entryTypesManager).save(SaveDatabaseAction.SaveDatabaseMode.SILENT); } catch (Throwable e) { LOGGER.error("Problem occured while saving.", e); } } <START> }, 200); <END> }</code><technical_language>Please introduce a constant - I think, header of this class is OK - (no magic numbers in code)</technical_language>

Target:
public void listen(@SuppressWarnings("unused") AutosaveEvent event) { try { new SaveDatabaseAction(panel, Globals.prefs, Globals.entryTypesManager).save(SaveDatabaseAction.SaveDatabaseMode.SILENT); } catch (Throwable e) { LOGGER.error("Problem occurred while saving.", e); } }
Source:
<code>public void testMultiplePerTargetAspects() throws SecurityException, NoSuchMethodException { TestBean target = new TestBean(); int realAge = 65; target.setAge(realAge); List<Advisor> advisors = new LinkedList<>(); PerTargetAspect aspect1 = new PerTargetAspect(); aspect1.count = 100; aspect1.setOrder(10); advisors.addAll( getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect1, "someBean1"))); PerTargetAspect aspect2 = new PerTargetAspect(); aspect2.setOrder(5); advisors.addAll( getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect2, "someBean2"))); <START> advisors.sort(new OrderComparator()); <END> TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class); assertThat(itb.getAge()).as("Around advice must NOT apply").isEqualTo(realAge); itb.getSpouse(); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1); }</code><technical_language>If optimize, do step :) > sort(advisors, OrderComparator.INSTANCE);</technical_language>

Target:
public void testMultiplePerTargetAspects() throws SecurityException, NoSuchMethodException { TestBean target = new TestBean(); int realAge = 65; target.setAge(realAge); List<Advisor> advisors = new LinkedList<>(); PerTargetAspect aspect1 = new PerTargetAspect(); aspect1.count = 100; aspect1.setOrder(10); advisors.addAll( getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect1, "someBean1"))); PerTargetAspect aspect2 = new PerTargetAspect(); aspect2.setOrder(5); advisors.addAll( getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect2, "someBean2"))); OrderComparator.sort(advisors); TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class); assertThat(itb.getAge()).as("Around advice must NOT apply").isEqualTo(realAge); itb.getSpouse(); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1); }
Source:
<code>@Nullable public String getAuthURL() { for (FormGroup formGroup : form) { <START> for (FormField formField : formGroup.getFields()) { <END> if (formField.getId().equals("authURL")) { return formField.getValue().toString(); } } } return null; }</code><technical_language>careful of nullable fields</technical_language>

Target:
@Nullable public String getAuthURL() { return getValueFromField(FormField.AUTH_URL); }
Source:
<code>public void run() { workerLastStartAt.set(System.currentTimeMillis()); try { final List<QueuedRequestId> queuedRequestIds = requestManager.getQueuedRequestIds(); if (!queuedRequestIds.isEmpty()) { final Set<String> handledServices = Sets.newHashSet(); for (QueuedRequestId queuedRequestId : queuedRequestIds) { if (!handledServices.contains(queuedRequestId.getServiceId())) { synchronized (BaragonRequestWorker.class) { handleQueuedRequest(queuedRequestId); } handledServices.add(queuedRequestId.getServiceId()); } } } <START> requestManager.failStuckPendingRequests(); <END> } catch (Exception e) { LOG.warn("Caught exception", e); } }</code><technical_language>flip-flopping want this check occur time request worker is triggered -- expensive for people enabled purging yet. move this of other background workers? investigate request creation stuff part of a ZK transaction</technical_language>

Target:
public void run() { workerLastStartAt.set(System.currentTimeMillis()); try { final List<QueuedRequestId> queuedRequestIds = requestManager.getQueuedRequestIds(); if (!queuedRequestIds.isEmpty()) { final Set<String> handledServices = Sets.newHashSet(); for (QueuedRequestId queuedRequestId : queuedRequestIds) { if (!handledServices.contains(queuedRequestId.getServiceId())) { synchronized (BaragonRequestWorker.class) { handleQueuedRequest(queuedRequestId); } handledServices.add(queuedRequestId.getServiceId()); } } } } catch (Exception e) { LOG.warn("Caught exception", e); } }
Source:
<code>private void addNewlines(Node n) { Node nextNode = n.getNext(); if (nextNode != null) { int lineSpacing = nextNode.getLineno() - n.getLineno(); if (lineSpacing > 1 || <START> (nextNode.getToken() == Token.MEMBER_FUNCTION_DEF ^ n.getToken() == Token.EMPTY)) { <END> add("\n"); } } }</code><technical_language>of newline conditions is "current node is empty next token is a member function" - i.e. add newline empty tokens a member function. non-intuitive me; is want</technical_language>

Target:
private void addNewlines(Node n) { Node nextNode = n.getNext(); if (nextNode != null) { int lineSpacing = nextNode.getLineno() - n.getLineno(); if (lineSpacing > 1 || (nextNode.getToken() == Token.MEMBER_FUNCTION_DEF && n.getToken() != Token.EMPTY)) { add("\n"); } } }
Source:
<code>public Builder type(BlockType type) { checkNotNull(type); <START> internalState = type.getDefaultState(); <END> return this; }</code><technical_language>I prefer return type(type.getDefaultState()) instead, repetitive</technical_language>

Target:
public Builder type(BlockType type) { checkNotNull(type); this.type = type; return this; }
Source:
<code>public void setBasicAuthorizationHeaderForUserAndPassword(String user, String password) { String credential = user + ":" + password; <START> String base64credential = Base64.getEncoder().encodeToString(credential.getBytes()); <END> setValueForHeader("Basic " + base64credential, "Authorization"); }</code><technical_language>Please add explicit encoding (using 'ISO-8859-1') converting string bytes</technical_language>

Target:
public void setBasicAuthorizationHeaderForUserAndPassword(String user, String password) { String credential = user + ":" + password; try { String base64credential = Base64.getEncoder().encodeToString(credential.getBytes("ISO-8859-1")); setValueForHeader("Basic " + base64credential, "Authorization"); } catch (UnsupportedEncodingException e) { throw new SlimFixtureException("ISO-8859-1 encoding unavailable!", e); } }
Source:
<code><START> public void signInForAdmin() throws Exception { <END> SignIn signIn = new SignIn.Builder().withStudy("originalStudy") .withEmail(TestConstants.EMAIL).withPassword("password").build(); TestUtils.mockPlayContextWithJson(signIn); when(authService.signIn(eq(study), any(CriteriaContext.class), signInCaptor.capture())).thenReturn(session); Result result = controller.signInForAdmin(); TestUtils.assertResult(result, 200); assertEquals("originalStudy", session.getStudyIdentifier().getIdentifier()); assertEquals("api", signInCaptor.getValue().getStudyId()); }</code><technical_language>For branch coverage, want a test for case a non-admin calls this API</technical_language>

Target:
public void signInForAdmin() throws Exception { when(bridgeConfig.getEnvironment()).thenReturn(Environment.LOCAL); SignIn signIn = new SignIn.Builder().withStudy("originalStudy") .withEmail(TestConstants.EMAIL).withPassword("password").build(); Response response = TestUtils.mockPlayContextWithJson(signIn); when(authService.signIn(eq(study), any(CriteriaContext.class), signInCaptor.capture())).thenReturn(session); Result result = controller.signInForAdmin(); TestUtils.assertResult(result, 200); assertEquals("originalStudy", session.getStudyIdentifier().getIdentifier()); assertEquals("api", signInCaptor.getValue().getStudyId()); verify(response).setCookie(BridgeConstants.SESSION_TOKEN_HEADER, session.getSessionToken(), BridgeConstants.BRIDGE_SESSION_EXPIRE_IN_SECONDS, "/", bridgeConfig.get("domain"), false, false); }