Java Code Examples for java.util.Deque#add()

The following examples show how to use java.util.Deque#add() . 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 File: TestAnd.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 1000)
public void testStopFirst() throws IOException {
  And and = new And();

  PathData pathData = mock(PathData.class);

  Expression first = mock(Expression.class);
  when(first.apply(pathData, -1)).thenReturn(Result.STOP);

  Expression second = mock(Expression.class);
  when(second.apply(pathData, -1)).thenReturn(Result.PASS);

  Deque<Expression> children = new LinkedList<Expression>();
  children.add(second);
  children.add(first);
  and.addChildren(children);

  assertEquals(Result.STOP, and.apply(pathData, -1));
  verify(first).apply(pathData, -1);
  verify(second).apply(pathData, -1);
  verifyNoMoreInteractions(first);
  verifyNoMoreInteractions(second);
}
 
Example 2
Source File: TupleExprs.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verifies if the supplied {@link TupleExpr} contains a {@link Projection} with the subquery flag set to true
 * (default). If the supplied TupleExpr is a {@link Join} or contains a {@link Join}, projections inside that Join's
 * arguments will not be taken into account.
 *
 * @param t a tuple expression.
 * @return <code>true</code> if the TupleExpr contains a subquery projection (outside of a Join), <code>false</code>
 *         otherwise.
 */
public static boolean containsSubquery(TupleExpr t) {
	Deque<TupleExpr> queue = new ArrayDeque<>();
	queue.add(t);
	while (!queue.isEmpty()) {
		TupleExpr n = queue.removeFirst();
		if (n instanceof Projection && ((Projection) n).isSubquery()) {
			return true;
		} else if (n instanceof Join) {
			// projections already inside a Join need not be
			// taken into account
			return false;
		} else {
			queue.addAll(getChildren(n));
		}
	}
	return false;
}
 
Example 3
Source File: InternalSpelExpressionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Eat an identifier, possibly qualified (meaning that it is dotted).
 * TODO AndyC Could create complete identifiers (a.b.c) here rather than a sequence of them? (a, b, c)
 */
private SpelNodeImpl eatPossiblyQualifiedId() {
	Deque<SpelNodeImpl> qualifiedIdPieces = new ArrayDeque<>();
	Token node = peekToken();
	while (isValidQualifiedId(node)) {
		nextToken();
		if (node.kind != TokenKind.DOT) {
			qualifiedIdPieces.add(new Identifier(node.stringValue(), toPos(node)));
		}
		node = peekToken();
	}
	if (qualifiedIdPieces.isEmpty()) {
		if (node == null) {
			throw internalException( this.expressionString.length(), SpelMessage.OOD);
		}
		throw internalException(node.startPos, SpelMessage.NOT_EXPECTED_TOKEN,
				"qualified ID", node.getKind().toString().toLowerCase());
	}
	int pos = toPos(qualifiedIdPieces.getFirst().getStartPosition(), qualifiedIdPieces.getLast().getEndPosition());
	return new QualifiedIdentifier(pos, qualifiedIdPieces.toArray(new SpelNodeImpl[0]));
}
 
Example 4
Source File: SPARQLSyntaxComplianceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static Object[][] getTestData() {

		List<Object[]> tests = new ArrayList<>();

		Deque<String> manifests = new ArrayDeque<>();
		manifests.add(
				SPARQLSyntaxComplianceTest.class.getClassLoader()
						.getResource("testcases-sparql-1.1-w3c/manifest-all.ttl")
						.toExternalForm());
		while (!manifests.isEmpty()) {
			String pop = manifests.pop();
			SPARQLSyntaxManifest manifest = new SPARQLSyntaxManifest(pop);
			tests.addAll(manifest.tests);
			manifests.addAll(manifest.subManifests);
		}

		Object[][] result = new Object[tests.size()][6];
		tests.toArray(result);

		return result;
	}
 
Example 5
Source File: FeatureManager.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
private void updateUnprocessedFeatures(
    Optional<double[]> point,
    Deque<Entry<Long, double[]>> shingle,
    AnomalyDetector detector,
    long endTime,
    ActionListener<SinglePointFeatures> listener
) {
    if (point.isPresent()) {
        if (shingle.size() == shingleSize) {
            shingle.remove();
        }
        shingle.add(new SimpleImmutableEntry<>(endTime, point.get()));
        getProcessedFeatures(shingle, detector, endTime, listener);
    } else {
        listener.onResponse(new SinglePointFeatures(Optional.empty(), Optional.empty()));
    }
}
 
