text:
package org.jvnet.sorcerer;

import antlr.Token;
import antlr.TokenStreamException;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LineMap;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import org.jvnet.sorcerer.Tag.ClassDecl;
import org.jvnet.sorcerer.Tag.DeclName;
import org.jvnet.sorcerer.Tag.FieldDecl;
import org.jvnet.sorcerer.Tag.FieldRef;
import org.jvnet.sorcerer.Tag.Literal;
import org.jvnet.sorcerer.Tag.LocalVarDecl;
import org.jvnet.sorcerer.Tag.LocalVarRef;
import org.jvnet.sorcerer.Tag.MethodDecl;
import org.jvnet.sorcerer.Tag.MethodRef;
import org.jvnet.sorcerer.Tag.TypeRef;
import org.jvnet.sorcerer.impl.JavaLexer;
import org.jvnet.sorcerer.impl.JavaTokenTypes;
import org.jvnet.sorcerer.util.CharSequenceReader;
import org.jvnet.sorcerer.util.TreeUtil;

import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.DiagnosticListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * Represents set of analyzed source code.
 *
 *

 * This object retains the entire parse trees of the source files
 * and type information, as well as enough indexes among them
 * to make page generation fast enough. There's always a tricky trade-off
 * between how much index you retain in memory vs how much you compute
 * dynamically.
 *
 *

 * Instances of this class can be safely accessed from multiple threads
 * concurrently.
 *
 *

 * Normally, {@link Analyzer} is used to create this object, but
 * advanced clients may invoke the constructor with a properly
 * configured {@link JavacTask}.
 *
 * @see Analyzer#analyze
 * @author Kohsuke Kawaguchi
 */
public class ParsedSourceSet {

    // javac related objects
    private final Trees trees;
    private final SourcePositions srcPos;
    private final Elements elements;
    private final Types types;

    private final List<CompilationUnitTree> compilationUnits = new ArrayList<CompilationUnitTree>();

    /**
     * path to {@link ClassTree} keyed by its full-qualified class name.
     */
    private final Map<String,TreePath> classes = new TreeMap<String,TreePath>();

    private final Set<PackageElement> packages = new TreeSet<PackageElement>(PACKAGENAME_COMPARATOR);

    private final List<Dependency> dependencies = new ArrayList<Dependency>();

    private final int tabWidth;

    /**
     * {@link ParsedType}s keyed by its {@link ParsedType#element}.
     */
    /*package*/ final Map<TypeElement,ParsedType> parsedTypes = new HashMap<TypeElement,ParsedType>();

    /**
     * {@link ClassTree}s in the compilation unit to their {@link TreePath}.
     */
    /*package*/ final Map<ClassTree,TreePath> treePathByClass = new HashMap<ClassTree,TreePath>();

    /**
     * Runs <tt>javac</tt> and analyzes the result.
     *
     *

     * Any error found during the analysis will be reported to
     * {@link DiagnosticListener} installed on {@link JavacTask}.
     */
    public ParsedSourceSet(JavacTask javac, int tabWidth) throws IOException {
        trees = Trees.instance(javac);
        elements = javac.getElements();
        types = javac.getTypes();
        srcPos = new SourcePositionsWrapper(trees.getSourcePositions());
        this.tabWidth = tabWidth;

        Iterable<? extends CompilationUnitTree> parsed = javac.parse();
        javac.analyze();

        // used to list up all analyzed classes
        TreePathScanner<?,?> classScanner = new TreePathScanner<Void,Void>() {
            public Void visitClass(ClassTree ct, Void _) {
                TreePath path = getCurrentPath();
                treePathByClass.put(ct,path);
                TypeElement e = (TypeElement) trees.getElement(path);
                if(e!=null) {
                    classes.put(e.getQualifiedName().toString(), path);

                    // make sure we have descendants tree built for all compilation units
                    getParsedType(e);

                    // remember packages that have compilation units in it
                    Element p = e.getEnclosingElement();
                    if(p.getKind()==ElementKind.PACKAGE)
                        packages.add((PackageElement) p);
                }

                return super.visitClass(ct, _);
            }
        };

        for( CompilationUnitTree u : parsed ) {
            compilationUnits.add(u);
            classScanner.scan(u,null);
        }

        // build up index for find usage.
        for( Map.Entry<TypeElement,Set<CompilationUnitTree>> e : ClassReferenceBuilder.build(compilationUnits).entrySet() )
            getParsedType(e.getKey()).referers = e.getValue().toArray(new CompilationUnitTree[e.getValue().size()]);
    }

    /**
     * Gets all the {@link CompilationUnitTree}s that are analyzed.
     *
     * @return
     *      can be empty but never null.
     */
    public List<CompilationUnitTree> getCompilationUnits() {
        return Collections.unmodifiableList(compilationUnits);
    }

    /**
     * Gets all the {@link TreePath}s to {@link ClassTree}s included
     * in the analyzed source files.
     *
     * @return
     *      can be empty but never null.
     */
    public Collection<TreePath> getClasses() {
        return Collections.unmodifiableCollection(classes.values());
    }

    /**
     * All the {@link ClassTree}s to their {@link TreePath}s.
     */
    public Map<ClassTree,TreePath> getTreePathByClass() {
        return treePathByClass;
    }

    public TreePath getTreePathByClass(ClassTree ct) {
        return treePathByClass.get(ct);
    }

    public CompilationUnitTree getCompilationUnitOf(ClassTree ct) {
        return getTreePathByClass(ct).getCompilationUnit();
    }

    /**
     * Gets the javadoc/sorcerer locations of dependencies.
     */
    public List<Dependency> getDependencies() {
        return dependencies;
    }

    public void addDependency(Dependency d) {
        dependencies.add(d);
    }

    /**
     * Gets all the classes included in the analyzed source files.
     *
     *

     * This includes interfaces, enums, and annotation types.
     * It also includes types that are defined elsewhere (that are referenced by
     * compiled source code.)
     *
     * @return
     *      can be empty but never null.
     */
    public Collection<TypeElement> getClassElements() {
        return Collections.unmodifiableCollection(parsedTypes.keySet());
    }

    /**
     * Gets all the classes in the given package.
     */
    public Collection<TypeElement> getClassElements(PackageElement pkg) {
        Set<TypeElement> r = new TreeSet<TypeElement>(TYPE_COMPARATOR);
        for (TypeElement e : parsedTypes.keySet()) {
            Element p = e.getEnclosingElement();
            if(p.equals(pkg))
                r.add(e);
        }
        return r;
    }

    /**
     * Gets all the packages of the analyzed source files.
     *
     *

     * This does not include those packages that are just referenced.
     *
     * @return
     *      can be empty but never null.
     */
    public Collection<PackageElement> getPackageElement() {
        return Collections.unmodifiableCollection(packages);
    }

    /**
     * Gets the list of all fully-qualified class names in the analyzed source files.
     *
     * @return
     *      can be empty but never null.
     */
    public Set<String> getClassNames() {
        return Collections.unmodifiableSet(classes.keySet());
    }

    /**
     * Gets the {@link TreePath} by its fully qualified class name.
     */
    public TreePath getClassTreePath(String fullyQualifiedClassName) {
        return classes.get(fullyQualifiedClassName);
    }

    /**
     * Gets the {@link Trees} object that lets you navigate around the tree model.
     *
     * @return
     *      always non-null, same object.
     */
    public Trees getTrees() {
        return trees;
    }

    /**
     * Gets the {@link SourcePositions} object that lets you find the location of objects.
     *
     * @return
     *      always non-null, same object.
     */
    public SourcePositions getSourcePositions() {
        return srcPos;
    }

    public Pos getPositionOf(TreePath p) {
        return getPositionOf(p.getCompilationUnit(),p.getLeaf());
    }

    public Pos getPositionOf(CompilationUnitTree cu, Tree t) {
        long pos = getSourcePositions().getStartPosition(cu, t);
        return new Pos(cu,pos);
    }

    /**
     * Gets the {@link Elements} object that lets you navigate around {@link Element}s.
     *
     * @return
     *      always non-null, same object.
     */
    public Elements getElements() {
        return elements;
    }

    /**
     * Gets the {@link Types} object that lets you navigate around {@link TypeMirror}s.
     *
     * @return
     *      always non-null, same object.
     */
    public Types getTypes() {
        return types;
    }

    /**
     * Gets the current TAB width.
     */
    public int getTabWidth() {
        return tabWidth;
    }

    /**
     * Gets or creates a {@link ParsedType} for the given {@link TypeElement}.
     */
    public ParsedType getParsedType(TypeElement e) {
        ParsedType v = parsedTypes.get(e);
        if(v==null)
            return new ParsedType(this,e);   // the constructor will register itself to the map
        else
            return v;
    }

    /**
     * Gets all the {@link ParsedType}s.
     */
    public Collection<ParsedType> getParsedTypes() {
        return parsedTypes.values();
    }

