Java Code Examples for com.google.common.collect.Collections2#permutations()

The following examples show how to use com.google.common.collect.Collections2#permutations() . 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: BitfinexOrderTest.java    From bitfinex-v2-wss-api-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testOrderStatusFlags2() {
	final Collection<List<BitfinexOrderFlag>> orderflagPermutations 
		= Collections2.permutations(Arrays.asList(BitfinexOrderFlag.values()));
	
	for(final List<BitfinexOrderFlag> flags : orderflagPermutations) {
		// Convert to set
		final HashSet<BitfinexOrderFlag> orderFlags = new HashSet<>(flags);

		final BitfinexNewOrder bitfinexNewOrder = new BitfinexNewOrder();
		bitfinexNewOrder.setOrderFlags(orderFlags);
		Assert.assertEquals(orderFlags, bitfinexNewOrder.getOrderFlags());
		
		// Marge and parse flags from and to long
		bitfinexNewOrder.setOrderFlags(bitfinexNewOrder.getCombinedFlags());
		
		Assert.assertEquals(orderFlags, bitfinexNewOrder.getOrderFlags());
	}
}
 
Example 2
Source File: GenerationRepository.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create all attribute permutations that can be used (within a lexeme) to
 * initialize this template.
 */
private List<List<String>> createAllAttributesPermutations(
		LexicalTemplate template) {
	if (template.getSignature().getNumAttributes() == 0) {
		return ListUtils
				.createSingletonList(Collections.<String> emptyList());
	}

	final List<List<String>> attributePermutations = new LinkedList<List<String>>();
	for (final List<String> subset : new PowerSetWithFixedSize<String>(
			attributes, template.getSignature().getNumAttributes())) {
		// Create all permutations of this subset of attributes.
		for (final List<String> permutation : Collections2
				.permutations(subset)) {
			if (template.apply(new Lexeme(TokenSeq.of(),
					template.getArguments(), permutation)) != null) {
				attributePermutations
						.add(Collections.unmodifiableList(permutation));
			}
		}
	}
	return attributePermutations;
}
 
Example 3
Source File: GenerationRepository.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
private List<List<String>> createAttributePermutations(int length) {
	if (length == 0) {
		return ListUtils
				.createSingletonList(Collections.<String> emptyList());
	}

	final List<List<String>> attributePermutations = new LinkedList<List<String>>();
	for (final List<String> subset : new PowerSetWithFixedSize<String>(
			attributes, length)) {
		// Create all permutations of this subset of attributes.
		for (final List<String> permutation : Collections2
				.permutations(subset)) {
			attributePermutations
					.add(Collections.unmodifiableList(permutation));
		}
	}
	return attributePermutations;
}
 
Example 4
Source File: TupleExecutionPlanGenerator.java    From rya with Apache License 2.0 6 votes vote down vote up
private List<TupleExpr> getPlans(final TupleExpr te) {


        final NodeCollector nc = new NodeCollector();
        te.visit(nc);

        final Set<QueryModelNode> nodeSet = nc.getNodeSet();
        final List<Filter> filterList = nc.getFilterSet();
        final Projection projection = nc.getProjection().clone();

        final List<TupleExpr> queryPlans = Lists.newArrayList();

        final Collection<List<QueryModelNode>> plans = Collections2.permutations(nodeSet);

        for (final List<QueryModelNode> p : plans) {
            if (p.size() == 0) {
                throw new IllegalArgumentException("Tuple must contain at least one node!");
            } else if (p.size() == 1) {
                queryPlans.add(te);
            } else {
                queryPlans.add(buildTuple(p, filterList, projection));
            }
        }

        return queryPlans;
    }
 
Example 5
Source File: DifferCorrectnessTest.java    From epoxy with Apache License 2.0 5 votes vote down vote up
@Test
public void shuffle() {
  // Tries all permutations of item shuffles, with various list sizes. Also randomizes
  // item values so that the diff must deal with both item updates and movements
  for (int i = 0; i < 9; i++) {
    List<EpoxyModel<?>> originalModels = new ArrayList<>();
    addModels(i, originalModels);
    int permutationNumber = 0;
    for (List<EpoxyModel<?>> permutedModels : Collections2.permutations(originalModels)) {
      permutationNumber++;

      // Resetting to the original models each time, otherwise each subsequent permutation is
      // only a small difference
      models.clear();
      models.addAll(originalModels);
      diffAndValidate();

      models.clear();
      models.addAll(permutedModels);
      changeValues(models);

      log("\n\n***** Permutation " + permutationNumber + " - List Size: " + i + " ****** \n");
      log("old models:\n" + models);
      log("\n");
      log("new models:\n" + models);
      log("\n");

      diffAndValidate();
    }
  }
}
 
