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

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

Introduction

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

Prototype

public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip) 

Source Link

Document

Returns a view of iterable that skips its first numberToSkip elements.

Usage

From source file:com.github.jsdossier.JsDoc.java

private void parse() {
    if (parsed) {
        return;/* www .ja  va2  s .c  o m*/
    }
    parsed = true;

    String original = Strings.nullToEmpty(info.getOriginalCommentString());
    if (original.isEmpty()) {
        return;
    }
    if (info.getStaticSourceFile() != null && info.getOriginalCommentPosition() > 0) {
        int offset = info.getOriginalCommentPosition();
        int column = info.getStaticSourceFile().getColumnOfOffset(offset);
        if (column > 0) {
            original = Strings.repeat(" ", column) + original;
        }
    }
    original = original.substring(0, original.length() - 2); // subtract closing */

    Iterable<String> lines = Splitter.on(EOL_PATTERN).split(original);
    int firstAnnotation = findFirstAnnotationLine(lines);
    int annotationOffset = 0;
    if (firstAnnotation != -1 && !info.getMarkers().isEmpty()) {
        blockComment = processBlockCommentLines(Iterables.limit(lines, firstAnnotation));

        JSDocInfo.StringPosition firstAnnotationPosition = info.getMarkers().iterator().next().getAnnotation();

        annotationOffset = firstAnnotationPosition.getStartLine() - firstAnnotation;
    } else {
        blockComment = processBlockCommentLines(lines);
    }

    // If we failed to extract a block comment, yet the original JSDoc has one, we've
    // probably encountered a case where the compiler merged multiple JSDoc comments
    // into one. Try to recover by parsing the compiler's provided block comment.
    if (isNullOrEmpty(blockComment) && !isNullOrEmpty(info.getBlockDescription())) {
        blockComment = processBlockCommentLines(Splitter.on('\n').split(info.getBlockDescription()));
    }

    for (JSDocInfo.Marker marker : info.getMarkers()) {
        Optional<Annotation> annotation = Annotation.forMarker(marker);
        if (!annotation.isPresent()) {
            continue; // Unrecognized/unsupported annotation.
        }

        JSDocInfo.StringPosition description = marker.getDescription();
        if (description == null) {
            continue;
        }

        int startLine = description.getStartLine() - annotationOffset;
        Iterable<String> descriptionLines = Iterables.skip(lines, startLine);

        int numLines = Math.max(description.getEndLine() - description.getStartLine(), 1);
        descriptionLines = Iterables.limit(descriptionLines, numLines);

        switch (annotation.get()) {
        case DEFINE:
            defineComment = processDescriptionLines(descriptionLines, description);
            break;
        case DEPRECATED:
            deprecationReason = processDescriptionLines(descriptionLines, description);
            break;
        case FILEOVERVIEW:
            fileoverview = processDescriptionLines(descriptionLines, description);
            break;
        case PARAM:
            String name = marker.getNameNode().getItem().getString();
            parameters.put(name, new Parameter(name, getJsTypeExpression(marker),
                    processDescriptionLines(descriptionLines, description)));
            break;
        case RETURN:
            returnDescription = processDescriptionLines(descriptionLines, description);
            break;
        case SEE:
            seeClauses.add(processDescriptionLines(descriptionLines, description));
            break;
        case THROWS:
            throwsClauses.add(new ThrowsClause(getJsTypeExpression(marker),
                    processDescriptionLines(descriptionLines, description)));
            break;
        }
    }

    if (isNullOrEmpty(blockComment)) {
        if (!isNullOrEmpty(fileoverview)) {
            blockComment = fileoverview;
        } else if (!isNullOrEmpty(defineComment)) {
            blockComment = defineComment;
        }
    }
}

From source file:org.kiji.schema.util.DebugResourceTracker.java

