コード例 #1
0
  public static void main(String[] args) throws NumberFormatException, IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(br.readLine());
    Queue<String> buffer = new ArrayDeque<String>();
    String line = br.readLine();

    while (!line.equals("Q")) {
      String[] commands = line.split(" ");
      if (commands[0].equals("A")) {
        int k = Integer.parseInt(commands[1]);
        for (int i = 0; i < k; i++) {
          if (buffer.size() == N) {
            buffer.poll();
          }
          buffer.offer(br.readLine());
        }
      } else if (commands[0].equals("R")) {
        int k = Integer.parseInt(commands[1]);
        for (int i = 0; i < k; i++) {
          if (!buffer.isEmpty()) {
            buffer.poll();
          }
        }
      } else if (commands[0].equals("L")) {
        for (String s : buffer) {
          System.out.println(s);
        }
      }
      line = br.readLine();
    }
  }
コード例 #2
0
ファイル: Locking.java プロジェクト: an1310/JGroups
    public synchronized void signal(boolean all) {
      if (queue.isEmpty()) {
        if (log.isTraceEnabled()) {
          log.trace(
              "Signal for [" + lock.lock_name + "] ignored since, no one is waiting in queue.");
        }
      }

      Owner entry;
      if (all) {
        while ((entry = queue.poll()) != null) {
          notifyAwaited(lock.lock_name, entry);
          if (log.isTraceEnabled()) {
            log.trace("Signalled " + entry + " for " + lock.lock_name);
          }
          sendSignalResponse(entry, lock.lock_name);
        }
      } else {
        entry = queue.poll();
        if (entry != null) {
          notifyAwaited(lock.lock_name, entry);
          if (log.isTraceEnabled()) {
            log.trace("Signalled " + entry + " for " + lock.lock_name);
          }
          sendSignalResponse(entry, lock.lock_name);
        }
      }
    }
コード例 #3
0
 public Object getNextValue(Sequence sequence, AbstractSession writeSession) {
   String seqName = sequence.getName();
   if (sequence.getPreallocationSize() > 1) {
     Queue sequencesForName = getPreallocationHandler().getPreallocated(seqName);
     // First try to get the next sequence value without locking.
     Object sequenceValue = sequencesForName.poll();
     if (sequenceValue != null) {
       return sequenceValue;
     }
     // Sequences are empty, so must lock and allocate next batch of sequences.
     acquireLock(seqName);
     try {
       sequenceValue = sequencesForName.poll();
       if (sequenceValue != null) {
         return sequenceValue;
       }
       Vector sequences = sequence.getGeneratedVector(null, writeSession);
       // Remove the first value before adding to the global cache to ensure this thread gets
       // one.
       sequenceValue = sequences.remove(0);
       // copy remaining values to global cache.
       getPreallocationHandler().setPreallocated(seqName, sequences);
       logDebugPreallocation(seqName, sequenceValue, sequences);
     } finally {
       releaseLock(seqName);
     }
     return sequenceValue;
   } else {
     // preallocation size is 1 - just return the first (and only) element of the allocated
     // vector.
     return sequence.getGeneratedVector(null, writeSession).firstElement();
   }
 }
コード例 #4
0
  /**
   * Gets a connection from the pool of available and free data connections to this server.
   *
   * @return data connection to this server
   */
  public DataConnection getConnection() {
    DataConnection connection;

    for (connection = availableConnections.poll();
        connection != null && !connection.isUsable();
        connection = availableConnections.poll()) {
      if (!connection.isUsable()) {
        connection.close();
      }
    }

    if (connection == null) {
      connection = new DataConnection(getDataUri());

      try {
        connection.connect();
      } catch (Exception e) {
        logger.error("[getConnection] could not connect to database", e);
        return null;
      }
    }

    connection.setLocale(threadLocale.getLocale());

    return connection;
  }
