Java Code Examples for java.util.PriorityQueue

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Jetwick, under directory /src/test/java/de/jetwick/data/.

Source file: JTagTest.java

  21 
vote

@Test public void testColllection(){
  Set<JTag> set=new LinkedHashSet<JTag>();
  set.add(new JTag("Test"));
  set.add(new JTag("Test2"));
  assertEquals(2,set.size());
  PriorityQueue q=new PriorityQueue<JTag>();
  q.add(new JTag("test"));
  q.add(new JTag("pest"));
  assertEquals(2,q.size());
  assertNotNull(q.poll());
  assertNotNull(q.poll());
  assertNull(q.poll());
  set=new TreeSet<JTag>();
  set.add(new JTag("Test"));
  set.add(new JTag("Test2"));
  assertEquals(1,set.size());
}
 

Example 2

From project droolsjbpm-integration, under directory /drools-simulator/src/main/java/org/drools/simulation/impl/.

Source file: Simulator.java

  20 
vote

public Simulator(Simulation simulation,long startTime){
  this.ksessions=new HashSet<StatefulKnowledgeSession>();
  this.startTime=startTime;
  this.simulation=(SimulationImpl)simulation;
  this.root=new ContextImpl(ROOT,this);
  this.root.set("simulator",this);
  this.contexts=new HashMap<String,Context>();
  this.contexts.put(ROOT,this.root);
  Map<String,SimulationPath> paths=this.simulation.getPaths();
  int capacity=0;
  for (  SimulationPath path : paths.values()) {
    this.contexts.put(path.getName(),new ContextImpl(path.getName(),this,root));
    capacity+=path.getSteps().size();
  }
  if (capacity == 0) {
    return;
  }
  this.queue=new PriorityQueue(capacity,new Comparator<SimulationStep>(){
    public int compare(    SimulationStep s1,    SimulationStep s2){
      return (int)(s1.getDistanceMillis() - s2.getDistanceMillis());
    }
  }
);
  for (  SimulationPath path : paths.values()) {
    for (    SimulationStep step : path.getSteps())     this.queue.add(step);
  }
}
 

Example 3

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/Help/.

Source file: HelpList.java

  19 
vote

/** 
 * Process all help to check get only the command that the player have access
 * @param sender
 */
private void checkPermissions(final CommandSender sender){
  if (lastCommandSender != null && sender.equals(lastCommandSender)) {
    return;
  }
  lastHelpEntries=new PriorityQueue<HelpEntry>(initSize,new EntryCommandComparator());
  lastCommandSender=sender;
  for (  final HelpEntry he : pluginHelp) {
    if (he.hasPerm(sender)) {
      lastHelpEntries.add(he);
    }
  }
}
 

Example 4

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/ai/desires/.

Source file: DesireQueue.java

  19 
vote

/** 
 * Adds desire to the queue. <p/> <p/> When adding object this method checks first for the same object by  {@link AbstractDesire#equals(Object)}, if such object found, next actions will be done:<br> <br> 1). Remove old desire instance from the list.<br> 2). Check if those desires are same instances by "==".<br> 3). If they are not the same instances, add desire power from old instance to new instance, if they are - do nothing.<br> <br> After all add new desire instance to the list.
 * @param desire desire instance to add
 */
public synchronized void addDesire(Desire desire){
  if (queue == null) {
    queue=new PriorityQueue<Desire>();
  }
  Iterator<Desire> iterator=queue.iterator();
  while (iterator.hasNext()) {
    Desire iterated=iterator.next();
    if (desire.equals(iterated)) {
      iterator.remove();
      if (desire != iterated) {
        desire.increaseDesirePower(iterated.getDesirePower());
      }
      break;
    }
  }
  queue.add(desire);
}
 

Example 5

From project AlgorithmsNYC, under directory /SlidingPuzzle/src/com/oti/solutions/sam/.

Source file: SASolver.java

  19 
vote

private void createNewLeaf(PriorityQueue<FrontierLeaf> frontierSet,FrontierLeaf currLeaf,Evalue currEvalue,byte action,BigInteger newState){
  FrontierLeaf newLeaf=new FrontierLeaf();
  newLeaf.cost=currLeaf.cost + 1;
  newLeaf.value=newLeaf.cost + m_hFunc.distanceToArrival(newState);
  newLeaf.state=newState;
  newLeaf.prevAction=action;
  newLeaf.previous=currEvalue;
  frontierSet.add(newLeaf);
}
 

Example 6

From project android-cropimage, under directory /src/com/android/camera/gallery/.

Source file: ImageListUber.java

  19 
vote

public ImageListUber(IImageList[] sublist,int sort){
  mSubList=sublist.clone();
  mQueue=new PriorityQueue<MergeSlot>(4,sort == ImageManager.SORT_ASCENDING ? new AscendingComparator() : new DescendingComparator());
  mSkipList=new long[16];
  mSkipListSize=0;
  mSkipCounts=new int[mSubList.length];
  mLastListIndex=-1;
  mQueue.clear();
  for (int i=0, n=mSubList.length; i < n; ++i) {
    IImageList list=mSubList[i];
    MergeSlot slot=new MergeSlot(list,i);
    if (slot.next())     mQueue.add(slot);
  }
}
 

Example 7

From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.

Source file: MemoryRunner.java

  19 
vote

StateWrapper(int c,boolean f,CardWrap cw,PriorityQueue<CardWrap> q,ArrayList<Integer> a){
  savCount=c;
  savFront=f;
  savWrap=cw;
  savQ=q;
  savAvail=a;
}
 

Example 8

From project android_packages_apps_Gallery, under directory /src/com/android/camera/gallery/.

Source file: ImageListUber.java

  19 
vote

public ImageListUber(IImageList[] sublist,int sort){
  mSubList=sublist.clone();
  mQueue=new PriorityQueue<MergeSlot>(4,sort == ImageManager.SORT_ASCENDING ? new AscendingComparator() : new DescendingComparator());
  mSkipList=new long[16];
  mSkipListSize=0;
  mSkipCounts=new int[mSubList.length];
  mLastListIndex=-1;
  mQueue.clear();
  for (int i=0, n=mSubList.length; i < n; ++i) {
    IImageList list=mSubList[i];
    MergeSlot slot=new MergeSlot(list,i);
    if (slot.next())     mQueue.add(slot);
  }
}
 

