示例#1
0
  public static void main(String[] args) throws Exception {
    BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(rd.readLine());
    Map<String, Integer> terms = new LinkedHashMap<String, Integer>(N * 2);

    for (int i = 0; i < N; i++) {
      String term = rd.readLine();
      Integer count = terms.get(term);
      count = (count == null) ? 1 : count + 1;
      terms.put(term, count);
    }

    int K = Integer.parseInt(rd.readLine());
    rd.close();

    Queue<TermCount> sortedTerms =
        new PriorityQueue<TermCount>(
            K,
            new Comparator<TermCount>() {
              @Override
              public int compare(TermCount x, TermCount y) {
                return (x.count == y.count) ? x.term.compareTo(y.term) : y.count - x.count;
              }
            });

    for (Map.Entry<String, Integer> entry : terms.entrySet()) {
      sortedTerms.add(new TermCount(entry.getKey(), entry.getValue()));
    }

    PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    for (int i = 0; i < K; i++) {
      pw.println(sortedTerms.poll().term);
    }
    pw.close();
  }
  /**
   * Dequeues all previously enqueued wrappers and writes them to the stream.
   *
   * @throws IOException If failed.
   */
  void delayedWrite() throws IOException {
    if (wrappers != null)
      for (GridOptimizedWrapper w = wrappers.poll(); w != null; w = wrappers.poll())
        w.delayedWriteExternal(this);

    wrappers = null; // GC.
  }
  /**
   * Delayed post processing of optimized wrappers.
   *
   * @throws IOException If failed.
   * @throws ClassNotFoundException If failed.
   */
  void delayedRead() throws IOException, ClassNotFoundException {
    if (wrappers != null)
      for (GridOptimizedWrapper w = wrappers.poll(); w != null; w = wrappers.poll())
        w.delayedReadExternal(this);

    wrappers = null; // GC.
  }
示例#4
0
  /* Fill the bipartite graph if possible. */
  boolean[] solve() {
    Map<Integer, List<Integer>> gr = makeGraph();

    boolean[] truthTable = new boolean[count];
    // keep track of which ones we've visited
    boolean[] visited = new boolean[count];
    Queue<Integer> queue = new LinkedList<Integer>();
    truthTable[0] = true; // assume the first person tells the truth
    queue.add(0);

    // Breadth first search on graph
    while (!queue.isEmpty()) {
      int next = queue.remove();
      boolean truth = truthTable[next];
      List<Integer> list = gr.get(next);

      // Go through list and toggle when needed
      for (int i = 0; i < list.size(); i++) {
        int node = list.get(i);
        if (!visited[node]) {
          visited[node] = true;
          truthTable[node] = !truth;
          queue.add(node);
        }
      }
    }

    return truthTable;
  }
 /**
  * The basic method for splitting off a clause of a tree. This modifies the tree in place.
  *
  * @param tree The tree to split a clause from.
  * @param toKeep The edge representing the clause to keep.
  */
 static void splitToChildOfEdge(SemanticGraph tree, SemanticGraphEdge toKeep) {
   Queue<IndexedWord> fringe = new LinkedList<>();
   List<IndexedWord> nodesToRemove = new ArrayList<>();
   // Find nodes to remove
   // (from the root)
   for (IndexedWord root : tree.getRoots()) {
     nodesToRemove.add(root);
     for (SemanticGraphEdge out : tree.outgoingEdgeIterable(root)) {
       if (!out.equals(toKeep)) {
         fringe.add(out.getDependent());
       }
     }
   }
   // (recursively)
   while (!fringe.isEmpty()) {
     IndexedWord node = fringe.poll();
     nodesToRemove.add(node);
     for (SemanticGraphEdge out : tree.outgoingEdgeIterable(node)) {
       if (!out.equals(toKeep)) {
         fringe.add(out.getDependent());
       }
     }
   }
   // Remove nodes
   nodesToRemove.forEach(tree::removeVertex);
   // Set new root
   tree.setRoot(toKeep.getDependent());
 }
 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;
 }
