Example usage for com.google.common.collect BiMap get

List of usage examples for com.google.common.collect BiMap get

Introduction

In this page you can find the example usage for com.google.common.collect BiMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:org.jpmml.evaluator.ClusteringModelEvaluator.java

private ClusterClassificationMap evaluateSimilarity(ComparisonMeasure comparisonMeasure,
        List<ClusteringField> clusteringFields, List<FieldValue> values) {
    ClusteringModel clusteringModel = getModel();

    ClusterClassificationMap result = new ClusterClassificationMap(ClassificationMap.Type.SIMILARITY);

    BitSet flags = MeasureUtil.toBitSet(values);

    BiMap<Cluster, String> inverseEntities = (getEntityRegistry()).inverse();

    List<Cluster> clusters = clusteringModel.getClusters();
    for (Cluster cluster : clusters) {
        BitSet clusterFlags = CacheUtil.getValue(cluster, ClusteringModelEvaluator.clusterFlagCache);

        if (flags.size() != clusterFlags.size()) {
            throw new InvalidFeatureException(cluster);
        }/* ww  w  . ja  va2  s  .co  m*/

        String id = inverseEntities.get(cluster);

        Double similarity = MeasureUtil.evaluateSimilarity(comparisonMeasure, clusteringFields, flags,
                clusterFlags);

        result.put(cluster, id, similarity);
    }

    return result;
}

From source file:org.invenzzia.opentrans.visitons.network.Track.java

/**
 * Imports the junctions from the given list of records.
 * //  w  ww .  j  a v a2s  . c om
 * @param records List of junction records.
 * @param world World instance used for finding the actual entity.
 */
public void importJunctions(List<JunctionRecord> records, BiMap<Long, Long> vertexMapping, World world) {
    if (records.isEmpty()) {
        this.junctions = ImmutableList.of();
    }
    Junction juncs[] = new Junction[records.size()];
    int i = 0;
    for (JunctionRecord jr : records) {
        long theId = jr.getId();
        if (vertexMapping.containsKey(theId)) {
            theId = vertexMapping.get(theId);
        }
        IVertex vertex = world.findVertex(theId);
        if (!(vertex instanceof Junction)) {
            throw new IllegalStateException("The vertex #" + theId + " was expected to be a junction.");
        }
        juncs[i++] = (Junction) vertex;
    }
    this.junctions = ImmutableList.copyOf(juncs);
}

From source file:org.jpmml.evaluator.ClusteringModelEvaluator.java

private ClusterClassificationMap evaluateDistance(ComparisonMeasure comparisonMeasure,
        List<ClusteringField> clusteringFields, List<FieldValue> values) {
    ClusteringModel clusteringModel = getModel();

    ClusterClassificationMap result = new ClusterClassificationMap(ClassificationMap.Type.DISTANCE);

    Double adjustment;//from   w w  w  .j a  v a  2  s  .c o  m

    MissingValueWeights missingValueWeights = clusteringModel.getMissingValueWeights();
    if (missingValueWeights != null) {
        Array array = missingValueWeights.getArray();

        List<Double> adjustmentValues = ArrayUtil.getRealContent(array);
        if (values.size() != adjustmentValues.size()) {
            throw new InvalidFeatureException(missingValueWeights);
        }

        adjustment = MeasureUtil.calculateAdjustment(values, adjustmentValues);
    } else

    {
        adjustment = MeasureUtil.calculateAdjustment(values);
    }

    BiMap<Cluster, String> inverseEntities = (getEntityRegistry()).inverse();

    List<Cluster> clusters = clusteringModel.getClusters();
    for (Cluster cluster : clusters) {
        List<FieldValue> clusterValues = CacheUtil.getValue(cluster,
                ClusteringModelEvaluator.clusterValueCache);

        if (values.size() != clusterValues.size()) {
            throw new InvalidFeatureException(cluster);
        }

        String id = inverseEntities.get(cluster);

        Double distance = MeasureUtil.evaluateDistance(comparisonMeasure, clusteringFields, values,
                clusterValues, adjustment);

        result.put(cluster, id, distance);
    }

    return result;
}

