Java Code Examples for com.google.common.collect.DiscreteDomain

The following examples show how to use com.google.common.collect.DiscreteDomain. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: presto   Source File: TestShortDecimalStatisticsBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMinMaxValues()
{
    assertMinMaxValues(0L, 0L);
    assertMinMaxValues(42L, 42L);
    assertMinMaxValues(MIN_VALUE, MIN_VALUE);
    assertMinMaxValues(MAX_VALUE, MAX_VALUE);

    assertMinMaxValues(0L, 42L);
    assertMinMaxValues(42L, 42L);
    assertMinMaxValues(MIN_VALUE, 42L);
    assertMinMaxValues(42L, MAX_VALUE);
    assertMinMaxValues(MIN_VALUE, MAX_VALUE);

    assertValues(-42L, 0L, ContiguousSet.create(Range.closed(-42L, 0L), DiscreteDomain.longs()).asList());
    assertValues(-42L, 42L, ContiguousSet.create(Range.closed(-42L, 42L), DiscreteDomain.longs()).asList());
    assertValues(0L, 42L, ContiguousSet.create(Range.closed(0L, 42L), DiscreteDomain.longs()).asList());
    assertValues(MIN_VALUE, MIN_VALUE + 42, ContiguousSet.create(Range.closed(MIN_VALUE, MIN_VALUE + 42), DiscreteDomain.longs()).asList());
    assertValues(MAX_VALUE - 42L, MAX_VALUE, ContiguousSet.create(Range.closed(MAX_VALUE - 42L, MAX_VALUE), DiscreteDomain.longs()).asList());
}
 
Example 2
Source Project: presto   Source File: TestDateStatisticsBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMinMaxValues()
{
    assertMinMaxValues(0, 0);
    assertMinMaxValues(42, 42);
    assertMinMaxValues(MIN_VALUE, MIN_VALUE);
    assertMinMaxValues(MAX_VALUE, MAX_VALUE);

    assertMinMaxValues(0, 42);
    assertMinMaxValues(42, 42);
    assertMinMaxValues(MIN_VALUE, 42);
    assertMinMaxValues(42, MAX_VALUE);
    assertMinMaxValues(MIN_VALUE, MAX_VALUE);

    assertValues(-42, 0, ContiguousSet.create(Range.closed(-42, 0), DiscreteDomain.integers()).asList());
    assertValues(-42, 42, ContiguousSet.create(Range.closed(-42, 42), DiscreteDomain.integers()).asList());
    assertValues(0, 42, ContiguousSet.create(Range.closed(0, 42), DiscreteDomain.integers()).asList());
    assertValues(MIN_VALUE, MIN_VALUE + 42, ContiguousSet.create(Range.closed(MIN_VALUE, MIN_VALUE + 42), DiscreteDomain.integers()).asList());
    assertValues(MAX_VALUE - 42, MAX_VALUE, ContiguousSet.create(Range.closed(MAX_VALUE - 42, MAX_VALUE), DiscreteDomain.integers()).asList());
}
 
Example 3
Source Project: presto   Source File: TestIntegerStatisticsBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMinMaxValues()
{
    assertMinMaxValues(0L, 0L);
    assertMinMaxValues(42L, 42L);
    assertMinMaxValues(MIN_VALUE, MIN_VALUE);
    assertMinMaxValues(MAX_VALUE, MAX_VALUE);

    assertMinMaxValues(0L, 42L);
    assertMinMaxValues(42L, 42L);
    assertMinMaxValues(MIN_VALUE, 42L);
    assertMinMaxValues(42L, MAX_VALUE);
    assertMinMaxValues(MIN_VALUE, MAX_VALUE);

    assertValues(-42L, 0L, ContiguousSet.create(Range.closed(-42L, 0L), DiscreteDomain.longs()).asList());
    assertValues(-42L, 42L, ContiguousSet.create(Range.closed(-42L, 42L), DiscreteDomain.longs()).asList());
    assertValues(0L, 42L, ContiguousSet.create(Range.closed(0L, 42L), DiscreteDomain.longs()).asList());
    assertValues(MIN_VALUE, MIN_VALUE + 42, ContiguousSet.create(Range.closed(MIN_VALUE, MIN_VALUE + 42), DiscreteDomain.longs()).asList());
    assertValues(MAX_VALUE - 42L, MAX_VALUE, ContiguousSet.create(Range.closed(MAX_VALUE - 42L, MAX_VALUE), DiscreteDomain.longs()).asList());
}
 