    /**
     * Invoked by {@link AstGenerator}'s constructor to complete the initialization.
     *

     * This is where the actual annotation of the source code happens.
     */
    protected void configure(final CompilationUnitTree cu, final AstGenerator gen) throws IOException {
        final LineMap lineMap = cu.getLineMap();

        // add lexical markers
        JavaLexer lexer = new JavaLexer(new CharSequenceReader(gen.sourceFile));
        lexer.setTabSize(tabWidth);
        try {
            Stack<Long> openBraces = new Stack<Long>();

            while(true) {
                Token token = lexer.nextToken();
                int type = token.getType();
                if(type == JavaTokenTypes.EOF)
                    break;
                if(type == JavaTokenTypes.IDENT && ReservedWords.LIST.contains(token.getText()))
                    gen.add(new Tag.ReservedWord(lineMap,token));
                if(type == JavaTokenTypes.ML_COMMENT
                || type == JavaTokenTypes.SL_COMMENT)
                    gen.add(new Tag.Comment(lineMap,token));
                if(type == JavaTokenTypes.LCURLY || type==JavaTokenTypes.LPAREN) {
                    openBraces.push(getPosition(lineMap,token));
                    gen.add(new Tag.Killer(lineMap,token)); // CurlyBracket tag yields '{'. so kill this off.
                }
                if(type == JavaTokenTypes.RCURLY) {
                    long sp = openBraces.pop();
                    gen.add(new Tag.CurlyBracket(sp,getPosition(lineMap,token)+1));
                    gen.add(new Tag.Killer(lineMap,token));
                }
                if(type == JavaTokenTypes.RPAREN) {
                    long sp = openBraces.pop();
                    gen.add(new Tag.Parenthesis(sp,getPosition(lineMap,token)+1));
                    gen.add(new Tag.Killer(lineMap,token));
                }
            }
        } catch (TokenStreamException e) {
            // the analysis phase should have reported all the errors,
            // so we should ignore any failures at this point.
        }

        final Name CLASS = elements.getName("class");

        // then semantic ones
        new TreeScanner<Void,Void>() {
            /**
             * primitive types like int, long, void, etc.
             */
            public Void visitPrimitiveType(PrimitiveTypeTree pt, Void _) {
                // all primitives should be marked up by lexer
                // gen.add(new Tag.PrimitiveType(cu,srcPos,pt));
                return super.visitPrimitiveType(pt,_);
            }

            /**
             * literal string, int, etc. Null.
             */
            public Void visitLiteral(LiteralTree lit, Void _) {
                gen.add(new Literal(cu,srcPos,lit));
                return super.visitLiteral(lit, _);
            }

            /**
             * Definition of a variable, such as parameter, field, and local variables.
             */
            public Void visitVariable(VariableTree vt, Void _) {
                VariableElement e = (VariableElement) TreeUtil.getElement(vt);
                if(e!=null) {
                    switch (e.getKind()) {
                    case ENUM_CONSTANT:
                    case FIELD:
                        gen.add(new FieldDecl(cu,srcPos,vt));
                        break;
                    case EXCEPTION_PARAMETER:
                    case LOCAL_VARIABLE:
                    case PARAMETER:
                        gen.add(new LocalVarDecl(cu,srcPos,vt,e));
                        break;
                    }

                    Token token;
                    if(e.getKind()!= ElementKind.ENUM_CONSTANT) {
                        // put the marker just on the variable name.
                        // the token for the variable name is after its type.
                        // note that we need to handle declarations like "int a,b".
                        token = gen.findTokenAfter(vt.getType(), true, vt.getName().toString());
                    } else {
                        // for the enum constant put the anchor around vt
                        token = gen.findTokenAfter(vt, false, vt.getName().toString());
                    }
                    // TODO: handle declarations like "String abc[]"
                    if(token!=null)
                        gen.add(new DeclName(lineMap,token));
                }
                return super.visitVariable(vt,_);
            }

            /**
             * Method declaration.
             */
            public Void visitMethod(MethodTree mt, Void _) {
                ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mt);
                if(e!=null) {
                    if ((((MethodSymbol)e).flags() & Flags.SYNTHETIC) != 0)
                        return _; // this is a synthesized constructor

                    // mark up the method name
                    Tree prev = mt.getReturnType();
                    String name;
                    if(e.getKind()== ElementKind.CONSTRUCTOR)
                        name = e.getEnclosingElement().getSimpleName().toString();
                    else // constructor returns <init> from getName(), so we need the above code
                        name = mt.getName().toString();
                    Token token;
                    if(prev!=null)
                        token = gen.findTokenAfter(prev, true, name);
                    else
                        token = gen.findTokenAfter(mt,false,name);

                    if(token!=null)
                        gen.add(new DeclName(lineMap,token));

                    ParsedType pt = getParsedType((TypeElement) e.getEnclosingElement());

                    gen.add(new MethodDecl(cu, srcPos, mt, e,
                        pt.findOverriddenMethods(elements, e),
                        pt.findOverridingMethods(elements, e)
                        ));
                }

                return super.visitMethod(mt, _);
            }

            /**
             * Class declaration.
             */
            public Void visitClass(ClassTree ct, Void _) {
                TypeElement e = (TypeElement) TreeUtil.getElement(ct);
                if(e!=null) {
                    // put the marker on the class name portion.
                    Token token=null;
                    if(ct.getModifiers()!=null)
                        token = gen.findTokenAfter(ct.getModifiers(), true, ct.getSimpleName().toString());
                        // on enum class, like "public enum En {ABC,DEF}", the above returns null somehow.
                        // so go with the plan B if it's not found.
                        // TODO: report to javac team
                    if(token==null)
                        token = gen.findTokenAfter(ct, false, ct.getSimpleName().toString());
                    if(token!=null)
                        gen.add(new DeclName(lineMap, token));

                    List<ParsedType> descendants = getParsedType(e).descendants;

                    gen.add(new ClassDecl(cu, srcPos, ct, e, descendants));

                    if(e.getNestingKind()== NestingKind.ANONYMOUS) {
                        // don't visit the extends and implements clause as
                        // they already show up in the NewClassTree
                        scan(ct.getMembers());
                        return _;
                    }
                }
                return super.visitClass(ct, _);
            }

            /**
             * All the symbols found in the source code.
             */
            public Void visitIdentifier(IdentifierTree id, Void _) {
                if(!ReservedWords.LIST.contains(id.getName().toString())) {
                    Element e = TreeUtil.getElement(id);
                    if(e!=null) {
                        switch (e.getKind()) {
                        case ANNOTATION_TYPE:
                        case CLASS:
                        case ENUM:
                        case INTERFACE:
                            gen.add(new TypeRef(cu,srcPos,id,(TypeElement)e));
                            break;
                        case FIELD: // such as objects imported by static import.
                        case ENUM_CONSTANT:
                            gen.add(new FieldRef(cu,srcPos,id,(VariableElement)e));
                            break;
                        case PARAMETER:
                        case EXCEPTION_PARAMETER:
                        case LOCAL_VARIABLE:
                            gen.add(new LocalVarRef(cu,srcPos,id,(VariableElement)e));
                            break;
                        }
                    }
                }

                return super.visitIdentifier(id,_);
            }

            /**
             * "exp.token"
             */
            public Void visitMemberSelect(MemberSelectTree mst, Void _) {
                // avoid marking 'Foo.class' as static reference
                if(!mst.getIdentifier().equals(CLASS)) {
                    // just select the 'token' portion
                    long ep = srcPos.getEndPosition(cu,mst);
                    long sp = ep-mst.getIdentifier().length();

                    // marker for the selected identifier
                    Element e = TreeUtil.getElement(mst);
                    if(e!=null) {
                        switch(e.getKind()) {
                        case FIELD:
                        case ENUM_CONSTANT:
                            gen.add(new FieldRef(sp,ep,(VariableElement)e));
                            break;

                        // these show up in the import statement
                        case ANNOTATION_TYPE:
                        case CLASS:
                        case ENUM:
                        case INTERFACE:
                            gen.add(new TypeRef(sp,ep,(TypeElement)e));
                            break;
                        }
                    }
                }

                return super.visitMemberSelect(mst, _);
            }

            /**
             * Constructor invocation.
             */
            public Void visitNewClass(NewClassTree nt, Void _) {
                long ep = srcPos.getEndPosition(cu, nt.getIdentifier());
                long sp = srcPos.getStartPosition(cu, nt.getIdentifier());

                // marker for jumping to the definition
                Element e = TreeUtil.getElement(nt);
                if(e instanceof ExecutableElement) {// this check is needed in case the source code contains errors
                    ExecutableElement ee = (ExecutableElement) e;
                    TypeElement ownerType = (TypeElement) ee.getEnclosingElement();
                    if(ownerType.getSimpleName().length()==0) {
                        // if this is the constructor for an anonymous class,
                        // can't link to the constructor as it's synthetic
                        scan(nt.getIdentifier());
                    } else {
                        // TODO: the identifier tree might contain type parameters, packaga names, etc.
                        // we should visit those
                        gen.add(new MethodRef(sp,ep,ee));
                    }
                }

                scan(nt.getEnclosingExpression());
                scan(nt.getArguments());
                scan(nt.getTypeArguments());
                scan(nt.getClassBody());

                return _;
            }

            // TODO: how is the 'super' or 'this' constructor invocation handled?

            /**
             * Method invocation of the form "exp.method()"
             */
            public Void visitMethodInvocation(MethodInvocationTree mi, Void _) {
                ExpressionTree ms = mi.getMethodSelect(); // PRIMARY.methodName portion
                Element e = TreeUtil.getElement(mi);
                if (e instanceof ExecutableElement) {// this check is needed in case the source code contains errors
                    ExecutableElement ee = (ExecutableElement) e;
                    Name methodName = ee.getSimpleName();
                    long ep = srcPos.getEndPosition(cu, ms);
                    if(ep>=0) {
                        // marker for the method name (and jump to definition)
                        gen.add(new MethodRef(ep-methodName.length(),ep,ee));
                    }
                }

                return super.visitMethodInvocation(mi,_);
            }

            // recursively scan trees
            private void scan(List<? extends Tree> list) {
                for (Tree t : list)
                    scan(t);
            }
            private void scan(Tree t) {
                scan(t,null);
            }
        }.scan(cu,null);

        // compilationUnit -> package name consists of member select trees
        // but it fails to create an element, so do this manually
        ExpressionTree packageName = cu.getPackageName();
        if(packageName!=null) {
            new TreeScanner<String,Void>() {
                /**
                 * For "a" of "a.b.c"
                 */
                public String visitIdentifier(IdentifierTree id, Void _) {
                    String name = id.getName().toString();
                    PackageElement pe = elements.getPackageElement(name);
                    // addRef(id,pe);
                    return name;
                }

                public String visitMemberSelect(MemberSelectTree mst, Void _) {
                    String baseName = scan(mst.getExpression(),_);
                    String name = mst.getIdentifier().toString();
                    if(baseName.length()>0) name = baseName+'.'+name;

                    PackageElement pe = elements.getPackageElement(name);

                    long ep = srcPos.getEndPosition(cu,mst);
                    long sp = ep-mst.getIdentifier().length();

                    // addRef(sp,ep,pe);
                    return name;
                }
            }.scan(packageName,null);
        }
    }

    private long getPosition(LineMap lineMap, Token token) {
        return lineMap.getPosition(token.getLine(),token.getColumn());
    }

    public static final Comparator<PackageElement> PACKAGENAME_COMPARATOR = new Comparator<PackageElement>() {
        public int compare(PackageElement lhs, PackageElement rhs) {
            return lhs.getQualifiedName().toString().compareTo(rhs.getQualifiedName().toString());
        }
    };

    public static final Comparator<Element> SIMPLENAME_COMPARATOR = new Comparator<Element>() {
        public int compare(Element lhs, Element rhs) {
            return lhs.getSimpleName().toString().compareTo(rhs.getSimpleName().toString());
        }
    };

    private static final Comparator<TypeElement> TYPE_COMPARATOR = new Comparator<TypeElement>() {
        public int compare(TypeElement lhs, TypeElement rhs) {
            return lhs.getQualifiedName().toString().compareTo(rhs.getQualifiedName().toString());
        }
    };
}


text:
// Modified to compile with MS Visual Studio 6.0 by Alan Mishchenko

#ifndef satSolver_h
#define satSolver_h

#ifdef _WIN32
#define inline __inline // compatible with MS VS 6.0
#endif

#include "satVec.h"
#include "satMem.h"

//=================================================================================================
// Simple types:

// does not work for c++
//typedef int                   bool;
#ifndef __cplusplus
#ifndef bool
#define bool int
#endif
#endif

static const bool  true      = 1;
static const bool  false     = 0;

typedef int                lit;
typedef char               lbool;

#ifndef SINT64
#define SINT64

#ifdef _WIN32
typedef signed __int64     sint64;   // compatible with MS VS 6.0
#else
typedef long long          sint64;
#endif

#endif

static const int   var_Undef = -1;
static const lit   lit_Undef = -2;

static const lbool l_Undef   =  0;
static const lbool l_True    =  1;
static const lbool l_False   = -1;

static inline lit  toLit    (int v)        { return v + v; }
static inline lit  toLitCond(int v, int c) { return v + v + (c != 0); }
static inline lit  lit_neg  (lit l)        { return l ^ 1; }
static inline int  lit_var  (lit l)        { return l >> 1; }
static inline int  lit_sign (lit l)        { return l & 1; }
static inline int  lit_print(lit l)        { return lit_sign(l)? -lit_var(l)-1 : lit_var(l)+1; }
static inline lit  lit_read (int s)        { return s > 0 ? toLit(s-1) : lit_neg(toLit(-s-1)); }

//=================================================================================================
// Public interface:

