Example usage for com.google.common.collect Sets newHashSetWithExpectedSize

List of usage examples for com.google.common.collect Sets newHashSetWithExpectedSize

Introduction

In this page you can find the example usage for com.google.common.collect Sets newHashSetWithExpectedSize.

Prototype

public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) 

Source Link

Document

Creates a HashSet instance, with a high enough initial table size that it should hold expectedSize elements without resizing.

Usage

From source file:org.apache.impala.analysis.CaseExpr.java

@Override
protected void computeNumDistinctValues() {
    // Skip the first child if case expression
    int loopStart = (hasCaseExpr_ ? 1 : 0);

    // If all the outputs have a known number of distinct values (i.e. not -1), then
    // sum the number of distinct constants with the maximum NDV for the non-constants.
    ////  w  w  w . ja va2  s .c  o  m
    // Otherwise, the number of distinct values is undetermined. The input cardinality
    // (i.e. the when's) are not used.
    boolean allOutputsKnown = true;
    int numOutputConstants = 0;
    long maxOutputNonConstNdv = -1;
    HashSet<LiteralExpr> constLiteralSet = Sets.newHashSetWithExpectedSize(children_.size());

    for (int i = loopStart; i < children_.size(); ++i) {
        // The children follow this ordering:
        // [optional first child] when1 then1 when2 then2 ... else
        // After skipping optional first child, even indices are when expressions, except
        // for the last child, which can be an else expression
        if ((i - loopStart) % 2 == 0 && !(i == children_.size() - 1 && hasElseExpr_)) {
            // This is a when expression
            continue;
        }

        // This is an output expression (either then or else)
        Expr outputExpr = children_.get(i);

        if (outputExpr.isConstant()) {
            if (outputExpr.isLiteral()) {
                LiteralExpr outputLiteral = (LiteralExpr) outputExpr;
                if (constLiteralSet.add(outputLiteral))
                    ++numOutputConstants;
            } else {
                ++numOutputConstants;
            }
        } else {
            long outputNdv = outputExpr.getNumDistinctValues();
            if (outputNdv == -1)
                allOutputsKnown = false;
            maxOutputNonConstNdv = Math.max(maxOutputNonConstNdv, outputNdv);
        }
    }

    // Else unspecified => NULL constant, which is not caught above
    if (!hasElseExpr_)
        ++numOutputConstants;

    if (allOutputsKnown) {
        if (maxOutputNonConstNdv == -1) {
            // All must be constant, because if we hit any SlotRef, this would be set
            numDistinctValues_ = numOutputConstants;
        } else {
            numDistinctValues_ = numOutputConstants + maxOutputNonConstNdv;
        }
    } else {
        // There is no correct answer when statistics are missing. Neither the
        // known outputs nor the inputs provide information
        numDistinctValues_ = -1;
    }
}

From source file:com.google.devtools.build.skyframe.SimpleCycleDetector.java

/**
 * Removes direct children of key from toVisit and from the entry itself, and makes the entry
 * ready if necessary. We must do this because it would not make sense to try to build the
 * children after building the entry. It would violate the invariant that a parent can only be
 * built after its children are built; See bug "Precondition error while evaluating a Skyframe
 * graph with a cycle"./* w  w w  .ja  va  2  s . c om*/
 *
 * @param key SkyKey of node in a cycle.
 * @param entry NodeEntry of node in a cycle.
 * @param cycleChild direct child of key in the cycle, or key itself if the cycle is a self-edge.
 * @param toVisit list of remaining nodes to visit by the cycle-checker.
 * @param cycleLength the length of the cycle found.
 */
