auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mRecyclerView=new RecyclerView(getContext()); ingredients=new ArrayList<>(); Callback<JsonNode> callback=new Callback<JsonNode>() { @Override public void onResponse(@NonNull Call<JsonNode> call, Response<JsonNode> response) { final JsonNode node=response.body(); final JsonNode ingredientsJsonNode=node.findValue("ingredients"); for(int i=0;i<ingredientsJsonNode.size();i++) { Ingredient ingredient=new Ingredient(); ingredient.setId(ingredientsJsonNode.get(i).findValue("id").toString()); ingredient.setText(ingredientsJsonNode.get(i).findValue("text").toString()); ingredient.setRank(Long.valueOf(ingredientsJsonNode.get(i).findValue("rank").toString())); ingredients.add(ingredient); } adapter= new IngredientAnalysisRecyclerAdapter(getContext(),ingredients,getActivity()); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.setAdapter(adapter); } @Override public void onFailure(@NonNull Call<JsonNode> call, Throwable t) { Toast.makeText(getActivity(), getActivity().getString(R.string.errorWeb), Toast.LENGTH_LONG).show(); } }; api.getIngredients(product.getCode(),callback); if(adapter!=null) { adapter.notifyDataSetChanged(); } return createView(inflater,container,R.layout.fragment_ingredients_analysis_product); }

Target:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mRecyclerView=new RecyclerView(getContext()); api.getIngredients(product.getCode(),((value, ingredients) -> { if(value) { adapter= new IngredientAnalysisRecyclerAdapter(getContext(),ingredients,getActivity()); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.setAdapter(adapter); } else { Toast.makeText(getActivity(), getActivity().getString(R.string.errorWeb), Toast.LENGTH_LONG).show(); } })); return createView(inflater,container,R.layout.fragment_ingredients_analysis_product); }
Source:
public static LifeForm parseLifeForm(String val) { switch(val) { case "None": return NONE; case "Microbes": return MICROBE; case "Plants": return PLANT; case "Fish": return FISH; case "Amphibians": return AMPH; case "Reptiles": return REPTILE; case "Birds": return BIRD; case "Mammals": return MAMMAL; case "Insects": return INSECT; default: return LifeForm.valueOf(val); } }

Target:
public static LifeForm parseLifeForm(String val) { switch(val.toLowerCase()) { case "microbe": case "microbes": return MICROBE; case "plant": case "plants": return PLANT; case "fish": return FISH; case "amphibian": case "amphibians": return AMPHIBIAN; case "reptile": case "reptiles": return REPTILE; case "bird": case "birds": return BIRD; case "mammal": case "mammals": return MAMMAL; case "insect": case "insects": return INSECT; default: return NONE; } }
Source:
public final ItemBinding<T> clearExtras() { if (extraBindings != null) { extraBindings.clear(); extraBindings = null; } return this; }

Target:
public final ItemBinding<T> clearExtras() { if (extraBindings != null) { extraBindings.clear(); } return this; }
Source:
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { Logger.debug(LOG_TAG, "addAccount"); final Bundle res = new Bundle(); if (!FxAccountConstants.ACCOUNT_TYPE.equals(accountType)) { res.putInt(AccountManager.KEY_ERROR_CODE, -1); res.putString(AccountManager.KEY_ERROR_MESSAGE, "Not adding unknown account type."); return res; } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setClassName(AppConstants.ANDROID_PACKAGE_NAME, AppConstants.ANDROID_PACKAGE_NAME + ".App"); intent.setData(Uri.parse("about:accounts")); res.putParcelable(AccountManager.KEY_INTENT, intent); return res; }

Target:
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { Logger.debug(LOG_TAG, "addAccount"); final Bundle res = new Bundle(); if (!FxAccountConstants.ACCOUNT_TYPE.equals(accountType)) { res.putInt(AccountManager.KEY_ERROR_CODE, -1); res.putString(AccountManager.KEY_ERROR_MESSAGE, "Not adding unknown account type."); return res; } Intent intent = new Intent(context, FxAccountSetupActivity.class); res.putParcelable(AccountManager.KEY_INTENT, intent); return res; }
Source:
public void testColumnWithInvalidType() { assertNull(metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS)); metadata.createTable(SESSION, getOrdersTable(), false); ConnectorTableHandle tableHandle = metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS); assertInstanceOf(tableHandle, RaptorTableHandle.class); RaptorTableHandle raptorTableHandle = (RaptorTableHandle) tableHandle; List<RowType.Field> fields = new ArrayList<RowType.Field>(); fields.add(new RowType.Field(Optional.of("field_1"), BIGINT)); try { metadata.addColumn(SESSION, raptorTableHandle, new ColumnMetadata("new_col", RowType.from(fields))); } catch (PrestoException pe) { assertEquals(pe.getErrorCode(), NOT_SUPPORTED.toErrorCode()); } }

Target:
public void testColumnWithInvalidType() { assertNull(metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS)); metadata.createTable(SESSION, getOrdersTable(), false); RaptorTableHandle raptorTableHandle = (RaptorTableHandle) metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS); List<RowType.Field> fields = (ImmutableList.of(new RowType.Field(Optional.of("field_1"), BIGINT))); try { metadata.addColumn( SESSION, raptorTableHandle, new ColumnMetadata("new_col", RowType.from(fields))); fail(); } catch (PrestoException e) { assertEquals(e.getErrorCode(), NOT_SUPPORTED.toErrorCode()); } }
Source:
public List<Organization> getApprovedOrganizations() { List<Organization> organizations = organizationDAO.findApprovedSortedByStar(); organizations.forEach(organization -> Hibernate.initialize(organization.getAliases())); return organizations; }

