switch(// see also parseUnaryExpr()
        token) {
            case LongConstant:
            case IntConstant:
            case CharConstant:
                lex.get();
                return new IntConst(lex.getLong(), token);
            case DoubleConstant:
            case FloatConstant:
                lex.get();
                return new DoubleConst(lex.getDouble(), token);
            default:
                break;
        }

/*
 * Javassist, a Java-bytecode translator toolkit.
 *
 */
package javassist.compiler;

import javassist.compiler.ast.*;

public final class Parser implements TokenId {

    private Lex lex;

    public Parser(Lex lex) {
        this.lex = lex;
    }

    public boolean hasMore() {
        return lex.lookAhead() >= 0;
    }

    public ASTList parseMember(SymbolTable tbl) throws CompileError {
        ASTList mem = parseMember1(tbl);
        if (mem instanceof MethodDecl)
            return parseMethod2(tbl, (MethodDecl) mem);
        else
            return mem;
    }

    /* A method body is not parsed.
     */
    public ASTList parseMember1(SymbolTable tbl) throws CompileError {
        ASTList mods = parseMemberMods();
        Declarator d;
        boolean isConstructor = false;
        if (lex.lookAhead() == Identifier && lex.lookAhead(1) == '(') {
            d = new Declarator(VOID, 0);
            isConstructor = true;
        } else
            d = parseFormalType(tbl);
        if (lex.get() != Identifier)
            throw new SyntaxError(lex);
        String name;
        if (isConstructor)
            name = MethodDecl.initName;
        else
            name = lex.getString();
        d.setVariable(new Symbol(name));
        if (isConstructor || lex.lookAhead() == '(')
            return parseMethod1(tbl, isConstructor, mods, d);
        else
            return parseField(tbl, mods, d);
    }

    private FieldDecl parseField(SymbolTable tbl, ASTList mods, Declarator d) throws CompileError {
        ASTree expr = null;
        if (lex.lookAhead() == '=') {
            lex.get();
            expr = parseExpression(tbl);
        }
        int c = lex.get();
        if (c == ';')
            return new FieldDecl(mods, new ASTList(d, new ASTList(expr)));
        else if (c == ',')
            throw new CompileError("only one field can be declared in one declaration", lex);
        else
            throw new SyntaxError(lex);
    }

    /* method.declaration
     *  : member.modifiers
     *    [ formal.type ]
     *    Identifier "(" [ formal.parameter ( "," formal.parameter )* ] ")"
     *    array.dimension
     *    [ THROWS class.type ( "," class.type ) ]
     *    ( block.statement | ";" )
     *
     * Note that a method body is not parsed.
     */
    private MethodDecl parseMethod1(SymbolTable tbl, boolean isConstructor, ASTList mods, Declarator d) throws CompileError {
        if (lex.get() != '(')
            throw new SyntaxError(lex);
        ASTList parms = null;
        if (lex.lookAhead() != ')')
            while (true) {
                parms = ASTList.append(parms, parseFormalParam(tbl));
                int t = lex.lookAhead();
                if (t == ',')
                    lex.get();
                else if (t == ')')
                    break;
            }
        lex.get();
        d.addArrayDim(parseArrayDimension());
        if (isConstructor && d.getArrayDim() > 0)
            throw new SyntaxError(lex);
        ASTList throwsList = null;
        if (lex.lookAhead() == THROWS) {
            lex.get();
            while (true) {
                throwsList = ASTList.append(throwsList, parseClassType(tbl));
                if (lex.lookAhead() == ',')
                    lex.get();
                else
                    break;
            }
        }
        return new MethodDecl(mods, new ASTList(d, ASTList.make(parms, throwsList, null)));
    }

    /* Parses a method body.
     */
    public MethodDecl parseMethod2(SymbolTable tbl, MethodDecl md) throws CompileError {
        Stmnt body = null;
        if (lex.lookAhead() == ';')
            lex.get();
        else {
            body = parseBlock(tbl);
            if (body == null)
                body = new Stmnt(BLOCK);
        }
        md.sublist(4).setHead(body);
        return md;
    }

    private ASTList parseMemberMods() {
        int t;
        ASTList list = null;
        while (true) {
            t = lex.lookAhead();
            if (t == ABSTRACT || t == FINAL || t == PUBLIC || t == PROTECTED || t == PRIVATE || t == SYNCHRONIZED || t == STATIC || t == VOLATILE || t == TRANSIENT || t == STRICT)
                list = new ASTList(new Keyword(lex.get()), list);
            else
                break;
        }
        return list;
    }

    private Declarator parseFormalType(SymbolTable tbl) throws CompileError {
        int t = lex.lookAhead();
        if (isBuiltinType(t) || t == VOID) {
            // primitive type
            lex.get();
            int dim = parseArrayDimension();
            return new Declarator(t, dim);
        } else {
            ASTList name = parseClassType(tbl);
            int dim = parseArrayDimension();
            return new Declarator(name, dim);
        }
    }

    private static boolean isBuiltinType(int t) {
        return (t == BOOLEAN || t == BYTE || t == CHAR || t == SHORT || t == INT || t == LONG || t == FLOAT || t == DOUBLE);
    }

    /* formal.parameter : formal.type Identifier array.dimension
     */
    private Declarator parseFormalParam(SymbolTable tbl) throws CompileError {
        Declarator d = parseFormalType(tbl);
        if (lex.get() != Identifier)
            throw new SyntaxError(lex);
        String name = lex.getString();
        d.setVariable(new Symbol(name));
        d.addArrayDim(parseArrayDimension());
        tbl.append(name, d);
        return d;
    }

    /* statement : [ label ":" ]* labeled.statement
     *
     * labeled.statement
     *          : block.statement
     *          | if.statement
     *          | while.statement
     *          | do.statement
     *          | for.statement
     *          | switch.statement
     *          | try.statement
     *          | return.statement
     *          | thorw.statement
     *          | break.statement
     *          | continue.statement
     *          | declaration.or.expression
     *          | ";"
     *
     * This method may return null (empty statement).
     */
    public Stmnt parseStatement(SymbolTable tbl) throws CompileError {
        int t = lex.lookAhead();
        if (t == '{')
            return parseBlock(tbl);
        else if (t == ';') {
            lex.get();
            // empty statement
            return new Stmnt(BLOCK);
        } else if (t == Identifier && lex.lookAhead(1) == ':') {
            // Identifier
            lex.get();
            String label = lex.getString();
            lex.get();
            return Stmnt.make(LABEL, new Symbol(label), parseStatement(tbl));
        } else if (t == IF)
            return parseIf(tbl);
        else if (t == WHILE)
            return parseWhile(tbl);
        else if (t == DO)
            return parseDo(tbl);
        else if (t == FOR)
            return parseFor(tbl);
        else if (t == TRY)
            return parseTry(tbl);
        else if (t == SWITCH)
            return parseSwitch(tbl);
        else if (t == SYNCHRONIZED)
            return parseSynchronized(tbl);
        else if (t == RETURN)
            return parseReturn(tbl);
        else if (t == THROW)
            return parseThrow(tbl);
        else if (t == BREAK)
            return parseBreak(tbl);
        else if (t == CONTINUE)
            return parseContinue(tbl);
        else
            return parseDeclarationOrExpression(tbl, false);
    }

    private Stmnt parseBlock(SymbolTable tbl) throws CompileError {
        if (lex.get() != '{')
            throw new SyntaxError(lex);
        Stmnt body = null;
        SymbolTable tbl2 = new SymbolTable(tbl);
        while (lex.lookAhead() != '}') {
            Stmnt s = parseStatement(tbl2);
            if (s != null)
                body = (Stmnt) ASTList.concat(body, new Stmnt(BLOCK, s));
        }
        lex.get();
        if (body == null)
            // empty block
            return new Stmnt(BLOCK);
        else
            return body;
    }

    private Stmnt parseIf(SymbolTable tbl) throws CompileError {
        // IF
        int t = lex.get();
        ASTree expr = parseParExpression(tbl);
        Stmnt thenp = parseStatement(tbl);
        Stmnt elsep;
        if (lex.lookAhead() == ELSE) {
            lex.get();
            elsep = parseStatement(tbl);
        } else
            elsep = null;
        return new Stmnt(t, expr, new ASTList(thenp, new ASTList(elsep)));
    }

    private Stmnt parseWhile(SymbolTable tbl) throws CompileError {
        // WHILE
        int t = lex.get();
        ASTree expr = parseParExpression(tbl);
        Stmnt body = parseStatement(tbl);
        return new Stmnt(t, expr, body);
    }

    /* do.statement : DO statement WHILE "(" expression ")" ";"
     */
    private Stmnt parseDo(SymbolTable tbl) throws CompileError {
        // DO
        int t = lex.get();
        Stmnt body = parseStatement(tbl);
        if (lex.get() != WHILE || lex.get() != '(')
            throw new SyntaxError(lex);
        ASTree expr = parseExpression(tbl);
        if (lex.get() != ')' || lex.get() != ';')
            throw new SyntaxError(lex);
        return new Stmnt(t, expr, body);
    }

    private Stmnt parseFor(SymbolTable tbl) throws CompileError {
        Stmnt expr1, expr3;
        ASTree expr2;
        // FOR
        int t = lex.get();
        SymbolTable tbl2 = new SymbolTable(tbl);
        if (lex.get() != '(')
            throw new SyntaxError(lex);
        if (lex.lookAhead() == ';') {
            lex.get();
            expr1 = null;
        } else
            expr1 = parseDeclarationOrExpression(tbl2, true);
        if (lex.lookAhead() == ';')
            expr2 = null;
        else
            expr2 = parseExpression(tbl2);
        if (lex.get() != ';')
            throw new CompileError("; is missing", lex);
        if (lex.lookAhead() == ')')
            expr3 = null;
        else
            expr3 = parseExprList(tbl2);
        if (lex.get() != ')')
            throw new CompileError(") is missing", lex);
        Stmnt body = parseStatement(tbl2);
        return new Stmnt(t, expr1, new ASTList(expr2, new ASTList(expr3, body)));
    }