Example 9

From project Battlepath, under directory /src/engine/.

Source file: Pathplanner.java

  19 
vote

/** 
 * Plans a path from a start wold position to a goal world position
 * @param start start position
 * @param goal goal position
 * @return list of needed moves go from start to goal
 */
public ArrayList<Vector2D> plan(Vector2D start,Vector2D goal){
  Tile tile=field.tileAt(goal);
  if (tile == null)   return null;
  if (tile.getValue() == 1)   return null;
  fChecks=new Field(field.getTilesX(),field.getTilesY(),"");
  fringe=new PriorityQueue<Node>();
  nodes=new HashMap<Integer,Node>();
  fringe.add(new Node(null,start,h(start,goal)));
  Node success=astar(goal);
  if (success != null)   return success.getPath();
 else   return null;
}
 

Example 10

From project cascading, under directory /src/core/cascading/cascade/planner/.

Source file: FlowGraph.java

  19 
vote

public TopologicalOrderIterator<Flow,Integer> getTopologicalIterator(){
  return new TopologicalOrderIterator<Flow,Integer>(this,new PriorityQueue<Flow>(10,new Comparator<Flow>(){
    @Override public int compare(    Flow lhs,    Flow rhs){
      return Integer.valueOf(lhs.getSubmitPriority()).compareTo(rhs.getSubmitPriority());
    }
  }
));
}
 

Example 11

From project cipango, under directory /cipango-util/src/test/java/org/cipango/util/.

Source file: TimerTaskTest.java

  19 
vote

@Test public void testOrder(){
  PriorityQueue<TimerTask> queue=new PriorityQueue<TimerTask>();
  Random random=new Random();
  for (int i=0; i < 10; i++) {
    queue.offer(new TimerTask(null,Math.abs(random.nextLong())));
  }
  long time=-1;
  while (!queue.isEmpty()) {
    TimerTask task=queue.poll();
    assertTrue(task.getExecutionTime() >= time);
    time=task.getExecutionTime();
  }
}
 

Example 12

From project Cloud9, under directory /src/dist/edu/umd/cloud9/example/pagerank/.

Source file: SequentialPageRank.java

  19 
vote

public static void main(String[] args) throws IOException {
  if (args.length != 2) {
    System.err.println("usage: SequentialPageRage [graph-adjacency-list] [random-jump-factor]");
    System.exit(-1);
  }
  String infile=args[0];
  float alpha=Float.parseFloat(args[1]);
  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();
  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);
  PageRank<String,Integer> ranker=new PageRank<String,Integer>(graph,alpha);
  ranker.evaluate();
  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));
  }
  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());
  }
}
 

Example 13

From project Codeable_Objects, under directory /codeableObjects/src/com/algorithm/.

Source file: VoronoiGenerator.java

  19 
vote

public void getEdges(Vector<CompPoint> _points,DoublyConnectedEdgeList border,int width,int height,DoublyConnectedEdgeList _faces,DoublyConnectedEdgeList diagram){
  this.initPoints=Geom.removeDuplicateVerts(_points);
  this.border=border;
  this.width=width;
  this.height=height;
  root=null;
  this.dcEdgeList=diagram;
  this.faces=_faces;
  eventQueue=new PriorityQueue<VorEvent>(initPoints.size(),new VorEventSorter());
  for (int i=0; i < initPoints.size(); i++) {
    CompPoint point=initPoints.get(i);
    VorEvent e1=new VorEvent(point,"site");
    eventQueue.add(e1);
  }
  while (eventQueue.size() > 0) {
    VorEvent currentEvent=eventQueue.poll();
    ly=currentEvent.point.getY();
    if (currentEvent.type == "site") {
      handleSiteEvent(currentEvent.point);
    }
    if (currentEvent.type == "circle") {
      handleCircleEvent(currentEvent);
    }
  }
  finishEdge(root);
  cleanEdges();
}
 

Example 14

From project commons-compress, under directory /src/main/java/org/apache/commons/compress/archivers/dump/.

Source file: DumpArchiveInputStream.java

  19 
vote

/** 
 * Constructor.
 * @param is
 * @throws ArchiveException
 */
public DumpArchiveInputStream(InputStream is) throws ArchiveException {
  this.raw=new TapeInputStream(is);
  this.hasHitEOF=false;
  try {
    byte[] headerBytes=raw.readRecord();
    if (!DumpArchiveUtil.verify(headerBytes)) {
      throw new UnrecognizedFormatException();
    }
    summary=new DumpArchiveSummary(headerBytes);
    raw.resetBlockSize(summary.getNTRec(),summary.isCompressed());
    blockBuffer=new byte[4 * DumpArchiveConstants.TP_SIZE];
    readCLRI();
    readBITS();
  }
 catch (  IOException ex) {
    throw new ArchiveException(ex.getMessage(),ex);
  }
  Dirent root=new Dirent(2,2,4,".");
  names.put(Integer.valueOf(2),root);
  queue=new PriorityQueue<DumpArchiveEntry>(10,new Comparator<DumpArchiveEntry>(){
    public int compare(    DumpArchiveEntry p,    DumpArchiveEntry q){
      if ((p.getOriginalName() == null) || (q.getOriginalName() == null)) {
        return Integer.MAX_VALUE;
      }
      return p.getOriginalName().compareTo(q.getOriginalName());
    }
  }
);
}
 

Example 15

From project crammer, under directory /src/main/java/uk/ac/ebi/ena/sra/compression/huffman/.

Source file: HuffmanCode.java

  19 
vote

@Deprecated public static <T>HuffmanTree<T> buildTreeUsingPriorityQueue(int[] charFreqs,T[] values){
  PriorityQueue<HuffmanTree<T>> queue=new PriorityQueue<HuffmanTree<T>>();
  for (int i=0; i < charFreqs.length; i++)   if (charFreqs[i] > 0)   queue.offer(new HuffmanLeaf<T>(charFreqs[i],values[i]));
  while (queue.size() > 1) {
    HuffmanTree<T> a=queue.poll();
    HuffmanTree<T> b=queue.poll();
    queue.offer(new HuffmanNode<T>(a,b));
  }
  return queue.poll();
}
 

