Java Code Examples for com.google.common.collect.Iterables#size()

The following examples show how to use com.google.common.collect.Iterables#size() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public boolean matchesSafely(T object, Description mismatch) {
    int matches = 0;
    int possibleMatches = Iterables.size(matchers);

    for (Matcher<? super T> matcher : matchers) {
        if (!matcher.matches(object)) {
            if (!mismatch.toString().endsWith("but: ")) {
                mismatch.appendText("\n          ");
            }
            matcher.describeMismatch(object, mismatch);
        } else {
            matches++;
            if (validWhen(matches, possibleMatches)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 2
@Override
public double getNodeCommunityWeight(int nodeCommunity)
{
    double nodeCommunityWeight = 0;
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            ResourceIterable<Node> iter = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, NODE_COMMUNITY,
                nodeCommunity);
            if (Iterables.size(iter) > 1)
            {
                for (Node n : iter)
                {
                    nodeCommunityWeight += getNodeOutDegree(n);
                }
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get node community weight", e);
        }
    }

    return nodeCommunityWeight;
}
 
Example 3
@Override
public boolean isExtensionUpdateRequired(final CheckCatalog catalog, final IPluginExtension extension, final Iterable<IPluginElement> elements) {
  // @Format-Off
  final boolean result = extension.getPoint().equals(PREFERENCES_EXTENSION_POINT_ID)
      && (!extensionNameMatches(extension, catalog)
      || Iterables.size(elements) != 2
      || !initializerClassMatches(getInitializerElement(elements), getTargetClassName(catalog)));
  return result;
  // @Format-On
}
 
Example 4
public ParallelFromStreamRecordsFunction(TypeSerializer<StreamRecord<T>> serializer,
                                         Iterable<StreamRecord<T>> input,
                                         Boolean flushOpenWindows
) throws IOException {
    this.serializer = serializer;
    elementsSerialized = serializeOutput(input, serializer).toByteArray();
    numElements = Iterables.size(input);
    this.flushOpenWindows = flushOpenWindows;
}
 
Example 5
private void count(Group g) {
  ndims += g.getDimensions().size();
  nvars += g.getVariables().size();
  ngatts += Iterables.size(g.attributes());
  ngroups += g.getGroups().size();

  for (Variable v : g.getVariables()) {
    natts += Iterables.size(v.attributes());
    if (v instanceof Structure) {
      nstructFields += ((Structure) v).getVariables().size();
    }
  }
  for (Group ng : g.getGroups())
    count(ng);
}
 
Example 6
@Override
public double getCommunityWeight(int community)
{
    double communityWeight = 0;
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            ResourceIterable<Node> iter = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, COMMUNITY, community);
            if (Iterables.size(iter) > 1)
            {
                for (Node n : iter)
                {
                    communityWeight += getNodeOutDegree(n);
                }
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get community weight", e);
        }
    }

    return communityWeight;
}
 
Example 7
Source Project: crate   File: SimpleTopNProjectorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testProjectLimitLessThanLimitUpStream() throws Throwable {
    Projector projector = prepareProjector(10, TopN.NO_OFFSET);
    BatchIterator<Row> batchIterator = projector.apply(TestingBatchIterators.range(0, 5));
    consumer.accept(batchIterator, null);
    Bucket projected = consumer.getBucket();
    assertThat(projected.size(), is(5));

    int iterateLength = Iterables.size(consumer.getBucket());
    assertThat(iterateLength, is(5));
}
 
Example 8
Source Project: flink-spector   File: OutputWithSize.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSafely(Iterable<T> item, Description mismatchDescription) {
    int size = Iterables.size(item);
    boolean matches = sizeMatcher.matches(size);
    if (!matches) {
        sizeMatcher.describeMismatch(size, mismatchDescription);
    }
    return matches;
}
 
Example 9
public AssertableDiagnostics assertDiagnosticsCount(int size) {
	int count = Iterables.size(getAllDiagnostics());
	if (count == size)
		return this;
	fail("There are " + count + " diagnostics, but " + size + " are expected.");
	return this;
}
 
Example 10
protected ISerializationContext getContext(EObject semanticObject) {
	Iterable<ISerializationContext> contexts = contextFinder.findByContentsAndContainer(semanticObject, null);
	if (Iterables.size(contexts) != 1) {
		StringBuilder msg = new StringBuilder();
		msg.append("One context is expected, but " + Iterables.size(contexts) + " have been found\n");
		msg.append("Contexts: " + Joiner.on(", ").join(contexts));
		msg.append("Semantic Object: " + EmfFormatter.objPath(semanticObject));
		Assert.fail(msg.toString());
	}
	return contexts.iterator().next();
}
 