    private Stmnt parseSwitch(SymbolTable tbl) throws CompileError {
        // SWITCH
        int t = lex.get();
        ASTree expr = parseParExpression(tbl);
        Stmnt body = parseSwitchBlock(tbl);
        return new Stmnt(t, expr, body);
    }

    private Stmnt parseSwitchBlock(SymbolTable tbl) throws CompileError {
        if (lex.get() != '{')
            throw new SyntaxError(lex);
        SymbolTable tbl2 = new SymbolTable(tbl);
        Stmnt s = parseStmntOrCase(tbl2);
        if (s == null)
            throw new CompileError("empty switch block", lex);
        int op = s.getOperator();
        if (op != CASE && op != DEFAULT)
            throw new CompileError("no case or default in a switch block", lex);
        Stmnt body = new Stmnt(BLOCK, s);
        while (lex.lookAhead() != '}') {
            Stmnt s2 = parseStmntOrCase(tbl2);
            if (s2 != null) {
                int op2 = s2.getOperator();
                if (op2 == CASE || op2 == DEFAULT) {
                    body = (Stmnt) ASTList.concat(body, new Stmnt(BLOCK, s2));
                    s = s2;
                } else
                    s = (Stmnt) ASTList.concat(s, new Stmnt(BLOCK, s2));
            }
        }
        lex.get();
        return body;
    }

    private Stmnt parseStmntOrCase(SymbolTable tbl) throws CompileError {
        int t = lex.lookAhead();
        if (t != CASE && t != DEFAULT)
            return parseStatement(tbl);
        lex.get();
        Stmnt s;
        if (t == CASE)
            s = new Stmnt(t, parseExpression(tbl));
        else
            s = new Stmnt(DEFAULT);
        if (lex.get() != ':')
            throw new CompileError(": is missing", lex);
        return s;
    }

    private Stmnt parseSynchronized(SymbolTable tbl) throws CompileError {
        // SYNCHRONIZED
        int t = lex.get();
        if (lex.get() != '(')
            throw new SyntaxError(lex);
        ASTree expr = parseExpression(tbl);
        if (lex.get() != ')')
            throw new SyntaxError(lex);
        Stmnt body = parseBlock(tbl);
        return new Stmnt(t, expr, body);
    }

    private Stmnt parseTry(SymbolTable tbl) throws CompileError {
        // TRY
        lex.get();
        Stmnt block = parseBlock(tbl);
        ASTList catchList = null;
        while (lex.lookAhead() == CATCH) {
            // CATCH
            lex.get();
            if (lex.get() != '(')
                throw new SyntaxError(lex);
            SymbolTable tbl2 = new SymbolTable(tbl);
            Declarator d = parseFormalParam(tbl2);
            if (d.getArrayDim() > 0 || d.getType() != CLASS)
                throw new SyntaxError(lex);
            if (lex.get() != ')')
                throw new SyntaxError(lex);
            Stmnt b = parseBlock(tbl2);
            catchList = ASTList.append(catchList, new Pair(d, b));
        }
        Stmnt finallyBlock = null;
        if (lex.lookAhead() == FINALLY) {
            // FINALLY
            lex.get();
            finallyBlock = parseBlock(tbl);
        }
        return Stmnt.make(TRY, block, catchList, finallyBlock);
    }

    private Stmnt parseReturn(SymbolTable tbl) throws CompileError {
        // RETURN
        int t = lex.get();
        Stmnt s = new Stmnt(t);
        if (lex.lookAhead() != ';')
            s.setLeft(parseExpression(tbl));
        if (lex.get() != ';')
            throw new CompileError("; is missing", lex);
        return s;
    }

    private Stmnt parseThrow(SymbolTable tbl) throws CompileError {
        // THROW
        int t = lex.get();
        ASTree expr = parseExpression(tbl);
        if (lex.get() != ';')
            throw new CompileError("; is missing", lex);
        return new Stmnt(t, expr);
    }

    private Stmnt parseBreak(SymbolTable tbl) throws CompileError {
        return parseContinue(tbl);
    }

    private Stmnt parseContinue(SymbolTable tbl) throws CompileError {
        // CONTINUE
        int t = lex.get();
        Stmnt s = new Stmnt(t);
        int t2 = lex.get();
        if (t2 == Identifier) {
            s.setLeft(new Symbol(lex.getString()));
            t2 = lex.get();
        }
        if (t2 != ';')
            throw new CompileError("; is missing", lex);
        return s;
    }

    /* declaration.or.expression
     *      : [ FINAL ] built-in-type array.dimension declarators
     *      | [ FINAL ] class.type array.dimension declarators
     *      | expression ';'
     *      | expr.list ';'             if exprList is true
     *
     * Note: FINAL is currently ignored.  This must be fixed
     * in future.
     */
    private Stmnt parseDeclarationOrExpression(SymbolTable tbl, boolean exprList) throws CompileError {
        int t = lex.lookAhead();
        while (t == FINAL) {
            lex.get();
            t = lex.lookAhead();
        }
        if (isBuiltinType(t)) {
            t = lex.get();
            int dim = parseArrayDimension();
            return parseDeclarators(tbl, new Declarator(t, dim));
        } else if (t == Identifier) {
            int i = nextIsClassType(0);
            if (i >= 0)
                if (lex.lookAhead(i) == Identifier) {
                    ASTList name = parseClassType(tbl);
                    int dim = parseArrayDimension();
                    return parseDeclarators(tbl, new Declarator(name, dim));
                }
        }
        Stmnt expr;
        if (exprList)
            expr = parseExprList(tbl);
        else
            expr = new Stmnt(EXPR, parseExpression(tbl));
        if (lex.get() != ';')
            throw new CompileError("; is missing", lex);
        return expr;
    }

    private Stmnt parseExprList(SymbolTable tbl) throws CompileError {
        Stmnt expr = null;
        for (; ; ) {
            Stmnt e = new Stmnt(EXPR, parseExpression(tbl));
            expr = (Stmnt) ASTList.concat(expr, new Stmnt(BLOCK, e));
            if (lex.lookAhead() == ',')
                lex.get();
            else
                return expr;
        }
    }

    private Stmnt parseDeclarators(SymbolTable tbl, Declarator d) throws CompileError {
        Stmnt decl = null;
        for (; ; ) {
            decl = (Stmnt) ASTList.concat(decl, new Stmnt(DECL, parseDeclarator(tbl, d)));
            int t = lex.get();
            if (t == ';')
                return decl;
            else if (t != ',')
                throw new CompileError("; is missing", lex);
        }
    }

    private Declarator parseDeclarator(SymbolTable tbl, Declarator d) throws CompileError {
        if (lex.get() != Identifier || d.getType() == VOID)
            throw new SyntaxError(lex);
        String name = lex.getString();
        Symbol symbol = new Symbol(name);
        int dim = parseArrayDimension();
        ASTree init = null;
        if (lex.lookAhead() == '=') {
            lex.get();
            init = parseInitializer(tbl);
        }
        Declarator decl = d.make(symbol, dim, init);
        tbl.append(name, decl);
        return decl;
    }

    /* initializer : expression | array.initializer
     */
    private ASTree parseInitializer(SymbolTable tbl) throws CompileError {
        if (lex.lookAhead() == '{')
            return parseArrayInitializer(tbl);
        else
            return parseExpression(tbl);
    }

    private ArrayInit parseArrayInitializer(SymbolTable tbl) throws CompileError {
        lex.get();
        ASTree expr = parseExpression(tbl);
        ArrayInit init = new ArrayInit(expr);
        while (lex.lookAhead() == ',') {
            lex.get();
            expr = parseExpression(tbl);
            ASTList.append(init, expr);
        }
        if (lex.get() != '}')
            throw new SyntaxError(lex);
        return init;
    }

    private ASTree parseParExpression(SymbolTable tbl) throws CompileError {
        if (lex.get() != '(')
            throw new SyntaxError(lex);
        ASTree expr = parseExpression(tbl);
        if (lex.get() != ')')
            throw new SyntaxError(lex);
        return expr;
    }

    /* expression : conditional.expr
     *            | conditional.expr assign.op expression (right-to-left)
     */
    public ASTree parseExpression(SymbolTable tbl) throws CompileError {
        ASTree left = parseConditionalExpr(tbl);
        if (!isAssignOp(lex.lookAhead()))
            return left;
        int t = lex.get();
        ASTree right = parseExpression(tbl);
        return AssignExpr.makeAssign(t, left, right);
    }

    private static boolean isAssignOp(int t) {
        return t == '=' || t == MOD_E || t == AND_E || t == MUL_E || t == PLUS_E || t == MINUS_E || t == DIV_E || t == EXOR_E || t == OR_E || t == LSHIFT_E || t == RSHIFT_E || t == ARSHIFT_E;
    }

    private ASTree parseConditionalExpr(SymbolTable tbl) throws CompileError {
        ASTree cond = parseBinaryExpr(tbl);
        if (lex.lookAhead() == '?') {
            lex.get();
            ASTree thenExpr = parseExpression(tbl);
            if (lex.get() != ':')
                throw new CompileError(": is missing", lex);
            ASTree elseExpr = parseExpression(tbl);
            return new CondExpr(cond, thenExpr, elseExpr);
        } else
            return cond;
    }