Example 16

From project crunch, under directory /crunch/src/main/java/org/apache/crunch/lib/.

Source file: Aggregate.java

  19 
vote

@Override public void process(Pair<Integer,Iterable<Pair<K,V>>> input,Emitter<Pair<Integer,Pair<K,V>>> emitter){
  Comparator<Pair<K,V>> cmp=new PairValueComparator<K,V>(maximize);
  PriorityQueue<Pair<K,V>> queue=new PriorityQueue<Pair<K,V>>(limit,cmp);
  for (  Pair<K,V> pair : input.second()) {
    queue.add(pair);
    if (queue.size() > limit) {
      queue.poll();
    }
  }
  List<Pair<K,V>> values=Lists.newArrayList(queue);
  Collections.sort(values,cmp);
  for (int i=values.size() - 1; i >= 0; i--) {
    emitter.emit(Pair.of(0,values.get(i)));
  }
}
 

Example 17

From project datafu, under directory /src/java/datafu/pig/bags/sets/.

Source file: SetIntersect.java

  19 
vote

private PriorityQueue<pair> load_bags(Tuple input) throws IOException {
  PriorityQueue<pair> pq=new PriorityQueue<pair>(input.size());
  for (int i=0; i < input.size(); i++) {
    Object o=input.get(i);
    if (!(o instanceof DataBag))     throw new RuntimeException("parameters must be databags");
    DataBag inputBag=(DataBag)o;
    pq.add(new pair(inputBag.iterator()));
  }
  return pq;
}
 

Example 18

From project drools-chance, under directory /drools-chance-core/src/test/java/org/drools/chance/kbase/.

Source file: AbstractChanceTest.java

  19 
vote

public String reportWMObjects(StatefulKnowledgeSession session){
  PriorityQueue<String> queue=new PriorityQueue<String>();
  for (  FactHandle fh : session.getFactHandles()) {
    Object o;
    if (fh instanceof EventFactHandle) {
      EventFactHandle efh=(EventFactHandle)fh;
      queue.add("\t " + efh.getStartTimestamp() + "\t"+ efh.getObject().toString()+ "\n");
    }
 else {
      o=((DefaultFactHandle)fh).getObject();
      queue.add("\t " + o.toString() + "\n");
    }
  }
  String ans=" ---------------- WM " + session.getObjects().size() + " --------------\n";
  while (!queue.isEmpty()) {
    Object o=queue.poll();
    ans+=o;
  }
  ans+=" ---------------- END WM -----------\n";
  return ans;
}
 

Example 19

From project drools-semantics, under directory /src/test/java/org/drools/semantics/lang/dl/.

Source file: AbstractReasonerTestBase.java

  19 
vote

public String reportWMObjects(StatefulKnowledgeSession session){
  PriorityQueue<String> queue=new PriorityQueue<String>();
  for (  FactHandle fh : session.getFactHandles()) {
    Object o;
    if (fh instanceof EventFactHandle) {
      EventFactHandle efh=(EventFactHandle)fh;
      queue.add("\t " + efh.getStartTimestamp() + "\t"+ efh.getObject().toString()+ "\n");
    }
 else {
      o=((DefaultFactHandle)fh).getObject();
      queue.add("\t " + o.toString() + "\n");
    }
  }
  String ans=" ---------------- WM " + session.getObjects().size() + " --------------\n";
  while (!queue.isEmpty())   ans+=queue.poll();
  ans+=" ---------------- END WM -----------\n";
  return ans;
}
 

Example 20

From project elasticsearch-analysis-combo, under directory /src/main/java/org/apache/lucene/analysis/.

Source file: ComboTokenStream.java

  19 
vote

public ComboTokenStream(TokenStream... tokenStreams){
  this.positionedTokenStreams=new PositionedTokenStream[tokenStreams.length];
  for (int i=tokenStreams.length - 1; i >= 0; --i) {
    if (tokenStreams[i] == null)     continue;
    this.positionedTokenStreams[i]=new PositionedTokenStream(tokenStreams[i]);
    Iterator<Class<? extends Attribute>> iterator=this.positionedTokenStreams[i].getAttributeClassesIterator();
    while (iterator.hasNext()) {
      super.addAttribute(iterator.next());
    }
  }
  this.lastPosition=0;
  this.readQueue=new PriorityQueue<PositionedTokenStream>(tokenStreams.length);
  readQueueResetted=false;
}
 

Example 21

From project erjang, under directory /src/main/java/erjang/driver/tcp_inet/.

Source file: TCPINet.java

  19 
vote

private MultiTimerData add_multi_timer(EPID caller,long timeout){
  MultiTimerData mtd=new MultiTimerData();
  mtd.when=System.currentTimeMillis() + timeout;
  mtd.caller=caller;
  if (this.mtd_queue == null) {
    this.mtd_queue=new PriorityQueue<MultiTimerData>();
  }
  this.mtd_queue.add(mtd);
  if (this.mtd_queue.peek() == mtd) {
    if (this.mtd_queue.size() > 1) {
      driver_cancel_timer();
    }
    driver_set_timer(timeout);
  }
  return mtd;
}
 

Example 22

From project floodlight, under directory /src/main/java/net/floodlightcontroller/topology/.

Source file: TopologyInstance.java

  19 
vote

protected BroadcastTree dijkstra(Cluster c,Long root,Map<Link,Integer> linkCost,boolean isDstRooted){
  HashMap<Long,Link> nexthoplinks=new HashMap<Long,Link>();
  HashMap<Long,Integer> cost=new HashMap<Long,Integer>();
  int w;
  for (  Long node : c.links.keySet()) {
    nexthoplinks.put(node,null);
    cost.put(node,MAX_PATH_WEIGHT);
  }
  HashMap<Long,Boolean> seen=new HashMap<Long,Boolean>();
  PriorityQueue<NodeDist> nodeq=new PriorityQueue<NodeDist>();
  nodeq.add(new NodeDist(root,0));
  cost.put(root,0);
  while (nodeq.peek() != null) {
    NodeDist n=nodeq.poll();
    Long cnode=n.getNode();
    int cdist=n.getDist();
    if (cdist >= MAX_PATH_WEIGHT)     break;
    if (seen.containsKey(cnode))     continue;
    seen.put(cnode,true);
    for (    Link link : c.links.get(cnode)) {
      Long neighbor;
      if (isDstRooted == true)       neighbor=link.getSrc();
 else       neighbor=link.getDst();
      if (linkCost == null || linkCost.get(link) == null)       w=1;
 else       w=linkCost.get(link);
      int ndist=cdist + w;
      if (ndist < cost.get(neighbor)) {
        cost.put(neighbor,ndist);
        nexthoplinks.put(neighbor,link);
        nodeq.add(new NodeDist(neighbor,ndist));
      }
    }
  }
  BroadcastTree ret=new BroadcastTree(nexthoplinks,cost);
  return ret;
}
 

