Example usage for com.google.common.collect Multiset size

List of usage examples for com.google.common.collect Multiset size

Introduction

In this page you can find the example usage for com.google.common.collect Multiset size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this collection.

Usage

From source file:edu.uw.cs.lil.tiny.test.ccg.lambda.SingleSentencePartialCreditTestingStatistics.java

private PartialCreditTriplet partialCompare(LogicalExpression gold, LogicalExpression label) {
    final Multiset<Pair<? extends LogicalExpression, ? extends LogicalExpression>> goldPairs = GetPredConstPairs
            .of(gold);//from   w  ww  .  j a  v a 2 s. co m
    final Multiset<Pair<? extends LogicalExpression, ? extends LogicalExpression>> labelPairs;
    if (label == null) {
        labelPairs = HashMultiset.create();
    } else {
        labelPairs = GetPredConstPairs.of(label);
    }

    // The "intersection" of the gold and label pair sets = the number of
    // matches
    final Multiset<Pair<? extends LogicalExpression, ? extends LogicalExpression>> intersection = HashMultiset
            .create();

    for (final Entry<Pair<? extends LogicalExpression, ? extends LogicalExpression>> entry : goldPairs
            .entrySet()) {
        intersection.setCount(entry.getElement(),
                Math.min(entry.getCount(), labelPairs.count(entry.getElement())));
    }

    return new PartialCreditTriplet(goldPairs.size(), labelPairs.size(), intersection.size());
}

From source file:org.bin01.db.verifier.Validator.java