コード例 #5
0
	@Test
	public void testDoSendDatagram() {
		Queue<Datagram> sendingQueue = new LinkedList<>();

		FutureRegistrationReference futureRegistrationReference =
			new FutureRegistrationReference(
				_executorIntraband, new ChannelContext(sendingQueue), null,
				null) {

				@Override
				public boolean isValid() {
					return true;
				}

			};

		Datagram datagram1 = Datagram.createRequestDatagram(_TYPE, _data);

		_executorIntraband.sendDatagram(futureRegistrationReference, datagram1);

		Datagram datagram2 = Datagram.createRequestDatagram(_TYPE, _data);

		_executorIntraband.sendDatagram(futureRegistrationReference, datagram2);

		Datagram datagram3 = Datagram.createRequestDatagram(_TYPE, _data);

		_executorIntraband.sendDatagram(futureRegistrationReference, datagram3);

		Assert.assertEquals(3, sendingQueue.size());
		Assert.assertSame(datagram1, sendingQueue.poll());
		Assert.assertSame(datagram2, sendingQueue.poll());
		Assert.assertSame(datagram3, sendingQueue.poll());
	}
コード例 #6
0
ファイル: Solution.java プロジェクト: wenyuwang/Leetcode_Java
 // Removes the element on top of the stack.
 public void pop() {
   int size = q.size();
   for (int i = 1; i < size; i++) {
     q.offer(q.poll());
   }
   q.poll();
 }
コード例 #7
0
  /**
   * 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.
  }
コード例 #8
0
  private void rightSideViewHelper(List<Integer> result, Queue<TreeNode> currLevel) {
    if (null == currLevel || currLevel.size() == 0) {
      return;
    }

    Queue<TreeNode> nextLevel = new LinkedList<>();

    while (currLevel.size() != 1) {
      TreeNode node = currLevel.poll();
      if (node.left != null) {
        nextLevel.add(node.left);
      }
      if (node.right != null) {
        nextLevel.add(node.right);
      }
    }

    TreeNode last = currLevel.poll();
    result.add(last.val);
    if (last.left != null) {
      nextLevel.add(last.left);
    }
    if (last.right != null) {
      nextLevel.add(last.right);
    }

    rightSideViewHelper(result, nextLevel);
  }
コード例 #9
0
 // Returns if the word is in the data structure. A word could
 // contain the dot character '.' to represent any one letter.
 public boolean search(String word) {
   Queue<TrieNode> queue = new LinkedList<TrieNode>();
   queue.add(root);
   for (int i = 0; i < word.length(); i++) {
     char c = word.charAt(i);
     if (queue.isEmpty()) return false;
     Queue<TrieNode> tempQueue = new LinkedList<TrieNode>();
     while (!queue.isEmpty()) {
       TrieNode tempNode = queue.poll();
       if (c == '.') {
         for (int j = 0; j < 26; j++) {
           if (tempNode.children[j] != null) tempQueue.offer(tempNode.children[j]);
         }
       } else {
         if (tempNode.children[c - 'a'] != null) tempQueue.add(tempNode.children[c - 'a']);
       }
     }
     queue = tempQueue;
   }
   boolean res = false;
   while (!queue.isEmpty()) {
     TrieNode tempNode = queue.poll();
     res = res || tempNode.isWord;
   }
   return res;
 }
コード例 #10
0
ファイル: Question7.java プロジェクト: kinshuk4/AlgorithmUtil
  public long kth(int k) {
    // write implementation here
    Queue<Long> three = new LinkedList<Long>();
    Queue<Long> five = new LinkedList<Long>();
    Queue<Long> seven = new LinkedList<Long>();
    three.add(3l);
    five.add(5l);
    seven.add(7l);

    int c = 0;
    long kth = 0;
    while (c++ < k) {
      kth = Math.min(three.peek(), Math.min(five.peek(), seven.peek()));
      if (kth == three.peek()) {
        three.poll();
        three.add(3 * kth);
        five.add(5 * kth);
      } else if (kth == five.peek()) {
        five.poll();
        five.add(5 * kth);
      } else if (kth == seven.peek()) {
        seven.poll();
      }
      seven.add(7 * kth);
    }
    return kth;
  }
コード例 #11
0
 @TearDown(Level.Iteration)
 public void emptyQs() {
   while (link1.poll() != null) ;
   while (link2.poll() != null) ;
   while (link3.poll() != null) ;
   while (link4.poll() != null) ;
 }
コード例 #12
0
ファイル: QueuesTest.java プロジェクト: Blackfin/MapDB
  @Test
  public void circular_queue_persisted() {
    // i put disk limit 4 objects ,
    File f = UtilsTest.tempDbFile();
    DB db = DBMaker.newFileDB(f).transactionDisable().cacheDisable().make();
    Queue queue = db.createCircularQueue("test", null, 4);
    // when i put 6 objects to queue
    queue.add(0);
    queue.add(1);
    queue.add(2);
    queue.add(3);
    // now deletes 0 on first
    queue.add(4);
    // now deletes 1
    queue.add(5);

    db.close();
    db = DBMaker.newFileDB(f).transactionDisable().cacheDisable().deleteFilesAfterClose().make();
    queue = db.getCircularQueue("test");

    assertEquals(2, queue.poll());
    assertEquals(3, queue.poll());
    assertEquals(4, queue.poll());
    assertEquals(5, queue.poll());
    assertNull(queue.poll());
    db.close();
  }
コード例 #13
0
  /**
   * 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.
  }
コード例 #14
0
ファイル: QueueRepository.java プロジェクト: JFanZhao/spider
 /** 从url仓库中取url,先从高优先级队列中取,如果高优先级队列中没有url,则从低优先级队列中取 */
 public String poll() {
   String url = highQueue.poll();
   if (url == null) {
     url = lowQueue.poll();
   }
   return url;
 }
