Java 类com.google.common.collect.HashMultiset 实例源码

项目:GitHub    文件:ValueTypeComposer.java   
private void checkAttributeNamesForDuplicates(ValueType type, Protoclass protoclass) {
  if (!type.attributes.isEmpty()) {
    Multiset<String> attributeNames = HashMultiset.create(type.attributes.size());
    for (ValueAttribute attribute : type.attributes) {
      attributeNames.add(attribute.name());
    }

    List<String> duplicates = Lists.newArrayList();
    for (Multiset.Entry<String> entry : attributeNames.entrySet()) {
      if (entry.getCount() > 1) {
        duplicates.add(entry.getElement());
      }
    }

    if (!duplicates.isEmpty()) {
      protoclass.report()
          .error("Duplicate attribute names %s. You should check if correct @Value.Style applied",
              duplicates);
    }
  }
}
项目:minebox    文件:SiaSeedServiceTest.java   
@Test
    public void getSiaSeed() throws Exception {
        final SiaSeedService siaSeedService = new SiaSeedService(new StaticEncyptionKeyProvider("123"));
//        final List<String> strings = siaSeedService.buildSiaSeed("123");
        final Multiset<Long> counts;
        counts = HashMultiset.create();
        for (int i = 0; i < 100000; i++) {
            final String secretKey = "abc123782567825784__" + i;
            final List<String> words = siaSeedService.buildSiaSeed(secretKey);
            final String wordsList = Joiner.on(" ").join(words);
            final String errrorMessage = "secret produced unexpected length: " + secretKey + " words: " + wordsList;
            counts.add((long) words.size());
//            Assert.assertEquals(errrorMessage, 29, words.size());

        }
        counts.forEachEntry((length, count) -> System.out.println(length + " occurred " + count + " times"));
    }
