List of usage examples for com.google.common.collect Iterables get
public static <T> T get(Iterable<T> iterable, int position)
From source file:io.prestosql.sql.planner.plan.SetOperationNode.java
@JsonCreator protected SetOperationNode(@JsonProperty("id") PlanNodeId id, @JsonProperty("sources") List<PlanNode> sources, @JsonProperty("outputToInputs") ListMultimap<Symbol, Symbol> outputToInputs, @JsonProperty("outputs") List<Symbol> outputs) { super(id);/*from www. ja v a 2s . c om*/ requireNonNull(sources, "sources is null"); checkArgument(!sources.isEmpty(), "Must have at least one source"); requireNonNull(outputToInputs, "outputToInputs is null"); requireNonNull(outputs, "outputs is null"); this.sources = ImmutableList.copyOf(sources); this.outputToInputs = ImmutableListMultimap.copyOf(outputToInputs); this.outputs = ImmutableList.copyOf(outputs); for (Collection<Symbol> inputs : this.outputToInputs.asMap().values()) { checkArgument(inputs.size() == this.sources.size(), "Every source needs to map its symbols to an output %s operation symbol", this.getClass().getSimpleName()); } // Make sure each source positionally corresponds to their Symbol values in the Multimap for (int i = 0; i < sources.size(); i++) { for (Collection<Symbol> expectedInputs : this.outputToInputs.asMap().values()) { checkArgument(sources.get(i).getOutputSymbols().contains(Iterables.get(expectedInputs, i)), "Source does not provide required symbols"); } } }
From source file:fi.jyu.ties454.cleaningAgents.infra.Floor.java
/** * Get a random location./*from w w w . j av a 2s .c o m*/ * * @param r * @return */ Location getRandomLocation(Random r) { Cell<Integer, Integer, FloorState> cell = Iterables.get(this.map.cellSet(), r.nextInt((this.map.cellSet().size()))); Location l = new Location(cell.getColumnKey(), cell.getRowKey()); if (!this.isValidLocation(l)) { throw new Error("Randomly chose location must be valid"); } return l; }
From source file:r.base.special.SwitchFunction.java
@Override public SEXP apply(Context context, Environment rho, FunctionCall call, PairList args) { EvalException.check(call.length() > 1, "argument \"EXPR\" is missing"); SEXP expr = context.evaluate(call.getArgument(0), rho); EvalException.check(expr.length() == 1, "EXPR must return a length 1 vector"); PromisePairList branchPromises = (PromisePairList) context.evaluate(call.getArgument(1), rho); Iterable<PairList.Node> branches = branchPromises.nodes(); if (expr instanceof StringVector) { String name = ((StringVector) expr).getElementAsString(0); if (StringVector.isNA(name)) { context.setInvisibleFlag();/*from w w w .j av a 2 s . c o m*/ return Null.INSTANCE; } SEXP partialMatch = null; int partialMatchCount = 0; for (PairList.Node node : branches) { if (node.hasTag()) { String branchName = node.getTag().getPrintName(); if (branchName.equals(name)) { return context.evaluate(nextNonMissing(node), rho); } else if (branchName.startsWith(name)) { partialMatch = nextNonMissing(node); partialMatchCount++; } } } if (partialMatchCount == 1) { return context.evaluate(partialMatch, rho); } else if (Iterables.size(branches) > 0) { PairList.Node last = Iterables.getLast(branches); if (!last.hasTag()) { return context.evaluate(last.getValue(), rho); } } } else if (expr instanceof AtomicVector) { int branchIndex = ((AtomicVector) expr).getElementAsInt(0); if (branchIndex >= 1 && branchIndex <= Iterables.size(branches)) { return context.evaluate(Iterables.get(branches, branchIndex - 1).getValue(), rho); } } return Null.INSTANCE; }
From source file:edu.wpi.checksims.algorithm.similaritymatrix.output.MatrixThresholdPrinter.java
/** * Print significant results in a similarity matrix. * * @param matrix Matrix to print/*from w ww .j a v a 2 s. c o m*/ * @return Results in matrix over threshold * @throws InternalAlgorithmError Thrown on internal error processing matrix */ @Override public String printMatrix(SimilarityMatrix matrix) throws InternalAlgorithmError { checkNotNull(matrix); StringBuilder builder = new StringBuilder(); DecimalFormat formatter = new DecimalFormat("0.##"); ImmutableSet<AlgorithmResults> results = matrix.getBaseResults(); Set<AlgorithmResults> filteredBelowThreshold = results.stream() .filter((result) -> result.percentMatchedA() >= threshold || result.percentMatchedB() >= threshold) .collect(Collectors.toCollection(HashSet::new)); if (filteredBelowThreshold.isEmpty()) { builder.append("No significant matches found.\n"); } // Loop until all results over threshold consumed while (!filteredBelowThreshold.isEmpty()) { // Find the largest single result double largest = 0.00; AlgorithmResults largestResult = Iterables.get(filteredBelowThreshold, 0); for (AlgorithmResults result : filteredBelowThreshold) { if (result.percentMatchedA() > largest) { largest = result.percentMatchedA(); largestResult = result; } if (result.percentMatchedB() > largest) { largest = result.percentMatchedB(); largestResult = result; } } double largerOfTwo; double smallerOfTwo; Submission largerSubmission; Submission smallerSubmission; if (largestResult.percentMatchedA() >= largestResult.percentMatchedB()) { largerOfTwo = largestResult.percentMatchedA() * 100; smallerOfTwo = largestResult.percentMatchedB() * 100; largerSubmission = largestResult.a; smallerSubmission = largestResult.b; } else { largerOfTwo = largestResult.percentMatchedB() * 100; smallerOfTwo = largestResult.percentMatchedA() * 100; largerSubmission = largestResult.b; smallerSubmission = largestResult.a; } // We have the largest single result, print it builder.append("Found match of "); builder.append(formatter.format(largerOfTwo)); builder.append("% (inverse match "); builder.append(formatter.format(smallerOfTwo)); builder.append("%) between submissions \""); builder.append(largerSubmission.getName()); builder.append("\" and \""); builder.append(smallerSubmission.getName()); builder.append("\"\n"); // Remove the largest results filteredBelowThreshold.remove(largestResult); } return builder.toString(); }
From source file:com.github.richardwilly98.esdms.shiro.EsRealm.java
@Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { log.trace("*** doGetAuthorizationInfo ***"); Collection<User> principalList = principals.byType(User.class); if (principals.isEmpty()) { throw new AuthorizationException("Empty principal list!"); }//from ww w.jav a2 s .co m User principal = Iterables.get(principalList, 0);//.iterator().next(); log.debug(String.format("getAuthorization for %s", principal.getId())); Set<String> roles = new HashSet<String>(); Set<String> permissions = new HashSet<String>(); for (Role role : principal.getRoles()) { log.trace(String.format("add role %s to %s", role.getId(), principal.getId())); roles.add(role.getId()); try { role = roleService.get(role.getId()); for (Permission permission : role.getPermissions()) { log.trace(String.format("add permission %s to %s", permission.getId(), principal.getId())); permissions.add(permission.getId()); } } catch (ServiceException ex) { log.error(String.format("Cannot get role from id [%s]", role.getId()), ex); } } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.setRoles(roles); info.setStringPermissions(permissions); return info; }
From source file:org.chtijbug.drools.guvnor.rest.RuleTemplateManager.java
private void updateTableContent(Map<String, List<String>> newTable, TemplateModel templateModel) throws ChtijbugDroolsRestException { templateModel.clearRows();//ww w.ja v a 2 s. c om int rowCount = Iterables.get(newTable.values(), 1).size(); List<String> columnNames = orderedColumnNames(templateModel); checkColumnNames(columnNames, newTable); for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { List<String> row = newArrayList(); for (String columnName : columnNames) { row.add(newTable.get(columnName).get(rowIndex)); } templateModel.addRow(row.toArray(new String[row.size()])); } }
From source file:org.jclouds.vcloud.director.v1_5.compute.util.VCloudDirectorComputeUtils.java
public static LoginCredentials getCredentialsFrom(VApp vApp) { return vApp.getChildren().getVms().size() > 0 ? getCredentialsFrom(Iterables.get(vApp.getChildren().getVms(), 0)) : null;//from w w w . j a v a 2 s . c o m }
From source file:com.replaymod.replaystudio.pathing.change.RemoveKeyframe.java
@Override public void apply(Timeline timeline) { Preconditions.checkState(!applied, "Already applied!"); Path path = timeline.getPaths().get(this.path); // The interpolator can only be saved if there are at least two keyframes / one segment if (!path.getSegments().isEmpty()) { // By default we keep the interpolator of the left-hand side and and store the right-hand side for undoing // however if this is the last keyframe, we have to store the left-hand side as it will otherwise be lost if (index == path.getSegments().size()) { // This is the last keyframe, save the previous interpolator removedInterpolator = Iterables.get(path.getSegments(), index - 1).getInterpolator(); } else {/*www .java2 s . com*/ // Save the next interpolator removedInterpolator = Iterables.get(path.getSegments(), index).getInterpolator(); } } path.remove(removedKeyframe = Iterables.get(path.getKeyframes(), index), true); applied = true; }
From source file:org.richfaces.component.DeclarativeTreeDataModelWalker.java
private void setupDataModelContext(Object key) { if (modelData instanceof Iterable<?>) { Iterable<?> iterable = (Iterable<?>) modelData; Integer index = (Integer) key; if (index < Iterables.size(iterable)) { data = Iterables.get(iterable, index); } else {// w ww . j a v a2s. c o m data = null; } } else { data = ((Map<?, ?>) modelData).get(key); } }
From source file:org.jclouds.savvis.vpdc.compute.functions.VMToNodeMetadata.java
@Override public NodeMetadata apply(VM from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getHref().toASCIIString()); builder.name(from.getName());// www. j av a 2 s . c o m String locationId = Iterables.get(from.getNetworkSection().getNetworks(), 0).getName(); builder.location(from(locations.get()).firstMatch(LocationPredicates.idEquals(locationId)).orNull()); builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName())); try { builder.operatingSystem(CIMOperatingSystem.toComputeOs(from.getOperatingSystemSection())); } catch (NullPointerException e) { // os section was null } // TODO build from resource allocation section // builder.hardware(findHardwareForVM.apply(from)); builder.status(VAPPSTATUS_TO_NODESTATE.get(from.getStatus())); Set<String> addresses = Utils.getIpsFromVM(from); builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE))); builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE)); return builder.build(); }