コード例 #15
0
  @Test
  public void run() throws Exception {

    final Queue<Integer> exitCode = new ArrayBlockingQueue<Integer>(1);
    CommandLineJobRunner.presetSystemExiter(
        new SystemExiter() {
          @Override
          public void exit(int status) {
            exitCode.add(status);
          }
        });

    CommandLineJobRunner.main(new String[] {JOB_CONTEXT, "importProductsJob"});
    assertThat(exitCode.poll().intValue()).isEqualTo(0);

    CommandLineJobRunner.main(
        new String[] {JOB_CONTEXT, "importProductsJob", "exit.status=COMPLETED"});
    assertThat(exitCode.poll().intValue()).isEqualTo(0);

    CommandLineJobRunner.main(
        new String[] {JOB_CONTEXT, "importProductsJob", "exit.status=FAILED"});
    assertThat(exitCode.poll().intValue()).isEqualTo(1);

    CommandLineJobRunner.main(
        new String[] {JOB_CONTEXT, "importProductsJob", "exit.status=COMPLETED WITH SKIPS"});
    assertThat(exitCode.poll().intValue()).isEqualTo(3);

    CommandLineJobRunner.main(
        new String[] {JOB_CONTEXT, "importProductsJob", "exit.status=ANYTHING"});
    assertThat(exitCode.poll().intValue()).isEqualTo(2);
  }
コード例 #16
0
ファイル: PredicateParser.java プロジェクト: jamesvivid/dari
  // 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;
    }
  }
コード例 #17
0
 private Map<String, File> getAllClasses(String rootDir) {
   File[] arr = new File(rootDir).listFiles();
   Queue<File> toNavigate = new LinkedList<File>();
   Queue<String> toNavigateString = new LinkedList<String>();
   Map<String, File> classMap = new HashMap<String, File>();
   for (File f : arr) {
     toNavigate.add(f);
     toNavigateString.add("");
   }
   while (!toNavigate.isEmpty()) {
     File next = toNavigate.poll();
     String nextString = toNavigateString.poll();
     if (next.isDirectory()) {
       arr = next.listFiles();
       for (File f : arr) {
         toNavigate.add(f);
         toNavigateString.add(nextString + next.getName() + ".");
       }
     } else {
       if (next.getName().endsWith(".class")) {
         System.out.println(nextString + next.getName().substring(0, next.getName().length() - 6));
         classMap.put(nextString + next.getName().substring(0, next.getName().length() - 6), next);
       }
     }
   }
   return classMap;
 }
コード例 #18
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);
     }
   }
 }