    /* logical.or.expr          10 (operator precedence)
     * : logical.and.expr
     * | logical.or.expr OROR logical.and.expr          left-to-right
     *
     * logical.and.expr         9
     * : inclusive.or.expr
     * | logical.and.expr ANDAND inclusive.or.expr
     *
     * inclusive.or.expr        8
     * : exclusive.or.expr
     * | inclusive.or.expr "|" exclusive.or.expr
     *
     * exclusive.or.expr        7
     *  : and.expr
     * | exclusive.or.expr "^" and.expr
     *
     * and.expr                 6
     * : equality.expr
     * | and.expr "&" equality.expr
     *
     * equality.expr            5
     * : relational.expr
     * | equality.expr (EQ | NEQ) relational.expr
     *
     * relational.expr          4
     * : shift.expr
     * | relational.expr (LE | GE | "<" | ">") shift.expr
     * | relational.expr INSTANCEOF class.type ("[" "]")*
     *
     * shift.expr               3
     * : additive.expr
     * | shift.expr (LSHIFT | RSHIFT | ARSHIFT) additive.expr
     *
     * additive.expr            2
     * : multiply.expr
     * | additive.expr ("+" | "-") multiply.expr
     *
     * multiply.expr            1
     * : unary.expr
     * | multiply.expr ("*" | "/" | "%") unary.expr
     */
    private ASTree parseBinaryExpr(SymbolTable tbl) throws CompileError {
        ASTree expr = parseUnaryExpr(tbl);
        for (; ; ) {
            int t = lex.lookAhead();
            int p = getOpPrecedence(t);
            if (p == 0)
                return expr;
            else
                expr = binaryExpr2(tbl, expr, p);
        }
    }

    private ASTree parseInstanceOf(SymbolTable tbl, ASTree expr) throws CompileError {
        int t = lex.lookAhead();
        if (isBuiltinType(t)) {
            // primitive type
            lex.get();
            int dim = parseArrayDimension();
            return new InstanceOfExpr(t, dim, expr);
        } else {
            ASTList name = parseClassType(tbl);
            int dim = parseArrayDimension();
            return new InstanceOfExpr(name, dim, expr);
        }
    }

    private ASTree binaryExpr2(SymbolTable tbl, ASTree expr, int prec) throws CompileError {
        int t = lex.get();
        if (t == INSTANCEOF)
            return parseInstanceOf(tbl, expr);
        ASTree expr2 = parseUnaryExpr(tbl);
        for (; ; ) {
            int t2 = lex.lookAhead();
            int p2 = getOpPrecedence(t2);
            if (p2 != 0 && prec > p2)
                expr2 = binaryExpr2(tbl, expr2, p2);
            else
                return BinExpr.makeBin(t, expr, expr2);
        }
    }

    private static final int[] binaryOpPrecedence = { 0, 0, 0, 0, 1, 6, 0, 0, 0, 1, 2, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 4, 0 };

    private int getOpPrecedence(int c) {
        if ('!' <= c && c <= '?')
            return binaryOpPrecedence[c - '!'];
        else if (c == '^')
            return 7;
        else if (c == '|')
            return 8;
        else if (c == ANDAND)
            return 9;
        else if (c == OROR)
            return 10;
        else if (c == EQ || c == NEQ)
            return 5;
        else if (c == LE || c == GE || c == INSTANCEOF)
            return 4;
        else if (c == LSHIFT || c == RSHIFT || c == ARSHIFT)
            return 3;
        else
            // not a binary operator
            return 0;
    }

    /* unary.expr : "++"|"--" unary.expr
                  | "+"|"-" unary.expr
                  | "!"|"~" unary.expr
                  | cast.expr
                  | postfix.expr

       unary.expr.not.plus.minus is a unary expression starting without
       "+", "-", "++", or "--".
     */
    private ASTree parseUnaryExpr(SymbolTable tbl) throws CompileError {
        int t;
        switch(lex.lookAhead()) {
            case '+':
            case '-':
            case PLUSPLUS:
            case MINUSMINUS:
            case '!':
            case '~':
                t = lex.get();
                if (t == '-') {
                    int t2 = lex.lookAhead();
                    switch(t2) {
                        case LongConstant:
                        case IntConstant:
                        case CharConstant:
                            lex.get();
                            return new IntConst(-lex.getLong(), t2);
                        case DoubleConstant:
                        case FloatConstant:
                            lex.get();
                            return new DoubleConst(-lex.getDouble(), t2);
                        default:
                            break;
                    }
                }
                return Expr.make(t, parseUnaryExpr(tbl));
            case '(':
                return parseCast(tbl);
            default:
                return parsePostfix(tbl);
        }
    }

    /* cast.expr : "(" builtin.type ("[" "]")* ")" unary.expr
                 | "(" class.type ("[" "]")* ")" unary.expr2

       unary.expr2 is a unary.expr beginning with "(", NULL, StringL,
       Identifier, THIS, SUPER, or NEW.

       Either "(int.class)" or "(String[].class)" is a not cast expression.
     */
    private ASTree parseCast(SymbolTable tbl) throws CompileError {
        int t = lex.lookAhead(1);
        if (isBuiltinType(t) && nextIsBuiltinCast()) {
            lex.get();
            // primitive type
            lex.get();
            int dim = parseArrayDimension();
            if (lex.get() != ')')
                throw new CompileError(") is missing", lex);
            return new CastExpr(t, dim, parseUnaryExpr(tbl));
        } else if (t == Identifier && nextIsClassCast()) {
            lex.get();
            ASTList name = parseClassType(tbl);
            int dim = parseArrayDimension();
            if (lex.get() != ')')
                throw new CompileError(") is missing", lex);
            return new CastExpr(name, dim, parseUnaryExpr(tbl));
        } else
            return parsePostfix(tbl);
    }

    private boolean nextIsBuiltinCast() {
        int t;
        int i = 2;
        while ((t = lex.lookAhead(i++)) == '[') if (lex.lookAhead(i++) != ']')
            return false;
        return lex.lookAhead(i - 1) == ')';
    }

    private boolean nextIsClassCast() {
        int i = nextIsClassType(1);
        if (i < 0)
            return false;
        int t = lex.lookAhead(i);
        if (t != ')')
            return false;
        t = lex.lookAhead(i + 1);
        return t == '(' || t == NULL || t == StringL || t == Identifier || t == THIS || t == SUPER || t == NEW || t == TRUE || t == FALSE || t == LongConstant || t == IntConstant || t == CharConstant || t == DoubleConstant || t == FloatConstant;
    }

    private int nextIsClassType(int i) {
        int t;
        while (lex.lookAhead(++i) == '.') if (lex.lookAhead(++i) != Identifier)
            return -1;
        while ((t = lex.lookAhead(i++)) == '[') if (lex.lookAhead(i++) != ']')
            return -1;
        return i - 1;
    }

    private int parseArrayDimension() throws CompileError {
        int arrayDim = 0;
        while (lex.lookAhead() == '[') {
            ++arrayDim;
            lex.get();
            if (lex.get() != ']')
                throw new CompileError("] is missing", lex);
        }
        return arrayDim;
    }

    private ASTList parseClassType(SymbolTable tbl) throws CompileError {
        ASTList list = null;
        for (; ; ) {
            if (lex.get() != Identifier)
                throw new SyntaxError(lex);
            list = ASTList.append(list, new Symbol(lex.getString()));
            if (lex.lookAhead() == '.')
                lex.get();
            else
                break;
        }
        return list;
    }

    /* postfix.expr : number.literal
     *              | primary.expr
     *              | method.expr
     *              | postfix.expr "++" | "--"
     *              | postfix.expr "[" array.size "]"
     *              | postfix.expr "." Identifier
     *              | postfix.expr ( "[" "]" )* "." CLASS
     *              | postfix.expr "#" Identifier
     *
     * "#" is not an operator of regular Java.  It separates
     * a class name and a member name in an expression for static member
     * access.  For example,
     *     java.lang.Integer.toString(3)        in regular Java
     * can be written like this:
     *     java.lang.Integer#toString(3)        for this compiler.
     */
    private ASTree parsePostfix(SymbolTable tbl) throws CompileError {
        int token = lex.lookAhead();

        String str;
        ASTree index;
        ASTree expr = parsePrimaryExpr(tbl);
        int t;
        while (true) {
            switch(lex.lookAhead()) {
                case '(':
                    expr = parseMethodCall(tbl, expr);
                    break;
                case '[':
                    if (lex.lookAhead(1) == ']') {
                        int dim = parseArrayDimension();
                        if (lex.get() != '.' || lex.get() != CLASS)
                            throw new SyntaxError(lex);
                        expr = parseDotClass(expr, dim);
                    } else {
                        index = parseArrayIndex(tbl);
                        if (index == null)
                            throw new SyntaxError(lex);
                        expr = Expr.make(ARRAY, expr, index);
                    }
                    break;
                case PLUSPLUS:
                case MINUSMINUS:
                    t = lex.get();
                    expr = Expr.make(t, null, expr);
                    break;
                case '.':
                    lex.get();
                    t = lex.get();
                    if (t == CLASS) {
                        expr = parseDotClass(expr, 0);
                    } else if (t == Identifier) {
                        str = lex.getString();
                        expr = Expr.make('.', expr, new Member(str));
                    } else
                        throw new CompileError("missing member name", lex);
                    break;
                case '#':
                    lex.get();
                    t = lex.get();
                    if (t != Identifier)
                        throw new CompileError("missing static member name", lex);
                    str = lex.getString();
                    expr = Expr.make(MEMBER, new Symbol(toClassName(expr)), new Member(str));
                    break;
                default:
                    return expr;
            }
        }
    }

    /* Parse a .class expression on a class type.  For example,
     * String.class   => ('.' "String" "class")
     * String[].class => ('.' "[LString;" "class")
     */
    private ASTree parseDotClass(ASTree className, int dim) throws CompileError {
        String cname = toClassName(className);
        if (dim > 0) {
            StringBuffer sbuf = new StringBuffer();
            while (dim-- > 0) sbuf.append('[');
            sbuf.append('L').append(cname.replace('.', '/')).append(';');
            cname = sbuf.toString();
        }
        return Expr.make('.', new Symbol(cname), new Member("class"));
    }

