List of usage examples for java.util Deque isEmpty
boolean isEmpty();
From source file:com.roche.sequencing.bioinformatics.common.utils.FileUtil.java
/** * taken from here http://codereview.stackexchange.com/questions/47923/simplifying-a-path -Kurt Heilman * //from w w w . j a v a2s . c o m * @param path * @return */ public static String simplifyPath(String path) { String simplifiedPath = null; Deque<String> pathDeterminer = new ArrayDeque<String>(); path = path.replaceAll(Pattern.quote("\\"), "/"); path = path.replaceAll(Pattern.quote("\\\\"), "/"); String[] pathSplitter = path.split("/"); StringBuilder absolutePath = new StringBuilder(); for (String term : pathSplitter) { if (term == null || term.length() == 0 || term.equals(".")) { /* ignore these guys */ } else if (term.equals("..")) { if (pathDeterminer.size() > 0) { pathDeterminer.removeLast(); } } else { pathDeterminer.addLast(term); } } if (pathDeterminer.isEmpty()) { simplifiedPath = "/"; } else { while (!pathDeterminer.isEmpty()) { absolutePath.insert(0, pathDeterminer.removeLast()); absolutePath.insert(0, "/"); } simplifiedPath = absolutePath.toString(); } return simplifiedPath; }
From source file:org.apache.openmeetings.web.room.wb.WbPanel.java
private UndoObject getUndo(Long wbId) { if (wbId == null || !undoList.containsKey(wbId)) { return null; }//from w w w . j av a2 s . co m Deque<UndoObject> deq = undoList.get(wbId); return deq.isEmpty() ? null : deq.pop(); }
From source file:org.graphwalker.io.factory.yed.YEdContextFactory.java
private Vertex addVertices(Model model, Context context, GraphmlDocument document, Map<String, Vertex> elements) throws XmlException { Vertex startVertex = null;// ww w .j a va 2s .co m Deque<XmlObject> workQueue = new ArrayDeque<>(); workQueue.addAll(Arrays.asList(document.selectPath(NAMESPACE + "$this/xq:graphml/xq:graph/xq:node"))); while (!workQueue.isEmpty()) { XmlObject object = workQueue.pop(); if (object instanceof NodeType) { NodeType node = (NodeType) object; if (0 < node.getGraphArray().length) { for (GraphType subgraph : node.getGraphArray()) { workQueue.addAll(Arrays.asList(subgraph.getNodeArray())); } } else { String description = ""; for (DataType data : node.getDataArray()) { if (0 < data.getDomNode().getChildNodes().getLength()) { if (data.getKey().equals("d5")) { description = ((DataTypeImpl) data).getStringValue(); } if (isSupportedNode(data.xmlText())) { StringBuilder label = new StringBuilder(); for (NodeLabelType nodeLabel : getSupportedNode(data.xmlText()) .getNodeLabelArray()) { label.append(((NodeLabelTypeImpl) nodeLabel).getStringValue()); } YEdVertexParser parser = new YEdVertexParser(getTokenStream(label.toString())); parser.removeErrorListeners(); parser.addErrorListener(YEdDescriptiveErrorListener.INSTANCE); YEdVertexParser.ParseContext parseContext = parser.parse(); Vertex vertex = new Vertex(); if (!description.isEmpty()) { vertex.setProperty("description", description); } vertex.setProperty("x", getSupportedNode(data.xmlText()).getGeometry().getX()); vertex.setProperty("y", getSupportedNode(data.xmlText()).getGeometry().getY()); boolean blocked = false; if (null != parseContext.start()) { elements.put(node.getId(), vertex); vertex.setId(node.getId()); startVertex = vertex; } else { for (YEdVertexParser.FieldContext field : parseContext.field()) { if (null != field.names()) { vertex.setName(field.names().getText()); } if (null != field.shared() && null != field.shared().Identifier()) { vertex.setSharedState(field.shared().Identifier().getText()); } if (null != field.reqtags()) { vertex.setRequirements(convertVertexRequirement( field.reqtags().reqtagList().reqtag())); } if (null != field.actions()) { model.addActions(convertVertexAction(field.actions().action())); } if (null != field.blocked()) { blocked = true; } } if (!blocked) { elements.put(node.getId(), vertex); vertex.setId(node.getId()); model.addVertex(vertex); } } } } } } } } return startVertex; }
From source file:uniol.apt.adt.automaton.FiniteAutomatonUtility.java
/** * Find a word whose prefixes (including the word) conform to a given predicate and which itself also conforms * to a second predicate./* w w w . j a v a 2s . co m*/ * * This method uses a depth-first search. A breath-first search would use more memory. * * @param a The automaton whose accepted words should get checked. * @param prefixPredicate The predicate to check the prefixes. * @param wordPredicate The predicate to check the words. * @return A word which conforms to the predicates. */ static public List<String> findPredicateWord(FiniteAutomaton a, Predicate<List<String>> prefixPredicate, Predicate<List<String>> wordPredicate) { MinimalDeterministicFiniteAutomaton dfa = minimizeInternal(a); Deque<Pair<DFAState, Iterator<Symbol>>> trace = new ArrayDeque<>(); LinkedList<String> word = new LinkedList<>(); DFAState initial = dfa.getInitialState(); DFAState sinkState = findSinkState(dfa); trace.add(new Pair<>(initial, initial.getDefinedSymbols().iterator())); while (!trace.isEmpty()) { Pair<DFAState, Iterator<Symbol>> pair = trace.peekLast(); if (!pair.getSecond().hasNext()) { trace.removeLast(); word.pollLast(); } else { Symbol symbol = pair.getSecond().next(); DFAState nextState = pair.getFirst().getFollowingState(symbol); if (!nextState.equals(sinkState)) { word.add(symbol.getEvent()); List<String> roWord = ListUtils.unmodifiableList(word); if (prefixPredicate.evaluate(roWord)) { trace.addLast(new Pair<>(nextState, nextState.getDefinedSymbols().iterator())); if (nextState.isFinalState() && wordPredicate.evaluate(roWord)) return word; } else { word.removeLast(); } } } } return null; }
From source file:ict.ocrabase.main.java.client.bulkload.LoadHFiles.java
/** * Perform a bulk load of the given directory into the given * pre-existing table.// w w w . j av a 2s .co m * @param hfofDir the directory that was provided as the output path * of a job using HFileOutputFormat * @param table the table to load into * @throws TableNotFoundException if table does not yet exist */ public void doBulkLoad(Path outDir, String[] tableNames) throws TableNotFoundException, IOException { Configuration config = getConf(); int num = 0; int tableNum = tableNames.length; for (String tableName : tableNames) { HTable table = new HTable(config, tableName); Path hfofDir = new Path(outDir, tableName); HConnection conn = table.getConnection(); if (!conn.isTableAvailable(table.getTableName())) { throw new TableNotFoundException( "Table " + Bytes.toStringBinary(table.getTableName()) + "is not currently available."); } Deque<LoadQueueItem> queue = null; try { queue = discoverLoadQueue(hfofDir); int total = queue.size(); while (!queue.isEmpty()) { LoadQueueItem item = queue.remove(); tryLoad(item, conn, table.getTableName(), queue, config); progress = (num + 1 - (float) queue.size() / total) / tableNum; } } finally { if (queue != null && !queue.isEmpty()) { StringBuilder err = new StringBuilder(); err.append("-------------------------------------------------\n"); err.append("Bulk load aborted with some files not yet loaded:\n"); err.append("-------------------------------------------------\n"); for (LoadQueueItem q : queue) { err.append(" ").append(q.hfilePath).append('\n'); } LOG.error(err); throw new IOException(); } } num++; } progress = 1; }
From source file:uniol.apt.adt.automaton.FiniteAutomatonUtility.java
static private <S extends State> Iterable<S> statesIterable(final S initialState) { return new Iterable<S>() { @Override// ww w.j a v a2s. c om public Iterator<S> iterator() { final Deque<State> unhandled = new LinkedList<>(); final Set<State> seen = new HashSet<>(); unhandled.add(initialState); seen.add(initialState); return new Iterator<S>() { @Override public boolean hasNext() { return !unhandled.isEmpty(); } @Override public S next() { State state = unhandled.pollFirst(); if (state == null) throw new NoSuchElementException(); for (State next : state.getFollowingStates(Symbol.EPSILON)) if (seen.add(next)) unhandled.add(next); for (Symbol symbol : state.getDefinedSymbols()) for (State next : state.getFollowingStates(symbol)) if (seen.add(next)) unhandled.add(next); @SuppressWarnings("unchecked") S ret = (S) state; return ret; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }
From source file:uniol.apt.analysis.isomorphism.IsomorphismLogicComplex.java
/** * Isomorphism-check for current state//from w w w .ja v a 2 s .co m * * @param state current state * @return true if node-pair m, n in state s is isomorphic. */ private boolean doMatch(ExtendedState state) { // Statal-tree, that stores all states Deque<ExtendedState> states = new LinkedList<>(); // Add current state to list of states states.addLast(state); int depth = 0; while (!states.isEmpty()) { ExtendedState s = states.getLast(); depth = s.depth; if (depth > 0) { core1.put(s.n, s.m); core2.put(s.m, s.n); } if (depth == numNodes) { break; } if (!s.active) { computeTerminalSets(depth, s); } Pair<State, State> node = computeP(depth, s); State n, m; //boolean that is true, if (m, n) is an isomorphic pair boolean goodState = false; s.active = true; for (; node != null; node = computeP(depth, s)) { InterrupterRegistry.throwIfInterruptRequestedForCurrentThread(); n = node.getFirst(); m = node.getSecond(); //if (m,n) is an isomorphic pair if (isFeasible(n, m)) { goodState = true; //increment depth because of new isomorphic pair and //set new pair (n,m) as current pair in new state ExtendedState news = new ExtendedState(s, depth + 1, n, m); if (!in1.containsKey(n)) { in1.put(n, depth + 1); news.numin1++; } if (!out1.containsKey(n)) { out1.put(n, depth + 1); news.numout1++; } if (!in2.containsKey(m)) { in2.put(m, depth + 1); news.numin2++; } if (!out2.containsKey(m)) { out2.put(m, depth + 1); news.numout2++; } //Add new state to state-tree states.addLast(news); break; } } //Discard current state if no isomorphic pair has been found if (!goodState) { rollback(depth, s.n, s.m); ExtendedState last = states.removeLast(); assert last == s; } } //Set final state, to get pairs of isomorphic nodes. this.finalState = states; for (ExtendedState ext : states) { if (ext.depth > 0) isomorphism.put(ext.n, ext.m); } return (depth == numNodes); }
From source file:io.jmnarloch.spring.cloud.zuul.trie.AbstractTrie.java
protected T remove(N root, String key) { int index = 0; N node = root;//from w w w .j a v a 2 s. c om N next; final Deque<N> stack = new LinkedList<N>(); while (index < key.length()) { stack.push(node); next = node.getNext(getChar(key, index)); if (next == null) { return null; } node = next; index++; } if (!node.hasValue()) { return null; } final T value = node.getValue(); node.setSize(node.getSize() - 1); node.removeValue(); index = key.length() - 1; while (!stack.isEmpty()) { final char c = getChar(key, index); node = stack.pop(); if (node.getNext(c).isEmpty()) { node.removeNext(c); } node.setSize(node.getSize() - 1); index--; } return value; }
From source file:org.jasig.resource.aggr.ResourcesAggregatorImpl.java
/** * Iterate over the list of {@link BasicInclude} sub-classes using the {@link AggregatorCallback#willAggregate(BasicInclude, BasicInclude)} * and {@link AggregatorCallback#aggregate(Deque)} to generate an aggregated list of {@link BasicInclude} sub-classes. *///from www .j a v a 2 s. c om protected <T extends BasicInclude> List<T> aggregateBasicIncludes(List<T> original, AggregatorCallback<T> callback) throws IOException { final List<T> result = new LinkedList<T>(); final Deque<T> currentAggregateList = new LinkedList<T>(); for (final T originalElement : original) { // handle first loop iteration if (currentAggregateList.isEmpty()) { currentAggregateList.add(originalElement); } else { // test if 'originalElement' will aggregate with head element in currentAggregate final T baseElement = currentAggregateList.getFirst(); if (callback.willAggregate(originalElement, baseElement)) { // matches current criteria, add to currentAggregate currentAggregateList.add(originalElement); } else { // doesn't match criteria // generate new single aggregate from currentAggregateList final T aggregate = callback.aggregate(currentAggregateList); if (null != aggregate) { // push result result.add(aggregate); } else { this.logger .warn("Generated 0 byte aggregate from: " + generatePathList(currentAggregateList)); } // zero out currentAggregateList currentAggregateList.clear(); // add originalElement to empty list currentAggregateList.add(originalElement); } } } // flush the currentAggregateList if (currentAggregateList.size() > 0) { final T aggregate = callback.aggregate(currentAggregateList); if (null != aggregate) { result.add(aggregate); } else { this.logger.warn("Generated 0 byte aggregate from: " + generatePathList(currentAggregateList)); } } return result; }
From source file:ro.hasna.ts.math.ml.distance.DynamicTimeWarpingDistance.java
/** * <p>/* w ww . j a v a2s .com*/ * Reference: * Daniel Lemire (2008) * <i>Faster Sequential Search with a Two-Pass Dynamic-Time-Warping Lower Bound</i> * </p> * * @param v the vector * @param n the length of the vector * @param radius the Sakoe-Chiba band radius * @return time series envelope */ protected Envelope computeLemireEnvelope(double[] v, int n, int radius) { int w = 2 * radius + 1; double[] upper = new double[n]; double[] lower = new double[n]; int i; Deque<Integer> upperList = new LinkedList<>(); Deque<Integer> lowerList = new LinkedList<>(); upperList.addLast(0); lowerList.addLast(0); for (i = 1; i < n; i++) { if (i >= w) { upper[i - w] = v[upperList.getFirst()]; lower[i - w] = v[lowerList.getFirst()]; } if (v[i] > v[i - 1]) { upperList.removeLast(); while (!upperList.isEmpty() && v[i] > v[upperList.getLast()]) { upperList.removeLast(); } } else { lowerList.removeLast(); while (!lowerList.isEmpty() && v[i] < v[lowerList.getLast()]) { lowerList.removeLast(); } } upperList.addLast(i); lowerList.addLast(i); if (i == 2 * w + upperList.getFirst()) { upperList.removeFirst(); } else if (i == 2 * w + lowerList.getFirst()) { lowerList.removeFirst(); } } for (i = n; i < n + w; i++) { upper[i - w] = v[upperList.getFirst()]; lower[i - w] = v[lowerList.getFirst()]; if (i - upperList.getFirst() >= 2 * w) { upperList.removeFirst(); } if (i - lowerList.getFirst() >= 2 * w) { lowerList.removeFirst(); } } return new Envelope(lower, upper); }