Example usage for com.google.common.collect Range upperEndpoint

List of usage examples for com.google.common.collect Range upperEndpoint

Introduction

In this page you can find the example usage for com.google.common.collect Range upperEndpoint.

Prototype

public C upperEndpoint() 

Source Link

Document

Returns the upper endpoint of this range.

Usage

From source file:edu.mit.streamjit.impl.compiler2.DescendingShareAllocationStrategy.java

@Override
public void allocateGroup(ActorGroup group, Range<Integer> iterations, List<Core> cores, Configuration config) {
    List<Float> shares = new ArrayList<>(cores.size());
    for (int core = 0; core < cores.size(); ++core) {
        String name = String.format("node%dcore%diter", group.id(), core);
        Configuration.FloatParameter parameter = config.getParameter(name, Configuration.FloatParameter.class);
        if (parameter == null)
            shares.add(0f);/*  www.j a v  a2  s. c o  m*/
        else
            shares.add(parameter.getValue());
    }

    assert iterations.lowerBoundType() == BoundType.CLOSED && iterations.upperBoundType() == BoundType.OPEN;
    int totalAvailable = iterations.upperEndpoint() - iterations.lowerEndpoint();
    while (!iterations.isEmpty()) {
        int max = CollectionUtils.maxIndex(shares);
        float share = shares.get(max);
        if (share == 0)
            break;
        int amount = DoubleMath.roundToInt(share * totalAvailable, RoundingMode.HALF_EVEN);
        int done = iterations.lowerEndpoint();
        Range<Integer> allocation = group.isStateful() ? iterations
                : iterations.intersection(Range.closedOpen(done, done + amount));
        cores.get(max).allocate(group, allocation);
        iterations = Range.closedOpen(allocation.upperEndpoint(), iterations.upperEndpoint());
        shares.set(max, 0f); //don't allocate to this core again
    }

    //If we have iterations left over not assigned to a core, spread them
    //evenly over all cores.
    if (!iterations.isEmpty()) {
        int perCore = IntMath.divide(iterations.upperEndpoint() - iterations.lowerEndpoint(), cores.size(),
                RoundingMode.CEILING);
        for (int i = 0; i < cores.size() && !iterations.isEmpty(); ++i) {
            int min = iterations.lowerEndpoint();
            Range<Integer> allocation = group.isStateful() ? iterations
                    : iterations.intersection(Range.closedOpen(min, min + perCore));
            cores.get(i).allocate(group, allocation);
            iterations = Range.closedOpen(allocation.upperEndpoint(), iterations.upperEndpoint());
        }
    }
    assert iterations.isEmpty();
}

From source file:org.pshdl.model.validation.builtin.BuiltInValidator.java

/**
 *
 * @param accessRange//from  w w  w .j  a  v  a 2 s. c om
 *            the range in which the array/bits can be acccessed
 * @param indexRange
 *            the range of the size that array size/ width of the type can
 *            be in
 * @param problems
 *            problems will be added here
 * @param arr
 *            the accessing {@link HDLExpression}
 * @param ref
 *            the reference that is accessed
 * @param bit
 *            when true bit access errors will be reported
 */
