List of usage examples for com.google.common.collect Iterables getOnlyElement
public static <T> T getOnlyElement(Iterable<T> iterable)
From source file:com.opengamma.financial.analytics.model.forex.option.callspreadblack.FXDigitalCallSpreadBlackVegaMatrixFunction.java
@Override protected Set<ComputedValue> getResult(final InstrumentDerivative fxDigital, final ForexOptionDataBundle<?> data, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final ValueSpecification spec, final FunctionExecutionContext executionContext) { final String spreadName = Iterables.getOnlyElement(desiredValues) .getConstraint(CalculationPropertyNamesAndValues.PROPERTY_CALL_SPREAD_VALUE); final double spread = Double.parseDouble(spreadName); final PresentValueBlackVolatilityNodeSensitivityCallSpreadBlackForexCalculator calculator = new PresentValueBlackVolatilityNodeSensitivityCallSpreadBlackForexCalculator( spread);/* ww w .j a va 2 s .com*/ final PresentValueForexBlackVolatilityNodeSensitivityDataBundle result = fxDigital.accept(calculator, (SmileDeltaTermStructureDataBundle) data.getVolatilityModel()); final double[] expiries = result.getExpiries().getData(); final double[] delta = result.getDelta().getData(); final double[][] vega = result.getVega().getData(); final int nDelta = delta.length; final int nExpiries = expiries.length; final Double[] rowValues = new Double[nExpiries]; final String[] rowLabels = new String[nExpiries]; final Double[] columnValues = new Double[nDelta]; final String[] columnLabels = new String[nDelta]; final double[][] values = new double[nDelta][nExpiries]; for (int i = 0; i < nDelta; i++) { columnValues[i] = delta[i]; columnLabels[i] = "P" + DELTA_FORMATTER.format(delta[i] * 100) + " " + result.getCurrencyPair().getFirst() + "/" + result.getCurrencyPair().getSecond(); for (int j = 0; j < nExpiries; j++) { if (i == 0) { rowValues[j] = expiries[j]; rowLabels[j] = getFormattedExpiry(expiries[j]); } values[i][j] = vega[j][i]; } } return Collections.singleton(new ComputedValue(spec, new DoubleLabelledMatrix2D(rowValues, rowLabels, columnValues, columnLabels, values))); }
From source file:grakn.core.graql.gremlin.sets.LabelFragmentSet.java
/** * Expand a {@link LabelFragmentSet} to match all sub-concepts of the single existing {@link Label}. * * Returns null if there is not exactly one label any of the {@link Label}s mentioned are not in the knowledge base. */// w w w . j av a2 s .c o m @Nullable LabelFragmentSet tryExpandSubs(Variable typeVar, TransactionOLTP tx) { if (labels().size() != 1) return null; Label oldLabel = Iterables.getOnlyElement(labels()); SchemaConcept concept = tx.getSchemaConcept(oldLabel); if (concept == null) return null; Set<Label> newLabels = concept.subs().map(SchemaConcept::label).collect(toSet()); return new AutoValue_LabelFragmentSet(varProperty(), typeVar, ImmutableSet.copyOf(newLabels)); }
From source file:com.google.devtools.build.lib.exec.FileWriteStrategy.java
@Override public void exec(AbstractFileWriteAction action, ActionExecutionContext actionExecutionContext) throws ExecException, InterruptedException { try (AutoProfiler p = AutoProfiler.logged("running " + action.prettyPrint(), LOG, /*minTimeForLoggingInMilliseconds=*/ 100)) { try {//from w w w .java2 s . c o m Path outputPath = Iterables.getOnlyElement(action.getOutputs()).getPath(); try (OutputStream out = new BufferedOutputStream(outputPath.getOutputStream())) { action.newDeterministicWriter(actionExecutionContext).writeOutputFile(out); } if (action.makeExecutable()) { outputPath.setExecutable(true); } } catch (IOException e) { throw new EnvironmentalExecException( "failed to create file '" + Iterables.getOnlyElement(action.getOutputs()).prettyPrint() + "' due to I/O error: " + e.getMessage(), e); } } }
From source file:com.google.errorprone.bugpatterns.InfiniteRecursion.java
@Override public Description matchMethod(MethodTree tree, VisitorState state) { if (tree.getBody() == null || tree.getBody().getStatements().size() != 1) { return NO_MATCH; }//from w ww.j a v a 2 s . c o m Tree statement = TreeInfo.skipParens((JCTree) Iterables.getOnlyElement(tree.getBody().getStatements())); ExpressionTree expr = statement.accept(new SimpleTreeVisitor<ExpressionTree, Void>() { @Override public ExpressionTree visitExpressionStatement(ExpressionStatementTree tree, Void unused) { return tree.getExpression(); } @Override public ExpressionTree visitReturn(ReturnTree tree, Void unused) { return tree.getExpression(); } }, null); if (!(expr instanceof MethodInvocationTree)) { return NO_MATCH; } ExpressionTree select = ((MethodInvocationTree) expr).getMethodSelect(); switch (select.getKind()) { case IDENTIFIER: break; case MEMBER_SELECT: ExpressionTree receiver = ((MemberSelectTree) select).getExpression(); if (receiver.getKind() != Kind.IDENTIFIER) { return NO_MATCH; } if (!((IdentifierTree) receiver).getName().contentEquals("this")) { return NO_MATCH; } break; default: return NO_MATCH; } MethodSymbol sym = ASTHelpers.getSymbol(tree); if (sym == null || !sym.equals(ASTHelpers.getSymbol(expr))) { return NO_MATCH; } return describeMatch(statement); }
From source file:org.apache.accumulo.test.merkle.MerkleTree.java
public MerkleTreeNode getRootNode() throws NoSuchAlgorithmException { ArrayList<MerkleTreeNode> buffer = new ArrayList<>(leaves.size()); buffer.addAll(leaves);// ww w .ja va 2s . c om while (buffer.size() > 1) { // Find two nodes that we want to roll up Pair<Integer, Integer> pairToJoin = findNextPair(buffer); // Make a parent node from them MerkleTreeNode parent = new MerkleTreeNode( Arrays.asList(buffer.get(pairToJoin.getFirst()), buffer.get(pairToJoin.getSecond())), digestAlgorithm); // Insert it back into the "tree" at the position of the first child buffer.set(pairToJoin.getFirst(), parent); // Remove the second child completely buffer.remove(pairToJoin.getSecond().intValue()); // "recurse" } return Iterables.getOnlyElement(buffer); }
From source file:com.google.template.soy.types.aggregate.UnionType.java
/** * Create a union from a collection of types. * @param members Member types of the union. * @return Union of those types./*from w w w. j a v a 2 s.co m*/ * If there is exactly one distinct type in members, then this will not be a UnionType. */ public static SoyType of(Collection<SoyType> members) { ImmutableSet<SoyType> flattenedMembers = flatten(members); if (flattenedMembers.size() == 1) { return Iterables.getOnlyElement(flattenedMembers); } return new UnionType(flattenedMembers); }
From source file:com.google.template.soy.jssrc.dsl.ConditionalExpressionBuilder.java
@Nullable private Expression tryCreateTernary(ImmutableList<IfThenPair<Expression>> pairs) { if (pairs.size() != 1 || trailingElse == null) { return null; }/* www . j a va 2 s .c o m*/ IfThenPair<Expression> ifThen = Iterables.getOnlyElement(pairs); Expression predicate = ifThen.predicate; Expression consequent = ifThen.consequent; // TODO(lukes): we could support nested ternaries with little additional difficulty if (predicate.initialStatements().containsAll(consequent.initialStatements()) && predicate.initialStatements().containsAll(trailingElse.initialStatements())) { return Ternary.create(predicate, consequent, trailingElse); } return null; }
From source file:com.opengamma.financial.analytics.model.curve.HardCodedHullWhiteOneFactorParametersFunction.java
@Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) throws AsynchronousExecution { final ValueProperties properties = Iterables.getOnlyElement(desiredValues).getConstraints().copy().get(); final ValueSpecification spec = new ValueSpecification(HULL_WHITE_ONE_FACTOR_PARAMETERS, target.toSpecification(), properties); return Collections.singleton(new ComputedValue(spec, CONSTANT_PARAMETERS)); }
From source file:com.eucalyptus.compute.vpc.persist.PersistenceInternetGateways.java
@Override public <T> T lookupByVpc(@Nullable final OwnerFullName ownerFullName, final String vpcId, final Function<? super InternetGateway, T> transform) throws VpcMetadataException { try {/*from ww w. ja v a 2 s. c o m*/ return Iterables.getOnlyElement(listByExample(InternetGateway.exampleWithOwner(ownerFullName), Predicates.alwaysTrue(), Restrictions.eq("vpc.displayName", vpcId), Collections.singletonMap("vpc", "vpc"), transform)); } catch (NoSuchElementException e) { throw new VpcMetadataNotFoundException("Internet gateway not found for " + vpcId); } }
From source file:io.druid.indexing.common.task.MoveTask.java
@Override public TaskStatus run(TaskToolbox toolbox) throws Exception { // Confirm we have a lock (will throw if there isn't exactly one element) final TaskLock myLock = Iterables.getOnlyElement(getTaskLocks(toolbox)); if (!myLock.getDataSource().equals(getDataSource())) { throw new ISE("WTF?! Lock dataSource[%s] != task dataSource[%s]", myLock.getDataSource(), getDataSource());/* w ww . j a v a 2s . com*/ } if (!myLock.getInterval().equals(getInterval())) { throw new ISE("WTF?! Lock interval[%s] != task interval[%s]", myLock.getInterval(), getInterval()); } // List unused segments final List<DataSegment> unusedSegments = toolbox.getTaskActionClient() .submit(new SegmentListUnusedAction(myLock.getDataSource(), myLock.getInterval())); // Verify none of these segments have versions > lock version for (final DataSegment unusedSegment : unusedSegments) { if (unusedSegment.getVersion().compareTo(myLock.getVersion()) > 0) { throw new ISE("WTF?! Unused segment[%s] has version[%s] > task version[%s]", unusedSegment.getIdentifier(), unusedSegment.getVersion(), myLock.getVersion()); } log.info("OK to move segment: %s", unusedSegment.getIdentifier()); } // Move segments for (DataSegment segment : unusedSegments) { final DataSegment movedSegment = toolbox.getDataSegmentMover().move(segment, targetLoadSpec); toolbox.getTaskActionClient().submit(new SegmentMetadataUpdateAction(ImmutableSet.of(movedSegment))); } return TaskStatus.success(getId()); }