コード例 #19
0
  /**
   * Handles post-mortem of writes that have failed.
   *
   * @param cause the cause of the failure.
   * @param propagateErrorIfRequired if {@code true} and {@code cause} is not an instance of {@link
   *     Exception}, the error is propagated through the netty pipeline.
   */
  private void handleChannelWriteFailure(Throwable cause, boolean propagateErrorIfRequired) {
    long writeFailureProcessingStartTime = System.currentTimeMillis();
    try {
      nettyMetrics.channelWriteError.inc();
      Exception exception;
      if (!(cause instanceof Exception)) {
        logger.warn("Encountered a throwable on channel write failure", cause);
        exception = new IllegalStateException("Encountered a Throwable - " + cause.getMessage());
        if (propagateErrorIfRequired) {
          // we can't ignore throwables - so we let Netty deal with it.
          ctx.fireExceptionCaught(cause);
          nettyMetrics.throwableCount.inc();
        }
      } else {
        exception = (Exception) cause;
      }
      onResponseComplete(exception);

      logger.trace("Cleaning up remaining chunks on write failure");
      Chunk chunk = chunksAwaitingCallback.poll();
      while (chunk != null) {
        chunk.resolveChunk(exception);
        chunk = chunksAwaitingCallback.poll();
      }
      chunk = chunksToWrite.poll();
      while (chunk != null) {
        chunksToWriteCount.decrementAndGet();
        chunk.resolveChunk(exception);
        chunk = chunksToWrite.poll();
      }
    } finally {
      nettyMetrics.channelWriteFailureProcessingTimeInMs.update(
          System.currentTimeMillis() - writeFailureProcessingStartTime);
    }
  }
 public void connect(TreeLinkNode root) {
   if (root == null) return;
   Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
   Queue<Integer> levelQ = new LinkedList<Integer>();
   q.add(root);
   levelQ.add(0);
   int curLevel = -1;
   TreeLinkNode curNode = null;
   while (!q.isEmpty()) {
     TreeLinkNode node = q.poll();
     int level = levelQ.poll();
     if (level != curLevel) {
       curLevel = level;
       curNode = node;
     } else {
       curNode.next = node;
       curNode = node;
     }
     if (node.left != null) {
       q.add(node.left);
       levelQ.add(level + 1);
     }
     if (node.right != null) {
       q.add(node.right);
       levelQ.add(level + 1);
     }
   }
 }
  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;
    }
  }
コード例 #22
0
 /**
  * Main process loop, takes a runnable task and executes it. If the graph has not been built when
  * getDependencyGraph is called, the calling thread will also join this. There are additional
  * threads that also run in a pool to complete the work of the graph building.
  *
  * @param context the calling thread's building context
  * @return true if there is more work still to do, false if all the work is done
  */
 protected boolean buildGraph(final GraphBuildingContext context) {
   ContextRunnable task = _runQueue.take();
   if (task == null) {
     task = _deferredQueue.poll();
     if (task == null) {
       // Nothing runnable and nothing deferred
       return false;
     }
   }
   if (!task.tryRun(context)) {
     // A concurrency limit was hit. Post the job into the contention buffer and try and take
     // another from the run queue.
     do {
       _deferredQueue.add(task);
       task = _runQueue.take();
       if (task == null) {
         // Nothing runnable. Abort as we can't just add the deferred items or we might end up
         // spinning
         return false;
       }
     } while (!task.tryRun(context));
   }
   // Reschedule a deferred item. There may be multiple deferred items, but we only release them
   // one at a time as other jobs complete
   // which may resolve the contention. If the run queue becomes empty they will be taken directly
   // by the code above.
   task = _deferredQueue.poll();
   if (task != null) {
     addToRunQueue(task);
   }
   _completedSteps.incrementAndGet();
   return true;
 }