    /* Parses a .class expression on a built-in type.  For example,
     * int.class   => ('#' "java.lang.Integer" "TYPE")
     * int[].class => ('.' "[I", "class")
     */
    private ASTree parseDotClass(int builtinType, int dim) throws CompileError {
        if (dim > 0) {
            String cname = CodeGen.toJvmTypeName(builtinType, dim);
            return Expr.make('.', new Symbol(cname), new Member("class"));
        } else {
            String cname;
            switch(builtinType) {
                case BOOLEAN:
                    cname = "java.lang.Boolean";
                    break;
                case BYTE:
                    cname = "java.lang.Byte";
                    break;
                case CHAR:
                    cname = "java.lang.Character";
                    break;
                case SHORT:
                    cname = "java.lang.Short";
                    break;
                case INT:
                    cname = "java.lang.Integer";
                    break;
                case LONG:
                    cname = "java.lang.Long";
                    break;
                case FLOAT:
                    cname = "java.lang.Float";
                    break;
                case DOUBLE:
                    cname = "java.lang.Double";
                    break;
                case VOID:
                    cname = "java.lang.Void";
                    break;
                default:
                    throw new CompileError("invalid builtin type: " + builtinType);
            }
            return Expr.make(MEMBER, new Symbol(cname), new Member("TYPE"));
        }
    }

    private ASTree parseMethodCall(SymbolTable tbl, ASTree expr) throws CompileError {
        if (expr instanceof Keyword) {
            int token = ((Keyword) expr).get();
            if (token != THIS && token != SUPER)
                throw new SyntaxError(lex);
        } else if (// Identifier
        expr instanceof Symbol)
            ;
        else if (expr instanceof Expr) {
            int op = ((Expr) expr).getOperator();
            if (op != '.' && op != MEMBER)
                throw new SyntaxError(lex);
        }
        return CallExpr.makeCall(expr, parseArgumentList(tbl));
    }

    private String toClassName(ASTree name) throws CompileError {
        StringBuffer sbuf = new StringBuffer();
        toClassName(name, sbuf);
        return sbuf.toString();
    }

    private void toClassName(ASTree name, StringBuffer sbuf) throws CompileError {
        if (name instanceof Symbol) {
            sbuf.append(((Symbol) name).get());
            return;
        } else if (name instanceof Expr) {
            Expr expr = (Expr) name;
            if (expr.getOperator() == '.') {
                toClassName(expr.oprand1(), sbuf);
                sbuf.append('.');
                toClassName(expr.oprand2(), sbuf);
                return;
            }
        }
        throw new CompileError("bad static member access", lex);
    }

    /* primary.expr : THIS | SUPER | TRUE | FALSE | NULL
     *              | StringL
     *              | Identifier
     *              | NEW new.expr
     *              | "(" expression ")"
     *              | builtin.type ( "[" "]" )* "." CLASS
     *
     * Identifier represents either a local variable name, a member name,
     * or a class name.
     */
    private ASTree parsePrimaryExpr(SymbolTable tbl) throws CompileError {
        int t;
        String name;
        Declarator decl;
        ASTree expr;
        switch(t = lex.get()) {
            case THIS:
            case SUPER:
            case TRUE:
            case FALSE:
            case NULL:
                return new Keyword(t);
            case Identifier:
                name = lex.getString();
                decl = tbl.lookup(name);
                if (decl == null)
                    return new Member(name);
                else
                    // local variable
                    return new Variable(name, decl);
            case StringL:
                return new StringL(lex.getString());
            case NEW:
                return parseNew(tbl);
            case '(':
                expr = parseExpression(tbl);
                if (lex.get() == ')')
                    return expr;
                else
                    throw new CompileError(") is missing", lex);
            default:
                if (isBuiltinType(t) || t == VOID) {
                    int dim = parseArrayDimension();
                    if (lex.get() == '.' && lex.get() == CLASS)
                        return parseDotClass(t, dim);
                }
                throw new SyntaxError(lex);
        }
    }

    private NewExpr parseNew(SymbolTable tbl) throws CompileError {
        ArrayInit init = null;
        int t = lex.lookAhead();
        if (isBuiltinType(t)) {
            lex.get();
            ASTList size = parseArraySize(tbl);
            if (lex.lookAhead() == '{')
                init = parseArrayInitializer(tbl);
            return new NewExpr(t, size, init);
        } else if (t == Identifier) {
            ASTList name = parseClassType(tbl);
            t = lex.lookAhead();
            if (t == '(') {
                ASTList args = parseArgumentList(tbl);
                return new NewExpr(name, args);
            } else if (t == '[') {
                ASTList size = parseArraySize(tbl);
                if (lex.lookAhead() == '{')
                    init = parseArrayInitializer(tbl);
                return NewExpr.makeObjectArray(name, size, init);
            }
        }
        throw new SyntaxError(lex);
    }

    private ASTList parseArraySize(SymbolTable tbl) throws CompileError {
        ASTList list = null;
        while (lex.lookAhead() == '[') list = ASTList.append(list, parseArrayIndex(tbl));
        return list;
    }

    private ASTree parseArrayIndex(SymbolTable tbl) throws CompileError {
        lex.get();
        if (lex.lookAhead() == ']') {
            lex.get();
            return null;
        } else {
            ASTree index = parseExpression(tbl);
            if (lex.get() != ']')
                throw new CompileError("] is missing", lex);
            return index;
        }
    }

    private ASTList parseArgumentList(SymbolTable tbl) throws CompileError {
        if (lex.get() != '(')
            throw new CompileError("( is missing", lex);
        ASTList list = null;
        if (lex.lookAhead() != ')')
            for (; ; ) {
                list = ASTList.append(list, parseExpression(tbl));
                if (lex.lookAhead() == ',')
                    lex.get();
                else
                    break;
            }
        if (lex.get() != ')')
            throw new CompileError(") is missing", lex);
        return list;
    }
}


switch(ctorType) {
            case POSITION_VAL:
                query.setText(position, val);
                break;
            case NAME_VAL:
                query.setText(name, val);
                break;
            default:
                throw new ShardedSessionException("Unknown ctor type in SetTextEvent: " + ctorType);
        }

package org.hibernate.shards.query;

import org.hibernate.Query;
import org.hibernate.shards.session.ShardedSessionException;

/**
 * @author Maulik Shah
 */
public class SetTextEvent implements QueryEvent {

    private static enum CtorType {

        POSITION_VAL, NAME_VAL
    }

    private final CtorType ctorType;

    private final int position;

    private final String val;

    private final String name;

    private SetTextEvent(CtorType ctorType, int position, String val, String name) {
        this.ctorType = ctorType;
        this.position = position;
        this.val = val;
        this.name = name;
    }

    public SetTextEvent(int position, String val) {
        this(CtorType.POSITION_VAL, position, val, null);
    }

    public SetTextEvent(String name, String val) {
        this(CtorType.NAME_VAL, -1, val, name);
    }