private static Set<SkyKey> removeDescendantsOfCycleValue(SkyKey key, NodeEntry entry,
        @Nullable SkyKey cycleChild, Iterable<SkyKey> toVisit, int cycleLength,
        ParallelEvaluatorContext evaluatorContext) throws InterruptedException {
    GroupedList<SkyKey> directDeps = entry.getTemporaryDirectDeps();
    Set<SkyKey> unvisitedDeps = Sets.newHashSetWithExpectedSize(directDeps.numElements());
    Iterables.addAll(unvisitedDeps, Iterables.concat(directDeps));
    unvisitedDeps.remove(cycleChild);
    // Remove any children from this node that are not part of the cycle we just found. They are
    // irrelevant to the node as it stands, and if they are deleted from the graph because they are
    // not built by the end of cycle-checking, we would have dangling references.
    Set<SkyKey> removedDeps = removeIncompleteChildrenForCycle(key, entry, unvisitedDeps, evaluatorContext);
    if (!entry.isReady()) {
        // The entry has at most one undone dep now, its cycleChild. Signal to make entry ready. Note
        // that the entry can conceivably be ready if its cycleChild already found a different cycle
        // and was built.
        entry.signalDep();
    }
    maybeMarkRebuilding(entry);
    Preconditions.checkState(entry.isReady(), "%s %s %s", key, cycleChild, entry);
    Iterator<SkyKey> it = toVisit.iterator();
    while (it.hasNext()) {
        SkyKey descendant = it.next();
        if (descendant == CHILDREN_FINISHED) {
            // Marker value, delineating the end of a group of children that were enqueued.
            cycleLength--;
            if (cycleLength == 0) {
                // We have seen #cycleLength-1 marker values, and have arrived at the one for this value,
                // so we are done.
                return removedDeps;
            }
            continue; // Don't remove marker values.
        }
        if (cycleLength == 1) {
            // Remove the direct children remaining to visit of the cycle node.
            Preconditions.checkState(unvisitedDeps.contains(descendant), "%s %s %s %s %s", key, descendant,
                    cycleChild, unvisitedDeps, entry);
            it.remove();
        }
    }
    throw new IllegalStateException(String
            .format("There were not %d groups of children in %s when trying to remove children of %s other "
                    + "than %s", cycleLength, toVisit, key, cycleChild));
}

From source file:com.zimbra.cs.milter.MilterHandler.java

private void SMFIC_BodyEOB() throws IOException {
    ZimbraLog.milter.debug("SMFIC_BodyEOB");
    Set<String> listAddrs = Sets.newHashSetWithExpectedSize(lists.size());
    Set<String> replyToAddrs = Sets.newHashSetWithExpectedSize(lists.size());
    for (Group group : lists) {
        if (group == null) {
            ZimbraLog.milter.warn("null group in group list!?!");
            continue;
        }/*from   w w w.  j  a v  a  2 s. c  o  m*/
        if (visibleAddresses.contains(group.getMail().toLowerCase())) {
            listAddrs.add(group.getMail());
            if (group.isPrefReplyToEnabled()) {
                String addr = group.getPrefReplyToAddress();
                if (Strings.isNullOrEmpty(addr)) {
                    addr = group.getMail(); // fallback to the default email address
                }
                String disp = group.getPrefReplyToDisplay();
                if (Strings.isNullOrEmpty(disp)) {
                    disp = group.getDisplayName(); // fallback to the default display name
                }
                replyToAddrs.add(new InternetAddress(disp, addr).toString());
            }
        }
    }
    if (!listAddrs.isEmpty()) {
        SMFIR_ChgHeader(1, "X-Zimbra-DL", Joiner.on(", ").join(listAddrs));
    }
    if (!replyToAddrs.isEmpty()) {
        SMFIR_ChgHeader(1, "Reply-To", Joiner.on(", ").join(replyToAddrs));
    }
    connection.send(new MilterPacket(SMFIR_ACCEPT));
}

From source file:com.opengamma.financial.analytics.model.YieldCurveFunctionUtils.java

public static Set<String> intersection(final Set<String> as, final String[] bs) {
    final Set<String> i = Sets.newHashSetWithExpectedSize(as.size());
    for (final String b : bs) {
        if (as.contains(b)) {
            i.add(b);/*from   w  w  w . j a  va  2 s .  c o  m*/
        }
    }
    return i;
}

From source file:com.android.builder.core.AndroidBuilder.java

/**
 * Returns the compile classpath for this config. If the config tests a library, this
 * will include the classpath of the tested config.
 *
 * If the SDK was loaded, this may include the renderscript support jar.
 *
 * @return a non null, but possibly empty set.
 */// w ww .ja va2  s  . co m