/**
 * Registers a resource that should be cleaned up and removed before JVM shutdown. When using
 * reference level tracking, the message and the current stack trace will be logged.
 *
 * @param resource Object which should be cleaned up before JVM shutdown.
 * @param message string which will be logged along with the current stack trace if the resource
 *    is not closed before shutdown. A good example of this error message is the stack trace at
 *    the time the object was created./* w w w.  j  a  va2s  .c om*/
 */
public void registerResource(final Object resource, final String message) {
    switch (TRACKING_LEVEL) {
    case NONE:
        break;
    case COUNTER: {
        mCounter.incrementAndGet();
        break;
    }
    case REFERENCES: {
        // Skip two stack frames. One for the throwable, one for this method.
        final String stackTrace = Joiner.on('\n')
                .join(Iterables.skip(Lists.newArrayList(ExceptionUtils.getStackFrames(new Throwable())), 2));
        mCounter.incrementAndGet();
        mReferenceTracker.registerResource(resource, message, stackTrace);
        break;
    }
    default:
        throw new InternalKijiError(
                String.format("Unknown DebugResourceTracker.TrackingType: %s", TRACKING_LEVEL));
    }
}

From source file:org.kiji.commons.ResourceTracker.java

/**
 * Registers a resource that should be cleaned up and removed before JVM shutdown. When using
 * reference level tracking, the message and the current stack trace will be logged.
 *
 * @param resource Object which should be cleaned up before JVM shutdown.
 * @param message string which will be logged along with the current stack trace if the resource
 *    is not closed before shutdown. A good example of this error message is the stack trace at
 *    the time the object was created.//w ww.  ja va 2s .  c o m
 */
public void registerResource(final Object resource, final String message) {
    switch (TRACKING_LEVEL) {
    case NONE:
        break;
    case COUNTER: {
        mCounter.incrementAndGet();
        break;
    }
    case REFERENCES: {
        // Skip two stack frames. One for the exception, one for this method.
        final String stackTrace = Joiner.on('\n')
                .join(Iterables.skip(Arrays.asList(new Exception().getStackTrace()), 2));
        mCounter.incrementAndGet();
        mReferenceTracker.registerResource(resource, message, stackTrace);
        break;
    }
    default:
        throw new IllegalArgumentException(
                String.format("Unknown ResourceTracker.TrackingLevel: %s", TRACKING_LEVEL));
    }
}

From source file:org.sosy_lab.cpachecker.util.predicates.interpolation.strategy.AbstractTreeInterpolation.java

/** check, if there exists a function-exit-node to the current call-node. */
protected static <T> boolean callHasReturn(
        final List<Triple<BooleanFormula, AbstractState, T>> formulasWithStatesAndGroupdIds, int callIndex) {
    // TODO caching as optimization to reduce from  k*O(n)  to  O(n)+k*O(1)  ?
    final Deque<CFANode> callstack = new ArrayDeque<>();

    {//from  ww  w .  j ava  2  s .c  o  m
        final AbstractState abstractionState = formulasWithStatesAndGroupdIds.get(callIndex).getSecond();
        final CFANode node = AbstractStates.extractLocation(abstractionState);
        assert (node instanceof FunctionEntryNode) : "call needed as input param";
        callstack.addLast(node);
    }

    // walk along path and track the call stack
    for (Triple<BooleanFormula, AbstractState, T> t : Iterables.skip(formulasWithStatesAndGroupdIds,
            callIndex + 1)) {
        assert !callstack.isEmpty() : "should have returned when callstack is empty";

        final AbstractState abstractionState = checkNotNull(t.getSecond());
        final CFANode node = AbstractStates.extractLocation(abstractionState);

        if (node instanceof FunctionEntryNode) {
            callstack.addLast(node);
        }

        final CFANode lastEntryNode = callstack.getLast();
        if ((node instanceof FunctionExitNode && ((FunctionExitNode) node).getEntryNode() == lastEntryNode)
        //|| (node.getEnteringSummaryEdge() != null
        // && node.getEnteringSummaryEdge().getPredecessor().getLeavingEdge(0).getSuccessor() == lastEntryNode)
        ) {
            callstack.removeLast();

            // we found the function exit for the input param
            if (callstack.isEmpty()) {
                return true;
            }
        }
    }
    return false;
}

