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:com.opengamma.financial.currency.AbstractCurrencyMatrixSourcingFunction.java

@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
        final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
    final CurrencyMatrix matrix = (CurrencyMatrix) target.getValue();
    final Set<ComputedValue> result = Sets.newHashSetWithExpectedSize(desiredValues.size());
    for (ValueRequirement desiredValue : desiredValues) {
        final Currency sourceCurrency = Currency.of(desiredValue.getConstraint(SOURCE_CURRENCY_PROPERTY));
        final Currency targetCurrency = Currency.of(desiredValue.getConstraint(TARGET_CURRENCY_PROPERTY));
        final ValueSpecification valueSpec = new ValueSpecification(desiredValue.getValueName(),
                target.toSpecification(), desiredValue.getConstraints());
        final Object resultValue = getRate(matrix, desiredValue, executionContext, inputs, sourceCurrency,
                targetCurrency);//from   ww  w  .ja v a2  s . c  o m
        if (resultValue != null) {
            result.add(new ComputedValue(valueSpec, resultValue));
        }
    }
    return result;
}

From source file:com.opengamma.financial.analytics.model.swaption.black.SwaptionBlackCurveSpecificFunction.java

@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context,
        final ComputationTarget target, final ValueRequirement desiredValue) {
    final ValueProperties constraints = desiredValue.getConstraints();
    final Set<String> curveNames = constraints.getValues(ValuePropertyNames.CURVE);
    if (curveNames == null || curveNames.size() != 1) {
        s_logger.error("Did not specify a curve name for requirement {}", desiredValue);
        return null;
    }/*from w  w  w .  j a  v a2 s . c  o  m*/
    final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
    if (surfaceNames == null || surfaceNames.size() != 1) {
        return null;
    }
    final String curveName = curveNames.iterator().next();
    final Set<String> curveCalculationConfigNames = constraints
            .getValues(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
    if (curveCalculationConfigNames == null || curveCalculationConfigNames.size() != 1) {
        return null;
    }
    final String curveCalculationConfigName = curveCalculationConfigNames.iterator().next();
    final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(context);
    final ConfigDBCurveCalculationConfigSource curveCalculationConfigSource = new ConfigDBCurveCalculationConfigSource(
            configSource);
    final MultiCurveCalculationConfig curveCalculationConfig = curveCalculationConfigSource
            .getConfig(curveCalculationConfigName);
    if (curveCalculationConfig == null) {
        s_logger.error("Could not find curve calculation configuration named " + curveCalculationConfigName);
        return null;
    }
    final Currency currency = FinancialSecurityUtils.getCurrency(target.getSecurity());
    if (!ComputationTargetSpecification.of(currency).equals(curveCalculationConfig.getTarget())) {
        s_logger.error("Security currency and curve calculation config id were not equal; have {} and {}",
                currency, curveCalculationConfig.getTarget());
    }
    final String[] configCurveNames = curveCalculationConfig.getYieldCurveNames();
    if (Arrays.binarySearch(configCurveNames, curveName) < 0) {
        s_logger.error("Curve named {} is not available in curve calculation configuration called {}",
                curveName, curveCalculationConfigName);
        return null;
    }
    final String surfaceName = surfaceNames.iterator().next();
    final Set<ValueRequirement> requirements = Sets.newHashSetWithExpectedSize(4);
    requirements.addAll(
            YieldCurveFunctionUtils.getCurveRequirements(curveCalculationConfig, curveCalculationConfigSource));
    requirements.add(getVolatilityRequirement(surfaceName, currency));
    return requirements;
}

From source file:com.opengamma.financial.analytics.model.irfutureoption.InterestRateFutureOptionBlackFunctionDeprecated.java

@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context,
        final ComputationTarget target, final ValueRequirement desiredValue) {
    final ValueProperties constraints = desiredValue.getConstraints();

    final Set<String> forwardCurveNames = constraints.getValues(YieldCurveFunction.PROPERTY_FORWARD_CURVE);
    if (forwardCurveNames == null || forwardCurveNames.size() != 1) {
        s_logger.info("Could not find {} requirement. Looking for a default..",
                YieldCurveFunction.PROPERTY_FORWARD_CURVE);
        return null;
    }//from w w w .j a va 2  s. c om
    final Set<String> fundingCurveNames = constraints.getValues(YieldCurveFunction.PROPERTY_FUNDING_CURVE);
    if (fundingCurveNames == null || fundingCurveNames.size() != 1) {
        s_logger.info("Could not find {} requirement. Looking for a default..",
                YieldCurveFunction.PROPERTY_FUNDING_CURVE);
        return null;
    }
    final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
    if (surfaceNames == null || surfaceNames.size() != 1) {
        s_logger.info("Could not find {} requirement. Looking for a default..", ValuePropertyNames.SURFACE);
        return null;
    }
    final Set<String> curveCalculationMethods = constraints
            .getValues(ValuePropertyNames.CURVE_CALCULATION_METHOD);
    if (curveCalculationMethods == null || curveCalculationMethods.size() != 1) {
        s_logger.info("Could not find {} requirement. Looking for a default..",
                ValuePropertyNames.CURVE_CALCULATION_METHOD);
        return null;
    }

    final String forwardCurveName = forwardCurveNames.iterator().next();
    final String fundingCurveName = fundingCurveNames.iterator().next();
    final String curveCalculationMethod = curveCalculationMethods.iterator().next();
    final String surfaceName = surfaceNames.iterator().next() + "_" + getFutureOptionPrefix(target);

    final Set<ValueRequirement> requirements = Sets.newHashSetWithExpectedSize(4);
    final Currency currency = FinancialSecurityUtils.getCurrency(target.getTrade().getSecurity());
    requirements.add(YieldCurveFunction.getCurveRequirement(currency, forwardCurveName, forwardCurveName,
            fundingCurveName, curveCalculationMethod));
    requirements.add(YieldCurveFunction.getCurveRequirement(currency, fundingCurveName, forwardCurveName,
            fundingCurveName, curveCalculationMethod));
    requirements.add(getVolatilityRequirement(surfaceName, currency));
    final Set<ValueRequirement> tsRequirements = _dataConverter.getConversionTimeSeriesRequirements(
            target.getTrade().getSecurity(), _converter.convert(target.getTrade()),
            new String[] { fundingCurveName, forwardCurveName });
    if (tsRequirements == null) {
        return null;
    }
    requirements.addAll(tsRequirements);
    return requirements;
}

