Beispiel #1
1
  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    StringTokenizer st;

    t = Integer.parseInt(br.readLine());
    while (t-- > 0) {
      st = new StringTokenizer(br.readLine());
      n = Integer.parseInt(st.nextToken());
      m = Integer.parseInt(st.nextToken());
      S = Integer.parseInt(st.nextToken());
      T = Integer.parseInt(st.nextToken());

      // build graph
      AdjList = new Vector<Vector<IntegerPair>>();
      for (i = 0; i < n; i++) AdjList.add(new Vector<IntegerPair>());

      while (m-- > 0) {
        st = new StringTokenizer(br.readLine());
        a = Integer.parseInt(st.nextToken());
        b = Integer.parseInt(st.nextToken());
        w = Integer.parseInt(st.nextToken());
        AdjList.get(a).add(new IntegerPair(b, w)); // bidirectional
        AdjList.get(b).add(new IntegerPair(a, w));
      }

      // SPFA from source S
      // initially, only S has dist = 0 and in the queue
      Vector<Integer> dist = new Vector<Integer>();
      for (i = 0; i < n; i++) dist.add(INF);
      dist.set(S, 0);
      Queue<Integer> q = new LinkedList<Integer>();
      q.offer(S);
      Vector<Boolean> in_queue = new Vector<Boolean>();
      for (i = 0; i < n; i++) in_queue.add(false);
      in_queue.set(S, true);

      while (!q.isEmpty()) {
        int u = q.peek();
        q.poll();
        in_queue.set(u, false);
        for (j = 0; j < AdjList.get(u).size(); j++) { // all outgoing edges from u
          int v = AdjList.get(u).get(j).first(), weight_u_v = AdjList.get(u).get(j).second();
          if (dist.get(u) + weight_u_v < dist.get(v)) { // if can relax
            dist.set(v, dist.get(u) + weight_u_v); // relax
            if (!in_queue.get(v)) { // add to the queue only if it's not in the queue
              q.offer(v);
              in_queue.set(v, true);
            }
          }
        }
      }

      pr.printf("Case #%d: ", caseNo++);
      if (dist.get(T) != INF) pr.printf("%d\n", dist.get(T));
      else pr.printf("unreachable\n");
    }

    pr.close();
  }
  public void connect(TreeLinkNode root) {
    if (root == null) return;
    Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
    Queue<Integer> depth = new LinkedList<Integer>();
    depth.add(1);
    queue.add(root);
    while (!queue.isEmpty()) {
      TreeLinkNode parent = queue.poll();
      Integer parDep = depth.poll();

      if (parent.left != null) {
        queue.add(parent.left);
        depth.add(parDep + 1);
      }
      if (parent.right != null) {
        queue.add(parent.right);
        depth.add(parDep + 1);
      }
      // 还是广度搜索;
      if (!queue.isEmpty()) {
        TreeLinkNode next = queue.peek();
        Integer nextDep = depth.peek();
        if (nextDep != parDep) parent.next = null;
        else parent.next = next;
      } else parent.next = null;
    }
  }
  protected void onUpdateData(int reason) {

    publishUpdate(
        new ExtensionData()
            .visible(true)
            .icon(R.drawable.ic_extension_example)
            .status("Rss")
            .expandedTitle(
                (feedqueue.isEmpty()) ? "Error grabbing feeds" : feedqueue.peek().getTitle())
            .expandedBody(
                (feedqueue.isEmpty()) ? "Error grabbing feeds" : feedqueue.peek().getDescription())
            .clickIntent(
                new Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse(
                        (feedqueue.isEmpty())
                            ? "Error grabbing feeds"
                            : feedqueue.peek().getLink().toString()))));

    if ((new java.util.Date()).getTime() - lastUpdate > 3600000) updateFeeds();
    else if (!feedqueue.isEmpty()) {
      Log.d("swiggins", "Displaying: " + feedqueue.peek().getTitle());
      feedqueue.poll();
      Log.d("swiggins", "Up next: " + feedqueue.peek().getTitle());
    } else onInitialize(true);
  }
