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

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

Introduction

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

Prototype

public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) 

Source Link

Document

Returns a range that contains all values greater than or equal to lower and less than or equal to upper .

Usage

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

/**
 * Assign buckets.//from   w w w . j ava 2  s . co m
 */
public void assignBuckets(int lowerBound, int upperBound, String fromShardId, String toShardId)
        throws InterruptedException, AdminException {
    Range range = Range.closed(lowerBound, upperBound);
    trace("[admin] Executing assign buckets={} from {} to {}", range, fromShardId, toShardId);
    for (int i = 1; i <= RETRY_COUNT; i++) {
        try {
            trace("[admin] Initializing slaves on {} ...", toShardId);
            shardManagerClient.startObserving(toShardId, fromShardId, TIMEOUT_MS * 3);

            trace("[admin] All nodes in {} are in slave mode, "
                    + "waiting for slave logs approaching to leader's log position.", toShardId);

            if (!shardManagerClient.waitSlavesApproaching(toShardId, -1)) {
                throw new ShardManagerException(SLAVE_NOT_SYNC);
            }

            trace("[admin] All nodes in {} logs approached to leader's log position, assigning buckets={} ...",
                    toShardId, range);
            // migrateBuckets is a atomic operation executing on leader at fromShard,
            // after operation is success, it will stop observing mode of toShard.
            shardManagerClient.migrateBuckets(range, fromShardId, toShardId, TIMEOUT_MS);
            trace("[admin] success!");
            trace("[admin] Writing latest config to config storage!");
            saveConfig(fromShardId, toShardId);
            break;
        } catch (ShardManagerException e) {
            logger.warn("Error occurred during assign buckets.. retrying {} / {}, errorMsg={}", i, RETRY_COUNT,
                    e.getMessage());
            try {
                shardManagerClient.stopObserving(toShardId, fromShardId, TIMEOUT_MS);
                shardManagerClient.rollbackBuckets(range);
            } catch (ShardManagerException e1) {
                logger.info("Rollback, Stop observing failed, ignoring the error. msg={}", e1.getMessage());
            }
            if (i == RETRY_COUNT) {
                logger.error("Assign bucket failed, lastError={}", e.getMessage());
                throw new AdminException(e);
            }
        }
    }
}

From source file:edu.kit.trufflehog.model.filter.IPAddressFilter.java

public IPAddressFilter(INetworkIOPort networkIOPort, final FilterInput filterInput) throws InvalidFilterRule {
    if (networkIOPort == null)
        throw new NullPointerException("networkIOPort must not be null!");

    if (filterInput == null)
        throw new NullPointerException("filterInput must not be null!");

    if (filterInput.getType() != FilterType.IP)
        throw new InvalidFilterRule(
                "The filter input contains invalid filter rules. This filter can only handle ip rules");

    this.networkIOPort = networkIOPort;
    filterColor = filterInput.getColor();
    priority = filterInput.getPriority();
    name = filterInput.getName();/*from  w w w.ja v a2s . co  m*/

    final List<String> rules = filterInput.getRules();

    if (rules == null) {
        throw new NullPointerException("the rules list in filterInput must not be null!");
    }

    for (String rule : rules) {
        if (!rule.matches(
                "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\/(([1-2][0-9])|([1-9])|(3[0-2])))?$")) {
            throw new InvalidFilterRule("IP address doesn't have the correct format!");
        }

        if (rule.matches(
                "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")) {
            final String[] parts = rule.split("\\.");

            try {
                addresses.add(Range.singleton(new IPAddress(parseIP(parts))));
            } catch (InvalidIPAddress invalidIPAddress) {
                // nothing to do here because the ip address has to be valid due to the regex above.
            }
        } else {
            final String[] masks = rule.split("/");
            final String[] parts = masks[0].split("\\.");
            final long ip = parseIP(parts);
            final long subnetMaskCount = Integer.parseInt(masks[1]);

            final long deviceMask = (1 << (32 - subnetMaskCount)) - 1;
            final long subnetMask = ((long) ((1 << subnetMaskCount) - 1)) << (32 - subnetMaskCount);
            final long from = ip & subnetMask;
            final long to = ip | deviceMask;

            try {
                addresses.add(Range.closed(new IPAddress(from), new IPAddress(to)));
            } catch (InvalidIPAddress invalidIPAddress) {
                // this should never happen but just in case notify user
                invalidIPAddress.printStackTrace();
                throw new InvalidFilterRule(
                        "IP address doesn't have the correct format or a parsing error occurred!");
            }
        }
    }
}

