com.google.common.collect.ContiguousSet Java Examples

The following examples show how to use com.google.common.collect.ContiguousSet. 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 check out the related API usage on the sidebar.
Example #1
Source File: TestShortDecimalStatisticsBuilder.java    From presto with 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 File: MemoryGroupByAggregationTest.java    From pentaho-kettle with 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 #3
Source File: GenerateEvenNumbers.java    From levelup-java-examples with 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 #4
Source File: GenerateOddNumbers.java    From levelup-java-examples with 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 #5
Source File: AggregationTest.java    From elasticsearch-sql with 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 #6
Source File: AggregationTest.java    From elasticsearch-sql with 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 File: MemoryGroupByAggregationTest.java    From hop with 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 #8
Source File: MemoryGroupByAggregationTest.java    From hop with 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 #9
Source File: TestDateStatisticsBuilder.java    From presto with 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 #10
Source File: TestIntegerStatisticsBuilder.java    From presto with 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 #11
Source File: PinLaterBackendBase.java    From pinlater with 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 #12
Source File: FibonacciQueueTest.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testIterator() {
    // insert lots of numbers in order
    final Set<Integer> values = ContiguousSet.create(closedOpen(0, 1000), integers());
    final FibonacciQueue<Integer> queue = FibonacciQueue.create();
    assertTrue(queue.addAll(values));
    assertEquals(values, ImmutableSet.copyOf(queue.iterator()));
    assertEquals(values, ImmutableSet.copyOf(queue));
}
 
Example #13
Source File: PreferredAlbumsTableFactory.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Queryable<Integer> fetchPreferredAlbums() {
  if (EnvironmentFairy.getUser() == EnvironmentFairy.User.SPECIFIC_USER) {
    return Linq4j.asEnumerable(SPECIFIC_USER_PREFERRED_ALBUMS).asQueryable();
  } else {
    final ContiguousSet<Integer> set =
        ContiguousSet.create(Range.closed(FIRST_ID, LAST_ID),
            DiscreteDomain.integers());
    return Linq4j.asEnumerable(set).asQueryable();
  }
}
 
Example #14
Source File: PreferredGenresTableFactory.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Queryable<Integer> fetchPreferredGenres() {
  if (EnvironmentFairy.getUser() == EnvironmentFairy.User.SPECIFIC_USER) {
    return Linq4j.asEnumerable(SPECIFIC_USER_PREFERRED_GENRES).asQueryable();
  } else {
    final ContiguousSet<Integer> set =
        ContiguousSet.create(Range.closed(FIRST_ID, LAST_ID),
            DiscreteDomain.integers());
    return Linq4j.asEnumerable(set).asQueryable();
  }
}
 
Example #15
Source File: AggregationTest.java    From elasticsearch-sql with 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 #16
Source File: TimeOfYear.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an {@link Iterable} of {@link DateTime}s of every recurrence of this particular
 * time of year within a given {@link Range} (usually one spanning many years).
 *
 * <p>WARNING: This can return a potentially very large {@link Iterable} if {@code END_OF_TIME}
 * is used as the upper endpoint of the range.
 */
public Iterable<DateTime> getInstancesInRange(Range<DateTime> range) {
  // In registry world, all dates are within START_OF_TIME and END_OF_TIME, so restrict any
  // ranges without bounds to our notion of zero-to-infinity.
  Range<DateTime> normalizedRange = range.intersection(Range.closed(START_OF_TIME, END_OF_TIME));
  Range<Integer> yearRange = Range.closed(
      normalizedRange.lowerEndpoint().getYear(),
      normalizedRange.upperEndpoint().getYear());
  return ContiguousSet.create(yearRange, integers())
      .stream()
      .map(this::getDateTimeWithYear)
      .filter(normalizedRange)
      .collect(toImmutableList());
}
 
Example #17
Source File: HeatmapRenderer.java    From JuiceboxLegacy with 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 #18
Source File: AccessControlListApiInterceptor.java    From zstack with 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 #19
Source File: LoadBalancerApiInterceptor.java    From zstack with 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 #20
Source File: AbstractTestParquetReader.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testParquetShortDecimalWriteToPrestoTinyintBlock()
        throws Exception
{
    for (int precision = 1; precision <= MAX_PRECISION_INT64; precision++) {
        MessageType parquetSchema = parseMessageType(format("message hive_decimal { optional INT64 test (DECIMAL(%d, %d)); }", precision, 0));
        ContiguousSet<Long> longValues = longsBetween(Byte.MIN_VALUE, Byte.MAX_VALUE);
        ImmutableList.Builder<Byte> expectedValues = new ImmutableList.Builder<>();
        for (Long value : longValues) {
            expectedValues.add(value.byteValue());
        }
        tester.testRoundTrip(javaLongObjectInspector, longValues, expectedValues.build(), TINYINT, Optional.of(parquetSchema));
    }
}
 