Example 23

From project flume, under directory /flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/.

Source file: ReplayHandler.java

  19 
vote

ReplayHandler(FlumeEventQueue queue,@Nullable KeyProvider encryptionKeyProvider){
  this.queue=queue;
  this.lastCheckpoint=queue.getLogWriteOrderID();
  pendingTakes=Lists.newArrayList();
  readers=Maps.newHashMap();
  logRecordBuffer=new PriorityQueue<LogRecord>();
  this.encryptionKeyProvider=encryptionKeyProvider;
}
 

Example 24

From project FML, under directory /common/cpw/mods/fml/common/registry/.

Source file: TickRegistry.java

  19 
vote

public static void updateTickQueue(List<IScheduledTickHandler> ticks,Side side){
synchronized (ticks) {
    ticks.clear();
    long tick=getCounter(side).incrementAndGet();
    PriorityQueue<TickQueueElement> tickHandlers=getQueue(side);
    while (true) {
      if (tickHandlers.size() == 0 || !tickHandlers.peek().scheduledNow(tick)) {
        break;
      }
      TickRegistry.TickQueueElement tickQueueElement=tickHandlers.poll();
      tickQueueElement.update(tick);
      tickHandlers.offer(tickQueueElement);
      ticks.add(tickQueueElement.ticker);
    }
  }
}
 

Example 25

From project gecko, under directory /src/test/java/com/taobao/gecko/core/nio/impl/.

Source file: PriorityQueuePerformanceTest.java

  19 
vote

public static void main(String[] args){
  final int count=10000000;
  final PriorityQueue<TimerRef> queue=new PriorityQueue<TimerRef>();
  final Random rand=new Random();
  long start=System.currentTimeMillis();
  for (int i=0; i < count; i++) {
    int timeout=rand.nextInt(10000);
    TimerRef e=new TimerRef(timeout,null);
    e.setTimeoutTimestamp(System.currentTimeMillis() + timeout);
    queue.offer(e);
  }
  System.out.println("insert rate:" + count * 1000L / (System.currentTimeMillis() - start));
  int miss=0;
  start=System.currentTimeMillis();
  for (int i=0; i < count; i++) {
    queue.poll();
  }
  System.out.println("poll rate:" + count * 1000L / (System.currentTimeMillis() - start));
  System.out.println(miss);
}
 

Example 26

From project genobyte, under directory /genobyte/src/main/java/org/obiba/bitwise/query/sort/.

Source file: SortedQueryResult.java

  19 
vote

/** 
 * Sorts the <link>QueryResult</link> according to the contents of <code>sortFields_</code>.  This method will initialze the <code>sorted_</code> field. 
 */
private void sort(){
  PriorityQueue<SortNode> sorted=new PriorityQueue<SortNode>(result_.count());
  for (int i=result_.next(0); i != -1; i=result_.next(i + 1)) {
    SortNode node=new SortNode(i);
    sorted.add(node);
  }
  int index=0;
  sorted_=new int[result_.count()];
  while (sorted.size() > 0) {
    sorted_[index++]=sorted.remove().recordIndex_;
  }
}
 

Example 27

From project gridland, under directory /agents/agents/.

Source file: LocalMap.java

  19 
vote

public List<Node> getOldestNodes(int count){
  PriorityQueue<Node> queue=new PriorityQueue<Node>();
  for (  Node n : nodes.values()) {
    if (n.body == 0) {
      queue.offer(n);
      if (queue.size() > count)       queue.poll();
    }
  }
  return new Vector<Node>(queue);
}
 

Example 28

From project grouperfish, under directory /tools/display/src/main/java/com/mozilla/grouperfish/mahout/clustering/display/lda/.

Source file: DisplayLDATopics.java

  19 
vote

public static void printTopics(Map<Integer,PriorityQueue<Pair<Double,String>>> topicQueues){
  System.out.println("LDA numTopics=" + topicQueues.size());
  for (  Map.Entry<Integer,PriorityQueue<Pair<Double,String>>> entry : topicQueues.entrySet()) {
    System.out.println();
    int topic=entry.getKey();
    System.out.println("===== Topic " + topic + " =====");
    List<Pair<Double,String>> topKWords=new ArrayList<Pair<Double,String>>(entry.getValue());
    Collections.sort(topKWords,Collections.reverseOrder());
    int rank=1;
    for (    Pair<Double,String> p : topKWords) {
      String feature=p.getSecond();
      double score=p.getFirst();
      System.out.println(rank++ + " - " + feature+ " [p("+ feature+ "|topic_"+ topic+ ") = "+ score+ "]");
    }
    System.out.println();
  }
}
 

Example 29

From project gs-algo, under directory /src/org/graphstream/algorithm/.

Source file: BetweennessCentrality.java

  19 
vote

/** 
 * Compute the betweenness centrality on the given graph for each node and eventually edges. This method is equivalent to a call in sequence to the two methods  {@link #init(Graph)} then {@link #compute()}.
 */
public void betweennessCentrality(Graph graph){
  init(graph);
  initAllNodes(graph);
  initAllEdges(graph);
  float n=graph.getNodeCount();
  float i=0;
  for (  Node s : graph) {
    PriorityQueue<Node> S=null;
    if (unweighted)     S=simpleExplore(s,graph);
 else     S=dijkstraExplore2(s,graph);
    while (!S.isEmpty()) {
      Node w=S.poll();
      for (      Node v : predecessorsOf(w)) {
        double c=((sigma(v) / sigma(w)) * (1.0 + delta(w)));
        if (doEdges) {
          Edge e=w.getEdgeBetween(v);
          setCentrality(e,centrality(e) + c);
        }
        setDelta(v,delta(v) + c);
      }
      if (w != s) {
        setCentrality(w,centrality(w) + delta(w));
      }
    }
    if (progress != null)     progress.progress(i / n);
    i++;
  }
}
 