项目:empiria.player    文件:ExpressionSetsFinderJUnitTest.java   
@Test
public void shouldUpdateExpressionSetsInBean() throws Exception {
    // given
    ExpressionBean expression = new ExpressionBean();

    expression.setTemplate("'a'+'b'='c'");
    Response responseA = new ResponseBuilder().withIdentifier("a").withCorrectAnswers("1").build();
    expression.getResponses().add(responseA);
    Response responseB = new ResponseBuilder().withIdentifier("b").withCorrectAnswers("2").build();
    expression.getResponses().add(responseB);
    Response responseC = new ResponseBuilder().withIdentifier("c").withCorrectAnswers("3").build();
    expression.getResponses().add(responseC);

    // when
    expressionSetsFinder.updateResponsesSetsInExpression(expression);

    Multiset<Multiset<String>> corectResponsesSets = expression.getCorectResponses();
    assertEquals(3, corectResponsesSets.size());
    assertTrue(corectResponsesSets.contains(HashMultiset.create(Lists.newArrayList("3"))));
    assertTrue(corectResponsesSets.contains(HashMultiset.create(Lists.newArrayList("1", "2"))));
    assertTrue(corectResponsesSets.contains(HashMultiset.create(Lists.newArrayList("1", "2", "3"))));
}
项目:empiria.player    文件:CommutationEvaluatorJUnitTest.java   
@Test
public void evaluateCorrect() {
    // given
    ExpressionBean bean = new ExpressionBean();

    List<Response> responses = Lists.newArrayList(correctResponse(), correctResponse(), correctResponse(), correctResponse(), correctResponse());
    bean.setTemplate("'0'+'2'+'3'='1'+'4'");
    bean.getResponses().addAll(responses);

    Multiset<Multiset<String>> correctAnswerMultiSet = HashMultiset.create(Lists.<Multiset<String>>newArrayList(
            HashMultiset.create(Lists.newArrayList("answer_1", "answer_4")),
            HashMultiset.create(Lists.newArrayList("answer_0", "answer_2", "answer_3")),
            HashMultiset.create(Lists.newArrayList("answer_0", "answer_2", "answer_3", "answer_1", "answer_4"))));
    bean.setCorectResponses(correctAnswerMultiSet);

    // when
    boolean result = testObj.evaluate(bean);

    // then
    assertThat(result, equalTo(true));
}
项目:empiria.player    文件:CommutationEvaluatorJUnitTest.java   
@Test
public void evaluateCorrect_commutated() {
    // given
    ExpressionBean bean = new ExpressionBean();

    List<Response> responses = Lists.newArrayList(response(0, 3), response(1, 4), response(2, 0), response(3, 2), (response(4, 1)));
    bean.setTemplate("'0'+'2'+'3'='1'+'4'");
    bean.getResponses().addAll(responses);

    Multiset<Multiset<String>> correctAnswerMultiSet = HashMultiset.create(Lists.<Multiset<String>>newArrayList(
            HashMultiset.<String>create(Lists.newArrayList("answer_1", "answer_4")),
            HashMultiset.<String>create(Lists.newArrayList("answer_0", "answer_2", "answer_3")),
            HashMultiset.<String>create(Lists.newArrayList("answer_0", "answer_2", "answer_3", "answer_1", "answer_4"))));
    bean.setCorectResponses(correctAnswerMultiSet);

    // when
    boolean result = testObj.evaluate(bean);

    // then
    assertThat(result, equalTo(true));
}
项目:empiria.player    文件:CommutationEvaluatorJUnitTest.java   
@Test
public void evaluateCorrect_commutated_equalSignInGap() {
    // given
    ExpressionBean bean = new ExpressionBean();

    List<Response> responses = Lists.newArrayList(response("=", "2", "id_equal"), response("1", "5", "id1"), response("5", "3", "id5"),
            response("3", "1", "id3"), (response("2", "=", "id2")));
    bean.setTemplate("'id1'+'id2'+'id3''id_equal'+'id5'");
    bean.getResponses().addAll(responses);

    Multiset<Multiset<String>> correctAnswerMultiSet = HashMultiset.create(Lists.<Multiset<String>>newArrayList(
            HashMultiset.create(Lists.newArrayList("5")), HashMultiset.create(Lists.newArrayList("1", "2", "3")),
            HashMultiset.create(Lists.newArrayList("1", "2", "3", "=", "5"))));
    bean.setCorectResponses(correctAnswerMultiSet);

    // when
    boolean result = testObj.evaluate(bean);

    // then
    assertThat(result, equalTo(true));
}
项目:empiria.player    文件:CommutationEvaluatorJUnitTest.java   
@Test
public void evaluateCorrectWithCharsConversionAdapter_commutated_equalSignInGap() {
    // given
    ExpressionBean bean = new ExpressionBean();

    List<Response> responses = Lists.newArrayList(response("=", "=", "id_equal"), response("/", ":", "id_oper"), response("15.1", "15,1", "id1"),
            response("5,1", "5.1", "id2"), response("2", "2", "id3"), response("12,5", "12,5", "id5"));
    bean.setTemplate("'id1'-'id2''id_oper''id3''id_equal''id5'");
    bean.getResponses().addAll(responses);

    Multiset<Multiset<String>> correctAnswerMultiSet = HashMultiset.create(Lists.<Multiset<String>>newArrayList(
            HashMultiset.create(Lists.newArrayList("12.5")), HashMultiset.create(Lists.newArrayList("15.1", "5,1", "/", "2")),
            HashMultiset.create(Lists.newArrayList("15.1", "5,1", "/", "2", "=", "12.5"))));
    bean.setCorectResponses(correctAnswerMultiSet);

    // when
    boolean result = testObj.evaluate(bean);

    // then
    assertThat(result, equalTo(true));
}
项目:empiria.player    文件:CommutationEvaluatorJUnitTest.java   
@Test
public void evaluateWrong_someWrongs() {
    // given
    ExpressionBean bean = new ExpressionBean();
    List<Response> responses = Lists.newArrayList(correctResponse(), correctResponse(), correctResponse(), correctResponse(), wrongResponse());
    bean.setTemplate("'0'+'2'+'3'='1'+'4'");
    bean.getResponses().addAll(responses);

    Multiset<Multiset<String>> correctAnswerMultiSet = HashMultiset.create(Lists.<Multiset<String>>newArrayList(
            HashMultiset.<String>create(Lists.newArrayList("answer_1", "answer_4")),
            HashMultiset.<String>create(Lists.newArrayList("answer_0", "answer_2", "answer_3")),
            HashMultiset.<String>create(Lists.newArrayList("answer_0", "answer_2", "answer_3", "answer_1", "answer_4"))));
    bean.setCorectResponses(correctAnswerMultiSet);

    // when
    boolean result = testObj.evaluate(bean);

    // then
    assertThat(result, equalTo(false));
}
项目:empiria.player    文件:CommutationEvaluatorJUnitTest.java   
@Test
public void evaluateWrong_commutated() {
    // given
    ExpressionBean bean = new ExpressionBean();
    List<Response> responses = Lists.newArrayList(response(0, 4), response(1, 3), response(2, 0), response(3, 2), (response(4, 1)));
    bean.setTemplate("'0'+'2'+'3'='1'+'4'");
    bean.getResponses().addAll(responses);

    Multiset<Multiset<String>> correctAnswerMultiSet = HashMultiset.create(Lists.<Multiset<String>>newArrayList(
            HashMultiset.<String>create(Lists.newArrayList("answer_1", "answer_4")),
            HashMultiset.<String>create(Lists.newArrayList("answer_0", "answer_2", "answer_3")),
            HashMultiset.<String>create(Lists.newArrayList("answer_0", "answer_2", "answer_3", "answer_1", "answer_4"))));
    bean.setCorectResponses(correctAnswerMultiSet);


    // when
    boolean result = testObj.evaluate(bean);

    // then
    assertThat(result, equalTo(false));
}
项目:ProjectAres    文件:EntropyTest.java   
@Test
public void intRange() throws Exception {
    Entropy e = new MutableEntropy(SEED);
    Range<Integer> range = Range.closedOpen(-5, 5);
    Multiset<Integer> distribution = HashMultiset.create();

    // Choose 1k values and check that they are in the range
    for(int i = 0; i < 10000; i++) {
        final int value = e.randomInt(range);
        assertContains(range, value);
        distribution.add(value);
        e.advance();
    }

    // Assert that each of the 10 values was chosen ~1000 times
    Ranges.forEach(range, value -> {
        assertEquals(1000D, distribution.count(value), 50D);
    });
}
项目:javaide    文件:JavaInputAstVisitor.java   
/**
 * 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;
}
项目:linkifier    文件:Tokenizers.java   
@Override
public Multiset<String> tokenizeToMultiset(String input) {

    // tokenizeToList is not reused here on purpose. Removing duplicate
    // words early means these don't have to be tokenized multiple
    // times. Increases performance.

    Multiset<String> tokens = HashMultiset.create(input.length());
    tokens.add(input);

    Multiset<String> newTokens = HashMultiset.create(input.length());
    for (Tokenizer t : tokenizers) {
        for (String token : tokens) {
            newTokens.addAll(t.tokenizeToList(token));
        }
        Multiset<String> swap = tokens;
        tokens = newTokens;
        newTokens = swap;
        newTokens.clear();
    }

    return tokens;
}
项目:bayou    文件:CFGFeature.java   
/**
 * Generate a subgraph of size k starting at node_id using bfs
 */