Example 4
Source Project: hop   Source File: MemoryGroupByAggregationTest.java    License: Apache License 2.0 6 votes vote down vote up
private Iterable<Object[]> getRows() {
  if ( data.isEmpty() ) {
    return ImmutableSet.of();
  }

  Range<Integer> rows = Range.closed( 0, data.rowMap().lastKey() );

  return FluentIterable.from( ContiguousSet.create( rows, DiscreteDomain.integers() ) )
    .transform( Functions.forMap( data.rowMap(), ImmutableMap.<Integer, Optional<Object>>of() ) )
    .transform( new Function<Map<Integer, Optional<Object>>, Object[]>() {
      @Override public Object[] apply( Map<Integer, Optional<Object>> input ) {
        Object[] row = new Object[ rowMeta.size() ];
        for ( Map.Entry<Integer, Optional<Object>> entry : input.entrySet() ) {
          row[ entry.getKey() ] = entry.getValue().orNull();
        }
        return row;
      }
    } );
}
 
Example 5
Source Project: hop   Source File: MemoryGroupByAggregationTest.java    License: Apache License 2.0 6 votes vote down vote up
private Iterable<Object[]> getRows() {
  if ( data.isEmpty() ) {
    return ImmutableSet.of();
  }

  Range<Integer> rows = Range.closed( 0, data.rowMap().lastKey() );

  return FluentIterable.from( ContiguousSet.create( rows, DiscreteDomain.integers() ) )
    .transform( Functions.forMap( data.rowMap(), ImmutableMap.<Integer, Optional<Object>>of() ) )
    .transform( new Function<Map<Integer, Optional<Object>>, Object[]>() {
      @Override public Object[] apply( Map<Integer, Optional<Object>> input ) {
        Object[] row = new Object[ rowMeta.size() ];
        for ( Map.Entry<Integer, Optional<Object>> entry : input.entrySet() ) {
          row[ entry.getKey() ] = entry.getValue().orNull();
        }
        return row;
      }
    } );
}
 
Example 6
Source Project: elasticsearch-sql   Source File: AggregationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void multipleGroupByTest() throws Exception {
	Set expectedAges = new HashSet<Integer>(ContiguousSet.create(Range.closed(20, 40), DiscreteDomain.integers()));

	Map<String, Set<Integer>> buckets = new HashMap<>();

	Aggregations result = query(String.format("SELECT COUNT(*) FROM %s/account GROUP BY gender,  terms('field'='age','size'=200,'alias'='age')", TEST_INDEX_ACCOUNT));
	Terms gender = result.get("gender");
	for(Terms.Bucket genderBucket : gender.getBuckets()) {
		String genderKey = genderBucket.getKey().toString();
		buckets.put(genderKey, new HashSet<Integer>());
		Terms ageBuckets = (Terms) genderBucket.getAggregations().get("age");
		for(Terms.Bucket ageBucket : ageBuckets.getBuckets()) {
			buckets.get(genderKey).add(Integer.parseInt(ageBucket.getKey().toString()));
		}
	}

	Assert.assertEquals(2, buckets.keySet().size());
	Assert.assertEquals(expectedAges, buckets.get("m"));
	Assert.assertEquals(expectedAges, buckets.get("f"));
}
 
Example 7
Source Project: elasticsearch-sql   Source File: AggregationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void multipleGroupBysWithSize() throws Exception {
    Set expectedAges = new HashSet<Integer>(ContiguousSet.create(Range.closed(20, 40), DiscreteDomain.integers()));

    Map<String, Set<Integer>> buckets = new HashMap<>();

    Aggregations result = query(String.format("SELECT COUNT(*) FROM %s/account GROUP BY gender, terms('alias'='ageAgg','field'='age','size'=3)", TEST_INDEX_ACCOUNT));
    Terms gender = result.get("gender");
    Assert.assertEquals(2,gender.getBuckets().size());
    for(Terms.Bucket genderBucket : gender.getBuckets()) {

        String genderKey = genderBucket.getKey().toString();
        buckets.put(genderKey, new HashSet<Integer>());
        Terms ageBuckets = genderBucket.getAggregations().get("ageAgg");
        Assert.assertEquals(3,ageBuckets.getBuckets().size());

    }


}
 