Example 6
Source File: BlazeCommandDispatcherRcoptionsTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testInheritedOptionsWithSpecificOverride() throws Exception {
  ImmutableList<ImmutableList<String>> blazercOpts =
      ImmutableList.of(
          ImmutableList.of(
              "--rc_source=/doesnt/matter/0/bazelrc",
              "--default_override=0:common=--stringoption=common",
              "--default_override=0:common=--numoption=42"),
          ImmutableList.of(
              "--rc_source=/doesnt/matter/1/bazelrc",
              "--default_override=0:reportall=--stringoption=reportall"),
          ImmutableList.of(
              "--rc_source=/doesnt/matter/2/bazelrc",
              "--default_override=0:reportallinherited=--stringoption=reportallinherited"));

  for (List<ImmutableList<String>> e : Collections2.permutations(blazercOpts)) {
    outErr.reset();
    BlazeCommandDispatcher dispatch =
        new BlazeCommandDispatcher(runtime, reportNum, reportAll, reportAllInherited);
    List<String> cmdLine = Lists.newArrayList("reportallinherited");
    List<String> orderedOpts = ImmutableList.copyOf(Iterables.concat(e));
    cmdLine.addAll(orderedOpts);

    dispatch.exec(cmdLine, "test", outErr);
    String out = outErr.outAsLatin1();
    assertWithMessage(String.format(
            "The more specific option should override, irrespective of source file or order. %s",
            orderedOpts))
        .that(out)
        .isEqualTo("42 reportallinherited");
  }
}
 
Example 7
Source File: Collections2Example.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void permutations () {

	List<Integer> vals = Ints.asList(new int[] {1, 2, 3});
	
	Collection<List<Integer>> orderPerm = 
			Collections2.permutations(vals);
	
	for (List<Integer> val : orderPerm) {
		logger.info(val);
	}
	
	assertEquals(6, orderPerm.size());
}
 
Example 8
Source File: FDBFilterCoalescingQueryTest.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
/**
 * TODO The planner does not currently coalesce the overlapping filters (>= 3 and > 0).
 * TODO: Planner does not currently coalesce overlapping filters (https://github.com/FoundationDB/fdb-record-layer/issues/1)
 */
@Test
public void overlappingFilters() throws Exception {
    RecordMetaDataHook hook = metaData -> {
        metaData.addIndex("MySimpleRecord", new Index("multi_index", "str_value_indexed", "num_value_3_indexed"));
    };
    complexQuerySetup(hook);
    RecordQuery query = RecordQuery.newBuilder()
            .setRecordType("MySimpleRecord")
            .setFilter(Query.and(
                    Query.field("str_value_indexed").equalsParameter("str"),
                    Query.field("num_value_3_indexed").greaterThanOrEquals(3),
                    Query.field("num_value_3_indexed").lessThanOrEquals(4),
                    Query.field("num_value_3_indexed").greaterThan(0)))
            .build();
    RecordQueryPlan plan = planner.plan(query);
    List<String> bounds = Arrays.asList("GREATER_THAN_OR_EQUALS 3", "LESS_THAN_OR_EQUALS 4", "GREATER_THAN 0");
    Collection<List<String>> combinations = Collections2.permutations(bounds);
    assertThat(plan, indexScan(allOf(indexName("multi_index"),
            bounds(anyOf(combinations.stream()
                    .map(ls -> hasTupleString("[EQUALS $str, [" + String.join(" && ", ls) + "]]"))
                    .collect(Collectors.toList()))))));
    assertEquals(241654378, plan.planHash());

    try (FDBRecordContext context = openContext()) {
        openSimpleRecordStore(context, hook);
        EvaluationContext boundContext = EvaluationContext.forBinding("str", "even");
        int i = 0;
        try (RecordCursorIterator<FDBQueriedRecord<Message>> cursor = plan.execute(recordStore, boundContext).asIterator()) {
            while (cursor.hasNext()) {
                FDBQueriedRecord<Message> rec = cursor.next();
                TestRecords1Proto.MySimpleRecord.Builder myrec = TestRecords1Proto.MySimpleRecord.newBuilder();
                myrec.mergeFrom(rec.getRecord());
                assertEquals("even", myrec.getStrValueIndexed());
                assertThat(myrec.getNumValue3Indexed(), allOf(greaterThanOrEqualTo(3), lessThanOrEqualTo(4)));
                i++;
            }
        }
        assertEquals(20, i);
        assertDiscardedNone(context);
    }
}
 
Example 9
Source File: ConjunctionQuery.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Get all possible orderings of fragments
 */
Set<List<Fragment>> allFragmentOrders() {
    Collection<List<EquivalentFragmentSet>> fragmentSetPermutations = Collections2.permutations(equivalentFragmentSets);
    return fragmentSetPermutations.stream().flatMap(this::cartesianProduct).collect(toSet());
}
 
