List of usage examples for com.google.common.collect Iterables skip
public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip)
From source file:edu.mit.streamjit.util.bytecode.insts.CallInst.java
public Iterable<Value> arguments() { return Iterables.skip(operands(), 1); }
From source file:google.registry.flows.host.HostFlowUtils.java
/** Return the {@link DomainResource} this host is subordinate to, or null for external hosts. */ static DomainResource lookupSuperordinateDomain(InternetDomainName hostName, DateTime now) throws EppException { Optional<InternetDomainName> tld = findTldForName(hostName); if (!tld.isPresent()) { // This is an host on a TLD we don't run, therefore obviously external, so we are done. return null; }//from www.j a v a2 s . c o m // This is a subordinate host String domainName = Joiner.on('.') .join(Iterables.skip(hostName.parts(), hostName.parts().size() - (tld.get().parts().size() + 1))); DomainResource superordinateDomain = loadByForeignKey(DomainResource.class, domainName, now); if (superordinateDomain == null || !isActive(superordinateDomain, now)) { throw new SuperordinateDomainDoesNotExistException(domainName); } return superordinateDomain; }
From source file:org.obm.servlet.filter.qos.handlers.RequestInfo.java
public RequestInfo<K> popContinuation() { Preconditions.checkState(continuationIds.size() > 0); return new RequestInfo<K>(key, numberOfRunningRequests, ImmutableList.copyOf(Iterables.skip(continuationIds, 1))); }
From source file:org.apache.mahout.knn.cluster.DataUtils.java
/** * Estimates the distance cutoff. In StreamingKMeans, the distance between two vectors divided * by this value is used as a probability threshold when deciding whether to form a new cluster * or not.//from w ww . j a va2 s . c o m * Small values (comparable to the minimum distance between two points) are preferred as they * guarantee with high likelihood that all but very close points are put in separate clusters * initially. The clusters themselves are actually collapsed periodically when their number goes * over the maximum number of clusters and the distanceCutoff is increased. * So, the returned value is only an initial estimate. * @param data * @param distanceMeasure * @param sampleLimit * @return the minimum distance between the first sampleLimit points * @see StreamingKMeans#clusterInternal(Iterable, boolean) */ public static double estimateDistanceCutoff(Iterable<? extends Vector> data, DistanceMeasure distanceMeasure, int sampleLimit) { Iterable<? extends Vector> limitedData = Iterables.limit(data, sampleLimit); double minDistance = Double.POSITIVE_INFINITY; int i = 1; for (Vector u : limitedData) { for (Vector v : Iterables.skip(limitedData, i)) { double distance = distanceMeasure.distance(u, v); if (minDistance > distance) { minDistance = distance; } } ++i; } return minDistance; }
From source file:org.obm.servlet.filter.qos.handlers.KeyRequestsInfo.java
public KeyRequestsInfo<K> popContinuation() { Preconditions.checkState(continuations.size() > 0); return new KeyRequestsInfo<K>(key, numberOfRunningRequests, ImmutableList.copyOf(Iterables.skip(continuations, 1))); }
From source file:org.apache.drill.exec.store.sys.store.LocalPersistentStore.java
@Override public Iterator<Map.Entry<String, V>> getRange(int skip, int take) { try {//from w w w. j av a 2 s . c om List<FileStatus> f = fs.list(false, basePath); if (f == null || f.isEmpty()) { return Collections.emptyIterator(); } List<String> files = Lists.newArrayList(); for (FileStatus stat : f) { String s = stat.getPath().getName(); if (s.endsWith(DRILL_SYS_FILE_SUFFIX)) { files.add(s.substring(0, s.length() - DRILL_SYS_FILE_SUFFIX.length())); } } Collections.sort(files); return Iterables.transform(Iterables.limit(Iterables.skip(files, skip), take), new Function<String, Entry<String, V>>() { @Nullable @Override public Entry<String, V> apply(String key) { return new ImmutableEntry<>(key, get(key)); } }).iterator(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.mahout.knn.means.StreamingKmeans.java
protected UpdatableSearcher clusterInternal(Iterable<MatrixSlice> data, int maxClusters, int depth, CentroidFactory centroidFactory) { // to cluster, we scan the data and either add each point to the nearest group or create a new group. // when we get too many groups, we need to increase the threshold and rescan our current groups Random rand = RandomUtils.getRandom(); int n = 0;/*from ww w .ja v a 2 s . c o m*/ UpdatableSearcher centroids = centroidFactory.create(); centroids.add(Centroid.create(0, Iterables.get(data, 0).vector()), 0); for (MatrixSlice row : Iterables.skip(data, 1)) { // estimate distance d to closest centroid WeightedVector closest = centroids.search(row.vector(), 1).get(0); if (rand.nextDouble() < closest.getWeight() / distanceCutoff) { // add new centroid, note that the vector is copied because we may mutate it later centroids.add(Centroid.create(centroids.size(), row.vector()), centroids.size()); } else { // merge against existing Centroid c = (Centroid) closest.getVector(); centroids.remove(c); c.update(row.vector()); centroids.add(c, c.getIndex()); } if (depth < 2 && centroids.size() > maxClusters) { maxClusters = (int) Math.max(maxClusters, 10 * Math.log(n)); // TODO does shuffling help? List<MatrixSlice> shuffled = Lists.newArrayList(centroids); Collections.shuffle(shuffled); centroids = clusterInternal(shuffled, maxClusters, depth + 1, centroidFactory); // in the original algorithm, with distributions with sharp scale effects, the // distanceCutoff can grow to excessive size leading sub-clustering to collapse // the centroids set too much. This test prevents increase in distanceCutoff // the current value is doing fine at collapsing the clusters. if (centroids.size() > 0.2 * maxClusters) { distanceCutoff *= BETA; } } n++; } return centroids; }
From source file:com.zulily.omicron.crontab.CrontabExpression.java
/** * Constructor// w w w .j ava2 s. com * * @param lineNumber the line number in the crontab * @param rawExpression the string value of the line as it appears in the crontab */ public CrontabExpression(final int lineNumber, final String rawExpression) { checkNotNull(rawExpression, "rawExpression"); checkArgument(lineNumber > 0, "lineNumber should be positive: %s", lineNumber); this.timestamp = Clock.systemUTC().millis(); this.lineNumber = lineNumber; final HashMap<ExpressionPart, ImmutableSortedSet<Integer>> runtimes = Maps.newHashMap(); checkArgument(!rawExpression.trim().isEmpty(), "Empty expression"); final String coalescedExpression = coalesceHashmarks(rawExpression.trim()); this.commented = coalescedExpression.startsWith("#"); this.rawExpression = this.commented ? coalescedExpression.substring(1) : coalescedExpression; boolean evaluationError = true; String userString = ""; String commandString = ""; try { final List<String> expressionParts = Utils.WHITESPACE_SPLITTER.splitToList(this.rawExpression); checkArgument(expressionParts.size() >= ExpressionPart.values().length, "Line %s does not contain all expected parts: %s", lineNumber, this.rawExpression); userString = expressionParts.get(ExpressionPart.ExecutingUser.ordinal()); // The command expression is everything after the user - just join it right back up with space separators // side-effect: collapses whitespace in the command - may break some commands out there that require lots of whitespace? commandString = Joiner.on(' ') .join(Iterables.skip(expressionParts, ExpressionPart.values().length - 1)); // Fill in the runtime schedule based on the cron expressions for (ExpressionPart expressionPart : ExpressionPart.values()) { // Ignore anything starting with or coming after the user value if (expressionPart.ordinal() >= ExpressionPart.ExecutingUser.ordinal()) { continue; } runtimes.put(expressionPart, evaluateExpressionPart(expressionPart, expressionParts.get(expressionPart.ordinal()))); } evaluationError = false; } catch (Exception e) { if (!this.isCommented()) { warn("[Line: {0}] Interpretation error: {1}", String.valueOf(lineNumber), e.getMessage()); } } this.malformed = evaluationError; this.executingUser = userString; this.command = commandString; this.expressionRuntimes = ImmutableMap.copyOf(runtimes); }
From source file:org.opendaylight.yangtools.yang.data.api.StackedYangInstanceIdentifier.java
@Nonnull @Override//from w w w .j av a2 s.com YangInstanceIdentifier createRelativeIdentifier(final int skipFromRoot) { // TODO: can we optimize this one? return YangInstanceIdentifier.create(Iterables.skip(getPathArguments(), skipFromRoot)); }
From source file:com.google.errorprone.bugpatterns.LockNotBeforeTry.java
private Description describe(MethodInvocationTree lockInvocation, TreePath statementPath, VisitorState state) { Tree lockStatement = statementPath.getLeaf(); ExpressionTree lockee = getReceiver(lockInvocation); if (lockee == null) { return NO_MATCH; }/* ww w . jav a2s . c o m*/ TryTree enclosingTry = state.findEnclosing(TryTree.class); if (enclosingTry != null && releases(enclosingTry, lockee, state)) { SuggestedFix fix = SuggestedFix.builder().replace(lockStatement, "") .prefixWith(enclosingTry, state.getSourceForNode(lockStatement)).build(); return buildDescription(lockInvocation).addFix(fix) .setMessage(String.format( "Prefer obtaining the lock for %s outside the try block. That way, if #lock" + " throws, the lock is not erroneously released.", state.getSourceForNode(getReceiver(lockInvocation)))) .build(); } Tree enclosing = state.getPath().getParentPath().getParentPath().getLeaf(); if (!(enclosing instanceof BlockTree)) { return NO_MATCH; } BlockTree block = (BlockTree) enclosing; int index = block.getStatements().indexOf(lockStatement); // Scan through the enclosing statements for (StatementTree statement : Iterables.skip(block.getStatements(), index + 1)) { // ... for a try/finally which releases this lock. if (statement instanceof TryTree && releases((TryTree) statement, lockee, state)) { SuggestedFix fix = SuggestedFix.builder().replace(lockStatement, "") .prefixWith(statement, state.getSourceForNode(lockStatement)).build(); return buildDescription(lockInvocation).addFix(fix) .setMessage("Prefer locking *immediately* before the try block which releases the lock to" + " avoid the possibility of any intermediate statements throwing.") .build(); } // ... or an unlock at the same level. if (statement instanceof ExpressionStatementTree) { ExpressionTree expression = ((ExpressionStatementTree) statement).getExpression(); if (acquires(expression, lockee, state)) { return buildDescription(lockInvocation) .setMessage(String.format("Did you forget to release the lock on %s?", state.getSourceForNode(getReceiver(lockInvocation)))) .build(); } if (releases(expression, lockee, state)) { SuggestedFix fix = SuggestedFix.builder().postfixWith(lockStatement, "try {") .prefixWith(statement, "} finally {").postfixWith(statement, "}").build(); return buildDescription(lockInvocation).addFix(fix) .setMessage(String.format("Prefer releasing the lock on %s inside a finally block.", state.getSourceForNode(getReceiver(lockInvocation)))) .build(); } } } return NO_MATCH; }