From source file:google.registry.tools.GenerateAuctionDataCommand.java

/** Return a record line for the given application. */
private String emitApplication(DomainApplication domainApplication, ContactResource registrant) {
    Optional<PostalInfo> postalInfo = Optional.fromNullable(registrant.getInternationalizedPostalInfo())
            .or(Optional.fromNullable(registrant.getLocalizedPostalInfo()));
    Optional<ContactAddress> address = Optional
            .fromNullable(postalInfo.isPresent() ? postalInfo.get().getAddress() : null);
    List<String> street = address.isPresent() ? address.get().getStreet() : ImmutableList.<String>of();
    Optional<ContactPhoneNumber> phoneNumber = Optional.fromNullable(registrant.getVoiceNumber());

    // Each line containing an auction participant has the following format:
    ////from  w  w w. j av  a2  s  .  com
    // Domain|Application ID|Application timestamp|Last update date|Registrar Name|
    // Registrant Name|Registrant Company|Registrant Address 1|Registrant Address 2|
    // Registrant City|Registrant Province|Registrant Postal Code|Registrant Country|
    // Registrant Email|Registrant Telephone|Reserve|Application Type
    return Joiner.on('|')
            .join(ImmutableList.of(domainApplication.getFullyQualifiedDomainName(),
                    domainApplication.getForeignKey(), formatter.print(domainApplication.getCreationTime()),
                    domainApplication.getLastEppUpdateTime() != null
                            ? formatter.print(domainApplication.getLastEppUpdateTime())
                            : "",
                    domainApplication.getCurrentSponsorClientId(),
                    nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getName() : ""),
                    nullToEmpty(postalInfo.isPresent() ? postalInfo.get().getOrg() : ""),
                    Iterables.getFirst(street, ""), Joiner.on(' ').skipNulls().join(Iterables.skip(street, 1)),
                    nullToEmpty(address.isPresent() ? address.get().getCity() : ""),
                    nullToEmpty(address.isPresent() ? address.get().getState() : ""),
                    nullToEmpty(address.isPresent() ? address.get().getZip() : ""),
                    nullToEmpty(address.isPresent() ? address.get().getCountryCode() : ""),
                    nullToEmpty(registrant.getEmailAddress()),
                    nullToEmpty(phoneNumber.isPresent() ? phoneNumber.get().toPhoneString() : ""), "",
                    domainApplication.getEncodedSignedMarks().isEmpty() ? "Landrush" : "Sunrise"));
}

From source file:com.facebook.presto.operator.WindowOperator.java

