Example usage for com.google.common.base Functions forMap

List of usage examples for com.google.common.base Functions forMap

Introduction

In this page you can find the example usage for com.google.common.base Functions forMap.

Prototype

public static <K, V> Function<K, V> forMap(Map<K, V> map) 

Source Link

Document

Returns a function which performs a map lookup.

Usage

From source file:org.caleydo.vis.lineup.internal.ui.CatFilterDalog.java

public CatFilterDalog(Shell parentShell, String title, Object receiver, Map<CATEGORY_TYPE, ?> categories,
        Set<CATEGORY_TYPE> selection, IFilterColumnMixin model, boolean hasSnapshots, Point loc,
        boolean filterNA, String labelNA) {
    this(parentShell, title, receiver, categories.keySet(), Functions.forMap(categories), selection, model,
            hasSnapshots, loc, filterNA, labelNA);
}

From source file:com.facebook.buck.util.FakeProcessExecutor.java

public FakeProcessExecutor(Map<ProcessExecutorParams, FakeProcess> processMap, Console console) {
    this(Functions.forMap(processMap), console);
}

From source file:com.facebook.buck.io.file.PathListing.java

/**
 * Lists paths in descending modified time order, excluding any paths which bring the number of
 * files over {@code maxNumPaths} or over {@code totalSizeFilter} bytes in size.
 */// w  ww.  jav  a  2 s  . c  o m
public static ImmutableSortedSet<Path> listMatchingPathsWithFilters(Path pathToGlob, String globPattern,
        PathModifiedTimeFetcher pathModifiedTimeFetcher, FilterMode filterMode, OptionalInt maxPathsFilter,
        Optional<Long> totalSizeFilter) throws IOException {

    // Fetch the modification time of each path and build a map of
    // (path => modification time) pairs.
    ImmutableMap.Builder<Path, FileTime> pathFileTimesBuilder = ImmutableMap.builder();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(pathToGlob, globPattern)) {
        for (Path path : stream) {
            try {
                pathFileTimesBuilder.put(path, pathModifiedTimeFetcher.getLastModifiedTime(path));
            } catch (NoSuchFileException e) {
                // Ignore the path.
                continue;
            }
        }
    }
    ImmutableMap<Path, FileTime> pathFileTimes = pathFileTimesBuilder.build();

    ImmutableSortedSet<Path> paths = ImmutableSortedSet.copyOf(Ordering.natural()
            // Order the keys of the map (the paths) by their values (the file modification
            // times).
            .onResultOf(Functions.forMap(pathFileTimes))
            // If two keys of the map have the same value, fall back to key order.
            .compound(Ordering.natural())
            // Use descending order.
            .reverse(), pathFileTimes.keySet());

    paths = applyNumPathsFilter(paths, filterMode, maxPathsFilter);
    paths = applyTotalSizeFilter(paths, filterMode, totalSizeFilter);
    return paths;
}

From source file:com.facebook.buck.io.PathListing.java

/**
 * Lists paths in descending modified time order,
 * excluding any paths which bring the number of files over {@code maxNumPaths}
 * or over {@code totalSizeFilter} bytes in size.
 *///from  www  .ja va  2 s .  co  m
public static ImmutableSortedSet<Path> listMatchingPathsWithFilters(Path pathToGlob, String globPattern,
        PathModifiedTimeFetcher pathModifiedTimeFetcher, FilterMode filterMode,
        Optional<Integer> maxPathsFilter, Optional<Long> totalSizeFilter) throws IOException {

    // Fetch the modification time of each path and build a map of
    // (path => modification time) pairs.
    ImmutableMap.Builder<Path, FileTime> pathFileTimesBuilder = ImmutableMap.builder();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(pathToGlob, globPattern)) {
        for (Path path : stream) {
            try {
                pathFileTimesBuilder.put(path, pathModifiedTimeFetcher.getLastModifiedTime(path));
            } catch (NoSuchFileException e) {
                // Ignore the path.
                continue;
            }
        }
    }
    ImmutableMap<Path, FileTime> pathFileTimes = pathFileTimesBuilder.build();

    ImmutableSortedSet<Path> paths = ImmutableSortedSet.copyOf(Ordering.natural()
            // Order the keys of the map (the paths) by their values (the file modification times).
            .onResultOf(Functions.forMap(pathFileTimes))
            // If two keys of the map have the same value, fall back to key order.
            .compound(Ordering.natural())
            // Use descending order.
            .reverse(), pathFileTimes.keySet());

    paths = applyNumPathsFilter(paths, filterMode, maxPathsFilter);
    paths = applyTotalSizeFilter(paths, filterMode, totalSizeFilter);
    return paths;
}

