下面列出了怎么用com.google.common.collect.Multiset的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
@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());
}
/**
* 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;
}
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);
}
/**
* 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);
}
@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;
}
/**
* 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;
}
/**
* 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;
}
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);
}
/**
* 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();
}
@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());
}
/** @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;
}
}
)
)
);
}
@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)));
}
@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);
}
@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)));
}
@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)));
}
@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)));
}
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;
}
/**
* 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;
}
@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);
}
@NoWarning("GC")
public static void testMultisetOK(Multiset<String> ms) {
ms.contains("x");
ms.count("x");
ms.remove("x");
ms.remove("x", 2);
}
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();
}
@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;
}
@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();
}
@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));
}
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;
}
@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;
}
@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);
}
@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;
}
@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);
}