text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Expression = (function () {
    function Expression(nodeType) {
        this.nodeType = nodeType;
    }
    Expression.prototype.accept = function (visitor) {
        throw new Error("not implemented");
    };
    Expression.prototype.acceptGeneric = function (visitor) {
        throw new Error("not implemented");
    };
    Expression.prototype.toString = function () {
        return new PrintVisitor().visit(this);
    };
    Expression.prototype.toBonsai = function () {
        return new BonsaiVisitor().visit(this);
    };
    Expression.constant = function (value) {
        return new ConstantExpression(value);
    };
    Expression.parameter = function (name) {
        return new ParameterExpression(name);
    };
    Expression.condition = function (test, ifTrue, ifFalse) {
        return new ConditionalExpression(test, ifTrue, ifFalse);
    };
    Expression.add = function (left, right) {
        return new BinaryExpression(3 /* Add */, left, right);
    };
    Expression.subtract = function (left, right) {
        return new BinaryExpression(4 /* Subtract */, left, right);
    };
    Expression.multiply = function (left, right) {
        return new BinaryExpression(5 /* Multiply */, left, right);
    };
    Expression.divide = function (left, right) {
        return new BinaryExpression(6 /* Divide */, left, right);
    };
    Expression.modulo = function (left, right) {
        return new BinaryExpression(7 /* Modulo */, left, right);
    };
    Expression.and = function (left, right) {
        return new BinaryExpression(8 /* And */, left, right);
    };
    Expression.andAlso = function (left, right) {
        return new BinaryExpression(10 /* AndAlso */, left, right);
    };
    Expression.or = function (left, right) {
        return new BinaryExpression(9 /* Or */, left, right);
    };
    Expression.orElse = function (left, right) {
        return new BinaryExpression(11 /* OrElse */, left, right);
    };
    Expression.exclusiveOr = function (left, right) {
        return new BinaryExpression(12 /* ExclusiveOr */, left, right);
    };
    Expression.equal = function (left, right) {
        return new BinaryExpression(13 /* Equal */, left, right);
    };
    Expression.notEqual = function (left, right) {
        return new BinaryExpression(14 /* NotEqual */, left, right);
    };
    Expression.lessThan = function (left, right) {
        return new BinaryExpression(15 /* LessThan */, left, right);
    };
    Expression.lessThanOrEqual = function (left, right) {
        return new BinaryExpression(16 /* LessThanOrEqual */, left, right);
    };
    Expression.greaterThan = function (left, right) {
        return new BinaryExpression(17 /* GreaterThan */, left, right);
    };
    Expression.greaterThanOrEqual = function (left, right) {
        return new BinaryExpression(18 /* GreaterThanOrEqual */, left, right);
    };
    Expression.leftShift = function (left, right) {
        return new BinaryExpression(19 /* LeftShift */, left, right);
    };
    Expression.rightShift = function (left, right) {
        return new BinaryExpression(20 /* RightShift */, left, right);
    };
    Expression.not = function (operand) {
        return new UnaryExpression(22 /* Not */, operand);
    };
    Expression.unaryPlus = function (operand) {
        return new UnaryExpression(24 /* UnaryPlus */, operand);
    };
    Expression.negate = function (operand) {
        return new UnaryExpression(23 /* Negate */, operand);
    };
    Expression.onesComplement = function (operand) {
        return new UnaryExpression(25 /* OnesComplement */, operand);
    };
    Expression.lambda = function (body) {
        var parameters = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            parameters[_i - 1] = arguments[_i];
        }
        return new LambdaExpression(body, parameters);
    };
    Expression.invoke = function (expression) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        return new InvocationExpression(expression, args);
    };
    Expression.new = function (typeName) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        return new NewExpression(typeName, args);
    };
    Expression.functionCall = function (obj, methodName) {
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        return new FunctionCallExpression(obj, methodName, args);
    };
    Expression.member = function (obj, memberName) {
        return new MemberExpression(obj, memberName);
    };
    Expression.index = function (obj) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        return new IndexExpression(obj, args);
    };
    return Expression;
})();
var ExpressionVisitorGeneric = (function () {
    function ExpressionVisitorGeneric() {
    }
    ExpressionVisitorGeneric.prototype.visit = function (node) {
        if (node === null) {
            return null;
        }
        return node.acceptGeneric(this);
    };
    ExpressionVisitorGeneric.prototype.visitConstant = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitParameter = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitBinary = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitUnary = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitConditional = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitLambda = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitInvoke = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitCall = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitNew = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitMember = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitIndex = function (node) {
        throw new Error("not implemented");
    };
    ExpressionVisitorGeneric.prototype.visitMany = function (nodes) {
        var res = new Array(nodes.length);
        for (var i = 0; i < nodes.length; i++) {
            var oldNode = nodes[i];
            var newNode = this.visit(oldNode);
            res[i] = newNode;
        }
        return res;
    };
    return ExpressionVisitorGeneric;
})();
var ExpressionVisitor = (function () {
    function ExpressionVisitor() {
    }
    ExpressionVisitor.prototype.visit = function (node) {
        if (node === null) {
            return null;
        }
        return node.accept(this);
    };
    ExpressionVisitor.prototype.visitConstant = function (node) {
        return node;
    };
    ExpressionVisitor.prototype.visitParameter = function (node) {
        return node;
    };
    ExpressionVisitor.prototype.visitBinary = function (node) {
        return node.update(this.visit(node.left), this.visit(node.right));
    };
    ExpressionVisitor.prototype.visitUnary = function (node) {
        return node.update(this.visit(node.operand));
    };
    ExpressionVisitor.prototype.visitConditional = function (node) {
        return node.update(this.visit(node.test), this.visit(node.ifTrue), this.visit(node.ifFalse));
    };
    ExpressionVisitor.prototype.visitLambda = function (node) {
        return node.update(this.visit(node.body), this.visitMany(node.parameters));
    };
    ExpressionVisitor.prototype.visitInvoke = function (node) {
        return node.update(this.visit(node.expression), this.visitMany(node.args));
    };
    ExpressionVisitor.prototype.visitCall = function (node) {
        return node.update(this.visit(node.obj), this.visitMany(node.args));
    };
    ExpressionVisitor.prototype.visitNew = function (node) {
        return node.update(this.visitMany(node.args));
    };
    ExpressionVisitor.prototype.visitMember = function (node) {
        return node.update(this.visit(node.obj));
    };
    ExpressionVisitor.prototype.visitIndex = function (node) {
        return node.update(this.visit(node.obj), this.visitMany(node.args));
    };
    ExpressionVisitor.prototype.visitMany = function (nodes) {
        var res = new Array(nodes.length);
        for (var i = 0; i < nodes.length; i++) {
            var oldNode = nodes[i];
            var newNode = this.visit(oldNode);
            res[i] = newNode;
        }
        return res;
    };
    return ExpressionVisitor;
})();
var ConstantExpression = (function (_super) {
    __extends(ConstantExpression, _super);
    function ConstantExpression(value) {
        _super.call(this, 0 /* Constant */);
        this._value = value;
    }
    Object.defineProperty(ConstantExpression.prototype, "value", {
        get: function () {
            return this._value;
        },
        enumerable: true,
        configurable: true
    });
    ConstantExpression.prototype.accept = function (visitor) {
        return visitor.visitConstant(this);
    };
    ConstantExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitConstant(this);
    };
    return ConstantExpression;
})(Expression);
var ParameterExpression = (function (_super) {
    __extends(ParameterExpression, _super);
    function ParameterExpression(name) {
        _super.call(this, 1 /* Parameter */);
        this._name = name;
    }
    Object.defineProperty(ParameterExpression.prototype, "name", {
        get: function () {
            return this._name;
        },
        enumerable: true,
        configurable: true
    });
    ParameterExpression.prototype.accept = function (visitor) {
        return visitor.visitParameter(this);
    };
    ParameterExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitParameter(this);
    };
    return ParameterExpression;
})(Expression);
var UnaryExpression = (function (_super) {
    __extends(UnaryExpression, _super);
    function UnaryExpression(nodeType, operand) {
        _super.call(this, nodeType);
        this._operand = operand;
    }
    Object.defineProperty(UnaryExpression.prototype, "operand", {
        get: function () {
            return this._operand;
        },
        enumerable: true,
        configurable: true
    });
    UnaryExpression.prototype.accept = function (visitor) {
        return visitor.visitUnary(this);
    };
    UnaryExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitUnary(this);
    };
    UnaryExpression.prototype.update = function (operand) {
        if (operand !== this._operand) {
            return new UnaryExpression(this.nodeType, operand);
        }
        return this;
    };
    return UnaryExpression;
})(Expression);
var BinaryExpression = (function (_super) {
    __extends(BinaryExpression, _super);
    function BinaryExpression(nodeType, left, right) {
        _super.call(this, nodeType);
        this._left = left;
        this._right = right;
    }
    Object.defineProperty(BinaryExpression.prototype, "left", {
        get: function () {
            return this._left;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BinaryExpression.prototype, "right", {
        get: function () {
            return this._right;
        },
        enumerable: true,
        configurable: true
    });
    BinaryExpression.prototype.accept = function (visitor) {
        return visitor.visitBinary(this);
    };
    BinaryExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitBinary(this);
    };
    BinaryExpression.prototype.update = function (left, right) {
        if (left !== this._left || right !== this._right) {
            return new BinaryExpression(this.nodeType, left, right);
        }
        return this;
    };
    return BinaryExpression;
})(Expression);
var ConditionalExpression = (function (_super) {
    __extends(ConditionalExpression, _super);
    function ConditionalExpression(test, ifTrue, ifFalse) {
        _super.call(this, 26 /* Condition */);
        this._test = test;
        this._ifTrue = ifTrue;
        this._ifFalse = ifFalse;
    }
    Object.defineProperty(ConditionalExpression.prototype, "test", {
        get: function () {
            return this._test;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ConditionalExpression.prototype, "ifTrue", {
        get: function () {
            return this._ifTrue;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ConditionalExpression.prototype, "ifFalse", {
        get: function () {
            return this._ifTrue;
        },
        enumerable: true,
        configurable: true
    });
    ConditionalExpression.prototype.accept = function (visitor) {
        return visitor.visitConditional(this);
    };
    ConditionalExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitConditional(this);
    };
    ConditionalExpression.prototype.update = function (test, ifTrue, ifFalse) {
        if (test !== this._test || ifTrue !== this._ifTrue || ifFalse !== this._ifFalse) {
            return new ConditionalExpression(test, ifTrue, ifFalse);
        }
        return this;
    };
    return ConditionalExpression;
})(Expression);
var LambdaExpression = (function (_super) {
    __extends(LambdaExpression, _super);
    function LambdaExpression(body, parameters) {
        _super.call(this, 2 /* Lambda */);
        this._body = body;
        this._parameters = parameters;
    }
    Object.defineProperty(LambdaExpression.prototype, "body", {
        get: function () {
            return this._body;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LambdaExpression.prototype, "parameters", {
        get: function () {
            return this._parameters;
        },
        enumerable: true,
        configurable: true
    });
    LambdaExpression.prototype.accept = function (visitor) {
        return visitor.visitLambda(this);
    };
    LambdaExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitLambda(this);
    };
    LambdaExpression.prototype.update = function (body, parameters) {
        if (body !== this._body || parameters !== this._parameters) {
            return new LambdaExpression(body, parameters);
        }
        return this;
    };
    LambdaExpression.prototype.compileToFunction = function (debug) {
        var comp = new LambdaCompiler();
        comp.visit(this);
        var code = comp.code;
        code = code.replace(/\"/g, "\\\""); // TODO: more escape sequences
        code = "new Function(\"return " + code + ";\")";
        code = code.replace(/\r?\n|\r/g, "");
        if (debug) {
            alert(code);
        }
        return code;
    };
    LambdaExpression.prototype.compile = function (debug) {
        var code = this.compileToFunction(debug);
        return eval(code)();
    };
    return LambdaExpression;
})(Expression);
var InvocationExpression = (function (_super) {
    __extends(InvocationExpression, _super);
    function InvocationExpression(expression, args) {
        _super.call(this, 21 /* Invoke */);
        this._expression = expression;
        this._args = args;
    }
    Object.defineProperty(InvocationExpression.prototype, "expression", {
        get: function () {
            return this._expression;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(InvocationExpression.prototype, "args", {
        get: function () {
            return this._args;
        },
        enumerable: true,
        configurable: true
    });
    InvocationExpression.prototype.accept = function (visitor) {
        return visitor.visitInvoke(this);
    };
    InvocationExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitInvoke(this);
    };
    InvocationExpression.prototype.update = function (expression, args) {
        if (expression !== this._expression || args !== this._args) {
            return new InvocationExpression(expression, args);
        }
        return this;
    };
    return InvocationExpression;
})(Expression);
var FunctionCallExpression = (function (_super) {
    __extends(FunctionCallExpression, _super);
    function FunctionCallExpression(expression, methodName, args) {
        _super.call(this, 28 /* Call */);
        this._expression = expression;
        this._method = methodName;
        this._args = args;
    }
    Object.defineProperty(FunctionCallExpression.prototype, "obj", {
        get: function () {
            return this._expression;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(FunctionCallExpression.prototype, "method", {
        get: function () {
            return this._method;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(FunctionCallExpression.prototype, "args", {
        get: function () {
            return this._args;
        },
        enumerable: true,
        configurable: true
    });
    FunctionCallExpression.prototype.accept = function (visitor) {
        return visitor.visitCall(this);
    };
    FunctionCallExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitCall(this);
    };
    FunctionCallExpression.prototype.update = function (expression, args) {
        if (expression !== this._expression || args !== this._args) {
            return new FunctionCallExpression(expression, this._method, args);
        }
        return this;
    };
    return FunctionCallExpression;
})(Expression);
var IndexExpression = (function (_super) {
    __extends(IndexExpression, _super);
    function IndexExpression(expression, args) {
        _super.call(this, 30 /* Index */);
        this._expression = expression;
        this._args = args;
    }
    Object.defineProperty(IndexExpression.prototype, "obj", {
        get: function () {
            return this._expression;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IndexExpression.prototype, "args", {
        get: function () {
            return this._args;
        },
        enumerable: true,
        configurable: true
    });
    IndexExpression.prototype.accept = function (visitor) {
        return visitor.visitIndex(this);
    };
    IndexExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitIndex(this);
    };
    IndexExpression.prototype.update = function (expression, args) {
        if (expression !== this._expression || args !== this._args) {
            return new IndexExpression(expression, args);
        }
        return this;
    };
    return IndexExpression;
})(Expression);
var NewExpression = (function (_super) {
    __extends(NewExpression, _super);
    function NewExpression(typeName, args) {
        _super.call(this, 27 /* New */);
        this._type = typeName;
        this._args = args;
    }
    Object.defineProperty(NewExpression.prototype, "type", {
        get: function () {
            return this._type;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NewExpression.prototype, "args", {
        get: function () {
            return this._args;
        },
        enumerable: true,
        configurable: true
    });
    NewExpression.prototype.accept = function (visitor) {
        return visitor.visitNew(this);
    };
    NewExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitNew(this);
    };
    NewExpression.prototype.update = function (args) {
        if (args !== this._args) {
            return new NewExpression(this._type, args);
        }
        return this;
    };
    return NewExpression;
})(Expression);
var MemberExpression = (function (_super) {
    __extends(MemberExpression, _super);
    function MemberExpression(obj, memberName) {
        _super.call(this, 29 /* Member */);
        this._obj = obj;
        this._member = memberName;
    }
    Object.defineProperty(MemberExpression.prototype, "obj", {
        get: function () {
            return this._obj;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MemberExpression.prototype, "member", {
        get: function () {
            return this._member;
        },
        enumerable: true,
        configurable: true
    });
    MemberExpression.prototype.accept = function (visitor) {
        return visitor.visitMember(this);
    };
    MemberExpression.prototype.acceptGeneric = function (visitor) {
        return visitor.visitMember(this);
    };
    MemberExpression.prototype.update = function (obj) {
        if (obj !== this._obj) {
            return new MemberExpression(obj, this._member);
        }
        return this;
    };
    return MemberExpression;
})(Expression);
var LambdaCompiler = (function (_super) {
    __extends(LambdaCompiler, _super);
    function LambdaCompiler() {
        _super.call(this);
        this._stack = new Array();
    }
    Object.defineProperty(LambdaCompiler.prototype, "code", {
        get: function () {
            if (this._stack.length != 1)
                throw new Error("invalid code generation");
            return this._stack[0];
        },
        enumerable: true,
        configurable: true
    });
    LambdaCompiler.prototype.visitConstant = function (node) {
        var value = "";
        if (typeof node.value == "string") {
            value = "\"" + node.value + "\""; // TODO: escape characters
        }
        else if (node.value instanceof Array) {
            value = JSON.stringify(node.value);
        }
        else if (node.value === undefined) {
            value = "undefined";
        }
        else {
            value = node.value.toString(); // TODO
        }
        this._stack.push(value);
        return node;
    };
    LambdaCompiler.prototype.visitUnary = function (node) {
        this.visit(node.operand);
        var o = this._stack.pop();
        var i = "";
        switch (node.nodeType) {
            case 23 /* Negate */:
                i = "-";
                break;
            case 24 /* UnaryPlus */:
                i = "+";
                break;
            case 22 /* Not */:
                i = "!";
                break;
            case 25 /* OnesComplement */:
                i = "~";
                break;
        }
        var res = "(" + i + "" + o + ")";
        this._stack.push(res);
        return node;
    };
    LambdaCompiler.prototype.visitBinary = function (node) {
        this.visit(node.left);
        this.visit(node.right);
        var r = this._stack.pop();
        var l = this._stack.pop();
        var i = "";
        switch (node.nodeType) {
            case 3 /* Add */:
                i = "+";
                break;
            case 4 /* Subtract */:
                i = "-";
                break;
            case 5 /* Multiply */:
                i = "*";
                break;
            case 6 /* Divide */:
                i = "/";
                break;
            case 7 /* Modulo */:
                i = "%";
                break;
            case 8 /* And */:
                i = "&";
                break;
            case 9 /* Or */:
                i = "|";
                break;
            case 10 /* AndAlso */:
                i = "&&";
                break;
            case 11 /* OrElse */:
                i = "||";
                break;
            case 12 /* ExclusiveOr */:
                i = "^";
                break;
            case 13 /* Equal */:
                i = "===";
                break;
            case 14 /* NotEqual */:
                i = "!==";
                break;
            case 15 /* LessThan */:
                i = "<";
                break;
            case 16 /* LessThanOrEqual */:
                i = "<=";
                break;
            case 17 /* GreaterThan */:
                i = ">";
                break;
            case 18 /* GreaterThanOrEqual */:
                i = ">=";
                break;
            case 19 /* LeftShift */:
                i = "<<";
                break;
            case 20 /* RightShift */:
                i = ">>";
                break;
        }
        var res = "(" + l + " " + i + " " + r + ")";
        this._stack.push(res);
        return node;
    };
    LambdaCompiler.prototype.visitConditional = function (node) {
        this.visit(node.test);
        this.visit(node.ifTrue);
        this.visit(node.ifFalse);
        var f = this._stack.pop();
        var t = this._stack.pop();
        var c = this._stack.pop();
        var res = "(" + c + " ? " + t + " : " + f + ")";
        this._stack.push(res);
        return node;
    };
    LambdaCompiler.prototype.visitParameter = function (node) {
        this._stack.push(node.name);
        return node;
    };
    LambdaCompiler.prototype.visitLambda = function (node) {
        this.visitMany(node.parameters);
        this.visit(node.body);
        var body = this._stack.pop();
        var n = node.parameters.length;
        var args = new Array(n);
        for (var i = 0; i < n; i++) {
            args[n - i - 1] = this._stack.pop();
        }
        var allArgs = args.join(", ");
        var res = "function(" + allArgs + ") { return " + body + "; }";
        this._stack.push(res);
        return node;
    };
    LambdaCompiler.prototype.visitInvoke = function (node) {
        this.visit(node.expression);
        this.visitMany(node.args);
        var n = node.args.length;
        var args = new Array(n);
        for (var i = 0; i < n; i++) {
            args[n - i - 1] = this._stack.pop();
        }
        var argList = args.join(", ");
        var func = this._stack.pop();
        var res = func + "(" + argList + ")";
        this._stack.push(res);
        return node;
    };
    LambdaCompiler.prototype.visitCall = function (node) {
        var res = "";
        if (node.obj !== null) {
            this.visit(node.obj);
            res = this._stack.pop() + ".";
        }
        this.visitMany(node.args);
        var n = node.args.length;
        var args = new Array(n);
        for (var i = 0; i < n; i++) {
            args[n - i - 1] = this._stack.pop();
        }
        var argList = args.join(", ");
        res += node.method + "(" + argList + ")";
        this._stack.push(res);
        return node;
    };
    LambdaCompiler.prototype.visitNew = function (node) {
        this.visitMany(node.args);
        var n = node.args.length;
        var args = new Array(n);
        for (var i = 0; i < n; i++) {
            args[n - i - 1] = this._stack.pop();
        }
        var argList = args.join(", ");
        var res = "new " + node.type + "(" + argList + ")";
        this._stack.push(res);
        return node;
    };
    LambdaCompiler.prototype.visitMember = function (node) {
        var res = "";
        if (node.obj !== null) {
            this.visit(node.obj);
            res = this._stack.pop() + ".";
        }
        res += node.member;
        this._stack.push(res);
        return node;
    };
    LambdaCompiler.prototype.visitIndex = function (node) {
        this.visit(node.obj);
        var res = this._stack.pop();
        this.visitMany(node.args);
        var n = node.args.length;
        var args = new Array(n);
        for (var i = 0; i < n; i++) {
            args[n - i - 1] = this._stack.pop();
        }
        var argList = args.join(", ");
        res += "[" + argList + "]";
        this._stack.push(res);
        return node;
    };
    return LambdaCompiler;
})(ExpressionVisitor);
var FreeVariableScanner = (function (_super) {
    __extends(FreeVariableScanner, _super);
    function FreeVariableScanner() {
        _super.call(this);
        this._stack = new Array();
        this._result = new Array();
    }
    Object.defineProperty(FreeVariableScanner.prototype, "result", {
        get: function () {
            return this._result;
        },
        enumerable: true,
        configurable: true
    });
    FreeVariableScanner.prototype.visitParameter = function (node) {
        var found = false;
        for (var i = this._stack.length - 1; i >= 0; i--) {
            if (this._stack[i].indexOf(node) >= 0) {
                found = true;
                break;
            }
        }
        if (!found) {
            this._result.push(node);
        }
        return node;
    };
    FreeVariableScanner.prototype.visitLambda = function (node) {
        this._stack.push(node.parameters);
        this.visit(node.body);
        this._stack.pop();
        return node;
    };
    return FreeVariableScanner;
})(ExpressionVisitor);
var ExpressionType;
(function (ExpressionType) {
    ExpressionType[ExpressionType["Constant"] = 0] = "Constant";
    ExpressionType[ExpressionType["Parameter"] = 1] = "Parameter";
    ExpressionType[ExpressionType["Lambda"] = 2] = "Lambda";
    ExpressionType[ExpressionType["Add"] = 3] = "Add";
    ExpressionType[ExpressionType["Subtract"] = 4] = "Subtract";
    ExpressionType[ExpressionType["Multiply"] = 5] = "Multiply";
    ExpressionType[ExpressionType["Divide"] = 6] = "Divide";
    ExpressionType[ExpressionType["Modulo"] = 7] = "Modulo";
    ExpressionType[ExpressionType["And"] = 8] = "And";
    ExpressionType[ExpressionType["Or"] = 9] = "Or";
    ExpressionType[ExpressionType["AndAlso"] = 10] = "AndAlso";
    ExpressionType[ExpressionType["OrElse"] = 11] = "OrElse";
    ExpressionType[ExpressionType["ExclusiveOr"] = 12] = "ExclusiveOr";
    ExpressionType[ExpressionType["Equal"] = 13] = "Equal";
    ExpressionType[ExpressionType["NotEqual"] = 14] = "NotEqual";
    ExpressionType[ExpressionType["LessThan"] = 15] = "LessThan";
    ExpressionType[ExpressionType["LessThanOrEqual"] = 16] = "LessThanOrEqual";
    ExpressionType[ExpressionType["GreaterThan"] = 17] = "GreaterThan";
    ExpressionType[ExpressionType["GreaterThanOrEqual"] = 18] = "GreaterThanOrEqual";
    ExpressionType[ExpressionType["LeftShift"] = 19] = "LeftShift";
    ExpressionType[ExpressionType["RightShift"] = 20] = "RightShift";
    ExpressionType[ExpressionType["Invoke"] = 21] = "Invoke";
    ExpressionType[ExpressionType["Not"] = 22] = "Not";
    ExpressionType[ExpressionType["Negate"] = 23] = "Negate";
    ExpressionType[ExpressionType["UnaryPlus"] = 24] = "UnaryPlus";
    ExpressionType[ExpressionType["OnesComplement"] = 25] = "OnesComplement";
    ExpressionType[ExpressionType["Condition"] = 26] = "Condition";
    ExpressionType[ExpressionType["New"] = 27] = "New";
    ExpressionType[ExpressionType["Call"] = 28] = "Call";
    ExpressionType[ExpressionType["Member"] = 29] = "Member";
    ExpressionType[ExpressionType["Index"] = 30] = "Index";
})(ExpressionType || (ExpressionType = {}));
var Binder = (function (_super) {
    __extends(Binder, _super);
    function Binder(resources) {
        _super.call(this);
        this._stack = new Array();
        this._resources = resources;
    }
    Binder.prototype.visitParameter = function (node) {
        var found = false;
        for (var i = this._stack.length - 1; i >= 0; i--) {
            if (this._stack[i].indexOf(node) >= 0) {
                found = true;
                break;
            }
        }
        if (!found) {
            return Expression.constant(this._resources[node.name]);
        }
        return node;
    };
    Binder.prototype.visitLambda = function (node) {
        this._stack.push(node.parameters);
        this.visit(node.body);
        this._stack.pop();
        return node;
    };
    return Binder;
})(ExpressionVisitor);
var PrintVisitor = (function (_super) {
    __extends(PrintVisitor, _super);
    function PrintVisitor() {
        _super.apply(this, arguments);
    }
    PrintVisitor.prototype.visitConstant = function (node) {
        return "Constant(" + node.value + ")";
    };
    PrintVisitor.prototype.visitParameter = function (node) {
        return "Parameter(" + node.name + ")";
    };
    PrintVisitor.prototype.visitBinary = function (node) {
        return ExpressionType[node.nodeType] + "(" + this.visit(node.left) + ", " + this.visit(node.right) + ")";
    };
    PrintVisitor.prototype.visitUnary = function (node) {
        return ExpressionType[node.nodeType] + "(" + this.visit(node.operand) + ")";
    };
    PrintVisitor.prototype.visitConditional = function (node) {
        return "Conditional(" + this.visit(node.test) + ", " + this.visit(node.ifTrue) + ", " + this.visit(node.ifFalse) + ")";
    };
    PrintVisitor.prototype.visitLambda = function (node) {
        var body = this.visit(node.body);
        var children = this.visitMany(node.parameters);
        children.unshift(body);
        return "Lambda(" + children.join(", ") + ")";
    };
    PrintVisitor.prototype.visitInvoke = function (node) {
        var expression = this.visit(node.expression);
        var children = this.visitMany(node.args);
        children.unshift(expression);
        return "Invoke(" + children.join(", ") + ")";
    };
    PrintVisitor.prototype.visitCall = function (node) {
        var children = this.visitMany(node.args);
        if (node.obj != null) {
            children.unshift(this.visit(node.obj));
        }
        children.unshift(node.method);
        return "Call(" + children.join(", ") + ")";
    };
    PrintVisitor.prototype.visitNew = function (node) {
        var children = this.visitMany(node.args);
        children.unshift(node.type);
        return "New(" + children.join(", ") + ")";
    };
    PrintVisitor.prototype.visitMember = function (node) {
        var children = [];
        if (node.obj != null) {
            children.unshift(this.visit(node.obj));
        }
        children.unshift(node.member);
        return "Member(" + children.join(", ") + ")";
    };
    PrintVisitor.prototype.visitIndex = function (node) {
        var children = this.visitMany(node.args);
        if (node.obj != null) {
            children.unshift(this.visit(node.obj));
        }
        return "Index(" + children.join(", ") + ")";
    };
    return PrintVisitor;
})(ExpressionVisitorGeneric);
var BonsaiVisitor = (function (_super) {
    __extends(BonsaiVisitor, _super);
    function BonsaiVisitor() {
        _super.apply(this, arguments);
    }
    BonsaiVisitor.prototype.visitConstant = function (node) {
        return [":", node.value];
    };
    BonsaiVisitor.prototype.visitParameter = function (node) {
        return ["$", node.name];
    };
    BonsaiVisitor.prototype.visitBinary = function (node) {
        var i = "";
        switch (node.nodeType) {
            case 3 /* Add */:
                i = "+";
                break;
            case 4 /* Subtract */:
                i = "-";
                break;
            case 5 /* Multiply */:
                i = "*";
                break;
            case 6 /* Divide */:
                i = "/";
                break;
            case 7 /* Modulo */:
                i = "%";
                break;
            case 8 /* And */:
                i = "&";
                break;
            case 9 /* Or */:
                i = "|";
                break;
            case 10 /* AndAlso */:
                i = "&&";
                break;
            case 11 /* OrElse */:
                i = "||";
                break;
            case 12 /* ExclusiveOr */:
                i = "^";
                break;
            case 13 /* Equal */:
                i = "===";
                break;
            case 14 /* NotEqual */:
                i = "!==";
                break;
            case 15 /* LessThan */:
                i = "<";
                break;
            case 16 /* LessThanOrEqual */:
                i = "<=";
                break;
            case 17 /* GreaterThan */:
                i = ">";
                break;
            case 18 /* GreaterThanOrEqual */:
                i = ">=";
                break;
            case 19 /* LeftShift */:
                i = "<<";
                break;
            case 20 /* RightShift */:
                i = ">>";
                break;
        }
        return [i, this.visit(node.left), this.visit(node.right)];
    };
    BonsaiVisitor.prototype.visitUnary = function (node) {
        var i = "";
        switch (node.nodeType) {
            case 23 /* Negate */:
                i = "-";
                break;
            case 24 /* UnaryPlus */:
                i = "+";
                break;
            case 22 /* Not */:
                i = "!";
                break;
            case 25 /* OnesComplement */:
                i = "~";
                break;
        }
        return [i, this.visit(node.operand)];
    };
    BonsaiVisitor.prototype.visitConditional = function (node) {
        return ["?:", this.visit(node.test), this.visit(node.ifTrue), this.visit(node.ifFalse)];
    };
    BonsaiVisitor.prototype.visitLambda = function (node) {
        return ["=>", this.visit(node.body), this.visitMany(node.parameters)];
    };
    BonsaiVisitor.prototype.visitInvoke = function (node) {
        var expression = this.visit(node.expression);
        var args = this.visitMany(node.args);
        return ["()", expression, args];
    };
    BonsaiVisitor.prototype.visitCall = function (node) {
        var args = [];
        if (node.obj != null) {
            args.unshift(this.visit(node.obj));
        }
        args.unshift(this.visitMany(node.args));
        return [".()", node.method, args];
    };
    BonsaiVisitor.prototype.visitNew = function (node) {
        var args = this.visitMany(node.args);
        return ["new", args];
    };
    BonsaiVisitor.prototype.visitMember = function (node) {
        var res = [".", node.member];
        if (node.obj != null) {
            res.unshift(this.visit(node.obj));
        }
        return res;
    };
    BonsaiVisitor.prototype.visitIndex = function (node) {
        throw new Error("not implemented");
    };
    return BonsaiVisitor;
})(ExpressionVisitorGeneric);
//# sourceMappingURL=compiler.js.map


text:
import optparse
import os
import re
import sys
import tempfile

sys.path.append(os.path.join(os.path.dirname(__file__), '../../'))
import pynacl.file_tools

import corpus_errors
import corpus_utils

def TestAppStartup(options, crx_path, app_path, profile_path):
  """Run the validator on a nexe, check if the result is expected.

  Args:
    options: bag of options.
    crx_path: path to the crx.
    app_path: path to the extracted crx.
    profile_path: path to a temporary profile dir.
  """
  expected_result = corpus_errors.ExpectedCrxResult(crx_path)
  try:
    manifest = corpus_utils.LoadManifest(app_path)
    start_path = manifest.get('app').get('launch').get('local_path')
  except:
    if expected_result.Matches(corpus_errors.BAD_MANIFEST):
      return True
    else:
      print "'%s': %s," % (
          corpus_utils.Sha1FromFilename(crx_path), corpus_errors.BAD_MANIFEST)
      return False
  start_url = 'chrome-extension://%s/%s' % (
      corpus_utils.ChromeAppIdFromPath(app_path), start_path)
  cmd = [options.browser,
      '--disable-web-resources',
      '--disable-preconnect',
      '--no-first-run',
      '--no-default-browser-check',
      '--enable-logging',
      '--log-level=1',
      '--safebrowsing-disable-auto-update',
      '--enable-nacl',
      '--load-extension=' + app_path,
      '--user-data-dir=' + profile_path, start_url]
  process_stdout, process_stderr, retcode = corpus_utils.RunWithTimeout(
      cmd, options.duration)
  # Check for errors we don't like.
  result = corpus_errors.GOOD
  errs = re.findall(':ERROR:[^\n]+', process_stderr)
  for err in errs:
    if 'extension_prefs.cc' in err or 'gles2_cmd_decoder.cc' in err:
      continue
    if 'Extension error: Could not load extension from' in err:
      result = result.Merge(corpus_errors.COULD_NOT_LOAD)
      continue
    if 'NaCl process exited with' in process_stderr:
      result = result.Merge(corpus_errors.MODULE_CRASHED)
      continue
    result = result.Merge(corpus_errors.CrxResult(
      'custom', custom=err, precidence=20))
  if 'NaClMakePcrelThunk:' not in process_stderr:
    result = result.Merge(corpus_errors.MODULE_DIDNT_START)
  # Check if result is what we expect.
  if not expected_result.Matches(result):
    print "'%s': %s," % (corpus_utils.Sha1FromFilename(crx_path), result)
    if options.verbose:
      print '-' * 70
      print 'Return code: %s' % retcode
      print '>>> STDOUT'
      print process_stdout
      print '>>> STDERR'
      print process_stderr
      print '-' * 70
    return False
  return True

def TestApps(options, work_dir):
  """Test a browser on a corpus of crxs.

  Args:
    options: bag of options.
    work_dir: directory to operate in.
  """
  profile_path = os.path.join(work_dir, 'profile_temp')
  app_path = os.path.join(work_dir, 'app_temp')

  list_filename = os.path.join(work_dir, 'naclapps.all')
  filenames = corpus_utils.DownloadCorpusList(list_filename)
  filenames = [f for f in filenames if f.endswith('.crx')]
  progress = corpus_utils.Progress(len(filenames))
  for filename in filenames:
    progress.Tally()
    corpus_utils.PrimeCache(options.cache_dir, filename)
    # Stop here if downloading only.
    if options.download_only:
      continue
    # Stop here if isn't a bad app but testing only bad apps.
    if options.bad_only and corpus_errors.ExpectedCrxResult(filename) == 'GOOD':
      continue
    # Unzip the app.
    corpus_utils.ExtractFromCache(options.cache_dir, filename, app_path)
    try:
      progress.Result(
          TestAppStartup(options, filename, app_path, profile_path))
    finally:
      pynacl.file_tools.RemoveDirectoryIfPresent(app_path)
      pynacl.file_tools.RemoveDirectoryIfPresent(profile_path)
  progress.Summary()

def Main():
  # TODO(bradnelson): Stderr scraping doesn't work on windows, find another
  # way if we want to run there.
  if sys.platform in ['cygwin', 'win32']:
    raise Exception('Platform not yet supported')

  parser = optparse.OptionParser()
  parser.add_option(
      '--download-only', dest='download_only',
      default=False, action='store_true',
      help='download to cache without running the tests')
  parser.add_option(
      '--duration', dest='duration', default=30,
      help='how long to run each app for')
  parser.add_option(
      '--browser', dest='browser',
      help='browser to run')
  parser.add_option(
      '-v', '--verbose', dest='verbose', default=False, action='store_true',
      help='run in verbose mode')
  parser.add_option(
      '--bad-only', dest='bad_only', default=False, action='store_true',
      help='test only known bad apps')
  parser.add_option(
      '--cache-dir', dest='cache_dir',
      default=corpus_utils.DefaultCacheDirectory(),
      help='directory to cache downloads in')
  options, args = parser.parse_args()
  if args:
    parser.error('unused arguments')
  if not options.download_only:
    if not options.browser:
      parser.error('no browser specified')

  work_dir = tempfile.mkdtemp(suffix='startup_crxs', prefix='tmp')
  work_dir = os.path.realpath(work_dir)
  try:
    TestApps(options, work_dir)
  finally:
    pynacl.file_tools.RemoveDirectoryIfPresent(work_dir)

if __name__ == '__main__':
  Main()

redpajama_set_name: RedPajamaGithub


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace DeviceExplorer.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Microsoft_IoTHub_ConnectionString {
            get {
                return ((string)(this["Microsoft_IoTHub_ConnectionString"]));
            }
            set {
                this["Microsoft_IoTHub_ConnectionString"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Microsoft_ServiceBus_EventHub_ConnectionString {
            get {
                return ((string)(this["Microsoft_ServiceBus_EventHub_ConnectionString"]));
            }
            set {
                this["Microsoft_ServiceBus_EventHub_ConnectionString"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Microsoft_ServiceBus_EventHub_EntityPath {
            get {
                return ((string)(this["Microsoft_ServiceBus_EventHub_EntityPath"]));
            }
            set {
                this["Microsoft_ServiceBus_EventHub_EntityPath"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Microsoft_Protocol_Gateway_Hostname {
            get {
                return ((string)(this["Microsoft_Protocol_Gateway_Hostname"]));
            }
            set {
                this["Microsoft_Protocol_Gateway_Hostname"] = value;
            }
        }
    }
}


text:
package pl.mobilization.conference2015.sponsor.rest;

/**
 * Created by msaramak on 29.07.15.
 */
public class SponsorRestModel {

    public String name;
    public String logo_url;
    public String link;
    public String description_html;
}


text:
package org.fcrepo.common.policy;

import org.jboss.security.xacml.sunxacml.attr.AnyURIAttribute;
import org.jboss.security.xacml.sunxacml.attr.StringAttribute;

/**
 * The Fedora Service Deployment XACML namespace.
 *
 * <pre>
 * Namespace URI    : urn:fedora:names:fedora:2.1:resource:sdep
 * </pre>
 */
public class ServiceDeploymentNamespace
        extends XacmlNamespace {

    public final XacmlName PID;

    public final XacmlName NAMESPACE;

    public final XacmlName STATE;

    public final XacmlName LOCATION;

    public final XacmlName NEW_PID;

    public final XacmlName NEW_NAMESPACE;

    private ServiceDeploymentNamespace(XacmlNamespace parent, String localName) {
        super(parent, localName);
        PID = addName(new XacmlName(this, "pid", StringAttribute.identifier));
        NEW_PID =
                addName(new XacmlName(this,
                                      "newPid",
                                      StringAttribute.identifier));
        NAMESPACE =
                addName(new XacmlName(this,
                                      "namespace",
                                      StringAttribute.identifier));
        NEW_NAMESPACE =
                addName(new XacmlName(this,
                                      "newNamespace",
                                      StringAttribute.identifier));
        LOCATION =
                addName(new XacmlName(this,
                                      "location",
                                      AnyURIAttribute.identifier));
        STATE =
                addName(new XacmlName(this, "state", StringAttribute.identifier));
    }

    public static ServiceDeploymentNamespace onlyInstance =
            new ServiceDeploymentNamespace(ResourceNamespace.getInstance(),
                                           "sdep");

    public static final ServiceDeploymentNamespace getInstance() {
        return onlyInstance;
    }

}


text:
<?php

namespace Test\Mnapoli\Translated;

use Mnapoli\Translated\TranslationUtils;

/**
 * @covers \Mnapoli\Translated\TranslationUtils
 */
class TranslationUtilsTest extends \PHPUnit_Framework_TestCase
{
    public function testGetLanguage()
    {
        $this->assertSame('en', TranslationUtils::getLanguage('en'));
        $this->assertSame('en', TranslationUtils::getLanguage('en_US'));
        $this->assertSame('en', TranslationUtils::getLanguage('en_US_US'));
        $this->assertSame('en', TranslationUtils::getLanguage('en_'));
        $this->assertSame('', TranslationUtils::getLanguage(''));
        $this->assertSame(null, TranslationUtils::getLanguage(null));
    }

    public function testGetRegion()
    {
        $this->assertEquals('US', TranslationUtils::getRegion('en_US'));
        $this->assertEquals('', TranslationUtils::getRegion('en'));
        $this->assertSame('US_US', TranslationUtils::getRegion('en_US_US'));
        $this->assertSame(null, TranslationUtils::getRegion('en_'));
        $this->assertEquals(null, TranslationUtils::getRegion(''));
        $this->assertSame(null, TranslationUtils::getRegion(null));
    }
}


text:
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Theater.Interfaces.Reflection;
using MediaBrowser.Theater.Interfaces.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Data;

namespace MediaBrowser.Theater.Presentation.ViewModels
{
    [TypeDescriptionProvider(typeof(HyperTypeDescriptionProvider))]
    public class ServerListViewModel : BaseViewModel
    {
        private readonly RangeObservableCollection<ServerInfoViewModel> _listItems =
            new RangeObservableCollection<ServerInfoViewModel>();

        private ListCollectionView _listCollectionView;
        public ListCollectionView ListCollectionView
        {
            get
            {
                if (_listCollectionView == null)
                {
                    _listCollectionView = new ListCollectionView(_listItems);
                    _listCollectionView.CurrentChanged += ListCollectionViewCurrentChanged;
                    ReloadItems(true);
                }

                return _listCollectionView;
            }

            set
            {
                var changed = _listCollectionView != value;
                _listCollectionView = value;

                if (changed)
                {
                    OnPropertyChanged("ListCollectionView");
                }
            }
        }

        private ServerInfoViewModel _currentItem;
        public ServerInfoViewModel CurrentItem
        {
            get { return _currentItem; }

            set
            {
                var changed = _currentItem != value;

                _currentItem = value;

                if (changed)
                {
                    OnPropertyChanged("CurrentItem");
                }
            }
        }

        private readonly List<ServerInfo> _servers;

        public ServerListViewModel(List<ServerInfo> servers)
        {
            _servers = servers;
        }

        private void ReloadItems(bool isInitialLoad)
        {
            // Record the current item
            var currentItem = _listCollectionView.CurrentItem as ServerInfoViewModel;

            int? selectedIndex = null;

            if (isInitialLoad)
            {
                selectedIndex = 0;
            }
            else if (currentItem != null)
            {
                var index = Array.FindIndex(_servers.ToArray(), i => string.Equals(i.Id, currentItem.Server.Id));

                if (index != -1)
                {
                    selectedIndex = index;
                }
            }

            _listItems.Clear();

            _listItems.AddRange(_servers.Select(i => new ServerInfoViewModel() { Server = i }));

            if (selectedIndex.HasValue)
            {
                ListCollectionView.MoveCurrentToPosition(selectedIndex.Value);
            }
        }

        void ListCollectionViewCurrentChanged(object sender, EventArgs e)
        {
            CurrentItem = ListCollectionView.CurrentItem as ServerInfoViewModel;
        }

        public void Dispose()
        {
        }
    }
}


text:
/**
 * @file   Archive.hpp
 * @brief  Archive class prototype.
 * @author zer0
 * @date   2019-02-25
 */

#ifndef __INCLUDE_LIBTBAG__LIBTBAG_ARCHIVE_ARCHIVE_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_ARCHIVE_ARCHIVE_HPP__

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/Err.hpp>
#include <libtbag/filesystem/details/FsTypes.hpp>
#include <libtbag/filesystem/Path.hpp>
#include <libtbag/filesystem/File.hpp>
#include <libtbag/util/BufferInfo.hpp>
#include <libtbag/Unit.hpp>

#include <cstdint>
#include <string>
#include <vector>
#include <memory>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

namespace archive {

/** Compression type.  */
enum class CompressType
{
    CT_NONE,
    CT_GZIP,
    CT_BZIP2,
    CT_LZMA,
    CT_XZ
};

TBAG_CONSTEXPR char const * const COMPRESS_FORMAT_7ZIP = "7zip";
TBAG_CONSTEXPR char const * const COMPRESS_FORMAT_PAX  = "pax";
TBAG_CONSTEXPR char const * const COMPRESS_FORMAT_PAXR = "paxr";
TBAG_CONSTEXPR char const * const COMPRESS_FORMAT_ZIP  = "zip";

/**
 * ArchiveEntry class prototype.
 *
 * @author zer0
 * @date   2019-02-27
 */
struct ArchiveEntry
{
    using DirentType = libtbag::filesystem::details::DirentType;

    TBAG_CONSTEXPR static DirentType const TYPE_UNKNOWN = libtbag::filesystem::details::DIRENT_UNKNOWN;
    TBAG_CONSTEXPR static DirentType const TYPE_FILE    = libtbag::filesystem::details::DIRENT_FILE   ;
    TBAG_CONSTEXPR static DirentType const TYPE_DIR     = libtbag::filesystem::details::DIRENT_DIR    ;
    TBAG_CONSTEXPR static DirentType const TYPE_LINK    = libtbag::filesystem::details::DIRENT_LINK   ;
    TBAG_CONSTEXPR static DirentType const TYPE_FIFO    = libtbag::filesystem::details::DIRENT_FIFO   ;
    TBAG_CONSTEXPR static DirentType const TYPE_SOCKET  = libtbag::filesystem::details::DIRENT_SOCKET ;
    TBAG_CONSTEXPR static DirentType const TYPE_CHAR    = libtbag::filesystem::details::DIRENT_CHAR   ;
    TBAG_CONSTEXPR static DirentType const TYPE_BLOCK   = libtbag::filesystem::details::DIRENT_BLOCK  ;

    /** Entry file type. */
    DirentType type = TYPE_FILE;

    /** Original source file path. */
    std::string source_path;

    /** Path name. */
    std::string path_name;

    /** File size. */
    std::size_t size = 0;

    /** User ID of owner. */
    uint64_t uid = 0;

    /** Group ID of owner. */
    uint64_t gid = 0;

    /** File permission. */
    uint64_t permission = 0644;

    ArchiveEntry() { /* EMPTY. */ }
    virtual ~ArchiveEntry() { /* EMPTY. */ }
};

struct ArchiveMemoryEntry : public ArchiveEntry
{
    using Buffer = libtbag::util::Buffer;

    /** File content. */
    Buffer data;

    ArchiveMemoryEntry() { /* EMPTY. */ }
    virtual ~ArchiveMemoryEntry() { /* EMPTY. */ }
};

/**
 * BaseArchive class prototype.
 *
 * @author zer0
 * @date   2019-02-27
 */
class TBAG_API BaseArchive : private Noncopyable
{
public:
    using Entries = std::vector<ArchiveEntry>;
    using MemoryEntries = std::vector<ArchiveMemoryEntry>;
    using Buffer = libtbag::util::Buffer;

protected:
    void * _archive;
    bool _verbose;

public:
    BaseArchive(bool verbose = false);
    virtual ~BaseArchive();

public:
    inline bool exists() const TBAG_NOEXCEPT
    { return _archive != nullptr; }

public:
    static std::size_t getBlockSize() TBAG_NOEXCEPT;
    static Err getErrFromArchiveCode(int code) TBAG_NOEXCEPT;

public:
    char const * getErrorString() const TBAG_NOEXCEPT;

public:
    Err getErrAndPrintDefaultLog(char const * name, int code) const TBAG_NOEXCEPT;
    Err prefix(char const * name, int code) const TBAG_NOEXCEPT;
};

class TBAG_API ArchiveWriter : public BaseArchive
{
private:
    std::string _format;
    CompressType _compress;
    bool _open;

public:
    ArchiveWriter(std::string const & format = COMPRESS_FORMAT_PAXR,
                  CompressType compress = CompressType::CT_NONE);
    virtual ~ArchiveWriter();

public:
    Err openFile(std::string const & path);
    Err openMemory(char * buffer, std::size_t size, std::size_t * used);

public:
    Err close();

public:
    Err writeFromFile(std::string const & path);
    Err writeFromMemory(ArchiveEntry const & entry, char const * buffer, std::size_t buffer_size);
    Err writeFromMemory(ArchiveEntry const & entry, Buffer const & buffer);
    Err writeFromMemory(ArchiveMemoryEntry const & entry);
};

class TBAG_API ArchiveReader : public BaseArchive
{
private:
    bool _open;

public:
    ArchiveReader();
    virtual ~ArchiveReader();

public:
    Err openFile(std::string const & path);
    Err openFile(std::string const & path, std::size_t block_size);
    Err openMemory(char const * buffer, std::size_t size);

public:
    Err close();

public:
    std::size_t readToFile(std::string const & prefix);
    std::size_t readToMemory(MemoryEntries & entries);
    std::size_t readHeader(Entries & entries);
    std::size_t readName(std::vector<std::string> & names);
};

class TBAG_API FileArchiveWriter : public ArchiveWriter
{
public:
    FileArchiveWriter();
    FileArchiveWriter(std::string const & format, CompressType compress);
    FileArchiveWriter(std::string const & path);
    FileArchiveWriter(std::string const & path, std::string const & format, CompressType compress);
    virtual ~FileArchiveWriter();
};

class TBAG_API MemoryArchiveWriter : public ArchiveWriter
{
public:
    TBAG_CONSTEXPR static std::size_t const DEFAULT_CAPACITY = 10 * libtbag::MEGA_BYTE_TO_BYTE;

private:
    Buffer _archive_memory;
    std::size_t _used;

public:
    MemoryArchiveWriter(std::size_t capacity,
                        std::string const & format = COMPRESS_FORMAT_PAXR,
                        CompressType compress = CompressType::CT_NONE);
    MemoryArchiveWriter(std::string const & format,
                        CompressType compress = CompressType::CT_NONE);
    MemoryArchiveWriter(CompressType compress);
    MemoryArchiveWriter();
    virtual ~MemoryArchiveWriter();

public:
    inline char * data() TBAG_NOEXCEPT_SP_OP(_archive_memory.data())
    {
        return _archive_memory.data();
    }

    inline char const * data() const TBAG_NOEXCEPT_SP_OP(_archive_memory.data())
    {
        return _archive_memory.data();
    }

    inline std::size_t capacity() const TBAG_NOEXCEPT_SP_OP(_archive_memory.size())
    {
        return _archive_memory.size();
    }

    inline std::size_t used() const TBAG_NOEXCEPT
    {
        return _used;
    }
};

class TBAG_API FileArchiveReader : public ArchiveReader
{
public:
    FileArchiveReader(std::string const & path);
    FileArchiveReader(std::string const & path, std::size_t block_size);
    virtual ~FileArchiveReader();
};

class TBAG_API MemoryArchiveReader : public ArchiveReader
{
private:
    Buffer _archive_memory;

public:
    MemoryArchiveReader(char const * buffer, std::size_t buffer_size);
    MemoryArchiveReader(Buffer const & buffer);
    virtual ~MemoryArchiveReader();
};

// -----------------------
// Miscellaneous utilities
// -----------------------

TBAG_API std::size_t compressArchive(std::string const & output_filename,
                                     std::vector<std::string> const & input_filenames,
                                     std::string const & format,
                                     CompressType compress = CompressType::CT_NONE);
TBAG_API std::size_t compressArchive(std::string const & output_filename,
                                     BaseArchive::MemoryEntries & entries,
                                     std::string const & format,
                                     CompressType compress = CompressType::CT_NONE);

TBAG_API std::string getCompressFormatFromOutputFileName(std::string const & output_filename);

TBAG_API std::size_t compressArchive(std::string const & output_filename,
                                     std::vector<std::string> const & input_filenames,
                                     CompressType compress = CompressType::CT_NONE);
TBAG_API std::size_t compressArchive(std::string const & output_filename,
                                     BaseArchive::MemoryEntries & entries,
                                     CompressType compress = CompressType::CT_NONE);

TBAG_API std::size_t decompressArchive(std::string const & filename,
                                       std::string const & output_prefix);
TBAG_API std::size_t decompressArchive(std::string const & filename,
                                       BaseArchive::MemoryEntries & entries);
TBAG_API BaseArchive::MemoryEntries decompressArchive(std::string const & filename);

TBAG_API std::size_t decompressMemoryArchive(char const * buffer, std::size_t size,
                                             std::string const & output_prefix);
TBAG_API std::size_t decompressMemoryArchive(char const * buffer, std::size_t size,
                                             BaseArchive::MemoryEntries & entries);
TBAG_API BaseArchive::MemoryEntries decompressMemoryArchive(char const * buffer, std::size_t size);

TBAG_API std::vector<std::string> getArchiveFileList(std::string const & filename);

} // namespace archive

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

#endif // __INCLUDE_LIBTBAG__LIBTBAG_ARCHIVE_ARCHIVE_HPP__


text:
package tamaized.voidcraft.common.events.client;

import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import tamaized.voidcraft.VoidCraft;

public class TextureStitch {

	public static TextureAtlasSprite colorFire_layer_0;
	public static TextureAtlasSprite colorFire_layer_1;

	public static TextureAtlasSprite guiSlot_Tool;
	public static TextureAtlasSprite guiSlot_Block;
	public static TextureAtlasSprite guiSlot_Dragonscale;
	public static TextureAtlasSprite guiSlot_QuoriFragment;
	public static TextureAtlasSprite guiSlot_AstralEsssence;
	public static TextureAtlasSprite guiSlot_VoidicPhlog;

	@SubscribeEvent
	public void stitchTexture(TextureStitchEvent.Pre e) {
		colorFire_layer_0 = e.getMap().registerSprite(new ResourceLocation(VoidCraft.modid, "layer/fire_layer_0"));
		colorFire_layer_1 = e.getMap().registerSprite(new ResourceLocation(VoidCraft.modid, "layer/fire_layer_1"));

		guiSlot_Tool = e.getMap().registerSprite(new ResourceLocation(VoidCraft.modid, "gui/icons/tool"));
		guiSlot_Block = e.getMap().registerSprite(new ResourceLocation(VoidCraft.modid, "gui/icons/block"));
		guiSlot_Dragonscale = e.getMap().registerSprite(new ResourceLocation(VoidCraft.modid, "gui/icons/dragonscale"));
		guiSlot_QuoriFragment = e.getMap().registerSprite(new ResourceLocation(VoidCraft.modid, "gui/icons/quorifragment"));
		guiSlot_AstralEsssence = e.getMap().registerSprite(new ResourceLocation(VoidCraft.modid, "gui/icons/astralessence"));
		guiSlot_VoidicPhlog = e.getMap().registerSprite(new ResourceLocation(VoidCraft.modid, "gui/icons/voidicphlog"));
	}

}


text:
package io.gatling.http.client.util;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

class Utf8UrlEncoderTest {

  private static String encodeQueryElement(String input) {
    StringBuilder sb = new StringBuilder(input.length() + 6);
    Utf8UrlEncoder.encodeAndAppendQueryElement(sb, input);
    return sb.toString();
  }

  @Test
  void testEncodeQueryElement() {
    assertEquals("foobar", encodeQueryElement("foobar"));
    // application/x-www-form-urlencoded leaves *, -, . and _ as is
    assertEquals("*-._", encodeQueryElement("*-._"));
    // space should be encoded as +
    assertEquals("+", encodeQueryElement(" "));
    // other chars should be encoded
    assertEquals("%7E%26%2B", encodeQueryElement("~&+"));
  }

  @Test
  void testPercentEncodeQueryElement() {
    assertEquals("foobar", Utf8UrlEncoder.percentEncodeQueryElement("foobar"));
    assertEquals("%2A%26%2B~_", Utf8UrlEncoder.percentEncodeQueryElement("*&+~_"));
  }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>Backbone.js - Recipes</title>

	<link rel="stylesheet" type="text/css" href="../../css/normalize.css">
	<link rel="stylesheet" type="text/css" href="../../css/skeleton.css">

	<link rel="stylesheet" type="text/css" href="../../css/edit.css">

Admin

		<input type="submit" class="btn-login" value="login"/>

Add post

Edit post

Remove post


text:
require 'odibot'

class ResponseSet < ActiveRecord::Base
  include Surveyor::Models::ResponseSetMethods
  include AASM
  include Ownership

  # Surveyor field types
  VALUE_FIELDS = [:datetime_value, :integer_value, :float_value, :unit, :text_value, :string_value]

  # Default title for a response set / dataset
  DEFAULT_TITLE = 'Untitled'

  REF_CHANGES = {
                  "ogl_uk" => "OGL-UK-2.0",
                  "cc_zero" => "CC0-1.0",
                  "odc_odbl" => "ODbL-1.0",
                  "cc_by" => "CC-BY-4.0",
                  "cc_by_sa" => "CC-BY-SA-4.0",
                  "odc_by" => "ODC-BY-1.0",
                  "odc_pddl" => "ODC-PDDL-1.0"
                }

  after_save :update_certificate
  before_save :update_dataset
  before_save :add_missing_responses, :if => :autogenerated?

  attr_accessible :dataset_id
  attr_accessor :documentation_url

  belongs_to :dataset, touch: true
  belongs_to :survey

  has_many :questions, through: :responses
  has_many :answers, through: :responses

  # One to one relationship with certificate
  has_one :certificate, dependent: :destroy

  # One to one relationship with kitten data object
  has_one :kitten_data, dependent: :destroy, order: "created_at DESC"
  has_one :certificate_generator

  scope :published, where(:aasm_state => 'published')

  # Checks if a value is blank by Surveyor's standards
  def self.is_blank_value?(value)
    value.is_a?(Array) ? value.all?{|values| values.blank? } : value.to_s.blank?
  end

  # Checks if a surveyor hash for a quesiton is considered blank (unanswered)
  # Overloads Surveyor's method to ensure only surveyor values are considered
  def self.has_blank_value?(hash)

    # It's definitely blank if there's no answer id
    return true if is_blank_value?(hash["answer_id"])

    # Otherwise it isn't blank if the question is a radio question
    return false if (q = Question.find_by_id(hash["question_id"])) and q.pick == "one"

    # Otherwise check surveyor values are blank
    hash.slice(*VALUE_FIELDS).any?{|k,v| is_blank_value?(v) }
  end

  # Gets data for status page
  def self.counts
    within_last_month = (Time.now - 1.month)..Time.now
    {
      :all                           => self.count,
      :all_datasets                  => self.select("DISTINCT(dataset_id)").count,
      :all_datasets_this_month       => self.select("DISTINCT(dataset_id)").where(created_at: within_last_month).count,
      :published_datasets            => self.published.select("DISTINCT(dataset_id)").count,
      :published_datasets_this_month => self.published.select("DISTINCT(dataset_id)").where(created_at: within_last_month).count
    }
  end

  def self.clone_response_set(source, attrs = {})
    attrs = {"survey_id" => source.survey_id}.merge(attrs)
    new_response_set = ResponseSet.create attrs
    new_response_set.kitten_data = source.kitten_data.dup if source.kitten_data.present?
    new_response_set.copy_answers_from_response_set!(source)
    new_response_set
  end

  def self.latest
    order(arel_table[:created_at].desc).first
  end

  # Simple state machine describing response set states
  aasm do
    state :draft, :initial => true

    state :published,
      :before_enter => :publish_certificate,
      :after_enter => [:archive_other_response_sets, :store_attained_index]

    state :archived

    state :superceded

    event :publish do
      transitions from: :draft, to: :published, guard: :all_mandatory_questions_complete?
    end

    event :archive do
      transitions from: :published, to: :archived
    end

    event :supercede do
      transitions from: [:draft, :published], to: :superceded
    end
  end

  def publish_certificate
    certificate.publish!
  end

  def archive_other_response_sets
    related = dataset.try(:response_sets) || []

    related.each do |response_set|
      if response_set.id != self.id
        response_set.archive! if response_set.published?
      end
    end

  end

  # Store the attained level so that it's queryable
  # Only stored once the certificate has been published
  def store_attained_index
    index = minimum_outstanding_requirement_level-1
    update_attribute(:attained_index, index)
  end

  scope :by_newest, order("response_sets.created_at DESC")
  scope :completed, where("response_sets.completed_at IS NOT NULL")
  scope :modified_since, ->(date) { where(arel_table[:updated_at].gteq(date)) }

  def title
    dataset_title_determined_from_responses || DEFAULT_TITLE
  end

  def response(identifier)
    responses.select{|r| r.question.reference_identifier == identifier.to_s }.first
  end

  def documentation_url
    response 'documentationUrl'
  end

  def documentation_url_question
    survey.question 'documentationUrl'
  end

  def documentation_url_explanation
    response_for(documentation_url_question.id).explanation
  end

  def documentation_url_explanation=(val)
    response = response_for(documentation_url_question.id)
    response.explanation = val.presence
    response.save
  end

  # This picks up the jurisdiction (survey title) from the survey, or the migrated survey
  def jurisdiction
    if Survey::MIGRATIONS.has_key? survey.access_code
      target_access_code = Survey::MIGRATIONS[survey.access_code]
      Survey.where(access_code: target_access_code).first.try(:title)
    else
      survey.title
    end
  end

  def translation
    survey.translations.where(locale: locale || I18n.locale).first
  end

  def locale_name
    translation.try(:locale_name) || survey.default_locale_name || locale
  end

  def modifications_allowed?
    draft?
  end

  # Finds which dependencies are active for this response set as a whole
  def depends
    return @depends if @depends

    deps = survey.dependencies.includes({:dependency_conditions => {:question => :answers}})

    resps = self.responses.includes(:answer)

    # gather if the dependencies are met in a hash
    @depends = deps.all.reduce({}) do |mem, v|
      mem[v.id] = v.is_met? self, resps
      mem
    end
  end

  # Allows response values to be accessed using the suffix '_determined_from_responses'
  def method_missing(method_name, *args, &blk)
    match = method_name.to_s.match(/^(.+)_determined_from_responses$/)
    identifier = match && match[1].to_sym

    # Checks to see if the response identifier is valid
    if Survey::RESPONSE_MAP[identifier]
      # Tries to get an existing instance variable  before loading the value from the database
      var = instance_variable_get("@#{method_name}") || value_for(identifier)
    else
      # Otherwise defaults to Surveyor's method_missing
      super
    end
  end

  # Custom getter which chooses an appropriate data licence
  def data_licence_determined_from_responses
    @data_licence_determined_from_responses ||= licence_from_ref(:data_licence)
  end

  # Custom getter which chooses an appropriate content licence
  def content_licence_determined_from_responses
    @content_licence_determined_from_responses ||= licence_from_ref(:content_licence)
  end

  def licence_from_ref(licence_type)
    ref = value_for(licence_type, :reference_identifier)
    case ref
    when nil, "na"
      {
        :title => "Not Applicable",
        :url => nil
      }
    when "other"
      case licence_type
      when :data_licence
        {
          :title => value_for(:other_dataset_licence_name),
          :url   => value_for(:other_dataset_licence_url)
        }
      when :content_licence
        {
          :title => value_for(:other_content_licence_name),
          :url   => value_for(:other_content_licence_url)
        }
      end
    else
      {
        title: value_for(licence_type),
        url: nil
      }
    end
  end

  def licences
    {
      data:     begin data_licence_determined_from_responses    rescue nil end,
      content:  begin content_licence_determined_from_responses rescue nil end
    }
  end

  def incomplete?
    !complete?
  end

  def incomplete_triggered_mandatory_questions
    responded_to_question_ids = responses.filled.pluck('question_id')
    triggered_mandatory_questions.reject { |q| responded_to_question_ids.include? q.id }
  end

  def triggered_mandatory_questions

    @triggered_mandatory_questions ||= survey.mandatory_questions.select do |r|
      r.dependency.nil? ?
        true : depends[r.dependency.id]
    end
  end

  def triggered_requirements
    @triggered_requirements ||= survey.requirements.select do |r|
      r.dependency.nil? ?
        true :
        depends[r.dependency.id]
    end
  end

  def outstanding_reference_identifiers
    triggered_requirements.map(&:reference_identifier)
  end

  def entered_reference_identifiers
    answers.includes(:question).map(&:requirement).map do |ref|
      ref.try(:scan, /\S+_\d+/)
    end.flatten.compact
  end

  def levels_count(reference_identifiers)
    # split level name off before _, count by occurance
    Hash[reference_identifiers.group_by { |r| r.split('_')[0] }.map { |k, v| [k, v.size] }]
  end

  def progress
    pending = incomplete_triggered_mandatory_questions.count
    complete = questions.mandatory.count
    outstanding = levels_count(outstanding_reference_identifiers)
    entered = levels_count(entered_reference_identifiers)

    result = {
      attained: attained_level
    }
    %w[basic pilot standard exemplar].each do |level|
      pending += outstanding[level] || 0
      complete += entered[level] || 0
      total = pending+complete
      if total > 0
        result[level] = (100.0*complete/total).to_i
      else
        result[level] = 0
      end
    end
    result
  end

  def responses_with_url_type
    responses.joins(:answer).merge(Answer.urls).readonly(false)
  end

  def all_urls_resolve?
    responses_with_url_type.all?(&:url_valid_or_explained?)
  end

  def uncompleted_mandatory_questions_count
    mandatory_question_ids = triggered_mandatory_questions.map(&:id)
    responded_to_question_ids = responses.select(&:filled?).map(&:question_id)
    (mandatory_question_ids - responded_to_question_ids).count
  end

  def all_mandatory_questions_complete?
    uncompleted_mandatory_questions_count == 0
  end

  def attained_level
    @attained_level ||= Survey::REQUIREMENT_LEVELS[minimum_outstanding_requirement_level-1]
  end

  def minimum_outstanding_requirement_level
    return 1 unless all_mandatory_questions_complete? # if there are any mandatory questions outstanding, they achieve no level
    @minimum_outstanding_requirement_level ||= (outstanding_requirements.map(&:requirement_level_index) << Survey::REQUIREMENT_LEVELS.size).min
  end

  def completed_requirements
    @completed_requirements ||= triggered_requirements.select { |r| r.requirement_met_by_responses?(self.responses) }
  end

  def outstanding_requirements
    @outstanding_requirements ||= triggered_requirements.select { |r| !r.requirement_met_by_responses?(self.responses) }
  end

  def responses_for_questions(questions)
    responses.includes(:question)
             .where(:question_id => questions)
             .order('questions.display_order ASC')
  end

  def update_certificate
    create_certificate if certificate.nil?

    certificate.update_from_response_set
  end

  def update_dataset
    create_dataset if dataset.nil?
  end

  def copy_answers_from_response_set!(source_response_set)
    ui_hash = HashWithIndifferentAccess.new

    raise "Attempt to over-write existing responses." if responses.any? # TODO: replace with specific exception

    source_response_set.responses.each do |previous_response|
      if question = survey.questions.where(reference_identifier: previous_response.question.reference_identifier).first
        if answer = question.answers.where(reference_identifier: previous_response.answer.reference_identifier).first
          api_id = Surveyor::Common.generate_api_id
          ui_hash[api_id] = { question_id: question.id.to_s,
                              api_id: api_id,
                              answer_id: answer.id.to_s }.merge(previous_response.ui_hash_values)
        end
      end
    end
    original_update_from_ui_hash(ui_hash)
  end

  # run updates through the response_cache_map, so that we can deal
  # with fields that have been claimed by a different response_set
  #
  # (allows us to cache the question html)
  #
  alias :original_update_from_ui_hash :update_from_ui_hash
  def update_from_ui_hash(ui_hash)

    # the api_ids in the ui_hash
    api_ids = ui_hash.map do |_ord, response_hash|
      response_hash["api_id"]
    end

    # find responses that have been claimed by another response_sets
    Response.where(api_id: api_ids).where('response_set_id != ?', id).each do |response|

      # use a mapping to this response_sets api_id instead
      rcm = ResponseCacheMap.find_or_create_by_origin_id_and_response_set_id(response.id, self.id)

      logger.info "cache map replacing api_id - #{response.api_id} with #{rcm.api_id}"

      # replace the one in the ui hash
      ui_hash.each do |_ord, response_hash|
        if response_hash["api_id"] == response.api_id
          response_hash["api_id"] = rcm.api_id
        end
      end
    end

    # pass through to the original method
    original_update_from_ui_hash(ui_hash)
  end

  # Updates responses without using a surveyor form
  def update_responses(responses)

    ui_hash = []

    responses.each do |key, value|
      question = survey.question(key)
      response = response(key)

      next if value.nil? || question.nil?

      if question.type == :none || question.type == :repeater
        answer = question.answers.first
        ui_hash.push(HashWithIndifferentAccess.new(
          question_id: question.id.to_s,
          api_id: response ? response.api_id : Surveyor::Common.generate_api_id,
          answer_id: answer.id.to_s,
          answer.value_key => value.to_s,
          autocompleted: true
        ))
      end

      if question.type == :one
        ui_hash.push(HashWithIndifferentAccess.new(
          question_id: question.id.to_s,
          api_id: response ? response.api_id : Surveyor::Common.generate_api_id,
          answer_id: question.answer(value).id.to_s,
          autocompleted: true
        ))
      end

      if question.type == :any
        value.each do |item|
          ui_hash.push(HashWithIndifferentAccess.new(
            question_id: question.id.to_s,
            api_id: response ? response.api_id : Surveyor::Common.generate_api_id,
            answer_id: question.answer(item).id.to_s,
            autocompleted: true
          ))
        end
      end
    end

    update_from_ui_hash(Hash[ui_hash.map.with_index { |value, i| [i.to_s, value] }])
  end

  def response_errors
    errors = Hash.new { |h, k| h[k] = [] }
    incomplete_triggered_mandatory_questions.each do |question|
      response = responses.where(question_id: question.id).first

      if !response || response.empty?
        errors[question.reference_identifier] << 'mandatory'
      end
    end
    responses_with_url_type.each do |response|
      unless response.url_valid_or_explained?
        errors[response.question.reference_identifier] << 'invalid-url'
      end
    end
    errors
  end

  def assign_to_user!(user)
    self.user = user
    self.dataset = user.datasets.create if !self.dataset
    self.dataset.update_attribute(:user, user)
    save
  end

  def newest_in_dataset?
    # TODO: this method would need to be extended to handle "newest for survey" - for phase 2...
    @newest_in_dataset_q ||= (dataset.try(:newest_response_set) == self)
  end

  def newest_completed_in_dataset?
    # TODO: this method would need to be extended to handle "newest for survey" - for phase 2...
    @newest_in_dataset_q ||= (dataset.try(:newest_completed_response_set) == self)
  end

  def response_for(question_id)
    responses.where(question_id: question_id).first || responses.where(question_id: question_id).build
  end

  def autocomplete(url)
    update_responses({documentationUrl: url})
    responses.update_all(autocompleted: false)
    update_attribute('kitten_data', nil)

    code = resolve_url(url)

    if code == 200
      create_kitten_data(url: url)
      update_responses(kitten_data.fields)
    end
  end

  def has_kitten_data?
    kitten_data && kitten_data.has_data?
  end

  def description
    kitten_data.get(:description) if has_kitten_data?
  end

  def resolve_url(url)
    if url =~ /^#{URI::regexp}$/
      ODIBot.new(url).response_code rescue nil
    end
  end

  # finds the string value for a given response_identifier
  private
  def value_for(reference_identifier, value = :to_s)
    relation = responses.joins(:question).eager_load(:answer, :question)
    relation.where(questions: {reference_identifier: survey.meta_map[reference_identifier]}).first.try(value)
  end

  def add_missing_responses
    self.missing_responses = incomplete_triggered_mandatory_questions.map { |q| q.text }.join(",")
  end

  def autogenerated?
    #FIXME: certificate_generator.present? was not working, can't figure out why
    CertificateGenerator.exists?(response_set_id: id)
  end

end


text:
bbots
====

dependencies:
    pexpect
    curl
    dos2unix
    telnet


text:
package org.apache.hive.service.servlet;

import org.apache.hadoop.hive.ql.QueryInfo;
import org.apache.hive.service.cli.operation.OperationManager;
import org.apache.hive.service.cli.session.HiveSession;
import org.apache.hive.service.cli.session.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * QueriesRESTfulAPIServlet.
 *
 */
public class QueriesRESTfulAPIServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private static final Logger LOG = LoggerFactory.getLogger(QueriesRESTfulAPIServlet.class);

  private static final String API_V1 = "v1";
  private static final String REQ_QUERIES = "queries";
  private static final String REQ_SESSIONS = "sessions";
  private static final String REQ_ACTIVE = "active";
  private static final String REQ_HISTORICAL = "historical";

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
        /*
            Available endpoints are:
             - /v1/queries/active
             - /v1/queries/historical
             - /v1/sessions
        */

    String pathInfo = request.getPathInfo();
    if (pathInfo == null || "/".equals(pathInfo)) {
      sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Path to the endpoint is missing");
      return;
    }

    String[] splits = pathInfo.split("/");
    if (splits.length < 3) { //expecting at least 2 parts in the path
      sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Expecting at least 2 parts in the path");
      return;
    }

    ServletContext ctx = getServletContext();
    SessionManager sessionManager =
        (SessionManager) ctx.getAttribute("hive.sm");
    OperationManager operationManager = sessionManager.getOperationManager();

    String apiVersion = splits[1];
    if (apiVersion.equals(API_V1)) {
      String reqType = splits[2];
      if (reqType.equals(REQ_QUERIES)) {
        if (splits.length != 4) {
          sendError(response, HttpServletResponse.SC_NOT_FOUND,
              "Expecting 3 parts in the path: /v1/queries/active or /v1/queries/historical");
          return;
        }
        String queriesType = splits[3];
        if (queriesType.equals(REQ_ACTIVE)) {
          Collection<QueryInfo> operations = operationManager.getLiveQueryInfos();
          LOG.info("Returning active SQL operations via the RESTful API");
          sendAsJson(response, operations);
        } else if (queriesType.equals(REQ_HISTORICAL)) {
          Collection<QueryInfo> operations = operationManager.getHistoricalQueryInfos();
          LOG.info("Returning historical SQL operations via the RESTful API");
          sendAsJson(response, operations);
        } else {
          sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Unknown query type: " + queriesType);
          return;
        }
      } else if (reqType.equals(REQ_SESSIONS)) {
        Collection<HiveSession> hiveSessions = sessionManager.getSessions();
        LOG.info("Returning active sessions via the RESTful API");
        sendAsJson(response, hiveSessions);
      } else { // unrecognized request
        sendError(response, HttpServletResponse.SC_NOT_FOUND, "Unknown request type: " + reqType);
        return;
      }
    } else { // unrecognized API version
      sendError(response, HttpServletResponse.SC_BAD_REQUEST, "This server only handles API v1");
      return;
    }
  }

  private void sendError(HttpServletResponse response,
                         Integer errorCode,
                         String message) {
    response.setStatus(errorCode);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    try {
      response.getWriter().write("{\"message\" : " + message + "}");
    } catch (IOException e) {
      LOG.error("Caught an exception while writing an HTTP error status", e);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }

  private void sendAsJson(
      HttpServletResponse response,
      Object obj) {
    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_OK);
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("CustomSessionModule", new Version(1, 0, 0, null, null, null));
    module.addSerializer(HiveSession.class, new HiveSessionSerializer());
    mapper.registerModule(module);

    try {
      PrintWriter out = response.getWriter();
      String objectAsJson = mapper.writeValueAsString(obj);
      out.print(objectAsJson);
      out.flush();
      out.close();
    } catch (IOException e) {
      LOG.error("Caught an exception while writing an HTTP response", e);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }

  private static class HiveSessionSerializer extends JsonSerializer<HiveSession> {
    @Override
    public void serialize(
        HiveSession hiveSession,
        JsonGenerator jgen,
        SerializerProvider serializerProvider)
        throws IOException, JsonProcessingException {
      long currentTime = System.currentTimeMillis();

      jgen.writeStartObject();
      jgen.writeStringField("sessionId", hiveSession.getSessionHandle().getSessionId().toString());
      jgen.writeStringField("username", hiveSession.getUserName());
      jgen.writeStringField("ipAddress", hiveSession.getIpAddress());
      jgen.writeNumberField("operationCount", hiveSession.getOpenOperationCount());
      jgen.writeNumberField("activeTime", (currentTime - hiveSession.getCreationTime()) / 1000);
      jgen.writeNumberField("idleTime", (currentTime - hiveSession.getLastAccessTime()) / 1000);
      jgen.writeEndObject();
    }
  }
}


text:
import request from 'supertest';
import faker from 'faker';
import app from '../../../app';

const agent = request.agent(app);

describe('Menu Details API', async () => {
  let token;
  beforeAll(async () => {
    const loginData = {
      email: 'admin@boldr.io',
      password: 'password',
    };
    const { body } = await agent
      .post('/api/v1/auth/login')
      .set('Accept', 'application/json')
      .send(loginData);
    token = body.token;
  });

  it('+++ GET /menu-details -- It should return menu details', () => {
    return agent
      .get('/api/v1/menu-details')
      .set('Accept', 'application/json')
      .expect(res => {
        expect(res.status).toBe(200);
        expect(typeof res.body).toBe('object');
      });
  });

  it('+++ POST /menu-details -- Should require authorization', () => {
    return agent
      .post('/api/v1/menu-details')
      .set('Accept', 'application/json')
      .send({ name: 'test' })
      .expect(res => {
        expect(res.status).toBe(401);
      });
  });
  it('+++ POST /menu-details -- should create a new detail', () => {
    return agent
      .post('/api/v1/menu-details')
      .set('Accept', 'application/json')
      .set('Authorization', `Bearer ${token}`)
      .send({
        name: faker.random.word(),
        href: 'test',
        order: 4,
        icon: 'question',
        hasDropdown: 'false',
      })
      .expect(res => {
        expect(res.status).toBe(201);
      });
  });
  it('GET /menu-details/:id -- By its id', () => {
    return agent
      .get('/api/v1/menu-details/1')
      .set('Accept', 'application/json')
      .expect(res => {
        expect(res.status).toBe(200);
        expect(typeof res.body).toBe('object');
      });
  });

  it('PUT /menu-details/:id -- Should fail without authorization', () => {
    return agent
      .put('/api/v1/menu-details/1')
      .send({ name: 'test' })
      .expect(res => {
        expect(res.status).toBe(401);
      });
  });
  it('+++ PUT /menu-details/:id -- Should update', () => {
    return agent
      .put('/api/v1/menu-details/1')
      .set('Authorization', `Bearer ${token}`)
      .send({
        href: 'test',
        order: 4,
        icon: 'question',
      })
      .expect(res => {
        expect(res.status).toBe(202);
      });
  });
  it('+++ DELETE /menu-details/:id -- Should delete a detail', () => {
    return agent
      .del('/api/v1/menu-details/2')
      .set('Accept', 'application/json')
      .expect(res => {
        // .set('Authorization', `Bearer ${token}`)
        expect(res.status).toBe(401);
      });
  });
});


text:
/**
 *
 */
package com.manning.sdmia.ch04;

import java.util.Arrays;
import java.util.Collection;
import java.util.jar.Manifest;

import junit.framework.Assert;

import org.osgi.framework.ServiceReference;
import org.springframework.context.ApplicationContext;

/**
 * Checks context files are taken with a recursive directory wildcard pattern.
 * @author acogoluegnes
 */
public class LoadingFromRecursiveWildcardTest extends AbstractTest {

	public void testLoadBundle() throws Exception {
		ServiceReference [] refs = bundleContext.getAllServiceReferences(ApplicationContext.class.getName(), null);
		// expected bean names in the context
		Collection<String> expectedNames = Arrays.asList("daoDummy","serviceDummy","boDummy","foDummy");
		boolean found = false;
		for(ServiceReference ref: refs) {
			ApplicationContext context = (ApplicationContext) bundleContext.getService(ref);
			String [] names = context.getBeanDefinitionNames();
			if(names.length == expectedNames.size()) {
				if(Arrays.asList(names).containsAll(expectedNames)) {
					found = true;
				}
			}
		}
		Assert.assertTrue("Could not find all the expected bean in the context", found);
	}

	/*
	 * (non-Javadoc)
	 * @see org.springframework.osgi.test.AbstractOnTheFlyBundleCreatorTests#getManifest()
	 */
	protected Manifest getManifest() {
		// let the testing framework create/load the manifest
		Manifest mf = super.getManifest();
		mf.getMainAttributes().putValue("Spring-Context",
				"/com/manning/sdmia/ch04/wildcard/**/*.xml");
		return mf;
	}

}


text: Official website for GDG DevFest Baguio


text:
<Context path="@contextPath@" docBase="@docBase@"
	debug="5" reloadable="true" crossContext="false">
    <Environment name="deploymentEnvironment" type="java.lang.String" value="@config.name@"/>
</Context>


text:
import * as React from 'react';
import { Page } from '../../components';

export class NotFoundPage extends React.Component {
    render() {
        return (
            <Page name="not-found">
                404
            </Page>
        );
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/labProject.iml" filepath="$PROJECT_DIR$/.idea/labProject.iml" />
    </modules>
  </component>
</project>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Maxillaria mombachoensis A.H.Heller ex J.T.Atwood

### Remarks
null