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

The following examples show how to use com.google.common.collect.Multiset. 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: askyblock   Source File: LevelCalcByChunk.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Collection<String> sortedReport(int total, Multiset<MaterialData> materialDataCount) {
    Collection<String> result = new ArrayList<>();
    Iterable<Multiset.Entry<MaterialData>> entriesSortedByCount = Multisets.copyHighestCountFirst(materialDataCount).entrySet();
    for (Entry<MaterialData> en : entriesSortedByCount) {
        MaterialData type = en.getElement();

        int value = 0;
        if (Settings.blockValues.containsKey(type)) {
            // Specific
            value = Settings.blockValues.get(type);
        } else if (Settings.blockValues.containsKey(new MaterialData(type.getItemType()))) {
            // Generic
            value = Settings.blockValues.get(new MaterialData(type.getItemType()));
        }
        if (value > 0) {
            result.add(type.toString() + ":"
                    + String.format("%,d", en.getCount()) + " blocks x " + value + " = " + (value
                            * en.getCount()));
            total += (value * en.getCount());
        }
    }
    result.add("Subtotal = " + total);
    result.add("==================================");
    return result;
}
 
Example 2
Source Project: log-synth   Source File: VinSamplerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSchema() throws IOException {
    //noinspection UnstableApiUsage
    SchemaSampler s = new SchemaSampler(Resources.asCharSource(Resources.getResource("schema014.json"), Charsets.UTF_8).read());

    Multiset<String> prefixCounts = TreeMultiset.create();
    Multiset<String> otherCounts = TreeMultiset.create();
    for (int i = 0; i < 100; i++) {
        JsonNode r = s.sample();
        assertEquals(r.get("v1").asText(), r.get("v2").get("VIN").asText());
        prefixCounts.add(r.get("v1").asText().substring(0, 2));
        otherCounts.add(r.get("v3").asText().substring(0, 2));
        System.out.printf("%s\n", r);
    }
    assertEquals("[1F, 2F, 3F]", prefixCounts.elementSet().toString());
    assertEquals("[2F, 3F]", otherCounts.elementSet().toString());
}
 
Example 3
Source Project: batfish   Source File: SwitchedVlanPropertiesAnswerer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets properties of switched vlans.
 *
 * @param ctxt context in which to apply {@code interfacesSpecifier}
 * @param configurations configuration to use in extractions
 * @param nodes the set of nodes to consider
 * @param interfaceSpecifier Specifies which interfaces to consider
 * @param columns a map from column name to {@link ColumnMetadata}
 * @return A multiset of {@link Row}s where each row corresponds to a node/vlan pair and columns
 *     correspond to property values.
 */
public static Multiset<Row> getProperties(
    SpecifierContext ctxt,
    Map<String, Configuration> configurations,
    Set<String> nodes,
    InterfaceSpecifier interfaceSpecifier,
    boolean excludeShutInterfaces,
    IntegerSpace vlans,
    Map<String, ColumnMetadata> columns) {
  Multiset<Row> rows = HashMultiset.create();
  for (String node : nodes) {
    Map<Integer, ImmutableSet.Builder<NodeInterfacePair>> switchedVlanInterfaces =
        new HashMap<>();
    ImmutableMap.Builder<Integer, Integer> vlanVnisBuilder = ImmutableMap.builder();
    computeNodeVlanProperties(
        ctxt,
        configurations.get(node),
        interfaceSpecifier,
        excludeShutInterfaces,
        vlans,
        switchedVlanInterfaces,
        vlanVnisBuilder);
    populateNodeRows(node, switchedVlanInterfaces, vlanVnisBuilder, columns, rows);
  }
  return rows;
}
 
Example 4
Source Project: tac-kbp-eal   Source File: CorpusAnalysis.java    License: MIT License 6 votes vote down vote up
static void writeToChart(final Multiset<Symbol> counts, final File outFile,
    final GnuPlotRenderer renderer,
    final String chartTitle, final String xAxisLabel, final String yAxisLabel)
    throws IOException {

  final Axis X_AXIS = Axis.xAxis().setLabel(xAxisLabel).rotateLabels().build();
  final Axis Y_AXIS = Axis.yAxis().setLabel(yAxisLabel).build();

  final BarChart.Builder chartBuilder =
      BarChart.builder().setTitle(chartTitle).setXAxis(X_AXIS).setYAxis(Y_AXIS).hideKey();

  for (final Multiset.Entry<Symbol> e : counts.entrySet()) {
    chartBuilder
        .addBar(BarChart.Bar.builder(e.getCount()).setLabel(e.getElement().toString()).build());
  }

  renderer.renderTo(chartBuilder.build(), outFile);
}
 