コード例 #23
0
  public void insertMessage(WebSocketMessageDTO message) throws DatabaseException {
    try {
      // synchronize on whole object to avoid race conditions with insertOrUpdateChannel()
      synchronized (this) {
        if (getConnection().isClosed()) {
          // temporarily buffer messages and write them the next time
          messagesBuffer.offer(message);
          return;
        }

        do {
          if (!channelIds.contains(message.channel.id)) {
            // maybe channel is buffered
            if (channelsBuffer.size() > 0) {
              insertOrUpdateChannel(channelsBuffer.poll());
            }
            throw new SQLException("channel not inserted: " + message.channel.id);
          }

          logger.info("insert message: " + message.toString());

          psInsertMessage.setInt(1, message.id);
          psInsertMessage.setInt(2, message.channel.id);
          psInsertMessage.setTimestamp(3, new Timestamp(message.timestamp));
          psInsertMessage.setInt(4, message.opcode);

          // write payload
          if (message.payload instanceof String) {
            psInsertMessage.setClob(5, new JDBCClob((String) message.payload));
            psInsertMessage.setNull(6, Types.BLOB);
          } else if (message.payload instanceof byte[]) {
            psInsertMessage.setNull(5, Types.CLOB);
            psInsertMessage.setBlob(6, new JDBCBlob((byte[]) message.payload));
          } else {
            throw new SQLException(
                "Attribute 'payload' of class WebSocketMessageDTO has got wrong type!");
          }

          psInsertMessage.setInt(7, message.payloadLength);
          psInsertMessage.setBoolean(8, message.isOutgoing);
          psInsertMessage.execute();

          if (message instanceof WebSocketFuzzMessageDTO) {
            WebSocketFuzzMessageDTO fuzzMessage = (WebSocketFuzzMessageDTO) message;
            psInsertFuzz.setInt(1, fuzzMessage.fuzzId);
            psInsertFuzz.setInt(2, fuzzMessage.id);
            psInsertFuzz.setInt(3, fuzzMessage.channel.id);
            psInsertFuzz.setString(4, fuzzMessage.state.toString());
            psInsertFuzz.setString(5, fuzzMessage.fuzz);
            psInsertFuzz.execute();
          }

          message = messagesBuffer.poll();
        } while (message != null);
      }
    } catch (SQLException e) {
      throw new DatabaseException(e);
    }
  }
コード例 #24
0
 /**
  * The only two things that a SubProcessWrapper cares about are the timeouts and the seed
  *
  * @param arg The parameter.
  * @param args The list of parameters.
  */
 @Override
 protected void _processParameter(String arg, Queue<String> args) {
   if (arg.equals("-seed")) {
     // ignored
     args.poll();
   } else if (arg.equals("-timeout")) {
     mTimeout = Float.parseFloat(args.poll());
   }
 }
コード例 #25
0
  //  Fields("frameId", "frameMat", "patchCount"));
  private void processFrame(Tuple tuple) {
    int frameId = tuple.getIntegerByField(FIELD_FRAME_ID);
    Serializable.Mat mat = (Serializable.Mat) tuple.getValueByField(FIELD_FRAME_MAT);
    int patchCount = tuple.getIntegerByField(FIELD_PATCH_COUNT);
    if (frameMap.containsKey(frameId)) {
      if (Debug.topologyDebugOutput)
        System.err.println(this.getClass() + "#" + "processFrame(): Received duplicate frame");
    } else {
      frameMap.put(frameId, mat);
    }
    if (patchQueue.containsKey(frameId)) {
      Queue<Serializable.PatchIdentifier> queue = patchQueue.get(frameId);
      while (!queue.isEmpty()) {
        Serializable.PatchIdentifier hostPatch = queue.poll();

        List<Serializable.Rect> detectedLogoList = new ArrayList<>();
        SIFTfeatures sifTfeatures =
            new SIFTfeatures(sift, mat.toJavaCVMat(), hostPatch.roi.toJavaCVRect(), true);

        for (int logoIndex = 0; logoIndex < detectors.size(); logoIndex++) {
          StormVideoLogoDetectorGamma detector = detectors.get(logoIndex);
          // detector.detectLogosInRoi(mat.toJavaCVMat(), hostPatch.roi.toJavaCVRect());
          detector.detectLogosByFeatures(sifTfeatures);

          Serializable.Rect detectedLogo = detector.getFoundRect();
          if (detectedLogo != null) {
            collector.emit(
                LOGO_TEMPLATE_UPDATE_STREAM,
                new Values(hostPatch, detectedLogo, detector.getParentIdentifier(), logoIndex));
          }
          detectedLogoList.add(detectedLogo);
        }
        collector.emit(
            DETECTED_LOGO_STREAM,
            tuple,
            new Values(frameId, hostPatch, detectedLogoList, patchCount));
      }
    } else {
      // patchQueue.put(frameId, new LinkedList<>());
    }
    if (templateQueue.containsKey(frameId)) {
      Queue<LogoTemplateUpdateBeta> queue = templateQueue.get(frameId);
      while (!queue.isEmpty()) {
        LogoTemplateUpdateBeta update = queue.poll();
        Serializable.Rect roi = update.detectedLogoRect;
        Serializable.PatchIdentifier hostPatchIdentifier = update.hostPatchIdentifier;
        Serializable.PatchIdentifier parent = update.parentIdentifier;
        int logoIndex = update.logoIndex;
        /// detector.addTemplateByRect(hostPatchIdentifier, mat, roi);
        /// detector.incrementPriority(parent, 1);
        detectors.get(logoIndex).addTemplateByRect(hostPatchIdentifier, mat, roi);
        detectors.get(logoIndex).incrementPriority(parent, 1);
      }
    } else {
      // templateQueue.put(frameId, new LinkedList<>());
    }
  }
