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

The following examples show how to use java.util.Deque#contains() . 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: JavaDequeue.java    From Hackerrank-Solutions with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	Deque<Integer> dq = new ArrayDeque<Integer>();
	HashSet<Integer> s = new HashSet<Integer>();
	int n = sc.nextInt();
	int m = sc.nextInt();
	int max = 0;
	for (int i = 0; i < n; i++) {
		int tmp = sc.nextInt();
		dq.add(tmp);
		s.add(tmp);

		if (dq.size() == m) {
			max = Math.max(s.size(), max);
			int item = dq.remove();
			if (!dq.contains(item)) {
				s.remove(item);
			}
		}
	}
	System.out.println(max);
	sc.close();
}
 
Example 2
Source File: BaseOperatorPlan.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * Move everything below a given operator to the new operator plan.  The specified operator will
 * be moved and will be the root of the new operator plan
 * @param root Operator to move everything after
 * @param newPlan new operator plan to move things into
 * @throws PlanException 
 */
public void moveTree(Operator root, BaseOperatorPlan newPlan) throws FrontendException {
    Deque<Operator> queue = new ArrayDeque<Operator>();
    newPlan.add(root);
    root.setPlan(newPlan);
    queue.addLast(root);
    while (!queue.isEmpty()) {
        Operator node = queue.poll();
        if (getSuccessors(node)!=null) {
            for (Operator succ : getSuccessors(node)) {
                if (!queue.contains(succ)) {
                    queue.addLast(succ);
                    newPlan.add(succ);
                    succ.setPlan(newPlan);
                    newPlan.connect(node, succ);
                }
            }
        }
    }

    trimBelow(root);
}
 
Example 3
Source File: ModuleSorter.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void visit(ResourcePoolModule node,
                   Deque<ResourcePoolModule> visited,
                   Deque<ResourcePoolModule> done) {
    if (visited.contains(node)) {
        if (!done.contains(node)) {
            throw new IllegalArgumentException("Cyclic detected: " +
                node + " " + edges.get(node.name()));
        }
        return;
    }
    visited.add(node);
    edges.get(node.name())
         .forEach(x -> visit(x, visited, done));
    done.add(node);
    result.addLast(node);
}
 
Example 4
Source File: ModuleHashesBuilder.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void sort() {
    Deque<T> visited = new LinkedList<>();
    Deque<T> done = new LinkedList<>();
    T node;
    while ((node = nodes.poll()) != null) {
        if (!visited.contains(node)) {
            visit(node, visited, done);
        }
    }
}
 
Example 5
Source File: ReferenceNode.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder toString(StringBuilder string, SerializationContext context, Deque<String> path, CompositeNode parent) {
    // A reference to an identifier (function argument or bound variable)?
    if (reference.isIdentifier() && context.getBinding(getName()) != null) {
        // a bound identifier: replace by the value it is bound to
        return string.append(context.getBinding(getName()));
    }

    // A reference to a function?
    ExpressionFunction function = context.getFunction(getName());
    if (function != null && function.arguments().size() == getArguments().size() && getOutput() == null) {
        // a function reference: replace by the referenced function wrapped in rankingExpression
        if (path == null)
            path = new ArrayDeque<>();
        String myPath = getName() + getArguments().expressions();
        if (path.contains(myPath))
            throw new IllegalStateException("Cycle in ranking expression function: " + path);
        path.addLast(myPath);

        String functionName = getName();
        String functionPropertyName = RankingExpression.propertyName(functionName);
        boolean alreadySerialized = context.serializedFunctions().containsKey(functionPropertyName);

        if ( ! alreadySerialized || getArguments().size() > 0) {
            ExpressionFunction.Instance instance = function.expand(context, getArguments().expressions(), path);
            functionName = instance.getName();

            context.addFunctionSerialization(RankingExpression.propertyName(functionName), instance.getExpressionString());
            for (Map.Entry<String, TensorType> argumentType : function.argumentTypes().entrySet())
                context.addArgumentTypeSerialization(functionName, argumentType.getKey(), argumentType.getValue());
            if (function.returnType().isPresent())
                context.addFunctionTypeSerialization(functionName, function.returnType().get());
        }
        path.removeLast();
        return string.append("rankingExpression(").append(functionName).append(')');
    }

    // Not resolved in this context: output as-is
    return reference.toString(string, context, path, parent);
}
 