private static void checkAccessBoundaries(Range<BigInteger> accessRange, Range<BigInteger> declaredRange,
        Set<Problem> problems, IHDLObject arr, HDLVariableRef ref, boolean bit) {
    // Reduce the declaredRange to the index limits
    Range<BigInteger> indexRange;
    if (declaredRange.hasUpperBound()) {
        final BigInteger upperEndpoint = declaredRange.upperEndpoint();
        final BigInteger subtract = upperEndpoint.subtract(BigInteger.ONE);
        if (subtract.compareTo(BigInteger.ZERO) < 0)
            // Maybe generate a warning here?
            return;
        indexRange = RangeTool.createRange(BigInteger.ZERO, subtract);
    } else {
        indexRange = Range.atLeast(BigInteger.ZERO);
    }
    final String info = "Expected value range:" + indexRange;
    // Check if highest idx is negative (Definitely a problem)
    if (accessRange.hasUpperBound() && (accessRange.upperEndpoint().signum() < 0)) {
        problems.add(new Problem(bit ? BIT_ACCESS_NEGATIVE : ARRAY_INDEX_NEGATIVE, arr, ref, info)
                .addMeta(ACCESS_RANGE, accessRange).addMeta(ARRAY_RANGE, indexRange));
        // Check if lowest idx is negative (Might be a problem)
    } else if (accessRange.hasLowerBound() && (accessRange.lowerEndpoint().signum() < 0)) {
        problems.add(
                new Problem(bit ? BIT_ACCESS_POSSIBLY_NEGATIVE : ARRAY_INDEX_POSSIBLY_NEGATIVE, arr, ref, info)
                        .addMeta(ACCESS_RANGE, accessRange).addMeta(ARRAY_RANGE, indexRange));
    }
    // Check whether the index and the access have at least something in
    // common (index 0..5 access 7..9)
    if (!indexRange.isConnected(accessRange)) {
        problems.add(new Problem(bit ? BIT_ACCESS_OUT_OF_BOUNDS : ARRAY_INDEX_OUT_OF_BOUNDS, arr, ref, info)
                .addMeta(ACCESS_RANGE, accessRange).addMeta(ARRAY_RANGE, indexRange));
    } else if (accessRange.hasUpperBound() && indexRange.hasUpperBound()
            && (accessRange.upperEndpoint().compareTo(indexRange.upperEndpoint()) > 0)) {
        problems.add(new Problem(bit ? BIT_ACCESS_POSSIBLY_OUT_OF_BOUNDS : ARRAY_INDEX_POSSIBLY_OUT_OF_BOUNDS,
                arr, ref, info).addMeta(ACCESS_RANGE, accessRange).addMeta(ARRAY_RANGE, indexRange));
    }
}

From source file:org.gbif.occurrence.download.service.HiveQueryVisitor.java

/**
 * Converts date range into a conjunction predicate with the form: field >= range.lower AND field <= range.upper.
 *
 * *//*from ww w .  ja  v  a 2 s.c  o m*/
private CompoundPredicate toDateRangePredicate(Range<Date> range, OccurrenceSearchParameter key) {
    ImmutableList<Predicate> predicates = new ImmutableList.Builder<Predicate>()
            .add(new GreaterThanOrEqualsPredicate(key,
                    IsoDateFormat.FULL.getDateFormat().format(range.lowerEndpoint().getTime())))
            .add(new LessThanOrEqualsPredicate(key,
                    IsoDateFormat.FULL.getDateFormat().format(range.upperEndpoint())))
            .build();
    return new ConjunctionPredicate(predicates);
}

From source file:com.yahoo.gondola.container.RoutingFilter.java

private long getRequestCount(Range<Integer> splitRange) {
    long requestCount = 0;
    for (int i = splitRange.lowerEndpoint(); i <= splitRange.upperEndpoint(); i++) {
        if (bucketRequestCounters.containsKey(i)) {
            requestCount += bucketRequestCounters.get(i).get();
        }/*from ww w . j ava2 s .  c o m*/
    }
    return requestCount;
}

From source file:net.sf.mzmine.modules.visualization.twod.TwoDDataSet.java