Target:
public List<Organization> getApprovedOrganizations() { return organizationDAO.findApprovedSortedByStar(); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Node node = (Node) o; return com.google.common.base.Objects.equal(id, node.id) && com.google.common.base.Objects.equal(ip, node.ip) && com.google.common.base.Objects.equal(addr, node.addr) && com.google.common.base.Objects.equal(name, node.name); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Node node = (Node) o; return Objects.equal(id, node.id) && Objects.equal(ip, node.ip) && Objects.equal(addr, node.addr) && Objects.equal(name, node.name); }
Source:
public static B2UnderFileSystem createInstance(AlluxioURI alluxioURI, UnderFileSystemConfiguration conf) throws ServiceException { LOG.debug("initializing B2 Storage Client"); LOG.debug(alluxioURI.toString()); B2StorageClient client = B2StorageClientFactory.createDefaultFactory() .create(conf.get(PropertyKey.B2_ACCESS_KEY), conf.get(PropertyKey.B2_SECRET_KEY), USER_AGENT); try { B2AccountAuthorization accountAuthorization = client.getAccountAuthorization(); LOG.debug(accountAuthorization.toString()); B2Allowed allowed = accountAuthorization.getAllowed(); LOG.debug(allowed.toString()); String accountId = accountAuthorization.getAccountId(); List<String> capabilities = allowed.getCapabilities(); String bucketNameFromURI = UnderFileSystemUtils.getBucketName(alluxioURI); LOG.debug("bucketname from uri: {}", bucketNameFromURI); String bucketId; String bucketName; if (allowed.getBucketId() != null) { bucketId = allowed.getBucketId(); bucketName = allowed.getBucketName(); } else { B2Bucket bucket = client.getBucketOrNullByName(bucketNameFromURI); LOG.debug(bucket.toString()); bucketId = bucket.getBucketId(); bucketName = bucket.getBucketName(); } short bucketMode = B2Utils.translateBucketAcl(capabilities); return new B2UnderFileSystem(alluxioURI, conf, client, bucketId, bucketName, bucketMode, accountId); } catch (B2Exception | NullPointerException e) { LOG.error("Failed to instantiate B2UnderFileSystem client with key:{} and URI: {}", conf.get(PropertyKey.B2_ACCESS_KEY), alluxioURI); Throwables.propagateIfPossible(e, ServiceException.class); } return null; }

Target:
public static B2UnderFileSystem createInstance(AlluxioURI alluxioURI, UnderFileSystemConfiguration conf) throws ServiceException { LOG.debug("Initializing B2 Storage Client at {}", alluxioURI); B2StorageClient client = B2StorageClientFactory.createDefaultFactory() .create(conf.get(PropertyKey.B2_ACCESS_KEY), conf.get(PropertyKey.B2_SECRET_KEY), USER_AGENT); try { B2AccountAuthorization accountAuthorization = client.getAccountAuthorization(); LOG.debug("B2AccountAuthorization {}", accountAuthorization); B2Allowed allowed = accountAuthorization.getAllowed(); LOG.debug("B2Allowed {}", allowed); String accountId = accountAuthorization.getAccountId(); List<String> capabilities = allowed.getCapabilities(); String bucketNameFromURI = UnderFileSystemUtils.getBucketName(alluxioURI); LOG.debug("bucket name from uri {}", bucketNameFromURI); String bucketId; String bucketName; if (allowed.getBucketId() != null) { bucketId = allowed.getBucketId(); bucketName = allowed.getBucketName(); } else { B2Bucket bucket = client.getBucketOrNullByName(bucketNameFromURI); LOG.debug("B2Bucket {}", bucket); bucketId = bucket.getBucketId(); bucketName = bucket.getBucketName(); } short bucketMode = B2Utils.translateBucketAcl(capabilities); return new B2UnderFileSystem(alluxioURI, conf, client, bucketId, bucketName, bucketMode, accountId); } catch (B2Exception | NullPointerException e) { LOG.error("Failed to instantiate B2UnderFileSystem client with key:{} and URI: {}", conf.get(PropertyKey.B2_ACCESS_KEY), alluxioURI); Throwables.propagateIfPossible(e, ServiceException.class); } return null; }
Source:
private void uploadParts(List<Part> parts, File file, String objectId, String uploadId, Progress progressBar) { transportBuilder.withProxy(storageService) .withProgressBar(progressBar) .withParts(parts) .withObjectId(objectId) .withTransportMode(Mode.UPLOAD) .withSessionId(uploadId); transportBuilder.build().send(file); }

Target:
private void uploadParts(List<Part> parts, File file, String objectId, String uploadId, Progress progressBar) { val transport = transportBuilder .withProxy(storageService) .withProgressBar(progressBar) .withParts(parts) .withObjectId(objectId) .withTransportMode(Mode.UPLOAD) .withSessionId(uploadId).build(); transport.send(file); }
Source:
public long getExpirationTimeStamp() { return lastUpdate.getTime() + lifeTimeInSec * 1000; }

Target:
public long getExpirationTimeStamp() { return getExpirationTimeStamp(0L); }
Source:
public ValidationWhiteListDeleteRequestBuilder prepareDelete(String id) { return prepareDelete(newHashSet(id)); }

Target:
public ValidationWhiteListDeleteRequestBuilder prepareDelete(String id) { return prepareDelete(Collections.singleton(id)); }
Source:
public void handle(LegacyPing ping) throws Exception { ServerPing legacy = new ServerPing( new ServerPing.Protocol( bungee.getGameVersion(), bungee.getProtocolVersion() ), new ServerPing.Players( listener.getMaxPlayers(), bungee.getOnlineCount(), null ), listener.getMotd(), new Favicon( null ) ); legacy = bungee.getPluginManager().callEvent( new ProxyPingEvent( this, legacy ) ).getResponse(); String kickMessage = ChatColor.DARK_BLUE + "\00" + 127 + "\00" + legacy.getVersion().getName() + "\00" + legacy.getDescription() + "\00" + legacy.getPlayers().getOnline() + "\00" + legacy.getPlayers().getMax(); ch.getHandle().writeAndFlush( kickMessage ); ch.close(); }

