List of usage examples for org.apache.commons.lang3.tuple Pair of
public static <L, R> Pair<L, R> of(final L left, final R right)
Obtains an immutable pair of from two objects inferring the generic types.
This factory allows the pair to be created using inference to obtain the generic types.
From source file:enumj.EnumerableTest.java
@Test public void testOf_Stream() { System.out.println("of"); EnumerableGenerator.generatorPairs().limit(100) .map(p -> Pair.of(p.getLeft().ofStreamEnumerable(), p.getRight().ofStreamEnumerable())) .forEach(p -> assertTrue(p.getLeft().elementsEqual(p.getRight()))); }
From source file:enumj.EnumeratorTest.java
@Test public void testOf_Enumeration() { System.out.println("of enumeration"); EnumeratorGenerator.generatorPairs().limit(100) .map(p -> Pair.of(p.getLeft().ofEnumerationEnumerator(), p.getRight().ofEnumerationEnumerator())) .forEach(p -> assertTrue(p.getLeft().elementsEqual(p.getRight()))); EnumeratorGenerator.generatorPairs().limit(100) .map(p -> Pair.of(p.getLeft().ofEnumerationEnumerator(), p.getRight().ofIterableEnumerator())) .forEach(p -> assertTrue(p.getLeft().elementsEqual(p.getRight()))); }
From source file:com.yahoo.bullet.result.MetadataTest.java
@Test public void testConceptKeyExtraction() { Map<String, Object> configuration = new HashMap<>(); configuration.put(BulletConfig.RESULT_METADATA_ENABLE, true); configuration.put(BulletConfig.RESULT_METADATA_METRICS, asMetadataEntries(Pair.of("Estimated Result", "foo"), Pair.of("Aggregation Metadata", "bar"), Pair.of("Standard Deviations", "baz"))); Set<Concept> concepts = new HashSet<>( asList(Concept.ESTIMATED_RESULT, Concept.AGGREGATION_METADATA, Concept.STANDARD_DEVIATIONS)); Map<String, String> expectedMap = new HashMap<>(); expectedMap.put(Concept.ESTIMATED_RESULT.getName(), "foo"); expectedMap.put(Concept.AGGREGATION_METADATA.getName(), "bar"); expectedMap.put(Concept.STANDARD_DEVIATIONS.getName(), "baz"); Assert.assertEquals(Metadata.getConceptNames(configuration, concepts), expectedMap); }
From source file:com.uber.hoodie.common.table.view.HoodieTableFileSystemView.java
/** * Adds the provided statuses into the file system view, and also caches it inside this object. * * @param statuses//from w w w .j a v a 2s . c o m * @return */ private List<HoodieFileGroup> addFilesToView(FileStatus[] statuses) { Map<Pair<String, String>, List<HoodieDataFile>> dataFiles = convertFileStatusesToDataFiles(statuses) .collect(Collectors.groupingBy((dataFile) -> { String partitionPathStr = FSUtils.getRelativePartitionPath(new Path(metaClient.getBasePath()), dataFile.getFileStatus().getPath().getParent()); return Pair.of(partitionPathStr, dataFile.getFileId()); })); Map<Pair<String, String>, List<HoodieLogFile>> logFiles = convertFileStatusesToLogFiles(statuses) .collect(Collectors.groupingBy((logFile) -> { String partitionPathStr = FSUtils.getRelativePartitionPath(new Path(metaClient.getBasePath()), logFile.getPath().getParent()); return Pair.of(partitionPathStr, logFile.getFileId()); })); Set<Pair<String, String>> fileIdSet = new HashSet<>(dataFiles.keySet()); fileIdSet.addAll(logFiles.keySet()); List<HoodieFileGroup> fileGroups = new ArrayList<>(); fileIdSet.forEach(pair -> { HoodieFileGroup group = new HoodieFileGroup(pair.getKey(), pair.getValue(), visibleActiveTimeline); if (dataFiles.containsKey(pair)) { dataFiles.get(pair).forEach(dataFile -> group.addDataFile(dataFile)); } if (logFiles.containsKey(pair)) { logFiles.get(pair).forEach(logFile -> group.addLogFile(logFile)); } fileGroups.add(group); }); // add to the cache. fileGroups.forEach(group -> { fileGroupMap.put(group.getId(), group); if (!partitionToFileGroupsMap.containsKey(group.getPartitionPath())) { partitionToFileGroupsMap.put(group.getPartitionPath(), new ArrayList<>()); } partitionToFileGroupsMap.get(group.getPartitionPath()).add(group); }); return fileGroups; }
From source file:de.tntinteractive.portalsammler.sources.IngDibaSourceV1.java
@Override public Pair<Integer, Integer> poll(final SourceSettings settings, final UserInteraction gui, final SecureStore store) throws Exception { final WebDriver driver = this.createDriver("https://banking.ing-diba.de/app/login"); final WebElement userField = driver.findElement(By.name("view:kontonummer:border:border_body:kontonummer")); userField.sendKeys(settings.get(USER, gui)); final WebElement passwordField = driver.findElement(By.name("view:pin:border:border_body:pin")); passwordField.sendKeys(settings.get(PASSWORD, gui)); passwordField.submit();/*from ww w .j av a 2 s .c om*/ waitForPresence(driver, By.className("dbkpBoard")); final List<Integer> missingValues = new ArrayList<Integer>(); for (final WebElement possibleKeyInput : driver.findElements(By.tagName("input"))) { final String missingValuePrefix = "view:key:border:border_body:key:dbkpDisplayDiv:values:"; final String name = possibleKeyInput.getAttribute("name"); if (startsWith(name, missingValuePrefix)) { final String s = name.substring(missingValuePrefix.length(), missingValuePrefix.length() + 1); missingValues.add(Integer.parseInt(s)); } } final String code = settings.get(CODE, gui); for (final Integer missing : missingValues) { final String number = Character.toString(code.charAt(missing)); clickButton(driver, number); } clickButton(driver, "Anmelden"); waitForPresence(driver, By.partialLinkText("Post-Box")); clickLink(driver, "Post-Box"); (new WebDriverWait(driver, WAIT_TIME)) .until(ExpectedConditions.invisibilityOfElementLocated(By.id("busy"))); int newDocs = 0; int knownDocs = 0; try { final FileDownloader d = new FileDownloader(driver); for (final WebElement row : driver.findElements(By.tagName("tbody"))) { final DocumentInfo metadata = DocumentInfo.create(this.getId(), DocumentFormat.PDF); for (final WebElement cell : row.findElements(By.tagName("td"))) { final String text = cell.getText(); if (this.isDate(text)) { metadata.setDate(parseDate(text)); } else { metadata.addKeywords(text); } } if (!store.containsDocument(metadata)) { final WebElement link = row.findElement(By.tagName("a")); final byte[] file = d.downloadFile(link); store.storeDocument(metadata, file); newDocs++; } else { knownDocs++; } } } finally { clickLink(driver, "Log-out"); } return Pair.of(newDocs, knownDocs); }
From source file:com.act.lcms.db.analysis.IonSearchAnalysis.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w w w. j av a 2 s . c o m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } Double fontScale = null; if (cl.hasOption("font-scale")) { try { fontScale = Double.parseDouble(cl.getOptionValue("font-scale")); } catch (IllegalArgumentException e) { System.err.format("Argument for font-scale must be a floating point number.\n"); System.exit(1); } } try (DB db = DB.openDBFromCLI(cl)) { Set<String> includeIons = null; if (cl.hasOption("include-ions")) { String[] ionNames = cl.getOptionValues("include-ions"); includeIons = new HashSet<>(Arrays.asList(ionNames)); System.out.format("Including ions in search: %s\n", StringUtils.join(includeIons, ", ")); } Set<String> excludeIons = null; if (cl.hasOption("exclude-ions")) { String[] ionNames = cl.getOptionValues("exclude-ions"); excludeIons = new HashSet<>(Arrays.asList(ionNames)); System.out.format("Excluding ions from search: %s\n", StringUtils.join(excludeIons, ", ")); } Set<Integer> takeSamplesFromPlateIds = null; if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) { String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE); System.out.format("Considering only sample wells in plates: %s\n", StringUtils.join(plateBarcodes, ", ")); takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length); for (String plateBarcode : plateBarcodes) { Plate p = Plate.getPlateByBarcode(db, plateBarcode); if (p == null) { System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode); } else { takeSamplesFromPlateIds.add(p.getId()); } } // Allow filtering on barcode even if we couldn't find any in the DB. } System.out.format("Loading/updating LCMS scan files into DB\n"); ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); System.out.format("Processing LCMS scans\n"); Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCTS), takeSamplesFromPlateIds, false); List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft(); if (positiveWells.size() == 0) { throw new RuntimeException("Found no LCMS wells for specified strains/constructs"); } // Only take negative samples from the plates where we found the positive samples. Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS), positiveWellsAndPlateIds.getRight(), true); List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft(); if (negativeWells == null || negativeWells.size() == 0) { System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n"); } // Extract the reference MZ that will be used in the LCMS trace processing. List<Pair<String, Double>> searchMZs = null; Set<CuratedChemical> standardChemicals = null; List<ChemicalAssociatedWithPathway> pathwayChems = null; if (cl.hasOption(OPTION_SEARCH_MZ)) { // Assume mz can be an FP number of a chemical name. String massStr = cl.getOptionValue(OPTION_SEARCH_MZ); Pair<String, Double> searchMZ = Utils.extractMassFromString(db, massStr); if (searchMZ != null) { searchMZs = Collections.singletonList(searchMZ); } standardChemicals = Utils.extractTargetsForWells(db, positiveWells); } else { CuratedChemical targetChemical = Utils.requireOneTarget(db, positiveWells); if (targetChemical == null) { throw new RuntimeException( "Unable to find a curated chemical entry for specified strains'/constructs' targets. " + "Please specify a chemical name or m/z explicitly or update the curated chemicals list in the DB."); } System.out.format("Using reference M/Z for positive target %s (%f)\n", targetChemical.getName(), targetChemical.getMass()); searchMZs = Collections.singletonList(Pair.of(targetChemical.getName(), targetChemical.getMass())); standardChemicals = Collections.singleton(targetChemical); } // Look up the standard by name, or use the target if none is specified. List<StandardWell> standardWells = null; if (cl.hasOption(OPTION_NO_STANDARD)) { System.err.format("WARNING: skipping standard comparison (no-standard option specified)\n"); standardWells = new ArrayList<>(0); } else if (cl.hasOption(OPTION_STANDARD_WELLS)) { String[] standardCoordinates = cl.getOptionValues(OPTION_STANDARD_WELLS); standardWells = new ArrayList<>(standardCoordinates.length); Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE)); List<String> foundCoordinates = new ArrayList<>(standardCoordinates.length); for (String stringCoords : standardCoordinates) { Pair<Integer, Integer> coords = Utils.parsePlateCoordinates(stringCoords); StandardWell well = StandardWell.getInstance().getStandardWellsByPlateIdAndCoordinates(db, standardPlate.getId(), coords.getLeft(), coords.getRight()); if (well == null) { System.err.format("Unable to find standard well at %s [%s]\n", standardPlate.getBarcode(), stringCoords); continue; } standardWells.add(well); foundCoordinates.add(stringCoords); } System.out.format("Using explicitly specified standard wells %s [%s]\n", standardPlate.getBarcode(), StringUtils.join(foundCoordinates, ", ")); } else if (cl.hasOption(OPTION_STANDARD_NAME)) { String standardName = cl.getOptionValue(OPTION_STANDARD_NAME); System.out.format("Using explicitly specified standard %s\n", standardName); standardWells = Collections.singletonList(Utils.extractStandardWellFromPlate(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName)); } else if (standardChemicals != null && standardChemicals.size() > 0) { // Default to using the target chemical(s) as a standard if none is specified. standardWells = new ArrayList<>(standardChemicals.size()); for (CuratedChemical c : standardChemicals) { String standardName = c.getName(); System.out.format("Searching for well containing standard %s\n", standardName); standardWells.add(Utils.extractStandardWellFromPlate(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName)); } } boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz"); boolean useSNR = cl.hasOption(OPTION_USE_SNR); /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be * iterated over for graph writing. */ HashMap<Integer, Plate> plateCache = new HashMap<>(); Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); String fmt = "pdf"; String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt; String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data"; System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg); produceLCMSSearchPlots(lcmsDir, outData, outImg, allStandardScans, allPositiveScans, allNegativeScans, fontScale, useFineGrainedMZ, cl.hasOption(OPTION_USE_HEATMAP), useSNR); } }
From source file:net.lldp.checksims.algorithm.AlgorithmRunnerTest.java
@Test public void TestRunAlgorithmThreePairs() throws ChecksimsException { Set<Pair<Submission, Submission>> submissions = setFromElements(Pair.of(a, b), Pair.of(a, c), Pair.of(b, c));/*from www . j a va 2 s. co m*/ Collection<AlgorithmResults> results = AlgorithmRunner.runAlgorithm(submissions, detectNothing, logger); AlgorithmUtils.checkResultsContainsPairs(results, submissions); }
From source file:it.polimi.diceH2020.SPACE4CloudWS.solvers.solversImpl.QNSolver.QNSolver.java
@Override protected Pair<Double, Boolean> run(Pair<List<File>, List<File>> pFiles, String remoteName, String remoteDirectory) throws Exception { File jmtFile = pFiles.getLeft().stream().filter(s -> s.getName().contains(".jsimg")).findFirst().get(); String jmtFileName = jmtFile.getName(); String remotePath = remoteDirectory + File.separator + jmtFileName; boolean stillNotOk = true; for (int i = 0; stillNotOk && i < MAX_ITERATIONS; ++i) { logger.info(remoteName + "-> Starting Queuing Net resolution on the server"); cleanRemoteSubDirectory(remoteDirectory); sendFiles(remoteDirectory, pFiles.getLeft()); sendFiles(remoteDirectory, pFiles.getRight()); logger.debug(remoteName + "-> Working files sent"); String command = connSettings.getMaxDuration() == Integer.MIN_VALUE ? String.format("java -cp %s jmt.commandline.Jmt sim %s ", connSettings.getSolverPath(), remotePath)/* w ww . j a v a2s. co m*/ : String.format("java -cp %s jmt.commandline.Jmt sim %s -maxtime %d", connSettings.getSolverPath(), remotePath, connSettings.getMaxDuration()); logger.debug(remoteName + "-> Starting JMT model..."); List<String> remoteMsg = connector.exec(command, getClass()); if (remoteMsg.contains("exit-status: 0")) { stillNotOk = false; logger.info(remoteName + "-> The remote optimization process completed correctly"); } else { logger.debug(remoteName + "-> Remote exit status: " + remoteMsg); } } if (stillNotOk) { logger.info(remoteName + "-> Error in remote optimization"); throw new Exception("Error in the QN server"); } else { File solFile = fileUtility.provideTemporaryFile(jmtFileName + "-result", ".jsim"); connector.receiveFile(solFile.getAbsolutePath(), remotePath + "-result" + ".jsim", getClass()); SolutionsWrapper resultObject = SolutionsWrapper.unMarshal(solFile); if (fileUtility.delete(solFile)) logger.debug(solFile + " deleted"); Double throughput = resultObject.getMeanValue(); /* This is a workaround for the crazy behavior of the PNML transformation * that converts milliseconds to seconds. * Here we turn hertz into kilohertz to obtain results consistent * with our input. */ if (usingInputModel) throughput /= 1000; boolean failure = resultObject.isFailed(); return Pair.of(throughput, failure); } }
From source file:com.twitter.distributedlog.subscription.ZKSubscriptionsStore.java
private void getLastCommitPositions(final Promise<Map<String, DLSN>> result, List<String> subscribers) { List<Future<Pair<String, DLSN>>> futures = new ArrayList<Future<Pair<String, DLSN>>>(subscribers.size()); for (String s : subscribers) { final String subscriber = s; Future<Pair<String, DLSN>> future = // Get the last commit position from zookeeper getSubscriber(subscriber).getLastCommitPositionFromZK() .map(new AbstractFunction1<DLSN, Pair<String, DLSN>>() { @Override public Pair<String, DLSN> apply(DLSN dlsn) { return Pair.of(subscriber, dlsn); }/*from w w w . ja va 2s . co m*/ }); futures.add(future); } Future.collect(futures).foreach(new AbstractFunction1<List<Pair<String, DLSN>>, BoxedUnit>() { @Override public BoxedUnit apply(List<Pair<String, DLSN>> subscriptions) { Map<String, DLSN> subscriptionMap = new HashMap<String, DLSN>(); for (Pair<String, DLSN> pair : subscriptions) { subscriptionMap.put(pair.getLeft(), pair.getRight()); } result.setValue(subscriptionMap); return BoxedUnit.UNIT; } }); }
From source file:com.yahoo.elide.extensions.JsonApiPatch.java
/** * Process json patch actions./*from w w w . j a v a 2 s . c o m*/ * * @return Pair (return code, JsonNode) */ private Supplier<Pair<Integer, JsonNode>> processActions(PatchRequestScope requestScope) { try { List<Supplier<Pair<Integer, JsonNode>>> results = handleActions(requestScope); postProcessRelationships(requestScope); // Avoid any lazy loading issues results.forEach(Supplier::get); return () -> { try { return Pair.of(HttpStatus.SC_OK, mergeResponse(results)); } catch (HttpStatusException e) { return buildErrorResponse(e, requestScope.getSecurityMode()); } }; } catch (HttpStatusException e) { return () -> buildErrorResponse(e, requestScope.getSecurityMode()); } }