From source file:net.automatalib.serialization.etf.writer.Mealy2ETFWriterIO.java

private <S, T> void writeETFInternal(PrintWriter pw, MealyMachine<S, I, T, O> mealy, Alphabet<I> inputs) {
    final StateIDs<S> stateIDs = mealy.stateIDs();

    // write the initial state
    pw.println("begin init");
    pw.printf("%d%n", stateIDs.getStateId(mealy.getInitialState()));
    pw.println("end init");

    // write the state ids
    pw.println("begin sort id");
    mealy.getStates().forEach(s -> pw.printf("\"%s\"%n", s));
    pw.println("end sort");

    // create a new bi-map that contains indices for the output alphabet
    final BiMap<O, Integer> outputIndices = HashBiMap.create();

    // write the transitions
    pw.println("begin trans");
    for (S s : mealy.getStates()) {
        for (I i : inputs) {
            final T t = mealy.getTransition(s, i);
            if (t != null) {
                final O o = mealy.getTransitionOutput(t);
                outputIndices.computeIfAbsent(o, ii -> outputIndices.size());
                final S n = mealy.getSuccessor(t);
                pw.printf("%s/%s %d %d%n", stateIDs.getStateId(s), stateIDs.getStateId(n),
                        inputs.getSymbolIndex(i), outputIndices.get(o));
            }/*from   w  w  w .  j a va 2s.c  o  m*/
        }
    }
    pw.println("end trans");

    // write the letters in the input alphabet
    pw.println("begin sort input");
    inputs.forEach(i -> pw.printf("\"%s\"%n", i));
    pw.println("end sort");

    // write the letters in the output alphabet
    pw.println("begin sort output");
    for (int i = 0; i < outputIndices.size(); i++) {
        pw.printf("\"%s\"%n", outputIndices.inverse().get(i));
    }
    pw.println("end sort");
}

From source file:de.lemo.dms.processing.questions.QCourseUserPaths.java