public WindowOperator(OperatorContext operatorContext, List<Type> sourceTypes, List<Integer> outputChannels,
        List<WindowFunctionDefinition> windowFunctionDefinitions, List<Integer> partitionChannels,
        List<Integer> preGroupedChannels, List<Integer> sortChannels, List<SortOrder> sortOrder,
        int preSortedChannelPrefix, FrameInfo frameInfo, int expectedPositions) {
    requireNonNull(operatorContext, "operatorContext is null");
    requireNonNull(outputChannels, "outputChannels is null");
    requireNonNull(windowFunctionDefinitions, "windowFunctionDefinitions is null");
    requireNonNull(partitionChannels, "partitionChannels is null");
    requireNonNull(preGroupedChannels, "preGroupedChannels is null");
    checkArgument(partitionChannels.containsAll(preGroupedChannels),
            "preGroupedChannels must be a subset of partitionChannels");
    requireNonNull(sortChannels, "sortChannels is null");
    requireNonNull(sortOrder, "sortOrder is null");
    checkArgument(sortChannels.size() == sortOrder.size(),
            "Must have same number of sort channels as sort orders");
    checkArgument(preSortedChannelPrefix <= sortChannels.size(),
            "Cannot have more pre-sorted channels than specified sorted channels");
    checkArgument(//  ww  w.jav  a 2s.c  om
            preSortedChannelPrefix == 0
                    || ImmutableSet.copyOf(preGroupedChannels).equals(ImmutableSet.copyOf(partitionChannels)),
            "preSortedChannelPrefix can only be greater than zero if all partition channels are pre-grouped");
    requireNonNull(frameInfo, "frameInfo is null");

    this.operatorContext = operatorContext;
    this.outputChannels = Ints.toArray(outputChannels);
    this.windowFunctions = windowFunctionDefinitions.stream()
            .map(WindowFunctionDefinition::createWindowFunction).collect(toImmutableList());
    this.frameInfo = frameInfo;

    this.types = Stream
            .concat(outputChannels.stream().map(sourceTypes::get),
                    windowFunctionDefinitions.stream().map(WindowFunctionDefinition::getType))
            .collect(toImmutableList());

    this.pagesIndex = new PagesIndex(sourceTypes, expectedPositions);
    this.preGroupedChannels = Ints.toArray(preGroupedChannels);
    this.preGroupedPartitionHashStrategy = pagesIndex.createPagesHashStrategy(preGroupedChannels,
            Optional.<Integer>empty());
    List<Integer> unGroupedPartitionChannels = partitionChannels.stream()
            .filter(channel -> !preGroupedChannels.contains(channel)).collect(toImmutableList());
    this.unGroupedPartitionHashStrategy = pagesIndex.createPagesHashStrategy(unGroupedPartitionChannels,
            Optional.empty());
    List<Integer> preSortedChannels = sortChannels.stream().limit(preSortedChannelPrefix)
            .collect(toImmutableList());
    this.preSortedPartitionHashStrategy = pagesIndex.createPagesHashStrategy(preSortedChannels,
            Optional.<Integer>empty());
    this.peerGroupHashStrategy = pagesIndex.createPagesHashStrategy(sortChannels, Optional.empty());

    this.pageBuilder = new PageBuilder(this.types);

    if (preSortedChannelPrefix > 0) {
        // This already implies that set(preGroupedChannels) == set(partitionChannels) (enforced with checkArgument)
        this.orderChannels = ImmutableList.copyOf(Iterables.skip(sortChannels, preSortedChannelPrefix));
        this.ordering = ImmutableList.copyOf(Iterables.skip(sortOrder, preSortedChannelPrefix));
    } else {
        // Otherwise, we need to sort by the unGroupedPartitionChannels and all original sort channels
        this.orderChannels = ImmutableList.copyOf(concat(unGroupedPartitionChannels, sortChannels));
        this.ordering = ImmutableList
                .copyOf(concat(nCopies(unGroupedPartitionChannels.size(), ASC_NULLS_LAST), sortOrder));
    }
}

From source file:com.facebook.buck.rules.coercer.ParamInfo.java

/** Returns the most-overridden getter on the abstract Immutable. */
@SuppressWarnings("PMD.EmptyCatchBlock")
private Method findClosestGetterOnAbstractClassOrInterface() {
    Iterable<Class<?>> superClasses = Iterables
            .skip(Types.getSupertypes(setter.getDeclaringClass().getEnclosingClass()), 1);
    ImmutableList<String> getterNames = getGetterNames();

    for (Class<?> clazz : superClasses) {
        for (String getterName : getterNames) {
            try {
                return clazz.getDeclaredMethod(getterName);
            } catch (NoSuchMethodException e) {
                // Handled below
            }//from   w  w  w  . ja va 2  s  .  c om
        }
    }
    throw new IllegalStateException(
            String.format("Couldn't find declared getter for %s#%s. Tried parent classes %s methods: %s",
                    setter.getDeclaringClass(), setter.getName(), superClasses, getterNames));
}

From source file:org.sosy_lab.cpachecker.cpa.value.refiner.ValueAnalysisPathInterpolator.java