Example 6
Source File: PartiallyOrderedSet.java    From Quicksql with MIT License 5 votes vote down vote up
private List<E> descendants(E e, boolean up) {
  Node<E> node = map.get(e);
  final Collection<Node<E>> c;
  if (node == null) {
    c = up ? findChildren(e) : findParents(e);
  } else {
    c = up ? node.childList : node.parentList;
  }
  if (c.size() == 1 && c.iterator().next().e == null) {
    return Collections.emptyList();
  }
  final Deque<Node<E>> deque = new ArrayDeque<>(c);

  final Set<Node<E>> seen = new HashSet<>();
  final List<E> list = new ArrayList<>();
  while (!deque.isEmpty()) {
    Node<E> node1 = deque.pop();
    list.add(node1.e);
    for (Node<E> child : up ? node1.childList : node1.parentList) {
      if (child.e == null) {
        // Node is top or bottom.
        break;
      }
      if (seen.add(child)) {
        deque.add(child);
      }
    }
  }
  return list;
}
 
Example 7
Source File: BuildChainBuilder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void cycleCheckProduce(Set<Produce> produceSet, Set<BuildStepBuilder> visited, Set<BuildStepBuilder> checked,
        final Map<BuildStepBuilder, Set<Produce>> dependencies, final Deque<Produce> producedPath)
        throws ChainBuildException {
    for (Produce produce : produceSet) {
        producedPath.add(produce);
        cycleCheck(produce.getStepBuilder(), visited, checked, dependencies, producedPath);
        producedPath.removeLast();
    }
}
 
Example 8
Source File: ExtraLanguageFeatureNameConverter.java    From sarl with Apache License 2.0 5 votes vote down vote up
private FeatureReplacement matchFirstPattern(List<Pair<FeaturePattern, FeatureReplacement>> patterns,
		String source, String simpleName, List<Object> receiver) {
	final LinkedList<String> sourceFeature = new LinkedList<>();
	for (final Object obj : receiver) {
		loopReceiver(sourceFeature, obj);
	}
	sourceFeature.add(source);
	final boolean isSarlKeyword = this.sarlKeywords.getThisKeyword().equals(simpleName) || this.sarlKeywords.getSuperKeyword().equals(simpleName);
	final Deque<String> sarlKeyword;
	if (isSarlKeyword) {
		sarlKeyword = new LinkedList<>();
		sarlKeyword.add(simpleName);
	} else {
		sarlKeyword = null;
	}
	for (final Pair<FeaturePattern, FeatureReplacement> patternMatching : patterns) {
		final FeaturePattern pattern = patternMatching.getKey();
		if (pattern.isNameReplacement()) {
			if (isSarlKeyword && pattern.matches(sarlKeyword)) {
				return patternMatching.getValue();
			}
		} else if (pattern.matches(sourceFeature)) {
			return patternMatching.getValue();
		}
	}
	return null;
}
 
Example 9
Source File: SkyQueryUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a path from {@code from} to {@code to}, walking the graph revealed by {@code getFwdDeps}.
 *
 * <p>In case the type {@link T} does not implement equality, {@code label} will be used to map
 * elements of type {@link T} to elements of type {@link L} which does implement equality. {@code
 * label} should be an injective function. For instance, if {@link T} is of type {@link Target}
 * then {@link L} could be of type {@link Label} and {@code label} could be {@link
 * Target::getLabel}.
 *
 * <p>Implemented with a breadth-first search.
 */
static <T, L> ImmutableList<T> getNodesOnPath(
    T from, T to, GetFwdDeps<T> getFwdDeps, Function<T, L> label) throws InterruptedException {
  // Tree of nodes visited so far.
  Map<L, L> nodeToParent = new HashMap<>();
  Map<L, T> labelToTarget = new HashMap<>();
  // Contains all nodes left to visit in a (LIFO) stack.
  Deque<T> toVisit = new ArrayDeque<>();
  toVisit.add(from);
  nodeToParent.put(label.apply(from), null);
  labelToTarget.put(label.apply(from), from);
  while (!toVisit.isEmpty()) {
    T current = toVisit.removeFirst();
    if (label.apply(to).equals(label.apply(current))) {
      List<L> labelPath = Digraph.getPathToTreeNode(nodeToParent, label.apply(to));
      ImmutableList.Builder<T> targetPathBuilder = ImmutableList.builder();
      for (L item : labelPath) {
        targetPathBuilder.add(Preconditions.checkNotNull(labelToTarget.get(item), item));
      }
      return targetPathBuilder.build();
    }
    for (T dep : getFwdDeps.getFwdDeps(ImmutableList.of(current))) {
      L depLabel = label.apply(dep);
      if (!nodeToParent.containsKey(depLabel)) {
        nodeToParent.put(depLabel, label.apply(current));
        labelToTarget.put(depLabel, dep);
        toVisit.addFirst(dep);
      }
    }
  }
  // Note that the only current caller of this method checks first to see if there is a path
  // before calling this method. It is not clear what the return value should be here.
  return null;
}
 
