<commit_before>define("ace/mode/beancount_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var BeancountHighlightRules = function() {

    this.$rules = {
        start: [{
            token: "comment.line.beancount",
            regex: /;.*/,
            comment: "Commented text"
        }, {
            token: "comment.line.shebang",
            regex: /^#!.*/,
            comment: "Shebangs"
        }, {
            token: "string.quoted.double.beancount",
            regex: /\".*\"/,
            comment: "strings"
        }, {
            token: [
                "text",
                "constant.language.beancount",
                "punctuation.separator.beancount"
            ],
            regex: /(\s)([A-Z][A-Za-z0-9\-]+)(:)/,
            comment: "Root Accounts"
        }, {
                token: [
                    "punctuation.separator.beancount",
                    "variable.account.beancount"
                ],
                regex: /([:]?)([A-Z][A-Za-z0-9\-]+)/,
            comment: "Accounts"
        }, {
            token: [
                "text",
                "constant.language.beancount",
                "punctuation.separator.beancount"
            ],
            regex: /(\s)([a-z][A-Za-z0-9\-\_]+)(:)/,
            comment: "Metadata"
        }, {
            token: [
                "support.function.directive.option.beancount",
                "meta.directive.option.beancount",
                "support.variable.language.option.beancount",
                "meta.directive.option.beancount",
                "support.class.option.beancount",
                "meta.directive.option.beancount"
            ],
            regex: /^(option)(\s*)(\".*\")(\s*)(\".*\")(\s*)/,
            comment: "Option directives"
        }, {
            token: "keyword.operator.directive.beancount",
            regex: /^(?:poptag|pushtag)\s/,
            comment: "Directives (no date)"
        }, {
            token: "variable.other.currency.beancount",
            regex: /\s[A-Z][A-Z0-9\'\.\_\-]{0,10}[A-Z0-9][\,?|\s]/,
            comment: "Currencies"
        }, {
            token: [
                "constant.numeric.date.year.beancount",
                "text",
                "constant.numeric.date.month.beancount",
                "text",
                "constant.numeric.date.day.beancount",
                "text",
                "support.function.directive.beancount"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})(\s)(open|close|pad|balance|note|price|event|document|commodity)/,
            comment: "Dated directives"
        }, {
            token: [
                "constant.numeric.date.year.beancount",
                "text",
                "constant.numeric.date.month.beancount",
                "text",
                "constant.numeric.date.day.beancount",
                "support.function.directive.beancount",
                "text"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})((?:\stxn)?)(\s)/,
            comment: "Transactions"
        }, {
            token: "keyword.other.beancount",
            regex: /\!\s/,
            comment: "flag"
        }, {
            token: "keyword.operator.assignment.beancount",
            regex: /\@/,
            comment: "Price assignment"
        }, {
            token: "keyword.operator.assignment.beancount",
            regex: /\{/,
            comment: "cost assignment"
        }, {
            token: ["text", "string.unquoted.tag.beancount"],
            regex: /(#)([A-Za-z0-9\-_\/.]+)/,
            comment: "Tags and links"
        }, {
            token: ["text", "string.unquoted.link.beancount"],
            regex: /(\^)([A-Za-z0-9\-_\/.]+)/,
            comment: "Links"
        }, {
            token: [
                "keyword.operator.modifier.beancount",
                "constant.numeric.currency.beancount"
            ],
            regex: /([\-|\+]?)([\d]+[\.]?[\d]*)/,
            comment: "numbers"
        }, {
            token: "invalid.illegal.unrecognized.beancount",
            regex: /[^\s}]/,
            comment: "Illegal"
        }],
        "#account-names": [{
            token: "text",
            regex: /[A-Z][A-Za-z0-9\-]+/
        }],
        "#dates": [{
            token: [
                "constant.numeric.date.year.beancount",
                "punctuation.separator.beancount",
                "constant.numeric.date.month.beancount",
                "punctuation.separator.beancount",
                "constant.numeric.date.day.beancount"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})/
        }],
        "#numbers": [{
            token: [
                "keyword.operator.modifier.beancount",
                "constant.numeric.currency.beancount"
            ],
            regex: /([\-|\+]?)([\d]+[\.]?[\d]*)/
        }, {
            token: "comment.line.beancount",
            regex: /\*.*/,
            comment: "Commented text"
        }]
    }

    this.normalizeRules();
};

BeancountHighlightRules.metaData = {
    fileTypes: ["beancount"],
    name: "Beancount",
    scopeName: "source.beancount"
}

oop.inherits(BeancountHighlightRules, TextHighlightRules);

exports.BeancountHighlightRules = BeancountHighlightRules;
});

define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function(commentRegex) {
    if (commentRegex) {
        this.foldingStartMarker = new RegExp(
            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
        );
        this.foldingStopMarker = new RegExp(
            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
        );
    }
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
    this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
    this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
    this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
    this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
    this._getFoldWidgetBase = this.getFoldWidget;
    this.getFoldWidget = function(session, foldStyle, row) {
        var line = session.getLine(row);

        if (this.singleLineBlockCommentRe.test(line)) {
            if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
                return "";
        }

        var fw = this._getFoldWidgetBase(session, foldStyle, row);

        if (!fw && this.startRegionRe.test(line))
            return "start"; // lineCommentRegionStart

        return fw;
    };

    this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
        var line = session.getLine(row);

        if (this.startRegionRe.test(line))
            return this.getCommentRegionBlock(session, line, row);

        var match = line.match(this.foldingStartMarker);
        if (match) {
            var i = match.index;

            if (match[1])
                return this.openingBracketBlock(session, match[1], row, i);

            var range = session.getCommentFoldRange(row, i + match[0].length, 1);

            if (range && !range.isMultiLine()) {
                if (forceMultiline) {
                    range = this.getSectionRange(session, row);
                } else if (foldStyle != "all")
                    range = null;
            }

            return range;
        }

        if (foldStyle === "markbegin")
            return;

        var match = line.match(this.foldingStopMarker);
        if (match) {
            var i = match.index + match[0].length;

            if (match[1])
                return this.closingBracketBlock(session, match[1], row, i);

            return session.getCommentFoldRange(row, i, -1);
        }
    };

    this.getSectionRange = function(session, row) {
        var line = session.getLine(row);
        var startIndent = line.search(/\S/);
        var startRow = row;
        var startColumn = line.length;
        row = row + 1;
        var endRow = row;
        var maxRow = session.getLength();
        while (++row < maxRow) {
            line = session.getLine(row);
            var indent = line.search(/\S/);
            if (indent === -1)
                continue;
            if  (startIndent > indent)
                break;
            var subRange = this.getFoldWidgetRange(session, "all", row);

            if (subRange) {
                if (subRange.start.row <= startRow) {
                    break;
                } else if (subRange.isMultiLine()) {
                    row = subRange.end.row;
                } else if (startIndent == indent) {
                    break;
                }
            }
            endRow = row;
        }

        return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
    };
    this.getCommentRegionBlock = function(session, line, row) {
        var startColumn = line.search(/\s*$/);
        var maxRow = session.getLength();
        var startRow = row;

        var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
        var depth = 1;
        while (++row < maxRow) {
            line = session.getLine(row);
            var m = re.exec(line);
            if (!m) continue;
            if (m[1]) depth--;
            else depth++;

            if (!depth) break;
        }

        var endRow = row;
        if (endRow > startRow) {
            return new Range(startRow, startColumn, endRow, line.length);
        }
    };

}).call(FoldMode.prototype);

});

