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

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

Introduction

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

Prototype

public static int size(Iterable<?> iterable) 

Source Link

Document

Returns the number of elements in iterable .

Usage

From source file:com.davidbracewell.ml.sequence.Sequence.java

/**
 * Instantiates a new Sequence.//from w  w w  .j a  va  2s .c  o m
 *
 * @param data       the data
 * @param extractors the extractors
 */
public Sequence(Iterable<V> data, ContextExtractorSet<V> extractors) {
    this.extractors = extractors;
    this.data = Collections.unmodifiableList(Lists.newArrayList(data));
    this.labels = new double[Iterables.size(data)];
    Arrays.fill(labels, Instance.MISSING_VALUE);
}

From source file:org.gradle.model.internal.type.ModelTypes.java

/**
 * Collect all types that make up the type hierarchy of the given types.
 *//*from ww  w .  j a va 2s.co  m*/
public static Set<ModelType<?>> collectHierarchy(Iterable<? extends ModelType<?>> types) {
    Queue<ModelType<?>> queue = new ArrayDeque<ModelType<?>>(Iterables.size(types) * 2);
    Iterables.addAll(queue, types);
    Set<ModelType<?>> seenTypes = Sets.newLinkedHashSet();
    ModelType<?> type;
    while ((type = queue.poll()) != null) {
        // Do not process Object's or GroovyObject's methods
        Class<?> rawClass = type.getRawClass();
        if (rawClass.equals(Object.class) || rawClass.equals(GroovyObject.class)) {
            continue;
        }
        // Do not reprocess
        if (!seenTypes.add(type)) {
            continue;
        }

        Class<?> superclass = rawClass.getSuperclass();
        if (superclass != null) {
            ModelType<?> superType = ModelType.of(superclass);
            if (!seenTypes.contains(superType)) {
                queue.add(superType);
            }
        }
        for (Class<?> iface : rawClass.getInterfaces()) {
            ModelType<?> ifaceType = ModelType.of(iface);
            if (!seenTypes.contains(ifaceType)) {
                queue.add(ifaceType);
            }
        }
    }

    return seenTypes;
}

From source file:pl.nort.dayoneevernote.convert.NotesConverter.java

@Override
public void run() {
    Set<Note> notes = fetcher.getNotes();

    Iterable<Note> filteredNotes = Iterables.filter(notes, filter);
    Iterable<Note> transformedNotes = Iterables.transform(filteredNotes, transformer);

    LOG.info("Matched " + Iterables.size(transformedNotes) + " of " + notes.size() + " notes");

    for (Pusher pusher : pushers) {
        if (!pusher.push(transformedNotes)) {
            LOG.error("Import of some notes failed!");
        }/*from  www . ja v  a2s .c  o  m*/
    }
}

From source file:org.renjin.primitives.special.SwitchFunction.java

private static SEXP doApply(Context context, Environment rho, FunctionCall call, PairList args) {
    EvalException.check(call.length() > 1, "argument \"EXPR\" is missing");

    SEXP expr = context.evaluate(args.getElementAsSEXP(0), rho);
    EvalException.check(expr.length() == 1, "EXPR must return a length 1 vector");

    Iterable<PairList.Node> branches = Iterables.skip(args.nodes(), 1);

    if (expr instanceof StringVector) {
        String name = ((StringVector) expr).getElementAsString(0);
        if (StringVector.isNA(name)) {
            context.setInvisibleFlag();/*from   w w w  .  ja  v  a 2 s.  co  m*/
            return Null.INSTANCE;
        }
        SEXP partialMatch = null;
        int partialMatchCount = 0;
        for (PairList.Node node : branches) {
            if (node.hasTag()) {
                String branchName = node.getTag().getPrintName();
                if (branchName.equals(name)) {
                    return context.evaluate(nextNonMissing(node), rho);
                } else if (branchName.startsWith(name)) {
                    partialMatch = nextNonMissing(node);
                    partialMatchCount++;
                }
            }
        }
        if (partialMatchCount == 1) {
            return context.evaluate(partialMatch, rho);
        } else if (Iterables.size(branches) > 0) {
            PairList.Node last = Iterables.getLast(branches);
            if (!last.hasTag()) {
                return context.evaluate(last.getValue(), rho);
            }
        }

    } else if (expr instanceof AtomicVector) {
        int branchIndex = ((AtomicVector) expr).getElementAsInt(0);
        if (branchIndex >= 1 && branchIndex <= Iterables.size(branches)) {
            return context.evaluate(Iterables.get(branches, branchIndex - 1).getValue(), rho);
        }
    }
    // no match
    return Null.INSTANCE;
}

