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

The following examples show how to use java.util.ArrayDeque#isEmpty() . 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
/**
     * Given a vertex, find all of the vertices in its component.
     *
     * @param graph The graph containing the vertex.
     * @param seedVxId The vertex to start from.
     * @param verticesToArrange a BitSet specifying which vertices to arrange.
     *
     * @return A Set<Integer%gt; containing all of the vertices in the same
     * component as rootVxId.
     */
    @Deprecated
    public static Set<Integer> getComponentContainingVertex(final GraphReadMethods graph, final int seedVxId, final BitSet verticesToArrange) {
        final Set<Integer> component = new HashSet<>();

        final ArrayDeque<Integer> neighbours = new ArrayDeque<>();
        neighbours.add(seedVxId);
        component.add(seedVxId);
        while (!neighbours.isEmpty()) {
            final Integer vxId = neighbours.removeFirst();
//            component.add(vxId);
//            Debug.debug("@added to component: %d (%d)\n", vxId, component.size());
            final int nNeighbours = graph.getVertexNeighbourCount(vxId);
            for (int nbPosition = 0; nbPosition < nNeighbours; nbPosition++) {
                final int nbId = graph.getVertexNeighbour(vxId, nbPosition);

                if (verticesToArrange.get(nbId) && !component.contains(nbId)) {
                    neighbours.add(nbId);
                    component.add(nbId);
                }
            }
        }

        return component;
    }
 
Example 2
Source Project: es6draft   File: World.java    License: MIT License 6 votes vote down vote up
/**
 * Executes the queue of pending jobs.
 * 
 * @param jobSource
 *            the job source
 * @throws InterruptedException
 *             if interrupted while waiting
 */
public void runEventLoop(JobSource jobSource) throws InterruptedException {
    ArrayDeque<Job> scriptJobs = this.scriptJobs;
    ArrayDeque<Job> promiseJobs = this.promiseJobs;
    ArrayDeque<Job> finalizerJobs = this.finalizerJobs;
    ConcurrentLinkedDeque<Job> asyncJobs = this.asyncJobs;
    ArrayDeque<Object> unhandledRejections = this.unhandledRejections;
    for (;;) {
        while (!(scriptJobs.isEmpty() && promiseJobs.isEmpty() && finalizerJobs.isEmpty() && asyncJobs.isEmpty())) {
            executeJobs(scriptJobs);
            executeJobs(promiseJobs);
            executeJobs(finalizerJobs);
            executeJobs(asyncJobs);
        }
        if (!unhandledRejections.isEmpty()) {
            throw new UnhandledRejectionException(unhandledRejections.poll());
        }
        Job job = jobSource.nextJob();
        if (job == null) {
            break;
        }
        enqueueScriptJob(job);
    }
}
 
Example 3
Source Project: lucene-solr   File: Operations.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns bitset marking states reachable from the initial state. */
private static BitSet getLiveStatesFromInitial(Automaton a) {
  int numStates = a.getNumStates();
  BitSet live = new BitSet(numStates);
  if (numStates == 0) {
    return live;
  }
  ArrayDeque<Integer> workList = new ArrayDeque<>();
  live.set(0);
  workList.add(0);

  Transition t = new Transition();
  while (workList.isEmpty() == false) {
    int s = workList.removeFirst();
    int count = a.initTransition(s, t);
    for(int i=0;i<count;i++) {
      a.getNextTransition(t);
      if (live.get(t.dest) == false) {
        live.set(t.dest);
        workList.add(t.dest);
      }
    }
  }

  return live;
}
 
Example 4
Source Project: Android-Cheat-sheet   File: Dequeue.java    License: Apache License 2.0 5 votes vote down vote up
public static void findMaximumSlidingWindow(int[] arr,
                                            int windowSize) {
    if (arr.length < windowSize) return;

    ArrayDeque<Integer> list = new ArrayDeque();
    for (int i = 0; i < windowSize; i++) {

        while (!list.isEmpty() && arr[i] >= arr[list.peekLast()]) {
            list.removeLast();
        }
        list.addLast(i);
    }

    System.out.print(arr[list.peekFirst()] + " ");


    for (int i = windowSize; i < arr.length; i++) {

        while (!list.isEmpty() && arr[i] >= arr[list.peekLast()]) {
            list.removeLast();
        }

        if (!list.isEmpty() && list.peekFirst() <= i - windowSize) {
            list.removeFirst();
        }

        list.addLast(i);
        System.out.print(arr[list.peekFirst()] + " ");
    }
}
 