Target:
public void handle(LegacyPing ping) throws Exception { ServerPing legacy = new ServerPing( new ServerPing.Protocol( bungee.getGameVersion(), bungee.getProtocolVersion() ), new ServerPing.Players( listener.getMaxPlayers(), bungee.getOnlineCount(), null ), listener.getMotd(), (Favicon) null ); legacy = bungee.getPluginManager().callEvent( new ProxyPingEvent( this, legacy ) ).getResponse(); String kickMessage = ChatColor.DARK_BLUE + "\00" + 127 + "\00" + legacy.getVersion().getName() + "\00" + legacy.getDescription() + "\00" + legacy.getPlayers().getOnline() + "\00" + legacy.getPlayers().getMax(); ch.getHandle().writeAndFlush( kickMessage ); ch.close(); }
Source:
public void start() { LOG.info("Starting the container process manager"); int containerRetryCount = clusterManagerConfig.getContainerRetryCount(); if (containerRetryCount < ClusterManagerConfig.DEFAULT_CONTAINER_RETRY_COUNT) { LOG.warn("{} configured to: that is less than the default of: may cause premature failure of this job", ClusterManagerConfig.CLUSTER_MANAGER_CONTAINER_RETRY_COUNT, containerRetryCount, ClusterManagerConfig.DEFAULT_CONTAINER_RETRY_COUNT); } if (containerRetryCount > -1) { LOG.info("Max retries on restarting failed containers: {}", containerRetryCount); } else { LOG.info("Infinite retries on restarting failed containers"); } if (jvmMetrics != null) { jvmMetrics.start(); } if (metricsReporters != null) { metricsReporters.values().forEach(reporter -> reporter.start()); } if (diagnosticsManager.isDefined()) { diagnosticsManager.get().start(); } LOG.info("Starting the cluster resource manager"); clusterResourceManager.start(); state.processorCount.set(state.jobModelManager.jobModel().getContainers().size()); state.neededProcessors.set(state.jobModelManager.jobModel().getContainers().size()); Map<String, String> processorToHostMapping = state.jobModelManager.jobModel().getAllContainerLocality(); containerAllocator.requestResources(processorToHostMapping); LOG.info("Starting the container allocator thread"); allocatorThread.start(); LOG.info("Starting the container process manager"); }

Target:
public void start() { LOG.info("Starting the container process manager"); int containerRetryCount = clusterManagerConfig.getContainerRetryCount(); if (containerRetryCount > -1) { LOG.info("Max retries on restarting failed containers: {}", containerRetryCount); } else { LOG.info("Infinite retries on restarting failed containers"); } if (jvmMetrics != null) { jvmMetrics.start(); } if (metricsReporters != null) { metricsReporters.values().forEach(reporter -> reporter.start()); } if (diagnosticsManager.isDefined()) { diagnosticsManager.get().start(); } LOG.info("Starting the cluster resource manager"); clusterResourceManager.start(); state.processorCount.set(state.jobModelManager.jobModel().getContainers().size()); state.neededProcessors.set(state.jobModelManager.jobModel().getContainers().size()); Map<String, String> processorToHostMapping = state.jobModelManager.jobModel().getAllContainerLocality(); containerAllocator.requestResources(processorToHostMapping); LOG.info("Starting the container allocator thread"); allocatorThread.start(); LOG.info("Starting the container process manager"); }
Source:
public String getDefaultExchange() { return null != exInfo ? exInfo.getDefaultExchange() : null; }

Target:
public String getDefaultExchange() { if (exInfo == null) { try { loadExchangeInfo(); } catch (ExchangeManagerException e) { LOG.error("There are some exception while loading internal exchange information ", e.getLocalizedMessage(), e); } } return null != exInfo ? exInfo.getDefaultExchange() : null; }
Source:
public Key(String location, InetAddress ipAddress) { this.location = location != null ? location : MonitoringLocationDao.DEFAULT_MONITORING_LOCATION_ID; this.ipAddress = Objects.requireNonNull(ipAddress); }

Target:
public Key(String location, InetAddress ipAddress) { this.location = LocationUtils.getEffectiveLocationName(location); this.ipAddress = Objects.requireNonNull(ipAddress); }
Source:
public void dismiss() { if (!mAnimated) { finish(); return; } if (mIsDismissing) { return; } final Animation slideOut = AnimationUtils.loadAnimation(getContext(), R.anim.snackbar_out); slideOut.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { mIsDismissing = true; if (mEventListener != null && mIsShowing) { mEventListener.onDismiss(getHeight() + mOffset); } } @Override public void onAnimationEnd(Animation animation) { post(new Runnable() { @Override public void run() { finish(); } }); } @Override public void onAnimationRepeat(Animation animation) { } }); startAnimation(slideOut); }

Target:
public void dismiss() { if (mIsDismissing) { return; } mIsDismissing = true; if (mEventListener != null && mIsShowing) { mEventListener.onDismiss(Snackbar.this); } if (!mAnimated) { finish(); return; } final Animation slideOut = AnimationUtils.loadAnimation(getContext(), R.anim.snackbar_out); slideOut.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { post(new Runnable() { @Override public void run() { finish(); } }); } @Override public void onAnimationRepeat(Animation animation) { } }); startAnimation(slideOut); }
Source:
public FormPage(final float height, final float textAngle, final DimensionUnit unit, final float width, final IterableStream<FormLine> lines, final IterableStream<FormTable> tables) { this.height = height; this.textAngle = textAngle; this.unit = unit; this.width = width; this.lines = lines == null ? new IterableStream<FormLine>(Collections.emptyList()) : lines; this.tables = tables == null ? new IterableStream<FormTable>(Collections.emptyList()) : tables; }

Target:
public FormPage(final float height, final float textAngle, final DimensionUnit unit, final float width, final IterableStream<FormLine> lines, final IterableStream<FormTable> tables) { this.height = height; this.textAngle = textAngle; this.unit = unit; this.width = width; this.lines = IterableStream.of(lines); this.tables = IterableStream.of(tables); }
Source:
@Override public final boolean permitsMethod(Method method, Object receiver, Object[] args) { String key = Whitelist.canonicalMethodSig(method); Boolean b = permittedCache.get(key); if (b != null) { return b; } boolean output = false; for (MethodSignature s : methodSignatures()) { if (s.matches(method)) { output = true; break; } } permittedCache.put(key, output); return output; }