define("ace/mode/beancount",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/beancount_highlight_rules","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var BeancountHighlightRules = require("./beancount_highlight_rules").BeancountHighlightRules;
var FoldMode = require("./folding/cstyle").FoldMode;

var Mode = function() {
    this.HighlightRules = BeancountHighlightRules;
    this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);

(function() {
    this.$id = "ace/mode/beancount"
}).call(Mode.prototype);

exports.Mode = Mode;
});
<commit_msg>Syntax highlighting for `Queries`<commit_after>define("ace/mode/beancount_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var SqlHighlightRules = require("ace/mode/sql_highlight_rules").SqlHighlightRules;

var BeancountHighlightRules = function() {

    this.$rules = {
        start: [{
            token: "comment.line.beancount",
            regex: /;.*/,
            comment: "Commented text"
        }, {
            token: "comment.line.shebang",
            regex: /^#!.*/,
            comment: "Shebangs"
        }, {
            token: "string.quoted.triple.beancount",
            regex: /"""/,
            comment: "Multi-line strings (embedded SQL)",
            next: "sql-start"
        }, {
            token: "string.quoted.double.beancount",
            regex: /"[^"]*"/,
            comment: "strings"
        }, {
            token: [
                "text",
                "constant.language.beancount",
                "punctuation.separator.beancount"
            ],
            regex: /(\s)([A-Z][A-Za-z0-9\-]+)(:)/,
            comment: "Root Accounts"
        }, {
                token: [
                    "punctuation.separator.beancount",
                    "variable.account.beancount"
                ],
                regex: /([:]?)([A-Z][A-Za-z0-9\-]+)/,
            comment: "Accounts"
        }, {
            token: [
                "text",
                "constant.language.beancount",
                "punctuation.separator.beancount"
            ],
            regex: /(\s)([a-z][A-Za-z0-9\-\_]+)(:)/,
            comment: "Metadata"
        }, {
            token: [
                "support.function.directive.option.beancount",
                "meta.directive.option.beancount",
                "support.variable.language.option.beancount",
                "meta.directive.option.beancount",
                "support.class.option.beancount",
                "meta.directive.option.beancount"
            ],
            regex: /^(option)(\s*)(\".*\")(\s*)(\".*\")(\s*)/,
            comment: "Option directives"
        }, {
            token: "keyword.operator.directive.beancount",
            regex: /^(?:poptag|pushtag)\s/,
            comment: "Directives (no date)"
        }, {
            token: "variable.other.currency.beancount",
            regex: /\s[A-Z][A-Z0-9\'\.\_\-]{0,10}[A-Z0-9][\,?|\s]/,
            comment: "Currencies"
        }, {
            token: [
                "constant.numeric.date.year.beancount",
                "text",
                "constant.numeric.date.month.beancount",
                "text",
                "constant.numeric.date.day.beancount",
                "text",
                "support.function.directive.beancount"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})(\s)(open|close|pad|balance|note|price|event|document|commodity|query)/,
            comment: "Dated directives"
        }, {
            token: [
                "constant.numeric.date.year.beancount",
                "text",
                "constant.numeric.date.month.beancount",
                "text",
                "constant.numeric.date.day.beancount",
                "support.function.directive.beancount",
                "text"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})((?:\stxn)?)(\s)/,
            comment: "Transactions"
        }, {
            token: "keyword.other.beancount",
            regex: /\!\s/,
            comment: "flag"
        }, {
            token: "keyword.operator.assignment.beancount",
            regex: /\@/,
            comment: "Price assignment"
        }, {
            token: "keyword.operator.assignment.beancount",
            regex: /\{/,
            comment: "cost assignment"
        }, {
            token: ["text", "string.unquoted.tag.beancount"],
            regex: /(#)([A-Za-z0-9\-_\/.]+)/,
            comment: "Tags and links"
        }, {
            token: ["text", "string.unquoted.link.beancount"],
            regex: /(\^)([A-Za-z0-9\-_\/.]+)/,
            comment: "Links"
        }, {
            token: [
                "keyword.operator.modifier.beancount",
                "constant.numeric.currency.beancount"
            ],
            regex: /([\-|\+]?)([\d]+[\.]?[\d]*)/,
            comment: "numbers"
        }, {
            token: "invalid.illegal.unrecognized.beancount",
            regex: /[^\s}]/,
            comment: "Illegal"
        }],
        "#account-names": [{
            token: "text",
            regex: /[A-Z][A-Za-z0-9\-]+/
        }],
        "#dates": [{
            token: [
                "constant.numeric.date.year.beancount",
                "punctuation.separator.beancount",
                "constant.numeric.date.month.beancount",
                "punctuation.separator.beancount",
                "constant.numeric.date.day.beancount"
            ],
            regex: /([0-9]{4})(\-)([0-9]{2})(\-)([0-9]{2})/
        }],
        "#numbers": [{
            token: [
                "keyword.operator.modifier.beancount",
                "constant.numeric.currency.beancount"
            ],
            regex: /([\-|\+]?)([\d]+[\.]?[\d]*)/
        }, {
            token: "comment.line.beancount",
            regex: /\*.*/,
            comment: "Commented text"
        }]
    }

    this.embedRules(SqlHighlightRules, "sql-", [{
        token: "string.quoted.triple.beancount",
        regex: /"""/,
        comment: "Multi-line strings",
        next: "start"
    }]);

    this.normalizeRules();
};

BeancountHighlightRules.metaData = {
    fileTypes: ["beancount"],
    name: "Beancount",
    scopeName: "source.beancount"
}

oop.inherits(BeancountHighlightRules, TextHighlightRules);

exports.BeancountHighlightRules = BeancountHighlightRules;
});

define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function(commentRegex) {
    if (commentRegex) {
        this.foldingStartMarker = new RegExp(
            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
        );
        this.foldingStopMarker = new RegExp(
            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
        );
    }
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
    this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
    this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
    this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
    this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
    this._getFoldWidgetBase = this.getFoldWidget;
    this.getFoldWidget = function(session, foldStyle, row) {
        var line = session.getLine(row);

        if (this.singleLineBlockCommentRe.test(line)) {
            if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
                return "";
        }

        var fw = this._getFoldWidgetBase(session, foldStyle, row);

        if (!fw && this.startRegionRe.test(line))
            return "start"; // lineCommentRegionStart

        return fw;
    };

    this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
        var line = session.getLine(row);

        if (this.startRegionRe.test(line))
            return this.getCommentRegionBlock(session, line, row);

        var match = line.match(this.foldingStartMarker);
        if (match) {
            var i = match.index;

            if (match[1])
                return this.openingBracketBlock(session, match[1], row, i);

            var range = session.getCommentFoldRange(row, i + match[0].length, 1);

            if (range && !range.isMultiLine()) {
                if (forceMultiline) {
                    range = this.getSectionRange(session, row);
                } else if (foldStyle != "all")
                    range = null;
            }

            return range;
        }

        if (foldStyle === "markbegin")
            return;

        var match = line.match(this.foldingStopMarker);
        if (match) {
            var i = match.index + match[0].length;

            if (match[1])
                return this.closingBracketBlock(session, match[1], row, i);

            return session.getCommentFoldRange(row, i, -1);
        }
    };

    this.getSectionRange = function(session, row) {
        var line = session.getLine(row);
        var startIndent = line.search(/\S/);
        var startRow = row;
        var startColumn = line.length;
        row = row + 1;
        var endRow = row;
        var maxRow = session.getLength();
        while (++row < maxRow) {
            line = session.getLine(row);
            var indent = line.search(/\S/);
            if (indent === -1)
                continue;
            if  (startIndent > indent)
                break;
            var subRange = this.getFoldWidgetRange(session, "all", row);

            if (subRange) {
                if (subRange.start.row <= startRow) {
                    break;
                } else if (subRange.isMultiLine()) {
                    row = subRange.end.row;
                } else if (startIndent == indent) {
                    break;
                }
            }
            endRow = row;
        }

        return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
    };
    this.getCommentRegionBlock = function(session, line, row) {
        var startColumn = line.search(/\s*$/);
        var maxRow = session.getLength();
        var startRow = row;

        var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
        var depth = 1;
        while (++row < maxRow) {
            line = session.getLine(row);
            var m = re.exec(line);
            if (!m) continue;
            if (m[1]) depth--;
            else depth++;

            if (!depth) break;
        }

        var endRow = row;
        if (endRow > startRow) {
            return new Range(startRow, startColumn, endRow, line.length);
        }
    };

}).call(FoldMode.prototype);

});

define("ace/mode/beancount",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/beancount_highlight_rules","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var BeancountHighlightRules = require("./beancount_highlight_rules").BeancountHighlightRules;
var FoldMode = require("./folding/cstyle").FoldMode;

var Mode = function() {
    this.HighlightRules = BeancountHighlightRules;
    this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);

(function() {
    this.$id = "ace/mode/beancount"
}).call(Mode.prototype);

exports.Mode = Mode;
});
<|endoftext|>


<commit_before>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BaseManager = require('module-toolkit').BaseManager;
var BateeqModels = require('bateeq-models');
var Bank = BateeqModels.master.Bank;
var map = BateeqModels.map;
//var generateCode = require('../../utils/code-generator');

