Example usage for com.google.common.collect ImmutableList get

List of usage examples for com.google.common.collect ImmutableList get

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList get.

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:com.google.errorprone.refaster.Template.java

/**
 * Returns a list of the expected types to be matched.  This consists of the argument types from
 * the @BeforeTemplate method, concatenated with the return types of expression placeholders, 
 * sorted by the name of the placeholder method.
 *
 * @throws CouldNotResolveImportException if a referenced type could not be resolved
 *///from ww  w. j  a  va 2  s. co m
protected List<Type> expectedTypes(Inliner inliner) throws CouldNotResolveImportException {
    ArrayList<Type> result = new ArrayList<>();
    ImmutableList<UType> types = expressionArgumentTypes().values().asList();
    ImmutableList<String> argNames = expressionArgumentTypes().keySet().asList();
    for (int i = 0; i < argNames.size(); i++) {
        String argName = argNames.get(i);
        Optional<JCExpression> singleBinding = inliner.getOptionalBinding(new UFreeIdent.Key(argName));
        if (!singleBinding.isPresent()) {
            Optional<java.util.List<JCExpression>> exprs = inliner
                    .getOptionalBinding(new URepeated.Key(argName));
            if (!exprs.isPresent() || exprs.get().isEmpty()) {
                // It is a repeated template variable and matches no expressions.
                continue;
            }
        }
        result.add(types.get(i).inline(inliner));
    }
    for (PlaceholderExpressionKey key : Ordering.natural()
            .immutableSortedCopy(Iterables.filter(inliner.bindings.keySet(), PlaceholderExpressionKey.class))) {
        result.add(key.method.returnType().inline(inliner));
    }
    return List.from(result);
}

From source file:com.wandoulabs.jodis.RoundRobinJedisPool.java

@Override
public Jedis getResource() {
    ImmutableList<PooledObject> pools = this.pools;
    if (pools.isEmpty()) {
        throw new JedisException("Proxy list empty");
    }//from  w  w  w .ja  v  a2 s.  c om
    for (;;) {
        int current = nextIdx.get();
        int next = current >= pools.size() - 1 ? 0 : current + 1;
        if (nextIdx.compareAndSet(current, next)) {
            return pools.get(next).pool.getResource();
        }
    }
}

From source file:org.eclipse.xtext.ui.resource.Storage2UriMapperImpl.java

@Inject
private void initializeContributions(ISharedStateContributionRegistry registry) {
    final ImmutableList<? extends IStorage2UriMapperContribution> allContributions = registry
            .getContributedInstances(IStorage2UriMapperContribution.class);
    final int size = allContributions.size();
    switch (size) {
    case 0://from  w  ww. j  ava2s  .c  o  m
        // nothing to do
        break;
    case 1:
        contribution = allContributions.get(0);
        break;
    default:
        contribution = new IStorage2UriMapperContribution() {
            @Override
            public void initializeCache() {
                for (IStorage2UriMapperContribution contribution : allContributions) {
                    contribution.initializeCache();
                }
            }

            @Override
            public boolean isRejected(/* @NonNull */ IFolder folder) {
                for (int i = 0; i < size; i++) {
                    if (allContributions.get(i).isRejected(folder)) {
                        return true;
                    }
                }
                return false;
            }

            /* @NonNull */
            @Override
            public Iterable<Pair<IStorage, IProject>> getStorages(/* @NonNull */ final URI uri) {
                return Iterables.concat(Lists.transform(allContributions,
                        new Function<IStorage2UriMapperContribution, Iterable<Pair<IStorage, IProject>>>() {
                            /* @NonNull */
                            @Override
                            public Iterable<Pair<IStorage, IProject>> apply(
                                    IStorage2UriMapperContribution contribution) {
                                return contribution.getStorages(uri);
                            }
                        }));
            }

            /* @Nullable */
            @Override
            public URI getUri(/* @NonNull */ IStorage storage) {
                for (int i = 0; i < size; i++) {
                    URI result = allContributions.get(i).getUri(storage);
                    if (result != null) {
                        return result;
                    }
                }
                return null;
            }
        };
    }
}

From source file:org.sosy_lab.cpachecker.pcc.strategy.partialcertificate.WeightedGraph.java