Target:
@Override public final boolean permitsMethod(Method method, Object receiver, Object[] args) { String key = canonicalMethodSig(method); Boolean b = permittedCache.get(key); if (b != null) { return b; } boolean output = false; for (MethodSignature s : methodSignatures()) { if (s.matches(method)) { output = true; break; } } permittedCache.put(key, output); return output; }
Source:
public void verifyPushToTopWikiThumbnail() { waitForElementByElement(pushToTopWikiThumbnail); }

Target:
public void verifyPushToTopWikiThumbnail() { waitForElementByElement(pushToTopWikiThumbnail); PageObjectLogging.log("verifyPushToTopWikiThumbnail", "Push to top wiki thumbnail verified", true, driver); }
Source:
public boolean doSomething(@NotNull PsiFile file, @NotNull Project project, @Nullable final VirtualFile virtualFile, @NotNull String groupId) throws ExecutionException { if (virtualFile == null || !virtualFile.isInLocalFileSystem()) return true; Document document = PsiDocumentManager.getInstance(project).getDocument(file); assert document != null; String filePath = virtualFile.getCanonicalPath(); assert filePath != null; GeneralCommandLine commandLine = new GeneralCommandLine(); String sdkHome = GoSdkService.getInstance().getSdkHomePath(project); if (StringUtil.isEmpty(sdkHome)) { warning(project, groupId, "Project sdk is not valid"); return true; } File executable = GoEnvironmentUtil.getExecutableForSdk(sdkHome); commandLine.setExePath(executable.getAbsolutePath()); commandLine.addParameters("fmt", filePath); commandLine.setPassParentEnvironment(true); FileDocumentManager.getInstance().saveDocument(document); String commandLineString = commandLine.getCommandLineString(); OSProcessHandler handler = new OSProcessHandler(commandLine.createProcess(), commandLineString); handler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(ProcessEvent event) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { virtualFile.refresh(false, false); } }); } }); } }); handler.startNotify(); return false; }

Target:
public boolean doSomething(@NotNull PsiFile file, @NotNull Project project, @Nullable final VirtualFile virtualFile, @NotNull String groupId) throws ExecutionException { if (virtualFile == null || !virtualFile.isInLocalFileSystem()) return true; Document document = PsiDocumentManager.getInstance(project).getDocument(file); assert document != null; String filePath = virtualFile.getCanonicalPath(); assert filePath != null; File executable = GoEnvironmentUtil.getBinaryFilePathFromEnvironment("gofmt"); if (executable == null) { warning(project, groupId, "Looks like you haven't any gofmt executable in your PATH"); return true; } FileDocumentManager.getInstance().saveDocument(document); GoExecutor. in(project). addParameters("fmt", filePath). showOutputOnError(). execute(); return false; }
Source:
protected ToggleDetailPaneAction getToggleDetailPaneAction(String orientation) { for (ToggleDetailPaneAction fToggleDetailPaneAction : fToggleDetailPaneActions) { if (fToggleDetailPaneAction.getOrientation().equals(orientation)) { return fToggleDetailPaneAction; } } return null; }

Target:
protected ToggleDetailPaneAction getToggleDetailPaneAction(String orientation) { for (ToggleDetailPaneAction action : fToggleDetailPaneActions) { if (action.getOrientation().equals(orientation)) { return action; } } return null; }
Source:
public PlanNode visitMarkDistinct(MarkDistinctNode node, RewriteContext<Expression> context) { if (!SymbolsExtractor.extractUnique(context.get()).contains(node.getMarkerSymbol())) { return context.defaultRewrite(node, context.get()); } if (context.get() == TRUE_LITERAL) { return node; } return new FilterNode(idAllocator.getNextId(), node, context.get()); }

Target:
public PlanNode visitMarkDistinct(MarkDistinctNode node, RewriteContext<Expression> context) { Set<Symbol> pushDownableSymbols = ImmutableSet.copyOf(node.getDistinctSymbols()); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream() .collect(Collectors.partitioningBy(conjunct -> SymbolsExtractor.extractUnique(conjunct).stream().allMatch(pushDownableSymbols::contains))); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(conjuncts.get(true))); if (!conjuncts.get(false).isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(conjuncts.get(false))); } return rewrittenNode; }
Source:
public void serve() throws TException { Dispatcher dispatcher = conn.createDispatcher(newRequestHandler()); for (String subject : subjects) { if (queue != null && !queue.isEmpty()) { dispatcher.subscribe(subject, queue); } else { dispatcher.subscribe(subject); } } LOGGER.info("Frugal server running..."); try { shutdownSignal.await(); } catch (InterruptedException ignored) { } LOGGER.info("Frugal server stopping..."); for (String subject : subjects) { try { dispatcher.unsubscribe(subject); } catch (IllegalArgumentException e) { LOGGER.warn("Frugal server failed to unsubscribe from " + subject + ": " + e.getMessage()); } } }

Target:
public void serve() throws TException { Dispatcher dispatcher = conn.createDispatcher(newRequestHandler()); for (String subject : subjects) { if (queue != null && !queue.isEmpty()) { dispatcher.subscribe(subject, queue); } else { dispatcher.subscribe(subject); } } LOGGER.info("Frugal server running..."); try { shutdownSignal.await(); } catch (InterruptedException ignored) { } LOGGER.info("Frugal server stopping..."); for (String subject : subjects) { try { dispatcher.unsubscribe(subject); } catch (IllegalStateException e) { LOGGER.warn("Frugal server failed to unsubscribe from " + subject + ": " + e.getMessage()); } } conn.closeDispatcher(dispatcher); }
Source:
public void test() throws Exception { deleteDb("functions"); testOverrideAlias(); deleteDb("functions"); if (!config.networked) { JdbcConnection conn = (JdbcConnection) getConnection("functions"); Session session = (Session) conn.getSession(); testToDate(session); testToDateException(session); conn.close(); } testVersion(); testFunctionTable(); testFunctionTableVarArgs(); testArrayParameters(); testDefaultConnection(); testFunctionInSchema(); testGreatest(); testSource(); testDynamicArgumentAndReturn(); testUUID(); testBase64(); testWhiteSpacesInParameters(); testSchemaSearchPath(); testDeterministic(); testTransactionId(); testPrecision(); testVarArgs(); testAggregate(); testAggregateType(); testFunctions(); testFileRead(); testValue(); testNvl2(); testConcatWs(); testToCharFromDateTime(); testToCharFromNumber(); testToCharFromText(); testFileWrite(); testThatCurrentTimestampIsSane(); testThatCurrentTimestampStaysTheSameWithinATransaction(); testThatCurrentTimestampUpdatesOutsideATransaction(); testAnnotationProcessorsOutput(); testSignal(); deleteDb("functions"); }

