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

The following examples show how to use java.util.Deque#removeFirst() . 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: XElement.java    From open-ig with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Iterate through the elements of this XElement and invoke the action for each.
 * @param depthFirst do a depth first search?
 * @param action the action to invoke, non-null
 */
public void visit(boolean depthFirst, Action1<XElement> action) {
	Deque<XElement> queue = new LinkedList<>();
	queue.add(this);
	while (!queue.isEmpty()) {
		XElement x = queue.removeFirst();
		action.invoke(x);
		if (depthFirst) {
			ListIterator<XElement> li = x.children.listIterator(x.children.size());
			while (li.hasPrevious()) {
				queue.addFirst(li.previous());
			}
		} else {
			for (XElement c : x.children) {
				queue.addLast(c);
			}
		}
	}
}
 
Example 2
Source File: Solution94.java    From LeetCodeSolution with Apache License 2.0 6 votes vote down vote up
private void inOrder(BinaryTreeNode op){
    if(op==null){
        return;
    }
    Deque<BinaryTreeNode> stack=new LinkedList<>();
    while(stack.size()!=0||op!=null){
        while(op!=null){
            stack.addFirst(op);
            op=op.left;
        }
        if(stack.size()!=0){
            BinaryTreeNode node=stack.removeFirst();
            list.add(node.val);
            if(node.right!=null){
                op=node.right;
            }
        }
    }
}
 
Example 3
Source File: ParsingTester.java    From protoparser with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) {
  int total = 0;
  int failed = 0;

  Deque<File> fileQueue = new ArrayDeque<>();
  fileQueue.add(ROOT);
  while (!fileQueue.isEmpty()) {
    File file = fileQueue.removeFirst();
    if (file.isDirectory()) {
      Collections.addAll(fileQueue, file.listFiles());
    } else if (file.getName().endsWith(".proto")) {
      System.out.println("Parsing " + file.getPath());
      total += 1;

      try {
        ProtoParser.parseUtf8(file);
      } catch (Exception e) {
        e.printStackTrace();
        failed += 1;
      }
    }
  }

  System.out.println("\nTotal: " + total + "  Failed: " + failed);
}
 
Example 4
Source File: MappingExpr.java    From spectator with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate a simple stack expression for the value.
 *
 * @param expr
 *     Basic stack expression that supports placeholders, numeric constants,
 *     and basic binary operations (:add, :sub, :mul, :div).
 * @param vars
 *     Map of variable substitutions that are available.
 * @return
 *     Double value for the expression. If the expression cannot be evaluated
 *     properly, then null will be returned.
 */
@SuppressWarnings("PMD")
static Double eval(String expr, Map<String, ? extends Number> vars) {
  Deque<Double> stack = new ArrayDeque<>();
  String[] parts = expr.split("[,\\s]+");
  for (String part : parts) {
    switch (part) {
      case ":add":        binaryOp(stack, (a, b) -> a + b); break;
      case ":sub":        binaryOp(stack, (a, b) -> a - b); break;
      case ":mul":        binaryOp(stack, (a, b) -> a * b); break;
      case ":div":        binaryOp(stack, (a, b) -> a / b); break;
      case ":if-changed": ifChanged(stack);                 break;
      default:
        if (part.startsWith("{") && part.endsWith("}")) {
          Number v = vars.get(part.substring(1, part.length() - 1));
          if (v == null) v = Double.NaN;
          stack.addFirst(v.doubleValue());
        } else {
          stack.addFirst(Double.parseDouble(part));
        }
        break;
    }
  }
  return stack.removeFirst();
}
 
Example 5
Source File: CrossProduct.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
private void recurse(Deque<List<T>> remainder,
		Stack<T> current, ArrayList<List<T>> accumulation) {
	if(remainder.isEmpty()) {
		// all done:
		dump(new ArrayList<T>(current));
		accumulation.add(new ArrayList<T>(current));
		
	} else {
		List<T> cur = remainder.removeFirst();
		for(T o : cur) {
			current.push(o);
			recurse(remainder,current,accumulation);
			current.pop();
		}
		remainder.addFirst(cur);
	}
}
 
