Example usage for java.util Stack Stack

List of usage examples for java.util Stack Stack

Introduction

In this page you can find the example usage for java.util Stack Stack.

Prototype

public Stack() 

Source Link

Document

Creates an empty Stack.

Usage

From source file:cf.adriantodt.utils.HTML2Discord.java

public static String toPlainText(String discordFormatMessage) {
    String strippedContent;/*  w ww.  j  a  v a 2 s .  co  m*/
    //all the formatting keys to keep track of
    String[] keys = new String[] { "*", "_", "`", "~~" };

    //find all tokens (formatting strings described above)
    TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start));
    for (String key : keys) {
        Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(discordFormatMessage);
        while (matcher.find()) {
            tokens.add(new FormatToken(key, matcher.start()));
        }
    }

    //iterate over all tokens, find all matching pairs, and add them to the list toRemove
    Stack<FormatToken> stack = new Stack<>();
    List<FormatToken> toRemove = new ArrayList<>();
    boolean inBlock = false;
    for (FormatToken token : tokens) {
        if (stack.empty() || !stack.peek().format.equals(token.format)
                || stack.peek().start + token.format.length() == token.start) {
            //we are at opening tag
            if (!inBlock) {
                //we are outside of block -> handle normally
                if (token.format.equals("`")) {
                    //block start... invalidate all previous tags
                    stack.clear();
                    inBlock = true;
                }
                stack.push(token);
            } else if (token.format.equals("`")) {
                //we are inside of a block -> handle only block tag
                stack.push(token);
            }
        } else if (!stack.empty()) {
            //we found a matching close-tag
            toRemove.add(stack.pop());
            toRemove.add(token);
            if (token.format.equals("`") && stack.empty()) {
                //close tag closed the block
                inBlock = false;
            }
        }
    }

    //sort tags to remove by their start-index and iteratively build the remaining string
    Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start));
    StringBuilder out = new StringBuilder();
    int currIndex = 0;
    for (FormatToken formatToken : toRemove) {
        if (currIndex < formatToken.start) {
            out.append(discordFormatMessage.substring(currIndex, formatToken.start));
        }
        currIndex = formatToken.start + formatToken.format.length();
    }
    if (currIndex < discordFormatMessage.length()) {
        out.append(discordFormatMessage.substring(currIndex));
    }
    //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block
    strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    return strippedContent;
}

From source file:com.medigy.persist.model.session.SessionManager.java

public SessionManager() {
    threadSession.set(new Stack<Session>());
}

From source file:org.liberty.android.fantastischmemo.downloader.DownloaderAnyMemo.java

@Override
protected void initialRetrieve() {
    dlAdapter = new DownloadListAdapter(this, R.layout.filebrowser_item);
    dlStack = new Stack<ArrayList<DownloadItem>>();
    mHandler = new Handler();
    listView = (ListView) findViewById(R.id.file_list);
    listView.setAdapter(dlAdapter);/*  w  w  w  .  ja  v a  2 s.c  o m*/
    mProgressDialog = ProgressDialog.show(this, getString(R.string.loading_please_wait),
            getString(R.string.loading_connect_net), true, true, new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    finish();
                }
            });
    new Thread() {
        public void run() {
            try {
                final ArrayList<DownloadItem> list = obtainCategories();
                mHandler.post(new Runnable() {
                    public void run() {
                        dlAdapter.addList(list);
                        sortAdapter();
                        mProgressDialog.dismiss();
                    }
                });

            } catch (final Exception e) {
                mHandler.post(new Runnable() {
                    public void run() {
                        Log.e(TAG, "Error obtaining categories", e);
                        new AlertDialog.Builder(DownloaderAnyMemo.this)
                                .setTitle(getString(R.string.downloader_connection_error))
                                .setMessage(
                                        getString(R.string.downloader_connection_error_message) + e.toString())
                                .setNeutralButton(getString(R.string.back_menu_text),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface arg0, int arg1) {
                                                finish();
                                            }
                                        })
                                .create().show();
                    }
                });
            }
        }
    }.start();
}

From source file:com.joliciel.jochre.graphics.features.InnerEmptyChupchikLowerLeftFeature.java