    public void onEvent(Query query) {


switch(member.getVisibility()) {
                case ICPPMember.v_private:
                    return ASTAccessVisibility.PRIVATE;
                case ICPPMember.v_protected:
                    return ASTAccessVisibility.PROTECTED;
                case ICPPMember.v_public:
                    return ASTAccessVisibility.PUBLIC;
            }

/**
 * ****************************************************************************
 *
 *  Contributors:
 *      Markus Schorn - initial API and implementation
 *      Anton Leherbauer (Wind River Systems)
 * *****************************************************************************
 */
package org.eclipse.cdt.internal.core.model.ext;

import java.net.URI;
import java.util.Collections;
import java.util.List;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.IPositionConverter;
import org.eclipse.cdt.core.dom.ast.ASTTypeUtil;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IFunction;
import org.eclipse.cdt.core.dom.ast.IParameter;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMember;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICElementVisitor;
import org.eclipse.cdt.core.model.ICModel;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ISourceRange;
import org.eclipse.cdt.core.model.ISourceReference;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.cdt.internal.core.model.CElement;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Region;

abstract class CElementHandle implements ICElementHandle, ISourceReference {

    protected static final String[] EMPTY_STRING_ARRAY = {};

    private static final ICElement[] NO_CHILDREN = {};

    private ICElement fParent;

    private String fName;

    private int fType;

    private IRegion fRegion;

    private long fTimestamp;

    private int fIndex;

    public CElementHandle(ICElement parent, int type, String name) {
        fParent = parent;
        fType = type;
        // Anonymous types are assigned a name in the index, we undo this here.
        if (name.length() > 0 && name.charAt(0) == '{') {
            fName = "";
            fIndex = name.hashCode();
        } else {
            fName = name;
        }
        fRegion = new Region(0, 0);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof ICElement) {
            return CElement.equals(this, (ICElement) obj);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return CElement.hashCode(this);
    }

    @Override
    public <T> T getAdapter(Class<T> adapter) {
        return null;
    }

    public void setRangeOfID(IRegion region, long timestamp) {
        fRegion = region;
        fTimestamp = timestamp;
    }

    @Override
    public ISourceRange getSourceRange() throws CModelException {
        IRegion region = fRegion;
        ITranslationUnit tu = getTranslationUnit();
        if (tu != null) {
            IPositionConverter converter = CCorePlugin.getPositionTrackerManager().findPositionConverter(tu, fTimestamp);
            if (converter != null) {
                region = converter.historicToActual(region);
            }
        }
        int startpos = region.getOffset();
        int length = region.getLength();
        return new SourceRange(startpos, length);
    }

    @Override
    public String getSource() throws CModelException {
        return null;
    }

    @Override
    public ITranslationUnit getTranslationUnit() {
        ICElement parent = fParent;
        do {
            if (parent instanceof ITranslationUnit) {
                return (ITranslationUnit) parent;
            }
            parent = parent.getParent();
        } while (parent != null);
        return null;
    }

    @Override
    public void accept(ICElementVisitor visitor) throws CoreException {
    }

    @Override
    public boolean exists() {
        return true;
    }

    @Override
    public ICElement getAncestor(int ancestorType) {
        return null;
    }

    @Override
    public ICModel getCModel() {
        return fParent.getCModel();
    }

    @Override
    public ICProject getCProject() {
        return fParent.getCProject();
    }

    @Override
    public String getElementName() {
        return fName;
    }

    @Override
    public int getElementType() {
        return fType;
    }

    @Override
    public ICElement getParent() {
        return fParent;
    }

    @Override
    public IPath getPath() {
        return getTranslationUnit().getPath();
    }

    @Override
    public URI getLocationURI() {
        return getTranslationUnit().getLocationURI();
    }

    @Override
    public IResource getResource() {
        return getTranslationUnit().getResource();
    }

    @Override
    public IResource getUnderlyingResource() {
        return getResource();
    }

    @Override
    public boolean isReadOnly() {
        return true;
    }

    @Override
    public boolean isStructureKnown() throws CModelException {
        return false;
    }

    public void copy(ICElement container, ICElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws CModelException {
    }

    public void delete(boolean force, IProgressMonitor monitor) throws CModelException {
    }

    public void move(ICElement container, ICElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws CModelException {
    }

    public void rename(String name, boolean replace, IProgressMonitor monitor) throws CModelException {
    }

    public void setTypeName(String type) throws CModelException {
    }

    public String getTypeName() {
        return "";
    }

    public ICElement[] getChildren() throws CModelException {
        return NO_CHILDREN;
    }

    public List<ICElement> getChildrenOfType(int type) throws CModelException {
        return Collections.emptyList();
    }

    public boolean hasChildren() {
        return false;
    }

    public String[] getExceptions() {
        return EMPTY_STRING_ARRAY;
    }

    public String getParameterInitializer(int pos) {
        return "";
    }

    public boolean isConst() {
        return false;
    }

    public boolean isVolatile() throws CModelException {
        return false;
    }

    public boolean isFriend() throws CModelException {
        return false;
    }

    public boolean isInline() throws CModelException {
        return false;
    }

    public boolean isOperator() throws CModelException {
        return false;
    }

    public boolean isPureVirtual() throws CModelException {
        return false;
    }

    public boolean isVirtual() throws CModelException {
        return false;
    }

    public boolean isMutable() throws CModelException {
        return false;
    }

    public String getInitializer() {
        return null;
    }

    public boolean isAbstract() throws CModelException {
        return false;
    }

    public ASTAccessVisibility getSuperClassAccess(String name) {
        return ASTAccessVisibility.PUBLIC;
    }

    public String[] getSuperClassesNames() {
        return EMPTY_STRING_ARRAY;
    }

    protected String[] extractParameterTypes(IFunction func) {
        IParameter[] params = func.getParameters();
        String[] parameterTypes = new String[params.length];
        for (int i = 0; i < params.length; i++) {
            IParameter param = params[i];
            parameterTypes[i] = ASTTypeUtil.getType(param.getType(), false);
        }
        if (parameterTypes.length == 1 && parameterTypes[0].equals("void")) {
            return EMPTY_STRING_ARRAY;
        }
        return parameterTypes;
    }

    protected ASTAccessVisibility getVisibility(IBinding binding) {
        if (binding instanceof ICPPMember) {
            ICPPMember member = (ICPPMember) binding;

        }
        return ASTAccessVisibility.PUBLIC;
    }

    /**
     * @see ICElement
     */
    @Override
    public String getHandleIdentifier() {
        ICElement cModelElement = mapToModelElement();
        if (cModelElement != null) {
            return cModelElement.getHandleIdentifier();
        }
        return null;
    }

    private ICElement mapToModelElement() {
        try {
            ISourceRange range = getSourceRange();
            return getTranslationUnit().getElementAtOffset(range.getIdStartPos());
        } catch (CModelException exc) {
            return null;
        }
    }

    @Override
    public boolean isActive() {
        return true;
    }

    @Override
    public int getIndex() {
        return fIndex;
    }
}


switch(msg.what) {
                case 0:
                    listAdapter.notifyDataSetChanged();
                    break;
            }

package com.BeeFramework.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import com.BeeFramework.AppConst;
import com.BeeFramework.adapter.CrashLogAdapter;
import com.BeeFramework.protocol.CrashMessage;
import com.external.maxwin.view.XListView;
import com.BeeFramework.example.R;
import org.apache.http.util.EncodingUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/*
 *	 ______    ______    ______
 *	/\  __ \  /\  ___\  /\  ___\
 *	\ \  __<  \ \  __\_ \ \  __\_
 *	 \ \_____\ \ \_____\ \ \_____\
 *	  \/_____/  \/_____/  \/_____/
 *
 *
 *
 *
 */
public class CrashLogActivity extends BaseActivity {

    ArrayList<File> logFilesList = new ArrayList<File>();

    ArrayList<CrashMessage> crashMessageArrayList = new ArrayList<CrashMessage>();

    XListView logListView;

    TextView titleTextView;

    CrashLogAdapter listAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.crash_log_activity);
        logListView = (XListView) findViewById(R.id.log_list_view);
        titleTextView = (TextView) findViewById(R.id.topview_title);
        titleTextView.setText("崩溃日志分析");
        new Thread() {

            @Override
            public void run() {
                initLog();
            }
        }.start();
        logListView.setPullLoadEnable(false);
        logListView.setPullRefreshEnable(false);
        logListView.setRefreshTime();
        listAdapter = new CrashLogAdapter(this, crashMessageArrayList);
        logListView.setAdapter(listAdapter);
        logListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int size = crashMessageArrayList.size();
                CrashMessage crashMessage = crashMessageArrayList.get(size - position);
                Intent it = new Intent(CrashLogActivity.this, CrashLogDetailActivity.class);
                it.putExtra("crash_time", crashMessage.crashTime);
                it.putExtra("crash_content", crashMessage.crashContent);
                startActivity(it);
            }
        });
    }

    public void initLog() {
        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + AppConst.LOG_DIR_PATH;
            getFiles(logFilesList, path);
            for (int i = 0; i < logFilesList.size(); i++) {
                File file = logFilesList.get(i);
                try {
                    FileInputStream fin = new FileInputStream(file);
                    int length = fin.available();
                    byte[] buffer = new byte[length];
                    fin.read(buffer);
                    String content = EncodingUtils.getString(buffer, "UTF-8");
                    fin.close();
                    String fileName = file.getName();
                    String[] nameArray = fileName.split("\\.");
                    if (nameArray.length > 0) {
                        String intStr = nameArray[0];
                        long timestamp = Long.parseLong(intStr);
                        Date currentTime = new Date(timestamp);
                        CrashMessage crashMessage = new CrashMessage();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                        String dateString = formatter.format(currentTime);
                        crashMessage.crashTime = dateString;
                        crashMessage.crashContent = content;
                        crashMessageArrayList.add(crashMessage);
                    }
                } catch (FileNotFoundException e) {
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            handler.sendEmptyMessage(0);
        }
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };

    private void getFiles(ArrayList<File> logFilesList, String path) {
        File[] allFiles = new File(path).listFiles();
        for (int i = 0; i < allFiles.length; i++) {
            File file = allFiles[i];
            if (file.isFile() && file.getName().contains("txt")) {
                logFilesList.add(file);
            }
        }
    }
}


switch(key.getKeyCode()) {
            case KeyEvent.VK_ESCAPE:
                System.exit(0);
            default:
                break;
        }

package glredbook10;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import com.jogamp.opengl.*;
import javax.swing.JFrame;
import com.jogamp.opengl.util.gl2.GLUT;
import com.jogamp.opengl.awt.GLJPanel;
import com.jogamp.opengl.glu.GLU;

/**
 * This program demonstrates a single modeling transformation, glScalef() and a
 * single viewing transformation, gluLookAt(). A wireframe cube is rendered.
 *
 * @author Kiet Le (Java port) Ported to JOGL 2.x by Claudio Eduardo Goes
 */
public class cube extends GLSkeleton<GLJPanel> implements GLEventListener, KeyListener {

    private GLU glu;

    private GLUT glut;

    @Override
    protected GLJPanel createDrawable() {
        GLCapabilities caps = new GLCapabilities(null);
        GLJPanel panel = new GLJPanel(caps);
        panel.addGLEventListener(this);
        panel.addKeyListener(this);
        return panel;
    }

    public static void main(String[] args) {
        cube demo = new cube();
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("cube");
        frame.setSize(500, 500);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(demo.drawable);
        frame.setVisible(true);
        demo.drawable.requestFocusInWindow();
    }

    public void init(GLAutoDrawable drawable) {
        GL2 gl = drawable.getGL().getGL2();
        glu = new GLU();
        glut = new GLUT();
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        gl.glShadeModel(GL2.GL_FLAT);
    }

    /*
     * Clear the screen. Set the current color to white. Draw the wire frame
     * cube.
     */
    public void display(GLAutoDrawable drawable) {
        GL2 gl = drawable.getGL().getGL2();
        gl.glClear(GL.GL_COLOR_BUFFER_BIT);
        gl.glColor3f(1.0f, 1.0f, 1.0f);
        gl.glLoadIdentity();
        /* clear the matrix */
        /* viewing transformation */
        glu.gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
        gl.glScalef(1.0f, 2.0f, 1.0f);
        /* modeling transformation */
        glut.glutWireCube(1.0f);
        gl.glFlush();
    }

    /*
     * Called when the window is first opened and whenever the window is
     * reconfigured (moved or resized).
     */
    public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) {
        GL2 gl = drawable.getGL().getGL2();
        gl.glMatrixMode(GL2.GL_PROJECTION);
        /* prepare for and then */
        gl.glLoadIdentity();
        /* define the projection */
        gl.glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
        /* transformation */
        gl.glMatrixMode(GL2.GL_MODELVIEW);
        /* back to modelview matrix */
        gl.glViewport(0, 0, w, h);
        /* define the viewport */
    }

    public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
    }

    public void keyTyped(KeyEvent arg0) {
    }

    public void keyPressed(KeyEvent key) {

    }

    public void keyReleased(KeyEvent arg0) {
    }

    public void dispose(GLAutoDrawable arg0) {
    }
}


switch(imageStatus) {
                case OK:
                    setCommandEndStatus(command, false, status, childCmdIds);
                    break;
                case ILLEGAL:
                    setCommandEndStatus(command, true, status, childCmdIds);
                    break;
            }

package org.ovirt.engine.core.bll.storage.disk.cinder;

