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

The following are top voted examples for showing how to use com.google.common.collect.HashMultiset. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: ValueTypeComposer.java   View source code 6 votes vote down vote up
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);
    }
  }
}
 
Example 2
Project: minebox   File: SiaSeedServiceTest.java   View source code 6 votes vote down vote up
@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"));
    }
 
Example 3
Project: empiria.player   File: ExpressionSetsFinderJUnitTest.java   View source code 6 votes vote down vote up
@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"))));
}
 
Example 4
Project: empiria.player   File: CommutationEvaluatorJUnitTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 5
Project: empiria.player   File: CommutationEvaluatorJUnitTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 6
Project: empiria.player   File: CommutationEvaluatorJUnitTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 7
Project: empiria.player   File: CommutationEvaluatorJUnitTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 8
Project: empiria.player   File: CommutationEvaluatorJUnitTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 9
Project: empiria.player   File: CommutationEvaluatorJUnitTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 10
Project: ProjectAres   File: EntropyTest.java   View source code 6 votes vote down vote up
@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);
    });
}
 
Example 11
Project: javaide   File: JavaInputAstVisitor.java   View source code 6 votes vote down vote up
/**
 * 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 12
Project: linkifier   File: Tokenizers.java   View source code 6 votes vote down vote up
@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;
}
 
Example 13
Project: bayou   File: CFGFeature.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 14
Project: tools   File: SiaSeedServiceTest.java   View source code 6 votes vote down vote up
@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"));
    }
 
Example 15
Project: Mastering-Mesos   File: PendingTaskProcessor.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: twill   File: ApplicationMasterService.java   View source code 6 votes vote down vote up
/**
 * 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());
}
 
Example 17
Project: metrics-aggregator-daemon   File: UnorderedRecordEquality.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 18
Project: opencensus-java   File: TagContext.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 19
Project: JEmAS   File: BagOfWords2Vector_Processor.java   View source code 6 votes vote down vote up
/**
* 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);
}
 
Example 20
Project: beam   File: CompressedSourceTest.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 21
Project: turnus   File: CommFreqMovesGenerator.java   View source code 6 votes vote down vote up
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;

}
 
Example 22
Project: turnus   File: StepDataBox.java   View source code 6 votes vote down vote up
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>();
}
 
Example 23
Project: turnus   File: StepDataBox.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 24
Project: turnus   File: TraceEvaluator.java   View source code 6 votes vote down vote up
/**
 * 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();

}
 
Example 25
Project: turnus   File: SchedulerChecksCollector.java   View source code 6 votes vote down vote up
@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());
	}
}
 
Example 26
Project: nomulus   File: BaseDomainLabelList.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 27
Project: intellij-ce-playground   File: FindInProjectTask.java   View source code 6 votes vote down vote up
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);
}
 
Example 28
Project: intellij-ce-playground   File: AttributesModelColorPaletteModel.java   View source code 6 votes vote down vote up
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());
}
 
Example 29
Project: incubator-rya   File: PipelineQueryIT.java   View source code 6 votes vote down vote up
@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);
}
 
Example 30
Project: incubator-rya   File: PipelineQueryIT.java   View source code 6 votes vote down vote up
@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);
}
 
Example 31
Project: incubator-rya   File: SpinConstructRuleTest.java   View source code 6 votes vote down vote up
@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))));
}
 
Example 32
Project: angelix   File: TestTreeBoundedSynthesis.java   View source code 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 33
Project: simple-failover-java   File: WeightFailoverTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 34
Project: simple-failover-java   File: WeightFailoverTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 35
Project: simple-failover-java   File: WeightFailoverTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 36
Project: BeProductive   File: BeProductive.java   View source code 6 votes vote down vote up
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);
}
 
Example 37
Project: EasySRL   File: TagDict.java   View source code 6 votes vote down vote up
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);
}
 
Example 38
Project: angelix   File: TestTreeBoundedSynthesis.java   View source code 6 votes vote down vote up
@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());
}
 
Example 39
Project: java-smt   File: SolverFormulaIOTest.java   View source code 6 votes vote down vote up
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();
}
 
Example 40
Project: knowledgestore   File: Root.java   View source code 6 votes vote down vote up
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));
}