/**
 * This method performs interpolation on the complete path, based on the
 * use-def-relation obtained by {@link AssumptionUseDefinitionCollector} or
 * its subclass. It creates fake interpolants that are not inductive.
 *
 * @param errorPathPrefix the error path prefix to interpolate
 * @return/*  ww w .  jav  a  2 s .c  o  m*/
 */
private Map<ARGState, ValueAnalysisInterpolant> performPathBasedInterpolation(ARGPath errorPathPrefix) {

    assert (errorPathPrefix.getFirstState().getParents()
            .isEmpty()) : "static interpolation requires cpa.value.refinement.useTopDownInterpolationStrategy to be set to 'true'";

    AssumptionUseDefinitionCollector useDefinitionCollector = prefixPreference == ErrorPathPrefixPreference.DEFAULT
            ? new AssumptionUseDefinitionCollector()
            : new InitialAssumptionUseDefinitionCollector();

    Set<String> useDefRelation = useDefinitionCollector.obtainUseDefInformation(errorPathPrefix.asEdgesList());

    totalInterpolationQueries.setNextValue(1);
    sizeOfInterpolant.setNextValue(useDefRelation.size() * errorPathPrefix.size());

    Map<ARGState, ValueAnalysisInterpolant> pathInterpolants = new LinkedHashMap<>(errorPathPrefix.size());

    // add the "fake" interpolant for each state except the root of the ARG;
    // this makes the first child of the root the refinement root
    ValueAnalysisInterpolant fakeItp = createFakeInterpolant(useDefRelation);
    for (ARGState state : Iterables.skip(errorPathPrefix.asStatesList(), 1)) {
        pathInterpolants.put(state, fakeItp);
    }

    return pathInterpolants;
}

From source file:org.kiji.schema.util.DebugResourceTracker.java

/**
 * Registers a resource that should be cleaned up and removed before JVM shutdown. When using
 * reference level tracking, the message will be the {@link #toString()} of the resource, and the
 * current stack trace./*w  w  w  .j ava2s  .  co m*/
 * <p>
 * This method will call {@link #toString()} on the passed in resource, so it must be in a valid
 * state.
 *
 * @param resource Object which should be cleaned up before JVM shutdown.
 */
public void registerResource(final Object resource) {
    switch (TRACKING_LEVEL) {
    case NONE:
        break;
    case COUNTER: {
        mCounter.incrementAndGet();
        break;
    }
    case REFERENCES: {
        // Skip two stack frames. One for the throwable, one for this method.
        final String stackTrace = Joiner.on('\n')
                .join(Iterables.skip(Lists.newArrayList(ExceptionUtils.getStackFrames(new Throwable())), 2));

        mCounter.incrementAndGet();
        mReferenceTracker.registerResource(resource, resource.toString(), stackTrace);
        break;
    }
    default:
        throw new InternalKijiError(
                String.format("Unknown DebugResourceTracker.TrackingType: %s", TRACKING_LEVEL));
    }
}

From source file:org.kiji.commons.ResourceTracker.java

/**
 * Registers a resource that should be cleaned up and removed before JVM shutdown. When using
 * reference level tracking, the message will be the {@link #toString()} of the resource, and the
 * current stack trace.//from  w  w w.  j  a  va2s .c om
 * <p>
 * This method will call {@link #toString()} on the passed in resource, so it must be in a valid
 * state.
 *
 * @param resource Object which should be cleaned up before JVM shutdown.
 */
public void registerResource(final Object resource) {
    switch (TRACKING_LEVEL) {
    case NONE:
        break;
    case COUNTER: {
        mCounter.incrementAndGet();
        break;
    }
    case REFERENCES: {
        // Skip two stack frames. One for the exception, one for this method.
        final String stackTrace = Joiner.on('\n')
                .join(Iterables.skip(Arrays.asList(new Exception().getStackTrace()), 2));

        mCounter.incrementAndGet();
        mReferenceTracker.registerResource(resource, resource.toString(), stackTrace);
        break;
    }
    default:
        throw new IllegalStateException(
                String.format("Unknown ResourceTracker.TrackingLevel: %s", TRACKING_LEVEL));
    }
}