import java.util.List;
import javax.enterprise.inject.Typed;
import javax.inject.Inject;
import org.ovirt.engine.core.bll.CommandBase;
import org.ovirt.engine.core.bll.ConcurrentChildCommandsExecutionCallback;
import org.ovirt.engine.core.common.action.AddDiskParameters;
import org.ovirt.engine.core.common.businessentities.storage.CinderDisk;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.backendcompat.CommandExecutionStatus;
import org.ovirt.engine.core.dao.DiskDao;

@Typed(AddCinderDiskCommandCallback.class)
public class AddCinderDiskCommandCallback extends ConcurrentChildCommandsExecutionCallback {

    @Inject
    private DiskDao diskDao;

    @Override
    protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) {
        AddCinderDiskCommand<AddDiskParameters> addCinderDiskCommand = (AddCinderDiskCommand<AddDiskParameters>) command;
        Guid diskId = getDiskId(addCinderDiskCommand);
        ImageStatus imageStatus = addCinderDiskCommand.getCinderBroker().getDiskStatus(diskId);
        DiskImage disk = (CinderDisk) diskDao.get(diskId);
        if (imageStatus != null && imageStatus != disk.getImageStatus()) {

        }
    }

    protected Guid getDiskId(AddCinderDiskCommand<AddDiskParameters> addCinderDiskCommand) {
        return addCinderDiskCommand.getParameters().getDiskInfo().getId();
    }
}


switch(view.getId()) {
            case R.id.btnList:
                Utilidades.visualizacion = Utilidades.LIST;
                break;
            case R.id.btnGrid:
                Utilidades.visualizacion = Utilidades.GRID;
                break;
        }

package co.quindio.sena.recyclerviewpersonalizado;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<PersonajeVo> listaPersonajes;

    RecyclerView recyclerPersonajes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        construirRecycler();
    }

    private void llenarPersonajes() {
        listaPersonajes.add(new PersonajeVo("Krusty", "Herschel Shmoikel Pinkus Yerocham Krustofsky, conocido como Krusty el payaso, es un personaje de la serie de dibujos animados Los Simpson.", R.drawable.krusti));
        listaPersonajes.add(new PersonajeVo("Homero", "Homer Jay Simpson es uno de los protagonistas de la serie. Es el padre de la familia protagonista y uno de los personajes centrales y más importantes de la serie.", R.drawable.homero));
        listaPersonajes.add(new PersonajeVo("Marge", "Marjorie \"Marge\" Bouvier Simpson una de los protagonistas de la serie. Es la esposa de Homer Simpson y madre de los tres hijos que ha tenido de esta unión amorosa: Bart, Lisa y Maggie. ", R.drawable.marge));
        listaPersonajes.add(new PersonajeVo("Bart", "Bartholomew JoJo «Bart» Simpson, es uno de los protagonistas de la serie. Bart tiene 10 años y es el primogénito, y único hijo varón de Homer y Marge Simpson. ", R.drawable.bart));
        listaPersonajes.add(new PersonajeVo("Lisa", "Lisa Marie Simpson es una de las protagonistas de la serie. Es la hija mediana de Homer y Marge Simpson, y hermana de Bart y Maggie. Goza de notable protagonismo y complejidad en la serie.", R.drawable.lisa));
        listaPersonajes.add(new PersonajeVo("Magie", "Margaret Evelyn \"Maggie\" Simpson es una de las protagonistas de la serie. Es la tercera hija del matrimonio protagonista, Homer y Marge Simpson, y la más joven de ellos.", R.drawable.magie));
        listaPersonajes.add(new PersonajeVo("Flanders", "Nedward «Ned» Flanders es un personaje ficticio de la serie de televisión de dibujos animados Los Simpson. La voz original en inglés es de Harry Shearer.", R.drawable.flanders));
        listaPersonajes.add(new PersonajeVo("Milhouse", "Milhouse Mussolini Van Houten es un personaje ficticio de la serie animada Los Simpson, creado por Matt Groening.", R.drawable.milhouse));
        listaPersonajes.add(new PersonajeVo("Mr. Burns", "Charles Montgomery Burns, más conocido como el señor Burns o Monty Burns, es un personaje ficticio recurrente de la serie de televisión de dibujos animados Los Simpson, creada por Matt Groening.", R.drawable.burns));
    }

    public void onClick(View view) {

        construirRecycler();
    }

    private void construirRecycler() {
        listaPersonajes = new ArrayList<>();
        recyclerPersonajes = (RecyclerView) findViewById(R.id.RecyclerId);
        if (Utilidades.visualizacion == Utilidades.LIST) {
            recyclerPersonajes.setLayoutManager(new LinearLayoutManager(this));
        } else {
            recyclerPersonajes.setLayoutManager(new GridLayoutManager(this, 3));
        }
        llenarPersonajes();
        AdaptadorPersonajes adapter = new AdaptadorPersonajes(listaPersonajes);
        adapter.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Selección: " + listaPersonajes.get(recyclerPersonajes.getChildAdapterPosition(view)).getNombre(), Toast.LENGTH_SHORT).show();
            }
        });
        recyclerPersonajes.setAdapter(adapter);
    }
}


switch(rand.nextInt(3)) {
            case 0:
                return '%';
            case 1:
                return '\n';
            case 2:
                return '\r';
            default:
                throw new RuntimeException("Invalid random number");
        }

/*
 * ------------------------------------------------------------------ *
 *
 *
 *
 *  KNIME interoperates with ECLIPSE solely via ECLIPSE's plug-in APIs.
 *  Hence, KNIME and ECLIPSE are both independent programs and are not
 *  KNIME and ECLIPSE being a combined program, KNIME AG herewith grants
 *  you the additional permission to use and propagate KNIME together with
 *  ECLIPSE with only the license terms in place for ECLIPSE applying to
 *  license terms of ECLIPSE themselves allow for the respective use and
 *  propagation of ECLIPSE together with KNIME.
 *
 *  Additional permission relating to nodes for KNIME that extend the Node
 *  Extension (and in particular that are based on subclasses of NodeModel,
 *  NodeDialog, and NodeView) and that only interoperate with KNIME through
 *  standard APIs ("Nodes"):
 *  Nodes are deemed to be separate and independent programs and to not be
 *  covered works.  Notwithstanding anything to the contrary in the
 *  License, the License does not apply to Nodes, you are not required to
 *  prepare and propagate Nodes, in each case even if such Nodes are
 *  propagated with or for interoperation with KNIME.  The owner of a Node
 *  may freely choose the license terms applicable to such Node, including
 *  when such Node is propagated with or for interoperation with KNIME.
 * ---------------------------------------------------------------------
 *
 * History
 *   Mar 28, 2007 (wiswedel): created
 */
package org.knime.core.util;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Random;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.knime.core.node.NodeLogger;
import junit.framework.Assert;

/**
 * @author wiswedel, University of Konstanz
 */