Example 8
Source Project: grappa   Source File: RangeMatcherBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static Range<Integer> normalizeRange(final Range<Integer> range)
{
    Range<Integer> newRange = AT_LEAST_ZERO.intersection(range);

    if (newRange.isEmpty())
        throw new IllegalArgumentException("illegal range " + range
            + ": intersection with " + AT_LEAST_ZERO + " is empty");

    newRange = newRange.canonical(DiscreteDomain.integers());

    final int lowerBound = newRange.lowerEndpoint();

    return newRange.hasUpperBound()
        ? Range.closed(lowerBound, newRange.upperEndpoint() - 1)
        : Range.atLeast(lowerBound);
}
 
Example 9
Source Project: levelup-java-examples   Source File: GenerateOddNumbers.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void generate_odd_numbers_in_range_guava() {

	Set<Integer> set = ContiguousSet.create(Range.closed(1, 10),
			DiscreteDomain.integers());

	Iterable<Integer> oddNumbers = Iterables.filter(set,
			new Predicate<Integer>() {
				@Override
				public boolean apply(Integer input) {
					return input % 2 != 0;
				}
			});

	logger.info(oddNumbers);

	assertThat(
			oddNumbers,
			contains(new Integer(1), new Integer(3), new Integer(5),
					new Integer(7), new Integer(9)));
}
 
Example 10
Source Project: levelup-java-examples   Source File: GenerateEvenNumbers.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void generate_even_numbers_in_range_guava() {

	Set<Integer> set = ContiguousSet.create(Range.closed(1, 10),
			DiscreteDomain.integers());

	Iterable<Integer> evenNumbers = Iterables.filter(set,
			new Predicate<Integer>() {
				@Override
				public boolean apply(Integer input) {
					return input % 2 == 0;
				}
			});


	assertThat(
			evenNumbers,
			contains(new Integer(2), new Integer(4), new Integer(6),
					new Integer(8), new Integer(10)));
}
 
Example 11
private Iterable<Object[]> getRows() {
  if ( data.isEmpty() ) {
    return ImmutableSet.of();
  }

  Range<Integer> rows = Range.closed( 0, data.rowMap().lastKey() );

  return FluentIterable.from( ContiguousSet.create( rows, DiscreteDomain.integers() ) )
    .transform( Functions.forMap( data.rowMap(), ImmutableMap.<Integer, Optional<Object>>of() ) )
    .transform( new Function<Map<Integer, Optional<Object>>, Object[]>() {
      @Override public Object[] apply( Map<Integer, Optional<Object>> input ) {
        Object[] row = new Object[rowMeta.size()];
        for ( Map.Entry<Integer, Optional<Object>> entry : input.entrySet() ) {
          row[entry.getKey()] = entry.getValue().orNull();
        }
        return row;
      }
    } );
}
 
Example 12
Source Project: java-n-IDE-for-Android   Source File: JavaInput.java    License: Apache License 2.0 5 votes vote down vote up
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()));
    }
    return tokenRangeSet;
}
 
Example 13
Source Project: javaide   Source File: JavaInput.java    License: GNU General Public License v3.0 5 votes vote down vote up
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()));
    }
    return tokenRangeSet;
}
 
Example 14
Source Project: matplotlib4j   Source File: NumpyUtils.java    License: MIT License 5 votes vote down vote up
public static List<Double> arange(double start, double end, double step) {
    double scaledStart = start / step;
    double scaledEnd = end / step;
    double floorGap = scaledStart - (int) scaledStart;
    return ContiguousSet.create(Range.closed((int) scaledStart, (int) scaledEnd), DiscreteDomain.integers())
            .stream().map(x -> (x + floorGap) * step).collect(Collectors.toList());
}
 