Example #21
Source File: LocalExecutionPlanner.java    From presto with Apache License 2.0 5 votes vote down vote up
private static List<Type> toTypes(Map<Symbol, Integer> layout, LocalExecutionPlanContext context)
{
    // verify layout covers all values
    int channelCount = layout.values().stream().mapToInt(Integer::intValue).max().orElse(-1) + 1;
    checkArgument(
            layout.size() == channelCount && ImmutableSet.copyOf(layout.values()).containsAll(ContiguousSet.create(closedOpen(0, channelCount), integers())),
            "Layout does not have a symbol for every output channel: %s", layout);
    Map<Integer, Symbol> channelLayout = ImmutableBiMap.copyOf(layout).inverse();

    return range(0, channelCount)
            .mapToObj(channelLayout::get)
            .map(context.getTypes()::get)
            .collect(toImmutableList());
}
 
Example #22
Source File: SetFactoryTest.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
private static Provider<Set<Integer>> integerSetProvider(Range<Integer> range) {
  final ContiguousSet<Integer> set = ContiguousSet.create(range, integers());
  return new Provider<Set<Integer>>() {
    @Override
    public Set<Integer> get() {
      return set;
    }
  };
}
 
Example #23
Source File: TestArrayCombinationsFunction.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testCardinality()
{
    for (int n = 0; n < 5; n++) {
        for (int k = 0; k <= n; k++) {
            String array = "ARRAY" + ContiguousSet.closedOpen(0, n).asList();
            assertFunction(format("cardinality(combinations(%s, %s))", array, k), BIGINT, factorial(n) / factorial(n - k) / factorial(k));
        }
    }
}
 
Example #24
Source File: PortManager.java    From android-test with 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 #25
Source File: JcloudsLocationTest.java    From brooklyn-server with 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 #26
Source File: WekaUtil.java    From AILibs with 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 #27
Source File: InMemCompactionAcceptanceTest.java    From synapse with 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 #28
Source File: UnboundableCQLStatementIterator.java    From Rhombus with MIT License 5 votes vote down vote up
public UnboundableCQLStatementIterator(Range<Long> shardKeyList, long limit, CObjectOrdering ordering, CQLStatement CQLTemplate, String objectName){
	this.keyRange = shardKeyList;
	ContiguousSet<Long> set = ContiguousSet.create(shardKeyList, DiscreteDomain.longs());
	this.keyIterator = (ordering == CObjectOrdering.ASCENDING) ? set.iterator() : set.descendingIterator();
	this.ordering = ordering;
	this.size = (long)set.size();
	this.limit = limit;
	this.numberRemaining = this.limit;
	this.CQLTemplate = CQLTemplate;
	this.setObjectName(objectName);

}
 
Example #29
Source File: KinesisCompactionAcceptanceTest.java    From synapse with 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 #30
Source File: InvoiceMenu.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Action(semantics = SemanticsOf.IDEMPOTENT, restrictTo = RestrictTo.PROTOTYPING)
@MemberOrder(sequence = "98")
public List<InvoiceForLease> republish(
        @ParameterLayout(describedAs = "invoice number prefix, eg 'CAR' (as in 'CAR-0144')")
        final String invoiceNumberPrefix,
        @ParameterLayout(describedAs = "invoice number suffices, eg '144,145,150' (for 'CAR-0144', 'CAR-0145', 'CAR-0150')")
        @Nullable
        final String invoiceNumberSuffices,
        @ParameterLayout(describedAs = "invoice number suffices from (inclusive), eg '144' (for 'CAR-0144', ...)")
        @Nullable
        final Integer invoiceNumberFrom,
        @ParameterLayout(describedAs = "invoice number suffices to (inclusive), eg '150' (for ..., 'CAR-0150')")
        @Nullable
        final Integer invoiceNumberTo,
        final int year
) {
    final List<Integer> invoiceNumberSuffixList;
    if(invoiceNumberSuffices != null) {
        invoiceNumberSuffixList = Lists.newArrayList(Splitter.on(',').split(invoiceNumberSuffices))
                                    .stream().map(Integer::parseInt).collect(Collectors.toList());
    } else {
        invoiceNumberSuffixList = ContiguousSet.create(
                        Range.closed(invoiceNumberFrom, invoiceNumberTo), DiscreteDomain.integers()).asList();
    }

    final List<InvoiceForLease> invoiceList = invoiceNumberSuffixList.stream()
            .map(num -> String.format("%s-%04d", invoiceNumberPrefix, num))
            .map(invoiceNumber -> {
                final List<InvoiceForLease> invoices = findInvoicesByInvoiceNumber(invoiceNumber, year);
                return invoices.size() == 1 ? invoices.get(0) : null;
            })
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

    invoiceList.forEach(invoice -> factoryService.mixin(InvoiceForLease_republish.class, invoice).act());

    return invoiceList;
}