public class DuplicateCheckerTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void testNoDuplicateManyRows() throws IOException {
        long t = System.currentTimeMillis();
        DuplicateChecker dc = new DuplicateChecker();
        try {
            int[] indices = new int[10000000];
            for (int i = 0; i < indices.length; i++) {
                indices[i] = i;
            }
            Random r = new Random();
            for (int i = indices.length - 1; i >= 0; i--) {
                int swpIndex = r.nextInt(indices.length);
                int swp = indices[i];
                indices[i] = indices[swpIndex];
                indices[swpIndex] = swp;
            }
            for (int i : indices) {
                dc.addKey("Row " + i);
            }
            dc.checkForDuplicates();
        } catch (DuplicateKeyException ex) {
            NodeLogger.getLogger(getClass()).error("No duplicates inserted but exception was thrown", ex);
            Assert.fail("No duplicates inserted but exception was thrown");
        } finally {
            dc.clear();
        }
        NodeLogger.getLogger(getClass()).info((System.currentTimeMillis() - t) + "ms");
    }

    @Test
    public void testNoStringsAtAll() throws DuplicateKeyException, IOException {
        DuplicateChecker dc = new DuplicateChecker();
        dc.checkForDuplicates();
    }

    @Test
    public void testArbitraryStringsNoDuplicates() throws IOException {
        long seed = System.currentTimeMillis();
        NodeLogger.getLogger(getClass()).info("Using seed " + seed);
        internalTestArbitraryStrings(false, seed);
    }

    @Test
    public void testArbitraryStringsDuplicates() throws IOException {
        long seed = System.currentTimeMillis();
        NodeLogger.getLogger(getClass()).info("Using seed " + seed);
        internalTestArbitraryStrings(true, seed);
        // this one generates invalid UTF-16 strings
        seed = 1343253055319L;
        NodeLogger.getLogger(getClass()).info("Using seed " + seed);
        internalTestArbitraryStrings(true, seed);
    }

    /**
     * Simple test for duplicates in the first chunk.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testEarlyDuplicate() throws Exception {
        DuplicateChecker checker = new DuplicateChecker();
        checker.addKey("A");
        expectedException.expect(DuplicateKeyException.class);
        checker.addKey("A");
    }

    // * Simply test that calling write to disk works with duplicates works as expected.
    // * @throws Exception
    // @Test
    // * Simply test that calling write to disk works with unique keys works as expected.
    // * @throws Exception
    // @Test
    // // do useless writeToDisk calls
    // // add an additional row that resides in memory
    private void internalTestArbitraryStrings(final boolean isAddDuplicates, final long seed) throws IOException {
        LinkedHashSet<String> hash = new LinkedHashSet<String>();
        Random r = new Random(seed);
        while (hash.size() < 300000) {
            int length = 5 + r.nextInt(30);
            char[] c = new char[length];
            for (int i = 0; i < length; i++) {
                double prob = r.nextDouble();
                if (prob < 0.05) {
                    c[i] = getRandomSpecialChar(r);
                } else if (prob < 0.1) {
                    c[i] = getRandomArbitraryChar(r);
                } else {
                    c[i] = getRandomASCIIChar(r);
                }
            }
            hash.add(new String(c));
        }
        DuplicateChecker dc = new DuplicateChecker(1000, 50);
        int duplIndex = r.nextInt(hash.size());
        int indexToInsert = r.nextInt(hash.size());
        while (indexToInsert == duplIndex) {
            indexToInsert = r.nextInt(hash.size());
        }
        if (duplIndex > indexToInsert) {
            int swap = duplIndex;
            duplIndex = indexToInsert;
            indexToInsert = swap;
        }
        String dupl = null;
        try {
            int index = 0;
            for (String c : hash) {
                if (index == duplIndex) {
                    dupl = c;
                } else if (isAddDuplicates && index == indexToInsert) {
                    assert dupl != null;
                    dc.addKey(dupl);
                }
                dc.addKey(c);
                index++;
            }
            dc.checkForDuplicates();
        } catch (DuplicateKeyException e) {
            dc.clear();
            if (isAddDuplicates) {
                Assert.assertEquals(dupl, e.getKey());
                return;
            } else {
                NodeLogger.getLogger(getClass()).error("No duplicates inserted but exception was thrown", e);
                Assert.fail("Duplicate detected even though no duplicates are present");
            }
        }
        dc.clear();
        if (isAddDuplicates) {
            Assert.fail("No duplicate detected even though at least one is present");
        }
    }

    private static char getRandomSpecialChar(final Random rand) {

    }

    private static char getRandomArbitraryChar(final Random rand) {
        return (char) rand.nextInt(Character.MAX_VALUE + 1);
    }

    private static char getRandomASCIIChar(final Random rand) {
        return (char) (' ' + rand.nextInt(Byte.MAX_VALUE - ' '));
    }
}


switch(((Integer) objArr[2]).intValue()) {
                    case 1:
                        lnVar.mdA = aVar3.pMj.mH();
                        return 0;
                    case 2:
                        lnVar.moj = aVar3.pMj.mH();
                        return 0;
                    default:
                        return -1;
                }

package com.tencent.mm.protocal.c;

import com.tencent.mm.ba.a;

public final class ln extends a {

    public int mdA;

    public int moj;

    protected final int a(int i, Object... objArr) {
        if (i == 0) {
            a.a.a.c.a aVar = (a.a.a.c.a) objArr[0];
            aVar.dV(1, this.mdA);
            aVar.dV(2, this.moj);
            return 0;
        } else if (i == 1) {
            return (a.a.a.a.dS(1, this.mdA) + 0) + a.a.a.a.dS(2, this.moj);
        } else {
            if (i == 2) {
                a.a.a.a.a aVar2 = new a.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
                for (int a = a.a(aVar2); a > 0; a = a.a(aVar2)) {
                    if (!super.a(aVar2, this, a)) {
                        aVar2.bQL();
                    }
                }
                return 0;
            } else if (i != 3) {
                return -1;
            } else {
                a.a.a.a.a aVar3 = (a.a.a.a.a) objArr[0];
                ln lnVar = (ln) objArr[1];


switch(item.getItemId()) {
            case MENU_DICT_INFO:
                startActivity(new Intent(this, DictionariesActivity.class));
                break;
            case MENU_ABOUT:
                showAbout();
                break;
        }

/* This file is part of Aard Dictionary for Android <http://aarddict.org>.
 *
 * for more details.
 *
*/
package aarddict.android;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import aarddict.Entry;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.Uri;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TwoLineListItem;

public class LookupActivity extends BaseDictionaryActivity {

    private final static String TAG = LookupActivity.class.getName();

    private Timer timer;

    private ListView listView;

    private Iterator<Entry> empty = new ArrayList<Entry>().iterator();

    void updateTitle() {
        int dictCount = dictionaryService.getVolumes().size();
        Resources r = getResources();
        String dictionaries = r.getQuantityString(R.plurals.dictionaries, dictCount);
        String appName = r.getString(R.string.appName);
        String mainTitle = r.getString(R.string.titleLookupActivity, appName, String.format(dictionaries, dictCount));
        setTitle(mainTitle);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    private void updateWordListUI(final Iterator<Entry> results) {
        runOnUiThread(new Runnable() {

            public void run() {
                TextView messageView = (TextView) findViewById(R.id.messageView);
                if (!results.hasNext()) {
                    Editable text = editText.getText();
                    if (text != null && !text.toString().equals("")) {
                        messageView.setText(Html.fromHtml(getString(R.string.nothingFound)));
                        messageView.setVisibility(View.VISIBLE);
                    } else {
                        messageView.setVisibility(View.GONE);
                    }
                } else {
                    messageView.setVisibility(View.GONE);
                }
                WordAdapter wordAdapter = new WordAdapter(results);
                listView.setAdapter(wordAdapter);
                listView.setOnItemClickListener(wordAdapter);
                setProgressBarIndeterminateVisibility(false);
            }
        });
    }

    final Runnable updateProgress = new Runnable() {

        public void run() {
            setProgressBarIndeterminateVisibility(true);
        }
    };

    private void doLookup(CharSequence word) {
        if (dictionaryService == null)
            return;
        word = trimLeft(word.toString());
        if (word.equals("")) {
            Log.d(TAG, "Nothing to look up");
            updateWordListUI(empty);
            return;
        }
        runOnUiThread(updateProgress);
        long t0 = System.currentTimeMillis();
        try {
            Iterator<Entry> results = dictionaryService.lookup(word);
            Log.d(TAG, "Looked up " + word + " in " + (System.currentTimeMillis() - t0));
            updateWordListUI(results);
        } catch (Exception e) {
            StringBuilder msgBuilder = new StringBuilder("There was an error while looking up ").append("\"").append(word).append("\"");
            if (e.getMessage() != null) {
                msgBuilder.append(": ").append(e.getMessage());
            }
            final String msg = msgBuilder.toString();
            Log.e(TAG, msg, e);
        }
    }

    private void launchWord(Entry theWord) {
        Intent next = new Intent();
        next.setClass(this, ArticleViewActivity.class);
        next.putExtra("word", theWord.title);
        next.putExtra("section", theWord.section);
        next.putExtra("volumeId", theWord.volumeId);
        next.putExtra("articlePointer", theWord.articlePointer);
        startActivity(next);
    }

    final class WordAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {

        private final List<Entry> words;

        private final LayoutInflater mInflater;

        private int itemCount;

        private Iterator<Entry> results;

        private boolean displayMore;

        public WordAdapter(Iterator<Entry> results) {
            this.results = results;
            this.words = new ArrayList<Entry>();
            loadBatch();
            mInflater = (LayoutInflater) LookupActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        private void loadBatch() {
            int count = 0;
            while (results.hasNext() && count < 20) {
                count++;
                words.add(results.next());
            }
            displayMore = results.hasNext();
            itemCount = words.size();
        }

        public int getCount() {
            return itemCount;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            if (displayMore && position == itemCount - 1) {
                loadMore(position);
            }
            TwoLineListItem view = (convertView != null) ? (TwoLineListItem) convertView : createView(parent);
            bindView(view, words.get(position));
            return view;
        }

        private int loadingMoreForPos;

        private void loadMore(int forPos) {
            if (loadingMoreForPos == forPos) {
                return;
            }
            loadingMoreForPos = forPos;
            new Thread(new Runnable() {

                public void run() {
                    loadBatch();
                    runOnUiThread(new Runnable() {

                        public void run() {
                            notifyDataSetChanged();
                        }
                    });
                }
            }).start();
        }

        private TwoLineListItem createView(ViewGroup parent) {
            TwoLineListItem item;
            if (DeviceInfo.EINK_SCREEN)
                item = (TwoLineListItem) mInflater.inflate(R.layout.eink_simple_list_item_2, parent, false);
            else
                item = (TwoLineListItem) mInflater.inflate(android.R.layout.simple_list_item_2, parent, false);
            item.getText2().setSingleLine();
            item.getText2().setEllipsize(TextUtils.TruncateAt.END);
            return item;
        }

        private void bindView(TwoLineListItem view, Entry word) {
            view.getText1().setText(word.title);
            view.getText2().setText(dictionaryService.getDisplayTitle(word.volumeId));
        }

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            launchWord(words.get(position));
        }
    }

    final static int MENU_DICT_INFO = 1;

    final static int MENU_ABOUT = 2;

    final static int MENU_DICT_REFRESH = 3;

    private EditText editText;

    private TextWatcher textWatcher;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_DICT_INFO, 0, R.string.mnInfo).setIcon(android.R.drawable.ic_menu_info_details);
        menu.add(0, MENU_ABOUT, 0, R.string.mnAbout).setIcon(R.drawable.ic_menu_aarddict);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return true;
    }

    private void showAbout() {
        PackageManager manager = getPackageManager();
        String versionName = "";
        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            versionName = info.versionName;
        } catch (NameNotFoundException e) {
            Log.e(TAG, "Failed to load package info for " + getPackageName(), e);
        }
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.HORIZONTAL);
        layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT, 1));
        layout.setPadding(10, 10, 10, 10);
        ImageView logo = new ImageView(this);
        logo.setImageResource(R.drawable.aarddict);
        logo.setPadding(0, 0, 20, 0);
        logo.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT));
        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER_HORIZONTAL);
        textView.setLineSpacing(2f, 1);
        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT));
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setText(Html.fromHtml(getString(R.string.about, getString(R.string.appName), versionName)));
        LinearLayout textViewLayout = new LinearLayout(this);
        textViewLayout.setOrientation(LinearLayout.VERTICAL);
        textViewLayout.setPadding(0, 0, 0, 10);
        textViewLayout.addView(textView);
        layout.addView(logo);
        layout.addView(textViewLayout);
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle(R.string.titleAbout).setView(layout).setNeutralButton(R.string.btnDismiss, new OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.show();
    }

    @Override
    void onDictionaryServiceReady() {
        updateTitle();
        Intent intent = getIntent();
        if (intent != null && intent.getAction() != null && intent.getAction().equals(Intent.ACTION_SEARCH)) {
            final String word = intent.getStringExtra("query");
            editText.setText(word);
            try {
                timer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        Log.d(TAG, "running lookup task for " + word + " in " + Thread.currentThread());
                        doLookup(word);
                    }
                }, 0);
            } catch (IllegalStateException e) {
                Log.e(TAG, "Failed to schedule lookup task", e);
            }
        } else {
            textWatcher.afterTextChanged(editText.getText());
        }
    }

    @Override
    void onDictionaryOpenFinished() {
        onDictionaryServiceReady();
    }

    @Override
    void initUI() {
        getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        if (DeviceInfo.EINK_SCREEN) {
            setContentView(R.layout.eink_lookup);
            listView = (ListView) findViewById(R.id.einkLookupResult);
        } else {
            setContentView(R.layout.lookup);
            listView = (ListView) findViewById(R.id.lookupResult);
        }
        timer = new Timer();
        editText = (EditText) findViewById(R.id.wordInput);
        textWatcher = new TextWatcher() {

            TimerTask currentLookupTask;

            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
                if (currentLookupTask != null) {
                    currentLookupTask.cancel();
                }
                final Editable textToLookup = s;
                currentLookupTask = new TimerTask() {

                    @Override
                    public void run() {
                        Log.d(TAG, "running lookup task for " + textToLookup + " in " + Thread.currentThread());
                        if (textToLookup.toString().equals(editText.getText().toString())) {
                            doLookup(textToLookup);
                        }
                    }
                };
                try {
                    timer.schedule(currentLookupTask, 600);
                } catch (IllegalStateException e) {
                    // this may happen if orientation changes while loading
                    Log.d(TAG, "Failed to schedule lookup task", e);
                }
            }
        };
        editText.addTextChangedListener(textWatcher);
        editText.setOnKeyListener(new OnKeyListener() {

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.hideSoftInputFromWindow(editText.getApplicationWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        Button btnClear = (Button) findViewById(R.id.clearButton);
        btnClear.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                editText.setText("");
                editText.requestFocus();
                InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
            }
        });
    }

    static String trimLeft(String s) {
        return s.replaceAll("^\\s+", "");
    }
}