module.exports = class BankManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.Bank);
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.master.Bank}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        var codeIndex = {
            name: `ix_${map.master.Bank}_code`,
            key: {
                code: 1
            },
            unique: true
        };

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }

    _getQuery(paging) {

        var basicFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            var filterName = {
                'name': {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterCode, filterName]
            };
        }
        query = { '$and': [basicFilter, paging.filter, keywordFilter] };
        return query;
    }

    _validate(bank) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = new Bank(bank);
            // 1. begin: Declare promises.
            var getBank = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                    code: valid.code
                }]
            });
            // 1. end: Declare promises.

            // 2. begin: Validation.
            Promise.all([getBank])
                .then(results => {
                    var _bank = results[0];
                    var patternForCode = "[a-zA-Z0-9]";

                    if (!valid.code || valid.code == '') {
                        errors["code"] = "Masukkan Kode";
                    } else if (valid.code.match(patternForCode) == null) {
                        errors["code"] = "Hanya menggunakan alphanumeric";
                    } else if (_bank) {
                        errors["code"] = "Kode sudah ada";
                    }
                    if (!valid.name || valid.name == '')
                        errors["name"] = "Masukkan nama";

                    // 2c. begin: check if data has any error, reject if it has.
                    for (var prop in errors) {
                        var ValidationError = require('module-toolkit').ValidationError;
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
};<commit_msg>Test module deployment<commit_after>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BaseManager = require('module-toolkit').BaseManager;
var BateeqModels = require('bateeq-models');
var Bank = BateeqModels.master.Bank;
var map = BateeqModels.map;
//var generateCode = require('../../utils/code-generator');

module.exports = class BankManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.Bank);
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.master.Bank}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        var codeIndex = {
            name: `ix_${map.master.Bank}_code`,
            key: {
                code: 1
            },
            unique: true
        };

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }

    _getQuery(paging) {

        var basicFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            var filterName = {
                'name': {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterCode, filterName]
            };
        }
        query = { '$and': [basicFilter, paging.filter, keywordFilter] };
        return query;
    }

    _validate(bank) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = new Bank(bank);
            // 1. begin: Declare promises.
            var getBank = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                    code: valid.code
                }]
            });
            // 1. end: Declare promises.

            // 2. begin: Validation.
            Promise.all([getBank])
                .then(results => {
                    var _bank = results[0];
                    var patternForCode = "[a-zA-Z0-9]";

                    if (!valid.code || valid.code == '') {
                        errors["code"] = "Masukkan Kode 2nd version";
                    } else if (valid.code.match(patternForCode) == null) {
                        errors["code"] = "Hanya menggunakan alphanumeric";
                    } else if (_bank) {
                        errors["code"] = "Kode sudah ada";
                    }
                    if (!valid.name || valid.name == '')
                        errors["name"] = "Masukkan nama";

                    // 2c. begin: check if data has any error, reject if it has.
                    for (var prop in errors) {
                        var ValidationError = require('module-toolkit').ValidationError;
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
};
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var concat = require('../lib/utils').concat;

var compressor = require('../lib/compressor');
var CompressionContext = compressor.CompressionContext;
var Compressor = compressor.Compressor;
var Decompressor = compressor.Decompressor;

var test_integers = [{
  N: 5,
  I: 10,
  buffer: new Buffer([10])
}, {
  N: 0,
  I: 10,
  buffer: new Buffer([10])
}, {
  N: 5,
  I: 1337,
  buffer: new Buffer([31, 128 + 26, 10])
}, {
  N: 0,
  I: 1337,
  buffer: new Buffer([128 + 57, 10])
}];

var test_strings = [{
  string: 'abcdefghij',
  buffer: new Buffer('0A6162636465666768696A', 'hex')
}, {
  string: 'éáűőúöüó€',
  buffer: new Buffer('13C3A9C3A1C5B1C591C3BAC3B6C3BCC3B3E282AC', 'hex')
}];

var test_headers = [{
  header: {
    name: 3,
    value: '/my-example/index.html',
    index: Infinity
  },
  buffer: new Buffer('44' + '162F6D792D6578616D706C652F696E6465782E68746D6C', 'hex')
}, {
  header: {
    name: 12,
    value: 'my-user-agent',
    index: Infinity
  },
  buffer: new Buffer('4D' + '0D6D792D757365722D6167656E74', 'hex')
}, {
  header: {
    name: 'x-my-header',
    value: 'first',
    index: Infinity
  },
  buffer: new Buffer('40' + '0B782D6D792D686561646572' + '056669727374', 'hex')
}, {
  header: {
    name: 38,
    value: 38,
    index: -1
  },
  buffer: new Buffer('A6', 'hex')
}, {
  header: {
    name: 40,
    value: 40,
    index: -1
  },
  buffer: new Buffer('A8', 'hex')
}, {
  header: {
    name: 3,
    value: '/my-example/resources/script.js',
    index: 38
  },
  buffer: new Buffer('0426' + '1F2F6D792D6578616D706C652F7265736F75726365732F7363726970742E6A73', 'hex')
}, {
  header: {
    name: 40,
    value: 'second',
    index: Infinity
  },
  buffer: new Buffer('5F0A' + '067365636F6E64', 'hex')
}, {
  header: {
    name: 40,
    value: 'third',
    index: -1
  },
  buffer: new Buffer('7F0A' + '057468697264', 'hex')
}];

var test_header_sets = [{
  headers: {
    ':path': '/my-example/index.html',
    'user-agent': 'my-user-agent',
    'x-my-header': 'first'
  },
  buffer: concat(test_headers.slice(0, 3).map(function(test) { return test.buffer; }))
}, {
  headers: {
    ':path': '/my-example/resources/script.js',
    'user-agent': 'my-user-agent',
    'x-my-header': 'second'
  },
  buffer: concat(test_headers.slice(3, 7).map(function(test) { return test.buffer; }))
}, {
  headers: {
    ':path': '/my-example/resources/script.js',
    'user-agent': 'my-user-agent',
    'x-my-header': ['second', 'third']
  },
  buffer: test_headers[7].buffer
}, {
  headers: {
    ':status': '200',
    'user-agent': 'my-user-agent',
    'cookie': ['first', 'second', 'third', 'third'],
    'verylong': (new Buffer(9000)).toString('hex')
  }
}];

describe('compressor.js', function() {
  describe('CompressionContext', function() {
    describe('static method .equal([name1, value1], [name2, value2])', function() {
      var equal = CompressionContext.equal;
      it('decides if the two headers are considered equal', function() {
        expect(equal(['name', 'value'], ['name', 'value'])).to.be.equal(true);
        expect(equal(['name', 'value'], ['nAmE', 'value'])).to.be.equal(true);
        expect(equal(['NaMe', 'value'], ['nAmE', 'value'])).to.be.equal(true);
        expect(equal(['name', 'VaLuE'], ['name', 'value'])).to.be.equal(false);
        expect(equal(['NaMe', 'VaLuE'], ['name', 'value'])).to.be.equal(false);
      });
    });
  });

  describe('Compressor', function() {
    describe('static method .integer(I, N)', function() {
      it('should return an array of buffers that represent the N-prefix coded form of the integer I', function() {
        for (var i = 0; i < test_strings.length; i++) {
          var test = test_strings[i];
          expect(concat(Compressor.string(test.string))).to.deep.equal(test.buffer);
        }
      });
    });
    describe('static method .string(string)', function() {
      it('should return an array of buffers that represent the encoded form of the string', function() {
        for (var i = 0; i < test_strings.length; i++) {
          var test = test_strings[i];
          expect(concat(Compressor.string(test.string))).to.deep.equal(test.buffer);
        }
      });
    });
    describe('static method .header({ name, value, indexing, substitution })', function() {
      it('should return an array of buffers that represent the encoded form of the header', function() {
        for (var i = 0; i < test_headers.length; i++) {
          var test = test_headers[i];
          expect(concat(Compressor.header(test.header))).to.deep.equal(test.buffer);
        }
      });
    });
  });

  describe('Decompressor', function() {
    describe('static method .integer(buffer, N)', function() {
      it('should return the parsed N-prefix coded number and increase the cursor property of buffer', function() {
        for (var i = 0; i < test_integers.length; i++) {
          var test = test_integers[i];
          test.buffer.cursor = 0;
          expect(Decompressor.integer(test.buffer, test.N)).to.equal(test.I);
          expect(test.buffer.cursor).to.equal(test.buffer.length);
        }
      });
    });
    describe('static method .string(buffer)', function() {
      it('should return the parsed string and increase the cursor property of buffer', function() {
        for (var i = 0; i < test_strings.length; i++) {
          var test = test_strings[i];
          test.buffer.cursor = 0;
          expect(Decompressor.string(test.buffer)).to.equal(test.string);
          expect(test.buffer.cursor).to.equal(test.buffer.length);
        }
      });
    });
    describe('static method .header(buffer)', function() {
      it('should return the parsed header and increase the cursor property of buffer', function() {
        for (var i = 0; i < test_headers.length; i++) {
          var test = test_headers[i];
          test.buffer.cursor = 0;
          expect(Decompressor.header(test.buffer)).to.deep.equal(test.header);
          expect(test.buffer.cursor).to.equal(test.buffer.length);
        }
      });
    });
    describe('method decompress(buffer)', function() {
      it('should return the parsed header set in { name1: value1, name2: [value2, value3], ... } format', function() {
        var decompressor = new Decompressor('REQUEST');
        var header_set = test_header_sets[0];
        expect(decompressor.decompress(header_set.buffer)).to.deep.equal(header_set.headers);
        header_set = test_header_sets[1];
        expect(decompressor.decompress(header_set.buffer)).to.deep.equal(header_set.headers);
        header_set = test_header_sets[2];
        expect(decompressor.decompress(header_set.buffer)).to.deep.equal(header_set.headers);
      });
    });
  });

  describe('invariant', function() {
    describe('decompressor.decompress(compressor.compress(headerset)) === headerset', function() {
      it('should be true for any header set if the states are synchronized', function() {
        var compressor = new Compressor('REQUEST');
        var decompressor = new Decompressor('REQUEST');
        for (var i = 0; i < 10; i++) {
          var headers = test_header_sets[i%4].headers;
          var compressed = compressor.compress(headers);
          var decompressed = decompressor.decompress(compressed);
          expect(headers).to.deep.equal(decompressed);
          expect(compressor._table).to.deep.equal(decompressor._table);
          expect(compressor._reference).to.deep.equal(decompressor._reference);
          expect(compressor._working).to.deep.equal(compressor._working);
        }
      });
    });
    describe('source.pipe(compressor).pipe(decompressor).pipe(destination)', function() {
      it('should behave like source.pipe(destination) for a stream of frames', function(done) {
        var compressor = new Compressor('RESPONSE');
        var decompressor = new Decompressor('RESPONSE');
        compressor.pipe(decompressor);
        for (var i = 0; i < 10; i++) {
          compressor.write({
            type: i%2 ? 'HEADERS' : 'PUSH_PROMISE',
            flags: {},
            headers: test_header_sets[i%4].headers
          });
        }
        setTimeout(function() {
          for (var j = 0; j < 10; j++) {
            expect(decompressor.read().headers).to.deep.equal(test_header_sets[j%4].headers);
          }
          done();
        }, 10);
      });
    });
  });
});

// Missing test cases for 100% test coverage:
// * generateRemoveCommand for an entry not in the working set.
// * interrupting a compressed frame series with an unrelated frame<commit_msg>Compression: adding missing tests.<commit_after>var expect = require('chai').expect;
var concat = require('../lib/utils').concat;

var compressor = require('../lib/compressor');
var CompressionContext = compressor.CompressionContext;
var Compressor = compressor.Compressor;
var Decompressor = compressor.Decompressor;

var test_integers = [{
  N: 5,
  I: 10,
  buffer: new Buffer([10])
}, {
  N: 0,
  I: 10,
  buffer: new Buffer([10])
}, {
  N: 5,
  I: 1337,
  buffer: new Buffer([31, 128 + 26, 10])
}, {
  N: 0,
  I: 1337,
  buffer: new Buffer([128 + 57, 10])
}];

var test_strings = [{
  string: 'abcdefghij',
  buffer: new Buffer('0A6162636465666768696A', 'hex')
}, {
  string: 'éáűőúöüó€',
  buffer: new Buffer('13C3A9C3A1C5B1C591C3BAC3B6C3BCC3B3E282AC', 'hex')
}];

var test_headers = [{
  header: {
    name: 3,
    value: '/my-example/index.html',
    index: Infinity
  },
  buffer: new Buffer('44' + '162F6D792D6578616D706C652F696E6465782E68746D6C', 'hex')
}, {
  header: {
    name: 12,
    value: 'my-user-agent',
    index: Infinity
  },
  buffer: new Buffer('4D' + '0D6D792D757365722D6167656E74', 'hex')
}, {
  header: {
    name: 'x-my-header',
    value: 'first',
    index: Infinity
  },
  buffer: new Buffer('40' + '0B782D6D792D686561646572' + '056669727374', 'hex')
}, {
  header: {
    name: 38,
    value: 38,
    index: -1
  },
  buffer: new Buffer('A6', 'hex')
}, {
  header: {
    name: 40,
    value: 40,
    index: -1
  },
  buffer: new Buffer('A8', 'hex')
}, {
  header: {
    name: 3,
    value: '/my-example/resources/script.js',
    index: 38
  },
  buffer: new Buffer('0426' + '1F2F6D792D6578616D706C652F7265736F75726365732F7363726970742E6A73', 'hex')
}, {
  header: {
    name: 40,
    value: 'second',
    index: Infinity
  },
  buffer: new Buffer('5F0A' + '067365636F6E64', 'hex')
}, {
  header: {
    name: 40,
    value: 'third',
    index: -1
  },
  buffer: new Buffer('7F0A' + '057468697264', 'hex')
}];

var test_header_sets = [{
  headers: {
    ':path': '/my-example/index.html',
    'user-agent': 'my-user-agent',
    'x-my-header': 'first'
  },
  buffer: concat(test_headers.slice(0, 3).map(function(test) { return test.buffer; }))
}, {
  headers: {
    ':path': '/my-example/resources/script.js',
    'user-agent': 'my-user-agent',
    'x-my-header': 'second'
  },
  buffer: concat(test_headers.slice(3, 7).map(function(test) { return test.buffer; }))
}, {
  headers: {
    ':path': '/my-example/resources/script.js',
    'user-agent': 'my-user-agent',
    'x-my-header': ['second', 'third']
  },
  buffer: test_headers[7].buffer
}, {
  headers: {
    ':status': '200',
    'user-agent': 'my-user-agent',
    'cookie': ['first', 'second', 'third', 'third'],
    'verylong': (new Buffer(9000)).toString('hex')
  }
}];

describe('compressor.js', function() {
  describe('CompressionContext', function() {
    describe('static method .equal([name1, value1], [name2, value2])', function() {
      var equal = CompressionContext.equal;
      it('decides if the two headers are considered equal', function() {
        expect(equal(['name', 'value'], ['name', 'value'])).to.be.equal(true);
        expect(equal(['name', 'value'], ['nAmE', 'value'])).to.be.equal(true);
        expect(equal(['NaMe', 'value'], ['nAmE', 'value'])).to.be.equal(true);
        expect(equal(['name', 'VaLuE'], ['name', 'value'])).to.be.equal(false);
        expect(equal(['NaMe', 'VaLuE'], ['name', 'value'])).to.be.equal(false);
      });
    });
  });

  describe('Compressor', function() {
    describe('static method .integer(I, N)', function() {
      it('should return an array of buffers that represent the N-prefix coded form of the integer I', function() {
        for (var i = 0; i < test_strings.length; i++) {
          var test = test_strings[i];
          expect(concat(Compressor.string(test.string))).to.deep.equal(test.buffer);
        }
      });
    });
    describe('static method .string(string)', function() {
      it('should return an array of buffers that represent the encoded form of the string', function() {
        for (var i = 0; i < test_strings.length; i++) {
          var test = test_strings[i];
          expect(concat(Compressor.string(test.string))).to.deep.equal(test.buffer);
        }
      });
    });
    describe('static method .header({ name, value, indexing, substitution })', function() {
      it('should return an array of buffers that represent the encoded form of the header', function() {
        for (var i = 0; i < test_headers.length; i++) {
          var test = test_headers[i];
          expect(concat(Compressor.header(test.header))).to.deep.equal(test.buffer);
        }
      });
    });
  });

  describe('Decompressor', function() {
    describe('static method .integer(buffer, N)', function() {
      it('should return the parsed N-prefix coded number and increase the cursor property of buffer', function() {
        for (var i = 0; i < test_integers.length; i++) {
          var test = test_integers[i];
          test.buffer.cursor = 0;
          expect(Decompressor.integer(test.buffer, test.N)).to.equal(test.I);
          expect(test.buffer.cursor).to.equal(test.buffer.length);
        }
      });
    });
    describe('static method .string(buffer)', function() {
      it('should return the parsed string and increase the cursor property of buffer', function() {
        for (var i = 0; i < test_strings.length; i++) {
          var test = test_strings[i];
          test.buffer.cursor = 0;
          expect(Decompressor.string(test.buffer)).to.equal(test.string);
          expect(test.buffer.cursor).to.equal(test.buffer.length);
        }
      });
    });
    describe('static method .header(buffer)', function() {
      it('should return the parsed header and increase the cursor property of buffer', function() {
        for (var i = 0; i < test_headers.length; i++) {
          var test = test_headers[i];
          test.buffer.cursor = 0;
          expect(Decompressor.header(test.buffer)).to.deep.equal(test.header);
          expect(test.buffer.cursor).to.equal(test.buffer.length);
        }
      });
    });
    describe('method decompress(buffer)', function() {
      it('should return the parsed header set in { name1: value1, name2: [value2, value3], ... } format', function() {
        var decompressor = new Decompressor('REQUEST');
        var header_set = test_header_sets[0];
        expect(decompressor.decompress(header_set.buffer)).to.deep.equal(header_set.headers);
        header_set = test_header_sets[1];
        expect(decompressor.decompress(header_set.buffer)).to.deep.equal(header_set.headers);
        header_set = test_header_sets[2];
        expect(decompressor.decompress(header_set.buffer)).to.deep.equal(header_set.headers);
      });
    });
    describe('transform stream', function() {
      it('should emit an error event if a series of header frames is interleaved with other frames', function() {
        var decompressor = new Decompressor('REQUEST');
        var error_occured = false;
        decompressor.on('error', function() {
          error_occured = true;
        });
        decompressor.write({
          type: 'HEADERS',
          flags: {
            END_HEADERS: false
          },
          data: new Buffer(5)
        });
        decompressor.write({
          type: 'DATA',
          flags: {},
          data: new Buffer(5)
        });
        expect(error_occured).to.be.equal(true);
      });
    });
  });

  describe('invariant', function() {
    describe('decompressor.decompress(compressor.compress(headerset)) === headerset', function() {
      it('should be true for any header set if the states are synchronized', function() {
        var compressor = new Compressor('REQUEST');
        var decompressor = new Decompressor('REQUEST');
        for (var i = 0; i < 10; i++) {
          var headers = test_header_sets[i%4].headers;
          var compressed = compressor.compress(headers);
          var decompressed = decompressor.decompress(compressed);
          expect(headers).to.deep.equal(decompressed);
          expect(compressor._table).to.deep.equal(decompressor._table);
          expect(compressor._reference).to.deep.equal(decompressor._reference);
          expect(compressor._working).to.deep.equal(compressor._working);
        }
      });
    });
    describe('source.pipe(compressor).pipe(decompressor).pipe(destination)', function() {
      it('should behave like source.pipe(destination) for a stream of frames', function(done) {
        var compressor = new Compressor('RESPONSE');
        var decompressor = new Decompressor('RESPONSE');
        compressor.pipe(decompressor);
        for (var i = 0; i < 10; i++) {
          compressor.write({
            type: i%2 ? 'HEADERS' : 'PUSH_PROMISE',
            flags: {},
            headers: test_header_sets[i%4].headers
          });
        }
        setTimeout(function() {
          for (var j = 0; j < 10; j++) {
            expect(decompressor.read().headers).to.deep.equal(test_header_sets[j%4].headers);
          }
          done();
        }, 10);
      });
    });
  });
});
<|endoftext|>


<commit_before>const React = require('react');
const PropTypes = require('prop-types');
const Radium = require('radium');
const keycode = require('keycode');
const _merge = require('lodash/merge');

import { withTheme } from './Theme';
const Icon = require('./Icon');
const { Listbox, Option } = require('./accessibility/Listbox');
const MXFocusTrap = require('./MXFocusTrap');

const { themeShape } = require('../constants/App');

const StyleUtils = require('../utils/Style');
const { deprecatePrimaryColor, deprecateProp } = require('../utils/Deprecation');

class SimpleSelect extends React.Component {
  static propTypes = {
    'aria-label': PropTypes.string,
    elementRef: PropTypes.func,
    focusTrapProps: PropTypes.object,
    hoverColor: PropTypes.string,
    iconSize: PropTypes.number,
    iconStyles: PropTypes.object,
    items: PropTypes.array.isRequired,
    itemStyles: PropTypes.object,
    menuStyles: PropTypes.object,
    onScrimClick: PropTypes.func,
    scrimClickOnSelect: PropTypes.bool,
    style: PropTypes.object,
    styles: PropTypes.object,
    theme: themeShape
  };

  static defaultProps = {
    'aria-label': '',
    focusTrapProps: {},
    scrimClickOnSelect: false,
    items: [],
    onScrimClick () {}
  };

  componentDidMount () {
    deprecatePrimaryColor(this.props, 'hoverColor');
    deprecateProp(this.props, 'iconStyles', 'styles', 'simple-select');
    deprecateProp(this.props, 'menuStyles', 'styles', 'simple-select');
  }

  _handleKeyUp = (e) => {
    if (keycode(e) === 'esc') {
      e.preventDefault();
      this.props.onScrimClick();
    }
  };

  render () {
    const theme = StyleUtils.mergeTheme(this.props.theme, this.props.hoverColor);
    const styles = this.styles(theme);

    const mergedFocusTrapProps = {
      focusTrapOptions: {
        clickOutsideDeactivates: true
      },
      ...this.props.focusTrapProps
    };

    return (
      <MXFocusTrap {...mergedFocusTrapProps}>

          <Listbox
            aria-label={this.props['aria-label']}
            style={styles.menu}
            useGlobalKeyHandler={true}
          >
            {this.props.children ?
              this.props.children :
              (this.props.items.map((item, i) => {
                const { icon, isSelected, onClick, text, ...rest } = item;

                return (
                  <Option
                    isSelected={isSelected}
                    key={i}
                    label={text}
                    onClick={e => {
                      if (this.props.scrimClickOnSelect) {
                        e.stopPropagation();
                        this.props.onScrimClick();
                      }

                      if (onClick && typeof onClick === 'function') {
                        onClick(e, item);
                      }
                    }}
                    style={styles.item}
                    {...rest}
                  >
                    {icon ? (
                      <Icon size={this.props.iconSize || 20} style={styles.icon} type={icon} />
                    ) : null}

{text}

                  </Option>
                );
              })
            )}
          </Listbox>

 {
              e.stopPropagation();
              this.props.onScrimClick();
            }}
            style={styles.scrim}
          />

      </MXFocusTrap>
    );
  }

  styles = (theme) => {
    return _merge({}, {
      component: Object.assign({
        height: 0,
        position: 'relative'
      }, this.props.style),

      menu: Object.assign({}, {
        alignSelf: 'stretch',
        backgroundColor: theme.Colors.WHITE,
        borderRadius: 3,
        boxShadow: theme.ShadowHigh,
        boxSizing: 'border-box',
        color: theme.Colors.GRAY_700,
        display: 'flex',
        flexDirection: 'column',
        fill: theme.Colors.GRAY_700,
        fontFamily: theme.FontFamily,
        fontSize: theme.FontSizes.MEDIUM,
        top: 10,
        position: 'absolute',
        zIndex: 10
      }, this.props.menuStyles),

      item: Object.assign({}, {
        display: 'flex',
        alignItems: 'center',
        boxSizing: 'border-box',
        height: 40,
        padding: theme.Spacing.MEDIUM,

        ':hover': {
          backgroundColor: theme.Colors.PRIMARY,
          color: theme.Colors.WHITE,
          cursor: 'pointer',
          fill: theme.Colors.WHITE
        }
      }, this.props.itemStyles),
      icon: Object.assign({}, {
        marginRight: theme.Spacing.SMALL
      }, this.props.iconStyles),
      text: {
        whiteSpace: 'nowrap'
      },
      scrim: {
        bottom: 0,
        left: 0,
        position: 'fixed',
        right: 0,
        top: 0,
        zIndex: 9
      }
    }, this.props.styles);
  };
}

module.exports = withTheme(Radium(SimpleSelect));
<commit_msg>Switch SimpleSelect back to use FocusTrap directly<commit_after>const React = require('react');
const PropTypes = require('prop-types');
const Radium = require('radium');
const keycode = require('keycode');
const _merge = require('lodash/merge');

import { withTheme } from './Theme';
const Icon = require('./Icon');
const { Listbox, Option } = require('./accessibility/Listbox');
const FocusTrap = require('focus-trap-react');

const { themeShape } = require('../constants/App');

const StyleUtils = require('../utils/Style');
const { deprecatePrimaryColor, deprecateProp } = require('../utils/Deprecation');

class SimpleSelect extends React.Component {
  static propTypes = {
    'aria-label': PropTypes.string,
    elementRef: PropTypes.func,
    focusTrapProps: PropTypes.object,
    hoverColor: PropTypes.string,
    iconSize: PropTypes.number,
    iconStyles: PropTypes.object,
    items: PropTypes.array.isRequired,
    itemStyles: PropTypes.object,
    menuStyles: PropTypes.object,
    onScrimClick: PropTypes.func,
    scrimClickOnSelect: PropTypes.bool,
    style: PropTypes.object,
    styles: PropTypes.object,
    theme: themeShape
  };

  static defaultProps = {
    'aria-label': '',
    focusTrapProps: {},
    scrimClickOnSelect: false,
    items: [],
    onScrimClick () {}
  };

  componentDidMount () {
    deprecatePrimaryColor(this.props, 'hoverColor');
    deprecateProp(this.props, 'iconStyles', 'styles', 'simple-select');
    deprecateProp(this.props, 'menuStyles', 'styles', 'simple-select');
  }

  _handleKeyUp = (e) => {
    if (keycode(e) === 'esc') {
      e.preventDefault();
      this.props.onScrimClick();
    }
  };

  render () {
    const theme = StyleUtils.mergeTheme(this.props.theme, this.props.hoverColor);
    const styles = this.styles(theme);

    const mergedFocusTrapProps = {
      focusTrapOptions: {
        clickOutsideDeactivates: true
      },
      ...this.props.focusTrapProps
    };

    return (
      <FocusTrap {...mergedFocusTrapProps}>

          <Listbox
            aria-label={this.props['aria-label']}
            style={styles.menu}
            useGlobalKeyHandler={true}
          >
            {this.props.children ?
              this.props.children :
              (this.props.items.map((item, i) => {
                const { icon, isSelected, onClick, text, ...rest } = item;

                return (
                  <Option
                    isSelected={isSelected}
                    key={i}
                    label={text}
                    onClick={e => {
                      if (this.props.scrimClickOnSelect) {
                        e.stopPropagation();
                        this.props.onScrimClick();
                      }

                      if (onClick && typeof onClick === 'function') {
                        onClick(e, item);
                      }
                    }}
                    style={styles.item}
                    {...rest}
                  >
                    {icon ? (
                      <Icon size={this.props.iconSize || 20} style={styles.icon} type={icon} />
                    ) : null}

{text}

                  </Option>
                );
              })
            )}
          </Listbox>

 {
              e.stopPropagation();
              this.props.onScrimClick();
            }}
            style={styles.scrim}
          />

      </FocusTrap>
    );
  }

  styles = (theme) => {
    return _merge({}, {
      component: Object.assign({
        height: 0,
        position: 'relative'
      }, this.props.style),

      menu: Object.assign({}, {
        alignSelf: 'stretch',
        backgroundColor: theme.Colors.WHITE,
        borderRadius: 3,
        boxShadow: theme.ShadowHigh,
        boxSizing: 'border-box',
        color: theme.Colors.GRAY_700,
        display: 'flex',
        flexDirection: 'column',
        fill: theme.Colors.GRAY_700,
        fontFamily: theme.FontFamily,
        fontSize: theme.FontSizes.MEDIUM,
        top: 10,
        position: 'absolute',
        zIndex: 10
      }, this.props.menuStyles),

      item: Object.assign({}, {
        display: 'flex',
        alignItems: 'center',
        boxSizing: 'border-box',
        height: 40,
        padding: theme.Spacing.MEDIUM,

        ':hover': {
          backgroundColor: theme.Colors.PRIMARY,
          color: theme.Colors.WHITE,
          cursor: 'pointer',
          fill: theme.Colors.WHITE
        }
      }, this.props.itemStyles),
      icon: Object.assign({}, {
        marginRight: theme.Spacing.SMALL
      }, this.props.iconStyles),
      text: {
        whiteSpace: 'nowrap'
      },
      scrim: {
        bottom: 0,
        left: 0,
        position: 'fixed',
        right: 0,
        top: 0,
        zIndex: 9
      }
    }, this.props.styles);
  };
}