Example 15
Source Project: synapse   Source File: KinesisCompactionAcceptanceTest.java    License: Apache License 2.0 5 votes vote down vote up
private void sendTestMessagesWithCompoundKey(final Range<Integer> messageKeyRange, final String payloadPrefix) throws InterruptedException {
    ContiguousSet.create(messageKeyRange, DiscreteDomain.integers())
            .forEach(key -> kinesisV2Sender.send(message(Key.of(valueOf(key), "PRICE#" + key), payloadPrefix + "-" + key)).join());
    ContiguousSet.create(messageKeyRange, DiscreteDomain.integers())
            .forEach(key -> kinesisV2Sender.send(message(Key.of(valueOf(key),"AVAILABILITY#" + key), payloadPrefix + "-" + key)).join());
    sleep(20);
}
 
Example 16
Source Project: synapse   Source File: InMemCompactionAcceptanceTest.java    License: Apache License 2.0 5 votes vote down vote up
private void sendTestMessagesWithCompoundKey(final Range<Integer> messageKeyRange, final String payloadPrefix) throws InterruptedException {
    ContiguousSet.create(messageKeyRange, DiscreteDomain.integers())
            .forEach(key -> compactionTestSender.send(message(Key.of(valueOf(key), "PRICE#" + key), payloadPrefix + "-" + key)).join());
    ContiguousSet.create(messageKeyRange, DiscreteDomain.integers())
            .forEach(key -> compactionTestSender.send(message(Key.of(valueOf(key),"AVAILABILITY#" + key), payloadPrefix + "-" + key)).join());
    sleep(20);
}
 
Example 17
Source Project: AILibs   Source File: WekaUtil.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static Collection<Integer>[] getArbitrarySplit(final IWekaInstances data, final Random rand, final double... portions) {

		/* check that portions sum up to s.th. smaller than 1 */
		double sum = 0;
		for (double p : portions) {
			sum += p;
		}
		if (sum > 1) {
			throw new IllegalArgumentException(MSG_SUM1);
		}

		LinkedList<Integer> indices = new LinkedList<>(ContiguousSet.create(Range.closed(0, data.size() - 1), DiscreteDomain.integers()).asList());
		Collections.shuffle(indices, rand);

		@SuppressWarnings("unchecked")
		Collection<Integer>[] folds = new ArrayList[portions.length + 1];
		Instances emptyInstances = new Instances(data.getList());
		emptyInstances.clear();

		/* distribute instances over the folds */
		for (int i = 0; i <= portions.length; i++) {
			double portion = i < portions.length ? portions[i] : 1 - sum;
			int numberOfItems = (int) Math.floor(data.size() * portion);
			Collection<Integer> fold = new ArrayList<>(numberOfItems);
			for (int j = 0; j < numberOfItems; j++) {
				fold.add(indices.poll());
			}
			folds[i] = fold;
		}

		/* distribute remaining ones over the folds */
		while (!indices.isEmpty()) {
			folds[rand.nextInt(folds.length)].add(indices.poll());
		}

		if (debug && Arrays.asList(folds).stream().mapToInt(Collection::size).sum() != data.size()) {
			throw new IllegalStateException(MSG_DEVIATING_NUMBER_OF_INSTANCES);
		}
		return folds;
	}
 
Example 18
Source Project: science-journal   Source File: GraphPopulator.java    License: Apache License 2.0 5 votes vote down vote up
private Range<Long> getEffectiveAddedRange(TimeRange requested, Range<Long> returned) {
  if (returned == null) {
    return requested.getTimes().canonical(DiscreteDomain.longs());
  }

  switch (requested.getOrder()) {
    case NEWEST_FIRST:
      return Range.closed(returned.lowerEndpoint(), requested.getTimes().upperEndpoint());
    case OLDEST_FIRST:
      return Range.closed(requested.getTimes().lowerEndpoint(), returned.upperEndpoint());
    default:
      throw new IllegalArgumentException("Unexpected value for enum: " + requested.getOrder());
  }
}
 