From source file:org.jclouds.virtualbox.functions.admin.ImageFromYamlStream.java

@Override
public LoadingCache<String, Image> apply(InputStream source) {

    Constructor constructor = new Constructor(Config.class);

    TypeDescription imageDesc = new TypeDescription(YamlImage.class);
    imageDesc.putListPropertyType("images", String.class);
    constructor.addTypeDescription(imageDesc);

    Yaml yaml = new Yaml(new Loader(constructor));
    Config config = (Config) yaml.load(source);
    checkState(config != null, "missing config: class");
    checkState(config.images != null, "missing images: collection");

    Map<String, Image> backingMap = Maps.uniqueIndex(Iterables.transform(config.images, YamlImage.toImage),
            new Function<Image, String>() {
                public String apply(Image image) {
                    return image.getId();
                }//ww  w .j  a  v a 2 s.  c o m
            });
    LoadingCache<String, Image> cache = CacheBuilder.newBuilder()
            .build(CacheLoader.from(Functions.forMap(backingMap)));
    for (String node : backingMap.keySet())
        cache.getUnchecked(node);
    return cache;
}

From source file:com.isotrol.impe3.core.engine.BinaryRenderingEngine.java

private Function<CIP, RenderContext> rc(final Ok result) {
    Map<CIP, RenderContext> map = Maps.newHashMap();
    for (CIPResult cr : result.getCips().values()) {
        map.put(cr.getCip(), RequestContexts.render(cr.getContext(), null, result.getQuery()));
    }//from  www . j a  v a2 s  .co m
    return Functions.forMap(map);
}

From source file:edu.uci.ics.jung.samples.UnicodeLabelDemo.java

public UnicodeLabelDemo() {

    // create a simple graph for the demo
    graph = new DirectedSparseGraph<Integer, Number>();
    Integer[] v = createVertices(10);
    createEdges(v);//from w w  w  .  j av  a  2s.c om
    Map<Integer, Icon> iconMap = new HashMap<Integer, Icon>();

    vv = new VisualizationViewer<Integer, Number>(new FRLayout<Integer, Number>(graph));
    vv.getRenderContext().setVertexLabelTransformer(new UnicodeVertexStringer<Integer>(v));
    vv.getRenderContext().setVertexLabelRenderer(new DefaultVertexLabelRenderer(Color.cyan));
    vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.cyan));
    VertexIconShapeTransformer<Integer> vertexIconShapeFunction = new VertexIconShapeTransformer<Integer>(
            new EllipseVertexShapeTransformer<Integer>());
    Function<Integer, Icon> vertexIconFunction = Functions.forMap(iconMap);
    vv.getRenderContext().setVertexShapeTransformer(vertexIconShapeFunction);
    vv.getRenderContext().setVertexIconTransformer(vertexIconFunction);
    loadImages(v, iconMap);
    vertexIconShapeFunction.setIconMap(iconMap);
    vv.getRenderContext().setVertexFillPaintTransformer(
            new PickableVertexPaintTransformer<Integer>(vv.getPickedVertexState(), Color.white, Color.yellow));
    vv.getRenderContext().setEdgeDrawPaintTransformer(
            new PickableEdgePaintTransformer<Number>(vv.getPickedEdgeState(), Color.black, Color.lightGray));

    vv.setBackground(Color.white);

    // add my listener for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller());

    // create a frome to hold the graph
    final JFrame frame = new JFrame();
    Container content = frame.getContentPane();
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    content.add(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final DefaultModalGraphMouse<Integer, Number> gm = new DefaultModalGraphMouse<Integer, Number>();
    vv.setGraphMouse(gm);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JCheckBox lo = new JCheckBox("Show Labels");
    lo.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            showLabels = e.getStateChange() == ItemEvent.SELECTED;
            vv.repaint();
        }
    });
    lo.setSelected(true);

    JPanel controls = new JPanel();
    controls.add(plus);
    controls.add(minus);
    controls.add(lo);
    controls.add(gm.getModeComboBox());
    content.add(controls, BorderLayout.SOUTH);

    frame.pack();
    frame.setVisible(true);
}

From source file:gr.demokritos.iit.cru.creativity.reasoning.semantic.CompetitiveThinkingSpaces.java