Example 10
Source File: AlignmentGenlex.java    From amr with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ILexiconImmutable<LogicalExpression> generate(
		LabeledAmrSentence dataItem,
		IJointModelImmutable<SituatedSentence<AMRMeta>, LogicalExpression, LogicalExpression> model,
		ICategoryServices<LogicalExpression> categoryServices) {
	if (!dataItem.hasAlignments()) {
		LOG.debug(
				"Data item has no alignment information -- returning no entries");
		return new Lexicon<>();
	}

	// Get all factorable constants from the labeled logical form. We use
	// these to track which constants are not covered and issue a log
	// message appropriately.
	final Set<LogicalConstant> allConstants = GetConstantsSet
			.of(AMRServices.underspecifyAndStrip(dataItem.getLabel()))
			.stream().filter(FactoringServices::isFactorable)
			.collect(Collectors.toSet());

	final long startTime = System.currentTimeMillis();

	final TokenSeq tokens = dataItem.getSample().getTokens();
	final int numTokens = tokens.size();
	final Set<Lexeme> lexemes = new HashSet<>();
	for (int start = 0; start < numTokens; ++start) {
		for (int end = start + 1; end <= numTokens; ++end) {
			final TokenSeq seq = tokens.sub(start, end);
			final Set<LogicalExpression> aligned = dataItem
					.getAlignedExpressions(start, end);
			if (aligned != null) {
				for (final LogicalExpression exp : aligned) {
					LOG.debug("Alignment: %s -> %s", seq, exp);
					// Track this for logging.
					final int priorNumLexemes = lexemes.size();
					final List<LogicalConstant> constants = GetConstantsMultiSet
							.of(AMRServices.underspecifyAndStrip(exp))
							.stream()
							.filter(FactoringServices::isFactorable)
							.collect(Collectors.toList());
					// Remove the constants from the set we maintain for
					// logging.
					allConstants.removeAll(constants);

					for (final LexicalTemplate template : repo
							.getTemplates()) {
						for (final List<String> attributes : repo
								.getAttributeLists(template)) {
							for (final List<LogicalConstant> permutation : Collections2
									.permutations(constants)) {
								final Lexeme lexeme = new Lexeme(seq,
										permutation, attributes,
										entryProperties);
								if (!lexemes.contains(lexeme)
										&& template.isValid(lexeme)) {
									LOG.debug("Generated: %s", lexeme);
									lexemes.add(lexeme);
								}
							}
						}
					}
					LOG.debug("Generated %d new lexemes from alignment",
							lexemes.size() - priorNumLexemes);
				}
			}
		}
	}

	LOG.debug("Alignment GENLEX created %d lexemes (%.3fsec)",
			lexemes.size(),
			(System.currentTimeMillis() - startTime) / 1000.0);

	if (!allConstants.isEmpty()) {
		LOG.debug("Constants not covered by generator: %s", allConstants);
	}

	return new FactoredLexicon(lexemes, repo.getTemplates());
}
 
Example 11
Source File: GenerationRepository.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
public boolean addTemplate(LexicalTemplate template) {
	if (!templates.contains(template)) {
		LOG.debug("Trying to add template: %s", template);
		// First verify that we really need this template. There's an
		// existing issue with spurious ambiguity in factoring. This fix
		// is a brute-force hack to try to suppress it when using GENLEX.
		// When there are many templates, this process is going to explode
		final Iterator<LexicalTemplate> iterator = templates.iterator();
		while (iterator.hasNext()) {
			final LexicalTemplate existingTemplate = iterator.next();
			final int numAttributes = existingTemplate.getSignature()
					.getNumAttributes();
			if (numAttributes == template.getSignature().getNumAttributes()
					&& existingTemplate.getSignature().getTypes()
							.size() == template.getSignature().getTypes()
									.size()) {
				// Create dummy attributes list.
				final List<String> dummyAttributes = new ArrayList<String>(
						numAttributes);
				for (int i = 0; i < numAttributes; ++i) {
					dummyAttributes.add("dummy" + i);
				}
				for (final List<LogicalConstant> permutation : Collections2
						.permutations(template.getArguments())) {
					// Create a dummy lexeme.
					final Lexeme dummy = new Lexeme(TokenSeq.of(),
							permutation, dummyAttributes);
					if (existingTemplate.isValid(dummy)) {
						final Category<LogicalExpression> application = existingTemplate
								.apply(dummy);
						if (application != null && application.equals(
								template.apply(new Lexeme(TokenSeq.of(),
										template.getArguments(),
										dummyAttributes)))) {
							// Skip adding this template.
							LOG.debug(
									"Ignoring template (spurious ambiguity): %s",
									template);
							LOG.debug("... detected duplicate of: %s",
									existingTemplate);
							return false;
						}
					}
				}
			}
		}
		LOG.info(
				"Adding new template to generation repository (%d constants, %d attributes): %s",
				template.getArguments().size(),
				template.getSignature().getNumAttributes(), template);
		templates.add(template);
		if (signatures.add(template.getSignature()) && !arrityAndAttributes
				.containsKey(template.getSignature().getNumAttributes())) {
			arrityAndAttributes.put(
					template.getSignature().getNumAttributes(),
					createAttributePermutations(
							template.getSignature().getNumAttributes()));
		}

		templatesAndAttributes.put(template, Collections.unmodifiableList(
				createAllAttributesPermutations(template)));
		return true;
	}

	return false;
}
 
Example 12
Source File: MembersInjectionMethodsBuilderTest.java    From bullet with Apache License 2.0 4 votes vote down vote up
private static void addPermutations(ArrayList<Object[]> data, String desc, List<? extends Class<?>> inputs, Asserter asserter) {
  for (List<? extends Class<?>> permutation : Collections2.permutations(inputs)) {
    data.add(new Object[] { desc, permutation, asserter });
  }
}