Example 19
Source Project: api-compiler   Source File: Feature.java    License: Apache License 2.0 5 votes vote down vote up
private Feature(Builder builder) {
  Preconditions.checkArgument(
      !builder.supportedVersionRange.canonical(DiscreteDomain.integers()).isEmpty(),
      "supportedVersionRange must not be empty");
  featureName = builder.featureName;
  childBindings = builder.childBindings.build();
  supportedVersionRange = builder.supportedVersionRange;
  defaultVersionRange = builder.defaultVersionRange;
}
 
Example 20
Source Project: JuiceboxLegacy   Source File: HeatmapRenderer.java    License: MIT License 5 votes vote down vote up
private void updatePreDefColors() {
    int arrSize = MainViewPanel.preDefMapColorGradient.size();

    ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(0, arrSize), DiscreteDomain.integers());
    Integer[] arrTmp = set.toArray(new Integer[arrSize]);
    final int[] arrScores = new int[arrSize];

    for (int idx = 0; idx < arrSize; idx++) {
        arrScores[idx] = arrTmp[idx];
    }

    preDefColorScale.updateColors(MainViewPanel.preDefMapColorGradient.toArray(new Color[arrSize]), arrScores);
}
 
Example 21
Source Project: zstack   Source File: AccessControlListApiInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private void validateIp(String ips, AccessControlListVO acl) {
    DebugUtils.Assert(acl != null, "the invalide null AccessControlListVO");
    Integer ipVer = acl.getIpVersion();
    if (!ipVer.equals(IPv6Constants.IPv4)) {
        throw new ApiMessageInterceptionException(argerr("not support the ip version %d", ipVer));
    }
    try {
        RangeSet<Long> ipRanges = IpRangeSet.listAllRanges(ips);
        String[] ipcount = ips.split(IP_SPLIT);
        if (ipRanges.asRanges().size() < ipcount.length) {
            throw new ApiMessageInterceptionException(argerr("%s duplicate/overlap ip entry with access-control-list group:%s", ips, acl.getUuid()));
        }
        for (Range<Long> range : ipRanges.asRanges()) {
            final Range<Long> frange = ContiguousSet.create(range, DiscreteDomain.longs()).range();
            String startIp = NetworkUtils.longToIpv4String(frange.lowerEndpoint());
            String endIp = NetworkUtils.longToIpv4String(frange.upperEndpoint());
            if (!validateIpRange(startIp, endIp)) {
                throw new ApiMessageInterceptionException(argerr("ip format only supports ip/iprange/cidr, but find %s", ips));
            }
            ipRanges.asRanges().stream().forEach(r -> {
                if (!frange.equals(r) && NetworkUtils.isIpv4RangeOverlap(startIp, endIp, NetworkUtils.longToIpv4String(r.lowerEndpoint()), NetworkUtils.longToIpv4String(r.upperEndpoint()))) {
                    throw new ApiMessageInterceptionException(argerr("ip range[%s, %s] is overlap with [%s, %s] in access-control-list group:%s",
                            startIp, endIp, NetworkUtils.longToIpv4String(r.lowerEndpoint()), NetworkUtils.longToIpv4String(r.upperEndpoint()), acl.getUuid()));
                }
            });
        }

    } catch (IllegalArgumentException e) {
        throw new ApiMessageInterceptionException(argerr("Invalid rule expression, the detail: %s", e.getMessage()));
    }

}
 