@SuppressWarnings("unchecked")
@POST/*w  w w  .  j  a va 2  s  .co m*/
public JSONObject compute(@FormParam(MetaParam.COURSE_IDS) final List<Long> courses,
        @FormParam(MetaParam.START_TIME) final Long startTime, @FormParam(MetaParam.END_TIME) Long endTime,
        @FormParam(MetaParam.GENDER) List<Long> gender) throws JSONException {

    validateTimestamps(startTime, endTime);

    final Stopwatch stopWatch = new Stopwatch();
    stopWatch.start();

    final IDBHandler dbHandler = ServerConfiguration.getInstance().getMiningDbHandler();
    final Session session = dbHandler.getMiningSession();

    Criteria criteria;
    List<Long> users = new ArrayList<Long>(StudentHelper.getCourseStudentsAliasKeys(courses, gender).values());

    criteria = session.createCriteria(ILogMining.class, "log").add(Restrictions.in("log.course.id", courses))
            .add(Restrictions.between("log.timestamp", startTime, endTime))
            .add(Restrictions.eq("log.action", "view"));
    if (!users.isEmpty()) {
        criteria.add(Restrictions.in("log.user.id", users));
    } else {
        this.logger.debug("No users found for courses. Returning empty JSONObject.");
        return new JSONObject();
    }

    final List<ILogMining> logs = criteria.list();

    this.logger.debug("Found " + users.size() + " actions. " + +stopWatch.elapsedTime(TimeUnit.SECONDS));

    long courseCount = 0;
    final BiMap<CourseMining, Long> courseNodePositions = HashBiMap.create();
    final Map<Long/* user id */, List<Long/* course id */>> userPaths = Maps.newHashMap();

    this.logger.debug("Paths fetched: " + logs.size() + ". " + stopWatch.elapsedTime(TimeUnit.SECONDS));

    Map<Long, Long> idToAlias = StudentHelper.getCourseStudentsRealKeys(courses, gender);

    for (final ILogMining log : logs) {

        final CourseMining course = log.getCourse();
        Long nodeID = courseNodePositions.get(course);
        if (nodeID == null) {
            nodeID = courseCount++;
            courseNodePositions.put(course, nodeID);
        }

        final long userId = idToAlias.get(log.getUser().getId());

        List<Long> nodeIDs = userPaths.get(userId);
        if (nodeIDs == null) {
            nodeIDs = Lists.newArrayList();
            userPaths.put(userId, nodeIDs);
        }
        nodeIDs.add(nodeID);
    }

    this.logger.debug("userPaths: " + userPaths.size());

    final Map<Long /* node id */, List<UserPathLink>> coursePaths = Maps.newHashMap();

    for (final Entry<Long, List<Long>> userEntry : userPaths.entrySet()) {

        UserPathLink lastLink = null;

        for (final Long nodeID : userEntry.getValue()) {
            List<UserPathLink> links = coursePaths.get(nodeID);
            if (links == null) {
                links = Lists.newArrayList();
                coursePaths.put(nodeID, links);
            }
            final UserPathLink link = new UserPathLink(String.valueOf(nodeID), "0");
            links.add(link);

            if (lastLink != null) {
                lastLink.setTarget(String.valueOf(nodeID));
            }
            lastLink = link;
        }
    }
    stopWatch.stop();
    this.logger.debug("coursePaths: " + coursePaths.size());
    this.logger.debug("Total Fetched log entries: " + (logs.size() + logs.size()) + " log entries."
            + stopWatch.elapsedTime(TimeUnit.SECONDS));

    final Set<UserPathLink> links = Sets.newHashSet();

    final JSONObject result = new JSONObject();
    final JSONArray nodes = new JSONArray();
    final JSONArray edges = new JSONArray();

    for (final Entry<Long, List<UserPathLink>> courseEntry : coursePaths.entrySet()) {
        final JSONObject node = new JSONObject();
        node.put("name", courseNodePositions.inverse().get(courseEntry.getKey()).getTitle());
        node.put("value", courseEntry.getValue().size());
        node.put("group", courses.contains(courseNodePositions.inverse().get(courseEntry.getKey())) ? 1 : 2);
        nodes.put(node);

        for (final UserPathLink edge : courseEntry.getValue()) {
            if (edge.getTarget() == edge.getSource()) {
                continue;
            }
            links.add(edge);
        }
    }

    for (final UserPathLink link : links) {
        final JSONObject edgeJSON = new JSONObject();
        edgeJSON.put("target", link.getTarget());
        edgeJSON.put("source", link.getSource());
        edges.put(edgeJSON);
    }

    this.logger.debug("Nodes: " + nodes.length() + ", Links: " + edges.length() + "   / time: "
            + stopWatch.elapsedTime(TimeUnit.SECONDS));

    result.put("nodes", nodes);
    result.put("links", edges);
    session.close();
    return result;
}

From source file:org.gbif.common.search.builder.SolrQueryBuilder.java

/**
 * Sets the query filters./*w w  w .ja  va 2 s .co  m*/
 * Takes a {@link Multimap} and produces a Solr filter query containing the filtering criteria.
 * The output string will be in the format: (param1:vp1.1 OR param1:vp1.2) AND (param2:vf2.1 OR param2:vp2.2)...
 * The param-i key are taken from the key sets of the map and the vpi.j (value j of param i) are the entry set of the
 * map.
 * 
 * @return the String containing a Solr filter query
 */