module.exports = withTheme(Radium(SimpleSelect));
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import Items from './Items';
import { toggleItem } from '../actions';

const getVisibleItems = (
  items,
  filter
) => {
  switch (filter) {
    case 'all':
      return items;
    case 'enabled':
      return items.filter(
        i => i.enabled
      );
    case 'disabled':
      return items.filter(
        i => !i.enabled
      );
    default:
      throw new Error(`Unknown filter: ${filter}.`);
  }
}

const mapStateToProps = (state, { match }) => {
  return {
    items: getVisibleItems(
      state.items,
      match.params.filter || 'all'
    )
  };
}

const mapDispatchToProps = (dispatch) => {
  return {
    onItemClick: id => {
      dispatch(
        toggleItem(id)
      )
    }
  };
}

const VisibleItems = withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps
  )(Items)
);

export default VisibleItems;<commit_msg>refactor: Using mapDispatchToProps() Shorthand Notation<commit_after>import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import Items from './Items';
import { toggleItem } from '../actions';

const getVisibleItems = (
  items,
  filter
) => {
  switch (filter) {
    case 'all':
      return items;
    case 'enabled':
      return items.filter(
        i => i.enabled
      );
    case 'disabled':
      return items.filter(
        i => !i.enabled
      );
    default:
      throw new Error(`Unknown filter: ${filter}.`);
  }
}