Example 11
@Test
public void testGetLeafMethods() {
  Iterable<Method> methods = methodReader.getLeafMethods();

  TestHelper helper = new TestHelper(Iterables.size(methods));
  for (Method method : methods) {
    helper.verifySingleMethod(method);
  }
  helper.verifyAllMethodsSeen();
}
 
Example 12
@Check
public void checkDuplicateFeatureParameter(final FeatureParameterValue value) {
	FeatureConfiguration entry = (FeatureConfiguration) value.eContainer();
	Iterable<FeatureParameterValue> filter = Iterables.filter(entry.getParameterValues(),
			new Predicate<FeatureParameterValue>() {
				public boolean apply(FeatureParameterValue input) {
					return (input.getParameter().getName().equals(value.getParameter().getName()));
				}
			});
	if (Iterables.size(filter) > 1) {
		error(DUPLICATE_PARAMETER, SGenPackage.Literals.FEATURE_PARAMETER_VALUE__PARAMETER);
	}
}
 
Example 13
@Override
public boolean isExtensionUpdateRequired(final CheckCatalog catalog, final IPluginExtension extension, final Iterable<IPluginElement> elements) {
  // CHECKSTYLE:OFF
  // @Format-Off
  final boolean result = extension.getPoint().equals(CHECK_EXTENSION_POINT_ID)
      && (!extensionNameMatches(extension, catalog)
      || Iterables.size(elements) != 1
      || !targetClassMatches(Iterables.get(elements, 0), getTargetClassName(catalog))
      || catalog.getGrammar() == null && Iterables.get(elements, 0).getAttribute(LANGUAGE_ELEMENT_TAG) != null
      || catalog.getGrammar() != null && !languageNameMatches(Iterables.get(elements, 0), catalog.getGrammar().getName())
  );
  return result;
  // @Format-On
  // CHECKSTYLE:ON
}
 
Example 14
Source Project: spoofax   File: StrategoAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
@Override public ISpoofaxAnalyzeResults analyzeAll(Iterable<ISpoofaxParseUnit> inputs, IContext context,
    IProgress progress, ICancel cancel) throws AnalysisException, InterruptedException {
    cancel.throwIfCancelled();
    
    final ILanguageImpl language = context.language();

    final FacetContribution<AnalysisFacet> facetContribution = language.facetContribution(AnalysisFacet.class);
    if(facetContribution == null) {
        logger.debug("No analysis required for {}", language);
        return new SpoofaxAnalyzeResults(context);
    }
    final AnalysisFacet facet = facetContribution.facet;

    cancel.throwIfCancelled();
    final HybridInterpreter runtime;
    try {
        runtime = runtimeService.runtime(facetContribution.contributor, context);
    } catch(MetaborgException e) {
        throw new AnalysisException(context, "Failed to get Stratego runtime", e);
    }

    final int size = Iterables.size(inputs);
    progress.setWorkRemaining(size);
    final Collection<ISpoofaxAnalyzeUnit> results = Lists.newArrayListWithCapacity(size);
    for(ISpoofaxParseUnit input : inputs) {
        cancel.throwIfCancelled();
        if(!input.valid()) {
            logger.warn("Parse input for {} is invalid, cannot analyze", input.source());
            // TODO: throw exception instead?
            progress.work(1);
            continue;
        }
        final ISpoofaxAnalyzeUnit result = analyze(input, context, runtime, facet.strategyName, termFactory);
        results.add(result);
        progress.work(1);
    }
    return new SpoofaxAnalyzeResults(results, context);
}
 
Example 15
private int writeAtts(DataOutputStream stream, Iterable<Attribute> atts) throws IOException {
  int natts = Iterables.size(atts);
  if (null != stream) {
    if (natts == 0) {
      stream.writeInt(0);
      stream.writeInt(0);
    } else {
      stream.writeInt(N3header.MAGIC_ATT);
      stream.writeInt(natts);
    }
  }
  int hsize = 8;

  for (Attribute att : atts) {
    hsize += writeString(stream, N3iosp.makeValidNetcdfObjectName(att.getShortName()));
    int type = N3header.getType(att.getDataType());
    if (null != stream) {
      stream.writeInt(type);
    }
    hsize += 4;

    if (type == 2) {
      hsize += writeStringValues(stream, att);
    } else {
      int nelems = att.getLength();
      if (null != stream) {
        stream.writeInt(nelems);
      }
      hsize += 4;

      int nbytes = 0;
      for (int j = 0; j < nelems; j++) {
        nbytes += writeAttributeValue(stream, att.getNumericValue(j));
      }
      hsize += nbytes;

      hsize += pad(stream, nbytes, (byte) 0);
    }
  }

  return hsize;
}
 
