Example usage for org.apache.commons.lang3.tuple Pair getRight

List of usage examples for org.apache.commons.lang3.tuple Pair getRight

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getRight.

Prototype

public abstract R getRight();

Source Link

Document

Gets the right element from this pair.

When treated as a key-value pair, this is the value.

Usage

From source file:Solver.java

private static void Solve(Pair<Integer, Integer[]> data, boolean searchAll) {
    int N = data.getLeft();
    Integer[] S = data.getRight();
    int nsquares = S.length;
    Store store = new Store();

    IntVar[] X = new IntVar[nsquares];
    IntVar[] Y = new IntVar[nsquares];

    IntVar[] W = new IntVar[nsquares];
    IntVar[] H = new IntVar[nsquares];

    IntVar L = new IntVar(store, N, N);

    ArrayUtils.reverse(S);// ww  w .  ja v  a 2 s  .c o m

    for (int i = 0; i < nsquares; i++) {
        X[i] = new IntVar(store, "X" + i, 0, N - S[i]);
        Y[i] = new IntVar(store, "Y" + i, 0, N - S[i]);

        W[i] = new IntVar(store, S[i], S[i]);
        H[i] = new IntVar(store, S[i], S[i]);
    }

    Constraint ctr1 = new Diff2(X, Y, W, H);
    Constraint ctr2 = new Cumulative(X, W, H, L);
    Constraint ctr3 = new Cumulative(Y, W, H, L);

    ctr1.impose(store);
    ctr2.impose(store);
    ctr3.impose(store);

    Search<IntVar> searchX = new DepthFirstSearch<IntVar>();
    Search<IntVar> searchY = new DepthFirstSearch<IntVar>();
    SelectChoicePoint<IntVar> labelX = new SimpleSelect<>(X, new SmallestMin<>(), new SmallestDomain<>(),
            new IndomainMin<>());
    SelectChoicePoint<IntVar> labelY = new SimpleSelect<>(Y, new SmallestMin<>(), new SmallestDomain<>(),
            new IndomainMin<>());
    searchY.setSelectChoicePoint(labelY);
    searchX.addChildSearch(searchY);

    if (searchAll)
        searchX.getSolutionListener().searchAll(true);

    searchX.getSolutionListener().recordSolutions(true);
    searchY.getSolutionListener().recordSolutions(true);
    searchX.setPrintInfo(false);
    searchY.setPrintInfo(false);
    searchX.labeling(store, labelX);
    for (int sid = 1; sid <= searchX.getSolutionListener().solutionsNo(); sid++) {
        SwingUtilities.invokeLater((new Solver()).new Window(sid - 1, window_size, N, searchX.getSolution(sid),
                searchY.getSolution(sid), S));
    }
}

From source file:com.cheusov.Jrep.java

private static String getLineToPrint(String line, List<Pair<Integer, Integer>> startend) {
    StringBuilder sb = new StringBuilder();
    Collections.sort(startend, new Comparator<Pair<Integer, Integer>>() {
        public int compare(Pair<Integer, Integer> a, Pair<Integer, Integer> b) {
            if (a.getLeft() < b.getLeft())
                return -1;
            if (a.getLeft() > b.getLeft())
                return 1;
            return b.getRight() - a.getRight();
        }/*from   ww w  . ja va2  s .  c o  m*/
    });

    int prev = 0;
    for (Pair<Integer, Integer> p : startend) {
        int start = p.getLeft();
        int end = p.getRight();
        if (end < prev)
            continue;
        if (start < prev)
            start = prev;
        sb.append(line.substring(prev, start));
        if (start < end) {
            sb.append(colorEscStart);
            sb.append(line.substring(start, end));
            sb.append(colorEscEnd);
        }
        prev = end;
    }

    return (sb.toString() + line.substring(prev));
}

From source file:com.twitter.graphjet.bipartite.GraphConcurrentTestHelper.java

/**
 * This helper method tests up a concurrent read-write situation with a single writer and multiple
 * readers that access the same underlying bipartiteGraph, and tests for correct edge access after
 * every single edge write via latches. This helps test write flushing after every edge insertion.
 *
 * @param graph           is the underlying
 *                        {@link BipartiteGraph}
 * @param edgesToAdd      is a list of edges to add in the graph
 *///from  www .  j a va 2  s . c om
