com.google.common.collect.Multiset Java Examples
The following examples show how to use
com.google.common.collect.Multiset.
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: SlotMachineSimulation.java From levelup-java-exercises with Apache License 2.0 | 8 votes |
/** * 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 #2
Source File: MultisetExample.java From levelup-java-examples with Apache License 2.0 | 7 votes |
@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 #3
Source File: LevelCalcByChunk.java From askyblock with GNU General Public License v2.0 | 6 votes |
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 #4
Source File: IpsecSessionStatusAnswererTest.java From batfish with Apache License 2.0 | 6 votes |
@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 #5
Source File: IpsecSessionStatusAnswererTest.java From batfish with Apache License 2.0 | 6 votes |
@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 #6
Source File: NgramEnumerator.java From pyramid with Apache License 2.0 | 6 votes |
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 #7
Source File: IpsecSessionStatusAnswererTest.java From batfish with Apache License 2.0 | 6 votes |
@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 #8
Source File: VinSamplerTest.java From log-synth with Apache License 2.0 | 6 votes |
@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 #9
Source File: FormattingRenamings.java From naturalize with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * 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 #10
Source File: TracerouteAnswererTest.java From batfish with Apache License 2.0 | 6 votes |
@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 #11
Source File: TestTreeBoundedSynthesis.java From angelix with MIT License | 6 votes |
@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 File: SwitchedVlanPropertiesAnswerer.java From batfish with Apache License 2.0 | 6 votes |
/** * 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 #13
Source File: Word2VecTrainer.java From Word2VecJava with MIT License | 6 votes |
/** @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 #14
Source File: CorpusAnalysis.java From tac-kbp-eal with MIT License | 6 votes |
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 #15
Source File: TrainsModel.java From Rails with GNU General Public License v2.0 | 6 votes |
/** * 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 #16
Source File: TagDict.java From EasySRL with Apache License 2.0 | 6 votes |
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 #17
Source File: TagDict.java From EasySRL with Apache License 2.0 | 6 votes |
/** * 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 #18
Source File: ObservableMultisetWrapper.java From gef with Eclipse Public License 2.0 | 6 votes |
@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 #19
Source File: JavaInputAstVisitor.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
/** * 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 #20
Source File: AbstractAtomicMultimapService.java From atomix with Apache License 2.0 | 5 votes |
@Override public IteratorBatch<Multiset.Entry<byte[]>> iterateValuesSet() { IteratorContext iterator = new IteratorContext(getCurrentSession().sessionId().id()); if (!iterator.iterator.hasNext()) { return null; } long iteratorId = getCurrentIndex(); entryIterators.put(iteratorId, iterator); IteratorBatch<Multiset.Entry<byte[]>> batch = nextValuesSet(iteratorId, 0); if (batch.complete()) { entryIterators.remove(iteratorId); } return batch; }
Example #21
Source File: EdgesAnswerer.java From batfish with Apache License 2.0 | 5 votes |
@VisibleForTesting static Multiset<Row> getEigrpEdges( Set<String> includeNodes, Set<String> includeRemoteNodes, EigrpTopology eigrpTopology) { return eigrpTopology.getNetwork().edges().stream() .filter( eigrpEdge -> includeNodes.contains(eigrpEdge.getNode1().getHostname()) && includeRemoteNodes.contains(eigrpEdge.getNode2().getHostname())) .map(EdgesAnswerer::eigrpEdgeToRow) .collect(Collectors.toCollection(HashMultiset::create)); }
Example #22
Source File: Transaction.java From api-mining with GNU General Public License v3.0 | 5 votes |
public void initializeCachedSequences(final Multiset<Sequence> singletons, final long noTransactions) { cachedSequences = new HashMap<>(); for (final com.google.common.collect.Multiset.Entry<Sequence> entry : singletons.entrySet()) { if (this.contains(entry.getElement())) cachedSequences.put(entry.getElement(), entry.getCount() / (double) noTransactions); } }
Example #23
Source File: TestTreeBoundedSynthesis.java From angelix with MIT License | 5 votes |
@Test public void testForbiddenChoice() { Multiset<Node> components = HashMultiset.create(); components.add(x); components.add(y); components.add(Library.ADD); ArrayList<TestCase> testSuite = new ArrayList<>(); Map<ProgramVariable, Node> assignment1 = new HashMap<>(); assignment1.put(x, IntConst.of(1)); 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(3))); List<Expression> forbidden = new ArrayList<>(); Map<Hole, Expression> args = new HashMap<>(); args.put((Hole) Library.ADD.getLeft(), Expression.leaf(x)); args.put((Hole) Library.ADD.getRight(), Expression.leaf(y)); forbidden.add(Expression.app(Library.ADD, args)); Synthesis synthesizerWithForbidden = new Synthesis(new BoundedShape(2, forbidden), new TreeBoundedEncoder(false)); Optional<Pair<Expression, Map<Parameter, Constant>>> result = synthesizerWithForbidden.synthesize(testSuite, components); assertTrue(result.isPresent()); Node node = result.get().getLeft().getSemantics(result.get().getRight()); assertEquals(node, new Add(y, x)); }
Example #24
Source File: MultisetMutateMethodTest.java From FreeBuilder with Apache License 2.0 | 5 votes |
public MultisetMutateMethodTest( ElementFactory element, boolean checkedAndInterned, NamingConvention convention, FeatureSet features) { this.element = element; this.checked = checkedAndInterned; this.interned = checkedAndInterned; this.convention = convention; this.features = features; dataType = SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public interface DataType {") .addLine(" %s<%s> %s;", Multiset.class, element.type(), convention.get("properties")) .addLine("") .addLine(" class Builder extends DataType_Builder {"); if (checkedAndInterned) { dataType .addLine(" @Override public Builder setCountOfProperties(%s element, int count) {", element.unwrappedType()) .addLine(" %s.checkArgument(%s, \"%s\");", Preconditions.class, element.validation(), element.errorMessage()) .addLine(" return super.setCountOfProperties(%s, count);", element.intern("element")) .addLine(" }"); } dataType .addLine(" }") .addLine("}"); }
Example #25
Source File: RoutesAnswererTest.java From batfish with Apache License 2.0 | 5 votes |
@Test public void testHasVrfFiltering() { SortedMap<String, SortedMap<String, GenericRib<AbstractRouteDecorator>>> ribs = ImmutableSortedMap.of( "n1", ImmutableSortedMap.of( Configuration.DEFAULT_VRF_NAME, new MockRib<>( ImmutableSet.of( StaticRoute.builder() .setAdministrativeCost(1) .setNetwork(Prefix.parse("1.1.1.0/24")) .setNextHopInterface("Null") .build())), "notDefaultVrf", new MockRib<>( ImmutableSet.of( StaticRoute.builder() .setNetwork(Prefix.parse("2.2.2.0/24")) .setNextHopInterface("Null") .setAdministrativeCost(1) .build())))); Multiset<Row> actual = getMainRibRoutes( ribs, ImmutableSet.of("n1"), null, RoutingProtocolSpecifier.ALL_PROTOCOLS_SPECIFIER, "^not.*", null); assertThat(actual, hasSize(1)); assertThat( actual.iterator().next().getPrefix(COL_NETWORK), equalTo(Prefix.parse("2.2.2.0/24"))); }
Example #26
Source File: TracerouteAnswerer.java From batfish with Apache License 2.0 | 5 votes |
@Override public AnswerElement answerDiff(NetworkSnapshot snapshot, NetworkSnapshot reference) { TracerouteQuestion q = ((TracerouteQuestion) _question); Map<Flow, List<Trace>> baseFlowTraces = getTraces(snapshot, q); Map<Flow, List<Trace>> deltaFlowTraces = getTraces(reference, q); Multiset<Row> rows = diffFlowTracesToRows(baseFlowTraces, deltaFlowTraces, q.getMaxTraces()); TableAnswerElement table = new TableAnswerElement(metadata(true)); table.postProcessAnswer(_question, rows); return table; }
Example #27
Source File: MinRegionsResourcePlacementStrategy.java From bboxdb with Apache License 2.0 | 5 votes |
@Override protected double calculateUsageFactor(Multiset<BBoxDBInstance> systemUsage, BBoxDBInstance distributedInstance) { final int usageCount = systemUsage.count(distributedInstance); if(usageCount == 0) { return 0; } // Lower utilization is preferred by the algorithm return (1.0 / usageCount); }
Example #28
Source File: EMStep.java From sequence-mining with GNU General Public License v3.0 | 5 votes |
/** EM-step for hard EM */ static Table<Sequence, Integer, Double> hardEMStep(final List<Transaction> transactions, final InferenceAlgorithm inferenceAlgorithm) { final double noTransactions = transactions.size(); // E-step final Map<Multiset.Entry<Sequence>, Long> coveringWithCounts = transactions.parallelStream().map(t -> { final Multiset<Sequence> covering = inferenceAlgorithm.infer(t); t.setCachedCovering(covering); return covering.entrySet(); }).flatMap(Set::stream).collect(groupingBy(identity(), counting())); // M-step final Table<Sequence, Integer, Double> newSequences = coveringWithCounts.entrySet().parallelStream().collect( HashBasedTable::create, (t, e) -> t.put(e.getKey().getElement(), e.getKey().getCount(), e.getValue() / noTransactions), Table::putAll); newSequences.rowKeySet().parallelStream().forEach(seq -> { // Pad with zero counts for non-occurrences final int maxOccur = Collections.max(newSequences.row(seq).keySet()); for (int occur = 1; occur <= maxOccur; occur++) { if (!newSequences.contains(seq, occur)) newSequences.put(seq, occur, 0.); } // Add probabilities for zero occurrences double rowSum = 0; for (final Double count : newSequences.row(seq).values()) rowSum += count; newSequences.put(seq, 0, 1 - rowSum); }); // Update cached sequences transactions.parallelStream().forEach(t -> t.updateCachedSequences(newSequences)); return newSequences; }
Example #29
Source File: Guava.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
@NoWarning("GC") public static void testMultisetOK(Multiset<String> ms) { ms.contains("x"); ms.count("x"); ms.remove("x"); ms.remove("x", 2); }
Example #30
Source File: SsnSamplerTest.java From log-synth with Apache License 2.0 | 5 votes |
@Test public void testSsns() throws IOException { SchemaSampler s = new SchemaSampler(Resources.asCharSource(Resources.getResource("schema019.json"), Charsets.UTF_8).read()); JsonNode v = s.sample(); // regression test given that we specify the seed assertEquals("573-87-1992", v.get("z").get("ssn").asText()); Multiset<String> type1 = HashMultiset.create(); Multiset<String> type2 = HashMultiset.create(); Multiset<String> state1 = HashMultiset.create(); Multiset<String> state2 = HashMultiset.create(); String legalSsn = "\\d\\d\\d-\\d\\d-\\d\\d\\d\\d"; for (int i = 0; i < N; i++) { v = s.sample(); type1.add(v.get("z").get("type").asText()); type2.add(v.get("zLimited").get("type").asText()); state1.add(v.get("z").get("state").asText()); state2.add(v.get("zLimited").get("state").asText()); assertTrue(String.format("Bad format for SSN: %s", v.get("z").get("ssn")), v.get("z").get("ssn").asText().matches(legalSsn)); assertTrue(v.get("zFlat").asText().matches(legalSsn)); } assertEquals(1, type1.elementSet().size()); assertEquals(2, type2.elementSet().size()); assertEquals(52, state1.elementSet().size()); assertEquals(54, state2.elementSet().size()); }