List of usage examples for com.google.common.collect Iterables get
public static <T> T get(Iterable<T> iterable, int position)
From source file:iterator.Animator.java
/** * Parse the animation configuration file. * * See the online documentation for more details. The format is generally as shown below: * * <pre>//from w w w.java2 s .c o m * {@code # comment * ifs file * save directory * frames count * delay ms * iterations thousands * zoom scale centrex centrey * segment frames * transform id field start finish * end} * </pre> * * @see <a href="http://grkvlt.github.io/iterator/">online documentation</a> * @throws IOException * @throws IllegalStateException * @throws NumberFormatException */ public void parse(File config) throws IOException { for (String line : Files.readLines(config, Charsets.UTF_8)) { Iterable<String> tokens = Splitter.on(' ').omitEmptyStrings().trimResults().split(line); if (Iterables.isEmpty(tokens)) continue; String type = Iterables.get(tokens, 0); if (type.equalsIgnoreCase("ifs")) { // ifs file if (Iterables.size(tokens) != 2) { throw new IllegalStateException("Parse error at 'ifs': " + line); } input = new File(Iterables.get(tokens, 1).replace("~", System.getProperty("user.home"))); } else if (type.equalsIgnoreCase("save")) { // save directory if (Iterables.size(tokens) != 2) { throw new IllegalStateException("Parse error at 'save': " + line); } output = new File(Iterables.get(tokens, 1).replace("~", System.getProperty("user.home"))); } else if (type.equalsIgnoreCase("frames")) { // frames count if (Iterables.size(tokens) != 2) { throw new IllegalStateException("Parse error at 'frames': " + line); } frames = Long.valueOf(Iterables.get(tokens, 1)); } else if (type.equalsIgnoreCase("delay")) { // delay ms if (Iterables.size(tokens) != 2) { throw new IllegalStateException("Parse error at 'delay': " + line); } delay = Long.valueOf(Iterables.get(tokens, 1)); } else if (type.equalsIgnoreCase("iterations")) { // iterations thousands if (Iterables.size(tokens) != 2) { throw new IllegalStateException("Parse error at 'iterations': " + line); } iterations = Long.valueOf(Iterables.get(tokens, 1)); } else if (type.equalsIgnoreCase("zoom")) { // zoom scale centrex centrey if (Iterables.size(tokens) != 4) { throw new IllegalStateException("Parse error at 'zoom': " + line); } scale = Float.valueOf(Iterables.get(tokens, 1)); centre = new Point2D.Double(Double.valueOf(Iterables.get(tokens, 2)), Double.valueOf(Iterables.get(tokens, 3))); } else if (type.equalsIgnoreCase("transform")) { // transform id field start finish if (Iterables.size(tokens) != 5) { throw new IllegalStateException("Parse error at 'transform': " + line); } Change change = new Change(); change.transform = Integer.valueOf(Iterables.get(tokens, 1)); String field = Iterables.get(tokens, 2).toLowerCase(); if (field.length() == 1 && CharMatcher.anyOf("xywhr").matches(field.charAt(0))) { change.field = field.charAt(0); } else { throw new IllegalStateException("Parse error at 'transform' field: " + line); } change.start = Double.valueOf(Iterables.get(tokens, 3)); change.end = Double.valueOf(Iterables.get(tokens, 4)); list.add(change); } else if (type.equalsIgnoreCase("segment")) { // segment frames? if (Iterables.size(tokens) == 2) { segment = Long.valueOf(Iterables.get(tokens, 1)); } else { segment = frames; } list.clear(); } else if (type.equalsIgnoreCase("end")) { // end if (Iterables.size(tokens) != 1) { throw new IllegalStateException("Parse error at 'end': " + line); } segments.put(ImmutableList.copyOf(list), segment); } else if (type.startsWith("#")) { // # comment continue; } else { throw new IllegalStateException("Parse error: " + line); } } // Deal with single segment case (no 'segment' or 'end' token) if (segments.isEmpty() && list.size() > 0) { segments.put(ImmutableList.copyOf(list), frames); } }
From source file:dagger.internal.codegen.DuplicateBindingsValidation.java
private void reportDuplicateBindings(DependencyRequest dependencyRequest, Set<DependencyEdge> duplicateDependencies, BindingGraph bindingGraph, DiagnosticReporter diagnosticReporter) { ImmutableSet<BindingNode> duplicateBindings = duplicateDependencies.stream() .map(edge -> bindingGraph.incidentNodes(edge).target()).flatMap(instancesOf(BindingNode.class)) .collect(toImmutableSet());// w w w. j a v a 2 s. com diagnosticReporter.reportDependency(ERROR, Iterables.get(duplicateDependencies, 0), Iterables.any(duplicateBindings, node -> node.binding().kind().isMultibinding()) ? incompatibleBindingsMessage(dependencyRequest, duplicateBindings, bindingGraph) : duplicateBindingMessage(dependencyRequest, duplicateBindings, bindingGraph)); }
From source file:org.jclouds.gogrid.compute.strategy.GoGridComputeServiceAdapter.java
@Override public NodeAndInitialCredentials<Server> createNodeWithGroupEncodedIntoName(String group, String name, Template template) {/*w w w . j a va 2s .co m*/ Server addedServer = null; boolean notStarted = true; int numOfRetries = 20; GetIpListOptions unassignedIps = new GetIpListOptions().onlyUnassigned() .inDatacenter(template.getLocation().getId()).onlyWithType(IpType.PUBLIC); // lock-free consumption of a shared resource: IP address pool while (notStarted) { // TODO: replace with Predicate-based thread // collision avoidance for simplicity Set<Ip> availableIps = client.getIpServices().getIpList(unassignedIps); if (availableIps.isEmpty()) throw new RuntimeException("No IPs available on this identity."); int ipIndex = new SecureRandom().nextInt(availableIps.size()); Ip availableIp = Iterables.get(availableIps, ipIndex); try { addedServer = addServer(name, template, availableIp); notStarted = false; } catch (Exception e) { if (--numOfRetries == 0) Throwables.propagate(e); notStarted = true; } } if (template.getOptions().shouldBlockUntilRunning()) { serverLatestJobCompleted.apply(addedServer); client.getServerServices().power(addedServer.getName(), PowerCommand.START); serverLatestJobCompletedShort.apply(addedServer); addedServer = Iterables .getOnlyElement(client.getServerServices().getServersByName(addedServer.getName())); } LoginCredentials credentials = LoginCredentials .fromCredentials(client.getServerServices().getServerCredentialsList().get(addedServer.getName())); return new NodeAndInitialCredentials<Server>(addedServer, addedServer.getId() + "", credentials); }
From source file:org.jbb.permissions.web.role.controller.AbstractAcpPermissionRoleDetailsController.java
@AdministratorPermissionRequired(CAN_MANAGE_PERMISSION_ROLES) @RequestMapping(path = "/new", method = RequestMethod.GET) public String roleCreate(Model model) { List<PermissionRoleDefinition> predefinedRoles = permissionRoleService .getPredefinedRoles(getPermissionType()); List<RoleRow> roleRows = rolesMapper.toRowList(predefinedRoles); PredefinedRoleForm form = new PredefinedRoleForm(); form.setRoleId(Iterables.get(roleRows, 0).getRoleId()); model.addAttribute(PREDEFINED_ROLE_FORM, form); model.addAttribute(ROLE_TYPE_SUFFIX, getPermissionTypeUrlSuffix()); model.addAttribute("predefinedRoles", roleRows); return PREDEFINED_CHOOSE_VIEW_NAME; }
From source file:com.opengamma.integration.viewer.status.impl.SimpleViewStatusModel.java
@Override public Object getRowValueAt(int rowIndex, int columnIndex) { if (rowIndex < 0 || rowIndex >= _rows.size()) { throw new IllegalArgumentException("RowIndex must be in range 0 >= rowIndex < " + _rows.size()); }//from w w w.j ava 2 s . c o m if (columnIndex < 0 || columnIndex >= getColumnCount()) { throw new IllegalArgumentException( "ColumnIndex must be in range 0 >= columnIndex < " + getColumnCount()); } return Iterables.get(Iterables.get(_rows, rowIndex), columnIndex); }
From source file:com.caiyunworks.crm.business.service.impl.HolidayServiceImpl.java
@Override public int update(Holiday record) throws UnsupportedOperationException, RecordNotExistException, OutOfDateRecordException, RecordAlreadyExistException { Holiday holiday = holidayRepository.findById(record.getId()); if (null == holiday) { if (logger.isWarnEnabled()) { logger.warn("try to update holiday {}, but it does not exist in DB.", record.getId()); }// ww w . j a v a 2 s .c o m throw new RecordNotExistException(); } else { if (!holiday.getVersionNumber().equals(record.getVersionNumber())) { if (logger.isWarnEnabled()) { logger.warn("holiday record is out of date, version {}, latest version {}", record.getVersionNumber(), holiday.getVersionNumber()); } throw new OutOfDateRecordException(); } Iterable<Holiday> holidays = holidayRepository.findByNameOrDateRange(record.getName(), record.getStartDate(), record.getEndDate()); if (null == holidays || Iterables.isEmpty(holidays)) { return holidayRepository.update(record); } else { if (Iterables.size(holidays) == 1 && Iterables.get(holidays, 0).getId() == record.getId()) { return holidayRepository.update(record); } else { if (logger.isWarnEnabled()) { logger.warn("try to update holiday {}, but it is already exist in DB.", record); } throw new RecordAlreadyExistException(); } } } }
From source file:org.apache.mahout.knn.means.StreamingKmeans.java
protected UpdatableSearcher clusterInternal(Iterable<MatrixSlice> data, int maxClusters, int depth, CentroidFactory centroidFactory) { // to cluster, we scan the data and either add each point to the nearest group or create a new group. // when we get too many groups, we need to increase the threshold and rescan our current groups Random rand = RandomUtils.getRandom(); int n = 0;// www . j a va 2 s .c o m UpdatableSearcher centroids = centroidFactory.create(); centroids.add(Centroid.create(0, Iterables.get(data, 0).vector()), 0); for (MatrixSlice row : Iterables.skip(data, 1)) { // estimate distance d to closest centroid WeightedVector closest = centroids.search(row.vector(), 1).get(0); if (rand.nextDouble() < closest.getWeight() / distanceCutoff) { // add new centroid, note that the vector is copied because we may mutate it later centroids.add(Centroid.create(centroids.size(), row.vector()), centroids.size()); } else { // merge against existing Centroid c = (Centroid) closest.getVector(); centroids.remove(c); c.update(row.vector()); centroids.add(c, c.getIndex()); } if (depth < 2 && centroids.size() > maxClusters) { maxClusters = (int) Math.max(maxClusters, 10 * Math.log(n)); // TODO does shuffling help? List<MatrixSlice> shuffled = Lists.newArrayList(centroids); Collections.shuffle(shuffled); centroids = clusterInternal(shuffled, maxClusters, depth + 1, centroidFactory); // in the original algorithm, with distributions with sharp scale effects, the // distanceCutoff can grow to excessive size leading sub-clustering to collapse // the centroids set too much. This test prevents increase in distanceCutoff // the current value is doing fine at collapsing the clusters. if (centroids.size() > 0.2 * maxClusters) { distanceCutoff *= BETA; } } n++; } return centroids; }
From source file:sklearn.svm.BaseLibSVMClassifier.java
@Override public SupportVectorMachineModel encodeModel(Schema schema) { int[] shape = getSupportVectorsShape(); int numberOfVectors = shape[0]; int numberOfFeatures = shape[1]; List<Integer> support = getSupport(); List<? extends Number> supportVectors = getSupportVectors(); List<Integer> supportSizes = getSupportSizes(); List<? extends Number> dualCoef = getDualCoef(); List<? extends Number> intercept = getIntercept(); int[] offsets = new int[supportSizes.size() + 1]; for (int i = 0; i < supportSizes.size(); i++) { offsets[i + 1] = offsets[i] + supportSizes.get(i); }/* w w w . jav a2s. c om*/ VectorDictionary vectorDictionary = SupportVectorMachineUtil.encodeVectorDictionary(support, supportVectors, numberOfVectors, numberOfFeatures, schema); List<VectorInstance> vectorInstances = vectorDictionary.getVectorInstances(); Kernel kernel = SupportVectorMachineUtil.encodeKernel(getKernel(), getDegree(), getGamma(), getCoef0()); List<SupportVectorMachine> supportVectorMachines = new ArrayList<>(); int i = 0; List<String> targetCategories = schema.getTargetCategories(); for (int first = 0; first < targetCategories.size(); first++) { for (int second = first + 1; second < targetCategories.size(); second++) { List<VectorInstance> svmVectorInstances = new ArrayList<>(); svmVectorInstances.addAll(slice(vectorInstances, offsets, first)); svmVectorInstances.addAll(slice(vectorInstances, offsets, second)); List<Number> svmDualCoef = new ArrayList<>(); svmDualCoef.addAll( slice(MatrixUtil.getRow(dualCoef, targetCategories.size() - 1, numberOfVectors, second - 1), offsets, first)); svmDualCoef.addAll( slice(MatrixUtil.getRow(dualCoef, targetCategories.size() - 1, numberOfVectors, first), offsets, second)); // LibSVM: (decisionFunction > 0 ? first : second) // PMML: (decisionFunction < 0 ? first : second) SupportVectorMachine supportVectorMachine = SupportVectorMachineUtil .encodeSupportVectorMachine(svmVectorInstances, svmDualCoef, Iterables.get(intercept, i)) .setTargetCategory(targetCategories.get(second)) .setAlternateTargetCategory(targetCategories.get(first)); supportVectorMachines.add(supportVectorMachine); i++; } } SupportVectorMachineModel supportVectorMachineModel = new SupportVectorMachineModel( MiningFunction.CLASSIFICATION, ModelUtil.createMiningSchema(schema), vectorDictionary, supportVectorMachines) .setClassificationMethod(SupportVectorMachineModel.ClassificationMethod.ONE_AGAINST_ONE) .setKernel(kernel); return supportVectorMachineModel; }
From source file:dagger.internal.codegen.IncorrectlyInstalledBindsMethodsValidator.java
private void report(BindingNode incompatiblyInstalledBinding, ComponentPath idealComponentPath, BindingGraph graph, DiagnosticReporter diagnosticReporter) { // TODO(dpb): consider creating this once per visitGraph() ImmutableGraph<Node> dependencyGraph = dependencyGraph(graph).asGraph(); Set<Node> culpableDependencies = Graphs.reachableNodes(dependencyGraph, incompatiblyInstalledBinding) .stream().filter(node -> isChild(idealComponentPath, node.componentPath())) .filter(node -> !node.equals(incompatiblyInstalledBinding)) .collect(toCollection(LinkedHashSet::new)); if (culpableDependencies.isEmpty()) { return;//ww w .j ava2s .c o m } StringBuilder warning = new StringBuilder().append("Floating @Binds method detected:\n ") .append(incompatiblyInstalledBinding).append("\n It is installed in: ") .append(idealComponentPath).append("\n But is being resolved in: ") .append(incompatiblyInstalledBinding.componentPath()) .append("\n This is because it depends transitively on:"); while (!culpableDependencies.isEmpty()) { BindingNode culpableDependency = (BindingNode) Iterables.get(culpableDependencies, 0); warning.append("\n ").append(culpableDependency).append(", resolved in: ") .append(culpableDependency.componentPath()); culpableDependencies.removeAll(Graphs.reachableNodes(dependencyGraph, culpableDependency)); } diagnosticReporter.reportComponent(WARNING, graph.rootComponentNode(), warning.toString()); }
From source file:com.google.security.zynamics.reil.translators.ReilTranslator.java
/** * Returns the addresses of all basic blocks of a function. Note that the addresses are already * converted to REIL addresses./*from www .ja v a 2s . co m*/ * * @param function The input function. * * @return A list of all basic block addresses of the function. */ private static Collection<IAddress> getBlockAddresses(final IBlockContainer<?> function) { return CollectionHelpers.map(function.getBasicBlocks(), new ICollectionMapper<ICodeContainer<?>, IAddress>() { private boolean isDelayedBranch(final ReilInstruction instruction) { return instruction.getMnemonic().equals(ReilHelpers.OPCODE_JCC) && ReilHelpers.isDelayedBranch(instruction); } @Override public IAddress map(final ICodeContainer<?> block) { final IInstruction lastInstruction = Iterables.getFirst(block.getInstructions(), null); // getLastInstruction(block); final ReilTranslator<IInstruction> translator = new ReilTranslator<IInstruction>(); try { final ReilGraph reilGraph = translator.translate(new StandardEnvironment(), lastInstruction); final ReilBlock lastNode = reilGraph.getNodes().get(reilGraph.getNodes().size() - 1); final ReilInstruction lastReilInstruction = Iterables .getLast(lastNode.getInstructions()); if (isDelayedBranch(lastReilInstruction)) // If branch-delay { return ReilHelpers .toReilAddress(Iterables.get(block.getInstructions(), 1).getAddress()); } else { return ReilHelpers.toReilAddress(block.getAddress()); } } catch (final InternalTranslationException e) { return ReilHelpers.toReilAddress(block.getAddress()); } } }); }