Example 5
Source Project: EasySRL   Source File: TagDict.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Finds the set of categories used for each word in a corpus
 */
public static Map<String, Collection<Category>> makeDict(final Iterable<InputToParser> input) {
	final Multiset<String> wordCounts = HashMultiset.create();
	final Map<String, Multiset<Category>> wordToCatToCount = new HashMap<>();

	// First, count how many times each word occurs with each category
	for (final InputToParser sentence : input) {
		for (int i = 0; i < sentence.getInputWords().size(); i++) {
			final String word = sentence.getInputWords().get(i).word;
			final Category cat = sentence.getGoldCategories().get(i);
			wordCounts.add(word);

			if (!wordToCatToCount.containsKey(word)) {
				final Multiset<Category> tmp = HashMultiset.create();
				wordToCatToCount.put(word, tmp);
			}

			wordToCatToCount.get(word).add(cat);
		}
	}

	return makeDict(wordCounts, wordToCatToCount);
}
 
Example 6
Source Project: gef   Source File: ObservableMultisetWrapper.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean setCount(E element, int oldCount, int newCount) {
	Multiset<E> previousContents = delegateCopy();
	boolean changed = super.setCount(element, oldCount, newCount);
	// if changed it means that the oldCound was matched and that now we
	// have the new count
	if (changed) {
		if (newCount > oldCount) {
			helper.fireValueChangedEvent(
					new MultisetListenerHelper.AtomicChange<>(this,
							previousContents, new ElementarySubChange<>(
									element, 0, newCount - oldCount)));
		} else if (oldCount > newCount) {
			helper.fireValueChangedEvent(
					new MultisetListenerHelper.AtomicChange<>(this,
							previousContents, new ElementarySubChange<>(
									element, oldCount - newCount, 0)));
		}
	}
	return changed;
}
 
Example 7
/**
 * Returns true if {@code atLeastM} of the expressions in the given column are the same kind.
 */
private static boolean expressionsAreParallel(
        List<List<ExpressionTree>> rows, int column, int atLeastM) {
    Multiset<Tree.Kind> nodeTypes = HashMultiset.create();
    for (List<? extends ExpressionTree> row : rows) {
        if (column >= row.size()) {
            continue;
        }
        nodeTypes.add(row.get(column).getKind());
    }
    for (Multiset.Entry<Tree.Kind> nodeType : nodeTypes.entrySet()) {
        if (nodeType.getCount() >= atLeastM) {
            return true;
        }
    }
    return false;
}
 
Example 8
/**
 * Method should return the number of times an occurrence of a reel
 * 
 * @param reels
 * @return
 */
static int determinePayOutPercentage(List<String> reels) {

	Multiset<String> reelCount = HashMultiset.create();
	reelCount.addAll(reels);

	// order the number of elements by the higest
	ImmutableMultiset<String> highestCountFirst = Multisets.copyHighestCountFirst(reelCount);

	int count = 0;
	for (Entry<String> entry : highestCountFirst.entrySet()) {
		count = entry.getCount();
		break;
	}
	return count;
}
 
Example 9
Source Project: EasySRL   Source File: TagDict.java    License: Apache License 2.0 6 votes vote down vote up
private static void addEntryForWord(final Multiset<Category> countForCategory,
		final Map<String, Collection<Category>> result, final String word) {
	final List<Entry<Category>> cats = new ArrayList<>();
	for (final Entry<Category> catToCount : countForCategory.entrySet()) {
		cats.add(catToCount);
	}
	final int totalSize = countForCategory.size();
	final int minSize = Math.floorDiv(totalSize, 1000);
	Collections.sort(cats, comparator);
	final List<Category> cats2 = new ArrayList<>();

	for (final Entry<Category> entry : cats) {
		if (entry.getCount() >= minSize) {
			cats2.add(entry.getElement());
		}
	}

	result.put(word, cats2);
}
 
Example 10
Source Project: Rails   Source File: TrainsModel.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Make an abbreviated list of trains, like "2(6) 3(5)" etc, to show in the
 * IPO.
 */
