<commit_before>'use strict';
var _ = require('lodash');

var utils = require('./utils');
var expect = utils.expect;

var TT = require('../');

describe('Thin Tree', function() {
    var raw = {};
    beforeEach(function() {

    });

    it('should create a tree', function() {
        var tree = new TT({
            name: "Eve",
            children: [
                {
                    name: "Alice"
                }
            ]
        });
        expect(tree.name).to.equal("Eve");
        expect(tree.children).to.be.array;
        expect(tree.children[0].name).to.equal("Alice");
        expect(tree.hasChildren()).to.equal(true);
    });

    describe('Inheritance', function() {
        var First, Second, Third;
        beforeEach(function() {
            First = TT.extend({
                type: 'first',
                first: true,
                initialize: function() {
                    this.inheritted = "roar" + Math.random();
                    this.beforeInit = "first";
                    First.__super__.initialize.call(this);
                    this.afterInit = "first";
                },
                getType: function() {
                    return this.type;
                }
            });

            Second = First.extend({
                type: 'second',
                second: true,
                initialize: function() {
                    this.beforeInit = "second";
                    Second.__super__.initialize.call(this);
                    this.afterInit = "second";
                },
                getType: function() {
                    return [this.type, Second.__super__.getType()].join(':');
                    // return this.type + (this.super().getType())
                }
            });

        });

        it('should inherit parents methods', function() {
            var first = new First();
            expect(first.constructor.__super__).to.equal(TT.prototype);
            expect(first.getType()).to.equal('first')
        });

        it('should inherit ancestor methods', function() {
            var second = new Second();
            expect(second.__super__).to.equal(First.prototype);
            expect(second.__super__.__super__).to.equal(TT.prototype);

            expect(second.type).to.equal('second');
            expect(second.__super__.type).to.equal('first');
            expect(second.__super__.__super__.type).to.be.undefined
            expect(second.beforeInit).to.equal("first");
            expect(second.afterInit).to.equal("second");

            expect(second.__model__).to.equal(Second);
            expect(second.__super__).to.equal(First.prototype);
            expect(second.__super__.__model__).to.equal(First);
            expect(second.__super__.__super__).to.equal(TT.prototype);
            expect(second.__super__.__super__.__model__).to.be.undefined

            expect(second.getType()).to.equal("second:first");
            expect(second.__super__.getType()).to.equal("first");
        })
    });

    describe('Children', function() {
        it('should report hasChildren correctly', function() {
            var tree = new TT({
                name: "Eve",
                children: [
                    {
                        name: "Alice"
                    }
                ]
            });

            expect(tree.children).to.be.array;
            expect(tree.hasChildren()).to.equal(true);
            expect(tree.children[0].hasChildren()).to.equal(false)
        });

        it('should allow changing the recursive key', function() {
            var tree = new TT({
                name: "Eve",
                _key: "eschers",
                eschers: [
                    {
                        name: "Alice",
                        eschers: [
                            {
                                _key: "schroedingers",
                                name: "Turtle",
                                schroedingers: [
                                    {
                                        name: "Cat"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            });

            expect(tree.getChildren()).to.be.array;
            expect(tree.hasChildren()).to.equal(true);
            expect(tree.getChildren()[0].children).to.equal(undefined);
            var turtle = tree.getChildren()[0].getChildren()[0];
            expect(turtle.name).to.equal("Turtle");
            expect(turtle.eschers).to.equal(undefined);
            expect(turtle.hasChildren()).to.equal(true);
            expect(turtle.getChildren()[0].name).to.equal("Cat");
            expect(turtle.getChildren()[0].hasChildren()).to.equal(false);
        });
    });

    describe('ancestors', function () {
        var tree;
        var childRBBC;
        beforeEach(function() {
            tree = new TT({
                name: "R",
                children: [
                    { name: "RA" },
                    { name: "RB",
                        children: [
                            { name: "RBA" },
                            { name: "RBB",
                                children: [
                                    { name: "RBBC" } ]} ]},
                    { name: "RC"} ]}
            );
            childRBBC = tree.children[1].children[1].children[0];
        });

        it("creates array of ancestors", function () {
            var ancestors;
            ancestors = tree.getAncestors();
            expect(ancestors.length).to.equal(0);

            ancestors = childRBBC.getAncestors();
            expect(ancestors.length).to.equal(3);
            expect(ancestors[0].name).to.equal('RBB')
            expect(ancestors[1].name).to.equal('RB')
            expect(ancestors[2].name).to.equal('R')
        })
    });

    describe('PreOrder Traverse', function() {
        var complexTree, preOrderNames;

        beforeEach(function() {
           complexTree = new TT({
                name: "R",
                children: [{
                    name: "RA"
                }, {
                    name: "RB",
                    children: [{
                        name: "RBA"
                    },{
                        name: "RBB"
                    }]
                }, {
                    name: "RC"
                }]
            });
            preOrderNames = ["R", "RA", "RB", "RBA", "RBB", "RC"]
        });

        it('should work for a single node', function() {
            var tree = new TT({
                name: "Foo",
                children: []
            });

            expect(tree.preOrderTraverse()).to.be.array;
            expect(tree.preOrderTraverse().length).to.equal(1);
            expect(tree.preOrderNext()).to.be.equal(null);
        });

        it('should traverse a complex complexTree in pre order', function() {
            expect(complexTree.preOrderTraverse()).to.be.array;
            expect(complexTree.preOrderTraverse().length).to.equal(6);
            expect(complexTree.preOrderNext().name).to.be.equal("RA");

            var traverse = complexTree.preOrderTraverse();
            expect(traverse.length).to.equal(6);
            for (var i = 0; i < traverse.length; i++) {
                expect(traverse[i].name).to.equal(preOrderNames[i]);
            }
        });

        it('should be walkable with preOrderNext() from root', function() {
            var nextNode = complexTree;
            expect(nextNode.name).to.equal(preOrderNames[0]);

            for (var i = 1; i < preOrderNames.length; i++) {
                nextNode = nextNode.preOrderNext();
                expect(nextNode.name)
                    .to.equal(preOrderNames[i]);
            }
        });

        it('should be walkable with preOrderNext() from child', function() {
            var rbaNode = complexTree.getChildren()[1].getChildren()[0];
            expect(rbaNode.preOrderNext().name).to.equal("RBB");
            expect(rbaNode.preOrderNext()
                          .preOrderNext().name).to.equal("RC");
        });

        it('should be walkable with preOrderPrevious() from child', function() {
            var rcNode = complexTree.getChildren()[2];
            expect(rcNode.preOrderPrevious().name).to.equal("RBB");

            expect(rcNode.preOrderPrevious()
                          .preOrderPrevious().name).to.equal("RBA");

            expect(rcNode.preOrderPrevious()
                          .preOrderPrevious()
                          .preOrderPrevious().name).to.equal("RB");
        });
    });

    describe("Serialization", function() {
        var tree, flattened;

        beforeEach(function() {
            tree = new TT({
                name: "Eve",
                _key: "eschers",
                eschers: [
                    {
                        name: "Alice",
                        eschers: [
                            {
                                _key: "schroedingers",
                                name: "Turtle",
                                schroedingers: [
                                    {
                                        name: "Cat"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            });
            flattened = tree.flatten();
        });

        it("should remove properties prefixed with '_'", function(){
            _.each(tree.flatten(), function(node){
                var prefixedKeys = _(node.toJSON()).keys().filter(function(key){
                    return key[0] === '_';
                });
                expect(prefixedKeys.size()).to.equal(0);
            });
        });

        it("should remove circular references", function(){
            _.each(flattened, function(node) {
                var serialized = node.toJSON();
                expect(serialized.root).to.be.undefined;
                expect(serialized.parent).to.be.undefined;
            })
        });
    });
});
<commit_msg>Adds tests for preOrderPreceding and preOrderFollowing.<commit_after>'use strict';
var _ = require('lodash');

var utils = require('./utils');
var expect = utils.expect;

var TT = require('../');

describe('Thin Tree', function() {
    var raw = {};
    beforeEach(function() {

    });

    it('should create a tree', function() {
        var tree = new TT({
            name: "Eve",
            children: [
                {
                    name: "Alice"
                }
            ]
        });
        expect(tree.name).to.equal("Eve");
        expect(tree.children).to.be.array;
        expect(tree.children[0].name).to.equal("Alice");
        expect(tree.hasChildren()).to.equal(true);
    });

    describe('Inheritance', function() {
        var First, Second, Third;
        beforeEach(function() {
            First = TT.extend({
                type: 'first',
                first: true,
                initialize: function() {
                    this.inheritted = "roar" + Math.random();
                    this.beforeInit = "first";
                    First.__super__.initialize.call(this);
                    this.afterInit = "first";
                },
                getType: function() {
                    return this.type;
                }
            });

            Second = First.extend({
                type: 'second',
                second: true,
                initialize: function() {
                    this.beforeInit = "second";
                    Second.__super__.initialize.call(this);
                    this.afterInit = "second";
                },
                getType: function() {
                    return [this.type, Second.__super__.getType()].join(':');
                    // return this.type + (this.super().getType())
                }
            });

        });

        it('should inherit parents methods', function() {
            var first = new First();
            expect(first.constructor.__super__).to.equal(TT.prototype);
            expect(first.getType()).to.equal('first')
        });

        it('should inherit ancestor methods', function() {
            var second = new Second();
            expect(second.__super__).to.equal(First.prototype);
            expect(second.__super__.__super__).to.equal(TT.prototype);

            expect(second.type).to.equal('second');
            expect(second.__super__.type).to.equal('first');
            expect(second.__super__.__super__.type).to.be.undefined
            expect(second.beforeInit).to.equal("first");
            expect(second.afterInit).to.equal("second");

            expect(second.__model__).to.equal(Second);
            expect(second.__super__).to.equal(First.prototype);
            expect(second.__super__.__model__).to.equal(First);
            expect(second.__super__.__super__).to.equal(TT.prototype);
            expect(second.__super__.__super__.__model__).to.be.undefined

            expect(second.getType()).to.equal("second:first");
            expect(second.__super__.getType()).to.equal("first");
        })
    });

    describe('Children', function() {
        it('should report hasChildren correctly', function() {
            var tree = new TT({
                name: "Eve",
                children: [
                    {
                        name: "Alice"
                    }
                ]
            });

            expect(tree.children).to.be.array;
            expect(tree.hasChildren()).to.equal(true);
            expect(tree.children[0].hasChildren()).to.equal(false)
        });

        it('should allow changing the recursive key', function() {
            var tree = new TT({
                name: "Eve",
                _key: "eschers",
                eschers: [
                    {
                        name: "Alice",
                        eschers: [
                            {
                                _key: "schroedingers",
                                name: "Turtle",
                                schroedingers: [
                                    {
                                        name: "Cat"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            });

            expect(tree.getChildren()).to.be.array;
            expect(tree.hasChildren()).to.equal(true);
            expect(tree.getChildren()[0].children).to.equal(undefined);
            var turtle = tree.getChildren()[0].getChildren()[0];
            expect(turtle.name).to.equal("Turtle");
            expect(turtle.eschers).to.equal(undefined);
            expect(turtle.hasChildren()).to.equal(true);
            expect(turtle.getChildren()[0].name).to.equal("Cat");
            expect(turtle.getChildren()[0].hasChildren()).to.equal(false);
        });
    });

    describe('ancestors', function () {
        var tree;
        var childRBBC;
        beforeEach(function() {
            tree = new TT({
                name: "R",
                children: [
                    { name: "RA" },
                    { name: "RB",
                        children: [
                            { name: "RBA" },
                            { name: "RBB",
                                children: [
                                    { name: "RBBC" } ]} ]},
                    { name: "RC"} ]}
            );
            childRBBC = tree.children[1].children[1].children[0];
        });

        it("creates array of ancestors", function () {
            var ancestors;
            ancestors = tree.getAncestors();
            expect(ancestors.length).to.equal(0);

            ancestors = childRBBC.getAncestors();
            expect(ancestors.length).to.equal(3);
            expect(ancestors[0].name).to.equal('RBB')
            expect(ancestors[1].name).to.equal('RB')
            expect(ancestors[2].name).to.equal('R')
        })
    });

    describe('PreOrder Traverse', function() {
        var complexTree, preOrderNames;

        beforeEach(function() {
           complexTree = new TT({
                name: "R",
                children: [{
                    name: "RA"
                }, {
                    name: "RB",
                    children: [{
                        name: "RBA"
                    },{
                        name: "RBB"
                    }]
                }, {
                    name: "RC"
                }]
            });
            preOrderNames = ["R", "RA", "RB", "RBA", "RBB", "RC"]
        });

        it('should work for a single node', function() {
            var tree = new TT({
                name: "Foo",
                children: []
            });

            expect(tree.preOrderTraverse()).to.be.array;
            expect(tree.preOrderTraverse().length).to.equal(1);
            expect(tree.preOrderNext()).to.be.equal(null);
        });

        it('should traverse a complex complexTree in pre order', function() {
            expect(complexTree.preOrderTraverse()).to.be.array;
            expect(complexTree.preOrderTraverse().length).to.equal(6);
            expect(complexTree.preOrderNext().name).to.be.equal("RA");

            var traverse = complexTree.preOrderTraverse();
            expect(traverse.length).to.equal(6);
            for (var i = 0; i < traverse.length; i++) {
                expect(traverse[i].name).to.equal(preOrderNames[i]);
            }
        });

        it('should be walkable with preOrderNext() from root', function() {
            var nextNode = complexTree;
            expect(nextNode.name).to.equal(preOrderNames[0]);

            for (var i = 1; i < preOrderNames.length; i++) {
                nextNode = nextNode.preOrderNext();
                expect(nextNode.name)
                    .to.equal(preOrderNames[i]);
            }
        });

        it('should be walkable with preOrderNext() from child', function() {
            var rbaNode = complexTree.getChildren()[1].getChildren()[0];
            expect(rbaNode.preOrderNext().name).to.equal("RBB");
            expect(rbaNode.preOrderNext()
                          .preOrderNext().name).to.equal("RC");
        });

        it('should be walkable with preOrderPrevious() from child', function() {
            var rcNode = complexTree.getChildren()[2];
            expect(rcNode.preOrderPrevious().name).to.equal("RBB");

            expect(rcNode.preOrderPrevious()
                          .preOrderPrevious().name).to.equal("RBA");

            expect(rcNode.preOrderPrevious()
                          .preOrderPrevious()
                          .preOrderPrevious().name).to.equal("RB");
        });

        it('should return the preceding nodes with preOrderPreceding() from child', function() {

            var rbaNode = _.find(complexTree.preOrderTraverse(), {name: "RBB"});
            var preceding = _(rbaNode.preOrderPreceding());

            expect(preceding.size()).to.equal(4)
            expect(preceding.first().name).to.equal("RBA");
            expect(preceding.last().name).to.equal("R");
        });

        it('should return the following nodes with preOrderPreceding() from child', function() {

            var rbaNode = _.find(complexTree.preOrderTraverse(), {name: "RBA"});
            var preceding = _(rbaNode.preOrderFollowing());

            expect(preceding.size()).to.equal(2)
            expect(preceding.first().name).to.equal("RBB");
            expect(preceding.last().name).to.equal("RC");
        });
    });

    describe("Serialization", function() {
        var tree, flattened;

        beforeEach(function() {
            tree = new TT({
                name: "Eve",
                _key: "eschers",
                eschers: [
                    {
                        name: "Alice",
                        eschers: [
                            {
                                _key: "schroedingers",
                                name: "Turtle",
                                schroedingers: [
                                    {
                                        name: "Cat"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            });
            flattened = tree.flatten();
        });

        it("should remove properties prefixed with '_'", function(){
            _.each(tree.flatten(), function(node){
                var prefixedKeys = _(node.toJSON()).keys().filter(function(key){
                    return key[0] === '_';
                });
                expect(prefixedKeys.size()).to.equal(0);
            });
        });

        it("should remove circular references", function(){
            _.each(flattened, function(node) {
                var serialized = node.toJSON();
                expect(serialized.root).to.be.undefined;
                expect(serialized.parent).to.be.undefined;
            })
        });
    });
});
<|endoftext|>


<commit_before>$(function() {
    "use strict";

    var opt = {
        'row': 1,
        'noedit': false,
        'nomask': false,
        'export': false,
        'data': ""
    };

    var current_row = 0;
    var mouse_tracking;
    var touch_tracking = [];

    // http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript
    function is_touch_device() {
        return !!('ontouchstart' in window) // works on most browsers
            || !!('onmsgesturechange' in window); // works on ie10
    }

    function toggle_panel_color(panel) {
        if ($(panel).hasClass("black") || $(panel).hasClass("white")) {
            $(panel).toggleClass("black white");
        }
        else {
            $(panel).addClass("white invisible-text");
        }
    }

    function unmagnify_row(i, duration, delay) {
        duration /= 1000;
        delay /= 1000;
        var row = $('#row' + i);
        row.css({
            'transition-duration': '0.001s, ' + duration + 's, ' + duration + 's, ' + duration + 's, ' + duration + 's',
            'transition-delay': delay + 's'
        });
        row.removeClass('magnified');
    }

    function magnify_row(i, duration, delay) {
        duration /= 1000;
        delay /= 1000;
        var row = $('#row' + i);
        row.css({
            'transition-duration': '0.001s, ' + duration + 's, ' + duration + 's, ' + duration + 's, ' + duration + 's',
            'transition-delay': delay + 's'
        });
        row.addClass('magnified');
    }

    function move_focus(i) {
        var row = $('#row' + i);

        var unmasked_top = row.position().top;
        var unmasked_bottom = unmasked_top + row.outerHeight();

        var upper_mask = $('#upper-mask');
        var lower_mask = $('#lower-mask');
        upper_mask.css('transform', 'translate3d(0px, ' + (unmasked_top - upper_mask.outerHeight()) + 'px, 0px)');
        lower_mask.css('transform', 'translate3d(0px, ' + unmasked_bottom + 'px, 0px)');
    }

    function move_cursor_button(i) {
        var row = $('#row' + i);

        var unmasked_top = row.position().top;
        var unmasked_bottom = unmasked_top + row.outerHeight();

        var scaled_top = unmasked_top - 0.3 * 40 / 2;
        var scaled_bottom = unmasked_bottom + 0.3 * 40 / 2;
        var scaled_left = -0.3 * row.outerWidth() / 2;

        var space = 10;

        var prev_button = $('#prev-button');
        var next_button = $('#next-button');
        prev_button.css('transform',
            'translate3d(' +
                (scaled_left - 1.3 * 60 / 2 - prev_button.outerWidth() / 2) + 'px, ' +
                (scaled_top - 40 / 2 - space) + 'px, ' +
                '0) ' +
            'rotate(45deg)');
        next_button.css('transform',
            'translate3d(' +
                (scaled_left - 1.3 * 60 / 2 - next_button.outerWidth() / 2) + 'px, ' +
                (scaled_bottom - 40 / 2 + space) + 'px, ' +
                '0) ' +
            'rotate(45deg)'
        );
    }

    function initialize_mask_transformations() {
        var board_height = $('#board').outerHeight();

        $('#upper-mask').css('transform', 'translate3d(0px, ' + (-board_height) + 'px, 0px)');
        $('#lower-mask').css('transform', 'translate3d(0px, ' + board_height + 'px, 0px)');
    }

    function select_row(i) {
        unmagnify_row(current_row, 400, 0);
        current_row = i;
        move_focus(current_row);
        move_cursor_button(current_row);
        magnify_row(current_row, 400, 400);
    }

    function on_panel_mousedown(e) {
        mouse_tracking = { target: this };
        toggle_panel_color(this);
    }

    function on_panel_mousemove(e) {
        if (mouse_tracking && mouse_tracking.target !== this) {
            toggle_panel_color(this);
            mouse_tracking.target = this;
        }
    }

    function on_panel_mouseup(e) {
        mouse_tracking = null;
    }

    function on_panel_touchstart(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            var target = document.elementFromPoint(t.clientX, t.clientY);
            if ($(target).hasClass('panel')) {
                touch_tracking[t.identifier] = { target: target };
                toggle_panel_color(target);
            }
        });
    }

    function on_panel_touchmove(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            var target = document.elementFromPoint(t.clientX, t.clientY);
            if ($(target).hasClass('panel')) {
                if (touch_tracking[t.identifier] && touch_tracking[t.identifier].target !== target) {
                    toggle_panel_color(target);
                    touch_tracking[t.identifier].target = target;
                }
            }
        });
    }

    function on_panel_touchend(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            touch_tracking[t.identifier] = null;
        });
    }

    function change_query_string(qs, kvs) {
        $.each(kvs, function(key, value) {
            var re = new RegExp('([?&])' + key + '=[^&]+');
            if (qs.match(re)) {
                // The key is already used.
                qs = qs.replace(re, '$1' + key + '=' + value);
            }
            else {
                // The key isn't used.
                if (qs.match(/[?&]$/)) {
                    qs += key + '=' + value;
                }
                else if (qs.length > 0) {
                    qs += '&' + key + '=' + value;
                }
                else {
                    qs += '?' + key + '=' + value;
                }
            }
        });
        return qs;
    }

    function get_data() {
        var data = "";
        for (var i = 1; i <= 16; ++i) {
            for (var j = 1; j <= 16; ++j) {
                var panel = $('#panel' + i + '-' + j);

                if (panel.hasClass('white')) {
                    data += '0';
                }
                else if (panel.hasClass('black')) {
                    data += '1';
                }
                else {
                    data += '.';
                }
            }
        }
        return data;
    }

    function set_data(data) {
        for (var i = 1; i <= 16; ++i) {
            for (var j = 1; j <= 16; ++j) {
                var panel = $('#panel' + i + '-' + j);

                var k = 16 * (i - 1) + (j - 1);
                if (data[k] === '0') {
                    panel.addClass("white invisible-text");
                }
                else if (data[k] === '1') {
                    panel.addClass("black invisible-text");
                }
            }
        }
    }

    function export_data() {
        var loc = window.location;
        loc.search = change_query_string(loc.search, { 'data': get_data() });
    }

    // process options
    $.each(window.location.search.slice(1).split("&"), function(_, param) {
        var kv = param.split("=");

        switch (kv[0]) {
        case "row":
            opt.row = parseInt(kv[1]);
            break;
        case "noedit":
            opt.noedit = true;
            break;
        case "nomask":
            opt.nomask = true;
            break;
        case "export":
            opt.export = true;
            break;
        case "data":
            opt.data = kv[1];
            break;
        }
    });

    // create the board
    for (var i = 1; i <= 16; ++i) {
        var row = $('

');
        for (var j = 1; j <= 16; ++j) {
            var cell = $('

');
            var panel = $('
?
');
            panel.appendTo(cell);
            cell.appendTo(row);
        }
        row.appendTo('#board');
        var num_str = (i < 10 ? '0' : '') + i;
        $('').appendTo('#board');
    }

    if (opt.data.length > 0) {
        set_data(opt.data);
    }

    if (opt.export) {
        $('#export-button').css('display', 'block');
    }

    if (opt.nomask) {
        $('.mask').css('display', 'none');
        $('#prev-button, #next-button').css('display', 'none');
    }
    else {
        // masks
        initialize_mask_transformations();

        // initial focus
        current_row = opt.row;
        move_focus(current_row, 400, 0);
        move_cursor_button(current_row, 400, 400);
        magnify_row(current_row, 400, 400);
    }

    // events
    if (is_touch_device()) {
        // disable the overscroll effect on touch-capable environments.
        // http://www.html5rocks.com/en/mobile/touch/
        // http://stackoverflow.com/questions/2890361/disable-scrolling-in-an-iphone-web-application
        $(document).on('touchmove', function(e) {
            e.preventDefault();
        });

        if (!opt.nomask) {
            $('#prev-button').on('touchstart', function() {
                if (current_row > 1) {
                    select_row(current_row - 1);
                }
            });
            $('#next-button').on('touchstart', function() {
                if (current_row < 16) {
                    select_row(current_row + 1);
                }
            });
        }

        if (!opt.noedit) {
            $(".panel").each(function() {
                $(this).on('touchstart', on_panel_touchstart);
                $(this).on('touchmove', on_panel_touchmove);
                $(this).on('touchend', on_panel_touchend);
            });
        }
    }
    else {
        if (!opt.nomask) {
            $('#prev-button').on('click', function() {
                if (current_row > 1) {
                    select_row(current_row - 1);
                }
            });
            $('#next-button').on('click', function() {
                if (current_row < 16) {
                    select_row(current_row + 1);
                }
            });
        }

        if (!opt.noedit) {
            $(".panel").each(function() {
                $(this).on('mousedown', on_panel_mousedown);
                $(this).on('mousemove', on_panel_mousemove);
                $(this).on('mouseup', on_panel_mouseup);
            });
        }
    }

    if (opt.export) {
        $('#export-button').on('click', function() {
            export_data();
        });
    }
});
<commit_msg>Fix set_data() so that it can correctly overwrite panels' states.<commit_after>$(function() {
    "use strict";

    var opt = {
        'row': 1,
        'noedit': false,
        'nomask': false,
        'export': false,
        'data': ""
    };

    var current_row = 0;
    var mouse_tracking;
    var touch_tracking = [];

    // http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript
    function is_touch_device() {
        return !!('ontouchstart' in window) // works on most browsers
            || !!('onmsgesturechange' in window); // works on ie10
    }

    function toggle_panel_color(panel) {
        if ($(panel).hasClass("black") || $(panel).hasClass("white")) {
            $(panel).toggleClass("black white");
        }
        else {
            $(panel).addClass("white invisible-text");
        }
    }

    function unmagnify_row(i, duration, delay) {
        duration /= 1000;
        delay /= 1000;
        var row = $('#row' + i);
        row.css({
            'transition-duration': '0.001s, ' + duration + 's, ' + duration + 's, ' + duration + 's, ' + duration + 's',
            'transition-delay': delay + 's'
        });
        row.removeClass('magnified');
    }

    function magnify_row(i, duration, delay) {
        duration /= 1000;
        delay /= 1000;
        var row = $('#row' + i);
        row.css({
            'transition-duration': '0.001s, ' + duration + 's, ' + duration + 's, ' + duration + 's, ' + duration + 's',
            'transition-delay': delay + 's'
        });
        row.addClass('magnified');
    }

    function move_focus(i) {
        var row = $('#row' + i);

        var unmasked_top = row.position().top;
        var unmasked_bottom = unmasked_top + row.outerHeight();

        var upper_mask = $('#upper-mask');
        var lower_mask = $('#lower-mask');
        upper_mask.css('transform', 'translate3d(0px, ' + (unmasked_top - upper_mask.outerHeight()) + 'px, 0px)');
        lower_mask.css('transform', 'translate3d(0px, ' + unmasked_bottom + 'px, 0px)');
    }

    function move_cursor_button(i) {
        var row = $('#row' + i);

        var unmasked_top = row.position().top;
        var unmasked_bottom = unmasked_top + row.outerHeight();

        var scaled_top = unmasked_top - 0.3 * 40 / 2;
        var scaled_bottom = unmasked_bottom + 0.3 * 40 / 2;
        var scaled_left = -0.3 * row.outerWidth() / 2;

        var space = 10;

        var prev_button = $('#prev-button');
        var next_button = $('#next-button');
        prev_button.css('transform',
            'translate3d(' +
                (scaled_left - 1.3 * 60 / 2 - prev_button.outerWidth() / 2) + 'px, ' +
                (scaled_top - 40 / 2 - space) + 'px, ' +
                '0) ' +
            'rotate(45deg)');
        next_button.css('transform',
            'translate3d(' +
                (scaled_left - 1.3 * 60 / 2 - next_button.outerWidth() / 2) + 'px, ' +
                (scaled_bottom - 40 / 2 + space) + 'px, ' +
                '0) ' +
            'rotate(45deg)'
        );
    }

    function initialize_mask_transformations() {
        var board_height = $('#board').outerHeight();

        $('#upper-mask').css('transform', 'translate3d(0px, ' + (-board_height) + 'px, 0px)');
        $('#lower-mask').css('transform', 'translate3d(0px, ' + board_height + 'px, 0px)');
    }

    function select_row(i) {
        unmagnify_row(current_row, 400, 0);
        current_row = i;
        move_focus(current_row);
        move_cursor_button(current_row);
        magnify_row(current_row, 400, 400);
    }

    function on_panel_mousedown(e) {
        mouse_tracking = { target: this };
        toggle_panel_color(this);
    }

    function on_panel_mousemove(e) {
        if (mouse_tracking && mouse_tracking.target !== this) {
            toggle_panel_color(this);
            mouse_tracking.target = this;
        }
    }

    function on_panel_mouseup(e) {
        mouse_tracking = null;
    }

    function on_panel_touchstart(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            var target = document.elementFromPoint(t.clientX, t.clientY);
            if ($(target).hasClass('panel')) {
                touch_tracking[t.identifier] = { target: target };
                toggle_panel_color(target);
            }
        });
    }

    function on_panel_touchmove(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            var target = document.elementFromPoint(t.clientX, t.clientY);
            if ($(target).hasClass('panel')) {
                if (touch_tracking[t.identifier] && touch_tracking[t.identifier].target !== target) {
                    toggle_panel_color(target);
                    touch_tracking[t.identifier].target = target;
                }
            }
        });
    }

    function on_panel_touchend(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            touch_tracking[t.identifier] = null;
        });
    }

    function change_query_string(qs, kvs) {
        $.each(kvs, function(key, value) {
            var re = new RegExp('([?&])' + key + '=[^&]+');
            if (qs.match(re)) {
                // The key is already used.
                qs = qs.replace(re, '$1' + key + '=' + value);
            }
            else {
                // The key isn't used.
                if (qs.match(/[?&]$/)) {
                    qs += key + '=' + value;
                }
                else if (qs.length > 0) {
                    qs += '&' + key + '=' + value;
                }
                else {
                    qs += '?' + key + '=' + value;
                }
            }
        });
        return qs;
    }

    function get_data() {
        var data = "";
        for (var i = 1; i <= 16; ++i) {
            for (var j = 1; j <= 16; ++j) {
                var panel = $('#panel' + i + '-' + j);

                if (panel.hasClass('white')) {
                    data += '0';
                }
                else if (panel.hasClass('black')) {
                    data += '1';
                }
                else {
                    data += '.';
                }
            }
        }
        return data;
    }

    function set_data(data) {
        for (var i = 1; i <= 16; ++i) {
            for (var j = 1; j <= 16; ++j) {
                var panel = $('#panel' + i + '-' + j);

                var k = 16 * (i - 1) + (j - 1);
                if (data[k] === '0') {
                    panel.addClass("white invisible-text");
                    panel.removeClass("black");
                }
                else if (data[k] === '1') {
                    panel.addClass("black invisible-text");
                    panel.removeClass("white");
                }
                else {
                    panel.removeClass("white black invisible-text");
                }
            }
        }
    }

    function export_data() {
        var loc = window.location;
        loc.search = change_query_string(loc.search, { 'data': get_data() });
    }

    // process options
    $.each(window.location.search.slice(1).split("&"), function(_, param) {
        var kv = param.split("=");

        switch (kv[0]) {
        case "row":
            opt.row = parseInt(kv[1]);
            break;
        case "noedit":
            opt.noedit = true;
            break;
        case "nomask":
            opt.nomask = true;
            break;
        case "export":
            opt.export = true;
            break;
        case "data":
            opt.data = kv[1];
            break;
        }
    });

    // create the board
    for (var i = 1; i <= 16; ++i) {
        var row = $('

');
        for (var j = 1; j <= 16; ++j) {
            var cell = $('

');
            var panel = $('
?
');
            panel.appendTo(cell);
            cell.appendTo(row);
        }
        row.appendTo('#board');
        var num_str = (i < 10 ? '0' : '') + i;
        $('').appendTo('#board');
    }

    if (opt.data.length > 0) {
        set_data(opt.data);
    }

    if (opt.export) {
        $('#export-button').css('display', 'block');
    }

    if (opt.nomask) {
        $('.mask').css('display', 'none');
        $('#prev-button, #next-button').css('display', 'none');
    }
    else {
        // masks
        initialize_mask_transformations();

        // initial focus
        current_row = opt.row;
        move_focus(current_row, 400, 0);
        move_cursor_button(current_row, 400, 400);
        magnify_row(current_row, 400, 400);
    }

    // events
    if (is_touch_device()) {
        // disable the overscroll effect on touch-capable environments.
        // http://www.html5rocks.com/en/mobile/touch/
        // http://stackoverflow.com/questions/2890361/disable-scrolling-in-an-iphone-web-application
        $(document).on('touchmove', function(e) {
            e.preventDefault();
        });

        if (!opt.nomask) {
            $('#prev-button').on('touchstart', function() {
                if (current_row > 1) {
                    select_row(current_row - 1);
                }
            });
            $('#next-button').on('touchstart', function() {
                if (current_row < 16) {
                    select_row(current_row + 1);
                }
            });
        }

        if (!opt.noedit) {
            $(".panel").each(function() {
                $(this).on('touchstart', on_panel_touchstart);
                $(this).on('touchmove', on_panel_touchmove);
                $(this).on('touchend', on_panel_touchend);
            });
        }
    }
    else {
        if (!opt.nomask) {
            $('#prev-button').on('click', function() {
                if (current_row > 1) {
                    select_row(current_row - 1);
                }
            });
            $('#next-button').on('click', function() {
                if (current_row < 16) {
                    select_row(current_row + 1);
                }
            });
        }

        if (!opt.noedit) {
            $(".panel").each(function() {
                $(this).on('mousedown', on_panel_mousedown);
                $(this).on('mousemove', on_panel_mousemove);
                $(this).on('mouseup', on_panel_mouseup);
            });
        }
    }

    if (opt.export) {
        $('#export-button').on('click', function() {
            export_data();
        });
    }
});
<|endoftext|>


<commit_before>function decompose(endpoint) {
    // Note that we allow spaces in targets and sources but they are trimmed
    var regExp = /^(?:([\w\-]|(?:[\w\.\-]+[\w\-])?)=)?([^\|#]+)(?:#(.*))?$/;
    var matches = endpoint.match(regExp);
    var target;
    var error;

    if (!matches) {
        error = new Error('Invalid endpoint: ' + endpoint);
        error.code = 'EINVEND';
        throw error;
    }

    target = trim(matches[3]);

    return {
        name: trim(matches[1]),
        source: trim(matches[2]),
        target: isWildcard(target) ? '*' : target
    };
}

function compose(decEndpoint) {
    var name = trim(decEndpoint.name);
    var source = trim(decEndpoint.source);
    var target = trim(decEndpoint.target);
    var composed = '';

    if (name) {
        composed += name + '=';
    }

    composed += source;

    if (!isWildcard(target)) {
        composed += '#' + target;
    }

    return composed;
}

function json2decomposed(key, value) {
    var endpoint;
    var split;
    var error;

    key = trim(key);
    value = trim(value);

    if (!key) {
        error = new Error('The key must be specified');
        error.code = 'EINVEND';
        throw error;
    }

    endpoint = key + '=';
    split = value.split('#').map(trim);

    // If # was found, the source was specified
    if (split.length > 1) {
        endpoint += (split[0] || key) + '#' + split[1];
    // Check if value looks like a source
    } else if (isSource(value)) {
        endpoint += value + '#*';
    // Otherwise use the key as the source
    } else {
        endpoint += key + '#' + split[0];
    }

    return decompose(endpoint);
}

function decomposed2json(decEndpoint) {
    var error;
    var name = trim(decEndpoint.name);
    var source = trim(decEndpoint.source);
    var target = trim(decEndpoint.target);
    var value = '';
    var ret = {};

    if (!name) {
        error = new Error('Decomposed endpoint must have a name');
        error.code = 'EINVEND';
        throw error;
    }

    // Add source only if different than the name
    if  (source !== name) {
        value += source;
    }

    // If value is empty, we append the target always
    if (!value) {
        if (isWildcard(target)) {
            value += '*';
        } else {
            if (target.indexOf('/') !== -1) {
                value += '#' + target;
            } else {
                value += target;
            }
        }
    // Otherwise append only if not a wildcard or source does not look like a source
    } else if (!isWildcard(target) || !isSource(source)) {
        value += '#' + (target || '*');
    }

    ret[name] = value;

    return ret;
}

function trim(str) {
    return str ? str.trim() : '';
}

function isWildcard(target) {
    return !target || target === '*' || target === 'latest';
}

function isSource(value) {
    return (/[\/\\@]/).test(value);
}

module.exports.decompose = decompose;
module.exports.compose = compose;
module.exports.json2decomposed = json2decomposed;
module.exports.decomposed2json = decomposed2json;
<commit_msg>changed regexp to support categorization of packets by subdirectories<commit_after>function decompose(endpoint) {
    // Note that we allow spaces in targets and sources but they are trimmed
    var regExp = /^([^\|=]+)(?:=([^\|#]+))(?:#(.*))?$/;
    var matches = endpoint.match(regExp);
    var target;
    var error;

    if (!matches) {
        error = new Error('Invalid endpoint: ' + endpoint);
        error.code = 'EINVEND';
        throw error;
    }

    target = trim(matches[3]);

    return {
        name: trim(matches[1]),
        source: trim(matches[2]),
        target: isWildcard(target) ? '*' : target
    };
}

function compose(decEndpoint) {
    var name = trim(decEndpoint.name);
    var source = trim(decEndpoint.source);
    var target = trim(decEndpoint.target);
    var composed = '';

    if (name) {
        composed += name + '=';
    }

    composed += source;

    if (!isWildcard(target)) {
        composed += '#' + target;
    }

    return composed;
}

function json2decomposed(key, value) {
    var endpoint;
    var split;
    var error;

    key = trim(key);
    value = trim(value);

    if (!key) {
        error = new Error('The key must be specified');
        error.code = 'EINVEND';
        throw error;
    }

    endpoint = key + '=';
    split = value.split('#').map(trim);

    // If # was found, the source was specified
    if (split.length > 1) {
        endpoint += (split[0] || key) + '#' + split[1];
    // Check if value looks like a source
    } else if (isSource(value)) {
        endpoint += value + '#*';
    // Otherwise use the key as the source
    } else {
        endpoint += key + '#' + split[0];
    }

    return decompose(endpoint);
}

function decomposed2json(decEndpoint) {
    var error;
    var name = trim(decEndpoint.name);
    var source = trim(decEndpoint.source);
    var target = trim(decEndpoint.target);
    var value = '';
    var ret = {};

    if (!name) {
        error = new Error('Decomposed endpoint must have a name');
        error.code = 'EINVEND';
        throw error;
    }

    // Add source only if different than the name
    if  (source !== name) {
        value += source;
    }

    // If value is empty, we append the target always
    if (!value) {
        if (isWildcard(target)) {
            value += '*';
        } else {
            if (target.indexOf('/') !== -1) {
                value += '#' + target;
            } else {
                value += target;
            }
        }
    // Otherwise append only if not a wildcard or source does not look like a source
    } else if (!isWildcard(target) || !isSource(source)) {
        value += '#' + (target || '*');
    }

    ret[name] = value;

    return ret;
}

function trim(str) {
    return str ? str.trim() : '';
}

function isWildcard(target) {
    return !target || target === '*' || target === 'latest';
}

function isSource(value) {
    return (/[\/\\@]/).test(value);
}

module.exports.decompose = decompose;
module.exports.compose = compose;
module.exports.json2decomposed = json2decomposed;
module.exports.decomposed2json = decomposed2json;
<|endoftext|>


<commit_before>(function(){

  "use strict";

  var d = document;

  function initPage(){
    if (d.querySelectorAll){
      for (var xs = d.querySelectorAll('pre.csharp'), i = xs.length; i--; ){
        var x = xs[i];
        x.innerHTML = x.innerHTML
          .replace(/(\/\/\s*)(.*)/g, '$1$2');
      }
    }
  }

  window.initializers.push(initPage);
  initPage();
}())<commit_msg>Bug fix<commit_after>(function(){

  "use strict";

  var d = document;

  function initPage(){
    if (d.querySelectorAll){
      for (var xs = d.querySelectorAll('pre.csharp'), i = xs.length; i--; ){
        var x = xs[i];
        x.innerHTML = x.innerHTML
          .replace(/(\/\/+)(.*)/g, '$1$2');
      }
    }
  }

  window.initializers.push(initPage);
  initPage();
}())<|endoftext|>


<commit_before>/* eslint react/no-multi-comp: 0, react/prop-types: 0 */
import React from 'react';
import { PrismCode } from 'react-prism';
import Helmet from 'react-helmet';
import {
  Button,
  ButtonDropdown,
  DropdownToggle,
  DropdownItem,
  DropdownMenu } from 'reactstrap';
import Example from '../examples/ButtonDropdownMulti';
import ExampleSplit from '../examples/ButtonDropdownMultiSplit';
import ButtonDropdownExample from '../examples/ButtonDropdown';
const ButtonDropdownExampleSource = require('!!raw!../examples/ButtonDropdown');

export default class ButtonDropdownPage extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      dropdownOpen: false
    };
  }

  toggle() {
    this.setState({
      dropdownOpen: !this.state.dropdownOpen
    });
  }

  render() {
    return (

        <Helmet title="Button Dropdown" />

Button Dropdown

          <ButtonDropdownExample />

          <PrismCode className="language-jsx">
            {ButtonDropdownExampleSource}
          </PrismCode>

Properties

          <PrismCode className="language-jsx">
{`ButtonDropdown.propTypes = {
  disabled: PropTypes.bool,
  dropup: PropTypes.bool,
  group: PropTypes.bool,
  isOpen: PropTypes.bool,
  tag: PropTypes.string,
  tether: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  toggle: PropTypes.func
};

DropdownToggle.propTypes = {
  caret: PropTypes.bool,
  color: PropTypes.string,
  disabled: PropTypes.bool,
  onClick: PropTypes.func,
  'data-toggle': PropTypes.string,
  'aria-haspopup': PropTypes.bool
};`}
          </PrismCode>

Single button dropdowns

            <Example color="primary" text="Primary" />
            <Example color="secondary" text="Secondary" />
            <Example color="success" text="Success" />
            <Example color="info" text="Info" />
            <Example color="warning" text="Warning" />
            <Example color="danger" text="Darning" />

          <PrismCode className="language-jsx">
{`<ButtonDropdown color="primary" isOpen={isOpen} toggle={toggle}>
  <DropdownToggle caret>
    Text
  </DropdownToggle>
  <DropdownMenu>
    <DropdownItem header>Header</DropdownItem>
    <DropdownItem disabled>Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem divider/>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>`}
          </PrismCode>

Split button dropdowns

            <ExampleSplit color="primary" text="Primary" />
            <ExampleSplit color="secondary" text="Secondary" />
            <ExampleSplit color="success" text="Success" />
            <ExampleSplit color="info" text="Info" />
            <ExampleSplit color="warning" text="Warning" />
            <ExampleSplit color="danger" text="Darning" />

          <PrismCode className="language-jsx">
{`<ButtonDropdown isOpen={isOpen} toggle={toggle}>
  <Button id="caret" color="primary">{this.props.text}</Button>
  <DropdownToggle caret color="primary" />
  <DropdownMenu>
    <DropdownItem header>Header</DropdownItem>
    <DropdownItem disabled>Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem divider/>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>`}
          </PrismCode>

Sizing

            <ButtonDropdown isOpen={this.state.btnLg} toggle={() => { this.setState({ btnLg: !this.state.btnLg }); }}>
              <DropdownToggle caret size="lg">
                Large Button
              </DropdownToggle>
              <DropdownMenu>
                <DropdownItem>Another Action</DropdownItem>
                <DropdownItem>Another Action</DropdownItem>
              </DropdownMenu>
            </ButtonDropdown>

            <ButtonDropdown isOpen={this.state.btnSm} toggle={() => { this.setState({ btnSm: !this.state.btnSm }); }}>
              <DropdownToggle caret size="sm">
                Small Button
              </DropdownToggle>
              <DropdownMenu>
                <DropdownItem>Another Action</DropdownItem>
                <DropdownItem>Another Action</DropdownItem>
              </DropdownMenu>
            </ButtonDropdown>

          <PrismCode className="language-jsx">
{`<ButtonDropdown isOpen={isOpen} toggle={toggle}>
  <DropdownToggle caret size="lg">
    Large Button
  </DropdownToggle>
  <DropdownMenu>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>

<ButtonDropdown isOpen={isOpen} toggle={toggle}>
  <DropdownToggle caret size="sm">
    Small Button
  </DropdownToggle>
  <DropdownMenu>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>`}
          </PrismCode>

Dropup variation

            <ButtonDropdown dropup isOpen={this.state.btnDropup} toggle={() => { this.setState({ btnDropup: !this.state.btnDropup }); }}>
              <DropdownToggle caret size="lg">
                Dropup
              </DropdownToggle>
              <DropdownMenu>
                <DropdownItem>Another Action</DropdownItem>
                <DropdownItem>Another Action</DropdownItem>
              </DropdownMenu>
            </ButtonDropdown>

          <PrismCode className="language-jsx">
{`<ButtonDropdown isOpen={isOpen} toggle={toggle} dropup>
  <DropdownToggle caret caret size="lg">
    Dropup
  </DropdownToggle>
  <DropdownMenu>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>`}
          </PrismCode>

    );
  }
}
<commit_msg>docs(ButtonDropdown): move color prop to DropdownToggle<commit_after>/* eslint react/no-multi-comp: 0, react/prop-types: 0 */
import React from 'react';
import { PrismCode } from 'react-prism';
import Helmet from 'react-helmet';
import {
  Button,
  ButtonDropdown,
  DropdownToggle,
  DropdownItem,
  DropdownMenu } from 'reactstrap';
import Example from '../examples/ButtonDropdownMulti';
import ExampleSplit from '../examples/ButtonDropdownMultiSplit';
import ButtonDropdownExample from '../examples/ButtonDropdown';
const ButtonDropdownExampleSource = require('!!raw!../examples/ButtonDropdown');

export default class ButtonDropdownPage extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      dropdownOpen: false
    };
  }

  toggle() {
    this.setState({
      dropdownOpen: !this.state.dropdownOpen
    });
  }

  render() {
    return (

        <Helmet title="Button Dropdown" />

Button Dropdown

          <ButtonDropdownExample />

          <PrismCode className="language-jsx">
            {ButtonDropdownExampleSource}
          </PrismCode>

Properties

          <PrismCode className="language-jsx">
{`ButtonDropdown.propTypes = {
  disabled: PropTypes.bool,
  dropup: PropTypes.bool,
  group: PropTypes.bool,
  isOpen: PropTypes.bool,
  tag: PropTypes.string,
  tether: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  toggle: PropTypes.func
};

DropdownToggle.propTypes = {
  caret: PropTypes.bool,
  color: PropTypes.string,
  disabled: PropTypes.bool,
  onClick: PropTypes.func,
  'data-toggle': PropTypes.string,
  'aria-haspopup': PropTypes.bool
};`}
          </PrismCode>

Single button dropdowns

            <Example color="primary" text="Primary" />
            <Example color="secondary" text="Secondary" />
            <Example color="success" text="Success" />
            <Example color="info" text="Info" />
            <Example color="warning" text="Warning" />
            <Example color="danger" text="Darning" />

          <PrismCode className="language-jsx">
{`<ButtonDropdown isOpen={isOpen} toggle={toggle}>
  <DropdownToggle caret color="primary">
    Text
  </DropdownToggle>
  <DropdownMenu>
    <DropdownItem header>Header</DropdownItem>
    <DropdownItem disabled>Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem divider/>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>`}
          </PrismCode>

Split button dropdowns

            <ExampleSplit color="primary" text="Primary" />
            <ExampleSplit color="secondary" text="Secondary" />
            <ExampleSplit color="success" text="Success" />
            <ExampleSplit color="info" text="Info" />
            <ExampleSplit color="warning" text="Warning" />
            <ExampleSplit color="danger" text="Darning" />

          <PrismCode className="language-jsx">
{`<ButtonDropdown isOpen={isOpen} toggle={toggle}>
  <Button id="caret" color="primary">{this.props.text}</Button>
  <DropdownToggle caret color="primary" />
  <DropdownMenu>
    <DropdownItem header>Header</DropdownItem>
    <DropdownItem disabled>Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem divider/>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>`}
          </PrismCode>

Sizing

            <ButtonDropdown isOpen={this.state.btnLg} toggle={() => { this.setState({ btnLg: !this.state.btnLg }); }}>
              <DropdownToggle caret size="lg">
                Large Button
              </DropdownToggle>
              <DropdownMenu>
                <DropdownItem>Another Action</DropdownItem>
                <DropdownItem>Another Action</DropdownItem>
              </DropdownMenu>
            </ButtonDropdown>

            <ButtonDropdown isOpen={this.state.btnSm} toggle={() => { this.setState({ btnSm: !this.state.btnSm }); }}>
              <DropdownToggle caret size="sm">
                Small Button
              </DropdownToggle>
              <DropdownMenu>
                <DropdownItem>Another Action</DropdownItem>
                <DropdownItem>Another Action</DropdownItem>
              </DropdownMenu>
            </ButtonDropdown>

          <PrismCode className="language-jsx">
{`<ButtonDropdown isOpen={isOpen} toggle={toggle}>
  <DropdownToggle caret size="lg">
    Large Button
  </DropdownToggle>
  <DropdownMenu>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>

<ButtonDropdown isOpen={isOpen} toggle={toggle}>
  <DropdownToggle caret size="sm">
    Small Button
  </DropdownToggle>
  <DropdownMenu>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>`}
          </PrismCode>

Dropup variation

            <ButtonDropdown dropup isOpen={this.state.btnDropup} toggle={() => { this.setState({ btnDropup: !this.state.btnDropup }); }}>
              <DropdownToggle caret size="lg">
                Dropup
              </DropdownToggle>
              <DropdownMenu>
                <DropdownItem>Another Action</DropdownItem>
                <DropdownItem>Another Action</DropdownItem>
              </DropdownMenu>
            </ButtonDropdown>

          <PrismCode className="language-jsx">
{`<ButtonDropdown isOpen={isOpen} toggle={toggle} dropup>
  <DropdownToggle caret caret size="lg">
    Dropup
  </DropdownToggle>
  <DropdownMenu>
    <DropdownItem>Another Action</DropdownItem>
    <DropdownItem>Another Action</DropdownItem>
  </DropdownMenu>
</ButtonDropdown>`}
          </PrismCode>

    );
  }
}
<|endoftext|>


<commit_before>"use strict";

const recursiveFlatten = function (array) {
  const res = []
  for (let e of array) {
    if (Array.isArray(e)) {
      res.push(...recursiveFlatten(e))
      continue
    }
    res.push(e)
  }
  return res
}

/**
 * Flatten all the elements of array.
 * E.g. [1, [2, [3] ], 4] -> [1, 2, 3, 4]
 *
 * @param {Array} array
 */
module.exports = recursiveFlatten
<commit_msg>Single-line(ish) reduce based<commit_after>"use strict";

const recursiveFlatten = function (array) {
  return array.reduce(function (res, e) {
    Array.isArray(e) ? res.push(...recursiveFlatten(e)) : res.push(e)
    return res
  }, [])
}

/**
 * Flatten all the elements of array.
 * E.g. [1, [2, [3] ], 4] -> [1, 2, 3, 4]
 *
 * @param {Array} array
 */
module.exports = recursiveFlatten
<|endoftext|>


<commit_before>/**
 * - use dotenv to load .env variables
 * - dotenv will read the .env file in the root folder
 * - It will parse the file and inject the variables to our environment
 * ***** sample file******
 * LIPISHA_API_KEY=thisistheawesomelipishaapikey
 * LIPISHA_API_SIGNATURE=thisistheawesomelipishaapikeysignatue=
 * @type {[type]}
 */
'use strict';
require('dotenv').load();
var lipisha = require('../lib/lipisha.js');

var config = {
    apiKey: process.env.LIPISHA_API_KEY,
    apiSignature: process.env.LIPISHA_API_SIGNATURE,
    environment: 'LIVE',
    SUCCESS: 'SUCCESS',
    FAILURE: 'FAIL',
    FLOAT_ACCOUNT: '',

    PAYOUT_ACCOUNT: '',
    PAYOUT_AMOUNT: 0,
    PAYOUT_MOBILE_NUMBER: '',

    AIRTIME_ACCOUNT: '',
    AIRTIME_AMOUNT: 0,
    AIRTIME_MOBILE_NUMBER: '',
    AIRTIME_NETWORK: '',

    SMS_MOBILE_NUMBER: '',
    SMS_MESSAGE: 'Message from LP/Node/SDK',

    PAYMENT_ACCOUNT_TYPE_MOBILE: 1,
    PAYMENT_ACCOUNT_NAME: '',
    PAYMENT_ACCOUNT_ADMIN: '',

    REQUEST_MONEY_ACCOUNT: '',
    REQUEST_MONEY_MOBILE: '',
    REQUEST_MONEY_METHOD: 'Paybill (M-Pesa)',
    REQUEST_MONEY_REFERENCE: '',
    REQUEST_MONEY_AMOUNT: 10,

    WITHDRAWAL_ACCOUNT_TYPE: 1,
    WITHDRAWAL_ACCOUNT_NAME: '',
    WITHDRAWAL_ACCOUNT_NUMBER: '',
    WITHDRAWAL_ACCOUNT_BANK_NAME: 'Bank of Lipisha',
    WITHDRAWAL_ACCOUNT_BANK_BRANCH: 'HQ',
    WITHDRAWAL_ACCOUNT_BANK_ADDRESS: 'HQ001, Lipa Street, 99999',
    WITHDRAWAL_ACCOUNT_SWIFT_CODE: 'LPSHKENXXX',
    WITHDRAWAL_ACCOUNT_MANAGER: '',

    USER_NAMES: '',
    USER_ROLE: '',
    USER_MOBILE: '',
    USER_EMAIL: '',
    USER_LOGIN: '',
    USER_PASSWORD: '',

    STATUS_CONFIRMED: 'Completed',
    TRANSACTION_ID_CONFIRM: '',
    TRANSACTION_ID_REVERSE: '',

    CARD_ACCOUNT: '',
    CARD_NUMBER: '',
    CARD_ADDRESS1: '',
    CARD_ADDRESS2: '',
    CARD_EXPIRY: '',
    CARD_NAMES: '',
    CARD_COUNTRY: '',
    CARD_STATE: '',
    CARD_ZIP: '',
    CARD_SECURITY_CODE: '',
    CARD_AMOUNT: 0,
    CARD_CURRENCY: '',

    CARD_TX_COMPLETE_INDEX: '',
    CARD_TX_COMPLETE_REF: '',
    CARD_TX_REVERSE_INDEX: '',
    CARD_TX_REVERSE_REF: '',
    CARD_TX_VOID_INDEX: '',
    CARD_TX_VOID_REF: '',

};

var lipisha = new lipisha.Lipisha(config.apiKey, config.apiSignature, config.environment);

module.exports = {
    client: lipisha,
    config: config,
    require_var: function(v) {
        return !(!v);
    }
};
<commit_msg>Uses Lipisha as constructor<commit_after>/**
 * - use dotenv to load .env variables
 * - dotenv will read the .env file in the root folder
 * - It will parse the file and inject the variables to our environment
 * ***** sample file******
 * LIPISHA_API_KEY=thisistheawesomelipishaapikey
 * LIPISHA_API_SIGNATURE=thisistheawesomelipishaapikeysignatue=
 * @type {[type]}
 */
'use strict';
require('dotenv').load();
var Lipisha = require('../lib/lipisha.js');

var config = {
    apiKey: process.env.LIPISHA_API_KEY,
    apiSignature: process.env.LIPISHA_API_SIGNATURE,
    environment: 'LIVE',
    SUCCESS: 'SUCCESS',
    FAILURE: 'FAIL',
    FLOAT_ACCOUNT: '',

    PAYOUT_ACCOUNT: '',
    PAYOUT_AMOUNT: 0,
    PAYOUT_MOBILE_NUMBER: '',

    AIRTIME_ACCOUNT: '',
    AIRTIME_AMOUNT: 0,
    AIRTIME_MOBILE_NUMBER: '',
    AIRTIME_NETWORK: '',

    SMS_MOBILE_NUMBER: '',
    SMS_MESSAGE: 'Message from LP/Node/SDK',

    PAYMENT_ACCOUNT_TYPE_MOBILE: 1,
    PAYMENT_ACCOUNT_NAME: '',
    PAYMENT_ACCOUNT_ADMIN: '',

    REQUEST_MONEY_ACCOUNT: '',
    REQUEST_MONEY_MOBILE: '',
    REQUEST_MONEY_METHOD: 'Paybill (M-Pesa)',
    REQUEST_MONEY_REFERENCE: '',
    REQUEST_MONEY_AMOUNT: 10,

    WITHDRAWAL_ACCOUNT_TYPE: 1,
    WITHDRAWAL_ACCOUNT_NAME: '',
    WITHDRAWAL_ACCOUNT_NUMBER: '',
    WITHDRAWAL_ACCOUNT_BANK_NAME: 'Bank of Lipisha',
    WITHDRAWAL_ACCOUNT_BANK_BRANCH: 'HQ',
    WITHDRAWAL_ACCOUNT_BANK_ADDRESS: 'HQ001, Lipa Street, 99999',
    WITHDRAWAL_ACCOUNT_SWIFT_CODE: 'LPSHKENXXX',
    WITHDRAWAL_ACCOUNT_MANAGER: '',

    USER_NAMES: '',
    USER_ROLE: '',
    USER_MOBILE: '',
    USER_EMAIL: '',
    USER_LOGIN: '',
    USER_PASSWORD: '',

    STATUS_CONFIRMED: 'Completed',
    TRANSACTION_ID_CONFIRM: '',
    TRANSACTION_ID_REVERSE: '',

    CARD_ACCOUNT: '',
    CARD_NUMBER: '',
    CARD_ADDRESS1: '',
    CARD_ADDRESS2: '',
    CARD_EXPIRY: '',
    CARD_NAMES: '',
    CARD_COUNTRY: '',
    CARD_STATE: '',
    CARD_ZIP: '',
    CARD_SECURITY_CODE: '',
    CARD_AMOUNT: 0,
    CARD_CURRENCY: '',

    CARD_TX_COMPLETE_INDEX: '',
    CARD_TX_COMPLETE_REF: '',
    CARD_TX_REVERSE_INDEX: '',
    CARD_TX_REVERSE_REF: '',
    CARD_TX_VOID_INDEX: '',
    CARD_TX_VOID_REF: '',

};

var lipisha = new Lipisha(config.apiKey, config.apiSignature, config.environment);

module.exports = {
    client: lipisha,
    config: config,
    require_var: function(v) {
        return !(!v);
    }
};
<|endoftext|>


<commit_before>module.exports = {
    plugin: require('./lib/plugin')
};<commit_msg>updating to match the new api<commit_after>var plugin = require('./lib/plugin');

module.exports = {
    plugin: function () {
        return plugin;
    }
};<|endoftext|>


<commit_before>var dgram = require('dgram'),
    server = dgram.createSocket('udp4'),
    dns = require('dns')

var url = 'vincentdefeo.me',
   port = 8080

dns.lookup(url, function resolved(err, addresses){
    if (err) throw err
    console.log('\nSTARTING...\n' + url + ' RESOLVED TO: ' + addresses)
    server.bind(port, addresses)
})

server.on('listening', function(){
    var address = server.address()
    console.log('Listening on : ' + address.address + ':' + address.port)
})

server.on('message', function (msg, r){
    console.log('\nGOT MESSAGE:\n' + msg + '\nFROM: ' + r.address + ':' + r.port)
    server.send(msg, 0, msg.length, r.port, r.address)
})

server.on('error', function (msg, r){
	console.log(msg);
})
<commit_msg>timestamp<commit_after>var dgram = require('dgram'),
    server = dgram.createSocket('udp4'),
    dns = require('dns')

var url = 'vincentdefeo.me',
   port = 8080

dns.lookup(url, function resolved(err, addresses){
    if (err) throw err
    console.log('\nSTARTING...\n' + url + ' RESOLVED TO: ' + addresses)
    server.bind(port, addresses)
})

server.on('listening', function(){
    var address = server.address()
    console.log('Listening on : ' + address.address + ':' + address.port)
})

server.on('message', function (msg, r){
    console.log('\nGOT MESSAGE:\n' + msg + '\nFROM: ' + r.address + ':' + r.port)
    console.log('\nON: ' + Date.now())
    server.send(msg, 0, msg.length, r.port, r.address)
})

server.on('error', function (err){
	console.log("\n[!!] ERROR: " + err);
})
<|endoftext|>


<commit_before>/**
 * A Bot for Slack!
 */

/**
 * Define a function for initiating a conversation on installation
 * With custom integrations, we don't have a way to find out who installed us, so we can't message them :(
 */

function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({user: installer}, function (err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am a bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

/**
 * Configure the persistence options
 */

var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN)?'./db_slack_bot_ci/':'./db_slack_bot_a/'), //use a different name if an app or CI
    };
}

/**
 * Are being run as an app or a custom integration? The initialization will differ, depending
 */

if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    //Treat this as a custom integration
    var customIntegration = require('./lib/custom_integrations');
    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
    var controller = customIntegration.configure(token, config, onInstallation);
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
    //Treat this as an app
    var app = require('./lib/apps');
    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
} else {
    console.log('Error: If this is a custom integration, please specify TOKEN in the environment. If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment');
    process.exit(1);
}

var apiai = require('botkit-middleware-apiai')({
   token: process.env.APIAI_TOKEN
});
controller.middleware.receive.use(apiai.receive);

/**
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function (bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function (bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

/**
 * Core bot logic goes here!
 */
// BEGIN EDITING HERE!

controller.on('bot_channel_join', function (bot, message) {
    bot.reply(message, "I'm here!")
});

/*controller.hears('hello', ['mention', 'direct_mention','direct_message'], function (bot, message) {
    bot.reply(message, 'Hello!');
});*/

controller.hears(['hello'], 'direct_message', apiai.hears, function (bot, message) {
   bot.reply(message, 'Hello!');
});

controller.hears(['goodbye'], 'direct_message', apiai.hears, function (bot, message) {
   bot.reply(message, 'See you later alligator!');
});

controller.hears(['flights'], 'direct_message', apiai.hears, function (bot, message) {
   if(message.fulfillment.speech !== '') {
       bot.reply(message, message.fulfillment.speech);
   } else {
       bot.reply(message, "You requested to fly to " + message.entities['geo-city'] + " on " + message.entities['date']+".");
   }
});

controller.hears(['calculate'], ['direct_mention', 'mention', 'direct_message'], apiai.hears, function (bot,message) {
  var userID = message.user
  var user = "<@"+userID+">"
  if(message.fulfillment.speech !== '') {
    bot.reply(message, message.fulfillment.speech);
  } else if (message.entities['keyword'] == 'client') {
    var total = parseInt(message.entities['day_rate']);
    var client_rate = (parseInt(message.entities['rate']) / 100);
    var day_rate = (total / (1.1 + client_rate)).toFixed(2);
    var tax = (day_rate * 0.1).toFixed(2);
    var gst = (total * 0.1).toFixed(2);
    var margin = (total - tax - day_rate).toFixed(2);
    bot.reply(message, user+"\nThe client is paying: *$"+total+"*, plus *$"+gst+"* GST. :the_horns: \nThis is made up of: \nContractor day rate: *$"+day_rate+"* :tada: \nTax/Insurance: *$"+tax+"* :angry: \nLookahead margin: *$"+margin+"* :moneybag:");
  } else {
    var day_rate = parseInt(message.entities['day_rate']);
    var client_rate = (parseInt(message.entities['rate']) / 100);
    var total = (day_rate * (1.1 + client_rate)).toFixed(2);
    var tax = (day_rate * 0.1).toFixed(2);
    var gst = (total * 0.1).toFixed(2);
    var margin = (total - tax - day_rate).toFixed(2);
    bot.reply(message, user+"\nThe client will be charged: *$"+total+"*, plus *$"+gst+"* GST. :the_horns: \nTax/Insurance: *$"+tax+"* :angry: \nLookahead earn: *$"+margin+"* :moneybag:");
  }
});

/**
 * AN example of what could be:
 * Any un-handled direct mention gets a reaction and a pat response!
 */
//controller.on('direct_message,mention,direct_mention', function (bot, message) {
//    bot.api.reactions.add({
//        timestamp: message.ts,
//        channel: message.channel,
//        name: 'robot_face',
//    }, function (err) {
//        if (err) {
//            console.log(err)
//        }
//        bot.reply(message, 'I heard you loud and clear boss.');
//    });
//});
<commit_msg>First commit to new repo<commit_after>/**
 * A Spot for Slack!
 */

/**
 * Define a function for initiating a conversation on installation
 * With custom integrations, we don't have a way to find out who installed us, so we can't message them :(
 */

function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({user: installer}, function (err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am a bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

/**
 * Configure the persistence options
 */

var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN)?'./db_slack_bot_ci/':'./db_slack_bot_a/'), //use a different name if an app or CI
    };
}

/**
 * Are being run as an app or a custom integration? The initialization will differ, depending
 */

if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    //Treat this as a custom integration
    var customIntegration = require('./lib/custom_integrations');
    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
    var controller = customIntegration.configure(token, config, onInstallation);
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
    //Treat this as an app
    var app = require('./lib/apps');
    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
} else {
    console.log('Error: If this is a custom integration, please specify TOKEN in the environment. If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment');
    process.exit(1);
}

var apiai = require('botkit-middleware-apiai')({
   token: process.env.APIAI_TOKEN
});
controller.middleware.receive.use(apiai.receive);

/**
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function (bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function (bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

/**
 * Core bot logic goes here!
 */
// BEGIN EDITING HERE!

controller.on('bot_channel_join', function (bot, message) {
    bot.reply(message, "I'm here!")
});

/*controller.hears('hello', ['mention', 'direct_mention','direct_message'], function (bot, message) {
    bot.reply(message, 'Hello!');
});*/

controller.hears(['hello'], 'direct_message', apiai.hears, function (bot, message) {
   bot.reply(message, 'Hello!');
});

controller.hears(['goodbye'], 'direct_message', apiai.hears, function (bot, message) {
   bot.reply(message, 'See you later alligator!');
});

controller.hears(['flights'], 'direct_message', apiai.hears, function (bot, message) {
   if(message.fulfillment.speech !== '') {
       bot.reply(message, message.fulfillment.speech);
   } else {
       bot.reply(message, "You requested to fly to " + message.entities['geo-city'] + " on " + message.entities['date']+".");
   }
});

controller.hears(['calculate'], ['direct_mention', 'mention', 'direct_message'], apiai.hears, function (bot,message) {
  var userID = message.user
  var user = "<@"+userID+">"
  if(message.fulfillment.speech !== '') {
    bot.reply(message, message.fulfillment.speech);
  } else if (message.entities['keyword'] == 'client') {
    var total = parseInt(message.entities['day_rate']);
    var client_rate = (parseInt(message.entities['rate']) / 100);
    var day_rate = (total / (1.1 + client_rate)).toFixed(2);
    var tax = (day_rate * 0.1).toFixed(2);
    var gst = (total * 0.1).toFixed(2);
    var margin = (total - tax - day_rate).toFixed(2);
    bot.reply(message, user+"\nThe client is paying: *$"+total+"*, plus *$"+gst+"* GST. :the_horns: \nThis is made up of: \nContractor day rate: *$"+day_rate+"* :tada: \nTax/Insurance: *$"+tax+"* :angry: \nLookahead margin: *$"+margin+"* :moneybag:");
  } else {
    var day_rate = parseInt(message.entities['day_rate']);
    var client_rate = (parseInt(message.entities['rate']) / 100);
    var total = (day_rate * (1.1 + client_rate)).toFixed(2);
    var tax = (day_rate * 0.1).toFixed(2);
    var gst = (total * 0.1).toFixed(2);
    var margin = (total - tax - day_rate).toFixed(2);
    bot.reply(message, user+"\nThe client will be charged: *$"+total+"*, plus *$"+gst+"* GST. :the_horns: \nTax/Insurance: *$"+tax+"* :angry: \nLookahead earn: *$"+margin+"* :moneybag:");
  }
});

/**
 * AN example of what could be:
 * Any un-handled direct mention gets a reaction and a pat response!
 */
//controller.on('direct_message,mention,direct_mention', function (bot, message) {
//    bot.api.reactions.add({
//        timestamp: message.ts,
//        channel: message.channel,
//        name: 'robot_face',
//    }, function (err) {
//        if (err) {
//            console.log(err)
//        }
//        bot.reply(message, 'I heard you loud and clear boss.');
//    });
//});
<|endoftext|>


<commit_before>import * as completions from "./lib/completions.js";
export { completions }

import * as globalEval from "./lib/eval.js";
import * as esmEval from "./lib/esm-eval.js";
export { defaultTopLevelVarRecorderName } from "./lib/eval.js";
export { evalCodeTransform, evalCodeTransformOfSystemRegisterSetters } from "./lib/eval-support.js";
export { runEval, syncEval }

function runEval(code, options) {
  var {format, System: S, targetModule} = options = {
    format: "esm",
    System: null,
    targetModule: null,
    ...options
  }

  if (!S && typeof System !== "undefined") S = System;
  if (!S && targetModule) {
    return Promise.reject(new Error("options to runEval have targetModule but cannot find system loader!"));
  }

  return targetModule && (["esm", "es6", "register"].includes(format))?
    esmEval.runEval(S, code, options) :
    globalEval.runEval(code, options);
}

function syncEval(code, options) {
  return globalEval.syncEval(code, options);
}

import * as evalStrategies from "./lib/eval-strategies.js";
export { evalStrategies }
<commit_msg>export defaultClassToFunctionConverterName<commit_after>import * as completions from "./lib/completions.js";
export { completions }

import * as globalEval from "./lib/eval.js";
import * as esmEval from "./lib/esm-eval.js";
export { defaultTopLevelVarRecorderName } from "./lib/eval.js";
export {
  defaultClassToFunctionConverterName,
  evalCodeTransform,
  evalCodeTransformOfSystemRegisterSetters
} from "./lib/eval-support.js";

export { runEval, syncEval }

function runEval(code, options) {
  var {format, System: S, targetModule} = options = {
    format: "esm",
    System: null,
    targetModule: null,
    ...options
  }

  if (!S && typeof System !== "undefined") S = System;
  if (!S && targetModule) {
    return Promise.reject(new Error("options to runEval have targetModule but cannot find system loader!"));
  }

  return targetModule && (["esm", "es6", "register"].includes(format))?
    esmEval.runEval(S, code, options) :
    globalEval.runEval(code, options);
}

function syncEval(code, options) {
  return globalEval.syncEval(code, options);
}

import * as evalStrategies from "./lib/eval-strategies.js";
export { evalStrategies }
<|endoftext|>


<commit_before>var stream = require('stream')
var util = require('util')
var isBuffer = require('isbuffer')

function WebsocketStream(server, options) {
  if (!(this instanceof WebsocketStream)) return new WebsocketStream(server, options)
  stream.Stream.call(this)
  this.options = options || {}
  this.readable = true
  this.writable = true
  this._buffer = []

  if (typeof server === "object") {
    this.ws = server
    this.ws.on('message', this.onMessage.bind(this))
    this.ws.on('error', this.onError.bind(this))
    this.ws.on('close', this.onClose.bind(this))
    this.ws.on('open', this.onOpen.bind(this))
    if (this.ws.readyState === 1) this._open = true
  } else {
    this.ws = new WebSocket(server, this.options.protocol)
    this.ws.binaryType = this.options.binaryType || 'arraybuffer'
    this.ws.onmessage = this.onMessage.bind(this)
    this.ws.onerror = this.onError.bind(this)
    this.ws.onclose = this.onClose.bind(this)
    this.ws.onopen = this.onOpen.bind(this)
  }
}

util.inherits(WebsocketStream, stream.Stream)

module.exports = WebsocketStream
module.exports.WebsocketStream = WebsocketStream

WebsocketStream.prototype.onMessage = function(e, flags) {
  var data = e
  if (data.data) data = data.data

  // type must be a Typed Array (ArrayBufferView)
  var type = this.options.type
  if (type && data instanceof ArrayBuffer) data = new type(data)

  this.emit('data', data, flags)
}

WebsocketStream.prototype.onError = function(err) {
  this.emit('error', err)
}

WebsocketStream.prototype.onClose = function(err) {
  if (this._destroy) return
  this.emit('end')
}

WebsocketStream.prototype.onOpen = function(err) {
  if (this._destroy) return
  this._open = true
  for (var i = 0; i < this._buffer.length; i++) {
    this._write(this._buffer[i])
  }
  this._buffer = undefined
  this.emit('open')
  this.emit('connect')
  if (this._end) this.ws.close()
}

WebsocketStream.prototype.write = function(data) {
  if (!this._open) {
    this._buffer.push(data)
  } else {
    this._write(data)
  }
}

WebsocketStream.prototype._write = function(data) {
  typeof WebSocket != 'undefined' && this.ws instanceof WebSocket
    ? this.ws.send(data)
    : this.ws.send(data, { binary : isBuffer(data) })
}

WebsocketStream.prototype.end = function(data) {
  if (data !== undefined) this.write(data)
  if (this._open) this.ws.close()
  this._end = true
}

WebsocketStream.prototype.destroy = function() {
  this._destroy = true
  this.ws.close()
}
<commit_msg>Emitting the close event when the client closes.<commit_after>var stream = require('stream')
var util = require('util')
var isBuffer = require('isbuffer')

function WebsocketStream(server, options) {
  if (!(this instanceof WebsocketStream)) return new WebsocketStream(server, options)
  stream.Stream.call(this)
  this.options = options || {}
  this.readable = true
  this.writable = true
  this._buffer = []

  if (typeof server === "object") {
    this.ws = server
    this.ws.on('message', this.onMessage.bind(this))
    this.ws.on('error', this.onError.bind(this))
    this.ws.on('close', this.onClose.bind(this))
    this.ws.on('open', this.onOpen.bind(this))
    if (this.ws.readyState === 1) this._open = true
  } else {
    this.ws = new WebSocket(server, this.options.protocol)
    this.ws.binaryType = this.options.binaryType || 'arraybuffer'
    this.ws.onmessage = this.onMessage.bind(this)
    this.ws.onerror = this.onError.bind(this)
    this.ws.onclose = this.onClose.bind(this)
    this.ws.onopen = this.onOpen.bind(this)
  }
}

util.inherits(WebsocketStream, stream.Stream)

module.exports = WebsocketStream
module.exports.WebsocketStream = WebsocketStream

WebsocketStream.prototype.onMessage = function(e, flags) {
  var data = e
  if (data.data) data = data.data

  // type must be a Typed Array (ArrayBufferView)
  var type = this.options.type
  if (type && data instanceof ArrayBuffer) data = new type(data)

  this.emit('data', data, flags)
}

WebsocketStream.prototype.onError = function(err) {
  this.emit('error', err)
}

WebsocketStream.prototype.onClose = function(err) {
  if (this._destroy) return
  this.emit('end')
  this.emit('close')
}

WebsocketStream.prototype.onOpen = function(err) {
  if (this._destroy) return
  this._open = true
  for (var i = 0; i < this._buffer.length; i++) {
    this._write(this._buffer[i])
  }
  this._buffer = undefined
  this.emit('open')
  this.emit('connect')
  if (this._end) this.ws.close()
}

WebsocketStream.prototype.write = function(data) {
  if (!this._open) {
    this._buffer.push(data)
  } else {
    this._write(data)
  }
}

WebsocketStream.prototype._write = function(data) {
  typeof WebSocket != 'undefined' && this.ws instanceof WebSocket
    ? this.ws.send(data)
    : this.ws.send(data, { binary : isBuffer(data) })
}

WebsocketStream.prototype.end = function(data) {
  if (data !== undefined) this.write(data)
  if (this._open) this.ws.close()
  this._end = true
}

WebsocketStream.prototype.destroy = function() {
  this._destroy = true
  this.ws.close()
}
<|endoftext|>


<commit_before>var mixin = require('smart-mixin');
var assign = require('object-assign');

var mixinProto = mixin({
  // lifecycle stuff is as you'd expect
  componentDidMount: mixin.MANY,
  componentWillMount: mixin.MANY,
  componentWillReceiveProps: mixin.MANY,
  shouldComponentUpdate: mixin.ONCE,
  componentWillUpdate: mixin.MANY,
  componentDidUpdate: mixin.MANY,
  componentWillUnmount: mixin.MANY,
  getChildContext: mixin.MANY_MERGED
});

function setDefaultProps(reactMixin) {
  var getDefaultProps = reactMixin.getDefaultProps;

  if(getDefaultProps) {
    reactMixin.defaultProps = getDefaultProps();

    delete reactMixin.getDefaultProps;
  }
}

function setInitialState(reactMixin) {
  var getInitialState = reactMixin.getInitialState;
  var componentWillMount = reactMixin.componentWillMount;

  function applyInitialState(instance){
      var state = instance.state || {};
      assign(state, getInitialState.call(instance));
      instance.state = state;
  }

  if(getInitialState) {
    if(!componentWillMount) {
      reactMixin.componentWillMount = function() {
          applyInitialState(this);
      };
    }
    else {
      reactMixin.componentWillMount = function() {
        applyInitialState(this);
        componentWillMount.call(this);
      };
    }

    delete reactMixin.getInitialState;
  }
}

function mixinClass(reactClass, reactMixin) {
  setDefaultProps(reactMixin);
  setInitialState(reactMixin);

  var prototypeMethods = {};
  var staticProps = {};

  Object.keys(reactMixin).forEach(function(key) {
    if(typeof reactMixin[key] === 'function') {
      prototypeMethods[key] = reactMixin[key];
    }
    else {
      staticProps[key] = reactMixin[key];
    }
  });

  mixinProto(reactClass.prototype, prototypeMethods);

  var mergePropTypes = function(left, right, key){
    if (!left) return right;
    if (!right) return left;

    var result = {};
    Object.keys(left).forEach(function(leftKey){
      if (!right[leftKey]) {
        result[leftKey] = left[leftKey];
      }
    });

    Object.keys(right).forEach(function(rightKey){
      if (left[rightKey]) {
        result[rightKey] = function checkBothContextTypes(){
            return right[rightKey].apply(this, arguments) && left[rightKey].apply(this, arguments);
        }
      } else {
        result[rightKey] = right[rightKey];
      }
    });

    return result;
  };

  mixin({
    childContextTypes: mergePropTypes,
    contextTypes: mergePropTypes,
    propTypes: mixin.MANY_MERGED_LOOSE,
    defaultProps: mixin.MANY_MERGED_LOOSE
  })(reactClass, staticProps);
}

module.exports = (function () {
  var reactMixin = mixinProto;

  reactMixin.onClass = function(reactClass, mixin) {
    return mixinClass(reactClass, mixin)
  };

  reactMixin.decorate = function(mixin) {
    return function(reactClass) {
      return reactMixin.onClass(reactClass, mixin);
    };
  }

  return reactMixin;
})();
<commit_msg>Also return decorated class in mixinClass<commit_after>var mixin = require('smart-mixin');
var assign = require('object-assign');

var mixinProto = mixin({
  // lifecycle stuff is as you'd expect
  componentDidMount: mixin.MANY,
  componentWillMount: mixin.MANY,
  componentWillReceiveProps: mixin.MANY,
  shouldComponentUpdate: mixin.ONCE,
  componentWillUpdate: mixin.MANY,
  componentDidUpdate: mixin.MANY,
  componentWillUnmount: mixin.MANY,
  getChildContext: mixin.MANY_MERGED
});

function setDefaultProps(reactMixin) {
  var getDefaultProps = reactMixin.getDefaultProps;

  if(getDefaultProps) {
    reactMixin.defaultProps = getDefaultProps();

    delete reactMixin.getDefaultProps;
  }
}

function setInitialState(reactMixin) {
  var getInitialState = reactMixin.getInitialState;
  var componentWillMount = reactMixin.componentWillMount;

  function applyInitialState(instance){
      var state = instance.state || {};
      assign(state, getInitialState.call(instance));
      instance.state = state;
  }

  if(getInitialState) {
    if(!componentWillMount) {
      reactMixin.componentWillMount = function() {
          applyInitialState(this);
      };
    }
    else {
      reactMixin.componentWillMount = function() {
        applyInitialState(this);
        componentWillMount.call(this);
      };
    }

    delete reactMixin.getInitialState;
  }
}

function mixinClass(reactClass, reactMixin) {
  setDefaultProps(reactMixin);
  setInitialState(reactMixin);

  var prototypeMethods = {};
  var staticProps = {};

  Object.keys(reactMixin).forEach(function(key) {
    if(typeof reactMixin[key] === 'function') {
      prototypeMethods[key] = reactMixin[key];
    }
    else {
      staticProps[key] = reactMixin[key];
    }
  });

  mixinProto(reactClass.prototype, prototypeMethods);

  var mergePropTypes = function(left, right, key){
    if (!left) return right;
    if (!right) return left;

    var result = {};
    Object.keys(left).forEach(function(leftKey){
      if (!right[leftKey]) {
        result[leftKey] = left[leftKey];
      }
    });

    Object.keys(right).forEach(function(rightKey){
      if (left[rightKey]) {
        result[rightKey] = function checkBothContextTypes(){
            return right[rightKey].apply(this, arguments) && left[rightKey].apply(this, arguments);
        }
      } else {
        result[rightKey] = right[rightKey];
      }
    });

    return result;
  };

  mixin({
    childContextTypes: mergePropTypes,
    contextTypes: mergePropTypes,
    propTypes: mixin.MANY_MERGED_LOOSE,
    defaultProps: mixin.MANY_MERGED_LOOSE
  })(reactClass, staticProps);

  return reactClass;
}

module.exports = (function () {
  var reactMixin = mixinProto;

  reactMixin.onClass = function(reactClass, mixin) {
    return mixinClass(reactClass, mixin)
  };

  reactMixin.decorate = function(mixin) {
    return function(reactClass) {
      return reactMixin.onClass(reactClass, mixin);
    };
  }

  return reactMixin;
})();
<|endoftext|>


<commit_before>// A test to verify a canvas is created with buttons
var Application = require('spectron').Application;
var electron = require('electron-prebuilt');
var assert = require('assert');
const path = require('path');
var Card = require('../app/Card.js');

var app = new Application({
  path: electron,
  args: [path.join(__dirname, '..', 'main.js')],
  webPreferences: [],
});

describe('cards interactions', function () {
  this.timeout(30000);

  before(function () {
    this.app = new Application({
      path: electron,
      args: [path.join(__dirname, '..', 'main.js')],
    });
    return this.app.start();
  });

  after(function () {
    if (this.app && this.app.isRunning()) {
      return this.app.stop();
    }
  });

  it('creates a Card instance', function () {
    var card = new Card();
    return assert.equal(card.id, 1);
  });
});
<commit_msg>tests for card class to pass<commit_after>// A test to verify a canvas is created with buttons
var Application = require('spectron').Application;
var electron = require('electron-prebuilt');
var assert = require('assert');
const path = require('path');
var fs = require('fs');
var Card = require('../app/Card.js');
var Canvas = require('../app/Canvas.js');

var app = new Application({
  path: electron,
  args: [path.join(__dirname, '..', 'main.js')],
  webPreferences: [],
});

describe('cards interactions', function () {
  this.timeout(30000);

  before(function () {
    this.jsdom = require('jsdom-global')()
    global.$ = global.jQuery = require('jquery');
    this.app = new Application({
      path: electron,
      args: [path.join(__dirname, '..', 'main.js')],
    });
    return this.app.start();
  });

  after(function () {
    if (this.app && this.app.isRunning()) {
      return this.app.stop();
    }
  });

  it('creates a Card instance', function () {
    var card = new Card();
    return assert.equal(card.id, 1);
  });

  it('second card has id of 2', function(){
    var card2 = new Card();
    return assert.equal(card2.id, 2);
  });

  it('nextId establishes different card id', function(){
    var card = new Card();
    var card2 = new Card();
    console.log("card id: ", card.id, "card2 id: ", card2.id);
    return assert.notEqual(card.id, card2.id);
  });

  // it('nextID recognizes that a card has been deleted', function(){
  //   var card = new Card();
  //   var closeButton = document.createElement('button');
  //   $(closeButton).click(function() {
  //     let currcard = this.closest('.card');
  //     currcard.remove();
  //   });
  //   var card2 = new Card();
  //   return assert.equal(card.id, card2.id);
  // });

  it('correctly names a card', function(){
      var card = new Card();
      console.log(card.name);
      return assert.equal(card.name, "Card: " + card.id);
    });

  it('document contains a card and header div', function(){
    var card = new Card();
    card.cardBuilder();
    if(document.querySelector('.card') != undefined && document.querySelector('.card-header') != undefined)
      var div = 1;
    return assert.equal(div, 1);
  });

  it('document contains namebox span', function(){
    var card = new Card;
    card.cardBuilder();
    if(document.querySelector('.nameBox') != undefined)
      var span = 1;
    return assert.equal(span, 1);
  });

  it('document contains close, expand, and save buttons', function(){
    var card = new Card();
    card.cardBuilder();
    if(document.querySelector('.close') != undefined && document.querySelector('.expand') != undefined && document.querySelector('.save') != undefined)
      var buttons = 1;
    return assert.equal(buttons, 1);
  });

  it('new card is not in a stack', function(){
    var card = new Card();
    return assert.equal(card.inStack, false);
  });

  it('metadata is defined', function(){
      var card = new Card();
      console.log(card.buildMetadata());
      return assert.notEqual(card.buildMetadata(), undefined);
  });

  it('metadata will update', function(){
    var card = new Card();
    var built = card.buildMetadata();
    var updated;
    setTimeout(function(){
      console.log("waiting 3 seconds");
      var updated = card.updateMetadata();
      console.log(updated);
    }, 3000);
    return assert.notEqual(built, updated);
  });

  it('card will toggle on fullScreen mode', function(){
    var card = new Card();
    var height= card.toggleFullScreen();
    var h = window.innerHeight;
    console.log('toggle hight: ', height, 'window height: ', h)
    if(height == h)
      var size = 1;
    else {
      var size = 0;
    }
    return assert.equal(size, 1);
  });

  // it('card will toggle on fullScreen mode', function(){
  //   var card = new Card();
  //   var width = card.toggleFullScreen();
  //   var w = window.innerWidth;
  //   if(width == w &&)
  //     var size = 1;
  //   return assert.equal(size, 1);
  // });

  // it('cards being draggable is enabled', function(){
  //   var card = new Card();
  //   return assert.equal(card.setDraggable, true);
  // });

  // it('if no filedata is imported, filedata should be undefined', function(){
  //   var card = new Card;
  //   card.objectCleaner(fileData);
  //   return assert.equal(card.objectCleaner(fileData), undefined);
  // });

});
<|endoftext|>