struct sat_solver_t;
typedef struct sat_solver_t sat_solver;

extern sat_solver* sat_solver_new(void);
extern void        sat_solver_delete(sat_solver* s);

extern bool        sat_solver_addclause(sat_solver* s, lit* begin, lit* end);
extern bool        sat_solver_simplify(sat_solver* s);
extern int         sat_solver_solve(sat_solver* s, lit* begin, lit* end, sint64 nConfLimit, sint64 nInsLimit, sint64 nConfLimitGlobal, sint64 nInsLimitGlobal);

extern int         sat_solver_nvars(sat_solver* s);
extern int         sat_solver_nclauses(sat_solver* s);
extern int         sat_solver_nconflicts(sat_solver* s);

extern void        sat_solver_setnvars(sat_solver* s,int n);

struct stats_t
{
    sint64   starts, decisions, propagations, inspects, conflicts;
    sint64   clauses, clauses_literals, learnts, learnts_literals, max_literals, tot_literals;
};
typedef struct stats_t stats;

extern void        Sat_SolverWriteDimacs( sat_solver * p, char * pFileName, lit* assumptionsBegin, lit* assumptionsEnd, int incrementVars );
extern void        Sat_SolverPrintStats( FILE * pFile, sat_solver * p );
extern int *       Sat_SolverGetModel( sat_solver * p, int * pVars, int nVars );
extern void        Sat_SolverDoubleClauses( sat_solver * p, int iVar );

// trace recording
extern void        Sat_SolverTraceStart( sat_solver * pSat, char * pName );
extern void        Sat_SolverTraceStop( sat_solver * pSat );
extern void        Sat_SolverTraceWrite( sat_solver * pSat, int * pBeg, int * pEnd, int fRoot );

// clause storage
extern void        sat_solver_store_alloc( sat_solver * s );
extern void        sat_solver_store_write( sat_solver * s, char * pFileName );
extern void        sat_solver_store_free( sat_solver * s );
extern void        sat_solver_store_mark_roots( sat_solver * s );
extern void        sat_solver_store_mark_clauses_a( sat_solver * s );
extern void *      sat_solver_store_release( sat_solver * s );

//=================================================================================================
// Solver representation:

struct clause_t;
typedef struct clause_t clause;

struct sat_solver_t
{
    int      size;          // nof variables
    int      cap;           // size of varmaps
    int      qhead;         // Head index of queue.
    int      qtail;         // Tail index of queue.

    // clauses
    vecp     clauses;       // List of problem constraints. (contains: clause*)
    vecp     learnts;       // List of learnt clauses. (contains: clause*)

    // activities
    double   var_inc;       // Amount to bump next variable with.
    double   var_decay;     // INVERSE decay factor for variable activity: stores 1/decay.
    float    cla_inc;       // Amount to bump next clause with.
    float    cla_decay;     // INVERSE decay factor for clause activity: stores 1/decay.

    vecp*    wlists;        //
    double*  activity;      // A heuristic measurement of the activity of a variable.
    lbool*   assigns;       // Current values of variables.
    int*     orderpos;      // Index in variable order.
    clause** reasons;       //
    int*     levels;        //
    lit*     trail;

    clause*  binary;        // A temporary binary clause
    lbool*   tags;          //
    veci     tagged;        // (contains: var)
    veci     stack;         // (contains: var)

    veci     order;         // Variable order. (heap) (contains: var)
    veci     trail_lim;     // Separator indices for different decision levels in 'trail'. (contains: int)
    veci     model;         // If problem is solved, this vector contains the model (contains: lbool).

    int      root_level;    // Level of first proper decision.
    int      simpdb_assigns;// Number of top-level assignments at last 'simplifyDB()'.
    int      simpdb_props;  // Number of propagations before next 'simplifyDB()'.
    double   random_seed;
    double   progress_estimate;
    int      verbosity;     // Verbosity level. 0=silent, 1=some progress report, 2=everything

    stats    stats;

    sint64   nConfLimit;    // external limit on the number of conflicts
    sint64   nInsLimit;     // external limit on the number of implications

    veci     act_vars;      // variables whose activity has changed
    double*  factors;       // the activity factors
    int      nRestarts;     // the number of local restarts

    Sat_MmStep_t * pMem;

    int      fSkipSimplify; // set to one to skip simplification of the clause database

    // clause store
    void *   pStore;

    // trace recording
    FILE *   pFile;
    int      nClauses;
    int      nRoots;
};

#endif

redpajama_set_name: RedPajamaGithub


text:
module Application.DocManager.Xournal where

import System.IO
import System.FilePath
import System.Process
import System.Directory

import Application.DocManager.Type
import Application.DocManager.Config

import Control.Monad

runHXournal :: DocManagerConfig -> Document -> IO ()
runHXournal dmc doc = do
  let fname = docfilename doc
  let wdir = dmc_working dmc
      xdir = dmc_xojbase dmc
      webdir = dmc_webbase dmc
  let (fnamebdy,fnameext) = splitExtension fname

  putStrLn "runHXournal"

  b1 <- doesDirectoryExist (wdir </> fnamebdy)
  when b1 $ removeDirectoryRecursive (wdir </> fnamebdy)

  b2 <- doesDirectoryExist (webdir </> fnamebdy)
  when b2 $ removeDirectoryRecursive (webdir </> fnamebdy)

  createDirectory (wdir </> fnamebdy)
  setCurrentDirectory (wdir </> fnamebdy)

  copyFile (xdir </> fname) (wdir </> fnamebdy </> fname)
  system $ "hxournal makesvg " ++ fname

  renameDirectory (wdir </> fnamebdy) (webdir </> fnamebdy)
  return ()


text:
<?php

namespace PHPExiftool\Driver\Tag\MXF;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class TimepointValue extends AbstractTag
{

    protected $Id = '060e2b34.0101.0102.0530050d.00000000';

    protected $Name = 'TimepointValue';

    protected $FullName = 'MXF::Main';

    protected $GroupName = 'MXF';

    protected $g0 = 'MXF';

    protected $g1 = 'MXF';

    protected $g2 = 'Video';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Timepoint Value';
}


text:
`via_post { ... }`

The directive activates the routing of POST requests to the application. POST requests send JSON data in order to create new resources/model-instances on the server and return the created resource.

`via_post` may appear inside the directives:

* [`collection`](collection)
* [`association`](association) (plural)

The directive's block contains [`allow`](allow) <!-- [D.1] --> (required) and
[`handler`](handler) <!-- [D.2] --> directives (optional), which define run-time code to decide on authorization and contain custom business logic if the built-in default handlers are not appropriate.

To create new resources the POST request's URI must specify the base resource under which the new resource shall be available. This can be either the `:all` collection or a plural association.

# Example
{% highlight ruby %}
expose(Person) {
  readables :first_name, :last_name
  collection(:all) {
    via_get {
      allow do |*args|
        true
      end
    }

    via_post {
      allow do |*args|
        true
      end

      ## implicit handler
      # handler do |payload, uri_params|
      #   Person.create! payload
      # end
    }
  }

  association(:posts) {
    via_get {
      allow do |*args|
        true
      end
    }

    via_post {
      allow do |*args|
        true
      end

      ## Implicit handler
      # handler do |person, payload, uri_params|
      #   person.posts.create! payload
      # end
    }
  }
}

expose(Post) {
  readables :title, :text
  via_get {
    allow do |*args|
      true
    end
  }

  association(:author) {
    via_get {
      allow do |*args|
        true
      end
    }
  }
}
{% endhighlight %}

Request:

    POST https://example.com/people
      {"first_name": "Elinor", "last_name": "Langosh"}

Response:

{% highlight json %}
{
    "self"      : "https://example.com/people/102",
    "posts"     : "https://example.com/people/102/posts",
    "first_name": "Elinor",
    "last_name" : "Langosh"
}
{% endhighlight %}

Request:

    POST https://example.com/people/102/posts
      {"title": "My First Toast", "text": "It was a bit dry."}

Response:

{% highlight json %}
{
    "self"      : "https://example.com/posts/2957",
    "author"    : "https://example.com/posts/2957/author",
    "title"     : "My First Toast",
    "text"      : "It was a bit dry."
}
{% endhighlight %}


text:
'use strict';

var
    fs = require('fs'),
    less = require('less'),
    debug = require('debug')('express-webapp-assets:filter:less'),
    DEBUG = debug.enabled;

module.exports = function (src, dst, opts, callback) {
    return fs.readFile(src, 'utf8', function (err, srcData) {
        if (err) {
            DEBUG && debug('less err', err, src, '-->', dst);
            return callback(err);
        }
        DEBUG && debug('less', src, '-->', dst);
        opts = opts || {};
        opts.filename = src;
        less.render(srcData, opts, function (err, dstData) {
            if (err) {
                DEBUG && debug('less err', err, src, '-->', dst);
                return callback(err);
            }
            return fs.writeFile(dst, dstData.css, 'utf8', callback);
        });
    });
};
module.exports.ext = 'less';


text:
'use strict';

var assign = require('object-assign');

hexo.config.server = assign({
  port: 4000,
  log: false,
  ip: '0.0.0.0'
}, hexo.config.server);

hexo.extend.console.register('server', 'Start the server.', {
  desc: 'Start the server and watch for file changes.',
  options: [
    {name: '-i, --ip', desc: 'Override the default server IP. Bind to all IP address by default.'},
    {name: '-p, --port', desc: 'Override the default port.'},
    {name: '-s, --static', desc: 'Only serve static files.'},
    {name: '-l, --log [format]', desc: 'Enable logger. Override log format.'},
    {name: '-o, --open', desc: 'Immediately open the server url in your default web browser.'}
  ]
}, require('./lib/server'));

hexo.extend.filter.register('server_middleware', require('./lib/middlewares/header'));
hexo.extend.filter.register('server_middleware', require('./lib/middlewares/gzip'));
hexo.extend.filter.register('server_middleware', require('./lib/middlewares/logger'));
hexo.extend.filter.register('server_middleware', require('./lib/middlewares/route'));
hexo.extend.filter.register('server_middleware', require('./lib/middlewares/static'));
hexo.extend.filter.register('server_middleware', require('./lib/middlewares/redirect'));


text:
{-
  Querying for back/in links to a given page.

  foo$ path/to/linksTo "Haskell"
  ...
  foo$
-}
module Main(main) where

import MediaWiki.API.Base
import MediaWiki.API.Types ( PageTitle(..) )
import MediaWiki.API

import MediaWiki.API.Query.BackLinks.Import as Back

import Util.GetOpts

-- begin option handling
data Options
 = Options
    { optWiki :: String
    , optUser :: Maybe String
    , optPass :: Maybe String
    , optPage :: Maybe String
    }

nullOptions :: Options
nullOptions = Options
    { optWiki  = "http://en.wikipedia.org/w/"
    , optUser  = Nothing
    , optPass  = Nothing
    , optPage  = Nothing
    }

option_descr :: [OptDescr (Options -> Options)]
option_descr =
  [ Option ['u'] ["user"]
           (ReqArg (\ x o -> o{optUser=Just x}) "USER")
	   "Wiki user name to login as"
  , Option ['p'] ["pass"]
           (ReqArg (\ x o -> o{optPass=Just x}) "PASSWORD")
	   "user's password credentials to supply if logging in"
  , Option ['w'] ["wiki"]
           (ReqArg (\ x o -> o{optWiki=x}) "WIKI")
	   "the Wiki to access"
  , Option ['P'] ["page"]
           (ReqArg (\ x o -> o{optPage=Just x}) "PAGE")
	   "the page title to list category pages for"
  ]