Example 30

From project hbasene, under directory /src/main/java/org/hbasene/index/search/.

Source file: HBaseTopFieldCollector.java

  19 
vote

public HBaseTopFieldCollector(final HTablePool tablePool,final String indexName,final int nDocs,final Sort sort){
  this.tablePool=tablePool;
  this.indexName=indexName;
  this.nDocs=nDocs;
  this.fields=sort.getSort();
  this.pendingDocs=0;
  this.totalHits=0;
  this.pq=new PriorityQueue<SortFieldDoc>(nDocs,this.fields[0].getReverse() ? DESCENDING_COMPARATOR : ASCENDING_COMPARATOR);
  if (fields.length > 1) {
    throw new IllegalArgumentException("Multiple fields not supported yet ");
  }
}
 

Example 31

From project indextank-engine, under directory /src/main/java/com/flaptor/indextank/storage/.

Source file: LogOptimizer.java

  19 
vote

public LogOptimizer(LogCleaner cleaner,LogDealer dealer,LogRoot root){
  this.cleaner=cleaner;
  this.dealer=dealer;
  this.root=root;
  this.queue=new PriorityQueue<String>(1000,new Comparator<String>(){
    @Override public int compare(    String code1,    String code2){
      Score s1=scores.get(code1), s2=scores.get(code2);
      int c=s1.priority - s2.priority;
      if (c == 0)       c=Float.compare(s2.score,s1.score);
      return c;
    }
  }
);
}
 

Example 32

From project Ivory_1, under directory /src/java/main/ivory/core/data/index/.

Source file: PostingsListDocSortedPositional.java

  19 
vote

public static void mergeList(PostingsList newPostings,List<PostingsList> list,int nCollDocs){
  Preconditions.checkNotNull(list);
  int nLists=list.size();
  ivory.core.data.index.PostingsReader[] reader=new PostingsReader[nLists];
  Posting[] posting=new Posting[nLists];
  TermPositions[] tp=new TermPositions[nLists];
  PriorityQueue<DocList> heap=new PriorityQueue<DocList>(nLists,comparator);
  int totalPostings=0;
  int i=0;
  for (  PostingsList pl : list) {
    pl.setCollectionDocumentCount(nCollDocs);
    totalPostings+=pl.getNumberOfPostings();
    reader[i]=pl.getPostingsReader();
    posting[i]=new Posting();
    reader[i].nextPosting(posting[i]);
    tp[i]=new TermPositions();
    reader[i].getPositions(tp[i]);
    heap.add(new DocList(posting[i].getDocno(),i));
    i++;
  }
  newPostings.setCollectionDocumentCount(nCollDocs);
  newPostings.setNumberOfPostings(totalPostings);
  DocList dl;
  while (heap.size() > 0) {
    dl=heap.remove();
    i=dl.listIndex;
    newPostings.add(dl.id,posting[i].getTf(),tp[i]);
    if (reader[i].nextPosting(posting[i])) {
      reader[i].getPositions(tp[i]);
      dl.set(posting[i].getDocno(),i);
      heap.add(dl);
    }
  }
}
 

Example 33

From project jena-tdb, under directory /src/main/java/org/apache/jena/tdb/store/bulkloader3/.

Source file: MultiThreadedSortedDataBag.java

  19 
vote

public SpillSortIterator(List<Iterator<T>> inputs,Comparator<? super T> comp){
  this.inputs=inputs;
  this.comp=comp;
  this.minHeap=new PriorityQueue<Item<T>>(inputs.size());
  for (int i=0; i < inputs.size(); i++) {
    replaceItem(i);
  }
}
 

Example 34

From project joshua, under directory /src/joshua/decoder/chart_parser/.

Source file: Cell.java

  19 
vote

public Cell(Chart chart,int goalSymID){
  this.chart=chart;
  this.goalSymID=goalSymID;
  if (JoshuaConfiguration.useBeamAndThresholdPrune) {
    PriorityQueue<HGNode> nodesHeap=new PriorityQueue<HGNode>(1,HGNode.logPComparator);
    beamPruner=new BeamPruner<HGNode>(nodesHeap,JoshuaConfiguration.relative_threshold,JoshuaConfiguration.max_n_items);
  }
}
 

Example 35

From project jpropel-light, under directory /src/propel/core/collections/lists/.

Source file: SortedList.java

  19 
vote

/** 
 * Returns an ordered copy of elements. Note: The other toArray(T[]) method does not return ordered elements. This is an O(n) operation.
 */
@SuppressWarnings("unchecked") @Override public T[] toArray(){
  int size=size();
  T[] result=(T[])Array.newInstance(getGenericTypeParameter(),size);
  PriorityQueue<T> copy;
  if (comparator() != null)   copy=new PriorityQueue<T>(size,comparator());
 else   copy=new PriorityQueue<T>(size);
  copy.addAll(Linq.toList(super.toArray(result)));
  for (int i=0; i < result.length; i++)   result[i]=copy.remove();
  return result;
}
 

Example 36

From project knn, under directory /src/main/java/org/apache/mahout/knn/search/.

Source file: Brute.java

  19 
vote

/** 
 * Searches for N neighbors of a single vector.
 * @param v The vector query to search for.
 * @param n The number of neighbors.
 * @return A list of neighbors ordered closest first.
 */
public List<WeightedVector> search(Vector v,int n){
  final PriorityQueue<WeightedVector> results=searchInternal(v,reference,n,new PriorityQueue<WeightedVector>(n,Ordering.natural().reverse()));
  final List<WeightedVector> r=Lists.newArrayList(results);
  Collections.sort(r);
  return r;
}
 

Example 37

From project leveldb, under directory /leveldb/src/main/java/org/iq80/leveldb/util/.

Source file: Level0Iterator.java

  19 
vote