public static <T extends BipartiteGraph & DynamicBipartiteGraph> void testConcurrentReadWriteThreads(T graph,
        List<Pair<Long, Long>> edgesToAdd) {
    int numReaders = edgesToAdd.size(); // start reading after first edge is written
    ExecutorService executor = Executors.newFixedThreadPool(2 * (2 * numReaders) + 1);

    List<CountDownLatch> readerStartLatches = Lists.newArrayListWithCapacity(numReaders);
    List<CountDownLatch> readerDoneLatches = Lists.newArrayListWithCapacity(numReaders);
    List<BipartiteGraphReader> leftReaders = Lists.newArrayListWithCapacity(numReaders);
    List<BipartiteGraphReader> rightReaders = Lists.newArrayListWithCapacity(numReaders);

    for (Pair<Long, Long> edge : edgesToAdd) {
        CountDownLatch startLatch = new CountDownLatch(1);
        CountDownLatch doneLatch = new CountDownLatch(2);
        // Each time, get edges for the node added in the previous step
        BipartiteGraphReader leftReader = new BipartiteGraphReader(graph, startLatch, doneLatch, edge.getLeft(),
                true, 0);
        BipartiteGraphReader rightReader = new BipartiteGraphReader(graph, startLatch, doneLatch,
                edge.getRight(), false, 0);
        leftReaders.add(leftReader);
        executor.submit(leftReader);
        rightReaders.add(rightReader);
        executor.submit(rightReader);
        readerStartLatches.add(startLatch);
        readerDoneLatches.add(doneLatch);
    }

    /**
     * The start/done latches achieve the following execution order: writer, then reader 1, then
     * writer, then reader 2, and so on. As a concrete example, suppose we have two readers and a
     * writer, then the start/done latches are used as follows:
     * Initial latches state:
     * s1 = 1, d1 = 1
     * s2 = 1, d2 = 1
     * Execution steps:
     * - writer writes edge 1, sets s1 = 0 and waits on d1
     * - reader 1 reads since s1 == 0 and sets d1 = 0
     * - writer writes edge 2, sets s2 = 0 and waits on d2
     * - reader 2 reads since s2 == 0 and sets d2 = 0
     *
     * One detail to note is that here we have two readers (one for left, one for right) so the done
     * latches are initialized to value 2 so that both readers complete the read before moving on.
     */
    List<WriterInfo> writerInfo = Lists.newArrayListWithCapacity(numReaders);
    for (int i = 0; i < numReaders; i++) {
        // Start writing immediately at first, but then write an edge once the reader finishes reading
        // the previous edge
        CountDownLatch startLatch = (i > 0) ? readerDoneLatches.get(i - 1) : new CountDownLatch(0);
        // Release the next reader
        CountDownLatch doneLatch = readerStartLatches.get(i);
        writerInfo.add(new WriterInfo(edgesToAdd.get(i).getLeft(), edgesToAdd.get(i).getRight(), startLatch,
                doneLatch));
    }

    executor.submit(new BipartiteGraphWriter(graph, writerInfo));

    // Wait for all the processes to finish and then confirm that they did what they worked as
    // expected
    try {
        readerDoneLatches.get(numReaders - 1).await();
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for last reader was interrupted: ", e);
    }

    // Now we test the readers
    Long2ObjectMap<LongArrayList> leftSideGraph = new Long2ObjectOpenHashMap<LongArrayList>(numReaders);
    Long2ObjectMap<LongArrayList> rightSideGraph = new Long2ObjectOpenHashMap<LongArrayList>(numReaders);
    for (int i = 0; i < numReaders; i++) {
        long leftNode = edgesToAdd.get(i).getLeft();
        long rightNode = edgesToAdd.get(i).getRight();
        // Add edges to the graph
        if (!leftSideGraph.containsKey(leftNode)) {
            leftSideGraph.put(leftNode, new LongArrayList(new long[] { rightNode }));
        } else {
            leftSideGraph.get(leftNode).add(rightNode);
        }
        if (!rightSideGraph.containsKey(rightNode)) {
            rightSideGraph.put(rightNode, new LongArrayList(new long[] { leftNode }));
        } else {
            rightSideGraph.get(rightNode).add(leftNode);
        }
        // Check the read info
        assertEquals(leftSideGraph.get(leftNode).size(), leftReaders.get(i).getQueryNodeDegree());
        assertEquals(leftSideGraph.get(leftNode), leftReaders.get(i).getQueryNodeEdges());
        assertEquals(rightSideGraph.get(rightNode).size(), rightReaders.get(i).getQueryNodeDegree());
        assertEquals(rightSideGraph.get(rightNode), rightReaders.get(i).getQueryNodeEdges());
    }
}