public Multiset<Integer> gen_subgraph(int k, boolean bfs) {
    Multiset<Integer> result = HashMultiset.create();
    CFGFeature.logger.debug("Generating subgraphs using BFS with k = {} ...", k);
    if(this.nodes.size() == 0) {
        CFGFeature.logger.debug("Empty body.");
        return result;
    }
    for (CFGNode node : this.nodes) {
        // System.out.println(node.node.toString());
        int code = this.gen_subgraph_helper(node, k, bfs);
        // System.out.println("code : " + code + "\n\n");
        result.add(code);
    }

    CFGFeature.logger.debug("Done generating CFG feature.");
    return result;
}
项目:tools    文件:SiaSeedServiceTest.java   
@Test
    public void getSiaSeed() throws Exception {
        final SiaSeedService siaSeedService = new SiaSeedService(new StaticEncyptionKeyProvider("123"));
//        final List<String> strings = siaSeedService.buildSiaSeed("123");
        final Multiset<Long> counts;
        counts = HashMultiset.create();
        for (int i = 0; i < 100000; i++) {
            final String secretKey = "abc123782567825784__" + i;
            final List<String> words = siaSeedService.buildSiaSeed(secretKey);
            final String wordsList = Joiner.on(" ").join(words);
            final String errrorMessage = "secret produced unexpected length: " + secretKey + " words: " + wordsList;
            counts.add((long) words.size());
//            Assert.assertEquals(errrorMessage, 29, words.size());

        }
        counts.forEachEntry((length, count) -> System.out.println(length + " occurred " + count + " times"));
    }
项目:Mastering-Mesos    文件:PendingTaskProcessor.java   
/**
 * Creates execution sequence for pending task groups by interleaving their unique occurrences.
 * For example: {G1, G1, G1, G2, G2} will be converted into {G1, G2, G1, G2, G1}.
 *
 * @param groups Multiset of task groups.
 * @return A task group execution sequence.
 */
private static List<TaskGroupKey> getPreemptionSequence(Multiset<TaskGroupKey> groups) {
  Multiset<TaskGroupKey> mutableGroups = HashMultiset.create(groups);
  List<TaskGroupKey> instructions = Lists.newLinkedList();
  Set<TaskGroupKey> keys = ImmutableSet.copyOf(groups.elementSet());
  while (!mutableGroups.isEmpty()) {
    for (TaskGroupKey key : keys) {
      if (mutableGroups.contains(key)) {
        instructions.add(key);
        mutableGroups.remove(key);
      }
    }
  }

  return instructions;
}
项目:twill    文件:ApplicationMasterService.java   
/**
 * Handling containers that are completed.
 */