-- end option handling

queryPageInLinks :: URLString -> String -> IO [PageTitle]
queryPageInLinks url pgName = queryInLinks emptyBackLinksRequest{blTitle=Just pgName} []
 where
  queryInLinks bReq acc = do
    let req = emptyXmlRequest (mkQueryAction (queryPage pgName) bReq)
    mb <- webGetXml Back.stringXml url req
    case mb of
      Nothing -> fail ("Failed to fetch page" ++ pgName ++ " from " ++ url)
      Just c  -> do
        let acc' = acc ++ blLinks c
        case blContinue c of
          Nothing -> return acc'
	  Just x  -> queryInLinks bReq{blContinueFrom=Just x} acc'

main :: IO ()
main = do
  (opts, fs) <- processOptions option_descr nullOptions
  let url = optWiki opts
  case mbCons (optPage opts) fs of
    [] -> return ()
    xs -> mapM_ (linksToPage url) xs

linksToPage :: URLString -> String -> IO ()
linksToPage url pgName = do
  ps <- queryPageInLinks url pgName
  putStrLn ("Page " ++ show pgName ++ " has the following backlinks: ")
  mapM_ (putStrLn.toTitle) ps
 where
  toTitle pg = ' ':pgTitle pg

mbCons :: Maybe a -> [a] -> [a]
mbCons Nothing xs = xs
mbCons (Just x) xs = x:xs


text:
<?php

	$cs = Yii::app()->getClientScript();
$js=<<<EOP
	$('#PsbRegisters_batch_field').on('change', function() {
		var id = $(this).prop('checked');
		if(id == true) {
			$('div#batch').slideUp();
		} else {
			$('div#batch').slideDown();
		}
	});
	$('#PsbRegisters_batch_id').bind('change', function() {
		var url = $(this).parents('form').attr('action');
		var id = $(this).val();
		if(id != '')
			location.href = url+'/batch/'+id;
		else
			location.href = url;
	});
EOP;
	$cs->registerScript('batch', $js, CClientScript::POS_END);
?>

<?php $form=$this->beginWidget('application.libraries.yii-traits.system.OActiveForm', array(
	'id'=>'psb-registers-form',
	'enableAjaxValidation'=>true,
)); ?>

<?php //begin.Messages ?>

	<?php echo $form->errorSummary($model); ?>

<?php //begin.Messages ?>

<fieldset>

	<?php if(!$model->isNewRecord) {?>

		<?php echo $form->labelEx($model,'status'); ?>

			<?php echo $form->checkBox($model,'status'); ?>
			<?php echo $form->error($model,'status'); ?>
			<?php /*

*/?>

	<?php }?>

	<?php if($model->isNewRecord) {
		$model->batch_field = 1;
		if($batch != null) {
			$batch_name = ''.$batch->batch_name.' '.$batch->year->years.'';
			$model->batch_id = $batch->batch_id;
		} else
			$model->batch_field = 0;?>

		<?php echo $form->labelEx($model,'batch_field'); ?>

			<?php echo $form->checkBox($model,'batch_field'); ?> <?php echo $batch != null ? $batch_name : '';?>
			<?php echo $form->error($model,'batch_field'); ?>
			<?php /*

*/?>

	<?php }?>

	<div id="batch" class="clearfix <?php echo $model->isNewRecord && $model->batch_field == 1 ? 'hide' : ''?>">
		<?php echo $form->labelEx($model,'batch_id'); ?>

			<?php $getBatch = PsbYearBatch::getBatch(1);
			if($getBatch != null)
				echo $form->dropDownList($model,'batch_id', $getBatch, array('prompt'=>Yii::t('phrase', 'Pilih salah satu')));
			else
				echo $form->dropDownList($model,'batch_id', array('prompt'=>Yii::t('phrase', 'Pilih salah satu')));?>
			<?php echo $form->error($model,'batch_id'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'register_number'); ?>

			<?php echo $form->textField($model,'register_number', array('maxlength'=>32, 'class'=>'span-4')); ?>
			<?php echo $form->error($model,'register_number'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'bundle_date'); ?>

			<?php
			$model->isNewRecord && $model->bundle_date == '' ? $model->bundle_date = date('d-m-Y') : date('d-m-Y', strtotime($model->bundle_date));
			//echo $form->textField($model,'bundle_date', array('maxlength'=>32, 'class'=>'span-5'));
			$this->widget('zii.widgets.jui.CJuiDatePicker', array(
				'model'=>$model,
				'attribute'=>'bundle_date',
				//'mode'=>'datetime',
				'options'=>array(
					'dateFormat' => 'yy-mm-dd',
				),
				'htmlOptions'=>array(
					'class' => 'span-3',
				 ),
			));	?>
			<?php  ?>
			<?php echo $form->error($model,'bundle_date'); ?>
			<?php /*

*/?>

<?php echo Yii::t('phrase', 'Identitas Peserta Seleksi');?>

		<?php echo $form->labelEx($model,'register_name'); ?>

			<?php echo $form->textField($model,'register_name', array('maxlength'=>32, 'class'=>'span-5')); ?>
			<?php echo $form->error($model,'register_name'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'nisn'); ?>

			<?php echo $form->textField($model,'nisn', array('maxlength'=>12)); ?>
			<?php echo $form->error($model,'nisn'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'birthcity_field'); ?>

			<?php
			if(!$model->isNewRecord)
				$model->birthcity_field = $model->city_relation->city;
			//echo $form->textField($model,'birthcity_field', array('maxlength'=>32,'class'=>'span-4'));
			$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
				'model' => $model,
				'attribute' => 'birthcity_field',
				'source' => Yii::app()->createUrl('zonecity/suggest'),
				'options' => array(
					//'delay '=> 50,
					'minLength' => 1,
					'showAnim' => 'fold',
					'select' => "js:function(event, ui) {
						$('form #PsbRegisters_birthcity_field').val(ui.item.value);
						$('form #PsbRegisters_birth_city').val(ui.item.id);
					}"
				),
				'htmlOptions' => array(
					'class'	=> 'span-4',
					'maxlength'=>32,
				),
			));
			echo $form->hiddenField($model,'birth_city');?>
			<?php echo $form->error($model,'birthcity_field'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'birth_date'); ?>

			<?php
			!$model->isNewRecord ? ($model->birth_date != '0000-00-00' ? $model->birth_date = date('d-m-Y', strtotime($model->birth_date)) : '') : '';
			//echo $form->textField($model,'birth_date');
			$this->widget('zii.widgets.jui.CJuiDatePicker', array(
				'model'=>$model,
				'attribute'=>'birth_date',
				//'mode'=>'datetime',
				'options'=>array(
					'dateFormat' => 'yy-mm-dd',
				),
				'htmlOptions'=>array(
					'class' => 'span-4',
				 ),
			)); ?>
			<?php echo $form->error($model,'birth_date'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'gender'); ?>

			<?php echo $form->dropDownList($model,'gender', array(
				'male'=>Yii::t('phrase', 'Laki-laki'),
				'female'=>Yii::t('phrase', 'Perempuan'),
			), array('prompt'=>Yii::t('phrase', 'Pilih salah satu'))); ?>
			<?php echo $form->error($model,'gender'); ?>
			<?php /*

*/?>

	<?php if($setting->field_religion == 1) {?>

			<?php echo $form->labelEx($model,'religion'); ?>

				<?php
				$religion = PsbReligions::getReligion(1);
				if($religion != null)
					echo $form->dropDownList($model,'religion', $religion, array('prompt'=>Yii::t('phrase', 'Pilih salah satu')));
				else
					echo $form->dropDownList($model,'religion', array('prompt'=>Yii::t('phrase', 'Pilih salah satu')));?>
				<?php echo $form->error($model,'religion'); ?>
				<?php /*

*/?>

	<?php }?>

		<?php echo $form->labelEx($model,'address'); ?>

			<?php echo $form->textArea($model,'address', array('rows'=>6, 'cols'=>50, 'class'=>'span-8 smaller')); ?>
			<?php echo $form->error($model,'address'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'address_phone'); ?>

			<?php echo $form->textField($model,'address_phone', array('maxlength'=>15)); ?>
			<?php echo $form->error($model,'address_phone'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'address_yogya'); ?>

			<?php echo $form->textArea($model,'address_yogya', array('rows'=>6, 'cols'=>50, 'class'=>'span-8 smaller')); ?>
			<?php echo $form->error($model,'address_yogya'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'address_yogya_phone'); ?>

			<?php echo $form->textField($model,'address_yogya_phone', array('maxlength'=>15)); ?>
			<?php echo $form->error($model,'address_yogya_phone'); ?>
			<?php /*

*/?>