Example 6
Source File: Tracer.java    From wingtips with Apache License 2.0 5 votes vote down vote up
/**
 * @return the given span's *current* status relative to this {@link Tracer} on the current thread at the time this
 * method is called. This status is recalculated every time this method is called and is only relevant/correct until
 * this {@link Tracer}'s state is modified (i.e. by starting a subspan, completing a span, using any of the
 * asynchronous helper methods to modify the span stack in any way, etc), so it should only be considered relevant
 * for the moment the call is made.
 *
 * <p>NOTE: Most app-level developers should not need to worry about this at all.
 *
 * @see TracerManagedSpanStatus
 */
public TracerManagedSpanStatus getCurrentManagedStatusForSpan(Span span) {
    // See if this span is the current span.
    if (span.equals(getCurrentSpan())) {
        // This is the current span. It is therefore managed. Now we just need to see if it's the root span or
        //      a subspan. If the span stack size is 1 then it's the root span, otherwise it's a subspan.
        if (getCurrentSpanStackSize() == 1) {
            // It's the root span.
            return TracerManagedSpanStatus.MANAGED_CURRENT_ROOT_SPAN;
        }
        else {
            // It's a subspan.
            return TracerManagedSpanStatus.MANAGED_CURRENT_SUB_SPAN;
        }
    }
    else {
        // This is not the current span - find out if it's managed or unmanaged.
        Deque<Span> currentSpanStack = currentSpanStackThreadLocal.get();
        if (currentSpanStack != null && currentSpanStack.contains(span)) {
            // It's on the stack, therefore it's managed. Now we just need to find out if it's the root span or not.
            if (span.equals(currentSpanStack.peekLast())) {
                // It is the root span.
                return TracerManagedSpanStatus.MANAGED_NON_CURRENT_ROOT_SPAN;
            }
            else {
                // It is a subspan.
                return TracerManagedSpanStatus.MANAGED_NON_CURRENT_SUB_SPAN;
            }
        }
        else {
            // This span is not in Tracer's current span stack at all, therefore it is unmanaged.
            return TracerManagedSpanStatus.UNMANAGED_SPAN;
        }
    }
}
 
Example 7
Source File: SimpleTemplate.java    From sample-apps with Apache License 2.0 5 votes vote down vote up
private void render(PrintWriter writer, String template, Deque<String> stack) {
    Matcher m = pattern.matcher(template);
    int start = 0;
    while (m.find(start)) {
        writer.print(template.substring(start, m.start()));
        String tag = m.group(1);
        if (values.containsKey(tag) && ! stack.contains(tag)) {  // try to avoid infinite recursion
            stack.push(tag);
            render(writer, values.get(tag), stack);
            stack.pop();
        }
        start = m.end();
    }
    writer.print(template.substring(start));
}
 
Example 8
Source File: SimpleTemplate.java    From sample-apps with Apache License 2.0 5 votes vote down vote up
private void render(PrintWriter writer, String template, Deque<String> stack) {
    Matcher m = pattern.matcher(template);
    int start = 0;
    while (m.find(start)) {
        writer.print(template.substring(start, m.start()));
        String tag = m.group(1);
        if (values.containsKey(tag) && ! stack.contains(tag)) {  // try to avoid infinite recursion
            stack.push(tag);
            render(writer, values.get(tag), stack);
            stack.pop();
        }
        start = m.end();
    }
    writer.print(template.substring(start));
}
 
Example 9
Source File: ModuleSorter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private synchronized void build() {
    if (!result.isEmpty() || nodes.isEmpty())
        return;

    Deque<ResourcePoolModule> visited = new LinkedList<>();
    Deque<ResourcePoolModule> done = new LinkedList<>();
    ResourcePoolModule node;
    while ((node = nodes.poll()) != null) {
        if (!visited.contains(node)) {
            visit(node, visited, done);
        }
    }
}
 