private void setQueryFilter(final SearchRequest<P> searchRequest, SolrQuery solrQuery) {
    final Multimap<P, String> params = searchRequest.getParameters();
    final boolean isFacetedRequest = FacetedSearchRequest.class.isAssignableFrom(searchRequest.getClass());
    if (params != null) {
        BiMap<P, String> fieldsPropertiesMapInv = facetFieldsPropertiesMap.inverse();
        for (P param : params.keySet()) {
            if (param != null && !fieldsPropertiesMapInv.containsKey(param)) {
                LOG.warn("Unknown search parameter {}", param);
                continue;
            }
            // solr field for this parameter
            final String solrFieldName = fieldsPropertiesMapInv.get(param);

            List<String> filterQueriesComponents = Lists.newArrayList();
            for (String paramValue : params.get(param)) {
                // Negate expression is removed if it is present
                final String interpretedValue = getInterpretedValue(param.type(), removeNegation(paramValue));
                final String queryComponent = PARAMS_JOINER.join(solrFieldName, interpretedValue);

                filterQueriesComponents.add(isNegated(paramValue) ? NOT_OP + queryComponent : queryComponent);
            }
            if (!filterQueriesComponents.isEmpty()) { // there are filter queries for this parameter
                StringBuilder filterQuery = buildFilterQuery(isFacetedRequest, solrFieldName,
                        filterQueriesComponents);
                solrQuery.addFilterQuery(filterQuery.toString());
            }

        }
    }
}

From source file:org.eclipse.emf.compare.match.update.Updater.java

private void fixReference(EObject obj, EReference ref, BiMap<EObject, EObject> matches) {
    if (ref.isMany()) {
        EList<EObject> values = getManyEObjects(obj, ref);
        // Update remaining references to the reference model to point to
        // the equivalent element in the updated model.
        for (int i = 0; i < values.size(); i++) {
            EObject value = values.get(i);
            if (matches.containsKey(value)) {
                values.set(i, matches.get(value));
            }//from w  ww .j  a va2s  .  co  m
        }
        // Remove references to orphaned elements.
        for (Iterator<EObject> iter = values.iterator(); iter.hasNext(); /**/) {
            EObject eObject = iter.next();
            if (orphaned.contains(eObject)) {
                iter.remove();
            }
        }
    } else {
        Object value = obj.eGet(ref);
        if (matches.containsKey(value)) {
            obj.eSet(ref, matches.get(value));
        } else if (orphaned.contains(value)) {
            obj.eUnset(ref);
        }
    }
}

From source file:org.apache.hadoop.security.ShellBasedIdMapping.java

/**
 * Get the list of users or groups returned by the specified command,
 * and save them in the corresponding map.
 * @throws IOException /*from   w  ww .  j  av a 2  s  . c o m*/
 */
@VisibleForTesting
public static boolean updateMapInternal(BiMap<Integer, String> map, String mapName, String command,
        String regex, Map<Integer, Integer> staticMapping) throws IOException {
    boolean updated = false;
    BufferedReader br = null;
    try {
        Process process = Runtime.getRuntime().exec(new String[] { "bash", "-c", command });
        br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
        String line = null;
        while ((line = br.readLine()) != null) {
            String[] nameId = line.split(regex);
            if ((nameId == null) || (nameId.length != 2)) {
                throw new IOException("Can't parse " + mapName + " list entry:" + line);
            }
            LOG.debug("add to " + mapName + "map:" + nameId[0] + " id:" + nameId[1]);
            // HDFS can't differentiate duplicate names with simple authentication
            final Integer key = staticMapping.get(parseId(nameId[1]));
            final String value = nameId[0];
            if (map.containsKey(key)) {
                final String prevValue = map.get(key);
                if (value.equals(prevValue)) {
                    // silently ignore equivalent entries
                    continue;
                }
                reportDuplicateEntry("Got multiple names associated with the same id: ", key, value, key,
                        prevValue);
                continue;
            }
            if (map.containsValue(value)) {
                final Integer prevKey = map.inverse().get(value);
                reportDuplicateEntry("Got multiple ids associated with the same name: ", key, value, prevKey,
                        value);
                continue;
            }
            map.put(key, value);
            updated = true;
        }
        LOG.debug("Updated " + mapName + " map size: " + map.size());

    } catch (IOException e) {
        LOG.error("Can't update " + mapName + " map");
        throw e;
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e1) {
                LOG.error("Can't close BufferedReader of command result", e1);
            }
        }
    }
    return updated;
}

From source file:com.mycelium.wapi.wallet.bip44.Bip44Account.java