<?php echo Yii::t('phrase', 'Identitas Orang Tua / Wali');?>

		<?php echo $form->labelEx($model,'parent_name'); ?>

			<?php echo $form->textField($model,'parent_name', array('maxlength'=>32, 'class'=>'span-5')); ?>
			<?php echo $form->error($model,'parent_name'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'parent_work'); ?>

			<?php echo $form->textField($model,'parent_work', array('maxlength'=>32, 'class'=>'span-5')); ?>
			<?php echo $form->error($model,'parent_work'); ?>
			<?php /*

*/?>

	<?php if($setting->field_religion == 1) {?>

			<?php echo $form->labelEx($model,'parent_religion'); ?>

				<?php
				$religion = PsbReligions::getReligion(1);
				if($religion != null)
					echo $form->dropDownList($model,'parent_religion', $religion, array('prompt'=>Yii::t('phrase', 'Pilih salah satu')));
				else
					echo $form->dropDownList($model,'parent_religion', array('prompt'=>Yii::t('phrase', 'Pilih salah satu')));?>
				<?php echo $form->error($model,'parent_religion'); ?>
				<?php /*

*/?>

	<?php }?>

		<?php echo $form->labelEx($model,'parent_address'); ?>

			<?php echo $form->textArea($model,'parent_address', array('rows'=>6, 'cols'=>50, 'class'=>'span-8 smaller')); ?>
			<?php echo $form->error($model,'parent_address'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($model,'parent_phone'); ?>

			<?php echo $form->textField($model,'parent_phone', array('maxlength'=>15)); ?>
			<?php echo $form->error($model,'parent_phone'); ?>
			<?php /*

*/?>

	<?php if($setting->field_wali == 1) {?>

			<?php echo $form->labelEx($model,'wali_name'); ?>

				<?php echo $form->textField($model,'wali_name', array('maxlength'=>32, 'class'=>'span-5')); ?>
				<?php echo $form->error($model,'wali_name'); ?>
				<?php /*

*/?>

			<?php echo $form->labelEx($model,'wali_work'); ?>

				<?php echo $form->textField($model,'wali_work', array('maxlength'=>32, 'class'=>'span-5')); ?>
				<?php echo $form->error($model,'wali_work'); ?>
				<?php /*

*/?>

		<?php if($setting->field_religion == 1) {?>

				<?php echo $form->labelEx($model,'wali_religion'); ?>

					<?php
					$religion = PsbReligions::getReligion(1);
					if($religion != null)
						echo $form->dropDownList($model,'wali_religion', $religion, array('prompt'=>Yii::t('phrase', 'Pilih salah satu')));
					else
						echo $form->dropDownList($model,'wali_religion', array('prompt'=>Yii::t('phrase', 'Pilih salah satu')));?>
					<?php echo $form->error($model,'wali_religion'); ?>
					<?php /*

*/?>

		<?php }?>

			<?php echo $form->labelEx($model,'wali_address'); ?>

				<?php echo $form->textArea($model,'wali_address', array('rows'=>6, 'cols'=>50, 'class'=>'span-8 smaller')); ?>
				<?php echo $form->error($model,'wali_address'); ?>
				<?php /*

*/?>

			<?php echo $form->labelEx($model,'wali_phone'); ?>

				<?php echo $form->textField($model,'wali_phone', array('maxlength'=>15)); ?>
				<?php echo $form->error($model,'wali_phone'); ?>
				<?php /*

*/?>

	<?php }?>

<?php echo Yii::t('phrase', 'Asal Sekolah');?>

		<?php echo $form->labelEx($school,'school_name'); ?>

			<?php //echo $form->textField($school,'school_name', array('maxlength'=>64, 'class'=>'span-8'));
			$url = Yii::app()->controller->createUrl('school/ajaxget');
			$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
				'model' => $school,
				'attribute' => 'school_name',
				'source' => Yii::app()->controller->createUrl('school/suggest'),
				'options' => array(
					//'delay '=> 50,
					'minLength' => 1,
					'showAnim' => 'fold',
					'select' => "js:function(event, ui) {
						$('form #PsbSchools_school_name').val(ui.item.value);
						$('form #PsbRegisters_school_id').val(ui.item.id);
						$.ajax({
							type: 'post',
							url: '$url',
							data: { school_id: ui.item.id},
							dataType: 'json',
							success: function(response) {
								$('form #PsbSchools_school_address').val(response.school_address);
								$('form #PsbSchools_school_phone').val(response.school_phone);
								$('form #PsbSchools_school_status').val(response.school_status);
							}
						});
					}"
				),
				'htmlOptions' => array(
					'class'	=> 'span-5',
					'maxlength'=>64,
				),
			));
			if(!$model->isNewRecord) {
				$model->school_id_old = $model->school_id;
				echo $form->hiddenField($model,'school_id_old');
				$model->school_name_old = $school->school_name;
				echo $form->hiddenField($model,'school_name_old');
			}
			echo $form->hiddenField($model,'school_id');?>
			<?php echo $form->error($school,'school_name'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($school,'school_address'); ?>

			<?php echo $form->textArea($school,'school_address', array('rows'=>6, 'cols'=>50, 'class'=>'span-8 smaller')); ?>
			<?php echo $form->error($school,'school_address'); ?>
			<?php /*

*/?>

		<?php echo $form->labelEx($school,'school_phone'); ?>

			<?php echo $form->textField($school,'school_phone', array('maxlength'=>15)); ?>
			<?php echo $form->error($school,'school_phone'); ?>

		<?php echo $form->labelEx($school,'school_status'); ?>

			<?php echo $form->dropDownList($school,'school_status', array(
				1=>Yii::t('phrase', 'Negeri'),
				0=>Yii::t('phrase', 'Swasta'),
			)); ?>
			<?php echo $form->error($school,'school_status'); ?>

<?php echo Yii::t('phrase', 'Nilai Ujian Nasional / UASBN');?>

	<?php if($batch != null) {?>

		<?php echo $form->labelEx($model,'school_un_detail'); ?>

			<?php //echo $form->textArea($model,'school_un_detail', array('rows'=>6, 'cols'=>50, 'class'=>'span-8 smaller'));?>

			<?php
			$valuation = $batch->batch_valuation == 1 ? 1 : 3;
			$courses = $batch->year->courses;
			if(!$model->isNewRecord)
				$model->school_un_detail = unserialize($model->school_un_detail);
			/*echo '
';
			print_r($model->school_un_detail);
			print_r(unserialize($model->school_un_rank));
			echo '
';*/
			if($courses != '') {?>

					<?php foreach($courses as $key => $val) {?>
						<?php echo $val->course->course_name;?>
					<?php }?>

				<?php for($i = 0; $i<$valuation; $i++) {?>

						<?php foreach($courses as $key => $val) {?>
							<?php echo $form->textField($model,"school_un_detail[$i][$val->course_id]");?>
						<?php }?>

				<?php }
			}?>

			<?php echo $form->error($model,'school_un_detail'); ?>
			<?php /*

*/?>

	<?php }?>

	<?php if($setting->form_online == 1) {?>

<?php echo Yii::t('phrase', 'Author');?>

			<?php echo $form->labelEx($author,'name'); ?>

				<?php echo $form->textField($author,'name', array('maxlength'=>32, 'class'=>'span-5')); ?>
				<?php echo $form->error($author,'name'); ?>
				<?php /*

*/?>

			<?php echo $form->labelEx($author,'email'); ?>

				<?php echo $form->textField($author,'email', array('maxlength'=>32, 'class'=>'span-5')); ?>
				<?php echo $form->error($author,'email'); ?>
				<?php /*

*/?>

	<?php }?>

	<?php if($model->isNewRecord) {?>

		<?php echo $form->labelEx($model,'back_field'); ?>

			<?php echo $form->checkBox($model,'back_field'); ?>
			<?php echo $form->error($model,'back_field'); ?>
			<?php /*

*/?>

	<?php } else {
		$model->back_field = 1;
		echo $form->hiddenField($model,'back_field');
	}?>

			<?php echo CHtml::submitButton($model->isNewRecord ? Yii::t('phrase', 'Create') : Yii::t('phrase', 'Save'), array('onclick' => 'setEnableSave()')); ?>

</fieldset>
<?php $this->endWidget(); ?>


text:
package nt.hai.blinkforhackernews.swipelayout.app;

import nt.hai.blinkforhackernews.swipelayout.SwipeBackLayout;

/**
 * @author Yrom
 */
public interface SwipeBackActivityBase {
    /**
     * @return the SwipeBackLayout associated with this activity.
     */
    SwipeBackLayout getSwipeBackLayout();

    void setSwipeBackEnable(boolean enable);

    /**
     * Scroll out contentView and finish the activity
     */
    void scrollToFinishActivity();

}


text:
package org.arquillian.cube.kubernetes.impl.enricher.external;

import java.lang.annotation.Annotation;

import io.fabric8.kubernetes.api.model.v4_0.apps.DeploymentList;

import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;

/**
 * A {@link ResourceProvider} for {@link DeploymentList}.
 * It refers to deplotments that have been created during the current session.
 */
public class DeploymentListResourceProvider extends org.arquillian.cube.kubernetes.impl.enricher.internal.DeploymentListResourceProvider {

    @Override
    public boolean canProvide(Class<?> type) {
        return internalToUserType(DeploymentList.class.getName()).equals(type.getName());
    }

    @Override
    public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
        return toUsersResource(super.lookup(resource, qualifiers));
    }
}