From source file:org.gradoop.util.AsciiGraphLoader.java

/**
 * Returns all edges that belong to the given graphs.
 *
 * @param graphIds Graph identifiers//ww w . ja  v a 2  s.c  o m
 * @return edges
 */
public Collection<E> getEdgesByGraphIds(GradoopIdSet graphIds) {
    Collection<E> result = Sets.newHashSetWithExpectedSize(graphIds.size());
    for (E edge : edges.values()) {
        if (edge.getGraphIds().containsAny(graphIds)) {
            result.add(edge);
        }
    }
    return result;
}

From source file:net.sourceforge.docfetcher.gui.SearchQueue.java

private void updateParserFilter() {
    ListMap<Parser, Boolean> map = fileTypePanel.getParserStateMap();
    checkedParsers = Sets.newHashSetWithExpectedSize(map.size());
    for (Entry<Parser, Boolean> entry : map) {
        if (!entry.getValue())
            continue;
        String parserName = entry.getKey().getClass().getSimpleName();
        checkedParsers.add(parserName);//from  w  ww  . j  ava  2s . c  o m
    }
    allParsersChecked = checkedParsers.size() == map.size();
}

From source file:org.attribyte.api.pubsub.impl.server.admin.AdminServlet.java

private Set<Subscription.Status> getSubscriptionStatus(HttpServletRequest request, final boolean activeOnly) {

    if (activeOnly) {
        return Collections.singleton(Subscription.Status.ACTIVE);
    }/*from  w  w  w .j  a v a 2 s.c  o m*/

    String[] status = request.getParameterValues("status");
    if (status == null || status.length == 0) {
        return Collections.emptySet();
    } else {
        Set<Subscription.Status> statusSet = Sets.newHashSetWithExpectedSize(4);
        for (String s : status) {
            Subscription.Status toAdd = Subscription.Status.valueOf(s);
            if (toAdd != Subscription.Status.INVALID) {
                statusSet.add(toAdd);
            }
        }

        return statusSet;
    }
}