const mapStateToProps = (state, { match }) => {
  return {
    items: getVisibleItems(
      state.items,
      match.params.filter || 'all'
    )
  };
}

const VisibleItems = withRouter(
  connect(
    mapStateToProps,
    { onItemClick: toggleItem }
  )(Items)
);

export default VisibleItems;<|endoftext|>


<commit_before>'use strict';

var merge = require('lodash').merge;
var data = require('gulp-data');
var frontMatter = require('front-matter');
var fs = require('fs');
var handlebars = require('gulp-compile-handlebars');
var path = require('path');
var rename = require('gulp-rename');

var defaults = {
  sharedData: {},
  dest: './dist',
  layoutDir: './src/layouts',
  plugins: {
    handlebars: {
      ignorePartials: true,
      batch: ['./src/partials'],
    }
  },
  src: './src/*.hbs',
  templateExt: 'hbs'
};

module.exports = function (gulp, options) {
  var opts = merge({}, defaults, options);
  var sharedData = opts.sharedData;
  var dest = opts.dest;
  var layoutDir = opts.layoutDir;
  var plugins = opts.plugins;
  var src = opts.src;
  var templateExt = opts.templateExt;

  /* Helper to extract meta data embedded in the file contents. */
  function parseContent (file) {
    return frontMatter(String(file.contents));
  }

  /* Helper to resolve template paths. */
  function getLayoutPath (name) {
    return path.resolve(
      process.cwd(),
      layoutDir + '/',
      name + '.' + templateExt
    );
  }

  gulp.task('html', function () {
    /* Helper to abstract handlebars sub-task. */
    var compileHtml = function () {
      return handlebars(sharedData, plugins.handlebars)
    };

    /* Helper to abstract FrontMatter sub-task. */
    var parseData = function (file) {
      var content = parseContent(file);
      file.contents = new Buffer(content.body);
      return content.attributes;
    };

    /* Helper to abstract template replacement sub-task. */
    var wrapHtml = function (file, name) {
      var html = String(file.contents);
      var path = getLayoutPath(name);

      file.contents = fs.readFileSync(path);
      return { content: html };
    }

    return gulp.src(src)
      .pipe(data(function (file) {
        return parseData(file);
      }))
      .pipe(compileHtml())
      .pipe(data(function (file) {
        var layoutName = file.data.layout;
        return wrapHtml(file, layoutName);
      }))
      .pipe(compileHtml())
      .pipe(rename(function (path) {
        path.extname = '.html'
      }))
      .pipe(gulp.dest(dest));
  });
};
<commit_msg>ES6: Remove unnecessary use strict<commit_after>var merge = require('lodash').merge;
var data = require('gulp-data');
var frontMatter = require('front-matter');
var fs = require('fs');
var handlebars = require('gulp-compile-handlebars');
var path = require('path');
var rename = require('gulp-rename');