Example 22
Source Project: zstack   Source File: LoadBalancerApiInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private void validateIp(String ips, AccessControlListVO acl) {
    DebugUtils.Assert(acl != null, "the invalide null AccessControlListVO");
    Integer ipVer = acl.getIpVersion();
    if (!ipVer.equals(IPv6Constants.IPv4)) {
        throw new ApiMessageInterceptionException(argerr("operation failure, not support the ip version %d", ipVer));
    }
    try {
        RangeSet<Long> ipRanges = IpRangeSet.listAllRanges(ips);
        String[] ipcount = ips.split(IP_SPLIT);
        if (ipRanges.asRanges().size() < ipcount.length) {
            throw new ApiMessageInterceptionException(argerr("operation failure, duplicate/overlap ip entry in %s of accesscontrol list group:%s", ips, acl.getUuid()));
        }
        for (Range<Long> range : ipRanges.asRanges()) {
            final Range<Long> frange = ContiguousSet.create(range, DiscreteDomain.longs()).range();
            String startIp = NetworkUtils.longToIpv4String(frange.lowerEndpoint());
            String endIp = NetworkUtils.longToIpv4String(frange.upperEndpoint());
            if (!validateIpRange(startIp, endIp)) {
                throw new ApiMessageInterceptionException(argerr("operation failure, ip format only supports ip/iprange/cidr, but find %s", ips));
            }
            ipRanges.asRanges().stream().forEach(r -> {
                if (!frange.equals(r) && NetworkUtils.isIpv4RangeOverlap(startIp, endIp, NetworkUtils.longToIpv4String(r.lowerEndpoint()), NetworkUtils.longToIpv4String(r.upperEndpoint()))) {
                    throw new ApiMessageInterceptionException(argerr("ip range[%s, %s] is overlap with start ip:%s, end ip: %s of access-control-list group:%s",
                            startIp, endIp, NetworkUtils.longToIpv4String(r.lowerEndpoint()), NetworkUtils.longToIpv4String(r.upperEndpoint()), acl.getUuid()));
                }
            });
        }

    } catch (IllegalArgumentException e) {
        throw new ApiMessageInterceptionException(argerr("Invalid rule expression, the detail: %s", e.getMessage()));
    }

}
 
Example 23
Source Project: pinlater   Source File: PinLaterBackendBase.java    License: Apache License 2.0 5 votes vote down vote up
public Future<Integer> getJobCount(final PinLaterGetJobCountRequest request) {
  // If no priority is specified, search for jobs of all priorities.
  Range<Integer> priorityRange = request.isSetPriority()
                                 ? Range.closed((int) request.getPriority(),
      (int) request.getPriority()) :
                                 Range.closed(1, numPriorityLevels);
  final ContiguousSet<Integer> priorities =
      ContiguousSet.create(priorityRange, DiscreteDomain.integers());

  // Execute count query on each shard in parallel.
  List<Future<Integer>> futures = Lists.newArrayListWithCapacity(getShards().size());
  for (final String shardName : getShards()) {
    futures.add(futurePool.apply(new ExceptionalFunction0<Integer>() {
      @Override
      public Integer applyE() throws Throwable {
        return getJobCountFromShard(
            request.getQueueName(),
            shardName,
            priorities,
            request.getJobState(),
            request.isCountFutureJobs(),
            request.getBodyRegexToMatch());
      }
    }));
  }

  return Future.collect(futures).map(
      new Function<List<Integer>, Integer>() {
        @Override
        public Integer apply(List<Integer> shardCounts) {
          int totalCount = 0;
          for (Integer shardCount : shardCounts) {
            totalCount += shardCount;
          }
          return totalCount;
        }
      });
}
 
Example 24
Source Project: google-java-format   Source File: JavaInput.java    License: Apache License 2.0 5 votes vote down vote up
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()));
  }
  return tokenRangeSet;
}
 
Example 25
Source Project: android-test   Source File: PortManager.java    License: Apache License 2.0 5 votes vote down vote up
/** For testing, control all the dependencies of the PortManager. */
@VisibleForTesting
PortManager(
    Range<Integer> portRange,
    Collection<PortChecker> checkers,
    Random random,
    PortChecker clientConnectChecker) {
  this.random = checkNotNull(random);
  this.portSet = ContiguousSet.create(checkNotNull(portRange), DiscreteDomain.integers());
  this.checkers = ImmutableList.copyOf(checkNotNull(checkers));
  this.clientConnectChecker = checkNotNull(clientConnectChecker);
}
 
Example 26
Source Project: brooklyn-server   Source File: JcloudsLocationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCombinationOfInputstoIntPortArray() {
    Collection<Object> portInputs = Lists.newLinkedList();
    portInputs.add(1);
    portInputs.add("2");
    portInputs.add("3-100");
    portInputs.add("101,102,103");
    portInputs.add("[104,105,106]");
    portInputs.add(new int[] {107, 108, 109});
    portInputs.add(new String[] {"110", "111", "112"});
    portInputs.add(new Object[] {113, 114, 115});

    int[] intArray = Ints.toArray(ContiguousSet.create(Range.closed(1, 115), DiscreteDomain.integers()));
    Assert.assertEquals(intArray, JcloudsLocation.toIntPortArray(portInputs));
}
 