public Level0Iterator(TableCache tableCache,List<FileMetaData> files,Comparator<InternalKey> comparator){
  Builder<InternalTableIterator> builder=ImmutableList.builder();
  for (  FileMetaData file : files) {
    builder.add(tableCache.newIterator(file));
  }
  this.inputs=builder.build();
  this.comparator=comparator;
  this.priorityQueue=new PriorityQueue<ComparableIterator>(Iterables.size(inputs) + 1);
  resetPriorityQueue(comparator);
}
 

Example 38

From project ManelSim, under directory /src/main/java/core/.

Source file: EventSourceMultiplexer.java

  19 
vote

public EventSourceMultiplexer(EventSource[] eventSources){
  this.eventSources=new PushBackEventSource[eventSources.length];
  this.generatedEventsQueue=new PriorityQueue<Event>();
  for (int i=0; i < eventSources.length; i++) {
    this.eventSources[i]=new PushBackEventSource(eventSources[i]);
  }
}
 

Example 39

From project mawLib, under directory /src/mxj/trunk/smsLib-mxj/src/org/smslib/.

Source file: Service.java

  19 
vote

protected void initializeService(){
  this.startMillis=System.currentTimeMillis();
  listSystemInformation();
  this.gatewayList=new ArrayList<AGateway>();
  this.reorderMessageQueue=new PriorityQueue<OutboundMessage>(50,new Comparator<OutboundMessage>(){
    public int compare(    OutboundMessage x,    OutboundMessage y){
      int comp=x.getPriority() - y.getPriority();
      if (comp == 0)       comp=x.getDate().compareTo(y.getDate());
      return comp;
    }
  }
);
  setRouter(new Router(this));
  setLoadBalancer(new RoundRobinLoadBalancer(this));
}
 

Example 40

From project onebusaway-uk, under directory /onebusaway-uk-network-rail-gtfs-realtime/src/main/java/org/onebusaway/uk/network_rail/gtfs_realtime/graph/.

Source file: PositionBerthToStanoxGraphMain.java

  19 
vote

private Map<Location,Integer> getNearbyNodesWithLocation(Map<RawBerthNode,Location> nodesToLocations,RawBerthNode source,int minCount){
  Map<Location,Integer> locationsAndTime=new HashMap<Location,Integer>();
  PriorityQueue<OrderedNode> queue=new PriorityQueue<OrderedNode>();
  queue.add(new OrderedNode(source,0));
  Set<RawBerthNode> visited=new HashSet<RawBerthNode>();
  visited.add(source);
  Map<RawBerthNode,Integer> minTimeToSource=new HashMap<RawBerthNode,Integer>();
  while (!queue.isEmpty()) {
    OrderedNode orderedNode=queue.poll();
    RawBerthNode node=orderedNode.node;
    if (minTimeToSource.containsKey(node)) {
      continue;
    }
    int time=orderedNode.value;
    minTimeToSource.put(node,time);
    if (nodesToLocations.containsKey(node)) {
      locationsAndTime.put(nodesToLocations.get(node),time);
      if (locationsAndTime.size() >= minCount) {
        return locationsAndTime;
      }
    }
    for (    Edge edge : node.getEdges()) {
      RawBerthNode to=edge.getTo();
      int proposedTime=edge.getAverageDuration() + time;
      if (!minTimeToSource.containsKey(to)) {
        queue.add(new OrderedNode(to,proposedTime));
      }
    }
  }
  return locationsAndTime;
}
 

Example 41

From project OpenTripPlanner, under directory /opentripplanner-utils/src/test/java/org/opentripplanner/common/pqueue/.

Source file: TestPQueues.java

  19 
vote

public void testCompareHeaps() throws InterruptedException {
  List<Integer> input, expected;
  input=new ArrayList<Integer>(N);
  for (int i=0; i < N; i++)   input.add((int)(Math.random() * 10000));
  System.out.println("\ninsert/extract " + N + " Integers "+ INNER_ITER+ " times");
  expected=new ArrayList<Integer>(N);
  PriorityQueue<Integer> q=new PriorityQueue<Integer>(N);
  for (  Integer j : input)   q.add(j);
  while (!q.isEmpty())   expected.add(q.remove());
  System.out.println(q.getClass() + " (expected results)");
  for (int i=0; i < ITER; i++) {
    for (    OTPPriorityQueue<Integer> queue : makeQueues()) {
      doQueue(queue,input,expected);
    }
  }
  System.out.println("\nmaintain queue at size " + N);
  for (  OTPPriorityQueue<Integer> queue : makeQueues()) {
    fillQueue(queue,input);
  }
}
 

Example 42

From project org.openscada.atlantis, under directory /org.openscada.da.datasource.formula/src/org/openscada/da/datasource/formula/.

Source file: FormulaDataSource.java

  19 
vote

private void setScript(final ConfigurationDataHelper cfg) throws ScriptException {
  String engine=cfg.getString("engine",DEFAULT_ENGINE_NAME);
  if (engine.isEmpty()) {
    engine=DEFAULT_ENGINE_NAME;
  }
  this.scriptContext=new SimpleScriptContext();
  this.scriptEngine=this.manager.getEngineByName(engine);
  if (this.scriptEngine == null) {
    throw new IllegalArgumentException(String.format("'%s' is not a valid script engine",engine));
  }
  final Queue<InitCode> init=new PriorityQueue<FormulaDataSource.InitCode>();
  for (  final Map.Entry<String,String> entry : cfg.getPrefixed("init.").entrySet()) {
    init.add(new InitCode(Integer.valueOf(entry.getKey()),entry.getValue()));
  }
  while (!init.isEmpty()) {
    final InitCode entry=init.poll();
    logger.debug("Initializing #{}",entry.getOrder());
    this.scriptEngine.eval(entry.getCode(),this.scriptContext);
  }
  this.inputFormula=cfg.getString("inputFormula");
  this.outputFormula=cfg.getString("outputFormula");
  this.inputScript=null;
  this.outputScript=null;
  if (this.scriptEngine instanceof Compilable && this.precompile) {
    logger.debug("Using precompiled scripts");
    final Compilable compilable=(Compilable)this.scriptEngine;
    if (this.inputFormula != null && this.inputFormula.isEmpty()) {
      this.inputScript=compilable.compile(this.inputFormula);
    }
    if (this.outputFormula != null && this.outputFormula.isEmpty()) {
      this.outputScript=compilable.compile(this.outputFormula);
    }
  }
}
 

Example 43