Target:
public void test() throws Exception { deleteDb("functions"); testOverrideAlias(); deleteDb("functions"); if (!config.networked) { JdbcConnection conn = (JdbcConnection) getConnection("functions"); Session session = (Session) conn.getSession(); testToDate(session); testToDateException(session); conn.close(); } testVersion(); testFunctionTable(); testFunctionTableVarArgs(); testArrayParameters(); testDefaultConnection(); testFunctionInSchema(); testGreatest(); testSource(); testDynamicArgumentAndReturn(); testUUID(); testWhiteSpacesInParameters(); testSchemaSearchPath(); testDeterministic(); testTransactionId(); testPrecision(); testVarArgs(); testAggregate(); testAggregateType(); testFunctions(); testFileRead(); testValue(); testNvl2(); testConcatWs(); testToCharFromDateTime(); testToCharFromNumber(); testToCharFromText(); testFileWrite(); testThatCurrentTimestampIsSane(); testThatCurrentTimestampStaysTheSameWithinATransaction(); testThatCurrentTimestampUpdatesOutsideATransaction(); testAnnotationProcessorsOutput(); testSignal(); deleteDb("functions"); }
Source:
public double getSafely() throws InvalidSensorException { if (!enable) { return F * setpoint; } double input = 0.0; input = sensor.pidGet(); double error = setpoint - input; if (continuous) { double range = inputMax - inputMin; if (Math.abs(error) > range / 2) { if (error > 0) { error -= range; } else { error += range; } } } double errorDerivative = (error - lastError); totalError += error; double result = P * error + I * totalError + D * errorDerivative + F * setpoint; lastError = error; LogKitten.v(input + " " + setpoint + " " + result); if (capOutput) { result = Math.max(Math.min(result, outputMax), outputMin); } return result; }

Target:
public double getSafely() throws InvalidSensorException { if (!enable) { return F * setpoint; } double input = 0.0; input = sensor.pidGet(); double error = setpoint - input; if (continuous) { double range = inputMax - inputMin; if (Math.abs(error) > range / 2) { if (error > 0) { error -= range; } else { error += range; } } } double errorDerivative; long latestTime = System.currentTimeMillis(); long timeDiff = latestTime - lastTime; if (sensor instanceof NativeDerivativeSensor && sensor.getPIDSourceType() == PIDSourceType.kDisplacement) { errorDerivative = ((NativeDerivativeSensor) sensor).getRateSafely(); } else { errorDerivative = (error - lastError) / timeDiff; } lastTime = latestTime; totalError += error * timeDiff; double result = P * error + I * totalError + D * errorDerivative + F * setpoint; lastError = error; LogKitten.v(input + " " + setpoint + " " + result); if (capOutput) { result = Math.max(Math.min(result, outputMax), outputMin); } if (Math.abs(result) < minimumNominalOutput) { result = Math.signum(result) * minimumNominalOutput; } return result; }
Source:
public void shouldSaveARemoteIdentifierGenerator() throws Exception { long initialIdentifierSourceCount = getAllCount(); SimpleObject identifierSource = new SimpleObject(); identifierSource.add("name", "test remote identifier"); identifierSource.add("description", "test remote identifier"); identifierSource.add("url", "http://localhost"); identifierSource.add("username", "openmrsuser"); identifierSource.add("password", "openmrspassword"); identifierSource.add("identifierType", IDENTIFIER_TYPE_UUID); identifierSource.add("sourceType", "RemoteIdentifierSource"); String jsonIdentifierSource = new ObjectMapper().writeValueAsString(identifierSource); MockHttpServletRequest req = newPostRequest(getURI(), jsonIdentifierSource); handle(req); assertEquals(service.getAllIdentifierSources(false).get(7).getName(), "test remote identifier"); assertEquals(initialIdentifierSourceCount + 1, getAllCount()); }

Target:
public void shouldSaveARemoteIdentifierGenerator() throws Exception { long initialIdentifierSourceCount = getAllCount(); SimpleObject identifierSource = new SimpleObject(); identifierSource.add("name", "test remote identifier"); identifierSource.add("description", "This is a test description for the remote identifier"); identifierSource.add("url", "http://localhost"); identifierSource.add("username", "openmrsuser"); identifierSource.add("password", "openmrspassword"); identifierSource.add("identifierType", IDENTIFIER_TYPE_UUID); identifierSource.add("sourceType", REMOTE_IDENTIFIER_SOURCE_TYPE); String jsonIdentifierSource = new ObjectMapper().writeValueAsString(identifierSource); MockHttpServletRequest req = newPostRequest(getURI(), jsonIdentifierSource); SimpleObject newIdentifierSource = deserialize(handle(req)); String newIdentifierSourceUuid = PropertyUtils.getProperty(newIdentifierSource, "uuid").toString(); RemoteIdentifierSource generatedIdentifierSource = (RemoteIdentifierSource) service.getIdentifierSourceByUuid(newIdentifierSourceUuid); assertEquals(newIdentifierSourceUuid, generatedIdentifierSource.getUuid()); assertEquals(generatedIdentifierSource.getName(), "test remote identifier"); assertEquals(generatedIdentifierSource.getDescription(), "This is a test description for the remote identifier"); assertEquals(generatedIdentifierSource.getUrl(), "http://localhost"); assertEquals(generatedIdentifierSource.getUser(), "openmrsuser"); assertEquals(generatedIdentifierSource.getPassword(), "openmrspassword"); assertEquals(generatedIdentifierSource.getIdentifierType().getUuid(), IDENTIFIER_TYPE_UUID); assertEquals(initialIdentifierSourceCount + 1, getAllCount()); }
Source:
private Certificate generateCertificate() throws Exception { InputStream stream = new ByteArrayInputStream(publicCertificate); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Certificate certificate = certificateFactory.generateCertificate(stream); stream.close(); return certificate; }