public WeightedGraph(PartialReachedSetDirectedGraph pGraph) {
    if (pGraph == null) {
        throw new IllegalArgumentException("Graph may not be null.");
    }/*from   ww w.java2s  .c  o m*/
    totalNodeWeight = 0;
    numNodes = pGraph.getNumNodes();
    nodes = new WeightedNode[numNodes];
    outgoingEdges = new HashMap<>(numNodes);
    incomingEdges = new HashMap<>(numNodes);

    int weight = 1;
    ImmutableList<ImmutableList<Integer>> adjacencyList = pGraph.getAdjacencyList();

    for (int actualNode = 0; actualNode < numNodes; actualNode++) {
        WeightedNode start = new WeightedNode(actualNode, weight); //start node of newly found edges
        for (Integer successorNode : adjacencyList.get(actualNode)) { //iterate over successors of actual node
            WeightedNode end = new WeightedNode(successorNode, weight);
            WeightedEdge edge = new WeightedEdge(start, end, weight);
            addEdge(edge);
        }
    }
}

From source file:org.commoncrawl.mapred.pipelineV3.domainmeta.rank.LinkScannerStep.java

@Override
public void runStep(Path outputPathLocation) throws IOException {
    LOG.info("Task Identity Path is:" + getTaskIdentityPath());
    LOG.info("Temp Path is:" + outputPathLocation);

    ImmutableList<Path> paths = new ImmutableList.Builder<Path>()
            .addAll(filterMergeCandidtes(getFileSystem(), getConf(), 0)).build();

    // establish an affinity path ...
    Path affinityPath = paths.get(0);

    JobConf jobConf = new JobBuilder("Link Scanner Job", getConf())

            .inputs(paths).inputFormat(MultiFileMergeInputFormat.class)
            .mapperKeyValue(IntWritable.class, Text.class).outputKeyValue(TextBytes.class, TextBytes.class)
            .outputFormat(SequenceFileOutputFormat.class).reducer(LinkScannerStep.class, false)
            .partition(MultiFileMergePartitioner.class).numReducers(CrawlEnvironment.NUM_DB_SHARDS)
            .speculativeExecution(false).output(outputPathLocation)
            .setAffinityNoBalancing(affinityPath,
                    ImmutableSet.of("ccd001.commoncrawl.org", "ccd006.commoncrawl.org"))
            .compressMapOutput(false).compressor(CompressionType.BLOCK, SnappyCodec.class)

            .build();/*ww w  . j a  va2 s . c o m*/

    LOG.info("Starting JOB");
    JobClient.runJob(jobConf);
    LOG.info("Finsihed JOB");
}

From source file:edu.mit.streamjit.impl.common.BlobHostStreamCompiler.java

@Override
public <I, O> CompiledStream compile(OneToOneElement<I, O> stream, Input<I> input, Output<O> output) {
    ConnectWorkersVisitor cwv = new ConnectWorkersVisitor();
    stream.visit(cwv);/*from www .ja v  a  2  s . co  m*/
    ImmutableSet<Worker<?, ?>> workers = Workers.getAllWorkersInGraph(cwv.getSource());
    Configuration config = getConfiguration(workers);
    Blob blob = makeBlob(workers, config, input, output);

    Token inputToken = Iterables.getOnlyElement(blob.getInputs());
    Token outputToken = Iterables.getOnlyElement(blob.getOutputs());
    Buffer inputBuffer = makeInputBuffer(input, blob.getMinimumBufferCapacity(inputToken));
    Buffer outputBuffer = makeOutputBuffer(output, blob.getMinimumBufferCapacity(outputToken));
    ImmutableMap.Builder<Token, Buffer> bufferMap = ImmutableMap.<Token, Buffer>builder();
    if (inputBuffer != null)
        bufferMap.put(inputToken, inputBuffer);
    if (outputBuffer != null)
        bufferMap.put(outputToken, outputBuffer);
    blob.installBuffers(bufferMap.build());

    Configuration.PermutationParameter<Integer> affinityParam = config.getParameter("$affinity",
            Configuration.PermutationParameter.class, Integer.class);
    ImmutableList<? extends Integer> affinityList;
    affinityList = affinityParam != null ? affinityParam.getUniverse()
            : ImmutableList.copyOf(Affinity.getMaximalAffinity());
    ImmutableList.Builder<PollingCoreThread> threadsBuilder = ImmutableList.builder();
    for (int i = 0; i < blob.getCoreCount(); ++i) {
        PollingCoreThread thread = new PollingCoreThread(affinityList.get(i % affinityList.size()),
                blob.getCoreCode(i), blob.toString() + "-" + i);
        threadsBuilder.add(thread);
    }
    ImmutableList<PollingCoreThread> threads = threadsBuilder.build();

    final BlobHostCompiledStream cs = new BlobHostCompiledStream(blob, threads);
    if (input instanceof ManualInput)
        InputBufferFactory.setManualInputDelegate((ManualInput<I>) input,
                new InputBufferFactory.AbstractManualInputDelegate<I>(inputBuffer) {
                    @Override
                    public void drain() {
                        cs.drain();
                    }
                });
    else //Input provides all input, so immediately begin to drain.
        cs.drain();

    for (Thread t : threads)
        t.start();
    return cs;
}