text:
"""Script to run cross validation experiments and plot the results."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import os

from absl import app
from absl import flags
import numpy as np
from scipy.stats import randint as sp_randint
import sklearn.datasets
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import train_test_split

from agbt import AGBT
from agbt_b import AGBTB
import functional as F
from gbt import GBT
from tree import Dataset
from tensorflow.python.platform import gfile

FLAGS = flags.FLAGS

flags.DEFINE_string("data_folder", None, "The directory of datasets.")
flags.DEFINE_string("output_dir", None,
                    "The directory where output will be written.")

flags.DEFINE_enum("dataset_name", "housing", [
    "all_datasets", "a1a", "w1a", "housing", "w8a", "a9a", "colon", "Year",
    "rcv1", "german", "sonar", "eunite", "diabetes"
], ("The name of instances."
    "`all_datasets` means all of the instances in the folder."))

flags.DEFINE_enum("loss", "L2Loss", ["L2Loss", "LogisticLoss"],
                  "The loss function.")

flags.DEFINE_enum(
    "method", "AGBT", ["GBT", "AGBT", "AGBTB"],
    ("The method to use. GBT is the standard gradient boosted tree. AGBT is our"
     "proposed method and AGBTB is the method proposed by Biau et al."))

flags.DEFINE_integer(
    "early_stopping_rounds", 100000,
    ("Stop the algorithm if the validation loss does not improve after this"
     "number of iterations."))

flags.DEFINE_integer("cv_random_state", 100,
                     ("The random state for cross validation."))

flags.DEFINE_float(
    "z_shrinkage_parameter", 0.1,
    "The shrinkage parameter in the z-update in accelerated method.")

flags.DEFINE_integer("max_depth", 4, "Maximal depth of a tree.")
flags.DEFINE_integer("num_trees", 20, "Number of boosting iterations.")
flags.DEFINE_integer(
    "num_iteration", 10,
    "Number of iterations in random search of the parameters.")
flags.DEFINE_float("min_split_gain", 0.01, "Minimal gain for splitting a leaf.")
flags.DEFINE_float("learning_rate", 0.3, "Learning rate.")
flags.DEFINE_float("regularizer_const", 1, "Regularizer constant.")
flags.DEFINE_boolean("use_hessian", False, "Whether to use Hessian.")

TEST_SIZE = 0.2
RANDOM_STATE = 1

LOSS = {"L2Loss": F.L2Loss, "LogisticLoss": F.LogisticLoss}

def SetupData(data_folder, dataset_name):
  path = os.path.join(data_folder, dataset_name + ".txt")
  with gfile.Open(path, "rb") as f:
    data = sklearn.datasets.load_svmlight_file(f)
  x = np.asarray(data[0].todense())
  y = np.array(data[1])
  return train_test_split(x, y, test_size=TEST_SIZE, random_state=RANDOM_STATE)

def main(argv):
  del argv

  if FLAGS.output_dir is None:
    raise ValueError("Output directory must be provided.")

  if FLAGS.data_folder is None:
    raise ValueError("Directory with downloaded datasets must be provided.")

  if FLAGS.dataset_name == "all_datasets":
    names = ["a1a", "w1a", "housing"]
  else:
    names = [FLAGS.dataset_name]

  for name in names:
    x_train, x_test, y_train, y_test = SetupData(FLAGS.data_folder, name)
    train_data = Dataset(x_train, y_train)

    GBTParams = collections.namedtuple("GBTParams", [
        "regularizer_const", "min_split_gain", "max_depth", "learning_rate",
        "num_trees", "early_stopping_rounds", "loss", "use_hessian",
        "z_shrinkage_parameter"
    ])

    params = GBTParams(
        regularizer_const=FLAGS.regularizer_const,
        min_split_gain=FLAGS.min_split_gain,
        max_depth=FLAGS.max_depth,
        learning_rate=FLAGS.learning_rate,
        num_trees=FLAGS.num_trees,
        early_stopping_rounds=FLAGS.early_stopping_rounds,
        loss=FLAGS.loss,
        use_hessian=FLAGS.use_hessian,
        z_shrinkage_parameter=FLAGS.z_shrinkage_parameter)

    param_dist = {"max_depth": [4], "min_split_gain": [0.1, 0.01, 0.001]}

    if FLAGS.loss == "L2Loss":
      param_dist["learning_rate"] = [0.01, 0.03, 0.1, 0.3, 1]
    elif FLAGS.loss == "LogisticLoss":
      param_dist["learning_rate"] = [0.04, 0.12, 0.4, 1.2, 4]

    if FLAGS.method == "GBT":
      print("Start training using GBT...")
      method = GBT(params)
      param_dist["num_trees"] = sp_randint(10, 360)

    if FLAGS.method == "AGBT":
      print("Start training using AGBT...")
      method = AGBT(params)
      param_dist["z_shrinkage_parameter"] = ([
          0.01, 0.02, 0.03, 0.05, 0.1, 0.2, 0.3, 0.5, 1
      ])
      param_dist["num_trees"] = sp_randint(5, 180)

    if FLAGS.method == "AGBTB":
      print("Start training using AGBTB...")
      method = AGBTB(params)
      param_dist["num_trees"] = sp_randint(10, 360)

    random_search = RandomizedSearchCV(
        method,
        param_distributions=param_dist,
        n_iter=FLAGS.num_iteration,
        cv=5,
        random_state=FLAGS.cv_random_state)
    random_search.fit(train_data.x, train_data.y)
    with gfile.Open(
        FLAGS.output_dir + "/" + FLAGS.dataset_name + "_" + FLAGS.method + "_" +
        str(FLAGS.cv_random_state) + ".txt", "w") as f:
      f.write("The best parameter setting of {} is: {}.\n".format(
          FLAGS.method, str(random_search.best_params_)))
      f.write("The training error with the best {} model is: {:.10f}.\n".format(
          FLAGS.method, -random_search.best_estimator_.score(x_train, y_train)))
      f.write("The testing error with the best {} model is: {:.10f}".format(
          FLAGS.method, -random_search.best_estimator_.score(x_test, y_test)))

    print("The best parameter setting of {} is: {}.\n".format(
        FLAGS.method, str(random_search.best_params_)))
    print("The training error with the best {} model is: {:.10f}.\n".format(
        FLAGS.method, -random_search.best_estimator_.score(x_train, y_train)))
    print("The testing error with the best {} model is: {:.10f}".format(
        FLAGS.method, -random_search.best_estimator_.score(x_test, y_test)))

if __name__ == "__main__":
  app.run(main)


text:
#include "Tool.h"

class Tile;

class WallTool : public Tool {
public:
    WallTool(Ogre::SceneManager* sceneManager, MapGeometry* mapGeometry);
    ~WallTool();

    Tile* tile() const;
    void setTile(Tile* tile);

    bool mousePressEvent(QMouseEvent* mouseEvent, const Ogre::Ray& ray);
    bool mouseMoveEvent(QMouseEvent* mouseEvent, const Ogre::Ray& ray);
    bool mouseReleaseEvent(QMouseEvent* mouseEvent, const Ogre::Ray& ray);

private:
    bool mSelecting;
    QPoint mStart;
    QPoint mCurrent;

    Ogre::SceneNode* mNode;
    Ogre::ManualObject* mWall;

    MapGeometry* mMapGeometry;
    Tile* mTile;

    QPoint calculatePosition(const Ogre::Ray& ray);
};


text:
title: MP Edits
summary: YouTuber
date: 2020-02-25
categories:
- game
- video
- windows
---

### Who are you, and what do you do?

My name is Matthew Parachini, otherwise known as [MP Edits](https://www.youtube.com/user/TheMineMach "Matthew's YouTube channel.") on [YouTube][]. I create animated and edited [Destiny 2][destiny-2] content about weapons in the game that are either outright broken or just hilarious in their own right. I typically ask professional Destiny 2 players in the community to offer their gameplay of them using the gun so that I can include it in my video and give it my own editing twist!

Other than running my personal YouTube channel, I also run a [Discord][] server and edit for other YouTubers. Outside of YouTube I play guitar and am currently enrolled at the University of Central Florida to get my master's in aerospace engineering.

### What hardware do you use?

My hardware setup is a pretty standard PC gaming set-up; which, coincidentally, synergizes well with high-density video editing. My computer runs an Intel [Core i7-7700k CPU][core-i7-7700k] @ 4.20GHz, 64 GB of RAM, and a NVIDIA [GeForce GTX 1060][geforce-gtx-1060] 6GB graphics card. For space, my SSD is a Samsung 250GB [850 EVO][850-evo] paired with a 1TB hard drive.

Outside of the computer, I have two 27" 60Hz HP monitors with a 43" TV wall mounted above the two monitors. For the keyboard and mouse, I use a Logitech [G910 keyboard][g910] and Razer [Basilisk][] gaming mouse. I use a Blue [Yeti][] stand up mic for chatting with my buds and voice audio capture for YouTube videos, and for audio output, I use a pair of Bose [QuietComfort 35 II][quietcomfort-35-ii] Bluetooth headphones (not the best gaming headset but I just can't get over the comfort and audio quality, which is really useful for long nights of video editing!)

### And what software?

Software is pretty simple here, the Adobe Suite! I use [After Effects][after-effects] about 90% of the time, but other than AE I use [Premiere Pro][premiere-pro], [Photoshop][], [Lightroom][], and [Media Encoder][media-encoder]. After Effects is such a powerful motion graphics software that I never really feel forced to use anything else. I have a few AE plugins that help me edit: [Motion Bro][motion-bro], [Twixtor][] Pro, and [SABER][].

### What would be your dream setup?

I'm using it! I love the setup that I'm currently using. If I had to change anything I would probably just upgrade my computer hardware to fancier and faster hardware, but that's just impractical, haha. My hardware is fast enough for me. Realistically, I could use a Core i9 instead of a Core i7 because the i9 would render previews in AE faster, but again, I'm more than satisfied with what I have currently.

[850-evo]: https://www.samsung.com/semiconductor/minisite/ssd/product/consumer/850evo/ "An SSD drive."
[after-effects]: https://www.adobe.com/products/aftereffects.html "Motion graphics and video editing software."
[basilisk]: https://www.razer.com/gaming-mice/razer-basilisk "A gaming mouse."
[core-i7-7700k]: https://ark.intel.com/products/97129/Intel-Core-i7-7700K-Processor-8M-Cache-up-to-4_50-GHz "A computer processor."
[destiny-2]: https://www.destinythegame.com/ "A looter shooter MMO."
[discord]: https://discordapp.com/ "A voice and text chat service."
[g910]: https://www.logitechg.com/en-us/product/rgb-gaming-keyboard-g910 "A gaming keyboard."
[geforce-gtx-1060]: https://www.nvidia.com/en-us/geforce/products/10series/geforce-gtx-1060/ "A graphics card."
[lightroom]: https://www.adobe.com/products/photoshop-lightroom.html "Photo management and editing software."
[media-encoder]: https://creative.adobe.com/products/media-encoder "Software for encoding video for broadcast and the web."
[motion-bro]: https://motionbro.net/ "A video editor plugin for working with face presets."
[photoshop]: https://www.adobe.com/products/photoshop.html "A bitmap image editor."
[premiere-pro]: https://en.wikipedia.org/wiki/Adobe_Premiere_Pro "A video editing suite."
[quietcomfort-35-ii]: https://www.bose.com/en_us/products/headphones/over_ear_headphones/quietcomfort-35-wireless-ii.html "On-ear headphones."
[saber]: https://www.videocopilot.net/blog/2016/03/new-plug-in-saber-now-available-100-free/ "A video editor plugin for creating laser and lightsabers."
[twixtor]: https://revisionfx.com/products/twixtor/ "A video editor plugin for changing the speed of video."
[yeti]: http://bluemic.com/yeti/ "A USB microphone."
[youtube]: https://www.youtube.com/ "A web site for watching 80's TV commercials and bad mashups."


text:
#import <Foundation/Foundation.h>

@interface NSWindow (Util)

- (float)titleBarHeight;
- (float)toolbarHeight;
- (NSImageView*) addIconToTitleBar:(NSImage*) icon;
- (void) addViewToTitleBar:(NSView*)view xoffset:(CGFloat)xoffset;

@end


text:
<?php

namespace Restoore\SystempayWebservice\StructType;

use \WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for paymentRequest StructType
 * @subpackage Structs
 * @author restoore <github.com/restoore>
 * @date 2016-02-22
 * @version 1.0.0
 */
class PaymentRequest extends AbstractStructBase
{
    /**
     * The transactionId
     * Meta informations extracted from the WSDL
     * - minOccurs: 0
     * @var string
     */
    public $transactionId;
    /**
     * The amount
     * Meta informations extracted from the WSDL
     * - minOccurs: 0
     * @var int
     */
    public $amount;
    /**
     * The currency
     * Meta informations extracted from the WSDL
     * - minOccurs: 0
     * @var int
     */
    public $currency;
    /**
     * The expectedCaptureDate
     * Meta informations extracted from the WSDL
     * - minOccurs: 0
     * @var string
     */
    public $expectedCaptureDate;
    /**
     * The manualValidation
     * Meta informations extracted from the WSDL
     * - minOccurs: 0
     * @var int
     */
    public $manualValidation;
    /**
     * The paymentOptionCode
     * Meta informations extracted from the WSDL
     * - minOccurs: 0
     * @var string
     */
    public $paymentOptionCode;
    /**
     * Constructor method for paymentRequest
     * @uses PaymentRequest::setTransactionId()
     * @uses PaymentRequest::setAmount()
     * @uses PaymentRequest::setCurrency()
     * @uses PaymentRequest::setExpectedCaptureDate()
     * @uses PaymentRequest::setManualValidation()
     * @uses PaymentRequest::setPaymentOptionCode()
     * @param string $transactionId
     * @param int $amount
     * @param int $currency
     * @param string $expectedCaptureDate
     * @param int $manualValidation
     * @param string $paymentOptionCode
     */
    public function __construct($transactionId = null, $amount = null, $currency = null, $expectedCaptureDate = null, $manualValidation = null, $paymentOptionCode = null)
    {
        $this
            ->setTransactionId($transactionId)
            ->setAmount($amount)
            ->setCurrency($currency)
            ->setExpectedCaptureDate($expectedCaptureDate)
            ->setManualValidation($manualValidation)
            ->setPaymentOptionCode($paymentOptionCode);
    }
    /**
     * Get transactionId value
     * @return string|null
     */
    public function getTransactionId()
    {
        return $this->transactionId;
    }
    /**
     * Set transactionId value
     * @param string $transactionId
     * @return \Restoore\SystempayWebservice\StructType\PaymentRequest
     */
    public function setTransactionId($transactionId = null)
    {
        // validation for constraint: string
        if (!is_null($transactionId) && !is_string($transactionId)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($transactionId)), __LINE__);
        }
        $this->transactionId = $transactionId;
        return $this;
    }
    /**
     * Get amount value
     * @return int|null
     */
    public function getAmount()
    {
        return $this->amount;
    }
    /**
     * Set amount value
     * @param int $amount
     * @return \Restoore\SystempayWebservice\StructType\PaymentRequest
     */
    public function setAmount($amount = null)
    {
        // validation for constraint: int
        if (!is_null($amount) && !is_numeric($amount)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a numeric value, "%s" given', gettype($amount)), __LINE__);
        }
        $this->amount = $amount;
        return $this;
    }
    /**
     * Get currency value
     * @return int|null
     */
    public function getCurrency()
    {
        return $this->currency;
    }
    /**
     * Set currency value
     * @param int $currency
     * @return \Restoore\SystempayWebservice\StructType\PaymentRequest
     */
    public function setCurrency($currency = null)
    {
        // validation for constraint: int
        if (!is_null($currency) && !is_numeric($currency)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a numeric value, "%s" given', gettype($currency)), __LINE__);
        }
        $this->currency = $currency;
        return $this;
    }
    /**
     * Get expectedCaptureDate value
     * @return string|null
     */
    public function getExpectedCaptureDate()
    {
        return $this->expectedCaptureDate;
    }
    /**
     * Set expectedCaptureDate value
     * @param string $expectedCaptureDate
     * @return \Restoore\SystempayWebservice\StructType\PaymentRequest
     */
    public function setExpectedCaptureDate($expectedCaptureDate = null)
    {
        // validation for constraint: string
        if (!is_null($expectedCaptureDate) && !is_string($expectedCaptureDate)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($expectedCaptureDate)), __LINE__);
        }
        $this->expectedCaptureDate = $expectedCaptureDate;
        return $this;
    }
    /**
     * Get manualValidation value
     * @return int|null
     */
    public function getManualValidation()
    {
        return $this->manualValidation;
    }
    /**
     * Set manualValidation value
     * @param int $manualValidation
     * @return \Restoore\SystempayWebservice\StructType\PaymentRequest
     */
    public function setManualValidation($manualValidation = null)
    {
        // validation for constraint: int
        if (!is_null($manualValidation) && !is_numeric($manualValidation)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a numeric value, "%s" given', gettype($manualValidation)), __LINE__);
        }
        $this->manualValidation = $manualValidation;
        return $this;
    }
    /**
     * Get paymentOptionCode value
     * @return string|null
     */
    public function getPaymentOptionCode()
    {
        return $this->paymentOptionCode;
    }
    /**
     * Set paymentOptionCode value
     * @param string $paymentOptionCode
     * @return \Restoore\SystempayWebservice\StructType\PaymentRequest
     */
    public function setPaymentOptionCode($paymentOptionCode = null)
    {
        // validation for constraint: string
        if (!is_null($paymentOptionCode) && !is_string($paymentOptionCode)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($paymentOptionCode)), __LINE__);
        }
        $this->paymentOptionCode = $paymentOptionCode;
        return $this;
    }
    /**
     * Method called when an object has been exported with var_export() functions
     * It allows to return an object instantiated with the values
     * @see AbstractStructBase::__set_state()
     * @uses AbstractStructBase::__set_state()
     * @param array $array the exported values
     * @return \Restoore\SystempayWebservice\StructType\PaymentRequest
     */
    public static function __set_state(array $array)
    {
        return parent::__set_state($array);
    }
    /**
     * Method returning the class name
     * @return string __CLASS__
     */
    public function __toString()
    {
        return __CLASS__;
    }
}


text:
(function(global: any) {
  interface ScheduledFunction {
    endTime: number;
    id: number;
    func: Function;
    args: any[];
    delay: number;
    isPeriodic: boolean;
    isRequestAnimationFrame: boolean;
  }

  interface MicroTaskScheduledFunction {
    func: Function;
    args: any[];
    target: any;
  }

  class Scheduler {
    // Next scheduler id.
    public nextId: number = 0;

    // Scheduler queue with the tuple of end time and callback function - sorted by end time.
    private _schedulerQueue: ScheduledFunction[] = [];
    // Current simulated time in millis.
    private _currentTime: number = 0;

    constructor() {}

    scheduleFunction(
        cb: Function, delay: number, args: any[] = [], isPeriodic: boolean = false,
        isRequestAnimationFrame: boolean = false, id: number = -1): number {
      let currentId: number = id < 0 ? this.nextId++ : id;
      let endTime = this._currentTime + delay;

      // Insert so that scheduler queue remains sorted by end time.
      let newEntry: ScheduledFunction = {
        endTime: endTime,
        id: currentId,
        func: cb,
        args: args,
        delay: delay,
        isPeriodic: isPeriodic,
        isRequestAnimationFrame: isRequestAnimationFrame
      };
      let i = 0;
      for (; i < this._schedulerQueue.length; i++) {
        let currentEntry = this._schedulerQueue[i];
        if (newEntry.endTime < currentEntry.endTime) {
          break;
        }
      }
      this._schedulerQueue.splice(i, 0, newEntry);
      return currentId;
    }

    removeScheduledFunctionWithId(id: number): void {
      for (let i = 0; i < this._schedulerQueue.length; i++) {
        if (this._schedulerQueue[i].id == id) {
          this._schedulerQueue.splice(i, 1);
          break;
        }
      }
    }

    tick(millis: number = 0, doTick?: (elapsed: number) => void): void {
      let finalTime = this._currentTime + millis;
      let lastCurrentTime = 0;
      if (this._schedulerQueue.length === 0 && doTick) {
        doTick(millis);
        return;
      }
      while (this._schedulerQueue.length > 0) {
        let current = this._schedulerQueue[0];
        if (finalTime < current.endTime) {
          // Done processing the queue since it's sorted by endTime.
          break;
        } else {
          // Time to run scheduled function. Remove it from the head of queue.
          let current = this._schedulerQueue.shift();
          lastCurrentTime = this._currentTime;
          this._currentTime = current.endTime;
          if (doTick) {
            doTick(this._currentTime - lastCurrentTime);
          }
          let retval = current.func.apply(global, current.args);
          if (!retval) {
            // Uncaught exception in the current scheduled function. Stop processing the queue.
            break;
          }
        }
      }
      this._currentTime = finalTime;
    }

    flush(limit = 20, flushPeriodic = false, doTick?: (elapsed: number) => void): number {
      if (flushPeriodic) {
        return this.flushPeriodic(doTick);
      } else {
        return this.flushNonPeriodic(limit, doTick);
      }
    }

    private flushPeriodic(doTick?: (elapsed: number) => void): number {
      if (this._schedulerQueue.length === 0) {
        return 0;
      }
      // Find the last task currently queued in the scheduler queue and tick
      // till that time.
      const startTime = this._currentTime;
      const lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
      this.tick(lastTask.endTime - startTime, doTick);
      return this._currentTime - startTime;
    }

    private flushNonPeriodic(limit: number, doTick?: (elapsed: number) => void): number {
      const startTime = this._currentTime;
      let lastCurrentTime = 0;
      let count = 0;
      while (this._schedulerQueue.length > 0) {
        count++;
        if (count > limit) {
          throw new Error(
              'flush failed after reaching the limit of ' + limit +
              ' tasks. Does your code use a polling timeout?');
        }

        // flush only non-periodic timers.
        // If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
        if (this._schedulerQueue.filter(task => !task.isPeriodic && !task.isRequestAnimationFrame)
                .length === 0) {
          break;
        }

        const current = this._schedulerQueue.shift();
        lastCurrentTime = this._currentTime;
        this._currentTime = current.endTime;
        if (doTick) {
          // Update any secondary schedulers like Jasmine mock Date.
          doTick(this._currentTime - lastCurrentTime);
        }
        const retval = current.func.apply(global, current.args);
        if (!retval) {
          // Uncaught exception in the current scheduled function. Stop processing the queue.
          break;
        }
      }
      return this._currentTime - startTime;
    }
  }

  class FakeAsyncTestZoneSpec implements ZoneSpec {
    static assertInZone(): void {
      if (Zone.current.get('FakeAsyncTestZoneSpec') == null) {
        throw new Error('The code should be running in the fakeAsync zone to call this function');
      }
    }

    private _scheduler: Scheduler = new Scheduler();
    private _microtasks: MicroTaskScheduledFunction[] = [];
    private _lastError: Error = null;
    private _uncaughtPromiseErrors: {rejection: any}[] =
        (Promise as any)[(Zone as any).__symbol__('uncaughtPromiseErrors')];

    pendingPeriodicTimers: number[] = [];
    pendingTimers: number[] = [];

    constructor(namePrefix: string, private trackPendingRequestAnimationFrame = false) {
      this.name = 'fakeAsyncTestZone for ' + namePrefix;
    }

    private _fnAndFlush(fn: Function, completers: {onSuccess?: Function, onError?: Function}):
        Function {
      return (...args: any[]): boolean => {
        fn.apply(global, args);

        if (this._lastError === null) {  // Success
          if (completers.onSuccess != null) {
            completers.onSuccess.apply(global);
          }
          // Flush microtasks only on success.
          this.flushMicrotasks();
        } else {  // Failure
          if (completers.onError != null) {
            completers.onError.apply(global);
          }
        }
        // Return true if there were no errors, false otherwise.
        return this._lastError === null;
      };
    }

    private static _removeTimer(timers: number[], id: number): void {
      let index = timers.indexOf(id);
      if (index > -1) {
        timers.splice(index, 1);
      }
    }

    private _dequeueTimer(id: number): Function {
      return () => {
        FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
      };
    }

    private _requeuePeriodicTimer(fn: Function, interval: number, args: any[], id: number):
        Function {
      return () => {
        // Requeue the timer callback if it's not been canceled.
        if (this.pendingPeriodicTimers.indexOf(id) !== -1) {
          this._scheduler.scheduleFunction(fn, interval, args, true, false, id);
        }
      };
    }

    private _dequeuePeriodicTimer(id: number): Function {
      return () => {
        FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
      };
    }

    private _setTimeout(fn: Function, delay: number, args: any[], isTimer = true): number {
      let removeTimerFn = this._dequeueTimer(this._scheduler.nextId);
      // Queue the callback and dequeue the timer on success and error.
      let cb = this._fnAndFlush(fn, {onSuccess: removeTimerFn, onError: removeTimerFn});
      let id = this._scheduler.scheduleFunction(cb, delay, args, false, !isTimer);
      if (isTimer) {
        this.pendingTimers.push(id);
      }
      return id;
    }

    private _clearTimeout(id: number): void {
      FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
      this._scheduler.removeScheduledFunctionWithId(id);
    }

    private _setInterval(fn: Function, interval: number, ...args: any[]): number {
      let id = this._scheduler.nextId;
      let completers = {onSuccess: null as Function, onError: this._dequeuePeriodicTimer(id)};
      let cb = this._fnAndFlush(fn, completers);

      // Use the callback created above to requeue on success.
      completers.onSuccess = this._requeuePeriodicTimer(cb, interval, args, id);

      // Queue the callback and dequeue the periodic timer only on error.
      this._scheduler.scheduleFunction(cb, interval, args, true);
      this.pendingPeriodicTimers.push(id);
      return id;
    }

    private _clearInterval(id: number): void {
      FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
      this._scheduler.removeScheduledFunctionWithId(id);
    }

    private _resetLastErrorAndThrow(): void {
      let error = this._lastError || this._uncaughtPromiseErrors[0];
      this._uncaughtPromiseErrors.length = 0;
      this._lastError = null;
      throw error;
    }

    tick(millis: number = 0, doTick?: (elapsed: number) => void): void {
      FakeAsyncTestZoneSpec.assertInZone();
      this.flushMicrotasks();
      this._scheduler.tick(millis, doTick);
      if (this._lastError !== null) {
        this._resetLastErrorAndThrow();
      }
    }

    flushMicrotasks(): void {
      FakeAsyncTestZoneSpec.assertInZone();
      const flushErrors = () => {
        if (this._lastError !== null || this._uncaughtPromiseErrors.length) {
          // If there is an error stop processing the microtask queue and rethrow the error.
          this._resetLastErrorAndThrow();
        }
      };
      while (this._microtasks.length > 0) {
        let microtask = this._microtasks.shift();
        microtask.func.apply(microtask.target, microtask.args);
      }
      flushErrors();
    }

    flush(limit?: number, flushPeriodic?: boolean, doTick?: (elapsed: number) => void): number {
      FakeAsyncTestZoneSpec.assertInZone();
      this.flushMicrotasks();
      const elapsed = this._scheduler.flush(limit, flushPeriodic, doTick);
      if (this._lastError !== null) {
        this._resetLastErrorAndThrow();
      }
      return elapsed;
    }

    // ZoneSpec implementation below.

    name: string;

    properties: {[key: string]: any} = {'FakeAsyncTestZoneSpec': this};

    onScheduleTask(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): Task {
      switch (task.type) {
        case 'microTask':
          let args = task.data && (task.data as any).args;
          // should pass additional arguments to callback if have any
          // currently we know process.nextTick will have such additional
          // arguments
          let addtionalArgs: any[];
          if (args) {
            let callbackIndex = (task.data as any).callbackIndex;
            if (typeof args.length === 'number' && args.length > callbackIndex + 1) {
              addtionalArgs = Array.prototype.slice.call(args, callbackIndex + 1);
            }
          }
          this._microtasks.push({
            func: task.invoke,
            args: addtionalArgs,
            target: task.data && (task.data as any).target
          });
          break;
        case 'macroTask':
          switch (task.source) {
            case 'setTimeout':
              task.data['handleId'] =
                  this._setTimeout(task.invoke, task.data['delay'], (task.data as any)['args']);
              break;
            case 'setInterval':
              task.data['handleId'] =
                  this._setInterval(task.invoke, task.data['delay'], (task.data as any)['args']);
              break;
            case 'XMLHttpRequest.send':
              throw new Error(
                  'Cannot make XHRs from within a fake async test. Request URL: ' +
                  (task.data as any)['url']);
            case 'requestAnimationFrame':
            case 'webkitRequestAnimationFrame':
            case 'mozRequestAnimationFrame':
              // Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
              // (60 frames per second)
              task.data['handleId'] = this._setTimeout(
                  task.invoke, 16, (task.data as any)['args'],
                  this.trackPendingRequestAnimationFrame);
              break;
            default:
              throw new Error('Unknown macroTask scheduled in fake async test: ' + task.source);
          }
          break;
        case 'eventTask':
          task = delegate.scheduleTask(target, task);
          break;
      }
      return task;
    }

    onCancelTask(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): any {
      switch (task.source) {
        case 'setTimeout':
        case 'requestAnimationFrame':
        case 'webkitRequestAnimationFrame':
        case 'mozRequestAnimationFrame':
          return this._clearTimeout(task.data['handleId']);
        case 'setInterval':
          return this._clearInterval(task.data['handleId']);
        default:
          return delegate.cancelTask(target, task);
      }
    }

    onHandleError(
        parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
        error: any): boolean {
      this._lastError = error;
      return false;  // Don't propagate error to parent zone.
    }
  }

  // Export the class so that new instances can be created with proper
  // constructor params.
  (Zone as any)['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
})(typeof window === 'object' && window || typeof self === 'object' && self || global);


text:
package com.ptun.app;

/**
 * Created by Lenovo on 4/28/2017.
 */

import com.ptun.app.controllers.LoginModalController;
import com.ptun.app.db.models.User;
import com.ptun.app.enums.PEGAWAI_CHOICES;
import com.ptun.app.statics.Constants;
import com.ptun.app.statics.DBUtil;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import net.sf.dynamicreports.report.exception.DRException;

import java.io.IOException;
import java.sql.SQLException;

import static com.ptun.app.statics.Constants.LOGIN_UI;
import static com.ptun.app.statics.Constants.MAIN_UI;

public class App extends Application {

    public static Stage PRIMARY_STAGE = null;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws IOException, DRException {
        this.PRIMARY_STAGE = primaryStage;
        DBUtil.bootUpDB();
        Parent root = FXMLLoader.load(getClass().getResource(MAIN_UI));
        primaryStage.setTitle(Constants.APP_NAME);
        primaryStage.setScene(new Scene(root));
        primaryStage.setMaximized(true);
        primaryStage.show();
        loginFirst();
    }

    void loginFirst() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource(LOGIN_UI));
            AnchorPane pane = loader.load();
            LoginModalController controller = loader.getController();
            Stage stage = new Stage();
            stage.setTitle("Login");
            stage.initModality(Modality.WINDOW_MODAL);
            stage.initOwner(PRIMARY_STAGE);
            Scene scene = new Scene(pane);
            stage.setScene(scene);
            final boolean[] isValid = {false};
            controller.getBtnLogin().setOnAction(event -> {
                isValid[0] = controller.isCredentialValid();
                if (isValid[0]) stage.close();
                else controller.getLblPrompt().setText("Login gagal!");
            });
            stage.setOnCloseRequest(event -> {
                if (!isValid[0])
                    System.exit(0);
            });
            stage.showAndWait();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


text:
[![Build Status]](http://travis-ci.org/iangreenleaf/githubot)

## Install ##

    npm install githubot

## Require ##

Use it in your Hubot script:

```coffeescript
module.exports = (robot) ->
  github = require('githubot')(robot)
```

Or use it on its own:

```coffeescript
github = require('githubot')
```

You can pass additional [options](#options) to the constructor if needed.

## Use ##

Make any call to the Github v3 API, get the parsed JSON response:

```coffeescript
github.get "https://api.github.com/users/iangreenleaf/gists", (gists) ->
  console.log gists[0].description

github.get "users/foo/repos", {type: "owner"}, (repos) ->
  console.log repos[0].url

data = { description: "A test gist", public: true, files: { "abc.txt": { content: "abcdefg" } } }
github.post "gists", data, (gist) ->
  console.log gist.url

github.patch "repos/my/repo/issues/11", {status: "closed"}, (issue) ->
  console.log issue.html_url
```

## Authentication ##

If `process.env.HUBOT_GITHUB_TOKEN` is present, you're automatically authenticated. Sweet!

### Acquire a token ###

If you don't have a token yet, run this:

    curl -i https://api.github.com/authorizations -d '{"note":"githubot","scopes":["repo"]}' -u "yourusername"

Enter your Github password when prompted. When you get a response, look for the "token" value.

If you have two-factor authentication enabled, you'll have to append `-H 'X-GitHub-OTP: 123456'` to the end of the above command, or you'll receive HTTP 401 Unauthorized instead of your token.

## Handling errors ##

GitHubot will log errors automatically if it has a logger. Used with Hubot, these will go to the Hubot logger.

If your script would like to catch errors as well, define an extra callback:

```coffeescript
github.handleErrors (response) ->
  console.log "Oh no! #{response.statusCode}!"
```

The callback takes a `response` argument with the following keys:

* `error`: The error message.
* `statusCode`: The status code of the API response, if present.
* `body`: The body of the API response, if present.

You can also pass an error handler in [the options](#available-options) instead.

## Helpful Hubot ##

If `process.env.HUBOT_GITHUB_USER` is present, we can help you guess a repo's full name:

```coffeescript
github.qualified_repo "githubot" # => "iangreenleaf/githubot"
```

This will happen with the bespoke methods as well:

```coffeescript
gh.branches "githubot", (branches) ->
```

## Options ##

### Passing options ###

Options may be passed to githubot in three different ways,
in increasing order of precedence:

1. Through shell environment variables.
2. Through the constructor:

   ```coffeescript
   github = require('githubot')(robot, apiVersion: 'preview')
   ```
3. Using `withOptions`, which lets you pass options to only some requests:

   ```coffeescript
   github = require('githubot')(robot)
   preview = github.withOptions(apiVersion: 'preview')
   # Uses preview API
   preview.get '/preview/feature', -> # ...
   # Uses regular API
   github.get '/regular/feature', -> # ...
   ```

### Available options ###

* `token`/`process.env.HUBOT_GITHUB_TOKEN`:
  GitHub API token. Required to perform authenticated actions.

* `apiVersion`/`process.env.HUBOT_GITHUB_API_VERSION`:
  [Version of the API](http://developer.github.com/v3/versions/)
  to access. Defaults to 'v3'.

* `defaultUser`/`process.env.HUBOT_GITHUB_USER`:
  Default GitHub username to use if one is not given.

* `apiRoot`/`process.env.HUBOT_GITHUB_API`:
  The base API URL. This is useful for Enterprise Github installations.

  For example, `HUBOT_GITHUB_API='https://myprivate.github.int'`

* `concurrentRequests`/`process.env.HUBOT_CONCURRENT_REQUESTS`:
  Limits the allowed number of concurrent requests to the GitHub API. Defaults to 20.

* `errorHandler`:
  Function for custom error handling logic. See [handling errors](#handling-errors) for more details.

## Bespoke API access ##

Mostly a work in progress, but here's a taste of what I have in mind:

### Branches ###
#### List branches ####

```coffeescript
gh.branches "foo/bar", (branches) ->
  console.log branches[0].name
```

#### Create a branch ####

```coffeescript
# Branch from master
gh.branches( "foo/bar" ).create "my_radical_feature", (branch) ->
  console.log branch.sha

# Branch from another branch
gh.branches( "foo/bar" ).create "even_more_radical", from: "my_radical_feature", (branch) ->
  console.log branch.sha
```

#### Merge a branch ####

```coffeescript
# Merge a branch into master
gh.branches( "foo/bar" ).merge "my_radical_feature", (mergeCommit) ->
  console.log mergeCommit.message

# Merge a branch into a different target
gh.branches( "foo/bar" ).merge "my_radical_feature", into: "hotfixes", (mergeCommit) ->
  console.log mergeCommit.message

# `base` is an alias for `into`
gh.branches( "foo/bar" ).merge "my_radical_feature", base: "hotfixes", (mergeCommit) ->
  console.log mergeCommit.message

# Provide your own commit message
gh.branches( "foo/bar" ).merge "my_radical_feature", message: "Merge my radical feature!", (mergeCommit) ->
  console.log mergeCommit.sha
```

#### Delete a branch ####

```coffeescript
gh.branches( "foo/bar" ).delete "my_radical_feature", ->
  console.log "Deleted my branch!"
```

### Deployments ###

*Note*: These methods are smart and automatically use the
`cannonball-preview` version header. No intervention needed!

#### List deployments ####

```coffeescript
gh.deployments "foo/bar", (deploys) ->
  console.log deploys.length
```

#### Create a deployment ####

```coffeescript
gh.deployments("foo/bar")
  .create 'my-branch', payload: {env: 'staging'}, description: "Ship it!", (deploy) =>
    console.log deploy.url
```

#### Deployment statuses ####

```coffeescript
gh.deployments("foo/bar").status deployId, (deploys) ->
  console.log deploys[0].state
```

## Contributing ##

Install the dependencies:

    npm install

Run the tests:

    make test
    make test-all # Runs additional slower "integration" style tests, generally not necessary

**Pull requests encouraged!**

I'm vastly more likely to merge code that comes with tests. If you're confused by the testing process,
ask and I can probably point you in the right direction.

## Thanks ##

[These lovely people have contributed to githubot](https://github.com/iangreenleaf/githubot/contributors).

[Build Status]: https://travis-ci.org/iangreenleaf/githubot.png?branch=master