From project osiris, under directory /src/osiris/game/model/.

Source file: Player.java

  19 
vote

/** 
 * Gets the items kept on death.
 * @return the items kept on death
 */
public ArrayList<Item> getItemsKeptOnDeath(){
  PriorityQueue<Item> allItems=new PriorityQueue<Item>(1,new Comparator<Item>(){
    @Override public int compare(    Item a,    Item b){
      int difference=ItemDef.forId(b.getId()).getPrice() - ItemDef.forId(a.getId()).getPrice();
      return difference;
    }
  }
);
  Item[] items=new Item[equipment.getLength() + inventory.getLength()];
  System.arraycopy(equipment.getItems(),0,items,0,equipment.getLength());
  System.arraycopy(inventory.getItems(),0,items,equipment.getLength(),inventory.getLength());
  for (  Item item : items) {
    if (item == null)     continue;
    if (ItemDef.forId(item.getId()).isTradeable())     allItems.offer(Item.create(item.getId()));
  }
  ArrayList<Item> keptItems=new ArrayList<Item>();
  int itemsKept=3;
  PrayerEffect salvage=getPrayers().get(Prayer.Type.SALVAGE);
  if (salvage != null)   itemsKept+=1;
  while (keptItems.size() < itemsKept && allItems.size() > 0) {
    keptItems.add(allItems.poll());
  }
  return keptItems;
}
 

Example 44

From project parasim, under directory /extensions/visualisation-plot-impl/src/main/java/org/sybila/parasim/visualisation/plot/impl/layer/.

Source file: NeighbourhoodTransformer.java

  19 
vote

protected NeighbourhoodTransformer(Float[][] target,int xSize,int ySize,Comparator<T> comparator){
  this.target=target;
  this.xSize=xSize;
  this.ySize=ySize;
  cmp=comparator;
  unprocessed=new PriorityQueue<Target<T>>(11,new Comparator<Target<T>>(){
    public int compare(    Target<T> t,    Target<T> t1){
      return cmp.compare(t.getNeighbourhood(),t1.getNeighbourhood());
    }
  }
);
}
 

Example 45

From project platform_packages_apps_Gallery, under directory /src/com/android/camera/gallery/.

Source file: ImageListUber.java

  19 
vote

public ImageListUber(IImageList[] sublist,int sort){
  mSubList=sublist.clone();
  mQueue=new PriorityQueue<MergeSlot>(4,sort == ImageManager.SORT_ASCENDING ? new AscendingComparator() : new DescendingComparator());
  mSkipList=new long[16];
  mSkipListSize=0;
  mSkipCounts=new int[mSubList.length];
  mLastListIndex=-1;
  mQueue.clear();
  for (int i=0, n=mSubList.length; i < n; ++i) {
    IImageList list=mSubList[i];
    MergeSlot slot=new MergeSlot(list,i);
    if (slot.next())     mQueue.add(slot);
  }
}
 

Example 46

From project PocketMonstersOnline, under directory /Server/src/org/pokenet/server/backend/.

Source file: MovementManager.java

  19 
vote

/** 
 * Default constructor.
 */
public MovementManager(){
  m_comp=new Comparator<Char>(){
    public int compare(    Char arg0,    Char arg1){
      return arg0.getPriority() - arg1.getPriority();
    }
  }
;
  m_waiting=new PriorityQueue<Char>(11,m_comp);
  m_moved=new PriorityQueue<Char>(1,m_comp);
}
 

Example 47

From project QuickSnap, under directory /Camera/src/com/lightbox/android/camera/gallery/.

Source file: ImageListUber.java

  19 
vote

public ImageListUber(IImageList[] sublist,int sort){
  mSubList=sublist.clone();
  mQueue=new PriorityQueue<MergeSlot>(4,sort == ImageManager.SORT_ASCENDING ? new AscendingComparator() : new DescendingComparator());
  mSkipList=new long[16];
  mSkipListSize=0;
  mSkipCounts=new int[mSubList.length];
  mLastListIndex=-1;
  mQueue.clear();
  for (int i=0, n=mSubList.length; i < n; ++i) {
    IImageList list=mSubList[i];
    MergeSlot slot=new MergeSlot(list,i);
    if (slot.next())     mQueue.add(slot);
  }
}
 

Example 48

From project recommenders, under directory /plugins/org.eclipse.recommenders.completion.rcp/src/org/eclipse/recommenders/internal/completion/rcp/.

Source file: SessionProcessorDescriptor.java

  19 
vote

public static SessionProcessorDescriptor[] parseExtensions(){
  IExtensionRegistry registry=Platform.getExtensionRegistry();
  IExtensionPoint point=registry.getExtensionPoint(EXT_POINT_SESSION_PROCESSORS);
  Set<String> disabledProcessors=getDisabledProcessors();
  PriorityQueue<SessionProcessorDescriptor> queue=new PriorityQueue<SessionProcessorDescriptor>();
  try {
    for (    IConfigurationElement elem : point.getConfigurationElements()) {
      try {
        final String pluginId=elem.getContributor().getName();
        String id=elem.getAttribute("id");
        String name=elem.getAttribute("name");
        final String iconPath=elem.getAttribute("icon");
        String priorityString=elem.getAttribute("priority");
        int priority=priorityString == null ? 10 : Integer.parseInt(priorityString);
        final Image icon=AbstractUIPlugin.imageDescriptorFromPlugin(pluginId,iconPath).createImage();
        SessionProcessor processor=(SessionProcessor)elem.createExecutableExtension("class");
        boolean enable=!disabledProcessors.contains(id);
        SessionProcessorDescriptor d=new SessionProcessorDescriptor(id,name,icon,priority,enable,processor);
        queue.add(d);
      }
 catch (      Exception e) {
        RecommendersPlugin.logError(e,"Exception during extension point parsing");
      }
    }
  }
 catch (  Exception e) {
    RecommendersPlugin.logError(e,"Exception during extension point parsing");
  }
  SessionProcessorDescriptor[] res=queue.toArray(new SessionProcessorDescriptor[0]);
  return res;
}
 

Example 49

From project SIREn, under directory /siren-core/src/main/java/org/sindice/siren/search/.

Source file: SirenTopTermsRewrite.java

  19 
vote