From source file:jetbrains.jetpad.projectional.view.EllipseView.java

@Override
public boolean contains(Vector loc) {
    Vector r = radius().get();/*w w  w. j ava  2 s  . co m*/
    Vector nl = loc.sub(center().get());
    double eps = 0.001;
    if (nl.length() <= eps)
        return true;

    double a = r.x;
    double b = r.y;
    double x = nl.x;
    double y = nl.y;

    if (b * b * x * x + a * a * y * y > a * a * b * b)
        return false;

    double phi = -Math.atan2(nl.y, nl.x);
    double from = from().get();
    double to = to().get();
    for (int i = -1; i <= 1; i++) {
        double lower = from + 2 * Math.PI * i;
        double upper = to + 2 * Math.PI * i;
        if (Range.closed(lower, upper).contains(phi)) {
            return true;
        }
    }

    return false;
}

From source file:com.jeffreybosboom.lyne.Effector.java

public static Pair<Puzzle, ImmutableMap<Node, Region.Point>> parseImage(BufferedImage image) {
    ImmutableSet<Region> regions = Region.connectedComponents(image, Colors.LYNE_COLORS);
    List<Region> nodeRegions = regions.stream().filter(r -> Colors.NODE_COLORS.keySet().contains(r.color()))
            .collect(Collectors.toList());
    //terminal markers and pips are inside node regions, so must be smaller
    int maxSize = nodeRegions.stream().mapToInt(r -> r.points().size()).max().getAsInt();
    List<Region> terminalRegions = regions.stream().filter(r -> r.points().size() < maxSize)
            .filter(r -> r.color() == Colors.TERMINAL_CENTER).collect(Collectors.toList());
    List<Region> pipRegions = regions.stream().filter(r -> r.points().size() < maxSize)
            .filter(r -> r.color() == Colors.PIP).collect(Collectors.toList());

    RangeSet<Integer> rowRanges = TreeRangeSet.create();
    nodeRegions.stream().map(Region::centroid).mapToInt(Region.Point::y)
            .mapToObj(i -> Range.closed(i - TOLERANCE, i + TOLERANCE)).forEachOrdered(rowRanges::add);
    List<Range<Integer>> rows = rowRanges.asRanges().stream().collect(Collectors.toList());
    RangeSet<Integer> colRanges = TreeRangeSet.create();
    nodeRegions.stream().map(Region::centroid).mapToInt(Region.Point::x)
            .mapToObj(i -> Range.closed(i - TOLERANCE, i + TOLERANCE)).forEachOrdered(colRanges::add);
    List<Range<Integer>> cols = colRanges.asRanges().stream().collect(Collectors.toList());

    Node[][] puzzle = new Node[rows.size()][cols.size()];
    ImmutableMap.Builder<Node, Region.Point> mapBuilder = ImmutableMap.builder();
    for (Region r : nodeRegions) {
        Region.Point c = r.centroid();
        Rectangle b = r.boundingBox();
        int row = rows.indexOf(rowRanges.rangeContaining(c.y()));
        int col = cols.indexOf(colRanges.rangeContaining(c.x()));
        Node.Kind kind = Colors.NODE_COLORS.get(r.color());
        Node node;/*w  w w.  j  av a 2  s .  c  o  m*/
        if (kind == Node.Kind.OCTAGON) {
            int pips = (int) pipRegions.stream().filter(p -> b.contains(p.boundingBox())).count();
            node = Node.octagon(row, col, pips);
        } else {
            boolean terminal = terminalRegions.stream().anyMatch(t -> b.contains(t.boundingBox()));
            node = terminal ? Node.terminal(row, col, kind) : Node.nonterminal(row, col, kind);
        }
        puzzle[row][col] = node;
        mapBuilder.put(node, c);
    }
    return new Pair<>(new Puzzle(puzzle), mapBuilder.build());
}

From source file:com.wandrell.tabletop.interval.DefaultInterval.java

