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:com.michellemay.URLLanguageDetectorTest.java
public void validateTestCases(URLLanguageDetector detector, List<Pair<String, String>> testCases) throws Exception { List<Pair<Pair<String, String>, Optional<Locale>>> failedTests = testCases.stream() .map((test) -> Pair.of(test, detector.detect(test.getKey()))).filter((testAndResult) -> { Pair<String, String> test = testAndResult.getKey(); Optional<Locale> detectedLanguage = testAndResult.getValue(); boolean localTestFailed = (detectedLanguage.isPresent() != !test.getValue().isEmpty()); if (!localTestFailed && detectedLanguage.isPresent()) { localTestFailed = !detectedLanguage.get().equals(LocaleUtils.toLocale(test.getValue())); }/*from ww w. j av a2 s .co m*/ return localTestFailed; }).collect(Collectors.toList()); failedTests .forEach((test) -> System.out.println("FAILED: " + test.getKey() + ", FOUND: " + test.getValue())); assertTrue(failedTests.isEmpty()); }
From source file:com.addthis.hydra.data.io.DiskBackedList2.java
private Pair<Integer, Integer> indicesForElement(int elementIndex) { int chunkIndex = 0; int remaining = elementIndex; for (DBLChunk chunk : chunks) { int numEntries = chunk.getNumEntries(); if (remaining >= numEntries) { remaining -= numEntries;/*from www . j ava 2s . co m*/ chunkIndex += 1; } else { break; } } return Pair.of(chunkIndex, remaining); }
From source file:edu.sjsu.pokemonclassifier.classification.UserPreferenceInfo.java
public Map<String, Integer> getRecommendPokemon() { // API for downard module // Put all strongerCandidates to GMM model List<Pair<Integer, Double>> weightPairList = new ArrayList<>(); GaussianMixtureModel model = gmmTrainer.getModel(); for (int j = 0; j < model.getK(); j++) { weightPairList.add(Pair.of(j, model.weights()[j])); }//from w ww. j a v a 2 s . c o m Collections.sort(weightPairList, new Comparator<Pair<Integer, Double>>() { @Override public int compare(Pair<Integer, Double> o1, Pair<Integer, Double> o2) { if (o1.getValue() < o2.getKey()) return -1; else if (o1.getValue().equals(o2.getValue())) return 0; else return 1; } }); // Get top-5 // 5 is temp number // <String, Interger> -> <PokemonName, Rank#> HashMap<String, Integer> rankedPokemon = new HashMap<String, Integer>(); HashMap<Integer, String> strongerCandidatesMap = new HashMap<Integer, String>(); for (String strongerCandidate : strongerCandidates) { strongerCandidatesMap.put(strongerCandidates.indexOf(strongerCandidate), strongerCandidate); } // for (int i = 0; i < strongerCandidates.size(); i++) { // // strongerCandidatesMap.put(i, strongerCandidates.get(i).toLowerCase()); // } // modified by sidmishraw for getting top 10 pokemons rather than 5 int totalClusters = Math.min(model.getK(), 10); int rank = 1; for (int i = totalClusters - 1; i >= 0; i--) { int modelIdx = weightPairList.get(i).getKey(); double[] meanVector = model.gaussians()[modelIdx].mean().toArray(); double att = meanVector[0]; double def = meanVector[1]; double hp = meanVector[2]; double minDist = Double.MAX_VALUE; int minIdx = 0; String bestFitName = null; for (int j = 0; j < strongerCandidatesMap.size(); j++) { String name = strongerCandidatesMap.get(j); if (name == null) { continue; } //name = name.toLowerCase(); System.out.println("HARMLESS:::: name = " + name); System.out.println("HARMLESS:::: att2 = " + PokemonDict.getInstance().getAttack(name)); System.out.println("HARMLESS:::: def2 = " + PokemonDict.getInstance().getDefense(name)); System.out.println("HARMLESS:::: hp2 = " + PokemonDict.getInstance().getHP(name)); int att2 = PokemonDict.getInstance().getAttack(name); int def2 = PokemonDict.getInstance().getDefense(name); int hp2 = PokemonDict.getInstance().getHP(name); double dist = Math .sqrt((att - att2) * (att - att2) + (def - def2) * (def - def2) + (hp - hp2) * (hp - hp2)); if (dist < minDist) { minDist = dist; minIdx = j; bestFitName = name; } } strongerCandidatesMap.remove(minIdx); rankedPokemon.put(bestFitName, rank); rank++; } return rankedPokemon; }
From source file:de.tntinteractive.portalsammler.engine.SecureStore.java
private static Pair<Integer, MapReader> createMapReader(final InputStream stream, final SecureRandom srand, final byte[] key) throws IOException { final InputStream cipher = CryptoHelper.createAesDecryptStream(stream, key, srand); final int salt = readInt(cipher); final InflaterInputStream inflate = new InflaterInputStream(cipher); return Pair.of(salt, MapReader.createFrom(inflate)); }
From source file:com.act.lcms.db.io.parser.ConstructAnalysisFileParser.java
private void handleConstructProductsList(String construct, List<ConstructAssociatedChemical> products) { int step = 0; for (int i = products.size() - 1; i >= 0; i--) { products.get(i).setIndex(step);//from w ww.ja v a 2 s.c om step++; } constructProducts.add(Pair.of(construct, products)); }
From source file:com.twentyn.patentSearch.Searcher.java
private void init(List<File> indexDirectories) throws IOException { for (File indexDirectory : indexDirectories) { LOGGER.info("Opening index dir at %s", indexDirectory.getAbsolutePath()); Directory indexDir = FSDirectory.open(indexDirectory.toPath()); IndexReader indexReader = DirectoryReader.open(indexDir); IndexSearcher searcher = new IndexSearcher(indexReader); // Only add to the list if both of these calls work. indexReadersAndSearchers.add(Pair.of(indexReader, searcher)); }/* ww w .j a v a2 s .c o m*/ }
From source file:com.act.lcms.db.analysis.PathwayProductAnalysis.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. ja v a2 s.co 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<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_CONSTRUCT), 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 chemicals in the pathway and their product masses, then look up info on those chemicals List<Pair<ChemicalAssociatedWithPathway, Double>> productMasses = Utils .extractMassesForChemicalsAssociatedWithConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT)); List<Pair<String, Double>> searchMZs = new ArrayList<>(productMasses.size()); List<ChemicalAssociatedWithPathway> pathwayChems = new ArrayList<>(productMasses.size()); for (Pair<ChemicalAssociatedWithPathway, Double> productMass : productMasses) { String chemName = productMass.getLeft().getChemical(); searchMZs.add(Pair.of(chemName, productMass.getRight())); pathwayChems.add(productMass.getLeft()); } System.out.format("Searching for intermediate/side-reaction products:\n"); for (Pair<String, Double> searchMZ : searchMZs) { System.out.format(" %s: %.3f\n", searchMZ.getLeft(), searchMZ.getRight()); } // Look up the standard by name. List<StandardWell> standardWells = new ArrayList<>(); if (cl.hasOption(OPTION_STANDARD_WELLS)) { Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE)); Map<Integer, StandardWell> pathwayIdToStandardWell = extractStandardWellsFromOptionsList(db, pathwayChems, cl.getOptionValues(OPTION_STANDARD_WELLS), standardPlate); for (ChemicalAssociatedWithPathway c : pathwayChems) { // TODO: we can avoid this loop. StandardWell well = pathwayIdToStandardWell.get(c.getId()); if (well != null) { standardWells.add(well); } } } else { for (ChemicalAssociatedWithPathway c : pathwayChems) { String standardName = c.getChemical(); System.out.format("Searching for well containing standard %s\n", standardName); List<StandardWell> wells = StandardIonAnalysis.getStandardWellsForChemical(db, c.getChemical()); if (wells != null) { standardWells.addAll(wells); } } } 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. We do not need to specify granular includeIons and excludeIons since * this would not take advantage of our caching strategy which uses a list of metlin ions as an index. */ HashMap<Integer, Plate> plateCache = new HashMap<>(); Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, EMPTY_SET, EMPTY_SET, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, EMPTY_SET, EMPTY_SET, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, EMPTY_SET, EMPTY_SET, useSNR); String fmt = "pdf"; String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt; String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data"; String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".tsv"; System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg); String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR); List<ScanData<LCMSWell>> posNegWells = new ArrayList<>(); posNegWells.addAll(allPositiveScans.getLeft()); posNegWells.addAll(allNegativeScans.getLeft()); Map<Integer, String> searchIons; if (cl.hasOption(OPTION_PATHWAY_SEARCH_IONS)) { searchIons = extractPathwayStepIons(pathwayChems, cl.getOptionValues(OPTION_PATHWAY_SEARCH_IONS), cl.getOptionValue(OPTION_SEARCH_ION, "M+H")); /* This is pretty lazy, but works with the existing API. Extract all selected ions for all search masses when * performing the scan, then filter down to the desired ions for the plot at the end. * TODO: specify the masses and scans per sample rather than batching everything together. It might be slower, * but it'll be clearer to read. */ } else { // We need to make sure that the standard metlin ion we choose is consistent with the ion modes of // the given positive, negative and standard scan files. For example, we should not pick a negative // metlin ion if all our available positive control scan files are in the positive ion mode. Map<Integer, Pair<Boolean, Boolean>> ionModes = new HashMap<>(); for (ChemicalAssociatedWithPathway chemical : pathwayChems) { boolean isPositiveScanPresent = false; boolean isNegativeScanPresent = false; for (ScanData<StandardWell> scan : allStandardScans.getLeft()) { if (chemical.getChemical().equals(scan.getWell().getChemical()) && chemical.getChemical().equals(scan.getTargetChemicalName())) { if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) { isPositiveScanPresent = true; } if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) { isNegativeScanPresent = true; } } } for (ScanData<LCMSWell> scan : posNegWells) { if (chemical.getChemical().equals(scan.getWell().getChemical()) && chemical.getChemical().equals(scan.getTargetChemicalName())) { if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) { isPositiveScanPresent = true; } if (MS1.IonMode.valueOf( scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) { isNegativeScanPresent = true; } } } ionModes.put(chemical.getId(), Pair.of(isPositiveScanPresent, isNegativeScanPresent)); } // Sort in descending order of media where MeOH and Water related media are promoted to the top and // anything derived from yeast media are demoted. We do this because we want to first process the water // and meoh media before processing the yeast media since the yeast media depends on the analysis of the former. Collections.sort(standardWells, new Comparator<StandardWell>() { @Override public int compare(StandardWell o1, StandardWell o2) { if (StandardWell.doesMediaContainYeastExtract(o1.getMedia()) && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) { return 1; } else { return 0; } } }); searchIons = extractPathwayStepIonsFromStandardIonAnalysis(pathwayChems, lcmsDir, db, standardWells, plottingDirectory, ionModes); } produceLCMSPathwayHeatmaps(lcmsDir, outData, outImg, outAnalysis, pathwayChems, allStandardScans, allPositiveScans, allNegativeScans, fontScale, cl.hasOption(OPTION_USE_HEATMAP), searchIons); } }
From source file:enumj.EnumerableTest.java
@Test public void testOf_Enumeration() { System.out.println("of"); EnumerableGenerator.generatorPairs().limit(100) .map(p -> Pair.of(p.getLeft().ofEnumerationEnumerable(), p.getRight().ofEnumerationEnumerable())) .forEach(p -> assertTrue(p.getLeft().elementsEqual(p.getRight()))); }
From source file:com.github.steveash.jg2p.align.Alignment.java
public Pair<Word, Word> xyWordPair() { return Pair.of(input, Word.fromGrams(getYTokens())); }
From source file:blusunrize.immersiveengineering.client.render.IEBipedLayerRenderer.java
@Override public void doRenderLayer(EntityLivingBase living, float limbSwing, float prevLimbSwing, float partialTicks, float rotation, float yaw, float pitch, float scale) { // if(Lib.BAUBLES && living instanceof EntityPlayer) // {// ww w . jav a 2 s . c om // ItemStack belt = BaublesHelper.getBauble((EntityPlayer)living,3); // if(belt!=null && belt.getItem().equals(IEContent.itemManeuverGear)) // { // GlStateManager.pushMatrix(); // ModelBiped model = IEContent.itemManeuverGear.getArmorModel((EntityPlayer)living, belt, 2, null); // ClientUtils.bindTexture(IEContent.itemManeuverGear.getArmorTexture(belt, (EntityPlayer)living, 2, null)); // model.render(living, limbSwing, prevLimbSwing, rotation, yaw, pitch, scale); // GlStateManager.popMatrix(); // } // } if (!living.getItemStackFromSlot(EntityEquipmentSlot.HEAD).isEmpty() && ItemNBTHelper.hasKey(living.getItemStackFromSlot(EntityEquipmentSlot.HEAD), "IE:Earmuffs")) { ItemStack earmuffs = ItemNBTHelper.getItemStack(living.getItemStackFromSlot(EntityEquipmentSlot.HEAD), Lib.NBT_Earmuffs); if (!earmuffs.isEmpty()) { GlStateManager.pushMatrix(); ModelBiped model = IEContent.itemEarmuffs.getArmorModel(living, earmuffs, EntityEquipmentSlot.HEAD, null); ClientUtils.bindTexture(IEContent.itemEarmuffs.getArmorTexture(earmuffs, living, EntityEquipmentSlot.HEAD, "overlay")); model.render(living, limbSwing, prevLimbSwing, rotation, yaw, pitch, scale); int colour = ((IColouredItem) earmuffs.getItem()).getColourForIEItem(earmuffs, 0); GlStateManager.color((colour >> 16 & 255) / 255f, (colour >> 8 & 255) / 255f, (colour & 255) / 255f); ClientUtils.bindTexture( IEContent.itemEarmuffs.getArmorTexture(earmuffs, living, EntityEquipmentSlot.HEAD, null)); model.render(living, limbSwing, prevLimbSwing, rotation, yaw, pitch, scale); GlStateManager.popMatrix(); } } if (!living.getItemStackFromSlot(EntityEquipmentSlot.CHEST).isEmpty() && ItemNBTHelper.hasKey(living.getItemStackFromSlot(EntityEquipmentSlot.CHEST), "IE:Powerpack")) { ItemStack powerpack = ItemNBTHelper.getItemStack(living.getItemStackFromSlot(EntityEquipmentSlot.CHEST), Lib.NBT_Powerpack); addWornPowerpack(living, powerpack); } if (POWERPACK_PLAYERS.containsKey(living.getUniqueID())) { Pair<ItemStack, Integer> entry = POWERPACK_PLAYERS.get(living.getUniqueID()); renderPowerpack(entry.getLeft(), living, limbSwing, prevLimbSwing, partialTicks, rotation, yaw, pitch, scale); int time = entry.getValue() - 1; if (time <= 0) POWERPACK_PLAYERS.remove(living.getUniqueID()); else POWERPACK_PLAYERS.put(living.getUniqueID(), Pair.of(entry.getLeft(), time)); } }