Target:
private Certificate generateCertificate() throws IOException, CertificateException { try (InputStream stream = new ByteArrayInputStream(publicCertificate)) { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return certificateFactory.generateCertificate(stream); } }
Source:
public ScoredDocuments rerank(ScoredDocuments docs, RerankerContext context) { IndexReader reader = context.getIndexSearcher().getIndexReader(); String queryDocId = context.getQueryDocId(); final Map<String, Long> queryTermsMap = convertDocVectorToMap(reader, queryDocId); List<Map<String, Long>> docsVectorsMap = new ArrayList<>(); for (int i = 0; i < docs.documents.length; i++) { String docid = docs.documents[i].getField(FIELD_ID).stringValue(); docsVectorsMap.add(convertDocVectorToMap(reader, docid)); } Set<Integer> forbiddenDocIdsIndex = new HashSet<>(); for (int i = 0; i < docs.documents.length; i++) { if (forbiddenDocIdsIndex.contains(i)) continue; String docid = docs.documents[i].getField(FIELD_ID).stringValue(); if (computeCosineSimilarity(queryTermsMap, docsVectorsMap.get(i)) >= 0.9) { forbiddenDocIdsIndex.add(i); continue; } for (int j = i+1; j < docs.documents.length; j++) { if (computeCosineSimilarity(docsVectorsMap.get(i), docsVectorsMap.get(j)) >= 0.9) { forbiddenDocIdsIndex.add(j); } } } ScoredDocuments scoredDocs = new ScoredDocuments(); int resSize = docs.documents.length - forbiddenDocIdsIndex.size(); scoredDocs.documents = new Document[resSize]; scoredDocs.ids = new int[resSize]; scoredDocs.scores = new float[resSize]; int idx = 0; for (int i = 0; i < docs.documents.length; i++) { if (!forbiddenDocIdsIndex.contains(i)) { scoredDocs.documents[idx] = docs.documents[i]; scoredDocs.scores[idx] = docs.scores[i]; scoredDocs.ids[idx] = docs.ids[i]; idx++; } } return scoredDocs; }

Target:
public ScoredDocuments rerank(ScoredDocuments docs, RerankerContext context) { IndexReader reader = context.getIndexSearcher().getIndexReader(); String queryDocId = context.getQueryDocId(); final Map<String, Long> queryTermsMap = convertDocVectorToMap(reader, queryDocId); List<Map<String, Long>> docsVectorsMap = new ArrayList<>(); for (int i = 0; i < docs.documents.length; i++) { String docid = docs.documents[i].getField(FIELD_ID).stringValue(); docsVectorsMap.add(convertDocVectorToMap(reader, docid)); } Set<Integer> duplicates = new HashSet<>(); for (int i = 0; i < docs.documents.length; i++) { if (duplicates.contains(i)) continue; String docid = docs.documents[i].getField(FIELD_ID).stringValue(); if (computeCosineSimilarity(queryTermsMap, docsVectorsMap.get(i)) >= 0.9) { duplicates.add(i); continue; } for (int j = i+1; j < docs.documents.length; j++) { if (computeCosineSimilarity(docsVectorsMap.get(i), docsVectorsMap.get(j)) >= 0.9) { duplicates.add(j); } } } ScoredDocuments scoredDocs = new ScoredDocuments(); int resSize = docs.documents.length - duplicates.size(); scoredDocs.documents = new Document[resSize]; scoredDocs.ids = new int[resSize]; scoredDocs.scores = new float[resSize]; int idx = 0; for (int i = 0; i < docs.documents.length; i++) { if (!duplicates.contains(i)) { scoredDocs.documents[idx] = docs.documents[i]; scoredDocs.scores[idx] = docs.scores[i]; scoredDocs.ids[idx] = docs.ids[i]; idx++; } } return scoredDocs; }
Source:
DeviceToNodeMetadata(PlanToHardware planToHardware, OperatingSystemToImage operatingSystemToImage, FacilityToLocation facilityToLocation, Function<Device.State, NodeMetadata.Status> toPortableStatus, GroupNamingConvention.Factory groupNamingConvention) { this.planToHardware = checkNotNull(planToHardware, "planToHardware cannot be null"); this.operatingSystemToImage = checkNotNull(operatingSystemToImage, "operatingSystemToImage cannot be null"); this.facilityToLocation = checkNotNull(facilityToLocation, "facilityToLocation cannot be null"); this.toPortableStatus = checkNotNull(toPortableStatus, "toPortableStatus cannot be null"); this.groupNamingConvention = checkNotNull(groupNamingConvention, "groupNamingConvention cannot be null") .createWithoutPrefix(); }

Target:
DeviceToNodeMetadata(PlanToHardware planToHardware, OperatingSystemToImage operatingSystemToImage, FacilityToLocation facilityToLocation, Function<Device.State, NodeMetadata.Status> toPortableStatus, GroupNamingConvention.Factory groupNamingConvention) { this.planToHardware = planToHardware; this.operatingSystemToImage = operatingSystemToImage; this.facilityToLocation = facilityToLocation; this.toPortableStatus = toPortableStatus; this.groupNamingConvention = groupNamingConvention.createWithoutPrefix(); }
Source:
private void onEvent(CoreEvent event, ExecutorCallback executorCallback) { try { SdkInternalContext sdkInternalContext = ((SdkInternalContext) ((InternalEvent) event).<SdkInternalContext>getSdkInternalContext()); final Optional<ConfigurationInstance> configuration = sdkInternalContext.getConfiguration(); final Map<String, Object> resolutionResult = sdkInternalContext.getResolutionResult(); OperationExecutionFunction operationExecutionFunction = (parameters, operationEvent, callback) -> { sdkInternalContext.setOperationExecutionParams(configuration, parameters, operationEvent, callback); fluxSupplier.get().next(operationEvent); }; if (getLocation() != null) { ((DefaultFlowCallStack) event.getFlowCallStack()) .setCurrentProcessorPath(resolvedProcessorRepresentation); sdkInternalContext.getPolicyToApply().process(event, operationExecutionFunction, () -> resolutionResult, getLocation(), executorCallback); } else { operationExecutionFunction.execute(resolutionResult, event, executorCallback); } } catch (Throwable t) { executorCallback.error(unwrap(t)); } }