示例#7
0
  private static PencilPosition findShortestRoute(int[][] maze) {
    // all found solutions to the maze
    PriorityQueue<PencilPosition> solutions =
        new PriorityQueue<PencilPosition>(5, new PencilPositionComparator());
    // bread-first search queue
    Queue<PencilPosition> routes = new LinkedList<PencilPosition>();
    // set of already visited positions
    Set<PencilPosition> visitedPositions = new HashSet<PencilPosition>();

    // add the starting positions, which is always (0,0)
    routes.add(new PencilPosition(0, 0, false, null));

    while (!routes.isEmpty()) {
      PencilPosition position = routes.poll();

      // if this is the destinations position then we've found a solution
      if (0 == maze[position.row][position.column]) {
        solutions.add(position);
        continue;
      }

      // if we haven't already visited this position
      if (!visitedPositions.contains(position)) {
        routes.addAll(findPossibleRoutes(position, maze));
        visitedPositions.add(position);
      }
    }

    return solutions.poll();
  }
  @Override
  public Boolean call() throws Exception {

    long timeoutMillis = 5000;

    try {
      getServersFile();
      getZkRunning();

      while (true) {
        while (!restartQueue.isEmpty()) {
          LOG.debug("Restart queue size [" + restartQueue.size() + "]");
          RestartHandler handler = restartQueue.poll();
          Future<ScriptContext> runner = pool.submit(handler);
          ScriptContext scriptContext = runner.get(); // blocking call
          if (scriptContext.getExitCode() != 0) restartQueue.add(handler);
        }

        try {
          Thread.sleep(timeoutMillis);
        } catch (InterruptedException e) {
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
      LOG.error(e);
      pool.shutdown();
      throw e;
    }
  }
 public synchronized void workAllJobs() {
   while (!jobs.isEmpty()) {
     loadJob(jobs.remove());
   }
   while (!shadertoset.empty()) {
     shadertoset.pop().load();
   }
 }
示例#10
0
 protected void handleNewRunRequest(Owner sender) {
   _consumerLock.lock();
   try {
     if (!_runRequests.contains(sender)) {
       _runRequests.add(sender);
     }
   } finally {
     _consumerLock.unlock();
   }
 }
 public Object readObject() throws EOFException {
   synchronized (queue) {
     while (queue.isEmpty())
       try {
         Thread.sleep(250);
       } catch (InterruptedException e) {
       }
     return queue.poll();
   }
 }
示例#12
0
 protected void handleNewConsumer(Owner sender) {
   _consumerLock.lock();
   try {
     if (!_consumersAvailable.contains(sender)) {
       _consumersAvailable.add(sender);
     }
   } finally {
     _consumerLock.unlock();
   }
 }
示例#13
0
  /**
   * Output an instance after filtering but do not remove from the output queue.
   *
   * @return the instance that has most recently been filtered (or null if the queue is empty).
   * @exception NullPointerException if no input structure has been defined
   */
  public M5Instance outputPeek() {

    if (m_OutputFormat == null) {
      throw new NullPointerException("No output instance format defined");
    }
    if (m_OutputQueue.empty()) {
      return null;
    }
    M5Instance result = (M5Instance) m_OutputQueue.peek();
    return result;
  }
示例#14
0
  public double next(int val) {

    if (q.size() == this.max) {
      total -= q.poll();
    }

    q.offer(val);
    total += val;

    return (double) total / q.size();
  }
    // we don't care about the return value but care about it throwing exception
    public void runMayThrow() throws Exception {
      if (endpoints.isEmpty()) {
        differencingDone.signalAll();
        logger.info(
            "No neighbors to repair with for "
                + tablename
                + " on "
                + range
                + ": "
                + getName()
                + " completed.");
        return;
      }

      // Checking all nodes are live
      for (InetAddress endpoint : endpoints) {
        if (!FailureDetector.instance.isAlive(endpoint)) {
          differencingDone.signalAll();
          logger.info(
              "Could not proceed on repair because a neighbor ("
                  + endpoint
                  + ") is dead: "
                  + getName()
                  + " failed.");
          return;
        }
      }

      AntiEntropyService.instance.sessions.put(getName(), this);
      Gossiper.instance.register(this);
      FailureDetector.instance.registerFailureDetectionEventListener(this);
      try {
        // Create and queue a RepairJob for each column family
        for (String cfname : cfnames) {
          RepairJob job = new RepairJob(cfname);
          jobs.offer(job);
          activeJobs.put(cfname, job);
        }

        jobs.peek().sendTreeRequests();

        // block whatever thread started this session until all requests have been returned:
        // if this thread dies, the session will still complete in the background
        completed.await();
        if (exception != null) throw exception;
      } catch (InterruptedException e) {
        throw new RuntimeException(
            "Interrupted while waiting for repair: repair will continue in the background.");
      } finally {
        FailureDetector.instance.unregisterFailureDetectionEventListener(this);
        Gossiper.instance.unregister(this);
        AntiEntropyService.instance.sessions.remove(getName());
      }
    }
 public Object peekObject() throws EOFException {
   assert false : "Local match shouldn't have best-of-3 early termination";
   synchronized (queue) {
     while (queue.isEmpty()) {
       try {
         Thread.sleep(250);
       } catch (InterruptedException e) {
       }
     }
     return queue.peek();
   }
 }
示例#17
0
 public void run() {
   try {
     while (true) {
       Runnable cur;
       synchronized (q) {
         while ((cur = q.poll()) == null) q.wait();
       }
       cur.run();
       cur = null;
     }
   } catch (InterruptedException e) {
   }
 }
 public void run() {
   latch = new CountDownLatch(queue.size());
   while (!queue.isEmpty()) {
     final LineCounter counter = queue.remove();
     new Thread(
             new Runnable() {
               public void run() {
                 execute(counter);
                 latch.countDown();
               }
             })
         .start();
   }
   waitOnLatch();
 }
示例#19
0
  /**
   * Creates a new <tt>RawPacket</tt> from a specific <tt>DatagramPacket</tt> in order to have this
   * instance receive its packet data through its {@link #read(byte[], int, int)} method. Returns an
   * array of <tt>RawPacket</tt> with the created packet as its first element (and <tt>null</tt> for
   * the other elements).
   *
   * <p>Allows extenders to intercept the packet data and possibly filter and/or modify it.
   *
   * @param datagramPacket the <tt>DatagramPacket</tt> containing the packet data
   * @return an array of <tt>RawPacket</tt> containing the <tt>RawPacket</tt> which contains the
   *     packet data of the specified <tt>DatagramPacket</tt> as its first element.
   */
  protected RawPacket[] createRawPacket(DatagramPacket datagramPacket) {
    RawPacket[] pkts = rawPacketArrayPool.poll();
    if (pkts == null) pkts = new RawPacket[1];

    RawPacket pkt = rawPacketPool.poll();
    if (pkt == null) pkt = new RawPacket();

    pkt.setBuffer(datagramPacket.getData());
    pkt.setFlags(0);
    pkt.setLength(datagramPacket.getLength());
    pkt.setOffset(datagramPacket.getOffset());

    pkts[0] = pkt;
    return pkts;
  }
示例#20
0
  /**
   * Returns the number of instances pending output
   *
   * @return the number of instances pending output
   * @exception NullPointerException if no input structure has been defined
   */
  public int numPendingOutput() {

    if (m_OutputFormat == null) {
      throw new NullPointerException("No output instance format defined");
    }
    return m_OutputQueue.size();
  }
示例#21
0
  /*Constructor*/
  public MemCheck(TorrentInfo tInfo, RandomAccessFile file) {
    this.tInfo = tInfo;
    this.file = file;
    this.left = tInfo.file_length;
    this.last_piece_size = tInfo.file_length % tInfo.piece_length;
    System.out.println("Last piece size is " + this.last_piece_size);
    // INITIALIZE THE Queue, worry about everything else later
    for (int i = 0; i < tInfo.piece_hashes.length; i++) {
      neededPieces.add(i);
    }
    this.finished_pieces = new boolean[tInfo.piece_hashes.length];

    // INITIALIZE Pieces
    for (int i = 0; i < tInfo.piece_hashes.length; i++) {
      if (i != tInfo.piece_hashes.length - 1) {
        Piece p = new Piece(16384, tInfo.piece_length, i);
        pieces.add(p);
      } // last piece
      else {
        int lastPieceSize = tInfo.file_length % tInfo.piece_length;
        int lastBlockSize = lastPieceSize % 16384;
        if (lastPieceSize == lastBlockSize) {
          Piece p = new Piece(lastBlockSize, lastPieceSize, i, 0);
          pieces.add(p);
        } else {
          Piece p = new Piece(16384, lastPieceSize, i, lastBlockSize);
          pieces.add(p);
        }
      }
    }
  }
 boolean registruotiAuto(String autoNr) {
   if (regAuto.containsKey(autoNr)) return false;
   Automobilis a = neregAuto.poll();
   if (a == null) return false; // kai neregistruotų jau nėra
   regAuto.put(autoNr, a);
   return true;
 }
示例#23
0
 /**
  * Pools the specified <tt>RawPacket</tt> in order to avoid future allocations and to reduce the
  * effects of garbage collection.
  *
  * @param pkt the <tt>RawPacket</tt> to be offered to {@link #rawPacketPool}
  */
 private void poolRawPacket(RawPacket pkt) {
   pkt.setBuffer(null);
   pkt.setFlags(0);
   pkt.setLength(0);
   pkt.setOffset(0);
   rawPacketPool.offer(pkt);
 }
  protected void addToFailedList() {

    FailedFile ff = new FailedFile(currentFile, offset, retryCount);

    try {
      // try to close file
      if (this.inputStream != null) this.inputStream.close();
    } catch (IOException e) {
      localNumberOfFailures.increment();
      LOG.error("Could not close input stream on: " + currentFile);
    }

    ff.retryCount++;
    ff.lastFailedTime = System.currentTimeMillis();
    ff.offset = this.offset;

    // Clear current file state.
    this.currentFile = null;
    this.inputStream = null;

    if (ff.retryCount > maxRetryCount) return;

    localNumberOfRetries.increment();
    LOG.info("adding to failed list path {} offset {} retry {}", ff.path, ff.offset, ff.retryCount);
    failedFiles.add(ff);
  }
示例#25
0
  protected void handleView(View view) {
    this.view = view;
    if (log.isDebugEnabled()) log.debug("view=" + view);
    List<Address> members = view.getMembers();

    _consumerLock.lock();
    try {
      // This removes the consumers that were registered that are now gone
      Iterator<Owner> iterator = _consumersAvailable.iterator();
      while (iterator.hasNext()) {
        Owner owner = iterator.next();
        if (!members.contains(owner.getAddress())) {
          iterator.remove();
          sendRemoveConsumerRequest(owner);
        }
      }

      // This removes the tasks that those requestors are gone
      iterator = _runRequests.iterator();
      while (iterator.hasNext()) {
        Owner owner = iterator.next();
        if (!members.contains(owner.getAddress())) {
          iterator.remove();
          sendRemoveRunRequest(owner);
        }
      }

      synchronized (_awaitingReturn) {
        for (Entry<Owner, Runnable> entry : _awaitingReturn.entrySet()) {
          // The person currently servicing our request has gone down
          // without completing so we have to keep our request alive by
          // sending ours back to the coordinator
          Owner owner = entry.getKey();
          if (!members.contains(owner.getAddress())) {
            Runnable runnable = entry.getValue();
            // We need to register the request id before sending the request back to the coordinator
            // in case if our task gets picked up since another was removed
            _requestId.put(runnable, owner.getRequestId());
            _awaitingConsumer.add(runnable);
            sendToCoordinator(RUN_REQUEST, owner.getRequestId(), local_addr);
          }
        }
      }
    } finally {
      _consumerLock.unlock();
    }
  }
示例#26
0
  /**
   * Output an instance after filtering and remove from the output queue.
   *
   * @return the instance that has most recently been filtered (or null if the queue is empty).
   * @exception NullPointerException if no output structure has been defined
   */
  public M5Instance output() {

    if (m_OutputFormat == null) {
      throw new NullPointerException("No output instance format defined");
    }
    if (m_OutputQueue.empty()) {
      return null;
    }
    M5Instance result = (M5Instance) m_OutputQueue.pop();
    // Clear out references to old strings occasionally
    if (m_OutputQueue.empty() && m_NewBatch) {
      if (m_OutputStringAtts.length > 0) {
        m_OutputFormat = m_OutputFormat.stringFreeStructure();
      }
    }
    return result;
  }
示例#27
0
 protected void handleRemoveConsumer(Owner sender) {
   _consumerLock.lock();
   try {
     _consumersAvailable.remove(sender);
   } finally {
     _consumerLock.unlock();
   }
 }
示例#28
0
  /**
   * Adds an output instance to the queue. The derived class should use this method for each output
   * instance it makes available.
   *
   * @param instance the instance to be added to the queue
   */
  protected void push(M5Instance instance) {

    if (instance != null) {
      copyStringValues(instance, m_OutputFormat, m_OutputStringAtts);
      instance.setDataset(m_OutputFormat);
      m_OutputQueue.push(instance);
    }
  }
示例#29
0
 protected void handleRemoveRunRequest(Owner sender) {
   _consumerLock.lock();
   try {
     _runRequests.remove(sender);
   } finally {
     _consumerLock.unlock();
   }
 }
示例#30
0
 public void bfs(int s) {
   Queue<Integer> q = new Queue<Integer>();
   distTo[s] = 0;
   marked[s] = true;
   q.enqueue(s);
   while (!q.isEmpty()) {
     int v = q.dequeue();
     for (Route r : adj[v]) {
       int w = r.other(cities[v]).id() - 1; // index of other city on route
       if (!marked[w]) {
         edgeTo[w] = r;
         distTo[w] = distTo[v] + 1;
         marked[w] = true;
         q.enqueue(w);
       }
     }
   }
 }