/**
 * Sets the interval's upper limit./*from   w  w w .j  av  a2 s. co  m*/
 * 
 * @param upperLimit
 *            the upper limit
 */
public final void setUpperLimit(final Integer upperLimit) {
    checkNotNull(upperLimit, "Received a null pointer as upper limit");

    range = Range.closed(range.lowerEndpoint(), upperLimit);
}

From source file:org.caleydo.view.histogram.v2.BarDistributionElement.java

@Override
public Set<Integer> unapply(GLLocation location) {
    float max = EDimension.get(!vertical).select(getSize());
    int from = (int) (location.getOffset() * data.size() / max);
    int to = (int) (location.getOffset2() * data.size() / max);
    return ContiguousSet.create(Range.closed(from, to), DiscreteDomain.integers());
}

From source file:tile80.world80.World80Graph.java

@Override
public Iterable<Tile80> getTileByRect(Pair<Integer, Integer> topLeft, Pair<Integer, Integer> bottomRight) {
    Preconditions.checkNotNull(topLeft, bottomRight);
    return FluentIterable.from(coord.rightSet()).filter(Range.closed(topLeft, bottomRight))
            .transform(Functions.forMap(coord.rightMap())).transform(toTile80);
}

From source file:net.opentsdb.contrib.tsquare.web.view.DataQueryView.java

private void executeGroupedSeries(final GroupedSeriesWriter groupedSeriesWriter, final DataQueryModel modelObj,
        final ResponseContext context) throws IOException {
    Exception ex = null;/*from   w  ww  . j  ava 2 s .  c om*/

    try {
        groupedSeriesWriter.beginResponse(context);

        final Multimap<String, AnnotatedDataPoints> groups = LinkedListMultimap.create();

        for (final AnnotatedDataQuery dataQuery : modelObj.getQueries()) {
            final DataPoints[] result = dataQuery.getQuery().run();
            for (final DataPoints series : result) {
                AnnotatedDataPoints points = new AnnotatedDataPoints(dataQuery.getMetric(),
                        Range.closed(dataQuery.getQuery().getStartTime(), dataQuery.getQuery().getEndTime()),
                        series);
                groups.put(series.metricName(), points);
            }
        }

        for (final String metricName : groups.keySet()) {
            Collection<AnnotatedDataPoints> points = groups.get(metricName);
            groupedSeriesWriter.write(points, context);
        }

        groupedSeriesWriter.endResponse(context);
    } catch (IOException e) {
        ex = e;
        throw e;
    } catch (RuntimeException e) {
        ex = e;
        throw e;
    } finally {
        if (ex != null) {
            groupedSeriesWriter.onError(context, ex);
        }
    }
}

From source file:org.robotframework.ide.eclipse.main.plugin.project.build.validation.UnknownVariables.java

void reportUnknownVariables(final List<VariableDeclaration> variablesDeclarations,
        final Predicate<VariableDeclaration> isInvalid) {

    for (final VariableDeclaration variableDeclaration : variablesDeclarations) {
        if (isInvalid.apply(variableDeclaration)) {
            final String variableName = getVariableName(variableDeclaration);
            final RobotProblem problem = RobotProblem.causedBy(VariablesProblem.UNDECLARED_VARIABLE_USE)
                    .formatMessageWith(variableName);
            final int variableOffset = variableDeclaration.getStartFromFile().getOffset();
            final ProblemPosition position = new ProblemPosition(
                    variableDeclaration.getStartFromFile().getLine(),
                    Range.closed(variableOffset, variableOffset
                            + ((variableDeclaration.getEndFromFile().getOffset() + 1) - variableOffset)));
            final Map<String, Object> additionalArguments = ImmutableMap.<String, Object>of(
                    AdditionalMarkerAttributes.NAME, getVariableNameWithBrackets(variableDeclaration));
            reporter.handleProblem(problem, validationContext.getFile(), position, additionalArguments);
        }//from w  w  w.ja  v a 2 s . co  m
    }
}

From source file:com.rockhoppertech.music.series.time.TimeEvent.java

/**
 * @return a closed {@code Range}/*from  www .  j a va 2 s .c o m*/
 */
public Range<Double> getClosedRange() {
    return Range.closed(this.startBeat, this.startBeat + this.duration);
}