Example 6
Source File: Codec2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
private TreeNode buildTree(Deque<String> queue) {
    if (queue.isEmpty()) {
        return null;
    }
    String s = queue.removeFirst();
    if ("#".equals(s)) {
        return null;
    }

    TreeNode root = new TreeNode(Integer.parseInt(s));
    root.left = buildTree(queue);
    root.right = buildTree(queue);
    return root;
}
 
Example 7
Source File: NotificationAccumulator.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected Deque<T> tail(
        Consumer<? super T> observer,
        Deque<T> accumulatedValue) {
    accumulatedValue.removeFirst();
    return accumulatedValue;
}
 
Example 8
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * The compiler does not always preserve the concrete syntax of annotated array dimensions, and
 * mixed-notation array dimensions. Use look-ahead to preserve the original syntax.
 * <p>
 * <p>It is assumed that any number of regular dimension specifiers ({@code []} with no
 * annotations) may be present in the input.
 *
 * @param dimExpressions an ordered list of dimension expressions (e.g. the {@code 0} in {@code
 *                       new int[0]}
 * @param annotations    an ordered list of type annotations grouped by dimension (e.g. {@code
 *                       [[@A, @B], [@C]]} for {@code int @A [] @B @C []}
 */
private void maybeAddDims(
        Deque<ExpressionTree> dimExpressions, Deque<List<AnnotationTree>> annotations) {
    boolean lastWasAnnotation = false;
    while (builder.peekToken().isPresent()) {
        switch (builder.peekToken().get()) {
            case "@":
                if (annotations.isEmpty()) {
                    return;
                }
                List<AnnotationTree> dimAnnotations = annotations.removeFirst();
                if (dimAnnotations.isEmpty()) {
                    continue;
                }
                builder.breakToFill(" ");
                visitAnnotations(dimAnnotations, BreakOrNot.NO, BreakOrNot.NO);
                lastWasAnnotation = true;
                break;
            case "[":
                if (lastWasAnnotation) {
                    builder.breakToFill(" ");
                } else {
                    builder.breakToFill();
                }
                token("[");
                if (!builder.peekToken().get().equals("]")) {
                    scan(dimExpressions.removeFirst(), null);
                }
                token("]");
                lastWasAnnotation = false;
                break;
            default:
                return;
        }
    }
}
 
Example 9
Source File: RemoteInputStreamFactory.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private InputStream fetchBlobFromRemoteWorker(
    Digest blobDigest,
    Deque<String> workers,
    long offset,
    long deadlineAfter,
    TimeUnit deadlineAfterUnits,
    RequestMetadata requestMetadata)
    throws IOException, InterruptedException {
  String worker = workers.removeFirst();
  try {
    Instance instance = workerStub(worker);

    InputStream input =
        instance.newBlobInput(
            blobDigest, offset, deadlineAfter, deadlineAfterUnits, requestMetadata);
    // ensure that if the blob cannot be fetched, that we throw here
    input.available();
    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
    return input;
  } catch (StatusRuntimeException e) {
    Status st = Status.fromThrowable(e);
    if (st.getCode() == Code.UNAVAILABLE || st.getCode() == Code.UNIMPLEMENTED) {
      // for now, leave this up to schedulers
      onUnavailable.accept(worker, e, "getBlob(" + DigestUtil.toString(blobDigest) + ")");
    } else if (st.getCode() == Code.NOT_FOUND) {
      // ignore this, the worker will update the backplane eventually
    } else if (st.getCode() != Code.DEADLINE_EXCEEDED && SHARD_IS_RETRIABLE.test(st)) {
      // why not, always
      workers.addLast(worker);
    } else if (st.getCode() == Code.CANCELLED) {
      throw new InterruptedException();
    } else {
      throw e;
    }
  }
  throw new NoSuchFileException(DigestUtil.toString(blobDigest));
}
 
Example 10
Source File: VideoUtils.java    From Amphitheatre with Apache License 2.0 5 votes vote down vote up
public static List<SmbFile> getFilesFromDir(String path, NtlmPasswordAuthentication auth) throws Exception {
    List<SmbFile> results = new ArrayList<SmbFile>();
    Set<SmbFile> seen = new LinkedHashSet<SmbFile>();
    Deque<SmbFile> queue = new ArrayDeque<SmbFile>();

    SmbFile baseDir = new SmbFile(path, auth);
    queue.add(baseDir);

    while (!queue.isEmpty()) {
        SmbFile file = queue.removeFirst();
        seen.add(file);

        if (file.isDirectory()) {
            Set<SmbFile> smbFiles = new LinkedHashSet<SmbFile>();
            Collections.addAll(smbFiles, file.listFiles());

            for (SmbFile child : smbFiles) {
                if (!seen.contains(child)) {
                    queue.add(child);
                }
            }
        } else if (VideoUtils.isVideoFile(file.getName())) {
            results.add(file);
        }
    }

    return results;
}
 
Example 11
Source File: AddAndRemoveOnListAdapterOutsideOfJavaScriptContextTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testShift() throws ScriptException {
    final Deque<Object> l = getListAdapter();
    l.removeFirst();
    assertEquals(l.getFirst(), 2);
    assertEquals(l.getLast(), 4);
    assertEquals(l.size(), 3);
}
 
Example 12
Source File: ComponentScopeBuilder.java    From dagger-reflect with Apache License 2.0 5 votes vote down vote up
static ComponentScopeBuilder create(
    Class<?>[] moduleClasses,
    Class<?>[] dependencyClasses,
    Set<Annotation> scopeAnnotations,
    @Nullable Scope parent) {
  Map<Class<?>, Object> moduleInstances = new LinkedHashMap<>();
  Set<Class<?>> subcomponentClasses = new LinkedHashSet<>();

  Deque<Class<?>> moduleClassQueue = new ArrayDeque<>();
  Collections.addAll(moduleClassQueue, moduleClasses);
  while (!moduleClassQueue.isEmpty()) {
    Class<?> moduleClass = moduleClassQueue.removeFirst();
    Module module = requireAnnotation(moduleClass, Module.class);

    Collections.addAll(moduleClassQueue, module.includes());
    Collections.addAll(subcomponentClasses, module.subcomponents());

    // Start with all modules bound to null. Any remaining nulls will be assumed stateless.
    moduleInstances.put(moduleClass, null);
  }

  Map<Class<?>, Object> dependencyInstances = new LinkedHashMap<>();
  for (Class<?> dependencyClass : dependencyClasses) {
    // Start with all dependencies as null. Any remaining nulls at creation time is an error.
    dependencyInstances.put(dependencyClass, null);
  }

  return new ComponentScopeBuilder(
      moduleInstances, dependencyInstances, subcomponentClasses, scopeAnnotations, parent);
}
 
Example 13
Source File: ComputeBuildingsWithView.java    From elements-of-programming-interviews-solutions with MIT License 5 votes vote down vote up
public static Deque<BuildingWithHeight> examineBuildingsWithSunset(Iterator<Integer> sequence) {
    Deque<BuildingWithHeight> stack = new ArrayDeque<>();
    int c = 0;
    while (sequence.hasNext()) {
        Integer temp = sequence.next();
        while (stack.peekFirst()!=null && temp >= stack.peekFirst().height) {
            stack.removeFirst();
        }
        stack.addFirst(new BuildingWithHeight(c++,temp));
    }
    return stack;
}
 
Example 14
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
/**
 * 双端队列的做法
 *
 * @param nums
 * @param k
 * @return
 */
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    if (len == 0) {
        return new int[0];
    }
    int[] res = new int[len - k + 1];

    // 循环不变量:
    // queue 中的元素,如果先进来的元素比后进来的元素小,先进来的元素需要从对尾弹出以后,后进来的元素才进来
    // queue 首一定是当前滑动窗口内最大元素的索引

    Deque<Integer> queue = new LinkedList<>();
    for (int i = 0; i < len; i++) {
        if (i >= k && queue.getFirst() == i - k) {
            queue.removeFirst();
        }
        while (!queue.isEmpty() && nums[queue.getLast()] <= nums[i]) {
            queue.removeLast();
        }
        queue.add(i);
        if (i >= k - 1) {
            res[i - k + 1] = nums[queue.getFirst()];
        }
    }
    return res;
}
 
Example 15
Source File: Utils.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
/** Performs a check whether target object is strongly referenced from source.
 * @param source object to search path from
 * @return true is target is held by source
 */
public static boolean isReachableFrom(Instance source, Instance target) {
    if ((source == null) || (target == null)) {
        return false;
    }

    Logger.getLogger(Utils.class.getName()).log(Level.FINE, "Utils.isReachableFrom {0}, {1}", new Object[] { source, target });

    Set<Instance> processed = new HashSet<Instance>();
    Deque<Instance> fifo = new ArrayDeque<Instance>();
    fifo.add(source);

    while (!fifo.isEmpty()) {
        if (fifo.size() > 200) {
            Logger.getLogger(Utils.class.getName()).log(Level.FINE, "overflow in isReachableFrom {0}, {1}", new Object[] { source, target });

            break;
        }

        Instance act = fifo.removeFirst();

        if (act.equals(target)) {
            return true;
        }

        //System.err.println("  processing iof " + act.getJavaClass().getName() ); 
        @SuppressWarnings("unchecked")
        List<FieldValue> outgoing = act.getFieldValues();

        for (FieldValue v : outgoing) {
            Instance neu = null;

            if (v instanceof ObjectFieldValue) {
                Field fld = ((ObjectFieldValue) v).getField();

                if ("referent".equals(fld.getName()) && "java.lang.ref.Reference".equals(fld.getDeclaringClass().getName())) { // NOI18N
                    continue;
                }

                neu = ((ObjectFieldValue) v).getInstance();
            }

            if (v instanceof ArrayItemValue) {
                neu = ((ArrayItemValue) v).getInstance();
            }

            if (neu == null) {
                continue;
            }

            if (processed.add(neu)) {
                fifo.add(neu);
            }
        }
    }

    return false;
}
 
Example 16
Source File: VpcCfgReconstruction.java    From jakstab with GNU General Public License v2.0 4 votes vote down vote up
private Set<CFAEdge> reconstructCFGFromVPC(Map<Location, AbstractState> constants) {
	
	Set<CFAEdge> edges = new HashSet<CFAEdge>(1000);
	
	Deque<AbstractState> worklist = new LinkedList<AbstractState>();
	worklist.add(art.getRoot());
	Set<AbstractState> visited = new HashSet<AbstractState>();
	visited.add(art.getRoot());
	
	while (!worklist.isEmpty()) {
		AbstractState headState = worklist.removeFirst();
		BasedNumberElement vpcVal = getVPC(headState);
		VpcLocation headVpcLoc = new VpcLocation(vpcVal, (RTLLabel)headState.getLocation());

		Set<Pair<CFAEdge, AbstractState>> successors = art.getChildren(headState);
		for (Pair<CFAEdge, AbstractState> sPair : successors) {
			AbstractState nextState = sPair.getRight();
			CFAEdge edge = sPair.getLeft();
			
			if (isVpcStateBot(nextState))
				continue;
			
			VpcLocation vpcLoc = headVpcLoc;
			BasedNumberElement nextVpcVal = getVPC(nextState);
			
			List<RTLStatement> stmtList;
			if (Options.basicBlocks.getValue())
				stmtList = (BasicBlock)edge.getTransformer();
			else
				stmtList = Collections.singletonList((RTLStatement)edge.getTransformer());
			for (RTLStatement stmt : stmtList) {
				if (stmt instanceof RTLHalt)
					break;
				VpcLocation nextVpcLoc = new VpcLocation(nextVpcVal, stmt.getNextLabel());
				
				AbstractState flattenedStateAtStart = constants.get(vpcLoc);
				if (flattenedStateAtStart != null)
					stmt = substituteStatement(stmt, flattenedStateAtStart);
				
				edges.add(new CFAEdge(vpcLoc, nextVpcLoc, stmt));
				
				vpcLoc = nextVpcLoc;
			}
			
			if (!visited.contains(nextState)) {
				visited.add(nextState);
				worklist.add(nextState);
			}
		}
		
	}
	return edges;		
}
 
Example 17
Source File: AbstractRevisionHistory.java    From MOE with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T findRevisions(Revision revision, RevisionMatcher<T> matcher, SearchType searchType) {

  List<Revision> startingRevisions =
      (revision == null) ? findHeadRevisions() : ImmutableList.of(revision);

  if (startingRevisions.size() > 1 && searchType == SearchType.LINEAR) {
    throw new MoeProblem(
        "MOE found a repository (%s) with multiple heads while trying to search linear history.",
        startingRevisions.get(0).repositoryName());
  }

  RevisionGraph.Builder nonMatchingBuilder = RevisionGraph.builder(startingRevisions);
  ImmutableList.Builder<Revision> matchingBuilder = ImmutableList.builder();

  Deque<Revision> workList = new ArrayDeque<>();
  workList.addAll(startingRevisions);

  // Keep a visited list to make sure we don't visit the same change twice.
  Set<Revision> visited = Sets.newLinkedHashSet();
  visited.addAll(startingRevisions);

  while (!workList.isEmpty()) {
    Revision current = workList.removeFirst();
    if (!matcher.matches(current)) {
      RevisionMetadata metadata = getMetadata(current);
      nonMatchingBuilder.addRevision(current, metadata);

      List<Revision> parentsToSearch = metadata.parents();
      if (parentsToSearch.size() > 0 && searchType == SearchType.LINEAR) {
        parentsToSearch = parentsToSearch.subList(0, 1);
      }
      for (Revision parent : parentsToSearch) {
        // Don't add a visited parent to the search queue.
        if (visited.add(parent)) {
          workList.addLast(parent);
        }
      }

      if (visited.size() > MAX_REVISIONS_TO_SEARCH) {
        throw new MoeProblem(
            "Couldn't find a matching revision for matcher (%s) from %s within %d revisions.",
            matcher,
            (revision == null) ? "head" : revision,
            MAX_REVISIONS_TO_SEARCH);
      }
    } else {
      // Don't search past matching revisions.
      matchingBuilder.add(current);
    }
  }

  return matcher.makeResult(nonMatchingBuilder.build(), matchingBuilder.build());
}
 
Example 18
Source File: NShortestPaths.java    From jopenfst with MIT License 4 votes vote down vote up
/**
 * Calculates the shortest distances from each state to the final.
 *
 * See: M. Mohri, "Semiring Framework and Algorithms for Shortest-Distance Problems", Journal of Automata, Languages
 * and Combinatorics, 7(3), pp. 321-350, 2002.
 *
 * @param fst the fst to calculate the shortest distances
 * @return the array containing the shortest distances
 */
private static double[] shortestDistance(Fst fst) {

  Fst reversed = Reverse.reverse(fst);

  double[] d = new double[reversed.getStateCount()];
  double[] r = new double[reversed.getStateCount()];

  Semiring semiring = reversed.getSemiring();

  for (int i = 0; i < d.length; i++) {
    d[i] = semiring.zero();
    r[i] = semiring.zero();
  }

  IntObjectOpenHashMap<State> stateMap = new IntObjectOpenHashMap<>();
  Deque<Integer> queue = new LinkedList<>();
  IntOpenHashSet enqueuedStateIds = new IntOpenHashSet();

  queue.addLast(reversed.getStartState().getId());
  stateMap.put(reversed.getStartState().getId(), reversed.getStartState());

  d[reversed.getStartState().getId()] = semiring.one();
  r[reversed.getStartState().getId()] = semiring.one();

  while (!queue.isEmpty()) {
    int thisStateId = queue.removeFirst();
    enqueuedStateIds.remove(thisStateId);
    State thisState = stateMap.get(thisStateId);
    double rnew = r[thisState.getId()];
    r[thisState.getId()] = semiring.zero();

    for (int i = 0; i < thisState.getArcCount(); i++) {
      Arc arc = thisState.getArc(i);
      State nextState = arc.getNextState();
      double dnext = d[arc.getNextState().getId()];
      double dnextnew = semiring.plus(dnext, semiring.times(rnew, arc.getWeight()));
      if (dnext != dnextnew) {
        d[arc.getNextState().getId()] = dnextnew;
        r[arc.getNextState().getId()] = semiring.plus(r[arc.getNextState().getId()], semiring.times(rnew, arc.getWeight()));
        int nextStateId = nextState.getId();
        if (!enqueuedStateIds.contains(nextStateId)) {
          queue.addLast(nextStateId);
          enqueuedStateIds.add(nextStateId);
          stateMap.put(nextStateId, nextState);
        }
      }
    }
  }
  return d;
}
 
Example 19
Source File: TypeInspector.java    From js-dossier with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts information on the members (both functions and properties) of the given type.
 *
 * <p>The returned report will include information on all properties on the type, regardless of
 * whether the property is defined directly on the nominal type or one of its super
 * types/interfaces.
 */
public Report inspectInstanceType() {
  if (!inspectedType.getType().isConstructor() && !inspectedType.getType().isInterface()) {
    return Report.empty();
  }

  Report.Builder report = Report.builder();
  Multimap<String, InstanceProperty> properties =
      MultimapBuilder.treeKeys().linkedHashSetValues().build();

  for (JSType assignableType : getAssignableTypes(inspectedType.getType())) {
    for (Map.Entry<String, InstanceProperty> entry :
        getInstanceProperties(assignableType).entrySet()) {
      properties.put(entry.getKey(), entry.getValue());
    }
  }

  final JSType currentType = ((FunctionType) inspectedType.getType()).getInstanceType();
  final TemplateTypeReplacer replacer =
      TemplateTypeReplacer.forPartialReplacement(jsRegistry, currentType.getTemplateTypeMap());

  for (String key : properties.keySet()) {
    Deque<InstanceProperty> definitions = new ArrayDeque<>(properties.get(key));
    JSType propertyType = findPropertyType(definitions);
    InstanceProperty property = definitions.removeFirst();

    if (property.getJsDoc() != null
        && property.getJsDoc().getVisibility() == JSDocInfo.Visibility.PRIVATE) {
      continue;
    }

    NominalType ownerType = property.getOwnerType().orElse(inspectedType);
    DefinedByType definedBy = getDefinedByComment(linkFactory, ownerType, currentType, property);

    if (!currentType.getTemplateTypeMap().isEmpty()) {
      propertyType = propertyType.visit(replacer);
    }

    if (propertyType.isFunctionType()) {
      report
          .functionsBuilder()
          .add(
              getFunctionData(
                  property.getName(),
                  propertyType.toMaybeFunctionType(),
                  property.getNode(),
                  PropertyDocs.create(ownerType, property.getJsDoc()),
                  definedBy,
                  definitions));
    } else {
      report
          .propertiesBuilder()
          .add(
              getPropertyData(
                  property.getName(),
                  propertyType,
                  property.getNode(),
                  PropertyDocs.create(ownerType, property.getJsDoc()),
                  definedBy,
                  definitions));
    }
  }

  return report.build();
}
 
Example 20
Source File: LinkedDequeTest.java    From concurrentlinkedhashmap with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "emptyDeque", expectedExceptions = NoSuchElementException.class)
public void removeFirst_whenEmpty(Deque<SimpleLinkedValue> deque) {
  deque.removeFirst();
}