var defaults = {
  sharedData: {},
  dest: './dist',
  layoutDir: './src/layouts',
  plugins: {
    handlebars: {
      ignorePartials: true,
      batch: ['./src/partials'],
    }
  },
  src: './src/*.hbs',
  templateExt: 'hbs'
};

module.exports = function (gulp, options) {
  var opts = merge({}, defaults, options);
  var sharedData = opts.sharedData;
  var dest = opts.dest;
  var layoutDir = opts.layoutDir;
  var plugins = opts.plugins;
  var src = opts.src;
  var templateExt = opts.templateExt;

  /* Helper to extract meta data embedded in the file contents. */
  function parseContent (file) {
    return frontMatter(String(file.contents));
  }

  /* Helper to resolve template paths. */
  function getLayoutPath (name) {
    return path.resolve(
      process.cwd(),
      layoutDir + '/',
      name + '.' + templateExt
    );
  }

  gulp.task('html', function () {
    /* Helper to abstract handlebars sub-task. */
    var compileHtml = function () {
      return handlebars(sharedData, plugins.handlebars)
    };

    /* Helper to abstract FrontMatter sub-task. */
    var parseData = function (file) {
      var content = parseContent(file);
      file.contents = new Buffer(content.body);
      return content.attributes;
    };

    /* Helper to abstract template replacement sub-task. */
    var wrapHtml = function (file, name) {
      var html = String(file.contents);
      var path = getLayoutPath(name);

      file.contents = fs.readFileSync(path);
      return { content: html };
    }

    return gulp.src(src)
      .pipe(data(function (file) {
        return parseData(file);
      }))
      .pipe(compileHtml())
      .pipe(data(function (file) {
        var layoutName = file.data.layout;
        return wrapHtml(file, layoutName);
      }))
      .pipe(compileHtml())
      .pipe(rename(function (path) {
        path.extname = '.html'
      }))
      .pipe(gulp.dest(dest));
  });
};
<|endoftext|>


<commit_before>

var levelup = require('levelup')
var through = require('through')
var from    = require('from')

//this will hold the reductions to do.

var queue = []

function map (data, emit) {
  var company = JSON.parse(data)
  var id = company.name

  company.contacts.forEach(function (contact) {
//    emit(contact.last+', '+contact.first, id)
//    emit([contact.last, contact.first], id)
    // Emit name and company the person works for
    emit([contact.first, contact.last], JSON.stringify([id]))
  })
}

//merge sets.
// big is the list of already reduced values.
// little is the list of values that are being reduced for
// the first time
function reduce (big, little) {
  function prep(ary) {
    var ary = JSON.parse(ary)
    if(!Array.isArray(ary))
      ary = [ary]
    return ary
  }
  var big     = prep(big)
  var little  = prep(little)
  little.forEach(function (item) {
    if(!~big.indexOf(item))
      big.push(item)
  })
  big.sort()
  // return list of all companies I work for
  return JSON.stringify(big)
}

levelup('/tmp/reducer-testdb', function (err, db) {

  var writer = db.writeStream()

  function sk (key) {
    if(!Array.isArray(key)) key = [key]
    // prefix with length to be able to query for results
    // that are grouped at 2 or 3 deep granularity
    key = key.length + '~' + JSON.stringify(key)
    return key
  }

  // Read everything BEFORE ~. We store reduced data at ~ and
  // after
  db.readStream({end: '~', start: ''})
  .pipe(through(function (data) {
    //get any previous mapping for this object,
    //and delete it's keys...
    var k = data.key
    var v = data.value
    var self = this

    db.get('~map~~'+k, function (err, oldMap) {
      var old = oldMap ? JSON.parse(oldMap) : []

      var maps = [], keys = []

      function emit (key, val) {
        key = sk(key)
        keys.push(key)
        maps.push({type: 'put', key: '~map~' + key + '~' + k, value: val})
      }

      map(data.value, emit)

      //okay, so now these all must be saved...
      //also, so we will be able to update them,
      //save them as map!KEY!ID
      //also, save map!!!ID -> the keys.

      var bulk = [
        //they keys this value was mapped to.
        {type: 'put', key:'~map~~'+k, value: JSON.stringify(keys.sort())}
      ]

      //if a key was in old, but now not in keys, delete that map.
      old.forEach(function (key) {
        if(!~keys.indexOf(key)) {
          bulk.push({type: 'del', key: '~map~'+key+'~'+k})
        }
      })

      maps.forEach(function (m) {
        if(!~queue.indexOf(m.key))
          queue.push(m.key)
        bulk.push(m)
      })

      db.batch(bulk)

      //okay... so how do I decide where to bundle the reduce?
      //what about, when a key is updated
      //rereduce the whole group?
      //by doing a range query on the ~map~KEY~ to ~map~KEY~~
      //and save that to ~reduce~KEY
      //this basically leaves it up to the user...
      //so, when you update a doc... rerun the reduce for a key.
      //and then rerun the reduce for the rest of the keys.
      //this could potentially be a very large number...
      //how to partition this?
      //another approch maybe... how to make merkle tree?
      //clearly map each doc to hash(key), hash(value)
      //then, keys are evenly distributed, so it's easy to group by.
      //hmm, maybe just group by the letters in the key?
      //so, we sort by

      //[16, 256, all...]

      //so, basically, well add items to a reduce queue...
      //and then they will be reduced in batches.

      //so, each map result needs to get added to a reduce queue.
      //that should then run every so often, and also group the
      //updates so that they run in a good order.

//      console.log(queue)

      self.queue(data)
    })
  }, function () {
    this.queue(null)
  })).on('end', function () {
    console.log(queue.sort())
    console.log('END')

    //REDUCE.

    from(queue).pipe(through(function (key) {
      //parse the key, and get a range.
      var ary = JSON.parse(key.split('~')[3])
      console.log(ary)

      var start = '~map~'+sk([ary[0], ''])
      var end   = '~map~'+sk([ary[0], '~'])
      console.log('START', start, 'END', end)
      var collection = JSON.stringify([])
      db.readStream({start: start, end: end})
        .pipe(through(function (data) {
          collection = reduce(collection, data.value)
        }, function () {
          console.log('COLLECTION', ary[0], collection)
        }))
    }))
  })
})
<commit_msg>rm scratch.js<commit_after><|endoftext|>


<commit_before>import React from 'react';

export default class Header extends React.Component {
  render() {
    const h1Style = {
      margin: 0,
      padding: '47px 0 0 47px',
      float: 'left'
    };

    const aStyle = {
      float: 'right',
      // marginTop: '54px',
      marginTop: '60px',
      marginRight: '45px',
      fontSize: '15px',
      fontFamily: 'belwe'
    };

    return (

theoddvisualstuff

          Terug naar Aarde

    );
  }
}
<commit_msg>Implement more props for Header<commit_after>import React from 'react';
import cn from 'classnames';

export default class Header extends React.Component {
  render() {
    const h1Style = {
      margin: 0,
      float: 'left'
    };

    const aStyle = {
      float: 'right',
      fontSize: '15px',
      fontFamily: 'belwe'
    };

    const isLargeClass = this.props.isLarge && 'large' ? 'top large' : 'small';

    return (

theoddvisualstuff

          {this.props.linkName}

    );
  }
}
<|endoftext|>


<commit_before>//Use GreyHawk DnD campaign map as referance.
//TODO: Make merchants
'use strict';
var Cmd = require('../src/commands').cmd,
Room = require('../src/rooms').room,
World = require('../src/world').world;