private double upperEndpointIntensity(DataPoint dataPoints[], Range<Double> mzRange, PlotMode plotMode) {

    double maxIntensity = 0;

    DataPoint searchMZ = new SimpleDataPoint(mzRange.lowerEndpoint(), 0);
    int startMZIndex = Arrays.binarySearch(dataPoints, searchMZ,
            new DataPointSorter(SortingProperty.MZ, SortingDirection.Ascending));
    if (startMZIndex < 0)
        startMZIndex = (startMZIndex * -1) - 1;

    if (startMZIndex >= dataPoints.length)
        return 0;

    if (dataPoints[startMZIndex].getMZ() > mzRange.upperEndpoint()) {
        if (plotMode != PlotMode.CENTROID) {
            if (startMZIndex == 0)
                return 0;
            if (startMZIndex == dataPoints.length - 1)
                return dataPoints[startMZIndex - 1].getIntensity();

            // find which data point is closer
            double diffNext = dataPoints[startMZIndex].getMZ() - mzRange.upperEndpoint();
            double diffPrev = mzRange.lowerEndpoint() - dataPoints[startMZIndex - 1].getMZ();

            if (diffPrev < diffNext)
                return dataPoints[startMZIndex - 1].getIntensity();
            else//  w w  w .  j  a  v a  2s  . com
                return dataPoints[startMZIndex].getIntensity();
        } else {
            return 0;
        }

    }

    for (int mzIndex = startMZIndex; ((mzIndex < dataPoints.length)
            && (dataPoints[mzIndex].getMZ() <= mzRange.upperEndpoint())); mzIndex++) {
        if (dataPoints[mzIndex].getIntensity() > maxIntensity)
            maxIntensity = dataPoints[mzIndex].getIntensity();
    }

    return maxIntensity;

}

From source file:com.google.googlejavaformat.java.JavaInput.java

public RangeSet<Integer> characterRangesToTokenRanges(Collection<Range<Integer>> characterRanges)
        throws FormatterException {
    RangeSet<Integer> tokenRangeSet = TreeRangeSet.create();
    for (Range<Integer> characterRange0 : characterRanges) {
        Range<Integer> characterRange = characterRange0.canonical(DiscreteDomain.integers());
        tokenRangeSet.add(characterRangeToTokenRange(characterRange.lowerEndpoint(),
                characterRange.upperEndpoint() - characterRange.lowerEndpoint()));
    }/*  ww  w.  ja  va2 s .  com*/
    return tokenRangeSet;
}

From source file:com.wealdtech.jackson.modules.DateTimeRangeSerializer.java

@Override
public void serialize(final Range<DateTime> value, final JsonGenerator gen, final SerializerProvider provider)
        throws IOException {
    if (value != null) {
        final StringBuilder sb = new StringBuilder(64);
        if (value.hasLowerBound()) {
            if (value.lowerBoundType().equals(BoundType.CLOSED)) {
                sb.append('[');
            } else {
                sb.append('(');
            }/*from  ww w. j  a va 2 s  .  com*/
            sb.append(formatter.print(value.lowerEndpoint()));
        } else {
            sb.append('(');
            sb.append(NEGATIVE_INFINITY);
        }
        sb.append(',');

        if (value.hasUpperBound()) {
            sb.append(formatter.print(value.upperEndpoint()));
            if (value.upperBoundType().equals(BoundType.CLOSED)) {
                sb.append(']');
            } else {
                sb.append(')');
            }
        } else {
            sb.append(POSITIVE_INFINITY);
            sb.append(')');
        }

        gen.writeString(sb.toString());
    }
}

From source file:org.eclipse.fx.ui.controls.styledtext.skin.StyledTextSkin.java

public void scrollOffsetIntoView(int offset, int verticalOffset, int horizontalOffset) {
    if (offset >= 0) {
        int lineIdx = getSkinnable().getContent().getLineAtOffset(offset);
        Range<Integer> visibleLines = this.content.getVisibleLines();
        if (!visibleLines.contains(Integer.valueOf(lineIdx))) {
            int linesVisible = visibleLines.upperEndpoint().intValue()
                    - visibleLines.lowerEndpoint().intValue();
            int delta = linesVisible - verticalOffset;
            int scrollLine = Math.min(lineIdx + delta, getSkinnable().getContent().getLineCount() - 1);
            scrollLineIntoView(scrollLine);
        }/* w ww .  jav  a 2s . c  om*/

        int colIdx = offset - getSkinnable().getContent().getOffsetAtLine(lineIdx);
        String line = getSkinnable().getContent().getLine(lineIdx).substring(0, colIdx);
        int tabCount = (int) line.chars().filter(c -> c == '\t').count();
        scrollColumnIntoView(colIdx + tabCount * (getSkinnable().tabAvanceProperty().get() - 1),
                horizontalOffset);
    } else {
        scrollLineIntoView(0);
        scrollColumnIntoView(0, 0);
    }
}