Beispiel #4
0
 /**
  * This method is used to embed syntaxes associated with UDT attribute notations to a queue of
  * string tokens extracted from a UDT parameter.
  *
  * @param tokens Queue of string tokens
  * @param syntaxQueue Syntax embedded tokens
  * @param isIndex Flag to determine whether a particular string token is an inidex or a column
  *     name
  */
 public static void getSyntaxEmbeddedQueue(
     Queue<String> tokens, Queue<String> syntaxQueue, boolean isIndex) {
   if (!tokens.isEmpty()) {
     if ("[".equals(tokens.peek())) {
       isIndex = true;
       tokens.poll();
       syntaxQueue.add("INEDX_START");
       syntaxQueue.add(tokens.poll());
     } else if ("]".equals(tokens.peek())) {
       isIndex = false;
       tokens.poll();
       syntaxQueue.add("INDEX_END");
     } else if (".".equals(tokens.peek())) {
       tokens.poll();
       syntaxQueue.add("DOT");
       syntaxQueue.add("COLUMN");
       syntaxQueue.add(tokens.poll());
     } else {
       if (isIndex) {
         syntaxQueue.add("INDEX");
         syntaxQueue.add(tokens.poll());
       } else {
         syntaxQueue.add("COLUMN");
         syntaxQueue.add(tokens.poll());
       }
     }
     getSyntaxEmbeddedQueue(tokens, syntaxQueue, isIndex);
   }
 }
  // Minimize the distance in k sorted arrays
  public static int p15(int[][] arrs) {
    Queue<P15Obj> q = new PriorityQueue<P15Obj>();
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < arrs.length; i++) {
      if (arrs[i].length > 0) {
        q.add(new P15Obj(i, 0, arrs[i][0]));
        if (max < arrs[i][0]) {
          max = arrs[i][0];
        }
      } else {
        return -1;
      }
    }

    int minDist = Integer.MAX_VALUE;
    do {
      P15Obj min = q.remove();
      minDist = Math.min(max - min.val, minDist);

      int newVal = arrs[min.i][min.j + 1];
      if (newVal > max) max = newVal;
      q.add(new P15Obj(min.i, min.j + 1, newVal));

    } while (q.peek().j < arrs[q.peek().i].length - 1);

    return minDist;
  }
  /** This is synchronized to ensure that we process the queue serially. */
  private synchronized void complete(String message) {
    // This is a weird problem with writing stuff while idling. Need to investigate it more, but
    // for now just ignore it.
    if (MESSAGE_COULDNT_BE_FETCHED_REGEX.matcher(message).matches()) {
      log.warn(
          "Some messages in the batch could not be fetched for {}\n"
              + "---cmd---\n{}\n---wire---\n{}\n---end---\n",
          new Object[] {config.getUsername(), getCommandTrace(), getWireTrace()});
      errorStack.push(new Error(completions.peek(), message, wireTrace.list()));
      throw new RuntimeException(
          "Some messages in the batch could not be fetched for user " + config.getUsername());
    }

    CommandCompletion completion = completions.peek();
    if (completion == null) {
      if ("+ idling".equalsIgnoreCase(message)) {
        synchronized (idleMutex) {
          idler.idleStart();
          log.trace("IDLE entered.");
          idleAcknowledged.set(true);
        }
      } else {
        log.error("Could not find the completion for message {} (Was it ever issued?)", message);
        errorStack.push(new Error(null, "No completion found!", wireTrace.list()));
      }
      return;
    }

    if (completion.complete(message)) {
      completions.poll();
    }
  }