@NonNull
public Set<File> getCompileClasspath(@NonNull VariantConfiguration<?, ?, ?> variantConfiguration) {
    Set<File> compileClasspath = variantConfiguration.getCompileClasspath();

    if (variantConfiguration.getRenderscriptSupportModeEnabled()) {
        File renderScriptSupportJar = getRenderScriptSupportJar();

        Set<File> fullJars = Sets.newHashSetWithExpectedSize(compileClasspath.size() + 1);
        fullJars.addAll(compileClasspath);
        if (renderScriptSupportJar != null) {
            fullJars.add(renderScriptSupportJar);
        }
        compileClasspath = fullJars;
    }

    return compileClasspath;
}

From source file:net.automatalib.util.automata.cover.Covers.java

private static <S, I> void incrementalCover(DeterministicAutomaton<S, I, ?> automaton,
        Collection<? extends I> inputs, Collection<? extends Word<I>> oldStateCover,
        Collection<? extends Word<I>> oldTransCover, Consumer<? super Word<I>> newStateCover,
        Consumer<? super Word<I>> newTransCover) {

    MutableMapping<S, Record<S, I>> reach = automaton.createStaticStateMapping();

    Queue<Record<S, I>> bfsQueue = new ArrayDeque<>();

    // We enforce that the initial state *always* is covered by the empty word,
    // regardless of whether other sequence in oldCover cover it
    S init = automaton.getInitialState();

    Record<S, I> initRec = new Record<>(init, Word.epsilon(), Sets.newHashSetWithExpectedSize(inputs.size()));
    bfsQueue.add(initRec);//ww  w.  j  a va  2s .com
    reach.put(init, initRec);

    boolean hasEpsilon = buildReachFromStateCover(reach, bfsQueue, automaton, oldStateCover,
            (s, as) -> new Record<>(s, as, Sets.newHashSetWithExpectedSize(inputs.size())));

    // Add transition cover information from *state covers*
    for (Word<I> oldStateAs : oldStateCover) {
        if (oldStateAs.isEmpty()) {
            continue;
        }

        Word<I> asPrefix = oldStateAs.prefix(oldStateAs.length() - 1);
        S pred = automaton.getState(asPrefix);
        assert pred != null;

        Record<S, I> predRec = reach.get(pred);
        if (predRec == null) {
            throw new IllegalArgumentException(
                    "State cover was not prefix-closed: prefix of " + oldStateAs + " not in set");
        }
        I lastSym = oldStateAs.lastSymbol();
        predRec.coveredInputs.add(lastSym);
    }

    // Till now, we haven't augmented any set.
    if (!hasEpsilon) {
        newStateCover.accept(Word.epsilon());
    }

    // Add transition covers
    buildReachFromTransitionCover(reach, bfsQueue, automaton, oldTransCover,
            (s, as) -> new Record<>(s, as, Sets.newHashSetWithExpectedSize(inputs.size())), newStateCover);

    Record<S, I> curr;
    while ((curr = bfsQueue.poll()) != null) {
        for (I input : inputs) {
            if (curr.coveredInputs.add(input)) {
                S succ = automaton.getSuccessor(curr.state, input);

                Word<I> newAs = curr.accessSequence.append(input);

                if (succ != null) {
                    Record<S, I> succRec = reach.get(succ);

                    if (succRec == null) {
                        // new state!
                        succRec = new Record<>(succ, newAs, Sets.newHashSetWithExpectedSize(inputs.size()));
                        bfsQueue.add(succRec);
                        reach.put(succ, succRec);

                        newStateCover.accept(newAs);
                    }
                    // new transition
                    newTransCover.accept(newAs);
                }
            }
        }
    }
}

From source file:org.eclipse.hawkbit.repository.jpa.JpaControllerManagement.java

/**
 * Flush the update queue by means to persisting
 * {@link Target#getLastTargetQuery()}.//from w  w w.  j av  a  2s. co m
 */
private void flushUpdateQueue() {
    LOG.debug("Run flushUpdateQueue.");

    final int size = queue.size();
    if (size <= 0) {
        return;
    }

    LOG.debug("{} events in flushUpdateQueue.", size);

    final Set<TargetPoll> events = Sets.newHashSetWithExpectedSize(queue.size());
    final int drained = queue.drainTo(events);

    if (drained <= 0) {
        return;
    }

    try {
        events.stream().collect(Collectors.groupingBy(TargetPoll::getTenant)).forEach((tenant, polls) -> {
            final TransactionCallback<Void> createTransaction = status -> updateLastTargetQueries(tenant,
                    polls);
            tenantAware.runAsTenant(tenant, () -> DeploymentHelper.runInNewTransaction(txManager,
                    "flushUpdateQueue", createTransaction));
        });
    } catch (final RuntimeException ex) {
        LOG.error("Failed to persist UpdateQueue content.", ex);
        return;
    }

    LOG.debug("{} events persisted.", drained);
}