Target:
private void onEvent(CoreEvent event, ExecutorCallback executorCallback) { try { SdkInternalContext sdkInternalContext = from(event); final Optional<ConfigurationInstance> configuration = sdkInternalContext.getConfiguration(); final Map<String, Object> resolutionResult = sdkInternalContext.getResolutionResult(); OperationExecutionFunction operationExecutionFunction = (parameters, operationEvent, callback) -> { sdkInternalContext.setOperationExecutionParams(configuration, parameters, operationEvent, callback); fluxSupplier.get().next(operationEvent); }; if (getLocation() != null) { ((DefaultFlowCallStack) event.getFlowCallStack()) .setCurrentProcessorPath(resolvedProcessorRepresentation); sdkInternalContext.getPolicyToApply().process(event, operationExecutionFunction, () -> resolutionResult, getLocation(), executorCallback); } else { operationExecutionFunction.execute(resolutionResult, event, executorCallback); } } catch (Throwable t) { executorCallback.error(unwrap(t)); } }
Source:
public List<Channel> getChannelsOfGroup(String channelGroupId) { List<Channel> channels = new ArrayList<>(); for (Channel channel : this.channels) { ChannelUID channelUID = channel.getUID(); if (channelUID.isInGroup() && channelUID.getGroupId().equals(channelGroupId)) { channels.add(channel); } } return Collections.unmodifiableList(channels); }

Target:
public List<Channel> getChannelsOfGroup(String channelGroupId) { List<Channel> channels = new ArrayList<>(); for (Channel channel : this.channels) { if (channelGroupId.equals(channel.getUID().getGroupId())) { channels.add(channel); } } return Collections.unmodifiableList(channels); }
Source:
public void delete(final OperatorChain query) { synchronized (sharedLock) { activeQueryWaitingQueue.remove(query); activeQueryWorkingQueue.remove(query); } }