From source file:com.act.lcms.db.analysis.AnalysisHelper.java

/**
 * Process a list of wells (LCMS or Standard), producing a list of scan objects that encapsulate the plate,
 * scan file, and masses for that well./*from  ww  w.  j  ava2 s.c o m*/
 * @param db The DB from which to extract plate data.
 * @param lcmsDir The directory where the LCMS scans live.
 * @param searchMZs A list of target M/Zs to search for in the scans (see API for {@link MS1}.
 * @param kind The role of this well in this analysis (standard, positive sample, negative control).
 * @param plateCache A hash of Plates already accessed from the DB.
 * @param samples A list of wells to process.
 * @param useSNRForPeakIdentification If true, signal-to-noise ratio will be used for peak identification.  If not,
 *                                    peaks will be identified by intensity.
 * @param <T> The PlateWell type whose scans to process.
 * @return A list of ScanData objects that wraps the objects required to produce a graph for each specified well.
 * @throws Exception
 */
public static <T extends PlateWell<T>> Pair<List<ScanData<T>>, Double> processScans(DB db, File lcmsDir,
        List<Pair<String, Double>> searchMZs, ScanData.KIND kind, HashMap<Integer, Plate> plateCache,
        List<T> samples, boolean useFineGrainedMZTolerance, Set<String> includeIons, Set<String> excludeIons,
        boolean useSNRForPeakIdentification) throws Exception {
    Double maxIntensity = 0.0d;
    List<ScanData<T>> allScans = new ArrayList<>(samples.size());
    for (T well : samples) {
        // The foreign key constraint on wells ensure that plate will be non-null.
        Plate plate = plateCache.get(well.getPlateId());
        if (plate == null) {
            plate = Plate.getPlateById(db, well.getPlateId());
            plateCache.put(plate.getId(), plate);
        }

        LOGGER.info("Processing LCMS well %s %s", plate.getBarcode(), well.getCoordinatesString());

        List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, well.getPlateId(),
                well.getPlateRow(), well.getPlateColumn());
        if (scanFiles == null || scanFiles.size() == 0) {
            LOGGER.error("WARNING: No scan files available for %s %s", plate.getBarcode(),
                    well.getCoordinatesString());
            continue;
        }

        for (ScanFile sf : scanFiles) {
            if (sf.getFileType() != ScanFile.SCAN_FILE_TYPE.NC) {
                // TODO: Migrate sysem.err to LOGGER framework
                LOGGER.error("Skipping scan file with non-NetCDF format: %s", sf.getFilename());
                continue;
            }
            File localScanFile = new File(lcmsDir, sf.getFilename());
            if (!localScanFile.exists() && localScanFile.isFile()) {
                LOGGER.error("WARNING: could not find regular file at expected path: %s",
                        localScanFile.getAbsolutePath());
                continue;
            }

            MS1 mm = new MS1(useFineGrainedMZTolerance, useSNRForPeakIdentification);
            for (Pair<String, Double> searchMZ : searchMZs) {
                MS1.IonMode mode = MS1.IonMode.valueOf(sf.getMode().toString().toUpperCase());
                Map<String, Double> allMasses = mm.getIonMasses(searchMZ.getRight(), mode);
                Map<String, Double> metlinMasses = Utils.filterMasses(allMasses, includeIons, excludeIons);

                MS1ScanForWellAndMassCharge ms1ScanResults;

                List<ChemicalOfInterest> chemicalsOfInterest = ChemicalOfInterest.getInstance()
                        .getChemicalOfInterestByName(db, searchMZ.getLeft());

                // Check if in the input chemical is valid
                if (chemicalsOfInterest == null || chemicalsOfInterest.size() == 0) {
                    MS1 ms1 = new MS1();
                    ms1ScanResults = ms1.getMS1(metlinMasses, localScanFile.getAbsolutePath());
                } else {
                    MS1ScanForWellAndMassCharge ms1ScanResultsCache = new MS1ScanForWellAndMassCharge();
                    ms1ScanResults = ms1ScanResultsCache.getByPlateIdPlateRowPlateColUseSnrScanFileChemical(db,
                            plate, well, true, sf, searchMZ.getLeft(), metlinMasses, localScanFile);
                }

                maxIntensity = Math.max(ms1ScanResults.getMaxYAxis(), maxIntensity);

                LOGGER.info("Max intensity for target %s (%f) in %s is %f", searchMZ.getLeft(),
                        searchMZ.getRight(), sf.getFilename(), ms1ScanResults.getMaxYAxis());

                // TODO: purge the MS1 spectra from ms1ScanResults if this ends up hogging too much memory.
                allScans.add(new ScanData<T>(kind, plate, well, sf, searchMZ.getLeft(), metlinMasses,
                        ms1ScanResults));
            }
        }
    }
    return Pair.of(allScans, maxIntensity);
}

