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

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

Introduction

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

Prototype

public static <L, R> Pair<L, R> of(final L left, final R right) 

Source Link

Document

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.

Usage

From source file:com.act.lcms.AnimateNetCDFAroundMass.java

private List<XYZ> getSpectraInWindow(List<XYZ> spectra, Double time, Double tWin, Double mz, Double mzWin) {

    // tWin and mzWin are half windows around time and mz, respectively
    // Range of mz is ( mz - mzWin, mz + mzWin )
    // Range of time is ( time - timeWin, time + timeWin )

    double mzLow = mz - mzWin;
    double mzHigh = mz + mzWin;
    double timeLow = time - tWin;
    double timeHigh = time + tWin;

    Map<Pair<Long, Long>, List<Double>> gridVals = new HashMap<>();
    // initialize the grid to empty intensity data points 
    for (long i = 0; i <= gridSize; i++) {
        for (long j = 0; j <= gridSize; j++) {
            gridVals.put(Pair.of(i, j), new ArrayList<>());
        }/*from  w  ww  . j a va  2s . c om*/
    }

    // what is the step size between x -> x+1 and y -> y+1
    double timeStep = (2 * tWin) / gridSize;
    double mzStep = (2 * mzWin) / gridSize;

    // for each x,y,z find the grid position it lies in
    // (if it indeed is within the grid window we care)
    // and add that to the data points we see within
    for (XYZ xyz : spectra) {
        // ignore if outside the window
        if (xyz.mz < mzLow || xyz.mz > mzHigh)
            continue;
        if (xyz.time < timeLow || xyz.time > timeHigh)
            continue;

        // if inside the window find the grid position
        long timeGridPos = Math.round((xyz.time - timeLow) / timeStep);
        long mzGridPos = Math.round((xyz.mz - mzLow) / mzStep);
        Pair<Long, Long> xy = Pair.of(timeGridPos, mzGridPos);

        gridVals.get(xy).add(xyz.intensity);
    }

    // average out all the z values that appear at each x,y
    Map<Pair<Long, Long>, Double> gridAvg = new HashMap<>();
    for (Pair<Long, Long> xy : gridVals.keySet()) {
        Double avg = 0.0;
        List<Double> intensities = gridVals.get(xy);
        for (Double intensity : intensities)
            avg += intensity;
        if (!intensities.isEmpty())
            avg /= intensities.size();
        gridAvg.put(xy, avg);
    }

    // convert back to list of x,y,z coordinates
    List<XYZ> grid = new ArrayList<>();
    for (long i = 0; i <= gridSize; i++) {
        for (long j = 0; j <= gridSize; j++) {
            Double t = timeLow + i * timeStep;
            Double m = mzLow + j * mzStep;
            Double it = gridAvg.get(Pair.of(i, j));
            grid.add(new XYZ(t, m, it));
        }
    }

    return grid;
}

From source file:edu.uci.ics.hyracks.api.client.impl.JobActivityGraphBuilder.java

@Override
public void addSourceEdge(int operatorInputIndex, IActivity task, int taskInputIndex) {
    if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.finest("Adding source edge: " + task.getActivityId() + ":" + operatorInputIndex + " -> "
                + task.getActivityId() + ":" + taskInputIndex);
    }/* w  ww.ja v  a 2  s.  c om*/
    IOperatorDescriptor op = activityOperatorMap.get(task.getActivityId());
    IConnectorDescriptor conn = jobSpec.getInputConnectorDescriptor(op, operatorInputIndex);
    insertIntoIndexedMap(jag.getActivityInputMap(), task.getActivityId(), taskInputIndex, conn);
    connectorConsumerMap.put(conn.getConnectorId(), Pair.of(task, taskInputIndex));
}

From source file:com.yahoo.bullet.tracing.FilterRuleTest.java

