Esempio n. 1
0
 VoltMessage drain() {
   if (!m_servedFragment && m_firstFragment != null) {
     m_servedFragment = true;
     return m_firstFragment;
   } else if (!m_sequencedMessages.isEmpty()) {
     return m_sequencedMessages.poll();
   } else {
     return m_blockedMessages.poll();
   }
 }
 public IColumn pollColumn() {
   IColumn column = blockColumns.poll();
   if (column == null) {
     try {
       if (getNextBlock()) column = blockColumns.poll();
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
   return column;
 }
Esempio n. 3
0
  /** Notification that the current request is finished */
  public void requestDone() {

    connection.getSinkChannel().setConduit(originalSinkConduit);
    connection.getSourceChannel().setConduit(pushBackStreamSourceConduit);
    connection.getSinkChannel().suspendWrites();
    connection.getSinkChannel().setWriteListener(null);

    if (anyAreSet(state, CLOSE_REQ)) {
      currentRequest = null;
      this.state |= CLOSED;
      IoUtils.safeClose(connection);
    } else if (anyAreSet(state, UPGRADE_REQUESTED)) {
      connection.getSourceChannel().suspendReads();
      currentRequest = null;
      return;
    }
    currentRequest = null;

    HttpClientExchange next = pendingQueue.poll();

    if (next == null) {
      // we resume reads, so if the target goes away we get notified
      connection.getSourceChannel().setReadListener(clientReadListener);
      connection.getSourceChannel().resumeReads();
    } else {
      initiateRequest(next);
    }
  }
  public int[] maxSlidingWindow(int[] nums, int k) {
    if (nums == null || k == 0) {
      return new int[0];
    }

    int n = nums.length;

    int[] res = new int[n - k + 1];
    Deque<Integer> dq = new ArrayDeque<>();
    int pointer = 0;

    for (int i = 0; i < n; i++) {
      while (!dq.isEmpty() && dq.peek() < i - k + 1) {
        dq.poll();
      }

      while (!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) {
        dq.pollLast();
      }

      dq.offer(i);

      if (i >= k - 1) {
        res[pointer++] = nums[dq.peek()];
      }
    }

    return res;
  }
  /**
   * Construct and return a new session object, based on the default settings specified by this
   * Manager's properties. The session id specified will be used as the session id. If a new session
   * cannot be created for any reason, return <code>null</code>.
   *
   * @param sessionId The session id which should be used to create the new session; if <code>null
   *     </code>, a new session id will be generated
   * @exception IllegalStateException if a new session cannot be instantiated for any reason
   */
  @Override
  public Session createSession(String sessionId) {

    if ((maxActiveSessions >= 0) && (getActiveSessions() >= maxActiveSessions)) {
      rejectedSessions++;
      throw new IllegalStateException(sm.getString("managerBase.createSession.ise"));
    }

    // Recycle or create a Session instance
    Session session = createEmptySession();

    // Initialize the properties of the new session and return it
    session.setNew(true);
    session.setValid(true);
    session.setCreationTime(System.currentTimeMillis());
    session.setMaxInactiveInterval(this.maxInactiveInterval);
    String id = sessionId;
    if (id == null) {
      id = generateSessionId();
    }
    session.setId(id);
    sessionCounter++;

    SessionTiming timing = new SessionTiming(session.getCreationTime(), 0);
    synchronized (sessionCreationTiming) {
      sessionCreationTiming.add(timing);
      sessionCreationTiming.poll();
    }
    return (session);
  }
Esempio n. 6
0
  /** Notify all the handshake futures about the failure during the handshake. */
  private void setHandshakeFailure(Throwable cause) {
    // Release all resources such as internal buffers that SSLEngine
    // is managing.
    engine.closeOutbound();

    try {
      engine.closeInbound();
    } catch (SSLException e) {
      // only log in debug mode as it most likely harmless and latest chrome still trigger
      // this all the time.
      //
      // See https://github.com/netty/netty/issues/1340
      String msg = e.getMessage();
      if (msg == null || !msg.contains("possible truncation attack")) {
        logger.debug("SSLEngine.closeInbound() raised an exception.", e);
      }
    }
    notifyHandshakeFailure(cause);
    for (; ; ) {
      PendingWrite write = pendingUnencryptedWrites.poll();
      if (write == null) {
        break;
      }
      write.failAndRecycle(cause);
    }
  }
Esempio n. 7
0
 @Override
 public void flush(ChannelHandlerContext ctx) throws Exception {
   // Do not encrypt the first write request if this handler is
   // created with startTLS flag turned on.
   if (startTls && !sentFirstMessage) {
     sentFirstMessage = true;
     for (; ; ) {
       PendingWrite pendingWrite = pendingUnencryptedWrites.poll();
       if (pendingWrite == null) {
         break;
       }
       ctx.write(pendingWrite.msg(), (ChannelPromise) pendingWrite.recycleAndGet());
     }
     ctx.flush();
     return;
   }
   if (pendingUnencryptedWrites.isEmpty()) {
     pendingUnencryptedWrites.add(PendingWrite.newInstance(Unpooled.EMPTY_BUFFER, null));
   }
   if (!handshakePromise.isDone()) {
     flushedBeforeHandshakeDone = true;
   }
   wrap(ctx, false);
   ctx.flush();
 }
Esempio n. 8
0
  private static void solve(State initState) {
    Set<State> visited = new HashSet<State>();
    Map<State, State> pred = new HashMap<State, State>();
    Map<State, Integer> dist = new HashMap<State, Integer>();
    Deque<State> bfs = new ArrayDeque<State>();

    bfs.offer(initState);
    dist.put(initState, 0);

    while (bfs.size() > 0) {
      State s = bfs.poll();
      int n = dist.get(s);
      visited.add(s);

      if (s.isFinal()) {
        outputState(s, pred);
        return;
      }

      for (State child : s.getChildren()) {
        if (visited.contains(child)) continue;

        if (!pred.containsKey(child)) pred.put(child, s);

        if (!dist.containsKey(child)) {
          dist.put(child, n + 1);
          bfs.offer(child);
        }
      }
    }

    System.out.printf("%d %d %d\n", initState.a, initState.b, initState.c);
    System.out.println("============");
  }
Esempio n. 9
0
  // trim unnecessary log messages.
  private void truncate(long handle, boolean isSP) {
    // MIN value means no work to do, is a startup condition
    if (handle == Long.MIN_VALUE) {
      return;
    }

    Deque<RepairLog.Item> deq = null;
    if (isSP) {
      deq = m_logSP;
      if (m_truncationHandle < handle) {
        m_truncationHandle = handle;
        for (TransactionCommitInterest interest : m_txnCommitInterests) {
          interest.transactionCommitted(m_truncationHandle);
        }
      }
    } else {
      deq = m_logMP;
    }

    RepairLog.Item item = null;
    while ((item = deq.peek()) != null) {
      if (item.canTruncate(handle)) {
        deq.poll();
      } else {
        break;
      }
    }
  }
 public T get()
 {
   synchronized (mDataStore)
   {
     Object localObject2 = mDataStore.poll();
     ??? = localObject2;
     if (localObject2 == null) {
       ??? = mCallback.newInstance();
     }
Esempio n. 11
0
  public static void show(List<GPSState> states) {

    Deque<DeepTripState> boards = new LinkedList<DeepTripState>();
    for (GPSState state : states) {
      boards.push((DeepTripState) state);
    }
    GameViewer viewer = new GameViewer("test", boards.poll().getBoard());

    while (boards.peek() != null) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      viewer.refresh(boards.poll().getBoard());
    }
  }
Esempio n. 12
0
    VoltMessage poll() {
      if (!isReady()) return null;

      if (!m_servedFragment) {
        m_servedFragment = true;
        return m_firstFragment;
      } else {
        return m_sequencedMessages.poll();
      }
    }
Esempio n. 13
0
  private KafkaProducer getThreadLocalProducer() throws QiaoOperationException {
    KafkaProducer producer = threadLocalProducers.get();
    if (producer == null) {
      producer = producersStack.poll();
      if (producer == null) throw new QiaoOperationException("No producer available");

      threadLocalProducers.set(producer);
    }

    return producer;
  }
 protected IColumn computeNext() {
   while (true) {
     IColumn column = blockColumns.poll();
     if (column != null && isColumnNeeded(column)) return column;
     try {
       if (column == null && !fetcher.getNextBlock()) return endOfData();
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
 }
Esempio n. 15
0
 private TreeNode buildTree(Deque<String> nodes) {
   String val = nodes.poll();
   // Get a value from queue and build node
   if (NULLNODE.equals(val)) {
     return null;
   }
   TreeNode node = new TreeNode(Integer.valueOf(val));
   node.left = buildTree(nodes); // Build left subtree
   node.right = buildTree(nodes); // Build right subtree
   return node;
 }
Esempio n. 16
0
  private PooledPacket getPacket() {
    PooledPacket result;

    synchronized (this) {
      result = recycle.poll();
    }

    if (result == null) return new PooledPacket(new AVPacket()).alloc();

    return result;
  }
Esempio n. 17
0
  @VisibleForTesting
  IToken nextToken(final Supplier<Deque<IRobotLineElement>> elementsQueueSupplier) {
    if (tokensToAnalyze == null) {
      tokensToAnalyze = elementsQueueSupplier.get();

      final IRobotLineElement firstToken = tokensToAnalyze.peekFirst();
      if (firstToken != null) {
        currentOffsetInToken = rangeOffset - firstToken.getStartOffset();
      }
    }

    if (tokensToAnalyze.isEmpty()) {
      lastTokenPosition = new Position(getTokenOffset() + getTokenLength(), 0);
      return Token.EOF;
    }
    final IRobotLineElement nextToken = tokensToAnalyze.poll();
    for (final ISyntaxColouringRule rule : rules) {
      if (!rule.isApplicable(nextToken)) {
        continue;
      }
      final Optional<PositionedTextToken> tok =
          rule.evaluate(nextToken, currentOffsetInToken, analyzedTokens);
      if (tok.isPresent()) {
        final PositionedTextToken textToken = tok.get();
        lastTokenPosition = textToken.getPosition();

        if (lastTokenPosition.offset + lastTokenPosition.length
            >= nextToken.getStartOffset() + nextToken.getText().length()) {
          // rule have consumed whole Robot Token
          currentOffsetInToken = 0;
          analyzedTokens.add(nextToken);
        } else {
          // the token needs more coloring, so return it to queue and shift the
          // offset
          currentOffsetInToken =
              lastTokenPosition.getOffset()
                  + lastTokenPosition.getLength()
                  - nextToken.getStartOffset();
          tokensToAnalyze.addFirst(nextToken);
        }
        return textToken.getToken();
      }
    }
    lastTokenPosition =
        new Position(
            nextToken.getStartOffset() + currentOffsetInToken,
            nextToken.getText().length() - currentOffsetInToken);
    currentOffsetInToken = 0;
    analyzedTokens.add(nextToken);
    return ISyntaxColouringRule.DEFAULT_TOKEN;
  }
  public String[] generateBinaryNumbers(final int n) {
    final Deque<String> q = new LinkedList<>();
    final String[] binaryNumbers = new String[n];

    q.add("1");
    for (int i = 1; i <= n; i++) {
      final String number = q.poll();
      binaryNumbers[i - 1] = number;
      q.add(number + "0");
      q.add(number + "1");
    }

    return binaryNumbers;
  }
Esempio n. 19
0
 @Override
 public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
   if (decodeOut != null) {
     decodeOut.release();
     decodeOut = null;
   }
   for (; ; ) {
     PendingWrite write = pendingUnencryptedWrites.poll();
     if (write == null) {
       break;
     }
     write.failAndRecycle(new ChannelException("Pending write on removal of SslHandler"));
   }
 }
  @Override
  public void incrementFont(float incr) {
    Deque<Component> components = new ArrayDeque<>();
    components.addAll(Arrays.asList(getComponents()));
    Component c = null;
    while (null != (c = components.poll())) {
      Font f = c.getFont();
      c.setFont(f.deriveFont(f.getSize2D() + incr));

      if (c instanceof Container) {
        components.addAll(Arrays.asList(Container.class.cast(c).getComponents()));
      }
    }
  }
Esempio n. 21
0
  private void runEvictionIfRequired() {

    while (currentTableSize > maxTableSize) {
      TableEntry next = evictionQueue.poll();
      if (next == null) {
        return;
      }
      currentTableSize -= next.size;
      List<TableEntry> list = dynamicTable.get(next.name);
      list.remove(next);
      if (list.isEmpty()) {
        dynamicTable.remove(next.name);
      }
    }
  }
Esempio n. 22
0
  public static void collectAllInterfaces(ITypeBinding type, Set<ITypeBinding> interfaces) {
    Deque<ITypeBinding> typeQueue = Lists.newLinkedList();

    while (type != null) {
      typeQueue.add(type);
      type = type.getSuperclass();
    }

    while (!typeQueue.isEmpty()) {
      ITypeBinding nextType = typeQueue.poll();
      List<ITypeBinding> newInterfaces = Arrays.asList(nextType.getInterfaces());
      interfaces.addAll(newInterfaces);
      typeQueue.addAll(newInterfaces);
    }
  }
Esempio n. 23
0
  // https://www.hackerrank.com/challenges/bfsshortreach
  public static String shortestReach(int[][] edges, int n, int e, int start) {
    Map<Integer, List<Integer>> map = new HashMap<>();
    int[] nodes = new int[n];
    Arrays.fill(nodes, -1);
    for (int i = 0; i < e; i++) {
      int a = edges[i][0], b = edges[i][1];
      List<Integer> al = map.get(a);
      if (al == null) {
        al = new ArrayList<>();
        map.put(a, al);
      }
      al.add(b);

      al = map.get(b);
      if (al == null) {
        al = new ArrayList<>();
        map.put(b, al);
      }
      al.add(a);
    }

    Deque<Integer> q = new ArrayDeque<>();
    q.offer(start);
    nodes[start - 1] = 0;
    while (q.size() > 0) {
      int s = q.poll();
      List<Integer> al = map.get(s);
      for (int i = 0; al != null && i < al.size(); i++) {
        int v = al.get(i);
        if (nodes[v - 1] == -1) {
          q.offer(v);
          nodes[v - 1] = nodes[s - 1] + 6;
        }
      }
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; i++) {
      if (nodes[i] != 0) {
        sb.append(nodes[i]).append(' ');
      }
    }
    return sb.substring(0, sb.length() - 1);
  }
Esempio n. 24
0
    @Override
    public boolean hasNext() {
      WalkState walkState = null;
      do {
        if (stateStack.isEmpty()) {
          return false;
        }
        walkState = stateStack.poll();
      } while (walkState.isEnd());

      nextFile = walkState.currentFiles[walkState.currentIndex++];
      stateStack.push(walkState);
      if (nextFile.isDirectory()) {
        stateStack.push(new WalkState(nextFile.listFiles(), 0));
        return hasNext();
      } else {
        return true;
      }
    }
Esempio n. 25
0
 protected boolean slowCheck() {
   EntityPlayer player = Minecraft.getMinecraft().thePlayer;
   mOpen.clear();
   mClosed.clear();
   boolean newValue = false;
   // Boundry problems because doubles to ints suck, always pick the "good position"
   Pos current = new Pos(Math.ceil(player.posX), Math.ceil(player.posY), Math.ceil(player.posZ));
   if (!goodSuccessor(current, null))
     current = new Pos(Math.floor(player.posX), Math.floor(player.posY), Math.floor(player.posZ));
   while (current != null && !newValue) {
     if (current.isExposed()) {
       newValue = true;
       break;
     }
     mOpen.addAll(successors(current));
     mClosed.add(current);
     current = mOpen.poll();
   }
   return newValue;
 }
Esempio n. 26
0
  public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    if (root == null) {
      return res;
    }
    int curh = 1;
    // double ended queue
    Deque<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    TreeNode head = root, tail = null;
    List<Integer> path = new ArrayList<Integer>();
    while (!queue.isEmpty()) {
      TreeNode cur = queue.peek();
      if (cur == head) {
        if (!queue.isEmpty()) {
          tail = queue.getLast();
        }
      }
      queue.poll();
      path.add(cur.val);
      if (cur.left != null) {
        queue.add(cur.left);
      }
      if (cur.right != null) {
        queue.add(cur.right);
      }

      if (cur == tail) {
        if (!queue.isEmpty()) {
          head = queue.getFirst();
        }
        if ((curh & 1) == 0) {
          Collections.reverse(path);
        }
        res.add(new ArrayList<Integer>(path));
        path.clear();
        curh++;
      }
    }
    return res;
  }
  /**
   * Remove this Session from the active Sessions for this Manager.
   *
   * @param session Session to be removed
   * @param update Should the expiration statistics be updated
   */
  @Override
  public void remove(Session session, boolean update) {

    // If the session has expired - as opposed to just being removed from
    // the manager because it is being persisted - update the expired stats
    if (update) {
      long timeNow = System.currentTimeMillis();
      int timeAlive = (int) (timeNow - session.getCreationTimeInternal()) / 1000;
      updateSessionMaxAliveTime(timeAlive);
      expiredSessions.incrementAndGet();
      SessionTiming timing = new SessionTiming(timeNow, timeAlive);
      synchronized (sessionExpirationTiming) {
        sessionExpirationTiming.add(timing);
        sessionExpirationTiming.poll();
      }
    }

    if (session.getIdInternal() != null) {
      sessions.remove(session.getIdInternal());
    }
  }
Esempio n. 28
0
  /**
   * @param buffer
   * @param tile
   * @param pool
   * @return
   */
  private Tile createTile(
      FloatBuffer buffer,
      Rectangle tile,
      GL gl,
      Deque<Texture> pool,
      TablePerspective tablePerspective) {
    final VirtualArray recordVA = tablePerspective.getRecordPerspective().getVirtualArray();
    final VirtualArray dimVA = tablePerspective.getDimensionPerspective().getVirtualArray();
    final ATableBasedDataDomain dataDomain = tablePerspective.getDataDomain();
    final int ilast = tile.y + tile.height;
    final int jlast = tile.x + tile.width;

    // fill buffer
    buffer.rewind();
    for (int i = tile.y; i < ilast; ++i) {
      int recordID = recordVA.get(i);
      for (int j = tile.x; j < jlast; ++j) {
        int dimensionID = dimVA.get(j);
        Color color = blockColorer.apply(recordID, dimensionID, dataDomain, false);
        buffer.put(color.getRGBA());
      }
    }

    // load to texture
    buffer.rewind();
    Texture texture;
    if (!pool.isEmpty()) texture = pool.poll();
    else texture = TextureIO.newTexture(GL.GL_TEXTURE_2D);

    TextureData texData = asTextureData(buffer, tile.width, tile.height);
    texture.updateImage(gl, texData);
    gl.glFlush();
    texData.destroy();

    return new Tile(tile, texture);
  }
Esempio n. 29
0
  public void connectedComponents(
      GL4 gl,
      int toriBuffer,
      int edgesBuffer,
      int torusCount,
      int verticesBuffer,
      int vertexCount,
      int sphereCount) {
    boolean[][] adjacency = new boolean[vertexCount][vertexCount];
    int[][] edges = new int[torusCount][2];
    int[][] spheres = new int[torusCount][2];

    // map surface edges buffer
    gl.glBindBuffer(GL_SHADER_STORAGE_BUFFER, edgesBuffer);
    IntBuffer edgesData = gl.glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY).asIntBuffer();
    // fill adjacency matrix
    for (int i = 0; i < torusCount; i++) {
      int v0 = edgesData.get(4 * i);
      int v1 = edgesData.get(4 * i + 1);
      if (v0 != -1 && v1 != -1) {
        adjacency[v0][v1] = true;
        adjacency[v1][v0] = true;
        // store edges
        edges[i][0] = v0;
        edges[i][1] = v1;
        // get adjacent spheres
        spheres[i][0] = edgesData.get(4 * i + 2);
        spheres[i][1] = edgesData.get(4 * i + 3);
      }
    }
    // unmap edges buffer
    gl.glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

    // create CSR representation of the adjacency matrix
    int count = 0;
    int[] rows = new int[vertexCount + 1];
    rows[0] = count;
    for (int i = 0; i < vertexCount; i++) {
      for (int j = 0; j < vertexCount; j++) {
        if (adjacency[i][j]) {
          count++;
        }
      }
      rows[i + 1] = count;
    }

    int index = 0;
    int[] columns = new int[count];
    for (int i = 0; i < vertexCount; i++) {
      for (int j = 0; j < vertexCount; j++) {
        if (adjacency[i][j]) {
          columns[index] = j;
          index++;
        }
      }
    }

    Deque<Integer> vertices = new ArrayDeque<>();
    List<Integer> sizes = new ArrayList<>();
    boolean[] visited = new boolean[vertexCount];
    int[] labels = new int[vertexCount];

    int label = 1;
    int startVertex;
    do {
      // find start vertex
      startVertex = -1;
      for (int i = 0; i < vertexCount; i++) {
        if (!visited[i]) {
          startVertex = i;
          break;
        }
      }
      if (startVertex < 0) {
        break;
      }
      // label one connected component using BFS
      int size = 0;
      vertices.add(startVertex);
      while (!vertices.isEmpty()) {
        int vertex = vertices.poll();
        if (visited[vertex]) {
          continue;
        }
        visited[vertex] = true;
        labels[vertex] = label;
        int start = rows[vertex];
        int end = rows[vertex + 1];
        for (int i = start; i < end; i++) {
          vertices.add(columns[i]);
        }
        size++;
      }
      sizes.add(size);
      label++;
    } while (startVertex >= 0);

    // find largest connceted component
    int largest = 0;
    for (int i = 1; i < sizes.size(); i++) {
      if (sizes.get(i) > sizes.get(largest)) {
        largest = i;
      }
    }

    // map surface vertices buffer
    gl.glBindBuffer(GL_SHADER_STORAGE_BUFFER, verticesBuffer);
    IntBuffer verticesBuf = gl.glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_WRITE_ONLY).asIntBuffer();
    // write surface/cavity flags
    for (int i = 0; i < labels.length; i++) {
      int value = labels[i] == (largest + 1) ? 1 : 0;
      verticesBuf.put(i, value);
    }
    // unmap edges buffer
    gl.glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

    sphereCircles(gl, edges, spheres, sphereCount, toriBuffer, torusCount);

    try {
      writeCSR(rows, columns);
      writeLabels(labels, sizes);
    } catch (IOException ex) {
      ex.printStackTrace(System.err);
    }
  }
Esempio n. 30
0
 private ImapConnection pollConnection() {
   synchronized (connections) {
     return connections.poll();
   }
 }