Example 27
Source Project: tassal   Source File: ASTVisitors.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean visit(final FieldDeclaration node) {

	// Shift start position to after Javadoc (if present)
	shiftStartPosition(node);

	// Add to relevant containers
	final int line = cu.getLineNumber(node.getStartPosition());
	fieldLineRanges.add(Range.singleton(line).canonical(DiscreteDomain.integers()));
	fieldLineParentNodes.put(line, node.getParent());

	final Range<Integer> range = Range.closed(node.getStartPosition(),
			node.getStartPosition() + node.getLength() - 1);
	lineToFieldRanges.put(line, range);

	for (final Object fragment : node.fragments()) {
		final VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;

		// Split SIMPLE_NAME if token splitting enabled
		final SimpleName name = frag.getName();
		final ArrayList<String> identifiers = Lists.newArrayList();
		putSplitToken(identifiers, name.getIdentifier());
		for (final String identifier : identifiers)
			fieldIdentifiers.put(range, identifier);

		// Remove field identifiers from parent class
		final FoldableNode parentClass = foldableStack.peek();
		parentClass.removeTerms(identifiers);

	}
	return true;
}
 
Example 28
Source Project: elasticsearch-sql   Source File: AggregationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSubAggregations() throws  Exception {
	Set expectedAges = new HashSet<>(ContiguousSet.create(Range.closed(20, 40), DiscreteDomain.integers()));
	final String query = String.format("SELECT /*! DOCS_WITH_AGGREGATION(10) */" +
               " * FROM %s/account GROUP BY (gender, terms('field'='age','size'=200,'alias'='age')), (state) LIMIT 200,200", TEST_INDEX_ACCOUNT);

	Map<String, Set<Integer>> buckets = new HashMap<>();

       SqlElasticSearchRequestBuilder select = getSearchRequestBuilder(query);
	SearchResponse response = (SearchResponse) select.get();
	Aggregations result = response.getAggregations();

	Terms gender = result.get("gender");
	for(Terms.Bucket genderBucket : gender.getBuckets()) {
		String genderKey = genderBucket.getKey().toString();
		buckets.put(genderKey, new HashSet<Integer>());
		Terms ageBuckets = (Terms) genderBucket.getAggregations().get("age");
		for(Terms.Bucket ageBucket : ageBuckets.getBuckets()) {
			buckets.get(genderKey).add(Integer.parseInt(ageBucket.getKey().toString()));
		}
	}

	Assert.assertEquals(2, buckets.keySet().size());
	Assert.assertEquals(expectedAges, buckets.get("m"));
	Assert.assertEquals(expectedAges, buckets.get("f"));

	Terms state = result.get("state");
	for(Terms.Bucket stateBucket : state.getBuckets()) {
		if(stateBucket.getKey().toString().equalsIgnoreCase("ak")) {
			Assert.assertTrue("There are 22 entries for state ak", stateBucket.getDocCount() == 22);
		}
	}

	Assert.assertEquals(response.getHits().getTotalHits().value, 1000);
	Assert.assertEquals(response.getHits().getHits().length, 10);
}
 
Example 29
Source Project: batfish   Source File: IntegerSpace.java    License: Apache License 2.0 5 votes vote down vote up
/** Include a {@link SubRange} */
public @Nonnull Builder excluding(SubRange range) {
  if (!range.isEmpty()) {
    excluding(
        Range.closed(range.getStart(), range.getEnd()).canonical(DiscreteDomain.integers()));
  }
  return this;
}
 
Example 30
Source Project: batfish   Source File: IntegerSpace.java    License: Apache License 2.0 5 votes vote down vote up
/** Include a {@link SubRange} */
public @Nonnull Builder including(SubRange range) {
  if (!range.isEmpty()) {
    including(
        Range.closed(range.getStart(), range.getEnd()).canonical(DiscreteDomain.integers()));
  }
  return this;
}