public String makeListOfTrainCards() {
    if (trainCards.isEmpty()) return "";

    // create a bag with train types
    Multiset<TrainCardType> trainCardTypes = HashMultiset.create();
    for (TrainCard card:trainCards) {
        trainCardTypes.add(card.getType());
    }
    
    StringBuilder b = new StringBuilder();
    
    for (TrainCardType cardType:ImmutableSortedSet.copyOf(trainCardTypes.elementSet())) {
        if (b.length() > 0) b.append(" ");
        b.append(cardType.toText()).append("(");
        if (cardType.hasInfiniteQuantity()) {
            b.append("+");
        } else {
            b.append(trainCardTypes.count(cardType));
        }
        b.append(")");
    }

    return b.toString();
}
 
Example 11
Source Project: angelix   Source File: TestTreeBoundedSynthesis.java    License: MIT License 6 votes vote down vote up
@Test
public void testUniqueMultiple() {
    Multiset<Node> components = HashMultiset.create();
    components.add(x, 2);
    components.add(Library.ADD, 1);
    components.add(Library.ITE);
    components.add(BoolConst.TRUE);

    ArrayList<TestCase> testSuite = new ArrayList<>();
    Map<ProgramVariable, Node> assignment1 = new HashMap<>();
    assignment1.put(x, IntConst.of(1));
    testSuite.add(TestCase.ofAssignment(assignment1, IntConst.of(2)));

    Map<Hole, Expression> args = new HashMap<>();
    args.put((Hole) Library.ADD.getLeft(), Expression.leaf(x));
    args.put((Hole) Library.ADD.getRight(), Expression.leaf(x));
    List<Expression> forbidden = new ArrayList<>();
    forbidden.add(Expression.app(Library.ADD, args));

    Synthesis synthesizerWithForbidden =
            new Synthesis(new BoundedShape(3, forbidden), new TreeBoundedEncoder());
    Optional<Pair<Expression, Map<Parameter, Constant>>> result = synthesizerWithForbidden.synthesize(testSuite, components);
    assertFalse(result.isPresent());
}
 
Example 12
Source Project: Word2VecJava   Source File: Word2VecTrainer.java    License: MIT License 6 votes vote down vote up
/** @return Tokens with their count, sorted by frequency decreasing, then lexicographically ascending */
private ImmutableMultiset<String> filterAndSort(final Multiset<String> counts) {
	// This isn't terribly efficient, but it is deterministic
	// Unfortunately, Guava's multiset doesn't give us a clean way to order both by count and element
	return Multisets.copyHighestCountFirst(
			ImmutableSortedMultiset.copyOf(
					Multisets.filter(
							counts,
							new Predicate<String>() {
								@Override
								public boolean apply(String s) {
									return counts.count(s) >= minFrequency;
								}
							}
					)
			)
	);
	
}
 
Example 13
Source Project: batfish   Source File: TracerouteAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFlowTracesToRowsMaxTraces() {
  Flow flow = Flow.builder().setIngressNode("node").setDstIp(Ip.parse("1.1.1.1")).build();
  SortedMap<Flow, List<Trace>> flowTraces =
      ImmutableSortedMap.of(
          flow,
          ImmutableList.of(
              new Trace(FlowDisposition.DENIED_OUT, ImmutableList.of()),
              new Trace(FlowDisposition.DENIED_IN, ImmutableList.of())));
  Multiset<Row> rows = flowTracesToRows(flowTraces, 1);

  assertThat(
      rows.iterator().next(),
      allOf(
          hasColumn(
              COL_FLOW,
              allOf(hasDstIp(Ip.parse("1.1.1.1")), hasIngressNode("node")),
              Schema.FLOW),
          hasColumn(COL_TRACES, hasSize(1), Schema.set(Schema.TRACE)),
          hasColumn(TracerouteAnswerer.COL_TRACE_COUNT, equalTo(2), Schema.INTEGER)));
}
 
Example 14
Source Project: levelup-java-examples   Source File: MultisetExample.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void multiset_example () {
	
	Multiset<String> camouflage = HashMultiset.create();
	camouflage.add("Realtree APG");
	camouflage.add("Realtree Hardwoods HD");
	camouflage.add("Realtree APG");
	camouflage.add("Realtree Hardwoods Green HD");
	camouflage.add("Mossy Oak New Break-Up");
	camouflage.add("Realtree APG");
	
	logger.info(camouflage);

	int numberOfRealTrees = camouflage.count("Realtree APG");
	
	assertEquals(3, numberOfRealTrees);
}
 