public static ArrayList<String> CompetitiveThinkingSpaces(String story, int noOfClusters, String language)
        throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException,
        IOException, Exception {

    ArrayList<String> tokensList = new ArrayList<String>();
    Connect c = new Connect(language);
    InfoSummarization inf = new InfoSummarization(c);
    LinkedHashMap<ArrayList<String>, Double> temp = inf.TopTerms(story, true);
    for (ArrayList<String> stems : temp.keySet()) {
        for (int j = 0; j < stems.size(); j++) {
            //for every stem, put each of its corresponding terms to tagCloud with the stem's tf 
            tokensList.add(stems.get(j).split("\\{")[0] + ";" + temp.get(stems));
        }//from  www  .  j a  v  a2s.c om
    }
    c.CloseConnection();

    //String clusters = properties.getProperty("clusters");
    ArrayList<String> clustersList = new ArrayList<String>();
    KeyphraseClustering kc = new KeyphraseClustering(tokensList, noOfClusters, language);
    Connect m = new Connect(language);
    clustersList = kc.getClusters();
    int dom = 0;
    for (int i = 0; i < clustersList.size(); i++) {
        if (clustersList.get(i).split(";").length > tokensList.size() / 2) {
            dom = i;
        }
    }
    String[] words = clustersList.get(dom)
            .subSequence(clustersList.get(dom).indexOf(";") + 1, clustersList.get(dom).length()).toString()
            .split(";");//keep the rest of the words in the big cluster
    clustersList.set(dom, clustersList.get(dom).split(";")[0] + ";");//first cluster is its first word
    int noWords = (words.length + clustersList.size()) / clustersList.size();
    HashMap<String, Double> tags = new HashMap<String, Double>();
    for (String s : words) {//for all the candidate words
        for (int i = 0; i < clustersList.size(); i++) {
            tags.put(s + "-" + i, m.getDistance(s, clustersList.get(i).split(";")[0]));//semlev(words, clustersList));//store their difference between the words and each of the clusters

        }
    }
    Comparator<String> valueComparator = Ordering.natural().onResultOf(Functions.forMap(tags))
            .compound(Ordering.natural());
    ImmutableSortedMap<String, Double> es = ImmutableSortedMap.copyOf(tags, valueComparator);

    ArrayList<String> examined = new ArrayList<String>();
    ///sort tags ascending with guava
    for (String o : es.keySet()) {
        String[] g = o.split("-");
        int pointer = Integer.parseInt(g[1]);
        if (clustersList.get(pointer).split(";").length > noWords || examined.contains(g[0])) {
            ///if the cluster has already as much words as it should have, 
            //or if the word has already been stored into a cluster
            continue; //continue with the next minimum difference in the list
        }
        examined.add(g[0]);
        clustersList.set(pointer, clustersList.get(pointer) + g[0] + ";");
    }

    if (examined.size() < words.length) {// if some words have not been set to clusters
        //put them in the first cluster
        for (String h : words) {
            if (!examined.contains(h)) {
                clustersList.set(0, clustersList.get(0) + h + ";");
            }
        }
    }
    m.CloseConnection();
    return clustersList;
}

From source file:de.tuberlin.uebb.jdae.llmsl.specials.LinearGlobalEquation.java

@Override
public BlockEquation bind(final Map<GlobalVariable, BlockVariable> blockCtxt) {
    final List<BlockVariable> bvars = Lists.transform(variables, Functions.forMap(blockCtxt));

    return new BlockEquation() {

        @Override//  ww w .  j a  v  a 2 s.com
        public TDNumber exec(ExecutionContext m) {
            TDNumber ret = m.time().mult(time);
            for (int i = 0; i < bvars.size(); i++)
                ret = ret.add(bvars.get(i).load(m).mult(coefficients[i]));

            return ret.subtract(constant);
        }

    };
}

From source file:com.spotify.cassandra.opstools.DynamicSnitchDumper.java

private static Map<InetAddress, Double> sortMap(Map<InetAddress, Double> scores) {
    return ImmutableSortedMap.copyOf(scores,
            Ordering.natural().onResultOf(Functions.forMap(scores)).compound(new Comparator<InetAddress>() {
                @Override//from   w w  w.ja  v  a2  s . co  m
                public int compare(InetAddress o1, InetAddress o2) {
                    return o1.toString().compareTo(o2.toString());
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            }));
}