private void handleCompleted(List<YarnContainerStatus> completedContainersStatuses) {
  Multiset<String> restartRunnables = HashMultiset.create();
  for (YarnContainerStatus status : completedContainersStatuses) {
    LOG.info("Container {} completed with {}:{}.",
             status.getContainerId(), status.getState(), status.getDiagnostics());
    runningContainers.handleCompleted(status, restartRunnables);
  }

  for (Multiset.Entry<String> entry : restartRunnables.entrySet()) {
    LOG.info("Re-request container for {} with {} instances.", entry.getElement(), entry.getCount());
    runnableContainerRequests.add(createRunnableContainerRequest(entry.getElement(),  entry.getCount()));
  }

  // For all runnables that needs to re-request for containers, update the expected count timestamp
  // so that the EventHandler would triggered with the right expiration timestamp.
  expectedContainers.updateRequestTime(restartRunnables.elementSet());
}
项目:metrics-aggregator-daemon    文件:UnorderedRecordEquality.java   
/**
 * Compare two <code>Record</code> instances ignoring the ordering of the
 * values in each metric.
 *
 * @param r1 First <code>Record</code> instance.
 * @param r2 Second <code>Record</code> instance.
 * @return True if and only if <code>Record</code> instances are equal
 * irregardless of the order of the values of each metric.
 */
public static boolean equals(final Record r1, final Record r2) {
    if (!r1.getTime().equals(r2.getTime())
            || !r1.getAnnotations().equals(r2.getAnnotations())) {
        return false;
    }

    for (final Map.Entry<String, ? extends Metric> entry : r1.getMetrics().entrySet()) {
        if (!r2.getMetrics().containsKey(entry.getKey())) {
            return false;
        }
        final Metric m1 = entry.getValue();
        final Metric m2 = r2.getMetrics().get(entry.getKey());
        if (!m1.getType().equals(m2.getType())) {
            return false;
        }

        final Multiset<Quantity> v1 = HashMultiset.create(m1.getValues());
        final Multiset<Quantity> v2 = HashMultiset.create(m2.getValues());
        if (!v1.equals(v2)) {
            return false;
        }
    }

    return true;
}
项目:opencensus-java    文件:TagContext.java   
/**
 * Returns true iff the other object is an instance of {@code TagContext} and contains the same
 * key-value pairs. Implementations are free to override this method to provide better
 * performance.
 */
@Override
public boolean equals(@Nullable Object other) {
  if (!(other instanceof TagContext)) {
    return false;
  }
  TagContext otherTags = (TagContext) other;
  Iterator<Tag> iter1 = getIterator();
  Iterator<Tag> iter2 = otherTags.getIterator();
  Multiset<Tag> tags1 =
      iter1 == null
          ? ImmutableMultiset.<Tag>of()
          : HashMultiset.create(Lists.<Tag>newArrayList(iter1));
  Multiset<Tag> tags2 =
      iter2 == null
          ? ImmutableMultiset.<Tag>of()
          : HashMultiset.create(Lists.<Tag>newArrayList(iter2));
  return tags1.equals(tags2);
}
项目:JEmAS    文件:BagOfWords2Vector_Processor.java   
/**
* Transforms bag-of-words representation of the document into an emotion vector representation.
* @param givenSet
* @return Instance of class VectorizationResult. This class contains both, the documentVector and the number of successfully attributed vectors (the number of words found in the lexicon).
* @throws IOException
*/   
VectorizationResult calculateDocumentVector(HashMultiset<String> givenSet, EmotionLexicon givenLexicon, Settings givenSettings) throws IOException{
 if (givenSettings.printIdentifiedTokens) System.out.println("\n\nIdentified tokens:\n");
 EmotionVector documentVector = new EmotionVector(0, 0, 0);
 int count=0;
    //Iterates over all entries of the Multiset. N interations for an entry of count N.
    for (String currentToken : givenSet) { 
        EmotionVector currentVector = givenLexicon.lookUp(currentToken);
        //if Stemmer is used, the look-up should also check for small letter word beginnings
        if (givenSettings.usedPreprocessing == Preprocessing.STEM && currentVector==null){
            currentToken = currentToken.substring(0, 1).toLowerCase() +currentToken.substring(1);
            currentVector=givenLexicon.lookUp(currentToken);
        }
        if (currentVector!=null){
        documentVector.addVector(currentVector);
        count++;
        if (givenSettings.printIdentifiedTokens) System.out.println(currentToken);
        }
    }
    return new VectorizationResult(documentVector, count);
}
项目:beam    文件:CompressedSourceTest.java   
/**
 * Test reading multiple files.
 */