From source file:com.act.lcms.db.analysis.IonSearchAnalysis.java

public static void produceLCMSSearchPlots(File lcmsDir, String outData, String outImg,
        Pair<List<ScanData<StandardWell>>, Double> allStandardScans,
        Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans,
        Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans, Double fontScale, boolean useFineGrainedMZ,
        boolean makeHeatmaps, boolean useSNR) throws Exception {
    List<ScanData> allScanData = new ArrayList<ScanData>() {
        {//  w ww .  j  av a 2  s .  c o m
            addAll(allStandardScans.getLeft());
            addAll(allPositiveScans.getLeft());
            addAll(allNegativeScans.getLeft());
        }
    };
    // Get the global maximum intensity across all scans.
    Double maxIntensity = Math.max(allStandardScans.getRight(),
            Math.max(allPositiveScans.getRight(), allNegativeScans.getRight()));
    System.out.format("Processing LCMS scans for graphing:\n");
    for (ScanData scanData : allScanData) {
        System.out.format("  %s\n", scanData.toString());
    }

    String fmt = "pdf";
    System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg);

    // Generate the data file and graphs.
    try (FileOutputStream fos = new FileOutputStream(outData)) {
        // Write all the scan data out to a single data file.
        List<String> graphLabels = new ArrayList<>();
        for (ScanData scanData : allScanData) {
            graphLabels.addAll(
                    AnalysisHelper.writeScanData(fos, lcmsDir, maxIntensity, scanData, makeHeatmaps, true));
        }

        Gnuplotter plotter = fontScale == null ? new Gnuplotter() : new Gnuplotter(fontScale);
        if (makeHeatmaps) {
            plotter.plotHeatmap(outData, outImg, graphLabels.toArray(new String[graphLabels.size()]),
                    maxIntensity, fmt);
        } else {
            plotter.plot2D(outData, outImg, graphLabels.toArray(new String[graphLabels.size()]), "time",
                    maxIntensity, "intensity", fmt);
        }
    }
}

From source file:com.netflix.imfutility.itunes.audio.ChannelsMapperTest.java

private static void assertChannelEquals(Pair<SequenceUUID, Integer> channel, Integer audioSeqNum,
        Integer channelsNum) {/*  w ww . j ava  2  s. com*/
    SequenceUUID seqUuid = getSequenceUuid(audioSeqNum, SequenceType.AUDIO);

    assertEquals(seqUuid, channel.getLeft());
    assertEquals(channelsNum, channel.getRight());
}

From source file:com.act.lcms.db.analysis.AnalysisHelper.java

/**
 * This function takes a well as input, finds all the scan files associated with that well, then picks a representative
 * scan file, in this case, the first scan file which has the NC file format. It then extracts the ms1 scan results
 * corresponding to that scan file and packages it up into a ScanData container.
 * @param db - The db from which the data is extracteds
 * @param lcmsDir - The dir were scan files are present
 * @param well - The well based on which the scan file is founds
 * @param chemicalForMZValue - This is chemical from which the mz values that are needed from the ms1 analysis is extracted.
 * @param targetChemical - This is the target chemical for the analysis, ie find all chemicalForMZValue's mz variates
 *                       within targetChemical's ion profile.
 * @return ScanData - The resultant scan data.
 * @throws Exception/* w  w  w .  j  a v  a 2  s  . c o m*/
 */