From source file:com.opengamma.financial.analytics.model.irfutureoption.InterestRateFutureOptionBlackCurveSpecificFunctionDeprecated.java

@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context,
        final ComputationTarget target, final ValueRequirement desiredValue) {
    final ValueProperties constraints = desiredValue.getConstraints();
    final Set<String> curveNames = constraints.getValues(ValuePropertyNames.CURVE);
    if (curveNames == null || curveNames.size() != 1) {
        s_logger.error("Did not specify a curve name for requirement {}", desiredValue);
        return null;
    }/*from   w  w  w . j  av a  2 s  .c  o  m*/
    final Set<String> forwardCurveNames = constraints.getValues(YieldCurveFunction.PROPERTY_FORWARD_CURVE);
    if (forwardCurveNames == null || forwardCurveNames.size() != 1) {
        return null;
    }
    final Set<String> fundingCurveNames = constraints.getValues(YieldCurveFunction.PROPERTY_FUNDING_CURVE);
    if (fundingCurveNames == null || fundingCurveNames.size() != 1) {
        return null;
    }
    final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
    if (surfaceNames == null || surfaceNames.size() != 1) {
        return null;
    }
    final Set<String> curveCalculationMethods = constraints
            .getValues(ValuePropertyNames.CURVE_CALCULATION_METHOD);
    if (curveCalculationMethods == null || curveCalculationMethods.size() != 1) {
        return null;
    }
    final String forwardCurveName = forwardCurveNames.iterator().next();
    final String fundingCurveName = fundingCurveNames.iterator().next();
    final String curveName = curveNames.iterator().next();
    if (!(curveName.equals(forwardCurveName) || curveName.equals(fundingCurveName))) {
        s_logger.error(
                "Did not specify a curve to which this instrument is sensitive; asked for {}, {} and {} are allowed",
                new String[] { curveName, forwardCurveName, fundingCurveName });
        return null;
    }
    final String surfaceName = surfaceNames.iterator().next() + "_" + getFutureOptionPrefix(target);
    final String curveCalculationMethod = curveCalculationMethods.iterator().next();
    final Set<ValueRequirement> requirements = Sets.newHashSetWithExpectedSize(4);
    final Currency currency = FinancialSecurityUtils.getCurrency(target.getTrade().getSecurity());
    requirements.add(YieldCurveFunction.getCurveRequirement(currency, forwardCurveName, forwardCurveName,
            fundingCurveName, curveCalculationMethod));
    requirements.add(YieldCurveFunction.getCurveRequirement(currency, fundingCurveName, forwardCurveName,
            fundingCurveName, curveCalculationMethod));
    requirements.add(getVolatilityRequirement(surfaceName, currency));
    final Set<ValueRequirement> tsRequirements = _dataConverter.getConversionTimeSeriesRequirements(
            target.getTrade().getSecurity(), _converter.convert(target.getTrade()),
            new String[] { fundingCurveName, forwardCurveName });
    if (tsRequirements == null) {
        return null;
    }
    requirements.addAll(tsRequirements);
    return requirements;
}

From source file:com.google.template.soy.sharedpasses.BuildNearestDependeeMapVisitor.java

/**
 * Helper for visiting a given node and adding its mappings in nearestDependeeMap and
 * allDependeesMap./*from w ww  . j a  va  2 s  . c o m*/
 *
 * <p> Precondition: If this node is a parent, its children must have already been visited (thus
 * their mappings are already in allDependeesMap).
 *
 * @param node The node to visit.
 * @param topLevelRefs The top-level references made by this node. Does not include references
 *     made by its descendents. May be either empty or null if there are no references.
 */