Beispiel #7
0
 /**
  * 线程的主体方法
  *
  * @see java.lang.Thread#run()
  */
 public void run() { // 线程的主体方法
   while (conRun) {
     try {
       Thread.sleep(1000); // 线程休眠1秒
       Queue<Object[]> queue = localPanel.queue; // 获取本地面板的队列对象
       queueValues = queue.peek(); // 获取队列首的对象
       if (queueValues == null) { // 如果该对象为空
         continue; // 进行下一次循环
       }
       File file = (File) queueValues[0]; // 获取队列中的本队文件对象
       FtpFile ftpFile = (FtpFile) queueValues[1]; // 获取队列中的FTP文件对象
       if (file != null) {
         selPath = file.getParent();
         copyFile(file, ftpFile); // 调用递归方法上传文件
         FtpPanel ftpPanel = localPanel.frame.getFtpPanel();
         ftpPanel.refreshCurrentFolder(); // 刷新FTP面板中的资源
       }
       Object[] args = queue.peek();
       // 判断队列顶是否为处理的上一个任务。
       if (queueValues == null || args == null || !queueValues[0].equals(args[0])) {
         continue;
       }
       queue.remove(); // 移除队列首元素
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
 private static double median() {
   if (count % 2 != 0) {
     return Double.valueOf(maxHeap.peek());
   } else {
     return (maxHeap.peek() + minHeap.peek()) / 2.0;
   }
 }
Beispiel #9
0
 private static List<Integer> buildSkyline(Map<Integer, List<Building>> city) {
   Queue<Building> heights = new PriorityQueue<Building>();
   boolean[] active = new boolean[MAX_B + 1];
   List<Integer> skyline = new LinkedList<Integer>();
   int currHeight = 0;
   for (Integer p : city.keySet()) {
     for (Building b : city.get(p)) {
       if (p.intValue() == b.left) {
         heights.offer(b);
         active[b.idx] = true;
       } else {
         active[b.idx] = false;
         if (b.height == heights.peek().height) {
           while (!heights.isEmpty() && !active[heights.peek().idx]) {
             heights.poll();
           }
         }
       }
     }
     if (heights.isEmpty()) {
       skyline.add(p);
       skyline.add(0);
       currHeight = 0;
     } else if (currHeight != heights.peek().height) {
       skyline.add(p);
       skyline.add(heights.peek().height);
       currHeight = heights.peek().height;
     }
     // System.out.printf("Point %d. Heights: %s; Skyline: %s\n",
     //    p, heights, skyline);
   }
   return skyline;
 }
 public int completed(R request) {
   assert request.equals(requests.peek());
   requests.poll();
   int remaining = requests.size();
   if (remaining != 0) coordinator.send(requests.peek());
   return remaining;
 }
Beispiel #11
0
 public boolean eventHappened(int time) {
   if (eventQueue.peek() != null) {
     if (eventQueue.peek().getTimeStamp() == time) {
       return true;
     }
   }
   return false;
 }
Beispiel #12
0
  public void update() {

    if (!tasks.isEmpty() && tasks.peek().time < (int) (System.currentTimeMillis() / 1000)) {

      Task task = tasks.peek();
      try {

        if (task instanceof UpgradingFieldTask) {
          connection.upgradingField(((UpgradingFieldTask) task).idField);
        } else if (task instanceof UpgradingBuildingTask) {
          connection.upgradingBuilding(((UpgradingBuildingTask) task).idField);
        }
      } catch (LoadHttpPageException ex) {
        Logger.info("Can't load page");
        return;
      } catch (LoginException ex) {
        Logger.info("Can't login again. Was account information change?");
        return;
      } catch (UpgradingAvailableException ex) {
        if (buildingProductions != null && buildingProductions.length != 0) {
          int time = buildingProductions[buildingProductions.length - 1];
          task.time = buildingProductionsLastUpdate + time + 10;
          Logger.info("Already upgrading filed. Wait " + time + " sec");
        } else {

          UpgradingFieldPage page = ex.getUpgradingFieldPage();
          if (page.requiredResourses != null && resources != null && productions != null) {
            int time = 0;

            for (int i = 0; i < 4; i++) {
              int resorceTime =
                  (int)
                          Math.floor(
                              (page.requiredResourses[i] - resources[i])
                                  / (double) productions[i]
                                  * 3600)
                      + resourcesLastUpdate;

              if (time < resorceTime) {
                time = resorceTime;
              }
            }
            Logger.info("Wait resource to " + time + " ");
            task.time = time + 60;
          } else {
            task.time = task.time + 300;
          }
        }

        return;
      }
      tasks.poll();
    }
  }
Beispiel #13
0
  public void testConsumingIterable_queue_removesFromQueue() {
    Queue<Integer> queue = Lists.newLinkedList(asList(5, 14));

    Iterator<Integer> consumingIterator = Iterables.consumingIterable(queue).iterator();

    assertEquals(5, queue.peek().intValue());
    assertEquals(5, consumingIterator.next().intValue());

    assertEquals(14, queue.peek().intValue());
    assertTrue(consumingIterator.hasNext());
    assertTrue(queue.isEmpty());
  }
    public Map<Field, Object> next() {
      if (!hasNext()) {
        throw new NoSuchElementException();
      }

      Map<Field, Object> pass = new HashMap<Field, Object>();

      for (Entry<Field, Queue<? extends Object>> entry : queues.entrySet()) {
        final Field field = entry.getKey();
        final Queue<? extends Object> queue = entry.getValue();

        pass.put(field, queue.peek());
      }

      for (Entry<Field, Queue<? extends Object>> entry : queues.entrySet()) {
        final Field field = entry.getKey();
        final Queue<? extends Object> queue = entry.getValue();

        queue.poll();

        if (queue.isEmpty() && hasNext()) {
          List<? extends Object> parameter = parameters.get(field);
          queues.put(field, new LinkedList<Object>(parameter));
        } else {
          break;
        }
      }

      return pass;
    }
 public static void connect(TreeLinkNode root) {
   if (root == null) return;
   Queue<TreeLinkNode> q = new LinkedList<>();
   root.next = null;
   q.add(root);
   q.add(null);
   while (!q.isEmpty()) {
     TreeLinkNode n = q.poll();
     if (n != null) {
       n.next = q.peek();
       q.add(n.left);
       q.add(n.right);
       if (q.peek() == null) q.add(null);
     }
   }
 }
  public static int nextImportantEvent(
      Queue<OTH> othQueue, List<Instance> instanceList, CPUList cpuList) {
    int nextImportantTime = Integer.MAX_VALUE;

    int nextCpuTime;
    int nextOthTime;
    int nextNewTime;

    if (othQueue.isEmpty()) {
      nextOthTime = Integer.MAX_VALUE;
    } else {
      nextOthTime = othQueue.peek().getExitTime();
    }

    nextCpuTime = cpuList.getNextFinishTime();

    if (instanceList.isEmpty()) {
      nextNewTime = Integer.MAX_VALUE;
    } else {
      nextNewTime = instanceList.get(0).getStartTime();
    }

    nextImportantTime = Math.min(nextOthTime, nextCpuTime);
    nextImportantTime = Math.min(nextImportantTime, nextNewTime);

    //		System.out.println("\n################## NEXT IMPORTANT TIME: " + nextImportantTime);

    return nextImportantTime;
  }
  public void connect(TreeLinkNode root) {
    if (root == null) {
      return;
    }

    Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
    queue.offer(root);

    while (!queue.isEmpty()) {
      int size = queue.size();

      for (int i = 0; i < size; i++) {
        root = queue.poll();

        if (i == size - 1) {
          root.next = null;
        } else {
          root.next = queue.peek();
        }

        if (root.left != null) {
          queue.offer(root.left);
        }

        if (root.right != null) {
          queue.offer(root.right);
        }
      }
    }
  }
Beispiel #18
0
  protected void handleMessageData(byte[] aData) {
    // grab last fragment, use if not complete
    WebSocketFragment fragment = pendingFragments.peek();
    if (fragment == null || fragment.isValid()) {
      // assign web socket fragment since the last one was complete
      fragment = new WebSocketFragment(aData);

      pendingFragments.offer(fragment);
    } else if (fragment != null) {
      fragment.appendFragment(aData);
      if (fragment.canBeParsed()) {
        fragment.parseContent();
      }
    }

    // if we have a complete fragment, handle it
    if (fragment.isValid()) {
      // handle complete fragment
      handleCompleteFragment(fragment);

      // if we have extra data, handle it
      if (aData.length > fragment.getMessageLength()) {
        handleMessageData(
            WebSocketUtil.copySubArray(
                aData, fragment.getMessageLength(), aData.length - fragment.getMessageLength()));
      }
    }
  }
  public static int checkTimes(
      Queue<OTH> othQueue, List<Instance> instanceList, CPUList cpuList, int importantTime) {

    int nextCpuTime;
    int nextOthTime;
    int nextNewTime;

    if (othQueue.isEmpty()) {
      nextOthTime = Integer.MAX_VALUE;
    } else {
      nextOthTime = othQueue.peek().getExitTime();
    }

    nextCpuTime = cpuList.getNextFinishTime();

    if (instanceList.isEmpty()) {
      nextNewTime = Integer.MAX_VALUE;
    } else {
      nextNewTime = instanceList.get(0).getStartTime();
    }

    if (importantTime == nextCpuTime) {
      return 0;
    }
    if (importantTime == nextOthTime) {
      return 1;
    }

    if (importantTime == nextNewTime) {
      return 2;
    }
    return -1;
  }
Beispiel #20
0
  // Reads: value | '[' value1, value2, valueN ']'
  private Object readValue(Queue<String> tokens) {
    String token = tokens.poll();
    if (!"[".equals(token)) {
      return token;

    } else {
      List<Object> values = new ArrayList<Object>();
      while (true) {
        if ("]".equals(tokens.peek())) {
          tokens.remove();
          break;
        }

        Object value = readValue(tokens);
        values.add(value);

        String delimiter = tokens.poll();
        if ("]".equals(delimiter)) {
          break;

        } else if (!",".equals(delimiter)) {
          throw new IllegalArgumentException(String.format("Expected a comma after [%s]!", value));
        }
      }

      return values;
    }
  }
  @Override
  public void bindView(View convertView, Context context, Cursor cursor) {
    // Log.i(Constants.LOG_TAG, "in bind view " + cursor.getColumnCount());
    if (convertView != null) {
      ViewHolder holder = (ViewHolder) convertView.getTag();
      Type type = new TypeToken<ArrayList<String>>() {}.getType();
      ArrayList<String> finalOutputString = new Gson().fromJson(cursor.getString(1), type);
      Log.d(Constants.LOG_TAG, " in bind view " + finalOutputString);
      if (holder != null) {
        if (mListTitle != null && !mListTitle.isEmpty()) {
          holder.title.setText(mListTitle.peek());
          mListTitle.remove();
        }

        if (finalOutputString != null && !finalOutputString.isEmpty()) {
          if (finalOutputString.size() >= 1) {
            holder.listItem1.setText(finalOutputString.get(0));
            // Log.i(Constants.LOG_TAG, "in bind view pos 1 " + finalOutputString.get(0));
          } else holder.listItem1.setText("");
          if (finalOutputString.size() >= 2) {
            holder.listItem2.setText(finalOutputString.get(1));
            // Log.i(Constants.LOG_TAG, "in bind view pos 2 " + finalOutputString.get(1));

          } else holder.listItem2.setText("");
          if (finalOutputString.size() >= 3) {

            // Log.i(Constants.LOG_TAG, "in bind view pos 3 " + finalOutputString.get(2));
            holder.listItem3.setText(finalOutputString.get(2));
          } else holder.listItem3.setText("");
        }
      } else return;
    }
  }
Beispiel #22
0
  // A method used to tell set the time of how many ticks it takes to service the car
  public static int setTime(Queue<Car> b, String name, int a) {

    switch (b.size()) {
      case 0: // if it is the first car to arrive it takes 3 turns to complete
        if (a == 1) return 3;

        if ((name == "N" || name == "S")
            && light
                == true) // if there are no cars in a lane that is green then the car has to wait
                         // just one turn
        return 1;
        else if ((name == "E" || name == "W") && light == false) return 1;
        else // the light is red for that lane and the car must wait 3 turns
        return 3;

      case 1:
        // System.out.println("There is one car in the queue..so this is what b.peek().display does
        // just below this line\n"+b.peek().display());
        // the first if is to check if the car infront of it was the first car to arrive, if so,
        // this is the socond car to arrive and mustwait 2 clicks.
        if (b.peek().getTotalWait() == 3) return 2;
        // if it was
        // else if(b.peek().getTotalWait() == 2)
        // return 1;
        else return 1;

      default:
        return 1;
    }
  }
Beispiel #23
0
 // 思路,还是一样借助两个队列来进行完成
 public void connect(TreeLinkNode root) {
   if (root == null) {
     return;
   }
   Queue<TreeLinkNode> q1 = new LinkedList<TreeLinkNode>();
   Queue<TreeLinkNode> q2 = new LinkedList<TreeLinkNode>();
   q1.add(root);
   root.next = null;
   while (!(q1.isEmpty() && q2.isEmpty())) {
     while (!q1.isEmpty()) {
       TreeLinkNode node = q1.poll();
       if (node.left != null) {
         q2.add(node.left);
       }
       if (node.right != null) {
         q2.add(node.right);
       }
     }
     while (!q2.isEmpty()) {
       TreeLinkNode node = q2.poll();
       if (q2.isEmpty()) {
         node.next = null;
       } else {
         node.next = q2.peek();
       }
       q1.add(node);
     }
   }
 }
Beispiel #24
0
 private void checkNextTick() {
   // Check if there are more pending messages in the queue that can be processed next time around
   if (!pending.isEmpty()
       && !sentCheck
       && !paused
       && (pendingResponse == null || pending.peek() instanceof HttpContent)) {
     sentCheck = true;
     vertx.runOnContext(
         new VoidHandler() {
           public void handle() {
             sentCheck = false;
             if (!paused) {
               Object msg = pending.poll();
               if (msg != null) {
                 processMessage(msg);
               }
               if (channelPaused && pending.isEmpty()) {
                 // Resume the actual channel
                 ServerConnection.super.doResume();
                 channelPaused = false;
               }
             }
           }
         });
   }
 }
  @Override
  public void onSendFinished(boolean success, File file, Object key) {
    int status;
    if (success) {
      status = HistoryManager.STATUS_SEND_SUCCESS;
    } else {
      status = HistoryManager.STATUS_SEND_FAIL;
    }

    ContentValues values = new ContentValues();
    values.put(MetaData.History.STATUS, status);
    getContentResolver().update(getFileUri(key), values, null, null);

    SendFileThread thread = mSendingFileThreadMap.get(key);
    if (thread != null) {
      thread.setSendFinished();
      mSendingFileThreadMap.remove(key);
      mSendQueue.remove();
    }

    thread = mSendQueue.peek();
    if (thread != null) {
      mExecutorService.execute(thread);
    }
  }
  @Test
  public void testConnectToServerEndpoint() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(
        new ApplicationListener(TesterEchoServer.Config.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    Session wsSession =
        wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());
  }
Beispiel #27
0
  /* Given a binary tree, print its nodes in reverse level order */
  private void reverseLevelOrder(Node node, TraversalCallback callback) {
    Stack<Node> S = new Stack();
    Queue<Node> Q = new LinkedList();
    Q.add(node);

    // Do something like normal level order traversal order. Following are the
    // differences with normal level order traversal
    // 1) Instead of printing a node, we push the node to stack
    // 2) Right subtree is visited before left subtree
    while (Q.isEmpty() == false) {

      /* Dequeue node and make it root */
      node = Q.peek();
      Q.remove();
      S.push(node);

      /* Enqueue right child */
      if (node.getRight() != null) {
        Q.add(node.getRight()); // NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT
      }
      /* Enqueue left child */
      if (node.getLeft() != null) {
        Q.add(node.getLeft());
      }
    }

    // Now pop all items from stack one by one and print them
    while (S.empty() == false) {
      node = S.peek();

      callback.execute(node);

      S.pop();
    }
  }
  private void downloadNext() {
    if (downloadRunning) {
      return;
    }

    DownloadJob downloadJob = queue.peek();
    if (downloadJob != null) {
      DownloadTask downloadTask =
          new DownloadTask(
              downloadJob,
              new Handler() {
                @Override
                public void handleMessage(Message msg) {
                  final DownloadJob retryCandidate = queue.poll();
                  if (!retryCandidate.isSuccess() && retryCandidate.consumeRetry()) {
                    this.postDelayed(
                        new Runnable() {
                          @Override
                          public void run() {
                            queue.add(retryCandidate);
                            downloadNext();
                          }
                        },
                        3000);
                  }
                  downloadRunning = false;
                  downloadNext();
                }
              });
      downloadRunning = true;
      AsyncTaskUtils.execute(downloadTask);
    }
  }
Beispiel #29
0
  public Session take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      while (active) {
        Session first = queue.peek();
        if (first == null) {
          available.await();
        } else {
          long delay = getDelay(first, TimeUnit.NANOSECONDS);
          if (delay > 0) {
            available.awaitNanos(delay);
          } else {
            Session x = queue.poll();
            assert x != null;
            if (queue.size() != 0) {
              available.signalAll(); // wake up other takers
            }
            return x;
          }
        }
      }

      throw new InterruptedException("Session queue is stopping");
    } finally {
      lock.unlock();
    }
  }
Beispiel #30
0
  public static <T extends Comparable<T>> void merge(
      Queue<T> left, Queue<T> right, Queue<T> output) {
    T prevLeft = null;
    T prevRight = null;
    while ((left.size() > 0 && (prevLeft == null || prevLeft.compareTo(left.peek()) <= 0))
        || (right.size() > 0 && (prevRight == null || prevRight.compareTo(right.peek()) <= 0))) {

      if (right.size() == 0 || (left.size() > 0 && left.peek().compareTo(right.peek()) <= 0)) {
        prevLeft = left.poll();
        output.add(prevLeft);
      } else {
        prevRight = right.poll();
        output.add(prevRight);
      }
    }
  }