Java Code Examples for java.util.ArrayDeque#addFirst()

The following examples show how to use java.util.ArrayDeque#addFirst() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: consulo   File: ProjectViewTree.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void collapsePath(TreePath path) {
  int row = Registry.is("async.project.view.collapse.tree.path.recursively") ? getRowForPath(path) : -1;
  if (row < 0) {
    super.collapsePath(path);
  }
  else {
    ArrayDeque<TreePath> deque = new ArrayDeque<>();
    deque.addFirst(path);
    while (++row < getRowCount()) {
      TreePath next = getPathForRow(row);
      if (!path.isDescendant(next)) break;
      if (isExpanded(next)) deque.addFirst(next);
    }
    deque.forEach(super::collapsePath);
  }
}
 
Example 2
/**
 * Iterates over the provided records to deserialize, verifies the results and stats
 * the number of full records.
 *
 * @param records records to be deserialized
 * @param deserializer the record deserializer
 * @return the number of full deserialized records
 */
public static int deserializeRecords(
		ArrayDeque<SerializationTestType> records,
		RecordDeserializer<SerializationTestType> deserializer) throws Exception {
	int deserializedRecords = 0;

	while (!records.isEmpty()) {
		SerializationTestType expected = records.poll();
		SerializationTestType actual = expected.getClass().newInstance();

		if (deserializer.getNextRecord(actual).isFullRecord()) {
			Assert.assertEquals(expected, actual);
			deserializedRecords++;
		} else {
			records.addFirst(expected);
			break;
		}
	}

	return deserializedRecords;
}
 
Example 3
static int build(int size, int B, ArrayDeque<Integer> chunks) {
    chunks.addFirst(B);
    if (size < BOUND1) {
        chunks.addFirst(size);
        return size;
    }

    int asize = (size + 2) / 2;
    if (size >= BOUND2 && asize < BOUND1) {
        asize = BOUND1;
    } else if (size >= BOUND3 && asize < BOUND2) {
        asize = BOUND2;
    } else if (size >= BOUND4 && asize < BOUND3) {
        asize = BOUND3;
    } else if (size >= BOUND5 && asize < BOUND4) {
        asize = BOUND4;
    }
    if (size - asize >= B) {
        throw new AssertionError(" " + size + " , " + asize + " , " + B);
    }
    return build(asize, size - asize, chunks);
}
 
Example 4
Source Project: flink   File: DeserializationUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Iterates over the provided records to deserialize, verifies the results and stats
 * the number of full records.
 *
 * @param records records to be deserialized
 * @param deserializer the record deserializer
 * @return the number of full deserialized records
 */
public static int deserializeRecords(
		ArrayDeque<SerializationTestType> records,
		RecordDeserializer<SerializationTestType> deserializer) throws Exception {
	int deserializedRecords = 0;

	while (!records.isEmpty()) {
		SerializationTestType expected = records.poll();
		SerializationTestType actual = expected.getClass().newInstance();

		if (deserializer.getNextRecord(actual).isFullRecord()) {
			Assert.assertEquals(expected, actual);
			deserializedRecords++;
		} else {
			records.addFirst(expected);
			break;
		}
	}

	return deserializedRecords;
}
 
Example 5
static int build(int size, int B, ArrayDeque<Integer> chunks) {
    chunks.addFirst(B);
    if (size < BOUND1) {
        chunks.addFirst(size);
        return size;
    }

    int asize = (size + 2) / 2;
    if (size >= BOUND2 && asize < BOUND1) {
        asize = BOUND1;
    } else if (size >= BOUND3 && asize < BOUND2) {
        asize = BOUND2;
    } else if (size >= BOUND4 && asize < BOUND3) {
        asize = BOUND3;
    } else if (size >= BOUND5 && asize < BOUND4) {
        asize = BOUND4;
    }
    if (size - asize >= B) {
        throw new AssertionError(" " + size + " , " + asize + " , " + B);
    }
    return build(asize, size - asize, chunks);
}
 
Example 6
Source Project: clutz   File: TestUtil.java    License: MIT License 6 votes vote down vote up
public static String getRelativePathTo(File file, File relativeTo) {
  if (!relativeTo.isDirectory()) {
    throw new IllegalArgumentException(
        "Requested a path relative to non-directory " + relativeTo);
  }

  File tmp = file;
  ArrayDeque<String> parts = new ArrayDeque<>();
  while (tmp != null && !tmp.getAbsolutePath().equals(relativeTo.getAbsolutePath())) {
    parts.addFirst(tmp.getName());
    tmp = tmp.getParentFile();
  }

  StringBuilder builder = new StringBuilder();
  while (!parts.isEmpty()) {
    builder.append(parts.removeFirst());
    if (!parts.isEmpty()) {
      builder.append(File.separator);
    }
  }

  return builder.toString();
}
 
