List of usage examples for com.google.common.collect ImmutableList get
E get(int index);
From source file:com.google.devtools.build.skyframe.CycleDeduper.java
/** * Marks a non-empty list representing a cycle of unique values as being seen and returns true * iff the cycle hasn't been seen before, accounting for logical equivalence of cycles. * * For example, the cycle 'a' -> 'b' -> 'c' -> 'a' is represented by the list ['a', 'b', 'c'] * and is logically equivalent to the cycle represented by the list ['b', 'c', 'a']. *///w w w. j ava2 s. co m public boolean seen(ImmutableList<T> cycle) { ImmutableSet<T> cycleMembers = ImmutableSet.copyOf(cycle); Preconditions.checkState(!cycle.isEmpty()); Preconditions.checkState(cycle.size() == cycleMembers.size(), "cycle doesn't have unique members: " + cycle); if (knownCyclesByMembers.containsEntry(cycleMembers, cycle)) { return false; } // Of the C cycles, suppose there are D cycles that have the same members (but are in an // incompatible order). This code path takes O(D * L) time. The common case is that D is // very small. boolean found = false; for (ImmutableList<T> candidateCycle : knownCyclesByMembers.get(cycleMembers)) { int startPos = candidateCycle.indexOf(cycle.get(0)); // The use of a multimap keyed by cycle members guarantees that the first element of 'cycle' // is present in 'candidateCycle'. Preconditions.checkState(startPos >= 0); if (equalsWithSingleLoopFrom(cycle, candidateCycle, startPos)) { found = true; break; } } // We add the cycle even if it's a duplicate so that future exact copies of this can be // processed in O(L) time. We are already using O(CL) memory, and this optimization doesn't // change that. knownCyclesByMembers.put(cycleMembers, cycle); return !found; }
From source file:com.google.template.soy.jssrc.internal.NullSafeAccumulator.java
/** * Returns a code chunk representing the entire access chain. Null-safe accesses in the chain * generate code to make sure the chain is non-null before performing the access. *///from w w w . j av a 2s .c om CodeChunk.WithValue result(CodeChunk.Generator codeGenerator) { // First generate a list of every partial evaluation of the chain. ImmutableList<CodeChunk.WithValue> intermediateValues = buildIntermediateValues(); Preconditions.checkState(intermediateValues.size() == chain.size() + 1); // Walk backwards through the intermediate values. For any null-safe link in the chain, // test the intermediate value against null before dereferencing it. // For example, to translate a?.b.c, the rightmost link is not null-safe, so it translates to // a.b.c. The next link is null-safe, so it translates to a == null ? null : a.b.c. CodeChunk.WithValue cur = intermediateValues.get(intermediateValues.size() - 1); for (int i = intermediateValues.size() - 2; i >= 0; --i) { CodeChunk.WithValue chunk = intermediateValues.get(i); boolean nullSafe = chain.get(i).nullSafe; if (nullSafe) { cur = ifExpression(chunk.doubleEqualsNull(), LITERAL_NULL).else_(cur).build(codeGenerator); } } if (unpackFunction == null) { return cur; } else if (!isRepeated) { // It's okay if the whole chain evals to null. The unpack functions accept null. return unpackFunction.call(cur); } else { return GOOG_ARRAY_MAP.call(cur, unpackFunction); } }
From source file:com.facebook.buck.rules.macros.OutputToFileExpander.java
@Override public String expand(BuildTarget target, CellPathResolver cellNames, BuildRuleResolver resolver, ImmutableList<String> input) throws MacroException { try {//from w w w . j av a 2 s. co m String expanded; if (delegate instanceof MacroExpanderWithCustomFileOutput) { expanded = ((MacroExpanderWithCustomFileOutput) delegate).expandForFile(target, cellNames, resolver, input); } else { expanded = delegate.expand(target, cellNames, resolver, input); } Optional<BuildRule> rule = resolver.getRuleOptional(target); if (!rule.isPresent()) { throw new MacroException(String.format("no rule %s", target)); } ProjectFilesystem filesystem = rule.get().getProjectFilesystem(); Path tempFile = createTempFile(filesystem, target, input.get(0)); filesystem.writeContentsToPath(expanded, tempFile); return "@" + filesystem.resolve(tempFile); } catch (IOException e) { throw new MacroException("Unable to create file to hold expanded results", e); } }
From source file:ru.org.linux.topic.TopicController.java
private ModelAndView jumpMessage(HttpServletRequest request, int msgid, int cid, boolean skipDeleted) throws Exception { Template tmpl = Template.getTemplate(request); Topic topic = messageDao.getById(msgid); CommentList comments = commentService.getCommentList(topic, false); CommentNode node = comments.getNode(cid); if (node == null && skipDeleted) { ImmutableList<Comment> list = comments.getList(); if (list.isEmpty()) { return new ModelAndView(new RedirectView(topic.getLink())); }/*from w w w. j av a 2 s .c o m*/ Comment c = list.stream().filter(v -> v.getId() > cid).findFirst().orElse(list.get(list.size() - 1)); node = comments.getNode(c.getId()); } boolean deleted = false; if (node == null && tmpl.isModeratorSession()) { comments = commentService.getCommentList(topic, true); node = comments.getNode(cid); deleted = true; } if (node == null) { throw new MessageNotFoundException(topic, cid, " #" + cid + " ??"); } int pagenum = deleted ? 0 : comments.getCommentPage(node.getComment(), tmpl.getProf()); TopicLinkBuilder redirectUrl = TopicLinkBuilder.pageLink(topic, pagenum) .lastmod(tmpl.getProf().getMessages()).comment(node.getComment().getId()); if (deleted) { redirectUrl = redirectUrl.showDeleted(); } if (tmpl.isSessionAuthorized() && !deleted) { Set<Integer> ignoreList = ignoreListDao.get(tmpl.getCurrentUser()); Set<Integer> hideSet = commentService.makeHideSet(comments, getDefaultFilter(tmpl.getProf(), ignoreList.isEmpty()), ignoreList); if (hideSet.contains(node.getComment().getId())) { redirectUrl = redirectUrl.filter(CommentFilter.FILTER_NONE); } } return new ModelAndView(new RedirectView(redirectUrl.build())); }
From source file:com.matthewmitchell.nubitsj.crypto.DeterministicHierarchy.java
/** * Returns a key for the given path, optionally creating it. * * @param path the path to the key/*from w w w .j a v a 2 s . co m*/ * @param relativePath whether the path is relative to the root path * @param create whether the key corresponding to path should be created (with any necessary ancestors) if it doesn't exist already * @return next newly created key using the child derivation function * @throws IllegalArgumentException if create is false and the path was not found. */ public DeterministicKey get(List<ChildNumber> path, boolean relativePath, boolean create) { ImmutableList<ChildNumber> absolutePath = relativePath ? ImmutableList.<ChildNumber>builder().addAll(rootPath).addAll(path).build() : ImmutableList.copyOf(path); if (!keys.containsKey(absolutePath)) { if (!create) throw new IllegalArgumentException(String.format("No key found for %s path %s.", relativePath ? "relative" : "absolute", HDUtils.formatPath(path))); checkArgument(absolutePath.size() > 0, "Can't derive the master key: nothing to derive from."); DeterministicKey parent = get(absolutePath.subList(0, absolutePath.size() - 1), false, true); putKey(HDKeyDerivation.deriveChildKey(parent, absolutePath.get(absolutePath.size() - 1))); } return keys.get(absolutePath); }
From source file:org.sosy_lab.cpachecker.cpa.composite.CompositeTransferRelation.java
public CompositeTransferRelation(ImmutableList<TransferRelation> transferRelations, boolean pErrorDetctableInStrengthen, Configuration config) throws InvalidConfigurationException { config.inject(this); this.transferRelations = transferRelations; size = transferRelations.size();/*from www. ja v a2s . c o m*/ isErrorStateDetectableInStrengthening = pErrorDetctableInStrengthen; // prepare special case handling if both predicates and assumptions are used for (int i = 0; i < size; i++) { TransferRelation t = transferRelations.get(i); if (t instanceof PredicateTransferRelation) { predicatesIndex = i; } if (t instanceof AssumptionStorageTransferRelation) { assumptionIndex = i; } } }
From source file:com.opengamma.strata.pricer.curve.CurveCalibrator.java
private ImmutableMap<CurveName, DoubleArray> sensitivityToMarketQuoteForGroup(ImmutableRatesProvider provider, ImmutableList<ResolvedTrade> trades, ImmutableList<CurveParameterSize> orderGroup) { Builder<CurveName, DoubleArray> mqsGroup = new Builder<>(); int nodeIndex = 0; for (CurveParameterSize cps : orderGroup) { int nbParameters = cps.getParameterCount(); double[] mqsCurve = new double[nbParameters]; for (int looptrade = 0; looptrade < nbParameters; looptrade++) { DoubleArray mqsNode = pvMeasures.derivative(trades.get(nodeIndex), provider, orderGroup); mqsCurve[looptrade] = mqsNode.get(nodeIndex); nodeIndex++;// w w w.j a v a2 s . com } mqsGroup.put(cps.getName(), DoubleArray.ofUnsafe(mqsCurve)); } return mqsGroup.build(); }
From source file:org.locationtech.geogig.geotools.plumbing.ExportOp.java
private Iterator<SimpleFeature> alter(Iterator<SimpleFeature> plainFeatures, final ObjectId targetFeatureTypeId) { final RevFeatureType targetType = objectDatabase().getFeatureType(targetFeatureTypeId); Function<SimpleFeature, SimpleFeature> alterFunction = new Function<SimpleFeature, SimpleFeature>() { @Override//from w w w .ja v a 2 s .c o m public SimpleFeature apply(SimpleFeature input) { final RevFeatureType oldFeatureType; oldFeatureType = (RevFeatureType) input.getUserData().get(RevFeatureType.class); final ObjectId metadataId = oldFeatureType.getId(); if (targetType.getId().equals(metadataId)) { return input; } final RevFeature oldFeature; oldFeature = (RevFeature) input.getUserData().get(RevFeature.class); ImmutableList<PropertyDescriptor> oldAttributes = oldFeatureType.sortedDescriptors(); ImmutableList<PropertyDescriptor> newAttributes = targetType.sortedDescriptors(); ImmutableList<Optional<Object>> oldValues = oldFeature.getValues(); List<Optional<Object>> newValues = Lists.newArrayList(); for (int i = 0; i < newAttributes.size(); i++) { int idx = oldAttributes.indexOf(newAttributes.get(i)); if (idx != -1) { Optional<Object> oldValue = oldValues.get(idx); newValues.add(oldValue); } else { newValues.add(Optional.absent()); } } RevFeature newFeature = RevFeatureImpl.build(ImmutableList.copyOf(newValues)); FeatureBuilder featureBuilder = new FeatureBuilder(targetType); SimpleFeature feature = (SimpleFeature) featureBuilder.build(input.getID(), newFeature); return feature; } }; return Iterators.transform(plainFeatures, alterFunction); }
From source file:com.github.kryptohash.kryptohashj.crypto.DeterministicHierarchy.java
/** * Returns a key for the given path, optionally creating it. * * @param path the path to the key/* w w w . j av a 2 s. c om*/ * @param relativePath whether the path is relative to the root path * @param create whether the key corresponding to path should be created (with any necessary ancestors) if it doesn't exist already * @return next newly created key using the child derivation function * @throws IllegalArgumentException if create is false and the path was not found. */ public DeterministicEd25519Key get(List<ChildNumber> path, boolean relativePath, boolean create) { ImmutableList<ChildNumber> absolutePath = relativePath ? ImmutableList.<ChildNumber>builder().addAll(rootPath).addAll(path).build() : ImmutableList.copyOf(path); if (!keys.containsKey(absolutePath)) { if (!create) throw new IllegalArgumentException(String.format("No key found for %s path %s.", relativePath ? "relative" : "absolute", HDUtils.formatPath(path))); checkArgument(absolutePath.size() > 0, "Can't derive the master key: nothing to derive from."); DeterministicEd25519Key parent = get(absolutePath.subList(0, absolutePath.size() - 1), false, true); putKey(HDKeyDerivation.deriveChildKey(parent, absolutePath.get(absolutePath.size() - 1))); } return keys.get(absolutePath); }
From source file:com.google.javascript.jscomp.TypeTransformation.java
private JSType evalConditional(Node ttlAst, NameResolver nameResolver) { ImmutableList<Node> params = getCallParams(ttlAst); if (evalBoolean(params.get(0), nameResolver)) { return evalInternal(params.get(1), nameResolver); } else {/*from ww w .java2 s.co m*/ return evalInternal(params.get(2), nameResolver); } }