Example 15
Source Project: batfish   Source File: IpsecSessionStatusAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateRowsMissingEndpoint() {
  // Responder not set in the graph
  _graph.addNode(new IpsecPeerConfigId(INITIATOR_IPSEC_PEER_CONFIG, INITIATOR_HOST_NAME));
  Multiset<IpsecSessionInfo> ipsecSessionInfos =
      rawAnswer(
          _networkConfigurations,
          _graph,
          ImmutableSet.of(INITIATOR_HOST_NAME),
          ImmutableSet.of(RESPONDER_HOST_NAME));

  // answer should have exactly one row
  assertThat(ipsecSessionInfos, hasSize(1));

  assertThat(
      ipsecSessionInfos.iterator().next(), hasIpsecSessionStatus(equalTo(MISSING_END_POINT)));
}
 
Example 16
Source Project: batfish   Source File: IpsecSessionStatusAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateRowsIpsecEstablished() {
  // IPSecSession has all phases negotiated and IKE phase 1 key consistent
  _ipsecSessionBuilder.setNegotiatedIkeP1Proposal(new IkePhase1Proposal("test_ike_proposal"));
  _ipsecSessionBuilder.setNegotiatedIkeP1Key(new IkePhase1Key());
  _ipsecSessionBuilder.setNegotiatedIpsecP2Proposal(new IpsecPhase2Proposal());
  _graph.putEdgeValue(
      new IpsecPeerConfigId(INITIATOR_IPSEC_PEER_CONFIG, INITIATOR_HOST_NAME),
      new IpsecPeerConfigId(RESPONDER_IPSEC_PEER_CONFIG, RESPONDER_HOST_NAME),
      _ipsecSessionBuilder.build());
  Multiset<IpsecSessionInfo> ipsecSessionInfos =
      rawAnswer(
          _networkConfigurations,
          _graph,
          ImmutableSet.of(INITIATOR_HOST_NAME),
          ImmutableSet.of(RESPONDER_HOST_NAME));

  // answer should have exactly one row
  assertThat(ipsecSessionInfos, hasSize(1));

  assertThat(
      ipsecSessionInfos.iterator().next(),
      hasIpsecSessionStatus(equalTo(IPSEC_SESSION_ESTABLISHED)));
}
 
Example 17
Source Project: batfish   Source File: IpsecSessionStatusAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateRowsIpsec2Fail() {
  // IPSecSession does not have IPSec phase 2 proposal set
  _ipsecSessionBuilder.setNegotiatedIkeP1Proposal(new IkePhase1Proposal("test_ike_proposal"));
  _ipsecSessionBuilder.setNegotiatedIkeP1Key(new IkePhase1Key());
  _graph.putEdgeValue(
      new IpsecPeerConfigId(INITIATOR_IPSEC_PEER_CONFIG, INITIATOR_HOST_NAME),
      new IpsecPeerConfigId(RESPONDER_IPSEC_PEER_CONFIG, RESPONDER_HOST_NAME),
      _ipsecSessionBuilder.build());
  Multiset<IpsecSessionInfo> ipsecSessionInfos =
      rawAnswer(
          _networkConfigurations,
          _graph,
          ImmutableSet.of(INITIATOR_HOST_NAME),
          ImmutableSet.of(RESPONDER_HOST_NAME));

  // answer should have exactly one row
  assertThat(ipsecSessionInfos, hasSize(1));

  assertThat(
      ipsecSessionInfos.iterator().next(), hasIpsecSessionStatus(equalTo(IPSEC_PHASE2_FAILED)));
}
 
Example 18
Source Project: pyramid   Source File: NgramEnumerator.java    License: Apache License 2.0 6 votes vote down vote up
public static Multiset<Ngram> gatherNgram(ESIndex index, String[] ids, NgramTemplate template, int minDF){
    Multiset<Ngram> multiset = ConcurrentHashMultiset.create();
    String field = template.getField();
    Arrays.stream(ids).parallel().forEach(id -> {
        Map<Integer,String> termVector = index.getTermVectorFromIndex(field, id);
        add(termVector,multiset,template);
    });
    Multiset<Ngram> filtered = ConcurrentHashMultiset.create();
    for (Multiset.Entry entry: multiset.entrySet()){
        Ngram ngram = (Ngram)entry.getElement();
        int count = entry.getCount();
        if (count>=minDF){
            filtered.add(ngram,count);
        }
    }
    return filtered;
}
 