Example 10
Source File: NBTReflectionUtil.java    From Crazy-Crates with MIT License 5 votes vote down vote up
protected static Object gettoCompount(Object nbttag, NBTCompound comp) {
    Deque<String> structure = new ArrayDeque<>();
    while (comp.getParent() != null) {
        structure.add(comp.getName());
        comp = comp.getParent();
    }
    while (!structure.isEmpty()) {
        String target = structure.pollLast();
        nbttag = getSubNBTTagCompound(nbttag, target);
        if (nbttag == null) {
            throw new NbtApiException("Unable to find tag '" + target + "' in " + nbttag);
        }
    }
    return nbttag;
}
 
Example 11
Source File: DynaFileManager.java    From kan-java with Eclipse Public License 1.0 5 votes vote down vote up
private Deque<String> resolvePkgPath(String pkg) {
    Deque<String> ret = new ArrayDeque<String>();
    if (pkg != null)
        for (String s : pkg.split("\\.")) {
            ret.add(s);
        }
    return ret;
}
 
Example 12
Source File: StepStorage.java    From allure1 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the current thread's "initial value". Construct an new
 * {@link java.util.Deque} with root step {@link #createRootStep()}
 *
 * @return the initial value for this thread-local
 */
@Override
protected Deque<Step> initialValue() {
    Deque<Step> queue = new LinkedList<>();
    queue.add(createRootStep());
    return queue;
}
 
Example 13
Source File: Algorithms.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static <T> Set<T> search(T root, AdjacencyFunction<T> generator, QueueManager<T> queueManager) {
	Deque<T> queue = new LinkedList<T>();
	Set<T> visited = new HashSet<T>();
	queue.add(root);
	while (!queue.isEmpty()) {
		T current = queue.poll();
		visited.add(current);
		for (T neighbor: generator.getAdjacentVertices(current)) {
			if (!visited.contains(neighbor)) {
				queueManager.add(queue, neighbor);
			}
		}
	}
	return visited;
}
 
Example 14
Source File: AssertStepsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
private void mockStoriesChain(RunningStory runningStory, RunningStory rootRunningStory)
{
    Deque<RunningStory> storiesChain = new ArrayDeque<>();
    storiesChain.add(rootRunningStory);
    storiesChain.addFirst(runningStory);
    when(bddRunContext.getStoriesChain()).thenReturn(storiesChain);
    when(bddRunContext.getRunningStory()).thenReturn(runningStory);
    when(bddRunContext.getRootRunningStory()).thenReturn(rootRunningStory);
}
 
Example 15
Source File: SearchBuilder.java    From gadtry with Apache License 2.0 5 votes vote down vote up
/**
 * 深度优先 Depth first
 */
private static <E, R> void searchByDepthFirst(
        Deque<Route<E, R>> routes,
        SearchContext<E, R> context,
        Route<E, R> beginNode)
{
    final Deque<Route<E, R>> nextNodes = new LinkedList<>();  //Stack
    nextNodes.add(beginNode);

    Route<E, R> route;
    while ((route = nextNodes.pollLast()) != null) {
        for (Edge<E, R> edge : route.getLastNode().nextNodes()) {   //use stream.parallel();
            Route<E, R> newRoute = route.copy().add(edge).create();
            context.setLastRoute(newRoute);

            if (context.getNextRule().apply(newRoute)) {
                routes.add(newRoute);
                nextNodes.add(newRoute);
            }

            if (!context.getGlobalRule().apply(context)) {
                nextNodes.clear();
                return;
            }
        }
    }
}
 
Example 16
Source File: DirectLinkingResourceStorageLoadable.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private Deque<EObject> readMappedEObjects(final DirectLinkingEObjectInputStream objIn, final StorageAwareResource resource) throws IOException {
  int collectionSize = objIn.readCompressedInt();
  Deque<EObject> deque = new ArrayDeque<>(collectionSize);
  for (int j = 0; j < collectionSize; j++) {
    EObject target = objIn.readEObject(resource);
    if (target != null) {
      deque.add(target);
    }
  }
  return deque;
}
 
Example 17
Source File: Graph.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void visit(T node, Deque<T> visited, Deque<T> done) {
    if (visited.contains(node)) {
        if (!done.contains(node)) {
            throw new IllegalArgumentException("Cyclic detected: " +
                node + " " + graph.edges().get(node));
        }
        return;
    }
    visited.add(node);
    graph.edges().get(node).stream()
        .forEach(x -> visit(x, visited, done));
    done.add(node);
    result.addLast(node);
}
 
Example 18
Source File: PartiallyOrderedSet.java    From Bats with Apache License 2.0 4 votes vote down vote up
private Set<Node<E>> findParents(E e) {
  final Deque<Node<E>> ancestors = new ArrayDeque<>();
  ancestors.add(topNode);
  return findParentsChildren(e, ancestors, true);
}
 
Example 19
Source File: AliasMethod.java    From DevUtils with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a new AliasMethod to sample from a discrete distribution and
 * hand back outcomes based on the probability distribution.
 * <p>
 * Given as input a list of probabilities corresponding to outcomes 0, 1,
 * ..., n - 1, along with the random number generator that should be used
 * as the underlying generator, this constructor creates the probability
 * and alias tables needed to efficiently sample from this distribution.
 * @param probabilities The list of probabilities.
 * @param random        The random number generator
 */
public AliasMethod(List<Double> probabilities, Random random) {
    /* Begin by doing basic structural checks on the inputs. */
    if (probabilities == null || random == null)
        throw new NullPointerException();
    if (probabilities.size() == 0)
        throw new IllegalArgumentException("Probability vector must be nonempty.");

    /* Allocate space for the probability and alias tables. */
    probability = new double[probabilities.size()];
    alias = new int[probabilities.size()];

    /* Store the underlying generator. */
    this.random = random;

    /* Compute the average probability and cache it for later use. */
    final double average = 1.0 / probabilities.size();

    /* Make a copy of the probabilities list, since we will be making
     * changes to it.
     */
    probabilities = new ArrayList<Double>(probabilities);

    /* Create two stacks to act as worklists as we populate the tables. */
    Deque<Integer> small = new ArrayDeque<>();
    Deque<Integer> large = new ArrayDeque<>();

    /* Populate the stacks with the input probabilities. */
    for (int i = 0; i < probabilities.size(); ++i) {
        /* If the probability is below the average probability, then we add
         * it to the small list; otherwise we add it to the large list.
         */
        if (probabilities.get(i) >= average)
            large.add(i);
        else
            small.add(i);
    }

    /* As a note: in the mathematical specification of the algorithm, we
     * will always exhaust the small list before the big list.  However,
     * due to floating point inaccuracies, this is not necessarily true.
     * Consequently, this inner loop (which tries to pair small and large
     * elements) will have to check that both lists aren't empty.
     */
    while (!small.isEmpty() && !large.isEmpty()) {
        /* Get the index of the small and the large probabilities. */
        int less = small.removeLast();
        int more = large.removeLast();

        /* These probabilities have not yet been scaled up to be such that
         * 1/n is given weight 1.0.  We do this here instead.
         */
        probability[less] = probabilities.get(less) * probabilities.size();
        alias[less] = more;

        /* Decrease the probability of the larger one by the appropriate
         * amount.
         */
        probabilities.set(more,
                (probabilities.get(more) + probabilities.get(less)) - average);

        /* If the new probability is less than the average, add it into the
         * small list; otherwise add it to the large list.
         */
        if (probabilities.get(more) >= 1.0 / probabilities.size())
            large.add(more);
        else
            small.add(more);
    }

    /* At this point, everything is in one list, which means that the
     * remaining probabilities should all be 1/n.  Based on this, set them
     * appropriately.  Due to numerical issues, we can't be sure which
     * stack will hold the entries, so we empty both.
     */
    while (!small.isEmpty())
        probability[small.removeLast()] = 1.0;
    while (!large.isEmpty())
        probability[large.removeLast()] = 1.0;
}
 
Example 20
Source File: CopyOnWriteHashMap.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
void visit(Deque<Map.Entry<K, V>> entries, Deque<Node<K, V>> nodes) {
    for (int i = 0; i < keys.length; ++i) {
        entries.add(new AbstractMap.SimpleImmutableEntry<>(keys[i], values[i]));
    }
}