public List<Address> getAllAddresses() {
    List<Address> addresses = new ArrayList<Address>();

    //get all used external plus the next unused
    BiMap<Integer, Address> external = _externalAddresses.inverse();
    Integer externalIndex = _context.getLastExternalIndexWithActivity() + 1;
    for (Integer i = 0; i <= externalIndex; i++) {
        addresses.add(external.get(i));
    }//from   ww  w  . j ava2s. co  m

    //get all used internal
    BiMap<Integer, Address> internal = _internalAddresses.inverse();
    Integer internalIndex = _context.getLastInternalIndexWithActivity();
    for (Integer i = 0; i <= internalIndex; i++) {
        addresses.add(internal.get(i));
    }

    return addresses;
}

From source file:ca.wumbo.wdl.database.LogEventSubmitter.java

/**
 * Adds all the data to insert into the database into the statement in a
 * batch format such that at the end of everything, the commands can all
 * be sent as one.//from w  ww.j a v a 2s .  c  o  m
 * 
 * @param rp
 *       The stat round parser to extract events from.
 * 
 * @param idToPlayerMap
 *       A map of id to player names that will be used for matching log
 *       names to a player. 
 * 
 * @param roundId
 *       The round ID of the event data.
 * 
 * @param redTeamId
 *       The ID of the red team.
 * 
 * @throws SQLException
 *       If there is any exception calling the query or the database fails
 *       to create the necessary rows.
 */
private void pushEventsBatch(RoundParser rp, BiMap<Integer, String> idToPlayerMap, int roundId, int redTeamId,
        int blueTeamId) throws SQLException {
    assert rp != null;
    assert idToPlayerMap != null;
    assert idToPlayerMap.size() > 0;
    assert roundId >= 0;
    assert redTeamId >= 0;
    assert blueTeamId >= 0;

    try (Statement stmt = connection.createStatement()) {
        int eventLogId = -1;

        // Put in the header and remember the event log ID.
        String query = rp.getHeaderData().getSqlInsertionQuery("wdl", "event_logs", roundId, redTeamId,
                blueTeamId);
        log.trace(">>> {}", query);
        stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
        ResultSet rs = stmt.getGeneratedKeys();
        if (!rs.next()) {
            throw new SQLException(
                    "Unexpected end of result set, should have gotten back the key for the event log ID.");
        }
        eventLogId = rs.getInt(1);
        log.trace("Event log ID retrieved: {}", eventLogId);
        if (eventLogId == -1) {
            throw new SQLException("Commit did not yield an event log.");
        }

        // Everything from now on in can go into a single batch command.
        // Put in the players.
        log.debug("Inserting players into event player table.");
        BiMap<String, Integer> playerToIdMap = idToPlayerMap.inverse();
        log.trace("PlayerToIdMap = {}", playerToIdMap.toString());
        for (Player player : rp.getPlayers()) {
            // Getting the player ID shouldn't fail because we've checked
            // previously to make sure the player name and ID are valid.
            String playerLogName = player.getName();
            int playerId = playerToIdMap.get(playerLogName);
            int colorNumber = player.getTeam().ordinal();
            String insertQuery = String.format("INSERT INTO `%s`.`%s`(%s) VALUES(%d, %d, \"%s\", %d)", "wdl",
                    "event_players", "fk_event_log_id, fk_player_id, player_log_name, color_number", eventLogId,
                    playerId, playerLogName, colorNumber);
            log.trace(">>> {}", insertQuery);
            stmt.addBatch(insertQuery);
        }
        log.debug("Committing player queries...");
        stmt.executeBatch();
        log.debug("Committed player batch events.");

        // Put in the events.
        log.debug("Inserting events into event table.");
        for (Event e : rp.getEvents()) {
            String queryStr = e.getSqlInsertionQuery("wdl", "events", idToPlayerMap.inverse(), eventLogId);
            log.trace(">>> {}", queryStr);
            stmt.addBatch(queryStr);
        }

        // Everything is in, deploy it now.
        log.debug("Committing event queries...");
        stmt.executeBatch();
        log.debug("All event query events done.");
    }
}