Example 19
/**
 * Predict the max-likelihood tokens given the ngrams.
 * 
 * @param ngrams
 * @param alternatives
 * @return
 */
@Override
public SortedSet<Renaming> calculateScores(
		final Multiset<NGram<String>> ngrams,
		final Set<String> alternatives, final Scope scope) {
	final SortedSet<Renaming> suggestions = Sets.newTreeSet();

	for (final String alternative : alternatives) {
		double score = 0;
		for (final NGram<String> ngram : ngrams) {
			score += DoubleMath.log2(getNgramLM().getProbabilityFor(
					NGram.substituteTokenWith(ngram, WILDCARD_TOKEN,
							alternative)));
		}
		suggestions.add(new Renaming(alternative, -score, 1, null));
	}
	return suggestions;
}
 
Example 20
Source Project: spotbugs   Source File: Guava.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@ExpectWarning(value="GC", num=4)
public static void testMultiset(Multiset<String> ms) {
    ms.contains(1);
    ms.count(1);
    ms.remove(1);
    ms.remove(1, 2);
}
 
Example 21
Source Project: spotbugs   Source File: Guava.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@NoWarning("GC")
public static void testMultisetOK(Multiset<String> ms) {
    ms.contains("x");
    ms.count("x");
    ms.remove("x");
    ms.remove("x", 2);
}
 
Example 22
Source Project: presto   Source File: TestJdbcQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static Multiset<List<Object>> read(ResultSet resultSet)
        throws SQLException
{
    ImmutableMultiset.Builder<List<Object>> result = ImmutableMultiset.builder();
    while (resultSet.next()) {
        ImmutableList.Builder<Object> row = ImmutableList.builder();
        for (int column = 1; column <= resultSet.getMetaData().getColumnCount(); column++) {
            row.add(resultSet.getObject(column));
        }
        result.add(row.build());
    }
    return result.build();
}
 
Example 23
Source Project: gef   Source File: ObservableMultisetWrapper.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean add(E element) {
	Multiset<E> previousContents = delegateCopy();
	boolean changed = super.add(element);
	if (changed) {
		helper.fireValueChangedEvent(
				new MultisetListenerHelper.AtomicChange<>(this,
						previousContents,
						new ElementarySubChange<>(element, 0, 1)));
	}
	return changed;
}
 
Example 24
Source Project: gef   Source File: ObservableMultisetTests.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void add() {
	// prepare backup multiset
	Multiset<Integer> backupMultiset = HashMultiset.create();
	check(observable, backupMultiset);

	registerListeners();

	// add a single value
	invalidationListener.expect(1);
	multisetChangeListener.addAtomicExpectation();
	multisetChangeListener.addElementaryExpection(1, 0, 1);
	assertEquals(backupMultiset.add(1), observable.add(1));
	check(observable, backupMultiset);
	checkListeners();

	// add a second occurrence of the same value
	invalidationListener.expect(1);
	multisetChangeListener.addAtomicExpectation();
	multisetChangeListener.addElementaryExpection(1, 0, 1);
	assertEquals(backupMultiset.add(1), observable.add(1));
	check(observable, backupMultiset);
	checkListeners();

	// add a different value
	invalidationListener.expect(1);
	multisetChangeListener.addAtomicExpectation();
	multisetChangeListener.addElementaryExpection(2, 0, 1);
	assertEquals(backupMultiset.add(2), observable.add(2));
	check(observable, backupMultiset);
	checkListeners();
}
 