@Override
public FeatureResult<Boolean> checkInternal(ShapeWrapper shapeWrapper, RuntimeEnvironment env) {
    Shape shape = shapeWrapper.getShape();
    BitSet bitset = shape.getBlackAndWhiteBitSet(shape.getJochreImage().getBlackThreshold());
    boolean[][] grid = new boolean[shape.getWidth()][shape.getHeight()];
    for (int i = 0; i < shape.getWidth(); i++) {
        for (int j = 0; j < shape.getHeight(); j++) {
            if (bitset.get(j * shape.getWidth() + i))
                grid[i][j] = true;/*w w w  . j a  va2 s .c o m*/
        }
    }
    int startX = shape.getWidth() / 2;
    int startY = shape.getHeight() / 2;
    while (startY < shape.getHeight() && grid[startX][startY]) {
        startY += 1;
    }

    WritableImageGrid mirror = this.graphicsService.getEmptyMirror(shape);

    boolean foundChupchikOrOpening = false;
    if (startY < shape.getHeight()) {
        Stack<HorizontalLineSegment> whiteLineStack = new Stack<HorizontalLineSegment>();
        Set<HorizontalLineSegment> whiteLineSet = new TreeSet<HorizontalLineSegment>();
        HorizontalLineSegment startLine = new HorizontalLineSegment(startX, startY);
        whiteLineStack.push(startLine);
        while (!whiteLineStack.empty()) {
            HorizontalLineSegment line = whiteLineStack.pop();
            if (line.y == shape.getHeight() - 1) {
                // found opening to the outside world
                if (LOG.isTraceEnabled())
                    LOG.trace("Reached edge: found opening");
                foundChupchikOrOpening = true;
                break;
            }
            if (mirror.getPixel(line.xLeft, line.y) == 1)
                continue;

            // extend this line to the right and left
            for (int i = line.xLeft; i >= 0; i--) {
                if (!grid[i][line.y])
                    line.xLeft = i;
                else
                    break;
            }
            for (int i = line.xRight; i <= startX; i++) {
                if (!grid[i][line.y])
                    line.xRight = i;
                else
                    break;
            }
            if (LOG.isTraceEnabled())
                LOG.trace(line.toString());
            whiteLineSet.add(line);

            for (int i = line.xLeft; i <= line.xRight; i++) {
                mirror.setPixel(i, line.y, 1);
            }

            // find lines below and to the left
            if (line.y < shape.getHeight() - 1) {
                boolean inLine = false;
                int row = line.y + 1;
                int xLeft = 0;
                for (int i = line.xLeft; i <= line.xRight; i++) {
                    if (!inLine && !grid[i][row]) {
                        inLine = true;
                        xLeft = i;
                    } else if (inLine && grid[i][row]) {
                        HorizontalLineSegment newLine = new HorizontalLineSegment(xLeft, row);
                        newLine.xRight = i - 1;
                        whiteLineStack.push(newLine);
                        inLine = false;
                    }
                }
                if (inLine) {
                    HorizontalLineSegment newLine = new HorizontalLineSegment(xLeft, row);
                    newLine.xRight = line.xRight;
                    whiteLineStack.push(newLine);
                }
            }
        }

        if (!foundChupchikOrOpening) {
            //            if (LOG.isDebugEnabled()) {
            //               LOG.trace("List of lines");
            //               for (HorizontalLineSegment line : whiteLineSet) {
            //                  LOG.trace(line.toString());
            //               }
            //            }
            Iterator<HorizontalLineSegment> iLines = whiteLineSet.iterator();
            HorizontalLineSegment bottomLeftLine = iLines.next();
            double threshold = shape.getWidth() / 8;
            if (LOG.isTraceEnabled())
                LOG.trace("Length threshold: " + threshold);
            HorizontalLineSegment nextLine = null;
            List<HorizontalLineSegment> firstFewLines = new ArrayList<HorizontalLineSegment>();
            firstFewLines.add(bottomLeftLine);
            HorizontalLineSegment currentLine = bottomLeftLine;
            while (iLines.hasNext() && firstFewLines.size() < 3) {
                nextLine = iLines.next();
                if (nextLine.y != currentLine.y) {
                    firstFewLines.add(nextLine);
                    currentLine = nextLine;
                }
            }
            boolean mightHaveChupchik = true;
            HorizontalLineSegment prevLine = null;
            for (HorizontalLineSegment line : firstFewLines) {
                if (LOG.isTraceEnabled())
                    LOG.trace("Next line left, " + bottomLeftLine.xLeft + ", length: " + bottomLeftLine.length()
                            + ", threshold: " + threshold);
                if (line.length() > threshold) {
                    mightHaveChupchik = false;
                    break;
                }
                if (prevLine != null) {
                    if (line.xLeft + 2 < prevLine.xLeft) {
                        mightHaveChupchik = false;
                        break;
                    }
                    if (line.length() + 1 < prevLine.length()) {
                        mightHaveChupchik = false;
                        break;
                    }
                }
                prevLine = line;
                threshold = threshold * 1.2;
            }
            if (mightHaveChupchik)
                foundChupchikOrOpening = true;
        }
    }

    FeatureResult<Boolean> outcome = this.generateResult(foundChupchikOrOpening);
    return outcome;
}

From source file:com.webcohesion.ofx4j.io.tagsoup.TestTagSoupOFXReader.java