コード例 #26
0
ファイル: MazeMaker3.java プロジェクト: WonderBlack/TopCoder
  public int LongestPath(String[] maze, int startRow, int startCol, int[] moveRow, int[] moveCol) {

    int max = 0;
    int width = maze[0].length();
    int height = maze.length;
    int[][] board = new int[height][width]; // 各マスまでの移動回数を保持

    // ボードを未訪問(-1)で初期化
    for (int i = 0; i < height; i++) {
      for (int j = 0; j < width; j++) {
        board[i][j] = -1;
      }
    }

    board[startRow][startCol] = 0; // 出発点を訪問済みにする

    Queue<Integer> queueX = new LinkedList<Integer>();
    Queue<Integer> queueY = new LinkedList<Integer>();
    queueX.add(startRow);
    queueY.add(startCol);

    while (!queueX.isEmpty()) {

      int x = queueX.poll(); // キューから現在地のx座標を取り出す
      int y = queueY.poll(); // キューから現在地のy座標を取り出す

      // 全ての移動パターンを使って次のマスを割り出す
      for (int i = 0; i < moveRow.length; i++) {
        int nextx = x + moveCol[i]; // パターンiで移動後のx座標
        int nexty = y + moveRow[i]; // パターンiで移動後のy座標
        // 移動後のマスがエリア内で、なおかつ未訪問で、なおかつ障害物がないなら
        if (0 <= nextx
            && nextx < width
            && 0 <= nexty
            && nexty < height
            && board[nexty][nextx] == -1
            && maze[nexty].charAt(nextx) == '.') {
          board[nexty][nextx] = board[y][x] + 1; // 移動後のマスに前回のマスの移動回数に1を足した物を記録
          queueX.add(nextx); // x座標のキューに移動後の値を入れる
          queueY.add(nexty); // y座標のキューに移動後の値を入れる
        }
      }
    }

    for (int i = 0; i < height; i++) {
      for (int j = 0; j < width; j++) {
        if (maze[i].charAt(j) == '.' && board[i][j] == -1) {
          return -1;
        } else {
          max = Math.max(max, board[i][j]);
        }
      }
    }

    return max;
  }
コード例 #27
0
 synchronized void doCancel() {
   if (cancelled) {
     return;
   }
   cancelled = true;
   Runnable runnable = callbacks.poll();
   while (runnable != null) {
     runnable.run();
     runnable = callbacks.poll();
   }
 }