@Test
public void testMaximumEmittedWithNonMatchingRecords() {
    FilterRule rule = getFilterRule(makeRawFullRule("mid", Arrays.asList("1", "23"), FilterType.EQUALS,
            AggregationType.RAW, 2, Pair.of("mid", "mid")), emptyMap());
    RecordBox boxA = RecordBox.get().add("mid", "23");
    RecordBox expectedA = RecordBox.get().add("mid", "23");

    RecordBox boxB = RecordBox.get().add("mid", "42");

    Assert.assertTrue(rule.consume(boxA.getRecord()));
    Assert.assertEquals(rule.getData(), getListBytes(expectedA.getRecord()));

    Assert.assertFalse(rule.consume(boxB.getRecord()));
    Assert.assertNull(rule.getData());/*from  www.ja v  a  2s . c o m*/

    Assert.assertFalse(rule.consume(boxB.getRecord()));
    Assert.assertNull(rule.getData());

    Assert.assertTrue(rule.consume(boxA.getRecord()));
    Assert.assertEquals(rule.getData(), getListBytes(expectedA.getRecord()));

    for (int i = 0; i < 10; ++i) {
        Assert.assertFalse(rule.consume(boxA.getRecord()));
        Assert.assertNull(rule.getData());
        Assert.assertFalse(rule.consume(boxB.getRecord()));
        Assert.assertNull(rule.getData());
    }
}

From source file:com.helion3.prism.api.parameters.ParameterTime.java