Example 7
static int build(int size, int B, ArrayDeque<Integer> chunks) {
    chunks.addFirst(B);
    if (size < BOUND1) {
        chunks.addFirst(size);
        return size;
    }

    int asize = (size + 2) / 2;
    if (size >= BOUND2 && asize < BOUND1) {
        asize = BOUND1;
    } else if (size >= BOUND3 && asize < BOUND2) {
        asize = BOUND2;
    } else if (size >= BOUND4 && asize < BOUND3) {
        asize = BOUND3;
    } else if (size >= BOUND5 && asize < BOUND4) {
        asize = BOUND4;
    }
    if (size - asize >= B) {
        throw new AssertionError(" " + size + " , " + asize + " , " + B);
    }
    return build(asize, size - asize, chunks);
}
 
Example 8
Source Project: NullAway   File: NullAwayNativeModels.java    License: MIT License 6 votes vote down vote up
static void arrayDequeStuff() {
  ArrayDeque<Object> d = new ArrayDeque<>();
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.add(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.addFirst(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.addLast(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.offerFirst(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.offerLast(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.offer(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.push(null);
  Object[] o = null;
  // BUG: Diagnostic contains: passing @Nullable parameter 'o' where @NonNull is required
  d.toArray(o);
  // this should be fine
  d.toArray();
}
 
Example 9
Source Project: bazel   File: PathLabelVisitor.java    License: Apache License 2.0 6 votes vote down vote up
public Iterable<Target> somePath(
    ExtendedEventHandler eventHandler, Iterable<Target> from, Iterable<Target> to)
    throws NoSuchThingException, InterruptedException {
  Visitor visitor = new Visitor(eventHandler, VisitorMode.SOMEPATH);
  // TODO(ulfjack): It might be faster to stop the visitation once we see any 'to' Target.
  visitor.visitTargets(from);
  for (Target t : to) {
    if (visitor.hasVisited(t)) {
      ArrayDeque<Target> result = new ArrayDeque<>();
      Target at = t;
      // TODO(ulfjack): This can result in an infinite loop if there's a dependency cycle.
      while (true) {
        result.addFirst(at);
        List<Target> pred = visitor.getParents(at);
        if (pred == null) {
          break;
        }
        at = pred.get(0);
      }
      return result;
    }
  }
  return ImmutableList.of();
}
 
Example 10
static int build(int size, int B, ArrayDeque<Integer> chunks) {
    chunks.addFirst(B);
    if (size < BOUND1) {
        chunks.addFirst(size);
        return size;
    }

    int asize = (size + 2) / 2;
    if (size >= BOUND2 && asize < BOUND1) {
        asize = BOUND1;
    } else if (size >= BOUND3 && asize < BOUND2) {
        asize = BOUND2;
    } else if (size >= BOUND4 && asize < BOUND3) {
        asize = BOUND3;
    } else if (size >= BOUND5 && asize < BOUND4) {
        asize = BOUND4;
    }
    if (size - asize >= B) {
        throw new AssertionError(" " + size + " , " + asize + " , " + B);
    }
    return build(asize, size - asize, chunks);
}
 
Example 11
static int build(int size, int B, ArrayDeque<Integer> chunks) {
    chunks.addFirst(B);
    if (size < BOUND1) {
        chunks.addFirst(size);
        return size;
    }

    int asize = (size + 2) / 2;
    if (size >= BOUND2 && asize < BOUND1) {
        asize = BOUND1;
    } else if (size >= BOUND3 && asize < BOUND2) {
        asize = BOUND2;
    } else if (size >= BOUND4 && asize < BOUND3) {
        asize = BOUND3;
    } else if (size >= BOUND5 && asize < BOUND4) {
        asize = BOUND4;
    }
    if (size - asize >= B) {
        throw new AssertionError(" " + size + " , " + asize + " , " + B);
    }
    return build(asize, size - asize, chunks);
}
 
Example 12
Source Project: turbine   File: ConstEvaluator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Resolves the {@link ClassSymbol} for the given {@link Tree.ClassTy}, with handling for
 * non-canonical qualified type names.
 *
 * <p>Similar to {@code HierarchyBinder#resolveClass}, except we can't unconditionally consider
 * members of the current class (e.g. when binding constants inside annotations on that class),
 * and when we do want to consider members we can rely on them being in the current scope (it
 * isn't completed during the hierarchy phase).
 */
private Type resolveClass(ClassTy classTy) {
  ArrayDeque<Ident> flat = new ArrayDeque<>();
  for (ClassTy curr = classTy; curr != null; curr = curr.base().orElse(null)) {
    flat.addFirst(curr.name());
  }
  LookupResult result = scope.lookup(new LookupKey(ImmutableList.copyOf(flat)));
  if (result == null) {
    log.error(classTy.position(), ErrorKind.CANNOT_RESOLVE, flat.peekFirst());
    return Type.ErrorTy.create(flat);
  }
  if (result.sym().symKind() != Symbol.Kind.CLASS) {
    throw error(classTy.position(), ErrorKind.UNEXPECTED_TYPE_PARAMETER, flat.peekFirst());
  }
  ClassSymbol classSym = (ClassSymbol) result.sym();
  for (Ident bit : result.remaining()) {
    classSym = resolveNext(classTy.position(), classSym, bit);
  }
  return Type.ClassTy.asNonParametricClassTy(classSym);
}
 
Example 13
public void free(ByteBuffer bb)
{
	if (bb == null || !bb.isDirect())
		return;
	int actualCapacity = Integer.highestOneBit(bb.capacity());
	if (actualCapacity > _maxCachedBufferSize)
		return;
	ArrayDeque<ByteBuffer> bufQueue = _directBuffers.get()[getIdx(actualCapacity)];
	if (bufQueue.size() < _maxPoolSize)
	{
		bufQueue.addFirst(bb);
		// offerCount.getAndIncrement();
	}
}
 
Example 14
Source Project: beam   File: Networks.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of all distinct paths from roots of the network to leaves. The list can be in
 * arbitrary orders and can contain duplicate paths if there are multiple edges from two nodes.
 */
public static <NodeT, EdgeT> List<List<NodeT>> allPathsFromRootsToLeaves(
    Network<NodeT, EdgeT> network) {
  ArrayDeque<List<NodeT>> paths = new ArrayDeque<>();
  // Populate the list with all roots
  for (NodeT node : network.nodes()) {
    if (network.inDegree(node) == 0) {
      paths.add(ImmutableList.of(node));
    }
  }

  List<List<NodeT>> distinctPathsFromRootsToLeaves = new ArrayList<>();
  while (!paths.isEmpty()) {
    List<NodeT> path = paths.removeFirst();
    NodeT lastNode = path.get(path.size() - 1);
    if (network.outDegree(lastNode) == 0) {
      distinctPathsFromRootsToLeaves.add(new ArrayList<>(path));
    } else {
      for (EdgeT edge : network.outEdges(lastNode)) {
        paths.addFirst(
            ImmutableList.<NodeT>builder()
                .addAll(path)
                .add(network.incidentNodes(edge).target())
                .build());
      }
    }
  }
  return distinctPathsFromRootsToLeaves;
}
 
Example 15
Source Project: j2objc   File: ArrayDequeTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * addFirst(null) throws NPE
 */
public void testAddFirstNull() {
    ArrayDeque q = new ArrayDeque();
    try {
        q.addFirst(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 16
Source Project: beam   File: Networks.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of all distinct paths from roots of the network to leaves. The list can be in
 * arbitrary orders and can contain duplicate paths if there are multiple edges from two nodes.
 */
public static <NodeT, EdgeT> List<List<NodeT>> allPathsFromRootsToLeaves(
    Network<NodeT, EdgeT> network) {
  ArrayDeque<List<NodeT>> paths = new ArrayDeque<>();
  // Populate the list with all roots
  for (NodeT node : network.nodes()) {
    if (network.inDegree(node) == 0) {
      paths.add(ImmutableList.of(node));
    }
  }

  List<List<NodeT>> distinctPathsFromRootsToLeaves = new ArrayList<>();
  while (!paths.isEmpty()) {
    List<NodeT> path = paths.removeFirst();
    NodeT lastNode = path.get(path.size() - 1);
    if (network.outDegree(lastNode) == 0) {
      distinctPathsFromRootsToLeaves.add(new ArrayList<>(path));
    } else {
      for (EdgeT edge : network.outEdges(lastNode)) {
        paths.addFirst(
            ImmutableList.<NodeT>builder()
                .addAll(path)
                .add(network.incidentNodes(edge).target())
                .build());
      }
    }
  }
  return distinctPathsFromRootsToLeaves;
}
 
Example 17
Source Project: flink   File: BufferStorageTestBase.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testSpillWhileReading() throws IOException {
	final int sequences = 10;

	final Random rnd = new Random();

	final int maxNumEventsAndBuffers = 300;
	final int maxNumChannels = 1656;

	ArrayDeque<ArrayDeque<BufferOrEvent>> expectedRolledSequences = new ArrayDeque<>();
	ArrayDeque<BufferOrEvent> expectedPendingSequence = new ArrayDeque<>();

	BufferStorage bufferStorage = createBufferStorage();

	// do multiple spilling / rolling over rounds
	for (int round = 0; round < 2 * sequences; round++) {

		if (round % 2 == 1) {
			// make this an empty sequence
			bufferStorage.rollOver();
			expectedRolledSequences.addFirst(expectedPendingSequence);
			expectedPendingSequence = new ArrayDeque<>();
		} else {
			// proper spilled sequence
			final long bufferSeed = rnd.nextLong();
			final Random bufferRnd = new Random(bufferSeed);

			final int numEventsAndBuffers = rnd.nextInt(maxNumEventsAndBuffers) + 1;
			final int numberOfChannels = rnd.nextInt(maxNumChannels) + 1;

			final ArrayList<BufferOrEvent> events = new ArrayList<>(128);

			int generated = 0;
			while (generated < numEventsAndBuffers) {

				if (rnd.nextDouble() < 0.5) {
					// add a new record
					boolean isEvent = rnd.nextDouble() < 0.05;
					BufferOrEvent evt;
					if (isEvent) {
						evt = generateRandomEvent(rnd, numberOfChannels);
						events.add(evt);
					} else {
						evt = generateRandomBuffer(bufferRnd.nextInt(PAGE_SIZE) + 1, bufferRnd.nextInt(numberOfChannels));
					}
					bufferStorage.add(evt);

					expectedPendingSequence.addLast(evt);
					generated++;
				} else {
					// consume a record
					bufferStorage.rollOver();
					expectedRolledSequences.addFirst(expectedPendingSequence);
					expectedPendingSequence = new ArrayDeque<>();

					assertNextBufferOrEvent(expectedRolledSequences, bufferStorage);
				}
			}
			bufferStorage.rollOver();
			expectedRolledSequences.addFirst(expectedPendingSequence);
			expectedPendingSequence = new ArrayDeque<>();
		}
	}

	// consume all the remainder
	while (!expectedRolledSequences.isEmpty()) {
		assertNextBufferOrEvent(expectedRolledSequences, bufferStorage);
	}
}
 
Example 18
private void sampleForIteration(
    AnomalyDetector detector,
    Map<Long, double[]> cache,
    int maxSamples,
    long endTime,
    long span,
    int stride,
    ArrayDeque<double[]> sampledFeatures,
    boolean isInterpolatable,
    int iteration,
    ActionListener<Optional<double[][]>> listener
) {
    if (iteration < maxSamples) {
        long end = endTime - span * stride * iteration;
        if (cache.containsKey(end)) {
            sampledFeatures.addFirst(cache.get(end));
            sampleForIteration(
                detector,
                cache,
                maxSamples,
                endTime,
                span,
                stride,
                sampledFeatures,
                isInterpolatable,
                iteration + 1,
                listener
            );
        } else {
            getFeaturesForPeriod(detector, end - span, end, ActionListener.wrap(features -> {
                if (features.isPresent()) {
                    cache.put(end, features.get());
                    sampledFeatures.addFirst(features.get());
                    sampleForIteration(
                        detector,
                        cache,
                        maxSamples,
                        endTime,
                        span,
                        stride,
                        sampledFeatures,
                        isInterpolatable,
                        iteration + 1,
                        listener
                    );
                } else if (isInterpolatable) {
                    Optional<double[]> previous = Optional.ofNullable(cache.get(end - span * stride));
                    Optional<double[]> next = Optional.ofNullable(cache.get(end + span * stride));
                    if (previous.isPresent() && next.isPresent()) {
                        double[] interpolants = getInterpolants(previous.get(), next.get());
                        cache.put(end, interpolants);
                        sampledFeatures.addFirst(interpolants);
                        sampleForIteration(
                            detector,
                            cache,
                            maxSamples,
                            endTime,
                            span,
                            stride,
                            sampledFeatures,
                            isInterpolatable,
                            iteration + 1,
                            listener
                        );
                    } else {
                        listener.onResponse(toMatrix(sampledFeatures));
                    }
                } else {
                    listener.onResponse(toMatrix(sampledFeatures));
                }
            }, listener::onFailure));
        }
    } else {
        listener.onResponse(toMatrix(sampledFeatures));
    }
}
 
Example 19
/**
 * Returns a new deque of given size containing consecutive
 * Integers 0 ... n - 1.
 */
private static ArrayDeque<Integer> populatedDeque(int n) {
    // Randomize various aspects of memory layout, including
    // capacity slop and wraparound.
    final ArrayDeque<Integer> q;
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    switch (rnd.nextInt(6)) {
    case 0: q = new ArrayDeque<Integer>();      break;
    case 1: q = new ArrayDeque<Integer>(0);     break;
    case 2: q = new ArrayDeque<Integer>(1);     break;
    case 3: q = new ArrayDeque<Integer>(Math.max(0, n - 1)); break;
    case 4: q = new ArrayDeque<Integer>(n);     break;
    case 5: q = new ArrayDeque<Integer>(n + 1); break;
    default: throw new AssertionError();
    }
    switch (rnd.nextInt(3)) {
    case 0:
        q.addFirst(42);
        assertEquals((Integer) 42, q.removeLast());
        break;
    case 1:
        q.addLast(42);
        assertEquals((Integer) 42, q.removeFirst());
        break;
    case 2: /* do nothing */ break;
    default: throw new AssertionError();
    }
    assertTrue(q.isEmpty());
    if (rnd.nextBoolean())
        for (int i = 0; i < n; i++)
            assertTrue(q.offerLast((Integer) i));
    else
        for (int i = n; --i >= 0; )
            q.addFirst((Integer) i);
    assertEquals(n, q.size());
    if (n > 0) {
        assertFalse(q.isEmpty());
        assertEquals((Integer) 0, q.peekFirst());
        assertEquals((Integer) (n - 1), q.peekLast());
    }
    return q;
}
 
Example 20
/**
 * Gets a routing result.
 * 
 * @param mode				The mode in which to operate. <code>0</code> means calculating with street lengths, <code>1</code> means calculating based on speed/time 
 * @param direction			<code>0</code>=don't care about direction, <code>-1</code>=from startNode to endNode, <code>1</code>=from endNode to startNode
 * @param startX			the x coordinate of the start point
 * @param startY			the y coordinate of the start point
 * @param startStreet		the street on which the start point lies
 * @param startStreetPos	the position measured in cm from the startNode of the <code>startStreet</code>
 * @param targetX			the x coordinate of the target point
 * @param targetY			the y coordinate of the target point
 * @param targetStreet		the street on which the target point lies
 * @param targetStreetPos	the position measured in cm from the startNode of the <code>targetStreet</code>
 * @param penaltyStreets	an array with all streets which have penalties.
 * @param penaltyDirections	an array with directions corresponding to penaltyStreets. <code>1</code> in the array means from endNode to startNode, 
 * 							<code>0</code> means both directions and <code>-1</code> means from startNode to endNode
 * @param penalties			an array with all penalties measured in cm.
 * @param penaltySize		how many penalties exist.
 * @param additionalVar		can be used to set the maximum speed for calculations in <code>mode=1</code>
 *
 * 
 * @return An <code>ArrayDeque</code> for returning the result. The first element will be the start node and the last will be the end node of the routing.
 * 
 * @see	vanetsim.routing.RoutingAlgorithm#getRouting(int, int, int, int, Street, double, int, int, Street, double, Street[], int[], int[], int, int)
 */
public ArrayDeque<Node> getRouting(int mode, int direction, int startX, int startY, Street startStreet, double startStreetPos, int targetX, int targetY, Street targetStreet, double targetStreetPos, Street[] penaltyStreets, int[] penaltyDirections, int[] penalties, int penaltySize, int additionalVar){
	A_Star_Node curNode = computeRoute(mode, direction, startStreet, startStreetPos, targetX, targetY, targetStreet, targetStreetPos, penaltyStreets, penaltyDirections, penalties, penaltySize, additionalVar);
	ArrayDeque<Node> result = new ArrayDeque<Node>(255);
	while(curNode != null){
		result.addFirst(curNode.getRealNode());
		curNode = curNode.getPredecessor();
	}
	return result;
}