From source file:net.sf.mzmine.modules.visualization.histogram.HistogramPlotDataset.java

public HistogramPlotDataset(PeakList peakList, RawDataFile[] rawDataFiles, int numOfBins,
        HistogramDataType dataType, Range<Double> range) {

    this.list = new Vector<HashMap<?, ?>>();
    this.type = HistogramType.FREQUENCY;
    this.dataType = dataType;
    this.peakList = peakList;
    this.numOfBins = numOfBins;
    this.rawDataFiles = rawDataFiles;

    minimum = range.lowerEndpoint();//from  w w w. java  2  s. c o m
    maximum = range.upperEndpoint();

    updateHistogramDataset();

}

From source file:org.noroomattheinn.timeseries.PersistentTS.java

@Override
public final synchronized void streamRows(Range<Long> period, RowCollector collector) {
    double accumulator[] = new double[schema.nColumns];
    if (period == null)
        period = Range.all();/*ww  w .j a  v a2  s.  c o  m*/
    long fromTime = period.hasLowerBound() ? period.lowerEndpoint() : 0L;
    long toTime = period.hasUpperBound() ? period.upperEndpoint() : Long.MAX_VALUE;
    long prevTime = 0;
    BufferedReader rdr = null;
    try {
        rdr = repo.getReader();
        String line;
        while ((line = rdr.readLine()) != null) {
            if (line.startsWith("#")) {
                continue;
            }
            String[] tokens = line.split("\t");

            // The first entry on the line is the time in delta format
            Long time = longValue(tokens[0]);
            if (time == null) {
                continue;
            } // Invalid format, ignore this line
            time = time < 0 ? -time : time + prevTime;
            prevTime = time; // Keep a running tally of the current time

            time = inflate(time);
            if (time < fromTime)
                continue; // Out of range, ignore & move on
            if (time > toTime)
                break; // Out of range, ignore & stop

            Row row = new Row(time, 0L, schema.nColumns);

            // The second element is a bitvector corresponding to which
            // columns have values on this line
            Long bitVector = longValue("0x" + tokens[1]);
            if (bitVector == null) {
                continue;
            } // Invalid format, Ignore this line
            row.bitVector = bitVector;

            // The remaining entries are readings. There is one reading for
            // each 1 bit in the bitvector. The positions in the bitvector
            // correspond to the columns in the order initially specified
            long bit = 1;
            int tokenIndex = 2;
            for (int i = 0; i < schema.nColumns; i++) {
                row.values[i] = accumulator[i]; // Start off with the previous value
                if (row.includes(bit)) {
                    String valString = tokens[tokenIndex++];
                    switch (valString) {
                    case "*":
                        break;
                    case "!":
                        row.clear(bit);
                        break;
                    default:
                        Double val = doubleValue(valString);
                        if (val == null) {
                            row.clear(bit);
                        } else {
                            accumulator[i] = row.values[i] = val.doubleValue();
                        }
                        break;
                    }
                } else {
                    row.values[i] = accumulator[i];
                }
                bit = bit << 1;
            }
            if (!collector.collect(row))
                break;
        }
    } catch (IOException ex) {
        logger.severe("Error loading from repository" + ex);
    }
    if (rdr != null)
        try {
            rdr.close();
        } catch (IOException e) {
            logger.warning("Failure closing reader: " + e);
        }
}