module.exports = {
	name: 'Greyhawk_City',
	id: '4',
	type: 'outside',
	levels: 'All',
	description: 'A vast cityscape with infinite possiblities',
	reloads: 0,
	author: 'Sam Bolton (Anorak)',
	messages: [
		{msg: 'A cool breeze blows through the streets of Greyhawk city.'},
		{msg: 'The bustle of the city can be distracting. Keep an eye out for thieves.'}
	],
	rooms: [
		{
			id: '1',
			title: 'Greyhawk City main square',
			area: 'Greyhawk City',
			content: 'A busy hustling market square. To the NORTH you can see a residential area.',
			outdoors: true,
			exits: [
				{
					cmd: 'north',
					id: '1',
					area: 'Midgaard'
				}
			],
			monsters: [{
				name: 'InfoBroker',
				displayName: 'Grey Hawk Info Broker',
				charClass: 'theif',
				level: 35,
				short: 'Info Broker',
				long: 'Info Broker, a decent looking man with washed back hair.',
				description: 'A fine looking man with wased back hair, wearing a suit',
				inName: 'InfoBroker',
				race: 'human',
				id: 10005,
				area: 'Greyhawk_City',
				weight: 195,
				diceNum: 3,
				diceSides: 10,
				diceMod: 5,
				str: 20,
				dex: 18,
				position: 'standing',
				attackType: 'punch',
				damRoll: 20,
				hitRoll: 15,
				ac: 20,
				items: [],
				trainer: true,
				behaviors: [{
					module: 'InfoBroker1'
				}]
			}],
			items : [
				{
					name: 'Torch',
					short: 'a wooden torch',
					long: 'A wooden torch rests on the ground' ,
					area: 'Greyhawk_City',
					id: '104',
					level: 1,
					itemType: 'weapon',
					material: 'wood',
					weaponType: 'club',
					diceNum: 1,
					diceSides: 2,
					diceMod: -1,
					attackType: 'smash',
					ac: -1,
					weight: 1,
					slot: 'hands',
					equipped: false,
					light: true,
					lightDecay: 10,
					flickerMsg: '',
					extinguishMsg: '',
					spawn: 3,
					flags: [],
					beforeDrop: function(item, roomObj) {
						return true;
					}
				}
			]
		},
		{
			id: '2',
			title: 'Greyhawk City residential area',
			area: 'Greyhawk City',
			content: 'A calm area with some houses around.',
			messages: [
					{msg:"The sound of chatter and laughter can be heard from all the houses."}

			],
			outdoors: true,
			exits: [
				{
					cmd: 'down',
					id: '1',
					area: 'Midgaard'
				}
			]
		}
	]
};
<commit_msg>Touch ups<commit_after>//Use GreyHawk DnD campaign map as referance.
//TODO: Make merchants
'use strict';
var Cmd = require('../src/commands').cmd,
Room = require('../src/rooms').room,
World = require('../src/world').world;

module.exports = {
	name: 'Greyhawk_City',
	id: '4',
	type: 'outside',
	levels: 'All',
	description: 'A vast cityscape with infinite possiblities',
	reloads: 0,
	author: 'Sam Bolton (Anorak)',
	messages: [
		{msg: 'A cool breeze blows through the streets of Greyhawk city.'},
		{msg: 'The bustle of the city can be distracting. Keep an eye out for thieves.'}
	],
	rooms: [
		{
			id: '1',
			title: 'Greyhawk City main square',
			area: 'Greyhawk City',
			content: 'A busy hustling market square. To the NORTH you can see a residential area.',
			outdoors: true,
			exits: [
				{
					cmd: 'north',
					id: '2',
					area: 'Greyhawk_City'
				}
			],
			monsters: [{
				name: 'InfoBroker',
				displayName: 'Grey Hawk Info Broker',
				charClass: 'theif',
				level: 35,
				short: 'Info Broker',
				long: 'Info Broker, a decent looking man with washed back hair.',
				description: 'A fine looking man with wased back hair, wearing a suit',
				inName: 'InfoBroker',
				race: 'human',
				id: 10005,
				area: 'Greyhawk_City',
				weight: 195,
				diceNum: 3,
				diceSides: 10,
				diceMod: 5,
				str: 20,
				dex: 18,
				position: 'standing',
				attackType: 'punch',
				damRoll: 20,
				hitRoll: 15,
				ac: 20,
				items: [],
				trainer: true,
				behaviors: [{
					module: 'InfoBroker1'
				}]
			}],
			items : [
				{
					name: 'Torch',
					short: 'a wooden torch',
					long: 'A wooden torch rests on the ground' ,
					area: 'Greyhawk_City',
					id: '104',
					level: 1,
					itemType: 'weapon',
					material: 'wood',
					weaponType: 'club',
					diceNum: 1,
					diceSides: 2,
					diceMod: -1,
					attackType: 'smash',
					ac: -1,
					weight: 1,
					slot: 'hands',
					equipped: false,
					light: true,
					lightDecay: 10,
					flickerMsg: '',
					extinguishMsg: '',
					spawn: 3,
					flags: [],
					beforeDrop: function(item, roomObj) {
						return true;
					}
				}
			]
		},
		{
			id: '2',
			title: 'Greyhawk City residential area',
			area: 'Greyhawk City',
			content: 'A calm area with some houses around.',
			messages: [
					{msg:"The sound of chatter and laughter can be heard from all the houses."}

			],
			outdoors: true,
			exits: [
				{
					cmd: 'down',
					id: '1',
					area: 'Midgaard'
				}
			]
		}
	]
};
<|endoftext|>


<commit_before>var assert = require("assert")
var cookies = require('../index');

var url = 'http://www.example.com';

// these are simple tests
describe('CookieJar', function() {
  describe('add', function() {
    it("using a Cookie object", function(){
      var jar = new cookies.CookieJar();
      var c = new cookies.Cookie('foo=bar');
      jar.add(c, url);
      jar.getCookieHeaderString(url, function(error, header){
         assert(header === 'foo=bar');
      });
    });

    it("using a cookie string", function(){
      var jar = new cookies.CookieJar();
      jar.add('foo=bar', url);
      jar.getCookieHeaderString(url, function(error, header){
         assert(header === 'foo=bar');
      });
    });

    it("using a json object", function(){
      var jar = new cookies.CookieJar();
      jar.add({key:'foo', value:'bar'}, url);
      jar.getCookieHeaderString(url, function(error, header){
         assert(header === 'foo=bar');
      });
    });
  });

  describe('remove', function() {
    it('should not exist in jar', function(){
      var jar = new cookies.CookieJar();
      jar.add('foo=bar', url);
      jar.getCookieHeaderString(url, function(error, header){
        assert(header === 'foo=bar');
        jar.remove(url);
        jar.getCookieHeaderString(url, function(error, header){
          assert(header === '');
        })
      });
    });
  });

  describe('getCookies', function() {
    it('should find cookies that match the domain', function(){
      var jar = new cookies.CookieJar();
      jar.add('foo=bar', url);
      jar.getCookies(url, function(error, cookies){
        assert(cookies.length === 1);
        assert(cookies[0].getCookieHeaderString() === 'foo=bar');
      });
    });
  });

  // describe('toJSON', function() {
  //   it("should output a json representation", function(){
  //     var c = new cookies.Cookie('foo=bar');
  //     assert(c.toJSON().key === 'foo');
  //     assert(c.toJSON().value === 'bar');
  //   });
  // });
});<commit_msg>removing dead code<commit_after>var assert = require("assert")
var cookies = require('../index');

var url = 'http://www.example.com';

// these are simple tests
describe('CookieJar', function() {
  describe('add', function() {
    it("using a Cookie object", function(){
      var jar = new cookies.CookieJar();
      var c = new cookies.Cookie('foo=bar');
      jar.add(c, url);
      jar.getCookieHeaderString(url, function(error, header){
         assert(header === 'foo=bar');
      });
    });

    it("using a cookie string", function(){
      var jar = new cookies.CookieJar();
      jar.add('foo=bar', url);
      jar.getCookieHeaderString(url, function(error, header){
         assert(header === 'foo=bar');
      });
    });

    it("using a json object", function(){
      var jar = new cookies.CookieJar();
      jar.add({key:'foo', value:'bar'}, url);
      jar.getCookieHeaderString(url, function(error, header){
         assert(header === 'foo=bar');
      });
    });
  });

  describe('remove', function() {
    it('should not exist in jar', function(){
      var jar = new cookies.CookieJar();
      jar.add('foo=bar', url);
      jar.getCookieHeaderString(url, function(error, header){
        assert(header === 'foo=bar');
        jar.remove(url);
        jar.getCookieHeaderString(url, function(error, header){
          assert(header === '');
        })
      });
    });
  });

  describe('getCookies', function() {
    it('should find cookies that match the domain', function(){
      var jar = new cookies.CookieJar();
      jar.add('foo=bar', url);
      jar.getCookies(url, function(error, cookies){
        assert(cookies.length === 1);
        assert(cookies[0].getCookieHeaderString() === 'foo=bar');
      });
    });
  });
});<|endoftext|>


<commit_before>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var fse = require('fs-extra');
var ngit = require('nodegit');
var remote = require('gift');
var _ = require('lodash');
var exec = require('child_process').exec;
var assert = require('assert');

exports.clone = function(url, path, cb) {
  remote.clone(url, path, function(err, repo) {
    cb(err, repo);
  });
};

exports.push = function(path, cb) {
  var repo = remote(path);
  repo.remote_push('origin', 'master', function(err) {
    cb(err);
  });
};

exports.sync = function(path, cb) {
  var repo = remote(path);
  repo.sync(function(err) {
    cb(err);
  });
};

exports.remoteAdd = function(path, url, cb) {
  var repo = remote(path);
  repo.remote_add('origin', url, function(err) {
    cb(err);
  });
};

var addFiles = function(repoPath, cb) {
  exec('git add --all', {cwd: repoPath}, function(err) {
    if (err) { return cb(err); }
    cb(null);
  });
};

/**
 * commits array of files to specified repository with given commit log message
 */