@Override
public Optional<Pair<String, String>> processDefault(QuerySession session, Query query) {
    String since = Prism.getConfig().getNode("defaults", "since").getString();

    try {//from w  ww .j a v a  2  s. c  o  m
        Date date = DateUtil.parseTimeStringToDate(since, false);
        query.addCondition(FieldCondition.of(DataQueries.Created, MatchRule.GREATER_THAN_EQUAL, date));
        return Optional.of(Pair.of("since", since));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return Optional.empty();
}

From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java

public static void waitForNodeGroupConvergence(ServiceHost[] hosts, String nodeGroupPath, int maxRetries,
        int retryInterval) throws Throwable {

    checkArgument(hosts != null, "hosts cannot be null");
    checkArgument(hosts.length > 0, "hosts cannot be empty");
    checkArgument(!Strings.isNullOrEmpty(nodeGroupPath), "nodeGroupPath cannot be null or empty");
    checkArgument(maxRetries > 0, "maxRetries must be > 0");

    List<Pair<String, Integer>> remoteHostIpAndPortPairs = new ArrayList<>();
    for (ServiceHost host : hosts) {
        remoteHostIpAndPortPairs.add(Pair.of(host.getState().bindAddress, host.getPort()));
    }/*from  ww  w. j a va 2  s  . c  o m*/

    waitForNodeGroupConvergence(hosts[0], remoteHostIpAndPortPairs, nodeGroupPath, maxRetries, retryInterval);
}

From source file:cherry.foundation.bizcal.BizYearManagerImpl.java

private Pair<Integer, Range<LocalDate>> bizYearByDate(int year, LocalDate dt) {
    Range<LocalDate> range = bizYearStrategy.rangeOfBizYear(year);
    if (range.isAfter(dt)) {
        return bizYearByDate(year - 1, dt);
    }/* w  ww.  j a v  a 2 s . co  m*/
    if (range.isBefore(dt)) {
        return bizYearByDate(year + 1, dt);
    }
    return Pair.of(year, range);
}

From source file:net.malisis.doors.door.tileentity.FenceGateTileEntity.java

private Pair<BlockState, Integer> updateCamo() {
    ForgeDirection dir = getDirection() == 0 || getDirection() == 2 ? ForgeDirection.EAST
            : ForgeDirection.NORTH;//from  w ww .ja  va2  s  .  c o m
    BlockPos pos = new BlockPos(xCoord, yCoord, zCoord);

    BlockPos p = pos.offset(dir);
    FenceGateTileEntity te = TileEntityUtils.getTileEntity(FenceGateTileEntity.class, worldObj, p);
    if (te != null && isMatchingDoubleDoor(te))
        p = p.offset(dir);

    BlockState state1 = new BlockState(worldObj, p);
    int color1 = state1.getBlock().colorMultiplier(worldObj, p.getX(), p.getY(), p.getZ());
    if (state1.getBlock().isAir(worldObj, p.getX(), p.getY(), p.getZ()))
        return Pair.of(new BlockState(worldObj, pos), -1);

    dir = dir.getOpposite();
    p = pos.offset(dir);

    te = TileEntityUtils.getTileEntity(FenceGateTileEntity.class, worldObj, p);
    if (te != null && isMatchingDoubleDoor(te))
        p = p.offset(dir);

    BlockState state2 = new BlockState(worldObj, p);
    int color2 = state2.getBlock().colorMultiplier(worldObj, p.getX(), p.getY(), p.getZ());
    if (state1.getBlock().isAir(worldObj, p.getX(), p.getY(), p.getZ()))
        return Pair.of(new BlockState(worldObj, pos), -1);

    if (state1.getBlock() != state2.getBlock() || state1.getMetadata() != state2.getMetadata()
            || color1 != color2)
        return Pair.of(new BlockState(worldObj, pos), -1);

    return Pair.of(state1, color1);
}

From source file:edu.uci.ics.hyracks.api.rewriter.runtime.SuperActivity.java

@Override
public IOperatorNodePushable createPushRuntime(IHyracksTaskContext ctx,
        final IRecordDescriptorProvider recordDescProvider, final int partition, final int nPartitions)
        throws HyracksDataException {
    final Map<ActivityId, IActivity> startActivities = new HashMap<ActivityId, IActivity>();
    Map<ActivityId, IActivity> activities = getActivityMap();
    for (Entry<ActivityId, IActivity> entry : activities.entrySet()) {
        /**//from   w  w  w.j  av  a2 s . c  o  m
         * extract start activities
         */
        List<IConnectorDescriptor> conns = getActivityInputMap().get(entry.getKey());
        if (conns == null || conns.size() == 0) {
            startActivities.put(entry.getKey(), entry.getValue());
        }
    }

    /**
     * wrap a RecordDescriptorProvider for the super activity
     */
    IRecordDescriptorProvider wrappedRecDescProvider = new IRecordDescriptorProvider() {

        @Override
        public RecordDescriptor getInputRecordDescriptor(ActivityId aid, int inputIndex) {
            if (startActivities.get(aid) != null) {
                /**
                 * if the activity is a start (input boundary) activity
                 */
                int superActivityInputChannel = SuperActivity.this
                        .getClusterInputIndex(Pair.of(aid, inputIndex));
                if (superActivityInputChannel >= 0) {
                    return recordDescProvider.getInputRecordDescriptor(activityId, superActivityInputChannel);
                }
            }
            if (SuperActivity.this.getActivityMap().get(aid) != null) {
                /**
                 * if the activity is an internal activity of the super activity
                 */
                IConnectorDescriptor conn = getActivityInputMap().get(aid).get(inputIndex);
                return getConnectorRecordDescriptorMap().get(conn.getConnectorId());
            }

            /**
             * the following is for the case where the activity is in other SuperActivities
             */
            ActivityClusterGraph acg = SuperActivity.this.getActivityClusterGraph();
            for (Entry<ActivityClusterId, ActivityCluster> entry : acg.getActivityClusterMap().entrySet()) {
                ActivityCluster ac = entry.getValue();
                for (Entry<ActivityId, IActivity> saEntry : ac.getActivityMap().entrySet()) {
                    SuperActivity sa = (SuperActivity) saEntry.getValue();
                    if (sa.getActivityMap().get(aid) != null) {
                        List<IConnectorDescriptor> conns = sa.getActivityInputMap().get(aid);
                        if (conns != null && conns.size() >= inputIndex) {
                            IConnectorDescriptor conn = conns.get(inputIndex);
                            return sa.getConnectorRecordDescriptorMap().get(conn.getConnectorId());
                        } else {
                            int superActivityInputChannel = sa.getClusterInputIndex(Pair.of(aid, inputIndex));
                            if (superActivityInputChannel >= 0) {
                                return recordDescProvider.getInputRecordDescriptor(sa.getActivityId(),
                                        superActivityInputChannel);
                            }
                        }
                    }
                }
            }
            return null;
        }

        @Override
        public RecordDescriptor getOutputRecordDescriptor(ActivityId aid, int outputIndex) {
            /**
             * if the activity is an output-boundary activity
             */
            int superActivityOutputChannel = SuperActivity.this
                    .getClusterOutputIndex(Pair.of(aid, outputIndex));
            if (superActivityOutputChannel >= 0) {
                return recordDescProvider.getOutputRecordDescriptor(activityId, superActivityOutputChannel);
            }

            if (SuperActivity.this.getActivityMap().get(aid) != null) {
                /**
                 * if the activity is an internal activity of the super activity
                 */
                IConnectorDescriptor conn = getActivityOutputMap().get(aid).get(outputIndex);
                return getConnectorRecordDescriptorMap().get(conn.getConnectorId());
            }

            /**
             * the following is for the case where the activity is in other SuperActivities
             */
            ActivityClusterGraph acg = SuperActivity.this.getActivityClusterGraph();
            for (Entry<ActivityClusterId, ActivityCluster> entry : acg.getActivityClusterMap().entrySet()) {
                ActivityCluster ac = entry.getValue();
                for (Entry<ActivityId, IActivity> saEntry : ac.getActivityMap().entrySet()) {
                    SuperActivity sa = (SuperActivity) saEntry.getValue();
                    if (sa.getActivityMap().get(aid) != null) {
                        List<IConnectorDescriptor> conns = sa.getActivityOutputMap().get(aid);
                        if (conns != null && conns.size() >= outputIndex) {
                            IConnectorDescriptor conn = conns.get(outputIndex);
                            return sa.getConnectorRecordDescriptorMap().get(conn.getConnectorId());
                        } else {
                            superActivityOutputChannel = sa.getClusterOutputIndex(Pair.of(aid, outputIndex));
                            if (superActivityOutputChannel >= 0) {
                                return recordDescProvider.getOutputRecordDescriptor(sa.getActivityId(),
                                        superActivityOutputChannel);
                            }
                        }
                    }
                }
            }
            return null;
        }

    };
    return new SuperActivityOperatorNodePushable(this, startActivities, ctx, wrappedRecDescProvider, partition,
            nPartitions);
}

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

/**
 * Converts a coordinate string like 'C12' into zero-indexed row and column indices like (2, 11).
 * @param coords A coordinate string to parse.
 * @return A row and column index pair, where 'A1' is (0, 0).
 * @throws IllegalArgumentException Thrown when the coordinates can't be parsed or interpreted.
 *//*from   w  w w .  j a  v  a  2  s  . c o m*/
public static Pair<Integer, Integer> parsePlateCoordinates(String coords) throws IllegalArgumentException {
    Integer plateRow = null, plateColumn = null;
    Matcher matcher = PLATE_COORDINATES_PATTERN.matcher(coords);
    if (!matcher.matches()) {
        throw new IllegalArgumentException(String.format("Invalid plate coordinates: %s", coords));
    }

    String plateRowStr = matcher.group(1);
    plateRow = WELL_ROW_TO_INDEX.get(plateRowStr);
    if (plateRow == null) {
        throw new IllegalArgumentException(String.format(
                "Unable to handle multi-character plate row %s for coordinates %s", plateRowStr, coords));
    }
    plateColumn = Integer.parseInt(matcher.group(2)) - 1;

    return Pair.of(plateRow, plateColumn);
}

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

/**
 * This function takes in a HitOrMiss molecule and filters it based on metric thresholds.
 * @param replicate The molecule whose metric stats are being compared to the preset thresholds.
 * @return A pair of transformed HitOrMiss molecule and whether to save the result in the final model.
 *///from   ww w  .  ja  v a2 s.com
public Pair<IonAnalysisInterchangeModel.HitOrMiss, Boolean> apply(
        IonAnalysisInterchangeModel.HitOrMiss replicate) {
    Double intensity = replicate.getIntensity();
    Double snr = replicate.getSnr();
    Double time = replicate.getTime();
    String ion = replicate.getIon();

    IonAnalysisInterchangeModel.HitOrMiss molecule = new IonAnalysisInterchangeModel.HitOrMiss(
            replicate.getInchi(), ion, snr, time, intensity, replicate.getPlot());

    // If the intensity, snr and time pass the thresholds set AND the ion of the peak molecule is within the set of
    // ions we want extracted, we keep the molecule. Else, we throw it away.
    if (intensity > minIntensityThreshold && snr > minSnrThreshold && time > minTimeThreshold
            && (ions.size() == 0 || ions.contains(ion))) {
        return Pair.of(molecule, DO_NOT_THROW_OUT_MOLECULE);
    } else {
        return Pair.of(molecule, THROW_OUT_MOLECULE);
    }
}