Example 25
Source Project: batfish   Source File: FilterLineReachabilityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIpWildcards() {
  // First line accepts src IPs 1.2.3.4/30
  // Second line accepts src IPs 1.2.3.4/32
  List<AclLine> lines =
      ImmutableList.of(
          ExprAclLine.acceptingHeaderSpace(
              HeaderSpace.builder()
                  .setSrcIps(
                      IpWildcard.create(Prefix.create(Ip.parse("1.2.3.4"), 30)).toIpSpace())
                  .build()),
          ExprAclLine.acceptingHeaderSpace(
              HeaderSpace.builder()
                  .setSrcIps(IpWildcard.create(Ip.parse("1.2.3.4").toPrefix()).toIpSpace())
                  .build()),
          ExprAclLine.acceptingHeaderSpace(
              HeaderSpace.builder()
                  .setSrcIps(
                      IpWildcard.create(Prefix.create(Ip.parse("1.2.3.4"), 28)).toIpSpace())
                  .build()));
  _aclb.setLines(lines).setName("acl").build();
  List<String> lineNames = lines.stream().map(Object::toString).collect(Collectors.toList());

  TableAnswerElement answer = answer(new FilterLineReachabilityQuestion());

  // Construct the expected result. First line should block second.
  Multiset<Row> expected =
      ImmutableMultiset.of(
          Row.builder(COLUMN_METADATA)
              .put(COL_SOURCES, ImmutableList.of(_c1.getHostname() + ": acl"))
              .put(COL_UNREACHABLE_LINE, lineNames.get(1))
              .put(COL_UNREACHABLE_LINE_ACTION, LineAction.PERMIT)
              .put(COL_BLOCKING_LINES, ImmutableList.of(lineNames.get(0)))
              .put(COL_DIFF_ACTION, false)
              .put(COL_REASON, BLOCKING_LINES)
              .build());
  assertThat(answer.getRows().getData(), equalTo(expected));
}
 
Example 26
Source Project: angelix   Source File: Main.java    License: MIT License 5 votes vote down vote up
private static Multiset<Node> selectComponents(Expression expression, Set<ProgramVariable> contextVariables) {
    Multiset<Node> components = HashMultiset.create();

    components.addAll(expression.getAllComponents());
    components.addAll(contextVariables);

    components.add(Library.AND);
    components.add(Library.OR);
    components.add(Library.NOT);

    components.add(Library.LE);
    components.add(Library.LT);
    components.add(Library.GT);
    components.add(Library.GE);
    components.add(Library.EQ);
    components.add(Library.NEQ);

    components.add(Library.ADD);
    components.add(Library.SUB);
    components.add(Library.MINUS);

    components.add(Library.ID(IntType.TYPE));
    components.add(Library.ID(BoolType.TYPE));

    components.add(Parameter.mkInt("parameter"));

    return components;
}
 
Example 27
@Override
public boolean addInEdge(E edge, N node) {
  if (super.addInEdge(edge, node)) {
    Multiset<N> predecessors = getReference(predecessorsReference);
    if (predecessors != null) {
      checkState(predecessors.add(node));
    }
    return true;
  }
  return false;
}
 
Example 28
@Test
public void most_frequent_char_guava() throws IOException {

	Multiset<String> frequentCharacters = HashMultiset.create(Splitter
			.fixedLength(1).split(sentence.toLowerCase()));

	for (Entry<String> item : frequentCharacters.entrySet()) {
		System.out.println(item.getElement() + ":" + item.getCount());
	}

	assertEquals(7, frequentCharacters.count("e"), 0);
}
 
Example 29
@Override
public N removeOutEdge(Object edge) {
  N node = super.removeOutEdge(edge);
  if (node != null) {
    Multiset<N> successors = getReference(successorsReference);
    if (successors != null) {
      checkState(successors.remove(node));
    }
  }
  return node;
}
 
Example 30
Source Project: angelix   Source File: TestPatchSynthesis.java    License: MIT License 5 votes vote down vote up
@Test
public void testConditional() {
    Multiset<Node> components = HashMultiset.create();
    components.add(x, 2);
    components.add(y, 2);
    components.add(Library.GT);
    components.add(Library.SUB);

    ArrayList<TestCase> testSuite = new ArrayList<>();
    Map<ProgramVariable, Node> assignment1 = new HashMap<>();
    assignment1.put(x, IntConst.of(2));
    assignment1.put(y, IntConst.of(1));
    testSuite.add(TestCase.ofAssignment(assignment1, IntConst.of(2)));

    Map<ProgramVariable, Node> assignment2 = new HashMap<>();
    assignment2.put(x, IntConst.of(1));
    assignment2.put(y, IntConst.of(2));
    testSuite.add(TestCase.ofAssignment(assignment2, IntConst.of(2)));

    Expression original = Expression.leaf(x);

    Optional<Pair<Expression, Map<Parameter, Constant>>> result =
            synthesizer.repair(original, testSuite, components, SynthesisLevel.CONDITIONAL);
    assertTrue(result.isPresent());
    Node node = result.get().getLeft().getSemantics(result.get().getRight());
    Assert.assertEquals(new ITE(new Greater(x, y), x, y), node);
}