From source file:msi.gama.lang.gaml.ui.editor.GamlEditorState.java

public GamlEditorState(final ValidationContext status, final Iterable<? extends IDescription> descriptions) {

    if (status != null) {
        hasImportedErrors = status.hasImportedErrors();
        importedErrors = hasImportedErrors ? status.getImportedErrorsAsStrings() : Collections.EMPTY_MAP;
        hasInternalErrors = status.hasInternalErrors() || status.hasInternalSyntaxErrors();
        hasNullStatus = false;//from w w  w.  ja v  a  2  s. co m
        showExperiments = !status.getNoExperiment();
    } else {
        hasNullStatus = true;
        importedErrors = Collections.EMPTY_MAP;
        showExperiments = true;
    }
    final int n = Iterables.size(descriptions);
    if (n > 0) {
        hasExperiments = true;
        experiments = new ArrayList<>(n);
        abbreviations = new ArrayList<>(n);
        types = new ArrayList<>(n);
        for (final IDescription ep : descriptions) {
            final String name = ep.getName();
            experiments.add(name);
            abbreviations.add(name.replaceFirst("Experiment ", ""));
            types.add(((ExperimentDescription) ep).getExperimentType());
        }
    } else {
        experiments = Collections.EMPTY_LIST;
        abbreviations = Collections.EMPTY_LIST;
        types = Collections.EMPTY_LIST;
    }
}

From source file:org.apache.shiro.nexus.ShiroJCacheAdapter.java

@Override
public int size() {
    return Iterables.size(cache);
}

From source file:cloud.sync.watchdogs.AbstractWatchDog.java

@Transactional(readOnly = true)
@Override/*from   w  ww  .  j av a  2 s .  c om*/
public void run() {

    LOGGER.info(String.format("%s is starting watching.", this));

    Iterable<T> toWatch = toWatch();

    if (Iterables.size(toWatch) > 0) {
        LOGGER.debug(String.format("%s is watching %s entities.", this, Iterables.size(toWatch)));
        for (T t : toWatch()) {
            LOGGER.trace(String.format("%s is starting to watch %s", this, t));
            for (ProblemDetector<T> problemDetector : detectors) {
                LOGGER.trace(
                        String.format("%s is applying problem detector %s on %s", this, problemDetector, t));
                final Optional<Problem<T>> problem = problemDetector.apply(t);
                if (problem.isPresent()) {
                    LOGGER.debug(
                            String.format("%s found problem %s, reporting to queue.", this, problem.get()));
                    problemQueue.add(problem.get());
                }
            }
        }
    } else {
        LOGGER.debug(String.format("%s has nothing to watch", this));
    }

    LOGGER.info(String.format("%s finished watching", this));
}

From source file:ezbake.data.graph.blueprints.visibility.VisibilityFilterVertexQuery.java

@Override
public long count() {
    return Iterables.size(edges());
}

From source file:org.jboss.hal.ballroom.autocomplete.ReadChildrenAutoComplete.java