From source file:com.opengamma.strata.pricer.curve.CurveCalibrator.java

private DoubleMatrix derivatives(ImmutableList<ResolvedTrade> trades, ImmutableRatesProvider provider,
        ImmutableList<CurveParameterSize> orderAll, int totalParamsAll) {

    return DoubleMatrix.ofArrayObjects(trades.size(), totalParamsAll,
            i -> measures.derivative(trades.get(i), provider, orderAll));
}

From source file:org.apache.hadoop.hive.ql.stats.BasicStatsNoJobTask.java

private int updatePartitions(Hive db, List<FooterStatCollector> scs, Table table)
        throws InvalidOperationException, HiveException {

    String tableFullName = table.getFullyQualifiedName();

    if (scs.isEmpty()) {
        return 0;
    }//from  ww  w.  j a  v a2  s  .  co m
    if (work.isStatsReliable()) {
        for (FooterStatCollector statsCollection : scs) {
            if (statsCollection.result == null) {
                LOG.debug("Stats requested to be reliable. Empty stats found: {}",
                        statsCollection.partish.getSimpleName());
                return -1;
            }
        }
    }
    List<FooterStatCollector> validColectors = Lists.newArrayList();
    for (FooterStatCollector statsCollection : scs) {
        if (statsCollection.isValid()) {
            validColectors.add(statsCollection);
        }
    }

    EnvironmentContext environmentContext = new EnvironmentContext();
    environmentContext.putToProperties(StatsSetupConst.DO_NOT_UPDATE_STATS, StatsSetupConst.TRUE);

    ImmutableListMultimap<String, FooterStatCollector> collectorsByTable = Multimaps.index(validColectors,
            FooterStatCollector.SIMPLE_NAME_FUNCTION);

    LOG.debug("Collectors.size(): {}", collectorsByTable.keySet());

    if (collectorsByTable.keySet().size() < 1) {
        LOG.warn("Collectors are empty! ; {}", tableFullName);
    }

    // for now this should be true...
    assert (collectorsByTable.keySet().size() <= 1);

    LOG.debug("Updating stats for: {}", tableFullName);

    for (String partName : collectorsByTable.keySet()) {
        ImmutableList<FooterStatCollector> values = collectorsByTable.get(partName);

        if (values == null) {
            throw new RuntimeException("very intresting");
        }

        if (values.get(0).result instanceof Table) {
            db.alterTable(tableFullName, (Table) values.get(0).result, environmentContext, true);
            LOG.debug("Updated stats for {}.", tableFullName);
        } else {
            if (values.get(0).result instanceof Partition) {
                List<Partition> results = Lists.transform(values, FooterStatCollector.EXTRACT_RESULT_FUNCTION);
                db.alterPartitions(tableFullName, results, environmentContext, true);
                LOG.debug("Bulk updated {} partitions of {}.", results.size(), tableFullName);
            } else {
                throw new RuntimeException("inconsistent");
            }
        }
    }
    LOG.debug("Updated stats for: {}", tableFullName);
    return 0;
}

From source file:com.google.errorprone.refaster.Template.java

/**
 * Returns a list of the actual types to be matched.  This consists of the types of the 
 * expressions bound to the @BeforeTemplate method parameters, concatenated with the types
 * of the expressions bound to expression placeholders, sorted by the name of the placeholder 
 * method./*from  w  w w .  ja  v a2  s.  c  om*/
 */