From source file:org.openscience.cdk.smiles.smarts.SMARTSQueryTool.java

/**
 * Get the atoms in the target molecule that match the query pattern. <p/> Since there may be multiple matches, the
 * return value is a List of List objects. Each List object contains the unique set of indices of the atoms in the
 * target molecule, that match the query pattern
 *
 * @return A List of List of atom indices in the target molecule
 *//* ww  w. j a v  a  2s. co m*/
public List<List<Integer>> getUniqueMatchingAtoms() {
    List<List<Integer>> matched = new ArrayList<List<Integer>>(mappings.size());
    Set<BitSet> atomSets = Sets.newHashSetWithExpectedSize(mappings.size());
    for (int[] mapping : mappings) {
        BitSet atomSet = new BitSet();
        for (int x : mapping)
            atomSet.set(x);
        if (atomSets.add(atomSet))
            matched.add(Ints.asList(mapping));
    }
    return matched;
}

From source file:com.opengamma.financial.analytics.MissingInputsFunction.java

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues)
        throws AsynchronousExecution {
    final Set<ValueRequirement> underlyingDesired = Sets.newHashSetWithExpectedSize(desiredValues.size());
    for (final ValueRequirement desiredValue : desiredValues) {
        final ValueProperties requirementConstraints = desiredValue.getConstraints()
                .withoutAny(ValuePropertyNames.AGGREGATION);
        underlyingDesired.add(new ValueRequirement(desiredValue.getValueName(),
                desiredValue.getTargetReference(), requirementConstraints));
    }//ww w  .  j  a  va 2s  . c om
    try {
        return createExecuteResults(inputs,
                getUnderlyingInvoker().execute(executionContext, inputs, target, underlyingDesired));
    } catch (final AsynchronousExecution e) {
        final AsynchronousOperation<Set<ComputedValue>> async = AsynchronousOperation.createSet();
        e.setResultListener(new ResultListener<Set<ComputedValue>>() {
            @Override
            public void operationComplete(final AsynchronousResult<Set<ComputedValue>> result) {
                try {
                    async.getCallback().setResult(createExecuteResults(inputs, result.getResult()));
                } catch (final RuntimeException e) {
                    async.getCallback().setException(e);
                }
            }
        });
        return async.getResult();
    }
}

From source file:com.palantir.atlasdb.keyvalue.rocksdb.impl.RocksDbKeyValueService.java

@Override
public void putUnlessExists(String tableName, Map<Cell, byte[]> values) throws KeyAlreadyExistsException {
    LockState<Cell> locks = lockSet.lockOnObjects(values.keySet());
    try (Disposer d = new Disposer(); ColumnFamily table = columnFamilies.get(tableName)) {
        Set<Cell> alreadyExists = Sets.newHashSetWithExpectedSize(0);
        WriteOptions options = d.register(new WriteOptions().setSync(writeOptions.fsyncCommit()));
        WriteBatch batch = d.register(new WriteBatch());
        RocksIterator iter = d.register(getDb().newIterator(table.getHandle()));
        for (Entry<Cell, byte[]> entry : values.entrySet()) {
            byte[] key = RocksDbKeyValueServices.getKey(entry.getKey(), PUT_UNLESS_EXISTS_TS);
            if (RocksDbKeyValueServices.keyExists(iter, key)) {
                alreadyExists.add(entry.getKey());
            } else {
                batch.put(table.getHandle(), key, entry.getValue());
            }/*from  w  w  w  .j a v a2 s . co  m*/
        }
        getDb().write(options, batch);
        if (!alreadyExists.isEmpty()) {
            throw new KeyAlreadyExistsException("key already exists", alreadyExists);
        }
    } catch (RocksDBException e) {
        throw Throwables.propagate(e);
    } finally {
        locks.unlock();
    }
}