exports.commit = function(repoPath, message, authorName, authorMail, cb) {
  assert(repoPath);
  assert(message);
  assert(authorName);
  assert(authorMail);
  assert(cb);

  addFiles(repoPath, function(err) {
    if (err) { return cb(err); }
    ngit.Repo.open(repoPath, function(err, repo) {
      if (err) { return cb(err); }
      repo.openIndex(function(err, index) {
        if (err) { return cb(err); }
        index.write(function(err) {
          if (err) { return cb(err); }
          index.writeTree(function(err, oid) {
            if (err) { return cb(err); }
            ngit.Reference.oidForName(repo, 'HEAD', function(err, head) {
              var author = ngit.Signature.now(authorName || 'nscale', authorMail || 'info@nscale');
              var committer = ngit.Signature.now(authorName || 'nscale', authorMail || 'info@nscale');
              if (head) {
                repo.getCommit(head, function(err, prnt) {
                  if (err) { return cb(err); }
                  repo.createCommit('HEAD', author, committer, message, oid, [prnt], function(err, commitId) {
                    cb(err, commitId);
                  });
                });
              }
              else {
                repo.createCommit('HEAD', author, committer, message, oid, [], function(err, commitId) {
                  cb(err, commitId);
                });
              }
            });
          });
        });
      });
    });
  });
};

/**
 * create a new repository
 */
exports.createRepository = function(repoPath, authorName, authorMail, cb) {
  fse.mkdirpSync(repoPath);
  ngit.Repo.init(repoPath, false, function(err) {
    if (err) { return cb(err); }
    exports.commit(repoPath, 'first commit', authorName, authorMail, function(err, commitId) {
      cb(err, commitId);
    });
  });
};

/**
 * make commit on initial clone
 */
exports.initClonedRepo = function(repoPath, authorName, authorMail, cb) {
  exports.commit(repoPath, 'first commit', authorName, authorMail, function(err, commitId) {
    cb(err, commitId);
  });
};

/**
 * get a specific revision of a file
 */
exports.getFileRevision = function(repoPath, revisionId, file, cb) {
  ngit.Repo.open(repoPath, function(err, repo) {
    if (err) { return cb(err); }
    repo.getCommit(revisionId, function(err, commit) {
      if (err) { return cb(err); }
      commit.getEntry(file, function(err, entry) {
        if (err) { return cb(err); }
        entry.getBlob(function(err, blob) {
          cb(err, blob.toString());
        });
      });
    });
  });
};

/**
 * there appears to be no simple method to get the current branch using nodegit
 * therefore resorted to spawning the client - this needs to be replaced by a fix to nodegit
 */
var getCurrentBranchName = function(repoPath, cb) {
  exec('git branch ', {cwd: repoPath}, function(err, stdout) {
    if (err) { return cb(err); }
    var branch = _.find(stdout.split('\n'), function(line) { return line.indexOf('*') !== -1; }).substring(2).trim();
    cb(null, branch);
  });
};

/**
 * list all of the available revisions in the system
 */
exports.listRevisions = function(repoPath, cb) {
  var revisions = [];

  ngit.Repo.open(repoPath, function(err, repo) {
    if (err) { return cb(err); }
    getCurrentBranchName(repoPath, function(err, branchName) {
      if (err) { return cb(err); }
      repo.getBranch(branchName, function(err, branch) {
        if (err) { return cb(err); }

        var history = branch.history();
        history.on('commit', function(commit) {
          var result = {id: commit.sha(),
                        author: commit.author().name() + ' <' + commit.author().email() + '>',
                        date: commit.date(),
                        message: commit.message()};
          revisions.push(result);
        });
        history.on('end', function() {
          cb(null, revisions);
        });
        history.start();
      });
    });
  });
};

<commit_msg>Jshint ignore gift non-camelcase functions.<commit_after>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var fse = require('fs-extra');
var ngit = require('nodegit');
var remote = require('gift');
var _ = require('lodash');
var exec = require('child_process').exec;
var assert = require('assert');

exports.clone = function(url, path, cb) {
  remote.clone(url, path, function(err, repo) {
    cb(err, repo);
  });
};

exports.push = function(path, cb) {
  /*jshint camelcase: false */
  var repo = remote(path);
  repo.remote_push('origin', 'master', function(err) {
    cb(err);
  });
};

exports.sync = function(path, cb) {
  var repo = remote(path);
  repo.sync(function(err) {
    cb(err);
  });
};

exports.remoteAdd = function(path, url, cb) {
  /*jshint camelcase: false */
  var repo = remote(path);
  repo.remote_add('origin', url, function(err) {
    cb(err);
  });
};

var addFiles = function(repoPath, cb) {
  exec('git add --all', {cwd: repoPath}, function(err) {
    if (err) { return cb(err); }
    cb(null);
  });
};

/**
 * commits array of files to specified repository with given commit log message
 */
exports.commit = function(repoPath, message, authorName, authorMail, cb) {
  assert(repoPath);
  assert(message);
  assert(authorName);
  assert(authorMail);
  assert(cb);

  addFiles(repoPath, function(err) {
    if (err) { return cb(err); }
    ngit.Repo.open(repoPath, function(err, repo) {
      if (err) { return cb(err); }
      repo.openIndex(function(err, index) {
        if (err) { return cb(err); }
        index.write(function(err) {
          if (err) { return cb(err); }
          index.writeTree(function(err, oid) {
            if (err) { return cb(err); }
            ngit.Reference.oidForName(repo, 'HEAD', function(err, head) {
              var author = ngit.Signature.now(authorName || 'nscale', authorMail || 'info@nscale');
              var committer = ngit.Signature.now(authorName || 'nscale', authorMail || 'info@nscale');
              if (head) {
                repo.getCommit(head, function(err, prnt) {
                  if (err) { return cb(err); }
                  repo.createCommit('HEAD', author, committer, message, oid, [prnt], function(err, commitId) {
                    cb(err, commitId);
                  });
                });
              }
              else {
                repo.createCommit('HEAD', author, committer, message, oid, [], function(err, commitId) {
                  cb(err, commitId);
                });
              }
            });
          });
        });
      });
    });
  });
};

/**
 * create a new repository
 */
exports.createRepository = function(repoPath, authorName, authorMail, cb) {
  fse.mkdirpSync(repoPath);
  ngit.Repo.init(repoPath, false, function(err) {
    if (err) { return cb(err); }
    exports.commit(repoPath, 'first commit', authorName, authorMail, function(err, commitId) {
      cb(err, commitId);
    });
  });
};

/**
 * make commit on initial clone
 */
exports.initClonedRepo = function(repoPath, authorName, authorMail, cb) {
  exports.commit(repoPath, 'first commit', authorName, authorMail, function(err, commitId) {
    cb(err, commitId);
  });
};

/**
 * get a specific revision of a file
 */
exports.getFileRevision = function(repoPath, revisionId, file, cb) {
  ngit.Repo.open(repoPath, function(err, repo) {
    if (err) { return cb(err); }
    repo.getCommit(revisionId, function(err, commit) {
      if (err) { return cb(err); }
      commit.getEntry(file, function(err, entry) {
        if (err) { return cb(err); }
        entry.getBlob(function(err, blob) {
          cb(err, blob.toString());
        });
      });
    });
  });
};

/**
 * there appears to be no simple method to get the current branch using nodegit
 * therefore resorted to spawning the client - this needs to be replaced by a fix to nodegit
 */
var getCurrentBranchName = function(repoPath, cb) {
  exec('git branch ', {cwd: repoPath}, function(err, stdout) {
    if (err) { return cb(err); }
    var branch = _.find(stdout.split('\n'), function(line) { return line.indexOf('*') !== -1; }).substring(2).trim();
    cb(null, branch);
  });
};

/**
 * list all of the available revisions in the system
 */
exports.listRevisions = function(repoPath, cb) {
  var revisions = [];

  ngit.Repo.open(repoPath, function(err, repo) {
    if (err) { return cb(err); }
    getCurrentBranchName(repoPath, function(err, branchName) {
      if (err) { return cb(err); }
      repo.getBranch(branchName, function(err, branch) {
        if (err) { return cb(err); }

        var history = branch.history();
        history.on('commit', function(commit) {
          var result = {id: commit.sha(),
                        author: commit.author().name() + ' <' + commit.author().email() + '>',
                        date: commit.date(),
                        message: commit.message()};
          revisions.push(result);
        });
        history.on('end', function() {
          cb(null, revisions);
        });
        history.start();
      });
    });
  });
};

<|endoftext|>


<commit_before>// ─────────────────────────────────────────────────────────────────────────────
// import
// ─────────────────────────────────────────────────────────────────────────────

import styled from 'styled-components';
import { fadeOutAnimation } from '../../utils';

// ─────────────────────────────────────────────────────────────────────────────
// component
// ─────────────────────────────────────────────────────────────────────────────

export default styled.div(
  {
    position:  'fixed',
    left:      0,
    right:     0,
    padding:   '1rem',
    textAlign: 'center',
    zIndex:    'var(--z-index-popover)',
    animation: `250ms ${fadeOutAnimation} forwards`,
  },
  ({
    duration = 1000,
    color = 'white',
    backgroundColor = 'var(--color-success)',
    bottom = 'auto',
    top = '0',
  }) => ({
    animationDelay: `${duration - 250}ms`,
    color,
    backgroundColor,
    bottom,
    top,
  }),
);
<commit_msg>update popup component props logic<commit_after>// ─────────────────────────────────────────────────────────────────────────────
// import
// ─────────────────────────────────────────────────────────────────────────────

import styled from 'styled-components';
import { fadeOutAnimation, mediaQuerise } from '../../utils';

// ─────────────────────────────────────────────────────────────────────────────
// component
// ─────────────────────────────────────────────────────────────────────────────

export default styled.div(
  {
    position:  'fixed',
    left:      0,
    right:     0,
    padding:   '1rem',
    textAlign: 'center',
    zIndex:    'var(--z-index-popover)',
  },
  ({
    duration = 1000,
    color = 'white',
    backgroundColor = 'var(--color-success)',
    fontSize,
    bottom = 'auto',
    top = '0',
    animation = `250ms ${fadeOutAnimation} forwards`,
  }) => ({
    color,
    backgroundColor,
    fontSize,
    ...mediaQuerise({ bottom, top }),
    animation,
    animationDelay: `${duration - 250}ms`,
  }),
);
<|endoftext|>