Example 5
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 6
@Override
public void onComplete() {
    final ArrayDeque<UnicastSubject<T>> ws = windows;
    while (!ws.isEmpty()) {
        ws.poll().onComplete();
    }
    actual.onComplete();
}
 
Example 7
Source Project: copybara   File: Glob.java    License: Apache License 2.0 5 votes vote down vote up
static ImmutableSet<String> computeRootsFromIncludes(Iterable<String> includes) {
  List<String> roots = new ArrayList<>();

  for (String includePath : includes) {
    ArrayDeque<String> components = new ArrayDeque<>();
    for (String component : Splitter.on('/').split(includePath)) {
      components.add(unescape(component));
      if (isMeta(component)) {
        break;
      }
    }
    components.removeLast();
    if (components.isEmpty()) {
      return ImmutableSet.of("");
    }
    roots.add(Joiner.on('/').join(components));
  }

  // Remove redundant roots - e.g. "foo" covers all paths that start with "foo/"
  Collections.sort(roots);
  int r = 0;
  while (r < roots.size() - 1) {
    if (roots.get(r + 1).startsWith(roots.get(r) + "/")) {
      roots.remove(r + 1);
    } else {
      r++;
    }
  }

  return ImmutableSet.copyOf(roots);
}
 
Example 8
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    // 特判
    if (len == 0) {
        return new int[]{};
    }
    // 结果集
    List<Integer> res = new ArrayList<>();
    // 滑动窗口,注意:保存的是索引值
    ArrayDeque<Integer> deque = new ArrayDeque<>(k);

    for (int i = 0; i < len; i++) {
        // 当元素从左边界滑出的时候,如果它恰恰好是滑动窗口的最大值
        // 那么将它弹出
        if (i >= k && i - k == deque.getFirst()) {
            deque.pollFirst();
        }

        // 如果滑动窗口非空,新进来的数比队列里已经存在的数还要大
        // 则说明已经存在数一定不会是滑动窗口的最大值(它们毫无出头之日)
        // 将它们弹出
        while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[i]) {
            deque.pollLast();
        }
        deque.add(i);
        // 队首一定是滑动窗口的最大值的索引
        if (i >= k - 1) {
            res.add(nums[deque.peekFirst()]);
        }
    }

    int size = res.size();
    int[] result = new int[size];

    for (int i = 0; i < size; i++) {
        result[i] = res.get(i);
    }
    return result;
}
 
Example 9
/**
 * Get the normalized path for the given file path.
 * Any parent directories (..) will be resolved.
 * @param file file path
 * @return 
 */