Target:
public void delete(final OperatorChain query) { activeQueryQueue.remove(query); }
Source:
public void updateCatalog(Table table, long genId) { m_es.execute(new Runnable() { public void run() { if (genId != m_previousGenId) { assert (genId > m_previousGenId); StreamTableSchemaSerializer ds = new StreamTableSchemaSerializer(table, table.getTypeName(), genId); try { m_committedBuffers.updateSchema(ds); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to write PBD export header.", true, e); } m_previousGenId = genId; } } }); }

Target:
public void updateCatalog(Table table, long genId) { if (m_previousGenId >= genId) { return; } m_es.execute(new Runnable() { public void run() { if (m_previousGenId < genId) { StreamTableSchemaSerializer ds = new StreamTableSchemaSerializer(table, table.getTypeName(), genId); try { m_committedBuffers.updateSchema(ds); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to write PBD export header.", true, e); } m_previousGenId = genId; } } }); }
Source:
public static String getPathInDocument(Document document, String path) throws InterceptorException { if (document == null) { throw new InterceptorException("document may not be null"); } if (StringUtils.isEmpty(path)) { throw new InterceptorException("Missing parameter path"); } String result; try { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile(path); result = expr.evaluate(document, XPathConstants.STRING).toString(); } catch (XPathExpressionException e) { throw new InterceptorException("Could not : " + e.getMessage()); } return result; }

Target:
public static String getPathInDocument(Document document, String path) throws InterceptorException { if (document == null) { throw new InterceptorException("Document may not be null"); } if (StringUtils.isEmpty(path)) { throw new InterceptorException("Missing parameter path"); } String result; try { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile(path); result = expr.evaluate(document, XPathConstants.STRING).toString(); } catch (XPathExpressionException e) { throw new InterceptorException("Error while selecting document " + "element with XPath: " + e.getMessage()); } return result; }
Source:
public static void createTables(KeyValueService keyValueService) { keyValueService.createTables(ImmutableMap.of( TransactionConstants.TRANSACTION_TABLE, TransactionConstants.TRANSACTION_TABLE_METADATA.persistToBytes(), TransactionConstants.TRANSACTIONS2_TABLE, TransactionConstants.TRANSACTIONS2_METADATA.persistToBytes())); }

Target:
public static void createTables(KeyValueService keyValueService) { keyValueService.createTables(ImmutableMap.of( TransactionConstants.TRANSACTION_TABLE, TransactionConstants.TRANSACTION_TABLE_METADATA.persistToBytes(), TransactionConstants.TRANSACTIONS2_TABLE, TransactionConstants.TRANSACTIONS2_TABLE_METADATA.persistToBytes())); }
Source:
public void testSettingVariableWithSetWithMemory() throws Throwable { MIStoppedEvent stoppedEvent = SyncUtil.runToLocation("testMemoryChanges"); final IFrameDMContext frameDmc = SyncUtil.getStackFrame(stoppedEvent.getDMContext(), 0); final IExpressionDMContext exprDmc = SyncUtil.createExpression(frameDmc, "i"); Query<IExpressionDMAddress> query = new Query<IExpressionDMAddress>() { @Override protected void execute(final DataRequestMonitor<IExpressionDMAddress> rm) { fExprService.getExpressionAddressData(exprDmc, rm); } }; fSession.getExecutor().execute(query); IExpressionDMAddress data = query.get(); IMemoryDMContext memoryDmc = DMContexts.getAncestorOfType(frameDmc, IMemoryDMContext.class); readMemory(memoryDmc, data.getAddress(), 1); fEventsReceived.clear(); final String NEW_VALUE = "100"; queueConsoleCommand("set variable i=" + NEW_VALUE); IMemoryChangedEvent memoryEvent = waitForEvent(IMemoryChangedEvent.class); assertEquals(1, memoryEvent.getAddresses().length); assertEquals(data.getAddress(), memoryEvent.getAddresses()[0]); MemoryByte[] memory = readMemory(memoryDmc, data.getAddress(), 1); assertEquals(NEW_VALUE, Byte.toString(memory[0].getValue())); String exprValue = SyncUtil.getExpressionValue(exprDmc, IFormattedValues.DECIMAL_FORMAT); assertEquals(NEW_VALUE, exprValue); }

Target:
public void testSettingVariableWithSetWithMemory() throws Throwable { MIStoppedEvent stoppedEvent = SyncUtil.runToLocation("testMemoryChanges"); final IFrameDMContext frameDmc = SyncUtil.getStackFrame(stoppedEvent.getDMContext(), 0); final IExpressionDMContext exprDmc = SyncUtil.createExpression(frameDmc, "i"); Query<IExpressionDMAddress> query = new Query<IExpressionDMAddress>() { @Override protected void execute(final DataRequestMonitor<IExpressionDMAddress> rm) { fExprService.getExpressionAddressData(exprDmc, rm); } }; fSession.getExecutor().execute(query); IExpressionDMAddress data = query.get(); IMemoryDMContext memoryDmc = DMContexts.getAncestorOfType(frameDmc, IMemoryDMContext.class); readMemory(memoryDmc, data.getAddress(), 1); fEventsReceived.clear(); final String newValue = "100"; queueConsoleCommand("set variable i=" + newValue); IMemoryChangedEvent memoryEvent = waitForEvent(IMemoryChangedEvent.class); assertEquals(1, memoryEvent.getAddresses().length); assertEquals(data.getAddress(), memoryEvent.getAddresses()[0]); MemoryByte[] memory = readMemory(memoryDmc, data.getAddress(), 1); assertEquals(newValue, Byte.toString(memory[0].getValue())); String exprValue = SyncUtil.getExpressionValue(exprDmc, IFormattedValues.DECIMAL_FORMAT); assertEquals(newValue, exprValue); }
Source:
public synchronized void resumeAction() { if (isSuspended) { clearAction(); if (!suspendedActions.isEmpty()) { actions.addAll(suspendedActions); suspendedActions.clear(); } else { value = suspendedValue; } isSuspended = false; logger.trace("resuming suspended actions for channel {}", this); } else { logger.warn("trying to resume actions in non-suspended channel {}", this); } }

Target:
public synchronized void resumeAction() throws IllegalStateException { if (isSuspended) { clearAction(); if (!suspendedActions.isEmpty()) { actions.addAll(suspendedActions); suspendedActions.clear(); } else { value = suspendedValue; } isSuspended = false; logger.trace("resuming suspended actions for channel {}", this); } else { throw new IllegalStateException("trying to resume actions in non-suspended channel " + this.toString()); } }
Source:
public void rangeWrite(CorfuPayloadMsg<RangeWriteMsg> msg, ChannelHandlerContext ctx, IServerRouter r) { List<LogData> range = msg.getPayload().getEntries(); log.debug("rangeWrite: Writing entries [{}-{}]", range.size(), range.get(0).getGlobalAddress(), range.get(range.size() - 1).getGlobalAddress()); batchWriter.addTask(RANGE_WRITE, msg) .thenAccept(Void -> r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg())) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }

Target:
public void rangeWrite(CorfuPayloadMsg<RangeWriteMsg> msg, ChannelHandlerContext ctx, IServerRouter r) { List<LogData> range = msg.getPayload().getEntries(); log.debug("rangeWrite: Writing entries [{}-{}]", range.size(), range.get(0).getGlobalAddress(), range.get(range.size() - 1).getGlobalAddress()); batchWriter.addTask(RANGE_WRITE, msg) .thenRun(() -> r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg())) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }
Source:
public Object finalizeComputation(@Nullable Object object) { return object == null ? object : ((SerializablePair<Long, Float>) object).rhs; }

Target:
public Object finalizeComputation(@Nullable Object object) { return object == null ? null : ((SerializablePair<Long, Float>) object).rhs; }
Source:
public void testCollector() { final CollectorAsserterMonitor mon = new CollectorAsserterMonitor(); final int[] numLoops = new int[] { 10000 }; IProgressMonitorWithBlocking wrapper = ProgressMonitorUtil.createAccumulatingProgressMonitor(mon, Display.getDefault()); wrapper.beginTask("Some Task", 100); for (int i = 0; i < numLoops[0]; i++) { wrapper.setTaskName("Task Name " + i); } wrapper.done(); ArrayList<String> tasks = mon.getTaskNames(); int size = tasks.size(); assertEquals(0, size); runEventLoopUntilEmpty(); tasks = mon.getTaskNames(); size = tasks.size(); assertEquals(1, size); }

Target:
public void testCollector() { final CollectorAsserterMonitor mon = new CollectorAsserterMonitor(); final int[] numLoops = new int[] { 10000 }; IProgressMonitorWithBlocking wrapper = ProgressMonitorUtil.createAccumulatingProgressMonitor(mon, Display.getDefault()); wrapper.beginTask("Some Task", 100); for (int i = 0; i < numLoops[0]; i++) { wrapper.setTaskName("Task Name " + i); } wrapper.done(); ArrayList<String> tasks = mon.getTaskNames(); int size = tasks.size(); assertEquals(0, size); runEventLoopUntilEmpty(); tasks = mon.getTaskNames(); size = tasks.size(); assertEquals(1, size); String expected = "Task Name " + (numLoops[0] - 1); assertEquals(expected, tasks.get(0)); }
Source:
public void getMrrtReportTemplateByIdentifier_shouldFindObjectGivenValidIdentifier() throws Exception { MrrtReportTemplate template = mrrtReportTemplateService.getMrrtReportTemplateByIdentifier("identifier1"); assertNotNull(template); assertThat(template.getDcTermsIdentifier(), is("identifier1")); assertThat(template.getDcTermsTitle(), is("title1")); }

Target:
public void getMrrtReportTemplateByIdentifier_shouldFindObjectGivenValidIdentifier() throws Exception { MrrtReportTemplate template = mrrtReportTemplateService.getMrrtReportTemplateByIdentifier("identifier1"); assertNotNull(template); assertThat(template.getDcTermsIdentifier(), is("identifier1")); }