/** * Accomodates the paths opened in editor to the given new path. This should be used only to open * existing directories. * * @param newPath * @param openLast * @param lastRevision * @throws SVNException */ public void accomodate(String newPath, boolean openLast, long lastRevision) throws SVNException { // If there's a file opened, always closing it. if (fileOnTop) { // Checking if we don't want to have the same file opened. if (newPath.equals(pathsStack.peek())) return; editor.closeFile(pathsStack.pop(), null); fileOnTop = false; } // Poping and closing all opened directories which // don't fit into the new path. while ((!pathsStack.empty()) && (!newPath.startsWith(pathsStack.peek()))) { pathsStack.pop(); editor.closeDir(); } // Opening directories from the new path and putting their paths on the // stack. String currentPath = pathsStack.empty() ? "/" : pathsStack.peek(); String[] parts = newPath.substring(currentPath.length()).split("[/]"); for (int i = 0; i < (openLast ? parts.length : parts.length - 1); i++) { /* * A path part may be empty in two cases: * 1. pathStack.peek() is equal to newPath * 2. newPath = properPath + "/" * In both cases we don't want to open the "empty" directory. */ if (!"".equals(parts[i])) { currentPath += Tools.addPaths(parts[i], ""); editor.openDir(currentPath, lastRevision); pathsStack.push(currentPath); } } }
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { ModelReader8Handler.ElementHandler current = (myHandlersStack.empty() ? (ModelReader8Handler.ElementHandler) null : myHandlersStack.peek()); if (current == null) { // root current = modelhandler; } else { current = current.createChild(myValues.peek(), qName, attributes); } // check required for (String attr : current.requiredAttributes()) { if (attributes.getValue(attr) == null) { throw new SAXParseException("attribute " + attr + " is absent", null); } } Object result = current.createObject(attributes); if (myHandlersStack.empty()) { myResult = (ModelLoadResult) result; } // handle attributes for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getQName(i); String value = attributes.getValue(i); current.handleAttribute(result, name, value); } myHandlersStack.push(current); myValues.push(result); }
private void processOperator(char op) { if (operatorStack.empty()) { operatorStack.push(op); } else { char topOp = operatorStack.peek(); if (op == '(') { operatorStack.push(op); } else if ((topOp == '(' || precedence(op) > precedence(topOp)) && op != ')') { operatorStack.push(op); } else if (op == ')') { while (topOp != '(') { operatorStack.pop(); postfixDeque.add(String.valueOf(topOp)); if (!operatorStack.empty()) { topOp = operatorStack.peek(); } } operatorStack.pop(); // removes the right parenthesis } else { // Pop all stacked operators with equal // or higher precedence than op. while (!operatorStack.empty() && precedence(op) <= precedence(topOp) && topOp != '(') { operatorStack.pop(); postfixDeque.add(String.valueOf(topOp)); if (!operatorStack.empty()) { // Reset topOp. topOp = operatorStack.peek(); } } operatorStack.push(op); } } }
public void redo() { // add the endChange marker to redo if we can undo if (!redoStack.empty()) { undoStack.push(endChange); undoNotifyStack.push(endChange); } // keep undoing until the undo stack is empty, or we hit a stop action while (!redoStack.empty()) { // get the current change Change currentChange = redoStack.pop(); // if it is a stop action, break the loop if (currentChange == endChange) break; currentChange.redo(); // add the change to the redo stack undoStack.push(currentChange); } // find everyone to notify while (!redoNotifyStack.empty()) { ChangeNotification currentNotification = redoNotifyStack.pop(); if (currentNotification == endChange) break; currentNotification.notifyChange(); undoNotifyStack.push(currentNotification); } }
/** Create a random Json document with random values */ public String getRandomJson(int nbNodes) { // init sb.setLength(0); sb.append("{"); states.clear(); states.add(OBJECT_ATT); images.clear(); nodes.clear(); incr.clear(); datatypes.clear(); types.clear(); curNodePath.length = 1; curNodePath.offset = 0; Arrays.fill(curNodePath.ints, -1); shouldFail = false; nestedObjs = 0; // <= so that when nbNodes == 1, the json is still valid /* * the generated json might be uncomplete, if states is not empty, and * the maximum number of nodes has been reached. */ for (final int i = 0; i <= nbNodes && !states.empty(); nbNodes++) { sb.append(this.getWhitespace()).append(this.getNextNode()).append(this.getWhitespace()); } shouldFail = shouldFail ? true : !states.empty(); return sb.toString(); }
private void setLandscapeCommon(final List<Pair<String, Float>> landscape) { this.landscape = landscape; if (!stkLineChartZoom.empty()) { pnlLineChart.setViewport(stkLineChartZoom.get(0)); stkLineChartZoom.clear(); } if (landscape == null) { landscapeMin = landscapeMax = null; } else { float min = Float.POSITIVE_INFINITY; float max = Float.NEGATIVE_INFINITY; for (final Pair<String, Float> p : landscape) { final float fitness = p.getSecond(); if (Float.isInfinite(fitness)) { continue; } if (fitness < min) { min = fitness; } if (fitness > max) { max = fitness; } } landscapeMin = new Float(min - max * 0.05); landscapeMax = new Float(max * 1.05); } if (!stkHistogramZoom.empty()) { pnlHistogram.setViewport(stkHistogramZoom.get(0)); stkHistogramZoom.clear(); } if (useMinMax && (landscapeMin != null) && (landscapeMax != null)) { pnlHistogram.setBins( binLandscape(((Number) spnBins.getValue()).intValue()), landscapeMin.floatValue(), landscapeMax.floatValue()); } else { pnlHistogram.setBins(binLandscape(((Number) spnBins.getValue()).intValue())); } // cboDisplayType.setSelectedIndex(0); if (landscape == null) { txaRaw.setText(""); } else { final StringBuffer b = new StringBuffer(); if (rawTextComparator != null) { Collections.sort(landscape, rawTextComparator); } b.append(getXAxisLabel()); b.append('\t'); b.append(getYAxisLabel()); b.append('\n'); for (final Pair<String, Float> p : landscape) { b.append(p.getFirst()); b.append('\t'); b.append(Float.toString(p.getSecond())); b.append('\n'); } txaRaw.setText(b.toString()); txaRaw.select(0, 0); } }
public synchronized void unpack(ISOComponent c, InputStream in) throws ISOException, IOException { LogEvent evt = new LogEvent(this, "unpack"); try { if (!(c instanceof ISOMsg)) throw new ISOException("Can't call packager on non Composite"); while (!stk.empty()) // purge from possible previous error stk.pop(); reader.parse(new InputSource(in)); if (stk.empty()) throw new ISOException("error parsing"); ISOMsg m = (ISOMsg) c; m.merge((ISOMsg) stk.pop()); if (logger != null) evt.addMessage(m); } catch (ISOException e) { evt.addMessage(e); throw e; } catch (SAXException e) { evt.addMessage(e); throw new ISOException(e.toString()); } finally { Logger.log(evt); } }
public void postOrder() { Stack<BiNode> stk = new Stack<BiNode>(); BiNode lastVisited = null; stk.push(root); while (!stk.empty()) { BiNode tmp = stk.peek(); while (tmp != null) { tmp = tmp.left; stk.push(tmp); } stk.pop(); while (!stk.empty()) { tmp = stk.peek(); if (tmp.right == null || tmp.right.equals(lastVisited)) { tmp.visit(); lastVisited = tmp; stk.pop(); } else { stk.push(tmp.right); break; } } } System.out.println(); }
private void removeStackObj() throws XMLStreamException { if (!stackObj.empty()) { if (topNestedArrayObj == null) { stackObj.pop(); } else { if (stackObj.peek().equals(topNestedArrayObj)) { topNestedArrayObj = null; processedJsonObject.clear(); stackObj.pop(); } else { processedJsonObject.push(stackObj.pop()); } } if (!stackObj.empty()) { localName = stackObj.peek().getName(); } else { localName = ""; } } else { System.out.println("stackObj is empty"); throw new XMLStreamException( "Error while processing input JSON stream, JSON request may not valid ," + " it may has more end object characters "); } }
/** * Fired when a target finishes building, this adds the time taken and any error stacktrace to the * appropriate target element in the log. * * @param event An event with any relevant extra information. Will not be <code>null</code>. */ public void targetFinished(BuildEvent event) { System.out.println("target finished in cruise control HeliumCCLogger"); Target target = event.getTarget(); TimedElement targetElement = (TimedElement) targets.get(target); if (targetElement != null) { long totalTime = System.currentTimeMillis() - targetElement.startTime; // targetElement.element.setAttribute(TIME_ATTR, // DefaultLogger.formatTime(totalTime)); TimedElement parentElement = null; Stack threadStack = getStack(); if (!threadStack.empty()) { TimedElement poppedStack = (TimedElement) threadStack.pop(); if (poppedStack != targetElement) { throw new RuntimeException( "Mismatch - popped element = " + poppedStack + " finished target element = " + targetElement); } if (!threadStack.empty()) { parentElement = (TimedElement) threadStack.peek(); } } if (parentElement == null) { buildElement.element.appendChild(targetElement.element); } else { parentElement.element.appendChild(targetElement.element); } } targets.remove(target); }
public boolean forward() { if (!forw.empty()) { URL next = (forw.pop()); history.push(getPage()); setPageOnly(next, null); } return !forw.empty(); }
public boolean back() { if (!history.empty()) { URL prev = (history.pop()); forw.push(getPage()); setPageOnly(prev, null); } return !history.empty(); }
public DirectoryDescendingFileFinderImpl(File root, FilenameFilter filter, boolean canonical) throws IOException { if (!root.isDirectory()) throw new IllegalArgumentException(root.getName() + " is not a directory."); this.filter = filter; this.canonical = canonical; blossomDirectory(root); while (files.empty() && !direx.empty()) blossomDirectory((File) direx.pop()); }
public int pollFirst() throws Exception { if (size() == 0) throw new Exception("no elements !"); if (!stack2.empty()) { return stack2.pop(); } else { while (!stack1.empty()) stack2.push(stack1.pop()); return stack2.pop(); } }
/** * Fetches the List from the Stack and adds it to the TextElementArray on top of the Stack, or to * the Document if the Stack is empty. * * @throws DocumentException * @since 5.0.6 */ public void processList() throws DocumentException { if (stack.empty()) return; Element obj = stack.pop(); if (!(obj instanceof com.itextpdf.text.List)) { stack.push(obj); return; } if (stack.empty()) document.add(obj); else ((TextElementArray) stack.peek()).add(obj); }
public static boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') stack.push(s.charAt(i)); else if (s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(') stack.pop(); else if (s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[') stack.pop(); else if (s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{') stack.pop(); else return false; } return stack.empty(); }
private synchronized Object doOperation(Object value, EditorMonitorOperation operation) { if (activo) { if (operation == EditorMonitorOperation.addUndo) { this.undoStack.add(value); this.redoStack.clear(); } if (operation == EditorMonitorOperation.doUndo) { try { if (!undoStack.empty()) { Object actualValue = PropertyUtils.getProperty(target, property); this.redoStack.push(actualValue); Object oldValue = this.undoStack.pop(); this.ignoreUpdate(oldValue); PropertyUtils.setProperty(target, property, oldValue); } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { Logger.getLogger(PropertyEditorMonitor.class.getName()).log(Level.SEVERE, null, ex); } } if (operation == EditorMonitorOperation.doRedo) { try { if (!redoStack.empty()) { Object actualValue = PropertyUtils.getProperty(target, property); this.undoStack.push(actualValue); Object nextValue = this.redoStack.pop(); this.ignoreUpdate(nextValue); PropertyUtils.setProperty(target, property, nextValue); } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { Logger.getLogger(PropertyEditorMonitor.class.getName()).log(Level.SEVERE, null, ex); } } if (operation == EditorMonitorOperation.clear) { this.undoStack.clear(); this.redoStack.clear(); } if (operation == EditorMonitorOperation.desactiva) { this.activo = false; } } else { if (operation == EditorMonitorOperation.activa) { this.activo = true; } } if (operation == EditorMonitorOperation.getValue) { try { return PropertyUtils.getProperty(target, property); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { Logger.getLogger(PropertyEditorMonitor.class.getName()).log(Level.SEVERE, null, ex); } } return null; }
public Stack<Integer> sort(Stack<Integer> stack) { Stack<Integer> tempStack = new Stack<Integer>(); while (!stack.empty()) { Integer top = stack.pop(); while (!tempStack.empty() && top < tempStack.peek()) { stack.push(tempStack.pop()); } tempStack.push(top); } while (!tempStack.empty()) stack.push(tempStack.pop()); return stack; }
public int peek() throws Exception { if (size() == 0) { throw new Exception("no elements !"); } if (!stack2.empty()) { return stack2.peek(); } else { while (!stack1.empty()) { stack2.push(stack1.pop()); } return stack2.peek(); } }
public static void preOrderTraverse2(TreeNode node) { Stack<TreeNode> stack = new Stack<TreeNode>(); while (node != null || !stack.empty()) { while (node != null) { System.out.println(node.val + " "); stack.push(node); node = node.leftChild; } if (!stack.empty()) { node = stack.pop(); node = node.rightChild; } } }
private static void parseOperator(Character currentOperator) { // execute operator if its precedence is lower than or equal to stack's peek, else push to stack Character stackPeek = operators.empty() ? ' ' : operators.peek(); HashMap<Character, Integer> operatorsPrecedence = new HashMap<Character, Integer>(); operatorsPrecedence.put('(', 10); operatorsPrecedence.put(')', 10); operatorsPrecedence.put('*', 9); operatorsPrecedence.put('+', 9); operatorsPrecedence.put('.', 8); operatorsPrecedence.put('|', 7); int currentPrecedence = operatorsPrecedence.get(currentOperator); int stackPeekPrecedence = operators.empty() ? 0 : operatorsPrecedence.get( stackPeek); // 0 not needed, it would enter in operators.empty case if (currentOperator == ')') { // pop and execute from stack till '(' executeBracket(); } else if (operators.empty() || operators.peek() == '(' || currentOperator == '(' || currentPrecedence > stackPeekPrecedence) { operators.push(currentOperator); } else { while (true) { if (currentPrecedence <= stackPeekPrecedence && stackPeek != '(') { NFA secondOperandNFA = operands.pop(); NFA resultNFA; if (stackPeek == '.' | stackPeek == '|') { NFA firstOperandNFA = operands.pop(); resultNFA = generateNFA(stackPeek, firstOperandNFA, secondOperandNFA); } else { resultNFA = generateNFA(stackPeek, secondOperandNFA, null); } operands.push(resultNFA); operators.pop(); stackPeek = operators.empty() ? ' ' : operators.peek(); stackPeekPrecedence = operators.empty() ? 0 : operatorsPrecedence.get(stackPeek); } else { break; } } operators.push(currentOperator); } }
public static void main(String args[]) throws Exception { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line = stdin.readLine(); StringTokenizer st = new StringTokenizer(line); int n = Integer.parseInt(st.nextToken()); long values[] = new long[n + 1]; long sums[] = new long[n + 1]; line = stdin.readLine(); st = new StringTokenizer(line); for (int i = 1; i <= n; i++) { values[i] = Integer.parseInt(st.nextToken()); sums[i] = sums[i - 1] + values[i]; } int rights[] = new int[n + 1]; Stack<Integer> stack = new Stack<Integer>(); for (int i = 1; i <= n; i++) { while (stack.empty() == false && values[stack.peek()] > values[i]) { rights[stack.pop()] = i - 1; } stack.push(i); } while (stack.empty() == false) { rights[stack.pop()] = n; } int lefts[] = new int[n + 1]; stack = new Stack<Integer>(); for (int i = n; i >= 1; i--) { while (stack.empty() == false && values[stack.peek()] > values[i]) { lefts[stack.pop()] = i + 1; } stack.push(i); } while (stack.empty() == false) { lefts[stack.pop()] = 1; } long max = -1; int left = -1; int right = -1; for (int i = 1; i <= n; i++) { long temp = values[i] * (sums[rights[i]] - sums[lefts[i] - 1]); if (temp > max) { max = temp; left = lefts[i]; right = rights[i]; } } System.out.println(max); System.out.println(left + " " + right); }
/* <exercise chapter="3" section="2" type="programming" number="1"> */ public static String reverseWords(String sentence) { String[] words = sentence.split("\\s+"); Stack<String> stack = new Stack<String>(); for (String word : words) { stack.push(word); } StringBuilder stb = new StringBuilder(); while (!stack.empty()) { stb.append(stack.pop()); if (!stack.empty()) { stb.append(" "); } } return stb.toString(); }
private static long computeExpression(Stack<Long> oper, String op) { if (oper.empty()) return -1; long oper1 = oper.pop(); if (oper.empty()) return -1; long oper2 = oper.pop(); if ("*".equals(op)) { return oper1 * oper2; } else { long result = 1; for (long i = 0; i < oper1; i++) { result *= oper2; } return result; } }
public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); // Iterate through string until empty for (int i = 0; i < s.length(); i++) { // Push any open parentheses onto stack if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') stack.push(s.charAt(i)); // Check stack for corresponding closing parentheses, false if not valid else if (s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(') stack.pop(); else if (s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[') stack.pop(); else if (s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{') stack.pop(); else return false; } // return true if no open parentheses left in stack return stack.empty(); }
public void reorderList(ListNode head) { if (head == null || head.next == null || head.next.next == null) { return; } ListNode oneStep = head; ListNode twoStep = head; while (twoStep != null && twoStep.next != null) { twoStep = twoStep.next.next; oneStep = oneStep.next; } ListNode half = oneStep.next; oneStep.next = null; Stack<ListNode> stack = new Stack<ListNode>(); while (half != null) { stack.push(half); half = half.next; } ListNode tmp = head; while (head != null) { ListNode oldRight = head.next; if (stack.empty()) { break; } head.next = stack.pop(); head.next.next = oldRight; head = oldRight; } head = tmp; }
@SuppressWarnings("rawtypes") @Override public boolean visit(ClassInstanceCreation node) { List args = node.arguments(); Map<String, Integer> scopeBindings = getNodeScopes().get(node); List<String> argTypes = translateArgsToTypes(args, scopeBindings); String type = getNameOfType(node.getType()); if (!methodStack.empty()) { MethodDeclaration currentMethod = methodStack.peek(); MethodDecl methodDecl = getMethodDecl(currentMethod); List<MethodInvokRef> invoks = methodInvoks.get(methodDecl); if (invoks == null) { invoks = new ArrayList<>(); methodInvoks.put(methodDecl, invoks); } MethodInvokRef methodInvokRef = new MethodInvokRef( removeSpecialSymbols(node.getType().toString()), type, "", args.size(), node.getStartPosition(), argTypes, node.getLength(), true, getReturnType(node)); invoks.add(methodInvokRef); } return super.visit(node); }
/** * @param tagType * @param text * @param tagContent * @param tagName ; */ private void addInnerTagBean( TagType tagType, StringBuffer text, String tagContent, String tagName) { /* 在文本中插入索引 */ int index = -1; if (tagType == START) { HasStartTag = true; maxIndex++; indexStack.push(maxIndex); index = maxIndex; } else if (tagType == END) { if (!HasStartTag) { maxIndex++; indexStack.push(maxIndex); } HasStartTag = false; if (!indexStack.empty()) { index = indexStack.pop(); } } else if (tagType == STANDALONE) { maxIndex++; index = maxIndex; } if (index > -1) { InnerTagBean bean = new InnerTagBean(index, tagName, tagContent, tagType); beans.add(bean); SegmentText stText = new SegmentText(start, start + tagContent.length(), tagContent); lstSegment.add(stText); String placeHolder = placeHolderCreater.getPlaceHolder(beans, beans.size() - 1); text.replace(start, start + tagContent.length(), placeHolder); } }
public static boolean isPalindrome(Node n) { Node slow = n; Node fast = n; Stack<Integer> stack = new Stack<Integer>(); while (fast != null && fast.next != null) { stack.push(slow.data); slow = slow.next; fast = fast.next.next; } // odd number, skip the middle one if (fast != null) { slow = slow.next; } while (!stack.empty()) { int top = stack.pop(); if (slow.data != top) { return false; } slow = slow.next; } return true; }
public void printSolution() { String currState = "www0bbb"; File file = new File("solution_slidingtile_dfs.txt"); try { FileWriter fw = new FileWriter(file); path.push(currState); while (parentMap.get(currState) != null) { // System.out.println("inside while, parentMap.get(currState)!=null"); path.push(parentMap.get(currState)); currState = parentMap.get(currState); } System.out.println("Solution path:"); while (!path.empty()) { // System.out.println("inside while, stack not empty"); // System.out.println(path.pop()); fw.write(path.pop()); fw.write("\n"); } fw.close(); } catch (IOException ie) { ie.printStackTrace(); } finally { } }