private void visitHelper(SoyNode node, @Nullable Set<String> topLevelRefs) {

    boolean foundNearestDependee = false;
    Set<SoyNode> allDependees = Sets.newHashSetWithExpectedSize(4);

    for (List<SoyNode> potentialDependeeFrame : potentialDependeeFrames) {
        // We must iterate in reverse if we wish to encounter the nearest dependee first.
        for (int i = potentialDependeeFrame.size() - 1; i >= 0; i--) {
            SoyNode potentialDependee = potentialDependeeFrame.get(i);

            if (isDependent(potentialDependee, node, topLevelRefs)) {
                if (!foundNearestDependee) {
                    nearestDependeeMap.put(node, potentialDependee);
                    foundNearestDependee = true;
                }
                allDependees.add(potentialDependee);
            }
        }
    }

    if (!foundNearestDependee) {
        throw new AssertionError();
    }

    allDependeesMap.put(node, allDependees);
}

From source file:com.twitter.graphjet.bipartite.GraphConcurrentTestHelper.java

/**
 * This helper method sets up a concurrent read-write situation with a single writer and multiple
 * readers that access the same underlying bipartiteGraph, and tests for correct edge access during
 * simultaneous edge writes. This helps test read consistency during arbitrary points of
 * inserting edges. Note that the exact read-write sequence here is non-deterministic and would
 * vary depending on the machine, but the hope is that given the large number of readers the reads
 * would be done at many different points of edge insertion. The test itself checks only for
 * partial correctness (it could have false positives) so this should only be used as a supplement
 * to other testing.//from   ww  w .j  a va2s  .co  m
 *
 * @param graph              is the underlying
 *                           {@link BipartiteGraph}
 * @param numReadersPerNode  is the number of reader threads to use per node
 * @param leftSize           is the number of left nodes
 * @param rightSize          is the number of right nodes
 * @param edgeProbability    is the probability of an edge between a left-right node pair
 * @param random             is the random number generator to use for generating a random graph
 */
