List of usage examples for java.util Stack Stack
public Stack()
From source file:de.tudarmstadt.ukp.csniper.webapp.search.tgrep.PennTreeUtils.java
public static PennTreeNode parsePennTree(String aTree) { StringTokenizer st = new StringTokenizer(aTree, "() ", true); PennTreeNode root = null;// www. j a v a 2s.c o m Stack<PennTreeNode> stack = new Stack<PennTreeNode>(); boolean seenLabel = false; int i = 0; while (st.hasMoreTokens()) { String t = st.nextToken().trim(); if (t.length() == 0) { // Skip } else if ("(".equals(t)) { PennTreeNode n = new PennTreeNode(); stack.push(n); if (root == null) { root = n; } seenLabel = false; } else if (")".equals(t)) { PennTreeNode n = stack.pop(); if (!stack.isEmpty()) { PennTreeNode p = stack.peek(); p.addChild(n); } } else if (seenLabel) { // If the node has two labels, its a leaf, add a new terminal node then. PennTreeNode p = stack.peek(); PennTreeNode n = new PennTreeNode(); n.setTokenIndex(i); i++; n.setLabel(t); p.addChild(n); } else { PennTreeNode n = stack.peek(); n.setLabel(t); seenLabel = true; } } return root; }
From source file:ReversePolishNotation.java
/** * This method will calculate the answer of the given Reverse Polar Notation * equation. All exceptions are thrown to the parent for handling. * //from w w w.j a va 2 s . c om * @param input * is the equation entered by the user * @throws EmptyRPNException * when there is no RPN equation to be evaluated. * @throws RPNDivideByZeroException * when the RPN equation attempts to divide by zero. * @throws RPNUnderflowException * when the RPN equation has a mathematical operator before * there are enough numerical values for it to evaluate. * @throws InvalidRPNException * when the RPN equation is a String which is unable to be * manipulated. * @throws RPNOverflowException * when the RPN equation has too many numerical values and not * enough mathematical operators with which to evaluate them. * @return the top item of the stack; the calculated answer of the Reverse * Polish Notation equation */ public static double calcRPN(String input) { // eliminate any leading or trailing whitespace from input input = input.trim(); // scanner to manipulate input and stack to store double values String next; Stack<Double> stack = new Stack<Double>(); Scanner scan = new Scanner(input); // loop while there are tokens left in scan while (scan.hasNext()) { // retrieve the next token from the input next = scan.next(); // see if token is mathematical operator if (nextIsOperator(next)) { // ensure there are enough numbers on stack if (stack.size() > 1) { if (next.equals("+")) { stack.push((Double) stack.pop() + (Double) stack.pop()); } else if (next.equals("-")) { stack.push(-(Double) stack.pop() + (Double) stack.pop()); } else if (next.equals("*")) { stack.push((Double) stack.pop() * (Double) stack.pop()); } else if (next.equals("/")) { double first = stack.pop(); double second = stack.pop(); if (first == 0) { System.out.println("The RPN equation attempted to divide by zero."); } else { stack.push(second / first); } } } else { System.out.println( "A mathematical operator occured before there were enough numerical values for it to evaluate."); } } else { try { stack.push(Double.parseDouble(next)); } catch (NumberFormatException c) { System.out.println("The string is not a valid RPN equation."); } } } if (stack.size() > 1) { System.out.println( "There too many numbers and not enough mathematical operators with which to evaluate them."); } return (Double) stack.pop(); }
From source file:BreadthFirstPathTreeIterator.java
/** Construct a new BreadthFirstPathTreeIterator with the specified root. //from ww w. ja v a2 s . co m @param root The root directory @param servletContext The ServletContext */ public BreadthFirstPathTreeIterator(String root, ServletContext servletContext) { this.root = root; this.servletContext = servletContext; this.currentList = getPathArray(root); this.directories = new Stack(); }
From source file:com.ms.commons.test.math.expression.util.MathExpressionParseUtil.java
private static Stack<String> adjustExpressionStack(Stack<String> expressionStack) { if (expressionStack.size() <= 2) { return expressionStack; }/* w ww .java 2 s.c om*/ int lastOpPr = Integer.MAX_VALUE; int lowerPrOp = -1; for (int i = (expressionStack.size() - 1); i >= 0; i--) { String expr = expressionStack.get(i); if ((expr.length() == 1) && hasSeparators(expr)) { int opPr = ("*".equals(expr) || "/".equals(expr)) ? 2 : 1; if (opPr < lastOpPr) { lastOpPr = opPr; lowerPrOp = i; } } } if (lowerPrOp != -1) { Stack<String> tempStack = new Stack<String>(); int popCount = expressionStack.size() - lowerPrOp - 1; for (int i = 0; i < popCount; i++) { tempStack.push(expressionStack.pop()); } Collections.reverse(tempStack); expressionStack.push(StringUtils.join(tempStack, "")); } return expressionStack; }
From source file:net.sf.jabref.gui.help.HelpContent.java
public HelpContent(JabRefPreferences prefs_) { super();//from www. ja v a 2 s . c om pane = new JScrollPane(this, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); pane.setDoubleBuffered(true); prefs = prefs_; history = new Stack<>(); forw = new Stack<>(); setEditorKitForContentType("text/html", new MyEditorKit()); setContentType("text/html"); setText(""); setEditable(false); addHyperlinkListener(new HyperlinkListener() { private boolean lastStatusUpdateWasALink = false; @Override public void hyperlinkUpdate(HyperlinkEvent e) { String link = e.getDescription(); if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) { // show the link in the status bar - similar to Firefox behavior JabRef.jrf.setStatus(link); lastStatusUpdateWasALink = true; } else { if (lastStatusUpdateWasALink) { // remove the link from the status bar JabRef.jrf.setStatus(""); lastStatusUpdateWasALink = false; } } } }); }
From source file:controller.SeatController.java
public SeatController() { changes = new Stack<>(); currentPlace = new Seat(); }
From source file:ch.zhaw.icclab.tnova.expressionsolver.OTFlyEval.java
@POST @Consumes(MediaType.APPLICATION_JSON)/*from w w w. j a v a 2s. c o m*/ @Produces(MediaType.APPLICATION_JSON) public Response evalOnTheFly(String incomingMsg) { JSONObject incoming = (JSONObject) JSONValue.parse(incomingMsg); JSONObject outgoing = new JSONObject(); String result = ""; try { String expression = (String) incoming.get("exp"); JSONArray vals = (JSONArray) incoming.get("values"); Stack<Double> param = new Stack<Double>(); for (int i = 0; i < vals.size(); i++) { Double val = new Double((String) vals.get(i)); param.push(val); } double threshold = Double.parseDouble((String) incoming.get("threshold")); result = evaluateExpression(expression, param, threshold); } catch (Exception ex) { if (App.showExceptions) ex.printStackTrace(); } logger.info("received expression: " + incoming.get("exp")); logger.info("expression evaluation result: " + result); //construct proper JSON response. outgoing.put("info", "t-nova expression evaluation service"); if (result != null && result.length() != 0) { outgoing.put("result", result); outgoing.put("status", "ok"); KPI.expressions_evaluated += 1; KPI.api_calls_success += 1; return Response.ok(outgoing.toJSONString(), MediaType.APPLICATION_JSON_TYPE).build(); } else { outgoing.put("status", "execution failed"); outgoing.put("msg", "malformed request parameters, check your expression or parameter list for correctness."); KPI.expressions_evaluated += 1; KPI.api_calls_failed += 1; return Response.status(Response.Status.BAD_REQUEST).entity(outgoing.toJSONString()) .encoding(MediaType.APPLICATION_JSON).build(); } }
From source file:org.sift.batch.tuple.ProcessorChainItemProcessor.java
/** * Interface method implementation. Subjects the specified Tuple through a set of configured {@link Processor} instances, * @see org.springframework.batch.item.ItemProcessor#process(java.lang.Object) *///from w w w .ja va2 s . c o m @SuppressWarnings("unchecked") public S process(T paramTuple) throws Exception { Tuple tuple = (Tuple) paramTuple; //Stack holding list of tuples to be passed on to the next Processor Stack<Tuple> returnedTuples = new Stack<Tuple>(); returnedTuples.push(tuple); for (Processor p : this.getProcessors()) { MemOutputCollector collector = new MemOutputCollector(); //Process all the tuples for (Tuple returnTuple : returnedTuples) { p.process(returnTuple, collector); } //Clear and add the new tuples returnedTuples.clear(); returnedTuples.addAll(collector.getEmittedTuples()); // clear the collector as we are done processing the Tuple instances that it is holding collector.getEmittedTuples().clear(); } List<Tuple> returnTuples = new LinkedList<Tuple>(returnedTuples); return (S) returnTuples; }
From source file:com.github.stephenc.javaisotools.sabre.impl.XMLAtomHandler.java
public XMLAtomHandler(ContentHandler contentHandler, String namespace, String prefix) { this.contentHandler = contentHandler; this.namespace = namespace; this.prefix = prefix; this.elements = new Stack(); }
From source file:com.qwazr.utils.WildcardMatcher.java
/** * Match the passed name with the current pattern * * @param name the string to test * @param caseSensitivity/* www. ja v a 2 s .co m*/ * @return true if the name match the pattern */ public boolean match(String name, IOCase caseSensitivity) { if (name == null && wcs == null) { return true; } if (name == null || wcs == null) { return false; } if (caseSensitivity == null) { caseSensitivity = IOCase.SENSITIVE; } int length = name.length(); boolean anyChars = false; int textIdx = 0; int wcsIdx = 0; Stack<int[]> backtrack = new Stack<int[]>(); // loop around a backtrack stack, to handle complex * matching do { if (backtrack.size() > 0) { int[] array = backtrack.pop(); wcsIdx = array[0]; textIdx = array[1]; anyChars = true; } // loop whilst tokens and text left to process while (wcsIdx < wcs.length) { if (wcs[wcsIdx].equals("?")) { // ? so move to next text char textIdx++; if (textIdx > length) { break; } anyChars = false; } else if (wcs[wcsIdx].equals("*")) { // set any chars status anyChars = true; if (wcsIdx == wcs.length - 1) { textIdx = length; } } else { // matching text token if (anyChars) { // any chars then try to locate text token textIdx = caseSensitivity.checkIndexOf(name, textIdx, wcs[wcsIdx]); if (textIdx == -1) { // token not found break; } int repeat = caseSensitivity.checkIndexOf(name, textIdx + 1, wcs[wcsIdx]); if (repeat >= 0) { backtrack.push(new int[] { wcsIdx, repeat }); } } else { // matching from current position if (!caseSensitivity.checkRegionMatches(name, textIdx, wcs[wcsIdx])) { // couldnt match token break; } } // matched text token, move text index to end of matched token textIdx += wcs[wcsIdx].length(); anyChars = false; } wcsIdx++; } // full match if (wcsIdx == wcs.length && textIdx == length) { return true; } } while (backtrack.size() > 0); return false; }