public ReadChildrenAutoComplete(Dispatcher dispatcher, StatementContext statementContext,
        Iterable<AddressTemplate> templates) {
    verifyTemplates(templates);/* w w w. j ava 2s  .c o  m*/

    ResultProcessor resultProcessor;
    ItemRenderer<JsonObject> itemRenderer;
    int numberOfTemplates = Iterables.size(templates);

    if (numberOfTemplates == 1) {
        AddressTemplate template = templates.iterator().next();
        int wildcards = Iterables.size(Splitter.on('*').split(template.toString())) - 1;
        if (wildcards == 0 || (wildcards == 1 && "*".equals(template.lastValue()))) {
            resultProcessor = new NamesResultProcessor();
            itemRenderer = new StringRenderer<>(result -> result.get(NAME).asString());

        } else {
            resultProcessor = new SingleReadChildrenProcessor();
            itemRenderer = new ReadChildrenRenderer();
        }

    } else {
        resultProcessor = new CompositeReadChildrenProcessor();
        itemRenderer = new ReadChildrenRenderer();
    }

    Options options = new OptionsBuilder<JsonObject>((query, response) -> {
        List<Operation> operations = stream(templates.spliterator(), false)
                .map(template -> template.resolve(statementContext))
                .map(address -> operation(address, numberOfTemplates)).collect(toList());
        if (operations.size() == 1) {
            dispatcher.execute(operations.get(0),
                    result -> response.response(resultProcessor.process(query, result)),
                    (operation, failure) -> {
                        logger.error(ERROR_MESSAGE, templates, failure);
                        response.response(new JsonObject[0]);

                    }, (operation, exception) -> {
                        logger.error(ERROR_MESSAGE, templates, exception.getMessage());
                        response.response(new JsonObject[0]);
                    });

        } else {
            dispatcher.execute(new Composite(operations),
                    (CompositeResult result) -> response.response(resultProcessor.process(query, result)),
                    (operation, failure) -> {
                        logger.error(ERROR_MESSAGE, templates, failure);
                        response.response(new JsonObject[0]);

                    }, (operation, exception) -> {
                        logger.error(ERROR_MESSAGE, templates, exception.getMessage());
                        response.response(new JsonObject[0]);
                    });
        }
    }).renderItem(itemRenderer).build();
    init(options);
}

From source file:org.tensorics.core.tensor.lang.TensorStructurals.java

/**
 * Merges the given set of the Tensors based on information in their context and dimensions. This operation is only
 * possible, if the following preconditions are fulfilled:
 * <ul>//from   ww w. j  a va 2  s.c om
 * <li>The contexts of all the tensors have THE SAME dimensions AND</li>
 * <li>The dimensions of all the tensors are THE SAME (first found tensor dimension is taken as an reference)</li>
 * </ul>
 * 
 * @param tensors to be merged.
 * @return a merged tensor.
 * @throws IllegalArgumentException if zero or one tensor is put to be merged OR if tensors dimensionality and their
 *             context positions dimensionality is not equal OR tensor context is empty.
 */
public static <E> Tensor<E> merge(Iterable<Tensor<E>> tensors) {
    if (Iterables.isEmpty(tensors) || Iterables.size(tensors) == 1) {
        throw new IllegalArgumentException("Cannot merge empty or one element list of tensors!");
    }
    Tensor<E> firstTensor = tensors.iterator().next();
    Set<Class<?>> refDimensionSet = firstTensor.shape().dimensionSet();
    Position refContextPosition = firstTensor.context();
    Set<Class<?>> outcomeDimensionSet = new HashSet<>(refDimensionSet);
    Set<Class<?>> dimensionSet = refContextPosition.dimensionSet();
    if (dimensionSet.isEmpty()) {
        throw new IllegalArgumentException("Cannot merge tensors with empty context!");
    }
    outcomeDimensionSet.addAll(dimensionSet);
    Builder<E> tensorBuilder = ImmutableTensor.builder(outcomeDimensionSet);

    for (Tensor<E> oneTensor : tensors) {
        if (TensorStructurals.isValidInTermsOfDimensions(oneTensor, refDimensionSet,
                refContextPosition.dimensionSet())) {
            tensorBuilder.putAll(oneTensor.context(), oneTensor);
        } else {
            throw new IllegalArgumentException(
                    "One of the tensors in the provided list does not fit the others on dimensions."
                            + " Cannot continiue merging" + oneTensor);
        }
    }
    return tensorBuilder.build();
}