Example 10
Source File: ModuleHashesBuilder.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 11
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 12
Source File: Graph.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void sort() {
    Deque<T> visited = new LinkedList<>();
    Deque<T> done = new LinkedList<>();
    T node;
    while ((node = nodes.poll()) != null) {
        if (!visited.contains(node)) {
            visit(node, visited, done);
        }
    }
}
 
Example 13
Source File: ModuleHashesBuilder.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private void visit(T node, Set<T> visited, Deque<T> stack) {
    if (visited.add(node)) {
        stack.push(node);
        children(node).forEach(child -> visit(child, visited, stack));
        stack.pop();
        result.addLast(node);
    }
    else if (stack.contains(node)) {
        throw new IllegalArgumentException(
            "Cycle detected: " + node + " -> " + children(node));
    }
}
 
Example 14
Source File: ThriftCatalog.java    From drift with Apache License 2.0 5 votes vote down vote up
private ThriftStructMetadata extractThriftUnionMetadata(Type unionType)
{
    requireNonNull(unionType, "unionType is null");

    Deque<Type> stack = this.stack.get();
    if (stack.contains(unionType)) {
        String path = Stream.concat(stack.stream(), Stream.of(unionType))
                .map(type -> TypeToken.of(type).getRawType().getName())
                .collect(joining("->"));
        throw new IllegalArgumentException(
                "Circular references must be qualified with 'isRecursive' on a @ThriftField annotation in the cycle: " + path);
    }

    stack.push(unionType);
    try {
        ThriftUnionMetadataBuilder builder = new ThriftUnionMetadataBuilder(this, unionType);
        return builder.build();
    }
    finally {
        Type top = stack.pop();
        checkState(
                unionType.equals(top),
                "ThriftCatalog circularity detection stack is corrupt: expected %s, but got %s",
                unionType,
                top);
    }
}
 
Example 15
Source File: ThriftCatalog.java    From drift with Apache License 2.0 5 votes vote down vote up
private ThriftStructMetadata extractThriftStructMetadata(Type structType)
{
    requireNonNull(structType, "structType is null");

    Deque<Type> stack = this.stack.get();
    if (stack.contains(structType)) {
        String path = Stream.concat(stack.stream(), Stream.of(structType))
                .map(type -> TypeToken.of(type).getRawType().getName())
                .collect(joining("->"));
        throw new IllegalArgumentException(
                "Circular references must be qualified with 'isRecursive' on a @ThriftField annotation in the cycle: " + path);
    }
    else {
        stack.push(structType);

        try {
            ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(this, structType);
            return builder.build();
        }
        finally {
            Type top = stack.pop();
            checkState(
                    structType.equals(top),
                    "ThriftCatalog circularity detection stack is corrupt: expected %s, but got %s",
                    structType,
                    top);
        }
    }
}
 
Example 16
Source File: BindingGraphValidator.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
/**
 * Validates that scopes do not participate in a scoping cycle - that is to say, scoped
 * components are in a hierarchical relationship terminating with Singleton.
 *
 * <p>As a side-effect, this means scoped components cannot have a dependency cycle between
 * themselves, since a component's presence within its own dependency path implies a cyclical
 * relationship between scopes.
 */