protected List<Type> actualTypes(Inliner inliner) {
    ArrayList<Type> result = new ArrayList<>();
    ImmutableList<String> argNames = expressionArgumentTypes().keySet().asList();
    for (int i = 0; i < expressionArgumentTypes().size(); i++) {
        String argName = argNames.get(i);
        Optional<JCExpression> singleBinding = inliner.getOptionalBinding(new UFreeIdent.Key(argName));
        if (singleBinding.isPresent()) {
            result.add(singleBinding.get().type);
        } else {
            Optional<java.util.List<JCExpression>> exprs = inliner
                    .getOptionalBinding(new URepeated.Key(argName));
            if (exprs.isPresent() && !exprs.get().isEmpty()) {
                Type[] exprTys = new Type[exprs.get().size()];
                for (int j = 0; j < exprs.get().size(); j++) {
                    exprTys[j] = exprs.get().get(j).type;
                }
                // Get the least upper bound of the types of all expressions that the argument matches.
                // In the special case where exprs is empty, returns the "bottom" type, which is a
                // subtype of everything.
                result.add(inliner.types().lub(List.from(exprTys)));
            }
        }
    }
    for (PlaceholderExpressionKey key : Ordering.natural()
            .immutableSortedCopy(Iterables.filter(inliner.bindings.keySet(), PlaceholderExpressionKey.class))) {
        result.add(inliner.getBinding(key).type);
    }
    return List.from(result);
}

From source file:com.opengamma.strata.pricer.swaption.HullWhiteSwaptionPhysicalProductPricer.java

/**
 * Calculates the present value sensitivity of the swaption product.
 * <p>//from  www  .j ava 2s  .  com
 * The present value sensitivity of the product is the sensitivity of the present value to
 * the underlying curves.
 * 
 * @param swaption  the product
 * @param ratesProvider  the rates provider
 * @param hwProvider  the Hull-White model parameter provider
 * @return the point sensitivity to the rate curves
 */
public PointSensitivityBuilder presentValueSensitivityRates(ResolvedSwaption swaption,
        RatesProvider ratesProvider, HullWhiteOneFactorPiecewiseConstantParametersProvider hwProvider) {

    validate(swaption, ratesProvider, hwProvider);
    ResolvedSwap swap = swaption.getUnderlying();
    LocalDate expiryDate = swaption.getExpiryDate();
    if (expiryDate.isBefore(ratesProvider.getValuationDate())) { // Option has expired already
        return PointSensitivityBuilder.none();
    }
    ImmutableMap<Payment, PointSensitivityBuilder> cashFlowEquivSensi = CashFlowEquivalentCalculator
            .cashFlowEquivalentAndSensitivitySwap(swap, ratesProvider);
    ImmutableList<Payment> list = cashFlowEquivSensi.keySet().asList();
    ImmutableList<PointSensitivityBuilder> listSensi = cashFlowEquivSensi.values().asList();
    int nPayments = list.size();
    double[] alpha = new double[nPayments];
    double[] discountedCashFlow = new double[nPayments];
    for (int loopcf = 0; loopcf < nPayments; loopcf++) {
        Payment payment = list.get(loopcf);
        alpha[loopcf] = hwProvider.alpha(ratesProvider.getValuationDate(), expiryDate, expiryDate,
                payment.getDate());
        discountedCashFlow[loopcf] = paymentPricer.presentValueAmount(payment, ratesProvider);
    }
    double omega = (swap.getLegs(SwapLegType.FIXED).get(0).getPayReceive().isPay() ? -1d : 1d);
    double kappa = computeKappa(hwProvider, discountedCashFlow, alpha, omega);
    PointSensitivityBuilder point = PointSensitivityBuilder.none();
    for (int loopcf = 0; loopcf < nPayments; loopcf++) {
        Payment payment = list.get(loopcf);
        double cdf = NORMAL.getCDF(omega * (kappa + alpha[loopcf]));
        point = point
                .combinedWith(paymentPricer.presentValueSensitivity(payment, ratesProvider).multipliedBy(cdf));
        if (!listSensi.get(loopcf).equals(PointSensitivityBuilder.none())) {
            point = point.combinedWith(listSensi.get(loopcf).multipliedBy(
                    cdf * ratesProvider.discountFactor(payment.getCurrency(), payment.getDate())));
        }
    }
    return swaption.getLongShort().isLong() ? point : point.multipliedBy(-1d);
}