コード例 #28
0
  @Override
  protected void decode(ChannelHandlerContext ctx, RESPONSE msg, List<Object> out)
      throws Exception {
    if (currentDecodingState == DecodingState.INITIAL) {
      currentRequest = sentRequestQueue.poll();
      currentDecodingState = DecodingState.STARTED;
      if (currentRequest != null) {
        Long st = sentRequestTimings.poll();
        if (st != null) {
          currentOpTime = System.nanoTime() - st;
        } else {
          currentOpTime = -1;
        }
      }

      if (traceEnabled) {
        LOGGER.trace("{}Started decoding of {}", logIdent(ctx, endpoint), currentRequest);
      }
    }

    try {
      CouchbaseResponse response = decodeResponse(ctx, msg);
      if (response != null) {
        publishResponse(response, currentRequest.observable());

        if (currentDecodingState == DecodingState.FINISHED) {
          if (currentRequest != null
              && currentOpTime >= 0
              && env() != null
              && env().networkLatencyMetricsCollector().isEnabled()) {
            NetworkLatencyMetricsIdentifier identifier =
                new NetworkLatencyMetricsIdentifier(
                    remoteHostname,
                    serviceType().toString(),
                    currentRequest.getClass().getSimpleName(),
                    response.status().toString());
            env().networkLatencyMetricsCollector().record(identifier, currentOpTime);
          }
        }
      }
    } catch (CouchbaseException e) {
      currentRequest.observable().onError(e);
    } catch (Exception e) {
      currentRequest.observable().onError(new CouchbaseException(e));
    }

    if (currentDecodingState == DecodingState.FINISHED) {
      if (traceEnabled) {
        LOGGER.trace("{}Finished decoding of {}", logIdent(ctx, endpoint), currentRequest);
      }
      currentRequest = null;
      currentDecodingState = DecodingState.INITIAL;
    }
  }
コード例 #29
0
ファイル: CutLetterDigitFilter.java プロジェクト: khaliyo/pet
  private Token nextToken(Token reusableToken) throws IOException {
    assert reusableToken != null;

    // 先使用上次留下来的。
    Token nextToken = tokenQueue.poll();
    if (nextToken != null) {
      return nextToken;
    }

    /*//在 TokenUtils.nextToken 已经调用了 inc
    if(!input.incrementToken()) {
    	return null;
    }*/

    /*TermAttribute termAtt = (TermAttribute)input.getAttribute(TermAttribute.class);
    OffsetAttribute offsetAtt = (OffsetAttribute)input.getAttribute(OffsetAttribute.class);
    TypeAttribute typeAtt = (TypeAttribute)input.getAttribute(TypeAttribute.class);

    nextToken = reusableToken.reinit(termAtt.termBuffer(), 0, termAtt.termLength(), offsetAtt.startOffset(), offsetAtt.endOffset(), typeAtt.type());*/

    nextToken = TokenUtils.nextToken(input, reusableToken);

    if (nextToken != null
        && (Word.TYPE_LETTER_OR_DIGIT.equalsIgnoreCase(nextToken.type())
            || Word.TYPE_DIGIT_OR_LETTER.equalsIgnoreCase(nextToken.type()))) {
      final char[] buffer = nextToken.buffer();
      final int length = nextToken.length();
      byte lastType = (byte) Character.getType(buffer[0]); // 与上次的字符是否同类
      int termBufferOffset = 0;
      int termBufferLength = 0;
      for (int i = 0; i < length; i++) {
        byte type = (byte) Character.getType(buffer[i]);
        if (type <= Character.MODIFIER_LETTER) {
          type = Character.LOWERCASE_LETTER;
        }
        if (type != lastType) { // 与上一次的不同
          addToken(nextToken, termBufferOffset, termBufferLength, lastType);

          termBufferOffset += termBufferLength;
          termBufferLength = 0;

          lastType = type;
        }

        termBufferLength++;
      }
      if (termBufferLength > 0) { // 最后一次
        addToken(nextToken, termBufferOffset, termBufferLength, lastType);
      }
      nextToken = tokenQueue.poll();
    }

    return nextToken;
  }
コード例 #30
0
ファイル: Solution.java プロジェクト: wenyuwang/Leetcode_Java
  // Get the top element.
  public int top() {

    int size = q.size();
    for (int i = 1; i < size; i++) {
      q.offer(q.poll());
    }
    int top = q.peek();
    q.offer(q.poll());

    return top;
  }