@Test
public void testCompressedReadMultipleFiles() throws Exception {
  int numFiles = 3;
  String baseName = "test_input-";
  String filePattern = new File(tmpFolder.getRoot().toString(), baseName + "*").toString();
  List<Byte> expected = new ArrayList<>();

  for (int i = 0; i < numFiles; i++) {
    byte[] generated = generateInput(100);
    File tmpFile = tmpFolder.newFile(baseName + i);
    writeFile(tmpFile, generated, CompressionMode.GZIP);
    expected.addAll(Bytes.asList(generated));
  }

  CompressedSource<Byte> source =
      CompressedSource.from(new ByteSource(filePattern, 1))
          .withDecompression(CompressionMode.GZIP);
  List<Byte> actual = SourceTestUtils.readFromSource(source, PipelineOptionsFactory.create());
  assertEquals(HashMultiset.create(expected), HashMultiset.create(actual));
}
项目:turnus    文件:CommFreqMovesGenerator.java   
private List<Actor> sortDescendingByCommFreq(HashMultiset<Actor> commFreq) {
    final HashMultiset<Actor> unsortedCommFreq = commFreq;
    List<Actor> sortedActors = new ArrayList<Actor>(unsortedCommFreq.elementSet());
    Collections.sort(sortedActors, new Comparator<Actor>() {

        @Override
        public int compare(Actor a1, Actor a2) {
            if (unsortedCommFreq.count(a1) < unsortedCommFreq.count(a2)) {
                return 1;
            } else {
                return -1;
            }
        }

    });

    return sortedActors;

}
项目:turnus    文件:StepDataBox.java   
public StepDataBox(ProfiledStep step, boolean scheduledByFsm) {
    this.step = step;
    this.scheduledByFsm = scheduledByFsm;

    operators = HashMultiset.create();
    procedures = HashMultiset.create();
    stores = HashMultiset.create();
    loads = HashMultiset.create();
    producedTokens = HashMultiset.create();
    consumedTokens = HashMultiset.create();
    tokensProducers = new HashMap<>();
    procOperators = new HashMap<>();
    procProcedures = new HashMap<>();
    procStores = new HashMap<>();
    procLoads = new HashMap<>();
    proceduresStack = new ArrayDeque<Procedure>();
}
项目:turnus    文件:StepDataBox.java   
/**
 * Enter in a procedure
 * 
 * @param procedure
 */
public void logEnter(Procedure procedure) {
    // check if the procedure has been already called
    if (!procedures.contains(procedure)) {
        HashMultiset<Variable> readVars = HashMultiset.create();
        procLoads.put(procedure, readVars);
        HashMultiset<Variable> writeVars = HashMultiset.create();
        procStores.put(procedure, writeVars);
        HashMultiset<EOperator> opCalls = HashMultiset.create();
        procOperators.put(procedure, opCalls);
        HashMultiset<Procedure> procCalls = HashMultiset.create();
        procProcedures.put(procedure, procCalls);
    }
    procedures.add(procedure);

    if (!proceduresStack.isEmpty()) {
        procProcedures.get(proceduresStack.getLast()).add(procedure);
    }
    proceduresStack.addLast(procedure);
}
项目:turnus    文件:TraceEvaluator.java   
/**
 * Constructor. Create a new trace builder.
 * 
 * @param traceFile
 * @throws TurnusException
 */
public TraceEvaluator(Network network, File traceFile) throws TurnusException {
    try {
        writer = new TraceWriter(traceFile);
        writer.start();
    } catch (TurnusException e) {
        throw e;
    }

    this.network = network;

    lastSharedVarStore = new HashMap<>();
    lastSharedVarLoad = new HashMap<>();
    lastScheduledFsm = new HashMap<>();
    lastVarStore = HashBasedTable.create();
    lastVarLoad = HashBasedTable.create();
    lastPortWrite = HashBasedTable.create();
    lastPortRead = HashBasedTable.create();
    actionsFirings = HashMultiset.create();
    actionsIncomings = HashMultiset.create();
    actionsOutgoings = HashMultiset.create();
    dependenciesKind = HashMultiset.create();

}
项目:turnus    文件:SchedulerChecksCollector.java   
@Override
public void init() {
    checkedInLookUpMap = new HashMap<Actor, Integer>(); 
    checkedOutLookUpMap = new HashMap<Actor, Integer>();
    failedInLookUpMap = new HashMap<Actor, Integer>();  
    failedOutLookUpMap = new HashMap<Actor, Integer>();

    checkedPartitionCounters = HashMultiset.create();
    failedPartitionCounters = HashMultiset.create();

    checkedConditionsStatistics = new HashMap<Actor, SummaryStatistics>();
    failedConditionsStatistics = new HashMap<Actor, SummaryStatistics>();

    for (Actor actor : network.getActors()) {
        checkedInLookUpMap.put(actor, 0);
        checkedOutLookUpMap.put(actor, 0);
        failedInLookUpMap.put(actor, 0);
        failedOutLookUpMap.put(actor, 0);

        checkedConditionsStatistics.put(actor, new SummaryStatistics());
        failedConditionsStatistics.put(actor, new SummaryStatistics());
    }
}
项目:nomulus    文件:BaseDomainLabelList.java   
/**
 * Turns the list CSV data into a map of labels to parsed data of type R.
 *
 * @param lines the CSV file, line by line
 */