/**
 * tests using sax to parse an OFX doc.//from  w ww  . ja v a  2  s  .c o m
 */
public void testSimpleVersion1() throws Exception {
    TagSoupOFXReader reader = new TagSoupOFXReader();
    final Map<String, String> headers = new HashMap<String, String>();
    final Stack<Map<String, Object>> aggregateStack = new Stack<Map<String, Object>>();
    TreeMap<String, Object> root = new TreeMap<String, Object>();
    aggregateStack.push(root);

    reader.setContentHandler(new DefaultHandler() {

        @Override
        public void onHeader(String name, String value) {
            LOG.debug(name + ":" + value);
            headers.put(name, value);
        }

        @Override
        public void onElement(String name, String value) {
            char[] tabs = new char[aggregateStack.size() * 2];
            Arrays.fill(tabs, ' ');
            LOG.debug(new String(tabs) + name + "=" + value);

            aggregateStack.peek().put(name, value);
        }

        @Override
        public void startAggregate(String aggregateName) {
            char[] tabs = new char[aggregateStack.size() * 2];
            Arrays.fill(tabs, ' ');
            LOG.debug(new String(tabs) + aggregateName + " {");

            TreeMap<String, Object> aggregate = new TreeMap<String, Object>();
            aggregateStack.peek().put(aggregateName, aggregate);
            aggregateStack.push(aggregate);
        }

        @Override
        public void endAggregate(String aggregateName) {
            aggregateStack.pop();

            char[] tabs = new char[aggregateStack.size() * 2];
            Arrays.fill(tabs, ' ');
            LOG.debug(new String(tabs) + "}");
        }
    });
    reader.parse(TestNanoXMLOFXReader.class.getResourceAsStream("simple.ofx"));
    assertEquals(9, headers.size());
    assertEquals(1, aggregateStack.size());
    assertSame(root, aggregateStack.pop());
}

From source file:com.googlecode.promnetpp.translation.StandardTranslator.java

@Override
public void init() {
    if (!(Options.outputDirectory.equals("."))) {
        Utilities.makeDirectory(Options.outputDirectory);
    }//from   ww w.j  ava  2  s. c  o m
    //Initialize writers
    typeDefinitions = new IndentedStringWriter();
    globalDeclarations = new IndentedStringWriter();
    globalDefinitions = new IndentedStringWriter();
    //Initialize init process
    initProcess = new Process("init");
    //Initialize the various hash maps
    functions = new HashMap<String, Function>();
    macros = new HashMap<String, String>();
    nonMacros = new HashMap<String, String>();
    processes = new HashMap<String, Process>();
    //Other
    stepStack = new Stack<Integer>();
    templateParameters = new Stack<String>();

    Logger.getLogger(StandardTranslator.class.getName()).log(Level.INFO,
            "Translation process ready. Output directory: {0}", Options.outputDirectory);
}

From source file:com.movento.webview.impl.TiWebViewBinding.java

public TiWebViewBinding(WebView webView) {
    codeSnippets = new Stack<String>();
    this.webView = webView;
    apiBinding = new ApiBinding();
    appBinding = new AppBinding();
    tiReturn = new TiReturn();
}

From source file:com.universalavenue.ticrosswalk.WebViewBinding.java

public WebViewBinding(XWalkView webView) {
    codeSnippets = new Stack<String>();
    this.webView = webView;
    apiBinding = new ApiBinding();
    appBinding = new AppBinding();
    tiReturn = new TiReturn();

    addJavascriptInterfaces();//from  w w  w .  j  a va2 s .co  m
}

From source file:edu.umd.honghongie.BooleanRetrievalHBase.java

private void initialize(String tableName, String collectionPath, FileSystem fs) throws IOException {
    //initialize index
    Configuration conf = getConf();
    conf.addResource(new Path("/etc/hbase/conf/hbase-site.xml"));

    Configuration hbaseConfig = HBaseConfiguration.create(conf);
    HConnection hbaseConnection = HConnectionManager.createConnection(hbaseConfig);
    index = hbaseConnection.getTable(tableName);

    collection = fs.open(new Path(collectionPath));
    stack = new Stack<Set<Integer>>();
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.penntree.PennTreeUtils.java

public static PennTreeNode parsePennTree(String aTree) {
    StringTokenizer st = new StringTokenizer(aTree, "() ", true);

    PennTreeNode root = null;//from w w w.jav a2 s  .  c  o m
    Stack<PennTreeNode> stack = new Stack<PennTreeNode>();
    boolean seenLabel = false;

    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.setLabel(t);
            p.addChild(n);
        } else {
            PennTreeNode n = stack.peek();
            n.setLabel(t);
            seenLabel = true;
        }
    }

    return root;
}