private void validateScopeHierarchy(TypeElement rootComponent,
    TypeElement componentType,
    Builder<BindingGraph> reportBuilder,
    Deque<Equivalence.Wrapper<AnnotationMirror>> scopeStack,
    Deque<TypeElement> scopedDependencyStack) {
  Optional<AnnotationMirror> scope = getScopeAnnotation(componentType);
  if (scope.isPresent()) {
    Equivalence.Wrapper<AnnotationMirror> wrappedScope =
        AnnotationMirrors.equivalence().wrap(scope.get());
    if (scopeStack.contains(wrappedScope)) {
      scopedDependencyStack.push(componentType);
      // Current scope has already appeared in the component chain.
      StringBuilder message = new StringBuilder();
      message.append(rootComponent.getQualifiedName());
      message.append(" depends on scoped components in a non-hierarchical scope ordering:\n");
      appendIndentedComponentsList(message, scopedDependencyStack);
      if (scopeCycleValidationType.diagnosticKind().isPresent()) {
        reportBuilder.addItem(message.toString(),
            scopeCycleValidationType.diagnosticKind().get(),
            rootComponent, getAnnotationMirror(rootComponent, Component.class).get());
      }
      scopedDependencyStack.pop();
    } else {
      Optional<AnnotationMirror> componentAnnotation =
          getAnnotationMirror(componentType, Component.class);
      if (componentAnnotation.isPresent()) {
        ImmutableSet<TypeElement> scopedDependencies = scopedTypesIn(
            MoreTypes.asTypeElements(getComponentDependencies(componentAnnotation.get())));
        if (scopedDependencies.size() == 1) {
          // empty can be ignored (base-case), and > 1 is a different error reported separately.
          scopeStack.push(wrappedScope);
          scopedDependencyStack.push(componentType);
          validateScopeHierarchy(rootComponent, getOnlyElement(scopedDependencies),
              reportBuilder, scopeStack, scopedDependencyStack);
          scopedDependencyStack.pop();
          scopeStack.pop();
        }
      } // else: we skip component dependencies which are not components
    }
  }
}
 
Example 17
Source File: PropertiesConfiguration.java    From commons-configuration with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method for loading an included properties file. This method is
 * called by {@code load()} when an {@code include} property
 * is encountered. It tries to resolve relative file names based on the
 * current base path. If this fails, a resolution based on the location of
 * this properties file is tried.
 *
 * @param fileName the name of the file to load
 * @param optional whether or not the {@code fileName} is optional
 * @param seenStack Stack of seen include URLs
 * @throws ConfigurationException if loading fails
 */
private void loadIncludeFile(final String fileName, final boolean optional, final Deque<URL> seenStack)
        throws ConfigurationException
{
    if (locator == null)
    {
        throw new ConfigurationException("Load operation not properly "
                + "initialized! Do not call read(InputStream) directly,"
                + " but use a FileHandler to load a configuration.");
    }

    URL url = locateIncludeFile(locator.getBasePath(), fileName);
    if (url == null)
    {
        final URL baseURL = locator.getSourceURL();
        if (baseURL != null)
        {
            url = locateIncludeFile(baseURL.toString(), fileName);
        }
    }

    if (optional && url == null)
    {
        return;
    }

    if (url == null)
    {
        getIncludeListener().accept(new ConfigurationException("Cannot resolve include file " + fileName,
                new FileNotFoundException(fileName)));
    }
    else
    {
        final FileHandler fh = new FileHandler(this);
        fh.setFileLocator(locator);
        final FileLocator orgLocator = locator;
        try
        {
            try
            {
                // Check for cycles
                if (seenStack.contains(url))
                {
                    throw new ConfigurationException(
                            String.format("Cycle detected loading %s, seen stack: %s", url, seenStack));
                }
                seenStack.add(url);
                try
                {
                    fh.load(url);
                }
                finally
                {
                    seenStack.pop();
                }
            }
            catch (ConfigurationException e)
            {
                getIncludeListener().accept(e);
            }
        }
        finally
        {
            locator = orgLocator; // reset locator which is changed by load
        }
    }
}
 