public static ScanData<StandardWell> getScanDataForWell(DB db, File lcmsDir, StandardWell well,
        String chemicalForMZValue, String targetChemical) throws Exception {
    Plate plate = Plate.getPlateById(db, well.getPlateId());
    List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, well.getPlateId(),
            well.getPlateRow(), well.getPlateColumn());

    ScanFile representativeScanFile = null;

    for (ScanFile scanFile : scanFiles) {
        if (scanFile.getFileType() == ScanFile.SCAN_FILE_TYPE.NC) {
            representativeScanFile = scanFile;
            break;
        }
    }

    if (representativeScanFile == null) {
        throw new RuntimeException("None of the scan files are of the NC format");
    }

    File localScanFile = new File(lcmsDir, representativeScanFile.getFilename());
    if (!localScanFile.exists() && localScanFile.isFile()) {
        LOGGER.warn("Could not find regular file at expected path: %s", localScanFile.getAbsolutePath());
        return null;
    }

    Pair<String, Double> mzValue = Utils.extractMassFromString(db, chemicalForMZValue);
    MS1 mm = new MS1();

    // TODO: Unify these enums.
    MS1.IonMode mode = MS1.IonMode.valueOf(representativeScanFile.getMode().toString().toUpperCase());
    Map<String, Double> allMasses = mm.getIonMasses(mzValue.getRight(), mode);
    Map<String, Double> metlinMasses = Utils.filterMasses(allMasses, EMPTY_SET, EMPTY_SET);

    MS1ScanForWellAndMassCharge ms1ScanResultsCache = new MS1ScanForWellAndMassCharge();
    MS1ScanForWellAndMassCharge ms1ScanResultsForPositiveControl = ms1ScanResultsCache
            .getByPlateIdPlateRowPlateColUseSnrScanFileChemical(db, plate, well, true, representativeScanFile,
                    targetChemical, metlinMasses, localScanFile);

    ScanData<StandardWell> encapsulatedDataForPositiveControl = new ScanData<StandardWell>(
            ScanData.KIND.STANDARD, plate, well, representativeScanFile, targetChemical, metlinMasses,
            ms1ScanResultsForPositiveControl);

    return encapsulatedDataForPositiveControl;
}

From source file:hu.ppke.itk.nlpg.purepos.common.lemma.SuffixLemmaTransformation.java

@Override
protected Pair<String, Integer> encode(String word, Pair<String, Integer> representation) {
    int tagCode = representation.getRight() / SHIFT;
    int cutSize = representation.getRight() % SHIFT;
    String add = representation.getLeft();
    String lemma = word.substring(0, word.length() - cutSize) + add;
    return Pair.of(lemma, tagCode);
}

From source file:cc.kave.commons.model.groum.GroumBuilder.java

public Set<Node> getPredecessors(Node node) {
    Set<Node> predecessors = new HashSet<>();
    for (Pair<Node, Node> edge : edges) {
        if (edge.getRight() == node) {
            predecessors.add(edge.getLeft());
        }//from   w  w  w . j  a  va  2s  .  c o  m
    }
    return predecessors;
}

From source file:i5.las2peer.services.gamificationQuestService.GamificationQuestService.java

/**
 * Convert list of pair string and integer to JSON array
 * @return JSON array list of pair string and integer
 * @throws IOException IO exception// w  ww.j a v  a2s. co m
 */
private static JSONArray listPairtoJSONArray(List<Pair<String, Integer>> listpair) throws IOException {
    JSONArray arr = new JSONArray();

    if (listpair.isEmpty() || listpair.equals(null)) {
        throw new IOException("List pair is empty");
    }
    for (Pair<String, Integer> pair : listpair) {
        JSONObject obj = new JSONObject();
        obj.put("actionId", pair.getLeft());
        obj.put("times", pair.getRight());
        arr.add(obj);
    }
    return arr;
}