List of usage examples for com.google.common.collect HashMultiset create
public static <E> HashMultiset<E> create()
From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java
public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config, Validator validator) {// www. j a va 2 s .co m if (!ServletFileUpload.isMultipartContent(request)) { return; } logger.info("Request contains multipart data. Try to parse with commons-upload."); final Multiset<String> indexes = HashMultiset.create(); final Multimap<String, String> params = LinkedListMultimap.create(); ServletFileUpload uploader = createServletFileUpload(config); uploader.setSizeMax(config.getSizeLimit()); uploader.setFileSizeMax(config.getFileSizeLimit()); try { final List<FileItem> items = uploader.parseRequest(request); logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size()); for (FileItem item : items) { String name = item.getFieldName(); name = fixIndexedParameters(name, indexes); if (item.isFormField()) { logger.debug("{} is a field", name); params.put(name, getValue(item, request)); } else if (isNotEmpty(item)) { logger.debug("{} is a file", name); processFile(item, name, request); } else { logger.debug("A file field is empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } } catch (final SizeLimitExceededException e) { reportSizeLimitExceeded(e, validator); } catch (FileUploadException e) { reportFileUploadException(e, validator); } }
From source file:edu.cmu.lti.oaqa.baseqa.answer.yesno.scorers.ConceptOverlapYesNoScorer.java
@Override public Map<String, Double> score(JCas jcas) throws AnalysisEngineProcessException { // create ctype2concepts maps and concept counts in question and snippets SetMultimap<String, Concept> ctype2concepts = HashMultimap.create(); Multiset<Concept> concept2count = HashMultiset.create(); for (Concept concept : TypeUtil.getConcepts(jcas)) { TypeUtil.getConceptTypes(concept).stream().map(ConceptType::getAbbreviation) .forEach(ctype -> ctype2concepts.put(ctype, concept)); long count = TypeUtil.getConceptMentions(concept).stream() .map(cmention -> cmention.getView().getViewName()).distinct().count(); concept2count.setCount(concept, (int) count); }//from ww w . j a v a 2 s . c o m Set<Concept> qconcepts = TypeUtil.getConceptMentions(jcas).stream().map(ConceptMention::getConcept) .collect(toSet()); // prepare cross-ctype counts ImmutableMap.Builder<String, Double> features = ImmutableMap.builder(); ListMultimap<String, Double> keyword2values = ArrayListMultimap.create(); for (String ctype : ctype2concepts.keySet()) { Set<Concept> concepts = ctype2concepts.get(ctype); // local counts int[] totalCounts = concepts.stream().mapToInt(concept2count::count).toArray(); double[] questionCounts = concepts.stream().mapToDouble(concept -> qconcepts.contains(concept) ? 1 : 0) .toArray(); double[] questionRatios = IntStream.range(0, concepts.size()) .mapToDouble(i -> questionCounts[i] / totalCounts[i]).toArray(); double[] passageRatios = DoubleStream.of(questionRatios).map(r -> 1.0 - r).toArray(); // create feature counts aggregated for each ctype addAvgMaxMinFeatures(questionCounts, features, keyword2values, "question-count", ctype); addAvgMaxMinFeatures(questionRatios, features, keyword2values, "question-ratio", ctype); addAvgMaxMinFeatures(passageRatios, features, keyword2values, "passage-ratio", ctype); double questionRatioAvgMicro = DoubleStream.of(questionCounts).sum() / IntStream.of(totalCounts).sum(); features.put("question-ratio-avg-micro@" + ctype, questionRatioAvgMicro); keyword2values.put("question-ratio-avg-micro", questionRatioAvgMicro); double passageRatioAvgMicro = 1.0 - questionRatioAvgMicro; features.put("passage-ratio-avg-macro@" + ctype, passageRatioAvgMicro); keyword2values.put("passage-ratio-avg-macro", passageRatioAvgMicro); } // global features keyword2values.asMap().entrySet().stream().map(e -> YesNoScorer.aggregateFeatures(e.getValue(), e.getKey())) .forEach(features::putAll); return features.build(); }
From source file:com.b2international.snowowl.snomed.reasoner.server.diff.SourceConceptNamespaceAndModuleAssigner.java
@Override public void allocateRelationshipIdsAndModules(Multiset<String> conceptIds, final SnomedEditingContext editingContext) { Multiset<String> reservedIdsByNamespace = HashMultiset.create(); for (Multiset.Entry<String> conceptIdWithCount : conceptIds.entrySet()) { String namespace = SnomedIdentifiers.getNamespace(conceptIdWithCount.getElement()); reservedIdsByNamespace.add(namespace, conceptIdWithCount.getCount()); }/* www. j a v a2 s .c o m*/ ISnomedIdentifierService identifierService = getServiceForClass(ISnomedIdentifierService.class); for (Multiset.Entry<String> namespaceWithCount : reservedIdsByNamespace.entrySet()) { Collection<String> reservedIds = identifierService.reserve(namespaceWithCount.getElement(), ComponentCategory.RELATIONSHIP, namespaceWithCount.getCount()); this.reservedIds.addAll(reservedIds); namespaceToRelationshipIdMap.put(namespaceWithCount.getElement(), reservedIds.iterator()); } for (String conceptId : conceptIds.elementSet()) { Concept concept = editingContext.lookup(conceptId, Concept.class); conceptIdToRelationshipModuleMap.put(conceptId, concept.getModule()); } }
From source file:com.android.tools.idea.editors.theme.attributes.AttributesModelColorPaletteModel.java
private void loadColors() { if (myResourceResolver == null) { myColorList = Collections.emptyList(); return;/*from ww w. ja va2 s . co m*/ } 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.getSelectedValue(), myProject)) { myColorReferences.put(color, item); colorSet.add(color); } } myColorList = ImmutableList.copyOf(Multisets.copyHighestCountFirst(colorSet).elementSet()); }
From source file:com.clarkparsia.sbol.order.PartialOrder.java
/** * Returns the elements in an ascending topological order. * //from w w w .j a v a 2 s . c o m * @throws IllegalStateException if there are cycles between the elements */ @Override public Iterator<T> iterator() throws IllegalStateException { Multiset<T> degrees = HashMultiset.create(); Queue<T> nodesPending = new ArrayDeque<T>(); List<T> nodesSorted = Lists.newArrayList(); for (Entry<T, Set<T>> entry : precededBy.entrySet()) { T node = entry.getKey(); Set<T> precededByList = entry.getValue(); int degree = precededByList.size(); degrees.setCount(node, degree); if (degree == 0) { nodesPending.add(node); } } while (!nodesPending.isEmpty()) { T node = nodesPending.remove(); int deg = degrees.count(node); if (deg != 0) throw new IllegalStateException("Cycle detected " + node + " " + deg + " " + nodesSorted.size()); nodesSorted.add(node); for (Entry<T, Set<T>> entry : precededBy.entrySet()) { T n = entry.getKey(); Set<T> precededByList = entry.getValue(); if (precededByList.contains(node)) { int degree = degrees.count(n); if (degree == 1) { nodesPending.add(n); degrees.setCount(n, 0); } else { degrees.remove(n); } } } } if (nodesSorted.size() != precededBy.size()) { throw new IllegalStateException("Failed to sort elements"); } return nodesSorted.iterator(); }
From source file:com.continuuity.loom.layout.ClusterLayout.java
/** * Derive a ClusterLayout from a set of {@link Node}s and some {@link Constraints}. * * @param clusterNodes Nodes to derive the layout from. * @param constraints Constraints for the cluster layout. * @return ClusterLayout derived from the nodes. *///from w w w .ja va 2 s. com public static ClusterLayout fromNodes(Set<Node> clusterNodes, Constraints constraints) { Multiset<NodeLayout> nodeLayoutCounts = HashMultiset.create(); for (Node node : clusterNodes) { Set<String> nodeServices = Sets.newHashSet(); for (Service service : node.getServices()) { nodeServices.add(service.getName()); } String hardwareType = node.getProperties().getHardwaretype(); String imageType = node.getProperties().getImagetype(); nodeLayoutCounts.add(new NodeLayout(hardwareType, imageType, nodeServices)); } return new ClusterLayout(constraints, nodeLayoutCounts); }
From source file:se.gothiaforum.controller.tagcloud.TagCloudController.java
/** * Renders the view for the tag cloud./*from ww w. j a v a 2s .com*/ * * @param request * the request * @param model * the model * @return a view */ @RenderMapping public String renderView(RenderRequest request, Model model) { try { List<JournalArticle> articles = JournalArticleLocalServiceUtil.getJournalArticles(0, JournalArticleLocalServiceUtil.getJournalArticlesCount()); Set<AssetEntry> entrys = new HashSet<AssetEntry>(); for (JournalArticle ja : articles) { if (ja.getType().equals(ActorsConstants.TYPE_ACTOR)) { entrys.add(AssetEntryLocalServiceUtil.getEntry(JournalArticle.class.getName(), ja.getResourcePrimKey())); } } Multiset<AssetTag> tagMultiSet = HashMultiset.create(); for (AssetEntry entry : entrys) { List<AssetTag> tags = AssetTagLocalServiceUtil.getEntryTags(entry.getEntryId()); for (AssetTag tag : tags) { tagMultiSet.add(tag); } } List<TagVO> tagVOList = new ArrayList<TagVO>(); for (Entry<AssetTag> entry : tagMultiSet.entrySet()) { String cssClass; final int number8 = 8; final int number7 = 7; final int number6 = 6; final int number5 = 5; final int number4 = 4; final int number3 = 3; final int number2 = 2; if (entry.getCount() > number8) { cssClass = "tag-weight-10"; } else if (entry.getCount() > number7) { cssClass = "tag-weight-9"; } else if (entry.getCount() > number6) { cssClass = "tag-weight-8"; } else if (entry.getCount() > number5) { cssClass = "tag-weight-7"; } else if (entry.getCount() > number4) { cssClass = "tag-weight-6"; } else if (entry.getCount() > number3) { cssClass = "tag-weight-5"; } else if (entry.getCount() > number2) { cssClass = "tag-weight-4"; } else { cssClass = "tag-weight-2"; } TagVO tagVO = new TagVO(cssClass, entry.getElement().getName(), ActorsConstants.SEARCH_REDIRECT_URL + entry.getElement().getName(), entry.getElement().getTagId()); tagVO.setCount(entry.getCount()); tagVOList.add(tagVO); } final int size = 20; if (tagVOList.size() > size) { for (int i = 1; tagVOList.size() > size; i++) { List<TagVO> removeList = new ArrayList<TagVO>(); for (TagVO tagVO : tagVOList) { if (tagVO.getCount() == i) { removeList.add(tagVO); } } tagVOList.removeAll(removeList); } } Collections.shuffle(tagVOList); model.addAttribute("tagVOList", tagVOList); } catch (SystemException e) { e.printStackTrace(); } catch (PortalException e) { e.printStackTrace(); } return "tagCloudView"; }
From source file:org.kalypso.ogc.sensor.timeseries.TimestampGuesser.java
/** * This function guesses the timestamp./*from w ww . ja v a 2s . co m*/ * * @return The timestamp in UTC. */ public LocalTime execute() throws SensorException { /* Used to determine the number of equal timestamps. */ final Multiset<LocalTime> timestampsDSTWinter = HashMultiset.create(); final Multiset<LocalTime> timestampsDSTSummer = HashMultiset.create(); /* Get the number of test steps. */ final int testSteps = getTestSteps(); /* Find the date axis. */ final IAxis dateAxis = AxisUtils.findDateAxis(m_timeseries.getAxes()); if (dateAxis == null) throw new IllegalArgumentException("Argument mus tbe a timeseries"); //$NON-NLS-1$ /* Collect all timestamps. */ for (int i = 0; i < testSteps; i++) { /* REMARK: We need UTC here. */ final Date date = (Date) m_timeseries.get(i, dateAxis); final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); //$NON-NLS-1$ calendar.setTime(date); /* Differ between daylight saving winter and summer times. */ /* Old zml daylight saving summer times are possible broken! */ final boolean dstWinterTime = CalendarUtilities.isDSTWinterTime(date); /* REMARK: The ISO Chronolgy used will have the UTC timezone set. */ /* REMARK: See the source code of the constructor. */ final LocalTime timestamp = new LocalTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)); if (dstWinterTime) timestampsDSTWinter.add(timestamp); else timestampsDSTSummer.add(timestamp); } /* We want to use the one, with the most occurences. */ final LocalTime timestamp = doGuessTimestamp(timestampsDSTWinter); if (timestamp != null) return timestamp; return doGuessTimestamp(timestampsDSTSummer); }
From source file:org.caleydo.view.domino.internal.data.Categorical2DDataDomainValues.java
/** * @param t2//from ww w . jav a 2s . c o m * @return */ private Pair<TypedGroupSet, TypedGroupSet> extractGroups(TablePerspective t) { Multimap<Object, Integer> dimGroups = HashMultimap.create(); Multimap<Object, Integer> recGroups = HashMultimap.create(); TypedSet d = TypedSet.of(t.getDimensionPerspective().getVirtualArray()); TypedSet r = TypedSet.of(t.getRecordPerspective().getVirtualArray()); List<Multiset<Object>> rows = new ArrayList<>(r.size()); for (int i = 0; i < r.size(); ++i) rows.add(HashMultiset.create()); for (Integer dim : d) { Multiset<Object> col = HashMultiset.create(); int i = 0; for (Integer rec : r) { Object v = getRaw(dim, rec); col.add(v); rows.get(i++).add(v); } Object mostFrequent = mostFrequent(col); dimGroups.put(mostFrequent, dim); } { int i = 0; for (Integer rec : r) { Multiset<Object> row = rows.get(i++); Object mostFrequent = mostFrequent(row); recGroups.put(mostFrequent, rec); } } List<CategoryProperty<?>> categories = getCategories(getDataDomain()); return Pair.make(toGroups(dimGroups, categories, d.getIdType()), toGroups(recGroups, categories, r.getIdType())); }
From source file:org.apache.ctakes.relationextractor.data.GoldAnnotationStatsCalculator.java
@Override public void initialize(UimaContext context) throws ResourceInitializationException { tokenCount = 0;/* w w w .j av a 2 s . c o m*/ sentenceCount = 0; entityMentionCount = 0; entityMentionPairCount = 0; relationArgumentDistance = 0; relationTypes = HashMultiset.create(); entityMentionPairTypes = HashMultiset.create(); }