public String getResultsComparison() {
    List<List<Object>> controlResults = controlResult.getResults();
    List<List<Object>> testResults = testResult.getResults();

    if (valid() || (controlResults == null) || (testResults == null)) {
        return "";
    }//from   w ww  .  ja  v  a 2 s .  c om

    Multiset<List<Object>> control = ImmutableSortedMultiset.copyOf(rowComparator(), controlResults);
    Multiset<List<Object>> test = ImmutableSortedMultiset.copyOf(rowComparator(), testResults);

    try {
        Iterable<ChangedRow> diff = ImmutableSortedMultiset.<ChangedRow>naturalOrder()
                .addAll(Iterables.transform(Multisets.difference(control, test),
                        ChangedRow.changedRows(Changed.REMOVED)))
                .addAll(Iterables.transform(Multisets.difference(test, control),
                        ChangedRow.changedRows(Changed.ADDED)))
                .build();
        diff = Iterables.limit(diff, 100);

        StringBuilder sb = new StringBuilder();

        sb.append(format("Control %s rows, Test %s rows%n", control.size(), test.size()));
        if (verboseResultsComparison) {
            Joiner.on("\n").appendTo(sb, diff);
        } else {
            sb.append("RESULTS DO NOT MATCH\n");
        }

        return sb.toString();
    } catch (TypesDoNotMatchException e) {
        return e.getMessage();
    }
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.particlefilter.ParticleFilter.java

/**
 * This runs a single time-step of the particle filter, given a single
 * timestep's worth of sensor readings./*ww  w.j  av a 2  s .c  om*/
 * 
 * @param timestamp
 * @param obs
 * @param moveParticles
 * @throws ParticleFilterException
 */
private void runSingleTimeStep(double timestamp, OBS obs, boolean moveParticles)
        throws ParticleFilterException {

    Multiset<Particle> particles = _particles;

    /*
     * perform movement and weighing separately
     */
    if (moveParticles) {
        final double elapsed = timestamp - _timeOfLastUpdate;
        particles = _motionModel.move(_particles, timestamp, elapsed, obs, _previouslyResampled);
    }

    /**
     * 3. track the weighted particles (before resampling and normalization)
     */
    _weightedParticles = particles;

    /**
     * 4. store the most likely particle's information
     */
    computeBestState(particles);

    if (getEffectiveSampleSize(particles)
            / ParticleFactoryImpl.getInitialNumberOfParticles() < _resampleThreshold) {

        /**
         * 5. resample
         */
        final Multiset<Particle> resampled = lowVarianceSampler(particles, particles.size());

        final Multiset<Particle> reweighted = HashMultiset.create(resampled.size());
        for (final Entry<Particle> pEntry : resampled.entrySet()) {
            final Particle p = pEntry.getElement().cloneParticle();
            p.setWeight(((double) pEntry.getCount()) / resampled.size());
            reweighted.add(p, pEntry.getCount());
        }
        _particles = reweighted;
        _previouslyResampled = true;
    } else {
        _particles = particles;
        _previouslyResampled = false;
    }

}

From source file:com.b2international.snowowl.snomed.reasoner.server.diff.BranchMetadataNamespaceAndModuleAssigner.java

@Override
public void allocateRelationshipIdsAndModules(Multiset<String> conceptIds,
        final SnomedEditingContext editingContext) {

    if (conceptIds.isEmpty()) {
        return;//ww  w .j a v a  2 s .  c o  m
    }

    try {

        Branch branch = RepositoryRequests.branching().prepareGet(editingContext.getBranch())
                .build(SnomedDatastoreActivator.REPOSITORY_UUID)
                .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync();

        String defaultModuleId = BranchMetadataResolver.getEffectiveBranchMetadataValue(branch,
                SnomedCoreConfiguration.BRANCH_DEFAULT_MODULE_ID_KEY);
        String defaultNamespaceId = BranchMetadataResolver.getEffectiveBranchMetadataValue(branch,
                SnomedCoreConfiguration.BRANCH_DEFAULT_NAMESPACE_KEY);

        ISnomedIdentifierService identifierService = getServiceForClass(ISnomedIdentifierService.class);

        String defaultNamespace = Strings.isNullOrEmpty(defaultNamespaceId)
                ? editingContext.getDefaultNamespace()
                : defaultNamespaceId;

        reservedIds = identifierService.reserve(defaultNamespace, ComponentCategory.RELATIONSHIP,
                conceptIds.size());
        relationshipIds = reservedIds.iterator();

        defaultRelationshipModuleConcept = Strings.isNullOrEmpty(defaultModuleId)
                ? editingContext.getDefaultModuleConcept()
                : editingContext.getConcept(defaultModuleId);

    } catch (NotFoundException e) {
        super.allocateRelationshipIdsAndModules(conceptIds, editingContext);
    }

}

From source file:edu.berkeley.compbio.ml.cluster.bayesian.TacoaClustering.java

/**
 * Hack the prior probabilities using the number of clusters per training label.  TacoaDistanceMeasure takes the prior
 * to be per label, not per cluster.   So, the "distance" between a sample and a cluster depends on how many clusters
 * share the same training label./*from   w w w.  j a v  a2 s.c o  m*/
 */
protected synchronized void preparePriors() //throws DistributionException
{
    //normalizeClusterLabelProbabilities();
    try {
        final Multiset<String> populatedTrainingLabels = HashMultiset.create();
        //int clustersWithTrainingLabel = 0;
        final Collection<? extends CentroidCluster<T>> immutableClusters = getClusters();
        for (final CentroidCluster<T> theCluster : immutableClusters) {
            try {
                // note this also insures that every cluster has a training label, otherwise it throws NoSuchElementException
                final String label = theCluster.getImmutableWeightedLabels()
                        .getDominantKeyInSet(potentialTrainingBins);
                // could use theCluster.getDerivedLabelProbabilities() there except they're not normalized yet, and there's no need

                populatedTrainingLabels.add(label);
                //clustersWithTrainingLabel++;
            } catch (NoSuchElementException e) {
                logger.warn("Cluster has no training label: " + theCluster);
            }
        }

        logger.info(String.valueOf(populatedTrainingLabels.size()) + " of " + getNumClusters()
                + " clusters have a training label; " + populatedTrainingLabels.entrySet().size()
                + " labels were trained");

        final ImmutableMap.Builder<Cluster<T>, Double> builder = ImmutableMap.builder();

        final Multinomial<String> labelPriors = new Multinomial<String>(populatedTrainingLabels);
        for (final CentroidCluster<T> theCluster : immutableClusters) {
            final String label = theCluster.getImmutableWeightedLabels()
                    .getDominantKeyInSet(potentialTrainingBins); // PERF redundant
            builder.put(theCluster, labelPriors.get(label));
        }

        clusterPriors = builder.build();
    } catch (DistributionException e) {
        logger.error("Error", e);
        throw new ClusterRuntimeException(e);
    }
}

From source file:de.hzi.helmholtz.Compare.PathwayComparisonUsingModules.java

public Multimap<Double, String> SubsetsMatching(final PathwayUsingModules firstPathway,
        final PathwayUsingModules secondPathway, BiMap<String, Integer> newSourceGeneIdToPositionMap,
        BiMap<String, Integer> newTargetGeneIdToPositionMap, int Yes) {
    Multimap<Double, String> resultPerfect = TreeMultimap.create(Ordering.natural().reverse(),
            Ordering.natural());//ww w .  ja v a  2s.  c  om
    PathwayUsingModules firstPathwayCopy = new PathwayUsingModules(firstPathway);// Copy of the Query pathway
    PathwayUsingModules secondPathwayCopy = new PathwayUsingModules(secondPathway);// Copy of the Target pathway'
    // PathwayUsingModules secondPathwayCopy1 = new PathwayUsingModules(secondPathway);
    int currentQueryGene = 0;
    Iterator<Module> sourceGeneIt = firstPathway.geneIterator();
    List<String> QueryToRemove = new ArrayList<String>();
    List<String> TargetToRemove = new ArrayList<String>();
    while (sourceGeneIt.hasNext()) {
        currentQueryGene++;
        Module queryGene = sourceGeneIt.next();

        int currentTargetGene = 0;
        Multiset<String> qfunction = LinkedHashMultiset.create();
        List<String> qfunctionList = new ArrayList<String>();
        List<String> qactivity = new ArrayList<String>();
        List<Set<String>> qsubstrate = new ArrayList<Set<String>>();
        for (Domain d : queryGene.getDomains()) {
            qfunction.add(d.getDomainFunctionString());
            qfunctionList.add(d.getDomainFunctionString());
            qactivity.add(d.getStatus().toString());
            qsubstrate.add(d.getSubstrates());
        }
        Iterator<Module> targetGeneIt = secondPathway.geneIterator();

        while (targetGeneIt.hasNext()) {
            currentTargetGene++;
            Module targetGene = targetGeneIt.next();
            Multiset<String> tfunction = LinkedHashMultiset.create();
            List<String> tfunctionList = new ArrayList<String>();
            List<String> tactivity = new ArrayList<String>();
            List<Set<String>> tsubstrate = new ArrayList<Set<String>>();
            for (Domain d : targetGene.getDomains()) {
                tfunctionList.add(d.getDomainFunctionString());
                tfunction.add(d.getDomainFunctionString());
                tactivity.add(d.getStatus().toString());
                tsubstrate.add(d.getSubstrates());
            }
            Multiset<String> DomainsCovered = Multisets.intersection(qfunction, tfunction);
            if (DomainsCovered.size() == qfunction.size() && DomainsCovered.size() == tfunction.size()) {
                Multimap<Double, Multimap<String, Integer>> activityscores = myFunction.calculate(qactivity,
                        tactivity);
                Multimap<String, Integer> Functionscores = ArrayListMultimap.create();

                int TranspositionDomains = LevenshteinDistance.computeLevenshteinDistance(qfunctionList,
                        tfunctionList);
                if (TranspositionDomains > 0) {
                    TranspositionDomains = 1;
                }

                Functionscores.put(qfunction.size() + "-0", TranspositionDomains);
                Multimap<Double, Multimap<String, Integer>> substratescore = myFunction
                        .calculate(getSubstrateList(qsubstrate), getSubstrateList(tsubstrate));
                Object activityScore = activityscores.asMap().keySet().toArray()[0];
                Object substrateScore = substratescore.asMap().keySet().toArray()[0];
                double finalScore = Math
                        .round((((2.9 * 1.0) + (0.05 * Double.parseDouble(activityScore.toString().trim()))
                                + (0.05 * Double.parseDouble(substrateScore.toString().trim()))) / 3) * 100.0)
                        / 100.0;
                String ConvertedGeneIDs = "";
                if (Yes == 0) {
                    ConvertedGeneIDs = reconstructWithGeneId(Integer.toString(currentQueryGene),
                            newSourceGeneIdToPositionMap) + "->"
                            + reconstructWithGeneId(Integer.toString(currentTargetGene),
                                    newTargetGeneIdToPositionMap);
                } else {
                    ConvertedGeneIDs = reconstructWithGeneId(Integer.toString(currentTargetGene),
                            newTargetGeneIdToPositionMap) + "->"
                            + reconstructWithGeneId(Integer.toString(currentQueryGene),
                                    newSourceGeneIdToPositionMap);
                }
                resultPerfect.put(finalScore, ConvertedGeneIDs);
                ScoreFunctionMatchMisMatch.put(ConvertedGeneIDs, Functionscores);
                ScoreStatusMatchMisMatch.putAll(ConvertedGeneIDs, activityscores.values());
                ScoreSubstrateMatchMisMatch.putAll(ConvertedGeneIDs, substratescore.values());

                TargetToRemove.add(reconstructWithGeneId(Integer.toString(currentTargetGene),
                        newTargetGeneIdToPositionMap));
                QueryToRemove.add(reconstructWithGeneId(Integer.toString(currentQueryGene),
                        newSourceGeneIdToPositionMap));
            }
        }

    }
    for (String i : TargetToRemove) {
        secondPathwayCopy.removeModule(i);
    }
    for (String i : QueryToRemove) {
        firstPathwayCopy.removeModule(i);
    }
    if (firstPathwayCopy.size() > 0 && secondPathwayCopy.size() > 0) {
        // Re-construct the bimaps
        newSourceGeneIdToPositionMap = HashBiMap.create();
        int temp = 0;
        for (Module e : firstPathwayCopy.getModules()) {
            temp = temp + 1;
            newSourceGeneIdToPositionMap.put(e.getModuleId(), temp);
        }
        newTargetGeneIdToPositionMap = HashBiMap.create();
        temp = 0;
        for (Module e : secondPathwayCopy.getModules()) {
            temp = temp + 1;
            newTargetGeneIdToPositionMap.put(e.getModuleId(), temp);
        }
        resultPerfect.putAll(SubsetIdentification(firstPathwayCopy, secondPathwayCopy,
                newSourceGeneIdToPositionMap, newTargetGeneIdToPositionMap, Yes));
    }
    ////System.out.println(resultPerfect);
    return resultPerfect;
}

From source file:fr.obeo.releng.targetplatform.validation.TargetPlatformValidator.java

private void reportDuplicatedEnvironmentOptions(final TargetPlatform targetPlatform,
        final Multiset<String> valuesInFile, final String msg) {
    if (((valuesInFile.size() > 1) || IterableExtensions.<Multiset.Entry<String>>exists(valuesInFile.entrySet(),
            new Function1<Multiset.Entry<String>, Boolean>() {
                @Override/* w w w  . j  a va 2  s .  c  o  m*/
                public Boolean apply(final Multiset.Entry<String> it) {
                    int _count = it.getCount();
                    return Boolean.valueOf((_count > 1));
                }
            }))) {
        final Consumer<String> _function = new Consumer<String>() {
            @Override
            public void accept(final String e) {
                final Consumer<Environment> _function = new Consumer<Environment>() {
                    @Override
                    public void accept(final Environment env) {
                        for (int i = 0; (i < env.getEnv().size()); i++) {
                            {
                                final String it = env.getEnv().get(i);
                                boolean _equals = e.equals(it);
                                if (_equals) {
                                    TargetPlatformValidator.this.error(msg, env,
                                            TargetPlatformPackage.Literals.ENVIRONMENT__ENV, i,
                                            TargetPlatformValidator.CHECK__NO_DUPLICATE_ENVIRONMENT_OPTIONS);
                                }
                            }
                        }
                    }
                };
                Iterables.<Environment>filter(targetPlatform.getContents(), Environment.class)
                        .forEach(_function);
            }
        };
        valuesInFile.elementSet().forEach(_function);
    }
}

From source file:de.hzi.helmholtz.Compare.PathwayComparisonUsingModules.java

public Multimap<Double, String> SubsetIdentification(PathwayUsingModules firstPathway,
        PathwayUsingModules secondPathway, BiMap<String, Integer> newSourceGeneIdToPositionMap,
        BiMap<String, Integer> newTargetGeneIdToPositionMap, int Yes) {
    Multimap<Double, String> result = TreeMultimap.create(Ordering.natural().reverse(), Ordering.natural());

    Iterator<Module> sourceGeneIt = firstPathway.geneIterator();
    int currentQueryGene = 0;
    while (sourceGeneIt.hasNext()) {
        currentQueryGene++;/*from   www  .  j  av  a  2 s  .c  o  m*/
        Module queryGene = sourceGeneIt.next();
        Multimap<Integer, String> resultr = TreeMultimap.create(Ordering.natural(), Ordering.natural());
        int currentTargetGene = 0;
        Multiset<String> qfunction = LinkedHashMultiset.create();
        List<String> qfunctionList = new ArrayList<String>();
        List<String> qactivity = new ArrayList<String>();
        List<Set<String>> qsubstrate = new ArrayList<Set<String>>();
        for (Domain d : queryGene.getDomains()) {
            qfunction.add(d.getDomainFunctionString());
            qfunctionList.add(d.getDomainFunctionString());
            qactivity.add(d.getStatus().toString());
            qsubstrate.add(d.getSubstrates());
        }
        List<String> TargenesSelected = new ArrayList<String>();
        Iterator<Module> targetGeneIt = secondPathway.geneIterator();
        while (targetGeneIt.hasNext()) {
            currentTargetGene++;
            Module targetGene = targetGeneIt.next();
            Multiset<String> tfunction = LinkedHashMultiset.create();
            List<String> tactivity = new ArrayList<String>();
            List<Set<String>> tsubstrate = new ArrayList<Set<String>>();
            List<String> tfunctionList = new ArrayList<String>();
            Iterator<Domain> dIter = targetGene.domainIterator();
            while (dIter.hasNext()) {
                Domain d = dIter.next();
                tfunction.add(d.getDomainFunctionString());
                tfunctionList.add(d.getDomainFunctionString());
                tactivity.add(d.getStatus().toString());
                tsubstrate.add(d.getSubstrates());
            }
            Multiset<String> DomainsCovered = Multisets.intersection(qfunction, tfunction);
            int Differences = Math.max(Math.abs(DomainsCovered.size() - tfunction.size()),
                    Math.abs(DomainsCovered.size() - qfunction.size()));
            if (DomainsCovered.size() == tfunction.size() && tfunction.size() > 4) {
                TargenesSelected.add(Integer.toString(currentTargetGene));
            } else {
                resultr.put(Differences, Integer.toString(currentTargetGene));
            }

        }
        int count = 0;
        if (resultr.size() > 0) {
            int tsize = 0;
            if ((firstPathway.size() > 8 && firstPathway.size() < 10)
                    || (secondPathway.size() > 8 && secondPathway.size() < 10)) {
                tsize = 2;
            } else if ((firstPathway.size() > 2 && firstPathway.size() < 8)
                    && (secondPathway.size() > 2 && secondPathway.size() < 8)) {
                tsize = 4;
            } else {
                tsize = 1;
            }
            while (TargenesSelected.size() < tsize) {
                Multiset<String> k = LinkedHashMultiset.create(resultr.values());
                Multiset<String> t = LinkedHashMultiset.create(TargenesSelected);
                Multiset<String> Covered = Multisets.intersection(k, t);
                if (Covered.size() == k.size()) {
                    break;
                }

                try {
                    TargenesSelected.addAll(
                            resultr.get(Integer.parseInt(resultr.keySet().toArray()[count].toString())));
                } catch (Exception ds) {
                }
                count = count + 1;
            }
        }
        // ////System.out.println(TargenesSelected);
        //  Permutation perm = new Permutation();
        //  List<String> perms = perm.run(TargenesSelected);
        CombinationGenerator c = new CombinationGenerator(10, 10);
        List<String> perms = c.GenerateAllPossibleCombinations(TargenesSelected);
        myFunction sim = new myFunction();
        double score = 0;
        String targetIdentified = "";
        List<Module> targetGenesList = secondPathway.getModules();
        for (String permu : perms) {
            String[] values = permu.replace("[", "").replace("]", "").split(",");
            List<String> mergedTargetgenes = new ArrayList<String>();
            List<Integer> ToRemove = new ArrayList<Integer>();
            List<String> tactivity = new ArrayList<String>();
            List<Set<String>> tsubstrate = new ArrayList<Set<String>>();
            for (String j : values) {
                ToRemove.add(Integer.parseInt(j.trim()));
                for (Domain i : targetGenesList.get(Integer.parseInt(j.trim()) - 1).getDomains()) {

                    mergedTargetgenes.add(i.getDomainFunctionString());
                    tactivity.add(i.getStatus().toString());
                    tsubstrate.add(i.getSubstrates());
                }
            }
            Multimap<Double, Multimap<String, Integer>> FunctionScores = sim.calculate(qfunctionList,
                    mergedTargetgenes);
            Multimap<Double, Multimap<String, Integer>> activityscores = myFunction.calculate(qactivity,
                    tactivity);
            Multimap<Double, Multimap<String, Integer>> substratescores = myFunction
                    .calculate(getSubstrateList(qsubstrate), getSubstrateList(tsubstrate));
            Object FunctionScore = FunctionScores.asMap().keySet().toArray()[0];
            Object activityScore = activityscores.asMap().keySet().toArray()[0];
            Object substrateScore = substratescores.asMap().keySet().toArray()[0];

            double finalScore = Math
                    .round((((2.9 * Double.parseDouble(FunctionScore.toString().trim()))
                            + (0.05 * Double.parseDouble(activityScore.toString().trim()))
                            + (0.05 * Double.parseDouble(substrateScore.toString().trim()))) / 3) * 100.0)
                    / 100.0;
            targetIdentified = permu.replace(",", "+");
            String ConvertedGeneIDs = "";
            if (Yes == 0) {
                ConvertedGeneIDs = reconstructWithGeneId(Integer.toString(currentQueryGene),
                        newSourceGeneIdToPositionMap) + "->"
                        + reconstructWithGeneId(targetIdentified.replace("[", "").replace("]", ""),
                                newTargetGeneIdToPositionMap);
            } else {
                ConvertedGeneIDs = reconstructWithGeneId(targetIdentified.replace("[", "").replace("]", ""),
                        newTargetGeneIdToPositionMap) + "->"
                        + reconstructWithGeneId(Integer.toString(currentQueryGene),
                                newSourceGeneIdToPositionMap);
            }
            // String ConvertedGeneIDs = reconstructWithGeneId(Integer.toString(currentQueryGene), newSourceGeneIdToPositionMap) + "->" + reconstructWithGeneId(targetIdentified.replace("[", "").replace("]", ""), newTargetGeneIdToPositionMap);

            result.put(finalScore, ConvertedGeneIDs);

            ScoreFunctionMatchMisMatch.putAll(ConvertedGeneIDs, FunctionScores.values());
            ScoreStatusMatchMisMatch.putAll(ConvertedGeneIDs, activityscores.values());
            ScoreSubstrateMatchMisMatch.putAll(ConvertedGeneIDs, substratescores.values());

        }

    }
    return result;
}

From source file:com.continuuity.loom.layout.change.AddServiceChangeIterator.java

public AddServiceChangeIterator(ClusterLayout clusterLayout, String service) {
    this.service = service;
    // cluster services are needed in order to prune the constraints to only use ones that pertain to services
    // on the cluster
    Set<String> expandedClusterServices = Sets.newHashSet(service);
    for (NodeLayout nodeLayout : clusterLayout.getLayout().elementSet()) {
        expandedClusterServices.addAll(nodeLayout.getServiceNames());
    }//w ww .j a  v a 2s  .co  m
    // first figure out which node layouts can add this service
    this.expandableNodeLayouts = Lists.newArrayListWithCapacity(clusterLayout.getLayout().elementSet().size());
    Multiset<NodeLayout> expandedCounts = HashMultiset.create();
    for (NodeLayout originalNodeLayout : clusterLayout.getLayout().elementSet()) {
        NodeLayout expandedNodeLayout = NodeLayout.addServiceToNodeLayout(originalNodeLayout, service);
        if (expandedNodeLayout.satisfiesConstraints(clusterLayout.getConstraints(), expandedClusterServices)) {
            expandableNodeLayouts.add(originalNodeLayout);
            expandedCounts.add(originalNodeLayout, clusterLayout.getLayout().count(originalNodeLayout));
        }
    }
    // sort expandable node layouts by preference order
    Collections.sort(this.expandableNodeLayouts, new NodeLayoutComparator(null, null));
    // need to pass this to the slotted iterator so we don't try and add the service to a node layout more times
    // than there are nodes for the node layout.
    this.nodeLayoutMaxCounts = new int[expandableNodeLayouts.size()];
    for (int i = 0; i < nodeLayoutMaxCounts.length; i++) {
        nodeLayoutMaxCounts[i] = expandedCounts.count(expandableNodeLayouts.get(i));
    }
    // figure out the max number of nodes we can add the service to. Start off by saying we can add it to all nodes.
    this.nodesToAddTo = expandedCounts.size();
    // we always need to add the service to at least one node.
    this.minNodesToAddTo = 1;
    ServiceConstraint serviceConstraint = clusterLayout.getConstraints().getServiceConstraints().get(service);
    // if there is a max constraint on this service and its less than the number of nodes in the cluster, start
    // there instead. Similarly, if there is a min constraint on this service higher than 1, use that instead.
    if (serviceConstraint != null) {
        this.nodesToAddTo = Math.min(serviceConstraint.getMaxCount(), this.nodesToAddTo);
        this.minNodesToAddTo = Math.max(serviceConstraint.getMinCount(), this.minNodesToAddTo);
    }
    this.nodeLayoutCountIterator = (this.nodesToAddTo < 1) ? null
            : new SlottedCombinationIterator(expandableNodeLayouts.size(), nodesToAddTo, nodeLayoutMaxCounts);
}

From source file:org.sonar.server.component.ws.ComponentAppAction.java

private void appendMeasures(JsonWriter json, Map<String, MeasureDto> measuresByMetricKey,
        Multiset<String> severitiesAggregation, Integer periodIndex) {
    json.name("measures").beginObject();

    json.prop("fNcloc", formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.NCLOC_KEY), periodIndex));
    json.prop("fCoverage", formatMeasureOrVariation(coverageMeasure(measuresByMetricKey), periodIndex));
    json.prop("fDuplicationDensity", formatMeasureOrVariation(
            measuresByMetricKey.get(CoreMetrics.DUPLICATED_LINES_DENSITY_KEY), periodIndex));
    json.prop("fDebt",
            formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.TECHNICAL_DEBT_KEY), periodIndex));
    json.prop("fSqaleRating",
            formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.SQALE_RATING_KEY), periodIndex));
    json.prop("fSqaleDebtRatio",
            formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.SQALE_DEBT_RATIO_KEY), periodIndex));
    json.prop("fTests", formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.TESTS_KEY), periodIndex));

    json.prop("fIssues", i18n.formatInteger(UserSession.get().locale(), severitiesAggregation.size()));
    for (String severity : severitiesAggregation.elementSet()) {
        json.prop("f" + StringUtils.capitalize(severity.toLowerCase()) + "Issues",
                i18n.formatInteger(UserSession.get().locale(), severitiesAggregation.count(severity)));
    }/*from   ww w . java2s . c o m*/
    json.endObject();
}