public static String getNormalizedPath(String file) {
    Matcher m = schemedPathPattern.matcher(file);
    if(!m.find()) {
        return Directory.ROOT_DIRECTORY;
    }
    String scheme = m.group(1);
    String path = m.group(2);
    if(scheme == null) {
        scheme = "";
    }
    String[] st = path.split("(\\\\|/)+");
    ArrayDeque<String> segmentList = new ArrayDeque<String>();
    for(String segment : st) {
        if("..".equals(segment)) {
            segmentList.pollFirst();
            continue;
        }
        segmentList.offerFirst(segment);
    }
    if(segmentList.isEmpty() && scheme.isEmpty()) {
        return Directory.ROOT_DIRECTORY;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(scheme);
    while(!segmentList.isEmpty()) {
        sb.append(segmentList.pollLast());
        if(segmentList.peekLast() != null) {
            sb.append('/');
        }
    }
    return sb.length() == 0 ? Directory.ROOT_DIRECTORY : sb.toString();
}
 
Example 10
Source Project: EmergingTechnology   File: WorldTickHandler.java    License: MIT License 5 votes vote down vote up
@SubscribeEvent
public void tickEnd(TickEvent.WorldTickEvent event) {
    if (event.side != Side.SERVER) {
        return;
    }

    if (event.phase == TickEvent.Phase.END) {

        World world = event.world;
        int dim = world.provider.getDimension();

        ArrayDeque<ChunkPos> chunks = chunksToGen.get(dim);

        if (chunks != null && !chunks.isEmpty()) {
            ChunkPos c = chunks.pollFirst();
            long worldSeed = world.getSeed();
            Random rand = new Random(worldSeed);
            long xSeed = rand.nextLong() >> 2 + 1L;
            long zSeed = rand.nextLong() >> 2 + 1L;
            rand.setSeed(xSeed * c.x + zSeed * c.z ^ worldSeed);
            OreGenerator.instance.generateWorld(rand, c.x, c.z, world, false);
            chunksToGen.put(dim, chunks);
        } else if (chunks != null) {
            chunksToGen.remove(dim);
        }
    }
}
 
Example 11
private Optional<double[][]> toMatrix(ArrayDeque<double[]> sampledFeatures) {
    Optional<double[][]> samples;
    if (sampledFeatures.isEmpty()) {
        samples = Optional.empty();
    } else {
        samples = Optional.of(sampledFeatures.toArray(new double[0][0]));
    }
    return samples;
}
 
Example 12
Source Project: RichEditorView   File: LuBottomMenu.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param pathRecord 点击的展开路径记录
 *                   通过路径直接恢复视图序列
 */
private void restoreAllInfo(ArrayDeque<MenuItem> pathRecord) {
    mPathRecord.clear();
    while (!pathRecord.isEmpty()) {
        mCurMenuItem = pathRecord.getLast();
        addOneLevel();
        pathRecord.removeLast();
    }

}
 
Example 13
Source Project: MediaSDK   File: Converter.java    License: Apache License 2.0 4 votes vote down vote up
private <T> boolean search(MimedType<T> target, ArrayDeque<PathInfo> bestMatch, ArrayDeque<PathInfo> currentPath, MimedType currentSearch, HashSet<MimedType> searched) {
    if (target.isTypeOf(currentSearch)) {
        bestMatch.clear();
        bestMatch.addAll(currentPath);
        return true;
    }

    // the current path must have potential to be better than the best match
    if (!bestMatch.isEmpty() && PathInfo.distance(currentPath) >= PathInfo.distance(bestMatch))
        return false;

    // prevent reentrancy
    if (searched.contains(currentSearch))
        return false;

    boolean found = false;
    searched.add(currentSearch);
    ConverterTransformers<Object, Object> converterTransformers = outputs.getAll(currentSearch);
    for (MimedType candidate: converterTransformers.keySet()) {
        // this simulates the mime results of a transform
        MimedType newSearch = new MimedType(candidate.type, mimeReplace(currentSearch.mime, candidate.mime));

        PathInfo path = new PathInfo();
        path.transformer = converterTransformers.get(candidate);
        path.mime = newSearch.mime;
        path.candidate = candidate;
        currentPath.addLast(path);
        try {
            found |= search(target, bestMatch, currentPath, newSearch, searched);
        }
        finally {
            currentPath.removeLast();
        }
    }

    if (found) {
        // if this resulted in a success,
        // clear this from the currentSearch list, because we know this leads
        // to a potential solution. maybe we can arrive here faster.
        searched.remove(currentSearch);
    }

    return found;
}
 
Example 14
Source Project: QuickTheories   File: Core.java    License: Apache License 2.0 4 votes vote down vote up
<T> Optional<Pair<Falsification<T>, PrecursorDataPair<T>>> findFalsifyingValue(
    Property<T> prop, LongSupplier clock) {
  
  Guidance guidance = config.guidance();
  
  Distribution<T> randomDistribution =  new BoundarySkewedDistribution<>(config, prop.getGen()); 
  ArrayDeque<long[]> toVisit = new ArrayDeque<>();

  Distribution<T> distribution;

  long endTime = clock.getAsLong() + config.testingTimeMillis();
  for (int i = 0; i != config.examples(); i++) {
    if (toVisit.isEmpty()) {
      distribution = randomDistribution;
    } else {
      distribution = new ForcedDistribution<>(config, prop.getGen(), toVisit.pop());
    }
    
    PrecursorDataPair<T> t = distribution.generate();
    if (checkHash(t)) {
      continue;
    }  
    
    examplesUsed = examplesUsed + 1;
    guidance.newExample(t.precursor());
    
    Optional<Falsification<T>> falsification = prop.tryFalsification(t.value());
    guidance.exampleExecuted();

    if (falsification.isPresent()) {
      return falsification.map(f -> Pair.of(f, t));
    } else {
      toVisit.addAll(guidance.suggestValues(i,t.precursor()));
    }
    
    guidance.exampleComplete();

    if (config.testingTimeMillis() > 0 && clock.getAsLong() > endTime) {
      break;
    }
  }

  return Optional.empty();
}
 
Example 15
Source Project: litho   File: DataFlowGraph.java    License: Apache License 2.0 4 votes vote down vote up
@GuardedBy("this")
private void regenerateSortedNodes() {
  mSortedNodes.clear();

  if (mBindings.size() == 0) {
    return;
  }

  final ArraySet<ValueNode> leafNodes = new ArraySet<>();
  final SimpleArrayMap<ValueNode, Integer> nodesToOutputsLeft = new SimpleArrayMap<>();

  for (int i = 0, bindingsSize = mBindings.size(); i < bindingsSize; i++) {
    final ArrayList<ValueNode> nodes = mBindings.get(i).getAllNodes();
    for (int j = 0, nodesSize = nodes.size(); j < nodesSize; j++) {
      final ValueNode node = nodes.get(j);
      final int outputCount = node.getOutputCount();
      if (outputCount == 0) {
        leafNodes.add(node);
      } else {
        nodesToOutputsLeft.put(node, outputCount);
      }
    }
  }

  if (!nodesToOutputsLeft.isEmpty() && leafNodes.isEmpty()) {
    throw new DetectedCycleException(
        "Graph has nodes, but they represent a cycle with no leaf nodes!");
  }

  final ArrayDeque<ValueNode> nodesToProcess = new ArrayDeque<>();
  nodesToProcess.addAll(leafNodes);

  while (!nodesToProcess.isEmpty()) {
    final ValueNode next = nodesToProcess.pollFirst();
    mSortedNodes.add(next);
    NodeState nodeState = mNodeStates.get(next);
    if (nodeState == null) {
      String message =
          next.getClass().getSimpleName() + " : InputNames " + next.buildDebugInputsString();
      // Added for debugging T67342661
      ComponentsReporter.emitMessage(
          ComponentsReporter.LogLevel.ERROR, STATE_NOT_INTIALIZED_FOR_VALUE_NODE, message);
    }
    for (ValueNode input : next.getAllInputs()) {
      final int outputsLeft = nodesToOutputsLeft.get(input) - 1;
      nodesToOutputsLeft.put(input, outputsLeft);
      if (outputsLeft == 0) {
        nodesToProcess.addLast(input);
      } else if (outputsLeft < 0) {
        throw new DetectedCycleException("Detected cycle.");
      }
    }
  }

  int expectedTotalNodes = nodesToOutputsLeft.size() + leafNodes.size();
  if (mSortedNodes.size() != expectedTotalNodes) {
    throw new DetectedCycleException(
        "Had unreachable nodes in graph -- this likely means there was a cycle");
  }

  Collections.reverse(mSortedNodes);
  mIsDirty = false;
}
 
Example 16
Source Project: bazel   File: ActionRewindStrategy.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Looks at each action in {@code actionsToCheck} and determines whether additional artifacts,
 * actions, and (in the case of {@link SkyframeAwareAction}s) other Skyframe nodes need to be
 * restarted. If this finds more actions to restart, those actions are recursively checked too.
 */
private void checkActions(
    ImmutableList<ActionAndLookupData> actionsToCheck,
    Environment env,
    MutableGraph<SkyKey> rewindGraph,
    ImmutableList.Builder<Action> additionalActionsToRestart)
    throws InterruptedException {

  ArrayDeque<ActionAndLookupData> uncheckedActions = new ArrayDeque<>(actionsToCheck);
  while (!uncheckedActions.isEmpty()) {
    ActionAndLookupData actionAndLookupData = uncheckedActions.removeFirst();
    ActionLookupData actionKey = actionAndLookupData.lookupData();
    Action action = actionAndLookupData.action();
    ArrayList<Artifact.DerivedArtifact> artifactsToCheck = new ArrayList<>();
    ArrayList<ActionLookupData> newlyDiscoveredActions = new ArrayList<>();

    if (action instanceof SkyframeAwareAction) {
      // This action depends on more than just its input artifact values. We need to also restart
      // the Skyframe subgraph it depends on, up to and including any artifacts, which may
      // aggregate multiple actions.
      addSkyframeAwareDepsAndGetNewlyVisitedArtifactsAndActions(
          rewindGraph,
          actionKey,
          (SkyframeAwareAction) action,
          artifactsToCheck,
          newlyDiscoveredActions);
    }

    if (action.mayInsensitivelyPropagateInputs()) {
      // Restarting this action won't recreate the missing input. We need to also restart this
      // action's non-source inputs and the actions which created those inputs.
      addPropagatingActionDepsAndGetNewlyVisitedArtifactsAndActions(
          rewindGraph, actionKey, action, artifactsToCheck, newlyDiscoveredActions);
    }

    for (ActionLookupData actionLookupData : newlyDiscoveredActions) {
      Action additionalAction =
          checkNotNull(
              ActionUtils.getActionForLookupData(env, actionLookupData), actionLookupData);
      additionalActionsToRestart.add(additionalAction);
      uncheckedActions.add(ActionAndLookupData.create(actionLookupData, additionalAction));
    }
    for (Artifact.DerivedArtifact artifact : artifactsToCheck) {
      Map<ActionLookupData, Action> actionMap = getActionsForLostArtifact(artifact, env);
      if (actionMap == null) {
        continue;
      }
      ImmutableList<ActionAndLookupData> newlyVisitedActions =
          addArtifactDepsAndGetNewlyVisitedActions(rewindGraph, artifact, actionMap);
      additionalActionsToRestart.addAll(actions(newlyVisitedActions));
      uncheckedActions.addAll(newlyVisitedActions);
    }
  }
}
 
Example 17
/**
 * Iterates over the provided records and tests whether {@link SpanningRecordSerializer} and {@link RecordDeserializer}
 * interact as expected.
 *
 * <p>Only a single {@link MemorySegment} will be allocated.
 *
 * @param records records to test
 * @param segmentSize size for the {@link MemorySegment}
 */
private static void testSerializationRoundTrip(
		Iterable<SerializationTestType> records,
		int segmentSize,
		RecordSerializer<SerializationTestType> serializer,
		RecordDeserializer<SerializationTestType> deserializer)
	throws Exception {
	final ArrayDeque<SerializationTestType> serializedRecords = new ArrayDeque<>();

	// -------------------------------------------------------------------------------------------------------------

	BufferAndSerializerResult serializationResult = setNextBufferForSerializer(serializer, segmentSize);

	int numRecords = 0;
	for (SerializationTestType record : records) {

		serializedRecords.add(record);

		numRecords++;

		// serialize record
		serializer.serializeRecord(record);
		if (serializer.copyToBufferBuilder(serializationResult.getBufferBuilder()).isFullBuffer()) {
			// buffer is full => start deserializing
			deserializer.setNextBuffer(serializationResult.buildBuffer());

			numRecords -= DeserializationUtils.deserializeRecords(serializedRecords, deserializer);

			// move buffers as long as necessary (for long records)
			while ((serializationResult = setNextBufferForSerializer(serializer, segmentSize)).isFullBuffer()) {
				deserializer.setNextBuffer(serializationResult.buildBuffer());
			}
		}
	}

	// deserialize left over records
	deserializer.setNextBuffer(serializationResult.buildBuffer());

	while (!serializedRecords.isEmpty()) {
		SerializationTestType expected = serializedRecords.poll();

		SerializationTestType actual = expected.getClass().newInstance();
		RecordDeserializer.DeserializationResult result = deserializer.getNextRecord(actual);

		Assert.assertTrue(result.isFullRecord());
		Assert.assertEquals(expected, actual);
		numRecords--;
	}

	// assert that all records have been serialized and deserialized
	Assert.assertEquals(0, numRecords);
	Assert.assertFalse(serializer.hasSerializedData());
	Assert.assertFalse(deserializer.hasUnfinishedData());
}
 
Example 18
/**
 * Parses the text payload of a WebVTT Cue and applies modifications on {@link WebvttCue.Builder}.
 *
 * @param id Id of the cue, {@code null} if it is not present.
 * @param markup The markup text to be parsed.
 * @param styles List of styles defined by the CSS style blocks preceeding the cues.
 * @param builder Output builder.
 */
/* package */ static void parseCueText(String id, String markup, WebvttCue.Builder builder,
    List<WebvttCssStyle> styles) {
  SpannableStringBuilder spannedText = new SpannableStringBuilder();
  ArrayDeque<StartTag> startTagStack = new ArrayDeque<>();
  List<StyleMatch> scratchStyleMatches = new ArrayList<>();
  int pos = 0;
  while (pos < markup.length()) {
    char curr = markup.charAt(pos);
    switch (curr) {
      case CHAR_LESS_THAN:
        if (pos + 1 >= markup.length()) {
          pos++;
          break; // avoid ArrayOutOfBoundsException
        }
        int ltPos = pos;
        boolean isClosingTag = markup.charAt(ltPos + 1) == CHAR_SLASH;
        pos = findEndOfTag(markup, ltPos + 1);
        boolean isVoidTag = markup.charAt(pos - 2) == CHAR_SLASH;
        String fullTagExpression = markup.substring(ltPos + (isClosingTag ? 2 : 1),
            isVoidTag ? pos - 2 : pos - 1);
        String tagName = getTagName(fullTagExpression);
        if (tagName == null || !isSupportedTag(tagName)) {
          continue;
        }
        if (isClosingTag) {
          StartTag startTag;
          do {
            if (startTagStack.isEmpty()) {
              break;
            }
            startTag = startTagStack.pop();
            applySpansForTag(id, startTag, spannedText, styles, scratchStyleMatches);
          } while(!startTag.name.equals(tagName));
        } else if (!isVoidTag) {
          startTagStack.push(StartTag.buildStartTag(fullTagExpression, spannedText.length()));
        }
        break;
      case CHAR_AMPERSAND:
        int semiColonEndIndex = markup.indexOf(CHAR_SEMI_COLON, pos + 1);
        int spaceEndIndex = markup.indexOf(CHAR_SPACE, pos + 1);
        int entityEndIndex = semiColonEndIndex == -1 ? spaceEndIndex
            : (spaceEndIndex == -1 ? semiColonEndIndex
                : Math.min(semiColonEndIndex, spaceEndIndex));
        if (entityEndIndex != -1) {
          applyEntity(markup.substring(pos + 1, entityEndIndex), spannedText);
          if (entityEndIndex == spaceEndIndex) {
            spannedText.append(" ");
          }
          pos = entityEndIndex + 1;
        } else {
          spannedText.append(curr);
          pos++;
        }
        break;
      default:
        spannedText.append(curr);
        pos++;
        break;
    }
  }
  // apply unclosed tags
  while (!startTagStack.isEmpty()) {
    applySpansForTag(id, startTagStack.pop(), spannedText, styles, scratchStyleMatches);
  }
  applySpansForTag(id, StartTag.buildWholeCueVirtualTag(), spannedText, styles,
      scratchStyleMatches);
  builder.setText(spannedText);
}
 
Example 19
/**
 * Parses FTS options from the create statement of an FTS table.
 *
 * This method assumes the given create statement is a valid well-formed SQLite statement as
 * defined in the <a href="https://www.sqlite.org/lang_createvtab.html">CREATE VIRTUAL TABLE
 * syntax diagram</a>.
 *
 * @param createStatement the "CREATE VIRTUAL TABLE" statement.
 * @return the set of FTS option key and values in the create statement.
 */
@VisibleForTesting
@SuppressWarnings("WeakerAccess") /* synthetic access */
static Set<String> parseOptions(String createStatement) {
    if (createStatement.isEmpty()) {
        return new HashSet<>();
    }

    // Module arguments are within the parenthesis followed by the module name.
    String argsString = createStatement.substring(
            createStatement.indexOf('(') + 1,
            createStatement.lastIndexOf(')'));

    // Split the module argument string by the comma delimiter, keeping track of quotation so
    // so that if the delimiter is found within a string literal we don't substring at the wrong
    // index. SQLite supports four ways of quoting keywords, see:
    // https://www.sqlite.org/lang_keywords.html
    List<String> args = new ArrayList<>();
    ArrayDeque<Character> quoteStack = new ArrayDeque<>();
    int lastDelimiterIndex = -1;
    for (int i = 0; i < argsString.length(); i++) {
        char c = argsString.charAt(i);
        switch (c) {
            case '\'':
            case '"':
            case '`':
                if (quoteStack.isEmpty()) {
                    quoteStack.push(c);
                } else if (quoteStack.peek() == c) {
                    quoteStack.pop();
                }
                break;
            case '[':
                if (quoteStack.isEmpty()) {
                    quoteStack.push(c);
                }
                break;
            case ']':
                if (!quoteStack.isEmpty() && quoteStack.peek() == '[') {
                    quoteStack.pop();
                }
                break;
            case ',':
                if (quoteStack.isEmpty()) {
                    args.add(argsString.substring(lastDelimiterIndex + 1, i).trim());
                    lastDelimiterIndex = i;
                }
                break;
        }
    }
    args.add(argsString.substring(lastDelimiterIndex + 1).trim()); // Add final argument.

    // Match args against valid options, otherwise they are column definitions.
    HashSet<String> options = new HashSet<>();
    for (String arg : args) {
        for (String validOption : FTS_OPTIONS) {
            if (arg.startsWith(validOption)) {
                options.add(arg);
            }
        }
    }

    return options;
}
 
Example 20
private boolean nearbyUpstream(ArrayDeque<VcfRecord> regions, int start) {
  return !regions.isEmpty() && start < regions.peekLast().getEnd() + mDistance;
}