public static <T extends BipartiteGraph & DynamicBipartiteGraph> void testRandomConcurrentReadWriteThreads(
        T graph, int numReadersPerNode, int leftSize, int rightSize, double edgeProbability, Random random) {
    int maxWaitingTimeForThreads = 20; // in milliseconds
    int numLeftReaders = leftSize * numReadersPerNode;
    int numRightReaders = rightSize * numReadersPerNode;
    int totalNumReaders = numLeftReaders + numRightReaders;
    CountDownLatch readersDoneLatch = new CountDownLatch(totalNumReaders);
    // First, construct a random set of edges to insert in the graph
    Set<Pair<Long, Long>> edges = Sets
            .newHashSetWithExpectedSize((int) (leftSize * rightSize * edgeProbability));
    List<BipartiteGraphReader> leftReaders = Lists.newArrayListWithCapacity(numLeftReaders);
    List<BipartiteGraphReader> rightReaders = Lists.newArrayListWithCapacity(numRightReaders);
    Long2ObjectMap<LongSet> leftSideGraph = new Long2ObjectOpenHashMap<LongSet>(leftSize);
    Long2ObjectMap<LongSet> rightSideGraph = new Long2ObjectOpenHashMap<LongSet>(leftSize);
    int averageLeftDegree = (int) (rightSize * edgeProbability);
    for (int i = 0; i < leftSize; i++) {
        LongSet nodeEdges = new LongOpenHashSet(averageLeftDegree);
        for (int j = 0; j < rightSize; j++) {
            if (random.nextDouble() < edgeProbability) {
                nodeEdges.add(j);
                if (!rightSideGraph.containsKey(j)) {
                    rightSideGraph.put(j, new LongOpenHashSet(new long[] { i }));
                } else {
                    rightSideGraph.get(j).add(i);
                }
                edges.add(Pair.of((long) i, (long) j));
            }
        }
        leftSideGraph.put(i, nodeEdges);
    }

    // Create a bunch of leftReaders per node that'll read from the graph at random
    for (int i = 0; i < leftSize; i++) {
        for (int j = 0; j < numReadersPerNode; j++) {
            leftReaders.add(new BipartiteGraphReader(graph, new CountDownLatch(0), readersDoneLatch, i, true,
                    random.nextInt(maxWaitingTimeForThreads)));
        }
    }

    // Create a bunch of rightReaders per node that'll read from the graph at random
    for (int i = 0; i < rightSize; i++) {
        for (int j = 0; j < numReadersPerNode; j++) {
            rightReaders.add(new BipartiteGraphReader(graph, new CountDownLatch(0), readersDoneLatch, i, false,
                    random.nextInt(maxWaitingTimeForThreads)));
        }
    }

    // Create a single writer that will insert these edges in random order
    List<WriterInfo> writerInfo = Lists.newArrayListWithCapacity(edges.size());
    List<Pair<Long, Long>> edgesList = Lists.newArrayList(edges);
    Collections.shuffle(edgesList);
    CountDownLatch writerDoneLatch = new CountDownLatch(edgesList.size());
    for (Pair<Long, Long> edge : edgesList) {
        writerInfo.add(new WriterInfo(edge.getLeft(), edge.getRight(), new CountDownLatch(0), writerDoneLatch));
    }

    ExecutorService executor = Executors.newFixedThreadPool(totalNumReaders + 1); // single writer
    List<Callable<Integer>> allThreads = Lists.newArrayListWithCapacity(totalNumReaders + 1);
    // First, we add the writer
    allThreads.add(Executors.callable(new BipartiteGraphWriter(graph, writerInfo), 1));
    // then the readers
    for (int i = 0; i < numLeftReaders; i++) {
        allThreads.add(Executors.callable(leftReaders.get(i), 1));
    }
    for (int i = 0; i < numRightReaders; i++) {
        allThreads.add(Executors.callable(rightReaders.get(i), 1));
    }
    // these will execute in some non-deterministic order
    Collections.shuffle(allThreads, random);

    // Wait for all the processes to finish
    try {
        List<Future<Integer>> results = executor.invokeAll(allThreads, 10, TimeUnit.SECONDS);
        for (Future<Integer> result : results) {
            assertTrue(result.isDone());
            assertEquals(1, result.get().intValue());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for a thread was interrupted: ", e);
    } catch (ExecutionException e) {
        throw new RuntimeException("Execution issue in an executor thread: ", e);
    }

    // confirm that these worked as expected
    try {
        readersDoneLatch.await();
        writerDoneLatch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for a latch was interrupted: ", e);
    }

    // Check that all readers' read info is consistent with the graph
    // first check the left side
    for (int i = 0; i < numLeftReaders; i++) {
        LongSet expectedLeftEdges = leftSideGraph.get(leftReaders.get(i).queryNode);
        assertTrue(leftReaders.get(i).getQueryNodeDegree() <= expectedLeftEdges.size());
        if (leftReaders.get(i).getQueryNodeDegree() == 0) {
            assertNull(leftReaders.get(i).getQueryNodeEdges());
        } else {
            for (long edge : leftReaders.get(i).getQueryNodeEdges()) {
                assertTrue(expectedLeftEdges.contains(edge));
            }
        }
    }

    // then the right side
    for (int i = 0; i < numRightReaders; i++) {
        LongSet expectedRightEdges = rightSideGraph.get(rightReaders.get(i).queryNode);
        assertTrue(rightReaders.get(i).getQueryNodeDegree() <= expectedRightEdges.size());
        if (rightReaders.get(i).getQueryNodeDegree() == 0) {
            assertNull(rightReaders.get(i).getQueryNodeEdges());
        } else {
            for (long edge : rightReaders.get(i).getQueryNodeEdges()) {
                assertTrue(expectedRightEdges.contains(edge));
            }
        }
    }
}

From source file:org.artifactory.repo.db.importexport.DbRepoImportHandler.java

private Set<String> collectFileNamesForImport(File[] filesToImport) {
    Set<String> fileNames = Sets.newHashSetWithExpectedSize(filesToImport.length / 2);
    for (File childFile : filesToImport) {
        String name = childFile.getName();
        if (settings.isIncludeMetadata() && name.endsWith(METADATA_FOLDER)) {
            fileNames.add(name.substring(0, name.length() - METADATA_FOLDER.length()));
        } else if (isStorableFolder(name) && isStorableFile(name)
                && !GlobalExcludes.isInGlobalExcludes(childFile)) {
            fileNames.add(name);/*from  www  .j  a  va 2s.  c o  m*/
        }
    }
    return fileNames;
}