Example 16
@Override
public long count() {
  return Iterables.size(this);
}
 
Example 17
public int size() {
  return Iterables.size(features());
}
 
Example 18
public void showBenchmarks()
{
  final int start = 1;
  final int factor = 10;
  final int end = 10000000;
  final int radius = 10;

  for (int numPoints = start; numPoints <= end; numPoints *= factor) {
    try {
      BitmapFactory bf = new ConciseBitmapFactory();
      RTree tree = new RTree(2, new LinearGutmanSplitStrategy(0, 50, bf), bf);

      Stopwatch stopwatch = Stopwatch.createStarted();
      Random rand = new Random();
      for (int i = 0; i < numPoints; i++) {
        tree.insert(new float[]{(float) (rand.nextDouble() * 100), (float) (rand.nextDouble() * 100)}, i);
      }
      long stop = stopwatch.elapsed(TimeUnit.MILLISECONDS);
      System.out.printf("[%,d]: insert = %,d ms%n", numPoints, stop);

      stopwatch.reset().start();
      ImmutableRTree searchTree = ImmutableRTree.newImmutableFromMutable(tree);
      stop = stopwatch.elapsed(TimeUnit.MILLISECONDS);
      System.out.printf("[%,d]: size = %,d bytes%n", numPoints, searchTree.toBytes().length);
      System.out.printf("[%,d]: buildImmutable = %,d ms%n", numPoints, stop);

      stopwatch.reset().start();

      Iterable<ImmutableBitmap> points = searchTree.search(new RadiusBound(new float[]{50, 50}, radius));

      Iterables.size(points);
      stop = stopwatch.elapsed(TimeUnit.MILLISECONDS);

      System.out.printf("[%,d]: search = %,dms%n", numPoints, stop);

      stopwatch.reset().start();

      ImmutableBitmap finalSet = bf.union(points);

      stop = stopwatch.elapsed(TimeUnit.MILLISECONDS);
      System.out.printf("[%,d]: union of %,d points in %,d ms%n", numPoints, finalSet.size(), stop);
    }
    catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }
}
 
Example 19
public <T extends EObject> void forEachSafely(ITreeAppendable appendable, Iterable<T> elements,
		Procedure1<? super LoopParams> loopInitializer, Procedure2<? super T, ? super ITreeAppendable> body) {
	if (Iterables.isEmpty(elements)) {
		return;
	}
	LoopParams loopParams = ObjectExtensions.operator_doubleArrow(new LoopParams(), loopInitializer);
	boolean allElementsBroken = Iterables
			.size(Iterables.<T>filter(elements, (T it) -> hasErrors(it))) == Iterables.size(elements);
	ITreeAppendable currentAppendable = null;
	if (allElementsBroken) {
		currentAppendable = openErrorAppendable(appendable, null);
	} else {
		currentAppendable = appendable;
	}
	loopParams.appendPrefix(currentAppendable);
	boolean isFirst = true;
	boolean isFirstBroken = true;
	for (T element : elements) {
		if (!hasErrors(element)) {
			currentAppendable = closeErrorAppendable(appendable, currentAppendable);
			if (!isFirst) {
				loopParams.appendSeparator(appendable);
			}
			isFirst = false;
			body.apply(element, appendable);
		} else {
			if (!allElementsBroken) {
				currentAppendable = openErrorAppendable(appendable, currentAppendable);
			}
			if (!isFirst || !isFirstBroken) {
				loopParams.appendSeparator(currentAppendable);
			}
			isFirstBroken = false;
			try {
				body.apply(element, currentAppendable);
			} catch (Exception ignoreMe) {
			}
		}
	}
	if (!allElementsBroken) {
		currentAppendable = closeErrorAppendable(appendable, currentAppendable);
	}
	loopParams.appendSuffix(currentAppendable);
	closeErrorAppendable(appendable, currentAppendable);
}
 
Example 20
Source Project: n4js   File: BuilderUtil.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/***/
public static int countResourcesInIndex() {
	return Iterables.size(getAllResourceDescriptions());
}