Example 18
Source File: ComMailingBaseServiceImpl.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean isContentBlank(String content, Map<String, DynamicTag> contentMap, Deque<String> visitedDynBlocks) {
    if (StringUtils.isBlank(content)) {
        return true;
    }

    List<DynamicTag> tags = getDynamicTags(content);

    // Check if there's at least one non-whitespace character between (!) dyn-tags.
    if (!isOwnContentBlank(content, tags)) {
        return false;
    }

    // Check if at least one dyn-tag can be resolved as non-blank content.
    for (DynamicTag tag : tags) {
        // Ignore dyn-tag if the cyclic dependency is detected.
        if (visitedDynBlocks.contains(tag.getDynName())) {
            continue;
        }

        DynamicTag dynamicTag = contentMap.get(tag.getDynName());

        if (dynamicTag != null) {
            List<DynamicTagContent> entries = new ArrayList<>(dynamicTag.getDynContent().values());

            // Make sure that entries are sorted by designed order — to ignore unreachable ones.
            entries.sort(Comparator.comparingInt(DynamicTagContent::getDynOrder));

            visitedDynBlocks.push(tag.getDynName());
            for (DynamicTagContent entry : entries) {
                // Check if this entry can be resolved as non-blank content.
                if (!isContentBlank(entry.getDynContent(), contentMap, visitedDynBlocks)) {
                    visitedDynBlocks.pop();
                    return false;
                }

                // Ignore unreachable entries (placed below "All recipients" entry).
                if (entry.getTargetID() <= 0) {
                    break;
                }
            }
            visitedDynBlocks.pop();
        }
    }

    return true;
}
 
Example 19
Source File: ReflectiveMessageValidator.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Validate all fields of the given object.
 */
protected void validate(Object object, List<MessageIssue> issues, Deque<Object> objectStack, Deque<Object> accessorStack) throws Exception {
	if (object == null 
			|| object instanceof Enum<?> 
			|| object instanceof String 
			|| object instanceof Number
			|| object instanceof Boolean
			|| object instanceof JsonElement
			|| object instanceof Throwable) {
		return;
	}
	if (objectStack.contains(object)) {
		issues.add(new MessageIssue("An element of the message has a direct or indirect reference to itself."
				+ " Path: " + createPathString(accessorStack),
				ResponseErrorCode.InvalidParams.getValue()));
		return;
	}
	objectStack.push(object);
	if (object instanceof List<?>) {
		ListIterator<?> iter = ((List<?>) object).listIterator();
		while (iter.hasNext()) {
			accessorStack.push(iter.nextIndex());
			Object element = iter.next();
			if (element == null) {
				issues.add(new MessageIssue("Lists must not contain null references."
						+ " Path: " + createPathString(accessorStack),
						ResponseErrorCode.InvalidParams.getValue()));
			}
			validate(element, issues, objectStack, accessorStack);
			accessorStack.pop();
		}
	} else if (object instanceof Either<?, ?>) {
		Either<?, ?> either = (Either<?, ?>) object;
		if (either.isLeft()) {
			validate(either.getLeft(), issues, objectStack, accessorStack);
		} else if (either.isRight()) {
			validate(either.getRight(), issues, objectStack, accessorStack);
		} else {
			issues.add(new MessageIssue("An Either instance must not be empty."
					 + " Path: " + createPathString(accessorStack),
					ResponseErrorCode.InvalidParams.getValue()));
		}
	} else {
		for (Method method : object.getClass().getMethods()) {
			if (isGetter(method)) {
				accessorStack.push(method);
				Object value = method.invoke(object);
				if (value == null && method.getAnnotation(NonNull.class) != null) {
					issues.add(new MessageIssue("The accessor '" + method.getDeclaringClass().getSimpleName()
							 + "." + method.getName() + "()' must return a non-null value."
							 + " Path: " + createPathString(accessorStack),
							ResponseErrorCode.InvalidParams.getValue()));
				}
				validate(value, issues, objectStack, accessorStack);
				accessorStack.pop();
			}
		}
	}
	objectStack.pop();
}
 
Example 20
Source File: OrphanChainsMonitor.java    From nuls-v2 with MIT License 2 votes vote down vote up
/**
 * 判断subChain是否与mainChain重复
 *
 * @param mainChain
 * @param subChain
 * @return
 */
private boolean tryDuplicate(Chain mainChain, Chain subChain) {
    Deque<NulsHash> mainChainHashList = mainChain.getHashList();
    return mainChainHashList.contains(subChain.getEndHash()) && mainChainHashList.contains(subChain.getStartHash());
}