switch(position) {
                case 0:
                    gravity_hor = Gravity.LEFT;
                    break;
                case 1:
                    gravity_hor = Gravity.RIGHT;
                    break;
                case 2:
                    gravity_hor = Gravity.CENTER_HORIZONTAL;
                    break;
            }

package com.tmall.ultraviewpager.sample;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import com.tmall.ultraviewpager.UltraViewPager;
import com.tmall.ultraviewpager.transformer.UltraDepthScaleTransformer;
import com.tmall.ultraviewpager.transformer.UltraScaleTransformer;

public class PagerActivity extends Activity implements AdapterView.OnItemSelectedListener, CompoundButton.OnCheckedChangeListener, View.OnClickListener {

    private UltraViewPager ultraViewPager;

    private PagerAdapter adapter;

    private Spinner indicatorStyle;

    private Spinner indicatorGravityHor;

    private Spinner indicatorGravityVer;

    private Button indicatorBuildBtn;

    private CheckBox loopCheckBox;

    private CheckBox autoScrollCheckBox;

    private int gravity_hor;

    private int gravity_ver;

    private UltraViewPager.Orientation gravity_indicator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pager);
        int style = Integer.parseInt(getIntent().getStringExtra("style"));
        String name = getIntent().getStringExtra("name");
        ultraViewPager = (UltraViewPager) findViewById(R.id.ultra_viewpager);
        setTitle(name);
        switch(style) {
            case 1:
                ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
                adapter = new UltraPagerAdapter(false);
                ultraViewPager.setAdapter(adapter);
                ultraViewPager.setInfiniteRatio(100);
                gravity_indicator = UltraViewPager.Orientation.HORIZONTAL;
                break;
            case 2:
                ultraViewPager.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.VERTICAL);
                adapter = new UltraPagerAdapter(false);
                ultraViewPager.setAdapter(adapter);
                gravity_indicator = UltraViewPager.Orientation.VERTICAL;
                break;
            case 3:
            case 5:
            case 6:
                ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
                adapter = new UltraPagerAdapter(true);
                ultraViewPager.setAdapter(adapter);
                ultraViewPager.setMultiScreen(0.6f);
                ultraViewPager.setItemRatio(1.0f);
                ultraViewPager.setRatio(2.0f);
                ultraViewPager.setMaxHeight(800);
                ultraViewPager.setAutoMeasureHeight(true);
                gravity_indicator = UltraViewPager.Orientation.HORIZONTAL;
                if (style == 5) {
                    ultraViewPager.setPageTransformer(false, new UltraScaleTransformer());
                }
                if (style == 6) {
                    ultraViewPager.setPageTransformer(false, new UltraDepthScaleTransformer());
                }
                break;
            case 4:
                ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.VERTICAL);
                ultraViewPager.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                adapter = new UltraPagerAdapter(true);
                ultraViewPager.setAdapter(adapter);
                ultraViewPager.setMultiScreen(1.0f);
                ultraViewPager.setAutoMeasureHeight(true);
                gravity_indicator = UltraViewPager.Orientation.VERTICAL;
                break;
        }
        initUI();
    }

    private void initUI() {
        indicatorStyle = (Spinner) findViewById(R.id.indicator);
        indicatorGravityHor = (Spinner) findViewById(R.id.indicator_gravity_hor);
        indicatorGravityVer = (Spinner) findViewById(R.id.indicator_gravity_ver);
        ArrayAdapter<CharSequence> indicatorAdapter = ArrayAdapter.createFromResource(this, R.array.indicator_style, android.R.layout.simple_spinner_item);
        indicatorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        indicatorStyle.setAdapter(indicatorAdapter);
        ArrayAdapter<CharSequence> indicatorGraHorAdapter = ArrayAdapter.createFromResource(this, R.array.indicator_gravity_hor, android.R.layout.simple_spinner_item);
        indicatorGraHorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        indicatorGravityHor.setAdapter(indicatorGraHorAdapter);
        ArrayAdapter<CharSequence> indicatorGraVerAdapter = ArrayAdapter.createFromResource(this, R.array.indicator_gravity_ver, android.R.layout.simple_spinner_item);
        indicatorGraVerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        indicatorGravityVer.setAdapter(indicatorGraVerAdapter);
        indicatorStyle.setOnItemSelectedListener(this);
        indicatorGravityHor.setOnItemSelectedListener(this);
        indicatorGravityVer.setOnItemSelectedListener(this);
        loopCheckBox = (CheckBox) findViewById(R.id.loop);
        loopCheckBox.setOnCheckedChangeListener(this);
        autoScrollCheckBox = (CheckBox) findViewById(R.id.autoscroll);
        autoScrollCheckBox.setOnCheckedChangeListener(this);
        indicatorBuildBtn = (Button) findViewById(R.id.indicator_build);
        indicatorBuildBtn.setOnClickListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (ultraViewPager.getIndicator() == null) {
            ultraViewPager.initIndicator();
            ultraViewPager.getIndicator().setOrientation(gravity_indicator);
        }
        if (parent == indicatorStyle) {
            switch(position) {
                case 0:
                    ultraViewPager.disableIndicator();
                    break;
                case 1:
                    ultraViewPager.getIndicator().setFocusResId(0).setNormalResId(0);
                    ultraViewPager.getIndicator().setFocusColor(Color.GREEN).setNormalColor(Color.WHITE).setRadius((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()));
                    break;
                case 2:
                    ultraViewPager.getIndicator().setFocusResId(R.mipmap.tm_biz_lifemaster_indicator_selected).setNormalResId(R.mipmap.tm_biz_lifemaster_indicator_normal);
                    break;
                case 3:
                    break;
            }
        }
        if (parent == indicatorGravityHor) {

            if (ultraViewPager.getIndicator() != null) {
                if (gravity_ver != 0) {
                    ultraViewPager.getIndicator().setGravity(gravity_hor | gravity_ver);
                } else {
                    ultraViewPager.getIndicator().setGravity(gravity_hor);
                }
            }
        }
        if (parent == indicatorGravityVer) {
            switch(position) {
                case 0:
                    gravity_ver = Gravity.TOP;
                    break;
                case 1:
                    gravity_ver = Gravity.BOTTOM;
                    break;
                case 2:
                    gravity_ver = Gravity.CENTER_VERTICAL;
                    break;
            }
            if (ultraViewPager.getIndicator() != null) {
                if (gravity_hor != 0) {
                    ultraViewPager.getIndicator().setGravity(gravity_hor | gravity_ver);
                } else {
                    ultraViewPager.getIndicator().setGravity(gravity_ver);
                }
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView == loopCheckBox) {
            ultraViewPager.setInfiniteLoop(isChecked);
        }
        if (buttonView == autoScrollCheckBox) {
            if (isChecked) {
                SparseIntArray special = new SparseIntArray();
                special.put(0, 5000);
                special.put(1, 1500);
                ultraViewPager.setAutoScroll(2000, special);
            } else
                ultraViewPager.disableAutoScroll();
        }
    }

    @Override
    public void onClick(View v) {
        ultraViewPager.getIndicator().build();
    }

    private void defaultUltraViewPager() {
        UltraViewPager ultraViewPager = (UltraViewPager) findViewById(R.id.ultra_viewpager);
        ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
        // initialize UltraPagerAdapter，and add child view to UltraViewPager
        PagerAdapter adapter = new UltraPagerAdapter(false);
        ultraViewPager.setAdapter(adapter);
        // initialize built-in indicator
        ultraViewPager.initIndicator();
        // set style of indicators
        ultraViewPager.getIndicator().setOrientation(UltraViewPager.Orientation.HORIZONTAL).setFocusColor(Color.GREEN).setNormalColor(Color.WHITE).setRadius((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()));
        // set the alignment
        ultraViewPager.getIndicator().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        // construct built-in indicator, and add it to  UltraViewPager
        ultraViewPager.getIndicator().build();
        // set an infinite loop
        ultraViewPager.setInfiniteLoop(true);
        // enable auto-scroll mode
        ultraViewPager.setAutoScroll(2000);
    }
}