List of usage examples for com.google.common.collect Multimap entries
Collection<Map.Entry<K, V>> entries();
From source file:org.voltdb.sysprocs.saverestore.StreamSnapshotWritePlan.java
protected boolean createSetupInternal(String file_path, String file_nonce, long txnId, Map<Integer, Long> partitionTransactionIds, JSONObject jsData, SystemProcedureExecutionContext context, String hostname, final VoltTable result, Map<String, Map<Integer, Pair<Long, Long>>> exportSequenceNumbers, SiteTracker tracker, long timestamp) throws IOException { assert (SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.isEmpty()); final StreamSnapshotRequestConfig config = new StreamSnapshotRequestConfig(jsData, context.getDatabase()); final List<StreamSnapshotRequestConfig.Stream> localStreams = filterRemoteStreams(config.streams, Longs.asList(tracker.getLocalSites())); final Map<Long, Integer> tokensToAdd = createTokensToAdd(localStreams); // Coalesce a truncation snapshot if shouldTruncate is true if (config.shouldTruncate) { /*/*from w w w .j av a2 s . c o m*/ * The snapshot will only contain existing partitions. Write the new partition count * down in the digest so that we can check if enough command log is collected on * replay. */ final int newPartitionCount = calculateNewPartitionCount(context.getNumberOfPartitions(), tokensToAdd); coalesceTruncationSnapshotPlan(file_path, file_nonce, txnId, partitionTransactionIds, jsData, context, hostname, result, exportSequenceNumbers, tracker, timestamp, newPartitionCount); } // Create post snapshot update hashinator work List<Integer> localPartitions = tracker.getPartitionsForHost(context.getHostId()); if (!tokensToAdd.isEmpty()) { createUpdateHashinatorTasksForSites(localPartitions, tokensToAdd, txnId); } // Mark snapshot start in registry final AtomicInteger numTables = new AtomicInteger(config.tables.length); final SnapshotRegistry.Snapshot snapshotRecord = SnapshotRegistry.startSnapshot(txnId, context.getHostId(), file_path, file_nonce, SnapshotFormat.STREAM, config.tables); // table schemas for all the tables we'll snapshot on this partition Map<Integer, byte[]> schemas = new HashMap<Integer, byte[]>(); for (final Table table : config.tables) { VoltTable schemaTable = CatalogUtil.getVoltTable(table); schemas.put(table.getRelativeIndex(), schemaTable.getSchemaBytes()); } List<DataTargetInfo> sdts = createDataTargets(localStreams, schemas); // Pick a pair of source to destination for each stream to ship the replicated table data. Multimap<Long, Long> replicatedSrcToDst = pickOnePairPerStream(config.streams); if (SNAP_LOG.isDebugEnabled()) { SNAP_LOG.debug("Picked the following sites to transfer replicated table: " + CoreUtils.hsIdEntriesToString(replicatedSrcToDst.entries())); } // If there's no work to do on this host, just claim success, return an empty plan, // and things will sort themselves out properly // For each table, create tasks where each task has a data target. for (final Table table : config.tables) { createTasksForTable(table, sdts, replicatedSrcToDst, numTables, snapshotRecord); result.addRow(context.getHostId(), hostname, table.getTypeName(), "SUCCESS", ""); } return false; }
From source file:net.sourceforge.cilib.type.types.container.StandardGraph.java
@Override public boolean equals(Object obj) { if (this == obj) { return true; }//from w ww.ja v a 2s . c o m if ((obj == null) || (this.getClass() != obj.getClass())) { return false; } StandardGraph<E> graph = (StandardGraph<E>) obj; if (this.adjacencyMap.size() != graph.adjacencyMap.size()) { return false; } if (this.edgeCount() != graph.edgeCount()) { return false; } if (!adjacencyMap.keySet().containsAll(graph.adjacencyMap.keySet())) { return false; } // Set up the edge sets. Multimap<E, E> currentEdgeSet = this.getEdgeSet(); Multimap<E, E> otherEdgeSet = graph.getEdgeSet(); for (Map.Entry<E, E> entry : currentEdgeSet.entries()) { if (!otherEdgeSet.containsEntry(entry.getKey(), entry.getValue())) { return false; } } for (Map.Entry<E, E> entry : otherEdgeSet.entries()) { if (!currentEdgeSet.containsEntry(entry.getKey(), entry.getValue())) { return false; } } return true; }
From source file:org.apache.tez.history.parser.datamodel.DagInfo.java
/** * Get node details for this DAG. Would be useful for analyzing node to tasks. * * @return Multimap<String, TaskAttemptInfo> taskAttempt details at every node */// ww w . ja va 2 s . c o m public final Multimap<String, TaskAttemptInfo> getNodeDetails() { Multimap<String, TaskAttemptInfo> nodeDetails = LinkedListMultimap.create(); for (VertexInfo vertexInfo : getVertices()) { Multimap<Container, TaskAttemptInfo> containerMapping = vertexInfo.getContainersMapping(); for (Map.Entry<Container, TaskAttemptInfo> entry : containerMapping.entries()) { nodeDetails.put(entry.getKey().getHost(), entry.getValue()); } } return nodeDetails; }
From source file:ai.grakn.graql.internal.reasoner.atom.binary.Relation.java
/** * @return map of pairs role type - Id predicate describing the role player playing this role (substitution) *///www . j av a 2s. c om private Multimap<RoleType, String> getRoleConceptIdMap() { if (roleConceptIdMap == null) { roleConceptIdMap = ArrayListMultimap.create(); Map<Var, IdPredicate> varSubMap = getPartialSubstitutions().stream() .collect(Collectors.toMap(Atomic::getVarName, pred -> pred)); Multimap<RoleType, Var> roleMap = getRoleVarMap(); roleMap.entries().forEach(e -> { RoleType role = e.getKey(); Var var = e.getValue(); roleConceptIdMap.put(role, varSubMap.containsKey(var) ? varSubMap.get(var).getPredicateValue() : ""); }); } return roleConceptIdMap; }
From source file:com.qcadoo.mes.materialFlowResources.service.ResourceManagementServiceImpl.java
public Multimap<Long, BigDecimal> getQuantitiesInWarehouse(final Entity warehouse, Multimap<Entity, Entity> productsAndPositions) { Multimap<Long, BigDecimal> result = ArrayListMultimap.create(); String algorithm = warehouse.getStringField(LocationFieldsMFR.ALGORITHM); for (Map.Entry<Entity, Entity> productAndPosition : productsAndPositions.entries()) { Entity resource = productAndPosition.getValue().getBelongsToField(PositionFields.RESOURCE); if (algorithm.equalsIgnoreCase(WarehouseAlgorithm.MANUAL.getStringValue()) && resource != null) { result.put(productAndPosition.getKey().getId(), resource.getDecimalField(ResourceFields.QUANTITY)); } else {/*from w w w.j a v a2s. com*/ List<Entity> resources = dataDefinitionService .get(MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER, MaterialFlowResourcesConstants.MODEL_RESOURCE) .find().add(SearchRestrictions.belongsTo(ResourceFields.LOCATION, warehouse)) .add(SearchRestrictions.belongsTo(ResourceFields.PRODUCT, productAndPosition.getKey())) .list().getEntities(); if (result.containsKey(productAndPosition.getKey().getId())) { BigDecimal currentQuantity = result.get(productAndPosition.getKey().getId()).stream() .reduce(BigDecimal.ZERO, BigDecimal::add); result.put(productAndPosition.getKey().getId(), (resources.stream().map(res -> res.getDecimalField(ResourceFields.QUANTITY)) .reduce(BigDecimal.ZERO, BigDecimal::add)).add(currentQuantity)); } else { result.put(productAndPosition.getKey().getId(), resources.stream().map(res -> res.getDecimalField(ResourceFields.QUANTITY)) .reduce(BigDecimal.ZERO, BigDecimal::add)); } } } return result; }
From source file:com.palantir.atlasdb.keyvalue.impl.StatsTrackingKeyValueService.java
@Override public void putWithTimestamps(String tableName, Multimap<Cell, Value> values) { TableStats s = getTableStats(tableName); long start = System.currentTimeMillis(); super.putWithTimestamps(tableName, values); long finish = System.currentTimeMillis(); s.totalPutMillis.addAndGet(finish - start); s.totalPutCalls.incrementAndGet();//from w ww. j a va 2s. com // Only update stats after put was successful. s.totalPutCells.addAndGet(values.size()); for (Entry<Cell, Value> e : values.entries()) { s.totalPutCellBytes.addAndGet(e.getKey().getRowName().length); s.totalPutCellBytes.addAndGet(e.getKey().getColumnName().length); s.totalPutValueBytes.addAndGet(e.getValue().getContents().length); } }
From source file:org.sosy_lab.cpachecker.cfa.postprocessing.global.singleloop.CFASingleLoopTransformation.java
/** * Connects the nodes leaving a subgraph to the loop head using assignment * edges setting the program counter to the value required for reaching the * correct successor in the next loop iteration. * * @param pLoopHead the loop head.//from w w w.j a v a2 s . c om * @param pNewPredecessorsToPC the nodes that represent gates for leaving * their subgraph mapped to the program counter values corresponding to the * correct successor states. * @param pPCIdExpression the CIdExpression used for the program counter variable. */ private static void connectSubgraphLeavingNodesToLoopHead(CFANode pLoopHead, Multimap<Integer, CFANode> pNewPredecessorsToPC, CIdExpression pPCIdExpression) { Map<Integer, CFANode> connectionNodes = new HashMap<>(); for (Map.Entry<Integer, CFANode> newPredecessorToPC : pNewPredecessorsToPC.entries()) { int pcToSet = newPredecessorToPC.getKey(); CFANode connectionNode = connectionNodes.get(pcToSet); if (connectionNode == null) { connectionNode = new CFANode(ARTIFICIAL_PROGRAM_COUNTER_FUNCTION_NAME); connectionNodes.put(pcToSet, connectionNode); CFAEdge edgeToLoopHead = createProgramCounterAssignmentEdge(connectionNode, pLoopHead, pPCIdExpression, pcToSet); addToNodes(edgeToLoopHead); } CFANode subgraphPredecessor = newPredecessorToPC.getValue(); CFAEdge dummyEdge = new BlankEdge("", FileLocation.DUMMY, subgraphPredecessor, connectionNode, ""); addToNodes(dummyEdge); } }
From source file:ai.grakn.graql.internal.query.QueryAnswer.java
@Override public Answer unify(Unifier unifier) { if (unifier.isEmpty()) return this; Answer unified = new QueryAnswer(); Multimap<Var, Concept> answerMultimap = HashMultimap.create(); this.entrySet().forEach(e -> { Var var = e.getKey(); Collection<Var> uvars = unifier.get(var); if (uvars.isEmpty()) { answerMultimap.put(var, e.getValue()); } else {/*from ww w .ja v a2s . c om*/ uvars.forEach(uv -> answerMultimap.put(uv, e.getValue())); } }); //non-ambiguous mapping if (answerMultimap.keySet().size() == answerMultimap.values().size()) { answerMultimap.entries().forEach(e -> unified.put(e.getKey(), e.getValue())); } return unified.setExplanation(this.getExplanation()); }
From source file:net.myrrix.online.eval.ReconstructionEvaluator.java
public EvaluationResult evaluate(File originalDataDir) throws TasteException, IOException, InterruptedException { Preconditions.checkArgument(originalDataDir.exists() && originalDataDir.isDirectory(), "%s is not a directory", originalDataDir); File tempDir = Files.createTempDir(); ServerRecommender recommender = null; try {//from w w w .j a v a 2 s .c o m Multimap<Long, RecommendedItem> data; try { data = readAndCopyDataFiles(originalDataDir, tempDir); } catch (IOException ioe) { throw new TasteException(ioe); } recommender = new ServerRecommender(tempDir); recommender.await(); Generation generation = recommender.getGenerationManager().getCurrentGeneration(); FastByIDMap<float[]> X = generation.getX(); FastByIDMap<float[]> Y = generation.getY(); Mean averageError = new Mean(); // Only compute average over existing entries... for (Map.Entry<Long, RecommendedItem> entry : data.entries()) { long userID = entry.getKey(); long itemID = entry.getValue().getItemID(); // Each of which was a "1" in the factor P matrix double value = SimpleVectorMath.dot(X.get(userID), Y.get(itemID)); // So store abs(1-value), except, don't penalize for reconstructing > 1. Error is 0 in this case. averageError.increment(FastMath.max(0.0, 1.0 - value)); } return new EvaluationResultImpl(averageError.getResult()); } finally { recommender.close(); IOUtils.deleteRecursively(tempDir); } }
From source file:org.apache.twill.internal.zookeeper.DefaultZKClientService.java
/** * Creates a deep copy of the given authInfos multimap. *//* www . j a v a 2 s . c o m*/ private Multimap<String, byte[]> copyAuthInfo(Multimap<String, byte[]> authInfos) { Multimap<String, byte[]> result = ArrayListMultimap.create(); for (Map.Entry<String, byte[]> entry : authInfos.entries()) { byte[] info = entry.getValue(); result.put(entry.getKey(), info == null ? null : Arrays.copyOf(info, info.length)); } return result; }