@Override public Q rewrite(final IndexReader reader,final SirenMultiTermQuery query) throws IOException {
  final int maxSize=Math.min(size,getMaxSize());
  final PriorityQueue<ScoreTerm> stQueue=new PriorityQueue<ScoreTerm>();
  collectTerms(reader,query,new TermCollector(){
    public boolean collect(    Term t,    float boost){
      if (stQueue.size() >= maxSize && boost <= stQueue.peek().boost)       return true;
      st.term=t;
      st.boost=boost;
      stQueue.offer(st);
      st=(stQueue.size() > maxSize) ? stQueue.poll() : new ScoreTerm();
      return true;
    }
    private ScoreTerm st=new ScoreTerm();
  }
);
  final Q q=getTopLevelQuery();
  for (  final ScoreTerm st : stQueue) {
    addClause(q,st.term,query.getBoost() * st.boost);
  }
  query.incTotalNumberOfTerms(stQueue.size());
  return q;
}
 

Example 50

From project snaptree, under directory /src/test/java/jsr166tests/jtreg/util/concurrent/ConcurrentQueues/.

Source file: GCRetention.java

  19 
vote

Collection<Queue<Boolean>> queues(){
  List<Queue<Boolean>> queues=new ArrayList<Queue<Boolean>>();
  queues.add(new ConcurrentLinkedQueue<Boolean>());
  queues.add(new ArrayBlockingQueue<Boolean>(count,false));
  queues.add(new ArrayBlockingQueue<Boolean>(count,true));
  queues.add(new LinkedBlockingQueue<Boolean>());
  queues.add(new LinkedBlockingDeque<Boolean>());
  queues.add(new PriorityBlockingQueue<Boolean>());
  queues.add(new PriorityQueue<Boolean>());
  queues.add(new LinkedList<Boolean>());
  Collections.shuffle(queues);
  return queues;
}
 

Example 51

From project Starfish, under directory /starfish/src/whatif/edu/duke/starfish/whatif/oracle/.

Source file: MergeSimulator.java

  19 
vote

/** 
 * Default constructor
 */
public MergeSimulator(){
  segments=new PriorityQueue<Segment>();
  useCombiner=false;
  numMemSegments=0;
  totalInputRecords=0l;
}
 

Example 52

From project tdbloader4, under directory /src/test/java/dev/.

Source file: MergeSortIterator.java

  19 
vote

public MergeSortIterator(List<Iterator<T>> inputs,Comparator<? super T> comp){
  this.inputs=inputs;
  this.comp=comp;
  this.minHeap=new PriorityQueue<Item<T>>(inputs.size());
  for (int i=0; i < inputs.size(); i++) {
    replaceItem(i);
  }
}
 

Example 53

From project Terasology, under directory /mods/miniion/src/main/java/org/terasology/miniion/components/.

Source file: UIMessageQueue.java

  19 
vote

public UIMessageQueue(){
  elements=new ArrayList<UIImage>();
  messageQueue=new PriorityQueue<MinionMessage>();
  float height=Display.getHeight() / 2;
  setSize(new Vector2f(ICON_SIZE,height));
  setPosition(new Vector2f(4,4));
}
 

Example 54

From project terraform, under directory /src/main/java/org/urbancode/terraform/tasks/vmware/.

Source file: EnvironmentTaskVmware.java

  19 
vote

/** 
 * Creates clones in the order specified in the xml by the "order" attribute. Clones with the same order number will be created in parallel. Each chunk of clones is passed off to handleCloneCreation.
 * @throws Exception
 */
private void createClonesInOrder() throws Exception {
  PriorityQueue<CloneTask> taskQueue=new PriorityQueue<CloneTask>(cloneTasks);
  List<CloneTask> concurrentClones=new ArrayList<CloneTask>();
  int currentOrder=taskQueue.peek().getOrder();
  while (!taskQueue.isEmpty()) {
    if (taskQueue.peek().getOrder() == currentOrder) {
      concurrentClones.add(taskQueue.poll());
    }
 else {
      log.info("about to launch " + concurrentClones.size() + " clones");
      handleCloneCreation(concurrentClones);
      log.info("finished creating " + concurrentClones.size() + " clones");
      log.info("There are " + taskQueue.size() + " clones left in the queue");
      concurrentClones.clear();
      CloneTask clone=taskQueue.poll();
      currentOrder=clone.getOrder();
      concurrentClones.add(clone);
    }
  }
  handleCloneCreation(concurrentClones);
}
 

Example 55

From project ubuntu-packaging-floodlight, under directory /src/main/java/net/floodlightcontroller/topology/.

Source file: TopologyInstance.java

  19 
vote

protected BroadcastTree dijkstra(Cluster c,Long root,Map<Link,Integer> linkCost,boolean isDstRooted){
  HashMap<Long,Link> nexthoplinks=new HashMap<Long,Link>();
  HashMap<Long,Integer> cost=new HashMap<Long,Integer>();
  int w;
  for (  Long node : c.links.keySet()) {
    nexthoplinks.put(node,null);
    cost.put(node,MAX_PATH_WEIGHT);
  }
  HashMap<Long,Boolean> seen=new HashMap<Long,Boolean>();
  PriorityQueue<NodeDist> nodeq=new PriorityQueue<NodeDist>();
  nodeq.add(new NodeDist(root,0));
  cost.put(root,0);
  while (nodeq.peek() != null) {
    NodeDist n=nodeq.poll();
    Long cnode=n.getNode();
    int cdist=n.getDist();
    if (cdist >= MAX_PATH_WEIGHT)     break;
    if (seen.containsKey(cnode))     continue;
    seen.put(cnode,true);
    for (    Link link : c.links.get(cnode)) {
      Long neighbor;
      if (isDstRooted == true)       neighbor=link.getSrc();
 else       neighbor=link.getDst();
      if (linkCost == null || linkCost.get(link) == null)       w=1;
 else       w=linkCost.get(link);
      int ndist=cdist + w;
      if (ndist < cost.get(neighbor)) {
        cost.put(neighbor,ndist);
        nexthoplinks.put(neighbor,link);
        nodeq.add(new NodeDist(neighbor,ndist));
      }
    }
  }
  BroadcastTree ret=new BroadcastTree(nexthoplinks,cost);
  return ret;
}