public ImmutableMap<String, R> parse(Iterable<String> lines) {
  Map<String, R> labelsToEntries = new HashMap<>();
  Multiset<String> duplicateLabels = HashMultiset.create();
  for (String line : lines) {
    R entry = createFromLine(line);
    if (entry == null) {
      continue;
    }
    String label = entry.getLabel();
    // Check if the label was already processed for this list (which is an error), and if so,
    // accumulate it so that a list of all duplicates can be thrown.
    if (labelsToEntries.containsKey(label)) {
      duplicateLabels.add(label, duplicateLabels.contains(label) ? 1 : 2);
    } else {
      labelsToEntries.put(label, entry);
    }
  }
  if (!duplicateLabels.isEmpty()) {
    throw new IllegalStateException(
        String.format(
            "List '%s' cannot contain duplicate labels. Dupes (with counts) were: %s",
            name, duplicateLabels));
  }
  return ImmutableMap.copyOf(labelsToEntries);
}
项目:intellij-ce-playground    文件:FindInProjectTask.java   
private static void logStats(Collection<VirtualFile> otherFiles, long start) {
  long time = System.currentTimeMillis() - start;

  final Multiset<String> stats = HashMultiset.create();
  for (VirtualFile file : otherFiles) {
    //noinspection StringToUpperCaseOrToLowerCaseWithoutLocale
    stats.add(StringUtil.notNullize(file.getExtension()).toLowerCase());
  }

  List<String> extensions = ContainerUtil.newArrayList(stats.elementSet());
  Collections.sort(extensions, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
      return stats.count(o2) - stats.count(o1);
    }
  });

  String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" +
                   "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" +
                   "Most frequent non-indexed file extensions: ";
  for (int i = 0; i < Math.min(10, extensions.size()); i++) {
    String extension = extensions.get(i);
    message += extension + "(" + stats.count(extension) + ") ";
  }
  LOG.info(message);
}
项目:intellij-ce-playground    文件:AttributesModelColorPaletteModel.java   
private void loadColors() {
  if (myResourceResolver == null) {
    myColorList = Collections.emptyList();
    return;
  }

  int rows = myModel.getRowCount();
  Multiset<Color> colorSet = HashMultiset.create();
  for (int i = 0; i < rows; i++) {
    if (myModel.getCellClass(i, 0) != Color.class) {
      continue;
    }

    EditedStyleItem item = (EditedStyleItem)myModel.getValueAt(i, 0);
    for (Color color : ResourceHelper.resolveMultipleColors(myResourceResolver, item.getItemResourceValue())) {
      myColorReferences.put(color, item);
      colorSet.add(color);
    }
  }

  myColorList = ImmutableList.copyOf(Multisets.copyHighestCountFirst(colorSet).elementSet());
}
项目:incubator-rya    文件:PipelineQueryIT.java   
@Test
public void testSingleStatementPattern() throws Exception {
    // Insert data
    insert(OWL.THING, RDF.TYPE, OWL.CLASS);
    insert(FOAF.PERSON, RDF.TYPE, OWL.CLASS, 1);
    insert(FOAF.PERSON, RDFS.SUBCLASSOF, OWL.THING);
    insert(VF.createURI("urn:Alice"), RDF.TYPE, FOAF.PERSON);
    dao.flush();
    // Define query and expected results
    final String query = "SELECT * WHERE {\n"
            + "  ?individual a ?type .\n"
            + "}";
    List<String> varNames = Arrays.asList("individual", "type");
    Multiset<BindingSet> expectedSolutions = HashMultiset.create();
    expectedSolutions.add(new ListBindingSet(varNames, OWL.THING, OWL.CLASS));
    expectedSolutions.add(new ListBindingSet(varNames, FOAF.PERSON, OWL.CLASS));
    expectedSolutions.add(new ListBindingSet(varNames, VF.createURI("urn:Alice"), FOAF.PERSON));
    // Execute pipeline and verify results
    testPipelineQuery(query, expectedSolutions);
}
项目:incubator-rya    文件:PipelineQueryIT.java   
@Test
public void testMultiConstruct() throws Exception {
    // Insert data
    URI alice = VF.createURI("urn:Alice");
    URI bob = VF.createURI("urn:Bob");
    URI eve = VF.createURI("urn:Eve");
    URI friend = VF.createURI("urn:friend");
    URI knows = VF.createURI("urn:knows");
    URI person = VF.createURI("urn:Person");
    insert(alice, friend, bob);
    insert(bob, knows, eve);
    insert(eve, knows, alice);
    // Define query and expected results
    final String query = "CONSTRUCT {\n"
            + "    ?x rdf:type owl:Thing .\n"
            + "    ?x rdf:type <urn:Person> .\n"
            + "} WHERE { ?x <urn:knows> ?y }";
    final Multiset<BindingSet> expected = HashMultiset.create();
    List<String> varNames = Arrays.asList("subject", "predicate", "object");
    expected.add(new ListBindingSet(varNames, bob, RDF.TYPE, OWL.THING));
    expected.add(new ListBindingSet(varNames, bob, RDF.TYPE, person));
    expected.add(new ListBindingSet(varNames, eve, RDF.TYPE, OWL.THING));
    expected.add(new ListBindingSet(varNames, eve, RDF.TYPE, person));
    // Test query
    testPipelineQuery(query, expected);
}
项目:incubator-rya    文件:SpinConstructRuleTest.java   
@Test
public void testGeneralConsequent() throws Exception {
    String text = "CONSTRUCT {\n"
            + "  ?x ?p2 ?y"
            + "} WHERE {\n"
            + "  ?x ?p1 ?y .\n"
            + "  ?p1 rdfs:subPropertyOf ?p2 .\n"
            + "}";
    ParsedGraphQuery query = (ParsedGraphQuery) PARSER.parseQuery(text, null);
    SpinConstructRule rule = new SpinConstructRule(OWL.THING, RL_PRP_SPO1, query);
    Multiset<StatementPattern> expectedAntecedents = HashMultiset.create(Arrays.asList(
            new StatementPattern(new Var("p1"), ac(RDFS.SUBPROPERTYOF), new Var("p2")),
            new StatementPattern(new Var("x"), new Var("p1"), new Var("y"))));
    Multiset<StatementPattern> expectedConsequents = HashMultiset.create(Arrays.asList(
            new StatementPattern(new Var("subject"), new Var("predicate"), new Var("object"))));
    Assert.assertEquals(expectedAntecedents, HashMultiset.create(rule.getAntecedentPatterns()));
    Assert.assertEquals(expectedConsequents, HashMultiset.create(rule.getConsequentPatterns()));
    Assert.assertFalse(rule.hasAnonymousConsequent());
    // Basic pattern matches
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("a"), new Var("b"), new Var("c"))));
    // Narrower patterns match (constants in place of variables)
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("x"), c(RDFS.SUBPROPERTYOF), c(OWL.THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), new Var("prop"), c(OWL.THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(FOAF.PERSON), c(RDFS.SUBCLASSOF), new Var("x"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), c(RDFS.SUBCLASSOF), c(FOAF.PERSON))));
}
项目:angelix    文件:TestTreeBoundedSynthesis.java   
@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());
}
项目:simple-failover-java    文件:WeightFailoverTest.java   
@Test
void testCommon() {
    List<String> original = Arrays.asList("1", "2", "3");
    Failover<String> failover = WeightFailover.newBuilder() //
            .checker(this::check, 1) //
            .build(original);
    Multiset<String> result = HashMultiset.create();
    Multiset<Integer> getCount = HashMultiset.create();
    for (int i = 0; i < 500; i++) {
        List<String> available = failover.getAvailable(2);
        assertTrue(available.size() <= 2);
        getCount.add(available.size());
        available.forEach(obj -> {
            assertNotNull(obj);
            if (doSomething(obj, failover)) {
                result.add(obj);
            }
        });
        sleepUninterruptibly(10, MILLISECONDS);
    }
    System.out.println(getCount);
    System.out.println(result);
}
项目:simple-failover-java    文件:WeightFailoverTest.java   
@Test
void testDown() {
    List<String> original = Arrays.asList("1", "2", "3");
    Failover<String> failover = WeightFailover.<String> newGenericBuilder() //
            .checker(it -> false, 1) //
            .onMinWeight(i -> System.out.println("onMin:" + i)) //
            .build(original);
    Multiset<String> result = HashMultiset.create();
    Multiset<Integer> getCount = HashMultiset.create();
    failover.down("1");
    for (int i = 0; i < 500; i++) {
        String available = failover.getOneAvailable();
        assertNotEquals(available, "1");
        sleepUninterruptibly(10, MILLISECONDS);
    }
    System.out.println(getCount);
    System.out.println(result);
}
项目:simple-failover-java    文件:WeightFailoverTest.java   
@Test
void testLarge() {
    Map<String, Integer> map = new HashMap<>();
    for (int i = 0; i < 108; i++) {
        map.put("i" + i, 32518);
    }
    for (int i = 0; i < 331; i++) {
        map.put("j" + i, 2652);
    }
    WeightFailover<String> failover = WeightFailover.<String> newGenericBuilder() //
            .checker(it -> true, 1) //
            .build(map);
    Multiset<String> counter = HashMultiset.create();
    for (int i = 0; i < 100000; i++) {
        String oneAvailable = failover.getOneAvailable();
        counter.add(oneAvailable.substring(0, 1));
    }
    System.out.println(counter);
}
项目:BeProductive    文件:BeProductive.java   
private void update() {
    ArrayList<UUID> onlinePlayers = new ArrayList<UUID>();
    for (Object obj : FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getPlayerList()) {
        EntityPlayerMP player = (EntityPlayerMP) obj;
        UUID uuid = player.getUniqueID();

        onlinePlayers.add(uuid);
        timeOnCount.add(uuid);

        //Kick players who are on too long
        if ((maxTimeOn.containsKey(uuid) && timeOnCount.count(uuid) > maxTimeOn.get(uuid)) || (maxTimeOnGlobal != 0 && timeOnCount.count(uuid) > maxTimeOnGlobal)) {
            rejoinTime.put(uuid, System.currentTimeMillis() + (breakTime.containsKey(uuid) ? breakTime.get(uuid) * 50 : breakTimeGlobal * 50));
            kickPlayerForTime(player);
            timeOnCount.remove(uuid, timeOnCount.count(uuid));
        }
    }

    //Decrease timeOnCount time for players that aren't online
    HashMultiset<UUID> uuids = HashMultiset.create();
    for (UUID entry : timeOnCount.elementSet()) {
        if (!onlinePlayers.contains(entry)) {
            uuids.add(entry);
        }
    }
    Multisets.removeOccurrences(timeOnCount, uuids);
}
项目:EasySRL    文件:TagDict.java   
private static Map<String, Collection<Category>> makeDict(final Multiset<String> wordCounts,
        final Map<String, Multiset<Category>> wordToCatToCount) {
    // Now, save off a sorted list of categories
    final Multiset<Category> countsForOtherWords = HashMultiset.create();

    final Map<String, Collection<Category>> result = new HashMap<>();
    for (final Entry<String> wordAndCount : wordCounts.entrySet()) {
        final Multiset<Category> countForCategory = wordToCatToCount.get(wordAndCount.getElement());
        if (wordAndCount.getCount() > MIN_OCCURENCES_OF_WORD) {
            // Frequent word
            addEntryForWord(countForCategory, result, wordAndCount.getElement());
        } else {
            // Group stats for all rare words together.

            for (final Entry<Category> catToCount : countForCategory.entrySet()) {
                countsForOtherWords.add(catToCount.getElement(), catToCount.getCount());
            }
        }
    }
    addEntryForWord(countsForOtherWords, result, OTHER_WORDS);

    return ImmutableMap.copyOf(result);
}
项目:angelix    文件:TestTreeBoundedSynthesis.java   
@Test
public void testForbiddenDoubleNegation() {
    Multiset<Node> components = HashMultiset.create();
    components.add(x);
    components.add(Library.MINUS, 2);
    components.add(Library.ADD);

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

    List<Expression> forbidden = new ArrayList<>();
    forbidden.add(Expression.leaf(x));

    Map<Hole, Expression> args = new HashMap<>();
    args.put((Hole) Library.MINUS.getArg(), Expression.leaf(x));
    Map<Hole, Expression> args2 = new HashMap<>();
    args2.put((Hole) Library.MINUS.getArg(), Expression.app(Library.MINUS, args));
    forbidden.add(Expression.app(Library.MINUS, args2));

    Synthesis synthesizerWithForbidden =
            new Synthesis(new BoundedShape(3, forbidden), new TreeBoundedEncoder());
    Optional<Pair<Expression, Map<Parameter, Constant>>> result = synthesizerWithForbidden.synthesize(testSuite, components);
    assertFalse(result.isPresent());
}
项目:java-smt    文件:SolverFormulaIOTest.java   
private void checkThatFunOnlyDeclaredOnce(String formDump) {
  Multiset<String> funDeclares = HashMultiset.create();

  for (String line : Splitter.on('\n').split(formDump)) {
    if (line.startsWith("(declare-fun ")) {
      funDeclares.add(line.replaceAll("\\s+", ""));
    }
  }

  // remove non-duplicates
  Iterator<Multiset.Entry<String>> it = funDeclares.entrySet().iterator();
  while (it.hasNext()) {
    if (it.next().getCount() <= 1) {
      it.remove();
    }
  }
  assertThat(funDeclares).named("duplicate function declarations").isEmpty();
}
项目:knowledgestore    文件:Root.java   
private void uiReportMentionValueOccurrences(final Map<String, Object> model,
        final URI entityID, @Nullable final URI property) throws Throwable {

    // Do nothing in case the entity ID is missing
    if (entityID == null || property == null) {
        return;
    }

    // Compute the # of occurrences of all the values of the given property in entity mentions
    final Multiset<Value> propertyValues = HashMultiset.create();
    for (final Record mention : getEntityMentions(entityID, Integer.MAX_VALUE, null)) {
        propertyValues.addAll(mention.get(property, Value.class));
    }

    // Render the table
    final Escaper esc = UrlEscapers.urlFormParameterEscaper();
    final String linkTemplate = "ui?action=entity-mentions&entity="
            + esc.escape(entityID.stringValue()) + "&property="
            + esc.escape(Data.toString(property, Data.getNamespaceMap()))
            + "&value=${element}";
    model.put("valueOccurrencesTable", RenderUtils.renderMultisetTable(new StringBuilder(),
            propertyValues, "Property value", "# Mentions", linkTemplate));
}