<commit_before>'use strict';

delete require.cache[require.resolve('..')];
var DiagramRenderer = require('..');
var createRendererTester = require('../../../test_helper/create-renderer-tester');
var test = createRendererTester(DiagramRenderer);
var assert = require('../../../test_helper/empowered-assert');

describe('DiagramRenderer', function () {

    describe('Identifier', function () {
        test('boolean', function (transpiledCode) {
            var truthy = false;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       false  ',
        ]);

        test('empty string', function (transpiledCode) {
            var truthy = '';
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       ""     ',
        ]);

        test('zero', function (transpiledCode) {
            var truthy = 0;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       0      ',
        ]);

        test('undefined', function (transpiledCode) {
            var truthy = undefined;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       undefined',
        ]);
    });

    describe('UnaryExpression', function () {
        test('with NumberLiteral', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(-0)',
            '       |  ',
            '       0  '
        ]);

        test('with NumberLiteral and BinaryExpression', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(4 === -4)',
            '         |   |  ',
            '         |   -4 ',
            '         false  '
        ]);

        test('with Identifier and BinaryExpression', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(+num === -num)',
            '       ||   |   ||   ',
            '       ||   |   |1   ',
            '       ||   |   -1   ',
            '       |1   false    ',
            '       1             '
        ]);

        test('negation', function (transpiledCode) {
            var truth = true;
            eval(transpiledCode);
        }, [
            'assert(!truth)',
            '       ||     ',
            '       |true  ',
            '       false  '
        ]);

        test('double negation', function (transpiledCode) {
            var some = '';
            eval(transpiledCode);
        }, [
            'assert(!!some)',
            '       |||    ',
            '       ||""   ',
            '       |true  ',
            '       false  '
        ]);

        test('typeof operator', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert(typeof foo !== "undefined")',
            '       |          |               ',
            '       |          false           ',
            '       "undefined"                '
        ]);

        test('delete operator', function (transpiledCode) {
            var foo = {
                bar: {
                    baz: false
                }
            };
            eval(transpiledCode);
        }, [
            'assert(delete foo.bar === false)',
            '       |      |   |   |         ',
            '       |      |   |   false     ',
            '       |      |   Object{baz:false}',
            '       true   Object{bar:Object{baz:false}}',
        ]);
    });

    describe('MemberExpression', function () {
        test('computed: false', function (transpiledCode) {
            var en = { foo: false };
            eval(transpiledCode);
        }, [
            'assert(en.foo)',
            '       |  |   ',
            '       |  false',
            '       Object{foo:false}'
        ]);

        test('computed: false', function (transpiledCode) {
            var propName = 'foo';
            var en = { foo: false };
            eval(transpiledCode);
        }, [
            'assert(en[propName])',
            '       | ||         ',
            '       | |"foo"     ',
            '       | false      ',
            '       Object{foo:false}'
        ]);

        test('chained member', function (transpiledCode) {
            var en = { foo: { bar: false } };
            eval(transpiledCode);
        }, [
            'assert(en.foo.bar)',
            '       |  |   |   ',
            '       |  |   false',
            '       |  Object{bar:false}',
            '       Object{foo:Object{bar:false}}'
        ]);

        test('undefined property', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert({}.hoge === "xxx")',
            '       |  |    |         ',
            '       |  |    false     ',
            '       |  undefined      ',
            '       Object{}          '
        ]);
    });

    describe('CallExpression', function () {
        test('arguments', function (transpiledCode) {
            var name = 'bar';
            var age = 23;
            var foo = function (n, a) { return false; };
            eval(transpiledCode);
        }, [
            'assert(foo(name, age))',
            '       |   |     |    ',
            '       |   "bar" 23   ',
            '       false          '
        ]);

        test('deep CallExpression', function (transpiledCode) {
            var bar = function () { return 'baz'; };
            var en = { foo: function (n) { return false; } };
            eval(transpiledCode);
        }, [
            'assert(en.foo(bar()))',
            '       |  |   |      ',
            '       |  |   "baz"  ',
            '       |  false      ',
            '       Object{foo:#function#}'
        ]);
    });

    describe('BinaryExpression', function () {
        test('of BinaryExpression', function (transpiledCode) {
            var foo = 'foo';
            var bar = 'bar';
            eval(transpiledCode);
        }, [
            'assert(foo === bar === (foo === bar) === (foo === bar))',
            '       |   |   |   |    |   |   |    |    |   |   |    ',
            '       |   |   |   |    |   |   |    |    |   |   "bar"',
            '       |   |   |   |    |   |   |    |    |   false    ',
            '       |   |   |   |    |   |   |    |    "foo"        ',
            '       |   |   |   |    |   |   |    false             ',
            '       |   |   |   |    |   |   "bar"                  ',
            '       |   |   |   |    |   false                      ',
            '       |   |   |   true "foo"                          ',
            '       |   |   "bar"                                   ',
            '       |   false                                       ',
            '       "foo"                                           '
        ]);

        test('of Identifier', function (transpiledCode) {
            var foo = 'foo';
            var bar = 'bar';
            eval(transpiledCode);
        }, [
            'assert(foo === bar)',
            '       |   |   |   ',
            '       |   |   "bar"',
            '       |   false   ',
            '       "foo"       ',
        ]);

        test('of Identifier and StringLiteral', function (transpiledCode) {
            var foo = 'foo';
            eval(transpiledCode);
        }, [
            'assert(foo === "bar")',
            '       |   |         ',
            '       |   false     ',
            '       "foo"         ',
        ]);

        test('of StringLiteral', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert("foo" === "bar")',
            '             |         ',
            '             false     '
        ]);

        test('of NumberLiteral', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert(4 !== 4)',
            '         |     ',
            '         false '
        ]);

        test('of MemberExpression', function (transpiledCode) {
            var en = { foo: 'bar', toto: 'tata' };
            var fr = { toto: 'tata'};
            eval(transpiledCode);
        }, [
            'assert(en.foo === fr.toto)',
            '       |  |   |   |  |    ',
            '       |  |   |   |  "tata"',
            '       |  |   |   Object{toto:"tata"}',
            '       |  |   false       ',
            '       |  "bar"           ',
            '       Object{foo:"bar",toto:"tata"}'
        ]);

        test('of CallExpression', function (transpiledCode) {
            var en = { foo: function() { return 'bar';} };
            var fr = { toto: function() { return 'tata'; } };
            eval(transpiledCode);
        }, [
            'assert(en.foo() === fr.toto())',
            '       |  |     |   |  |      ',
            '       |  |     |   |  "tata" ',
            '       |  |     |   Object{toto:#function#}',
            '       |  "bar" false         ',
            '       Object{foo:#function#} '
        ]);

        test('non-Punctuator BinaryExpression operator', function (transpiledCode) {
            function Person (name) { this.name = name; };
            var foo = 'bob';
            eval(transpiledCode);
        }, [
            'assert(foo instanceof Person)',
            '       |   |          |      ',
            '       |   false      #function#',
            '       "bob"                 '
        ]);

        test('Loose equality', function (transpiledCode) {
            var truthy = '1';
            var falsy = false;
            eval(transpiledCode);
        }, [
            'assert(truthy == falsy)',
            '       |      |  |     ',
            '       |      |  false ',
            '       "1"    false    '
        ]);

        test('of NaN', function (transpiledCode) {
            var nan1 = NaN;
            var nan2 = NaN;
            eval(transpiledCode);
        }, [
            'assert(nan1 === nan2)',
            '       |    |   |    ',
            '       |    |   NaN  ',
            '       NaN  false    '
        ]);

        test('of Infinity', function (transpiledCode) {
            var positiveInfinity = Infinity;
            var negativeInfinity = -Infinity;
            eval(transpiledCode);
        }, [
            'assert(positiveInfinity === negativeInfinity)',
            '       |                |   |                ',
            '       |                |   -Infinity        ',
            '       Infinity         false                '
        ]);
    });

    describe('LogicalExpression', function () {
        test('of Identifiers', function (transpiledCode) {
            var x = false;
            var y = 0;
            var z = null;
            eval(transpiledCode);
        }, [
            'assert(x || y || z)',
            '       | |  | |  | ',
            '       | |  | |  null',
            '       | 0  0 null ',
            '       false       '
        ]);

        test('of Identifier evaluation order', function (transpiledCode) {
            var x = 'yeah';
            var y = 0;
            var z = true;
            eval(transpiledCode);
        }, [
            'assert(x && y && z)',
            '       | |  | |    ',
            '       | 0  0 0    ',
            '       "yeah"      '
        ]);

        test('of CallExpression and MemberExpression', function (transpiledCode) {
            var x = { foo: function(n) { return false; } };
            var y = function(n) { return null; };
            var z = { val: 0 };
            eval(transpiledCode);
        }, [
            'assert(x.foo() || y() || z.val)',
            '       | |     |  |   |  | |   ',
            '       | |     |  |   |  | 0   ',
            '       | |     |  |   0  Object{val:0}',
            '       | |     |  null         ',
            '       | false null            ',
            '       Object{foo:#function#}  '
        ]);
    });

    test('ArrayExpression as an argument of CallExpression', function (transpiledCode) {
        var pop = function (ary) { return ary.pop(); };
        var zero = 0;
        var one = 1;
        var two = 2;
        eval(transpiledCode);
    }, [
        'assert(pop([zero, one, two]) === one)',
        '       |   ||     |    |     |   |   ',
        '       |   ||     |    |     |   1   ',
        '       |   |0     1    2     false   ',
        '       2   [0,1]                     '
    ]);

    test('ObjectExpression', function (transpiledCode) {
        eval(transpiledCode);
    }, [
        'assert.deepEqual({ foo: 0 }, { foo: 1 })',
        '                 |           |          ',
        '                 |           Object{foo:1}',
        '                 Object{foo:0}          '
    ]);

    describe('ObjectRestSpread', function () {
        test('Spread Properties', function (transpiledCode) {
            var a = 'a';
            var b = 'b';
            var obj = { foo: 'FOO', bar: 'BAR' };
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ b, ...obj }, { a, ...obj })',
            '                 |              |             ',
            '                 |              Object{a:"a",foo:"FOO",bar:"BAR"}',
            '                 Object{b:"b",foo:"FOO",bar:"BAR"}'
        ]);
    });

    describe('Function Bind Syntax', function () {
        test('avajs/ava#881', function (transpiledCode) {
            function validate(name) {
                return {
                    name: name,
                    valid: true,
                    value: this
                };
            }
            eval(transpiledCode);
        }, [
            'assert.deepEqual(true::validate("foo"), { valid: true, value: true, name: "bar" })',
            '                 |                      |                                         ',
            '                 |                      Object{valid:true,value:true,name:"bar"}  ',
            '                 Object{name:"foo",valid:true,value:true}                         '
        ]);
    });

});
<commit_msg>test(power-assert-renderer-diagram): tests for ConditionalExpression<commit_after>'use strict';

delete require.cache[require.resolve('..')];
var DiagramRenderer = require('..');
var createRendererTester = require('../../../test_helper/create-renderer-tester');
var test = createRendererTester(DiagramRenderer);
var assert = require('../../../test_helper/empowered-assert');

describe('DiagramRenderer', function () {

    describe('Identifier', function () {
        test('boolean', function (transpiledCode) {
            var truthy = false;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       false  ',
        ]);

        test('empty string', function (transpiledCode) {
            var truthy = '';
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       ""     ',
        ]);

        test('zero', function (transpiledCode) {
            var truthy = 0;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       0      ',
        ]);

        test('undefined', function (transpiledCode) {
            var truthy = undefined;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       undefined',
        ]);
    });

    describe('UnaryExpression', function () {
        test('with NumberLiteral', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(-0)',
            '       |  ',
            '       0  '
        ]);

        test('with NumberLiteral and BinaryExpression', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(4 === -4)',
            '         |   |  ',
            '         |   -4 ',
            '         false  '
        ]);

        test('with Identifier and BinaryExpression', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(+num === -num)',
            '       ||   |   ||   ',
            '       ||   |   |1   ',
            '       ||   |   -1   ',
            '       |1   false    ',
            '       1             '
        ]);

        test('negation', function (transpiledCode) {
            var truth = true;
            eval(transpiledCode);
        }, [
            'assert(!truth)',
            '       ||     ',
            '       |true  ',
            '       false  '
        ]);

        test('double negation', function (transpiledCode) {
            var some = '';
            eval(transpiledCode);
        }, [
            'assert(!!some)',
            '       |||    ',
            '       ||""   ',
            '       |true  ',
            '       false  '
        ]);

        test('typeof operator', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert(typeof foo !== "undefined")',
            '       |          |               ',
            '       |          false           ',
            '       "undefined"                '
        ]);

        test('delete operator', function (transpiledCode) {
            var foo = {
                bar: {
                    baz: false
                }
            };
            eval(transpiledCode);
        }, [
            'assert(delete foo.bar === false)',
            '       |      |   |   |         ',
            '       |      |   |   false     ',
            '       |      |   Object{baz:false}',
            '       true   Object{bar:Object{baz:false}}',
        ]);
    });

    describe('MemberExpression', function () {
        test('computed: false', function (transpiledCode) {
            var en = { foo: false };
            eval(transpiledCode);
        }, [
            'assert(en.foo)',
            '       |  |   ',
            '       |  false',
            '       Object{foo:false}'
        ]);

        test('computed: false', function (transpiledCode) {
            var propName = 'foo';
            var en = { foo: false };
            eval(transpiledCode);
        }, [
            'assert(en[propName])',
            '       | ||         ',
            '       | |"foo"     ',
            '       | false      ',
            '       Object{foo:false}'
        ]);

        test('chained member', function (transpiledCode) {
            var en = { foo: { bar: false } };
            eval(transpiledCode);
        }, [
            'assert(en.foo.bar)',
            '       |  |   |   ',
            '       |  |   false',
            '       |  Object{bar:false}',
            '       Object{foo:Object{bar:false}}'
        ]);

        test('undefined property', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert({}.hoge === "xxx")',
            '       |  |    |         ',
            '       |  |    false     ',
            '       |  undefined      ',
            '       Object{}          '
        ]);
    });

    describe('CallExpression', function () {
        test('arguments', function (transpiledCode) {
            var name = 'bar';
            var age = 23;
            var foo = function (n, a) { return false; };
            eval(transpiledCode);
        }, [
            'assert(foo(name, age))',
            '       |   |     |    ',
            '       |   "bar" 23   ',
            '       false          '
        ]);

        test('deep CallExpression', function (transpiledCode) {
            var bar = function () { return 'baz'; };
            var en = { foo: function (n) { return false; } };
            eval(transpiledCode);
        }, [
            'assert(en.foo(bar()))',
            '       |  |   |      ',
            '       |  |   "baz"  ',
            '       |  false      ',
            '       Object{foo:#function#}'
        ]);
    });

    describe('BinaryExpression', function () {
        test('of BinaryExpression', function (transpiledCode) {
            var foo = 'foo';
            var bar = 'bar';
            eval(transpiledCode);
        }, [
            'assert(foo === bar === (foo === bar) === (foo === bar))',
            '       |   |   |   |    |   |   |    |    |   |   |    ',
            '       |   |   |   |    |   |   |    |    |   |   "bar"',
            '       |   |   |   |    |   |   |    |    |   false    ',
            '       |   |   |   |    |   |   |    |    "foo"        ',
            '       |   |   |   |    |   |   |    false             ',
            '       |   |   |   |    |   |   "bar"                  ',
            '       |   |   |   |    |   false                      ',
            '       |   |   |   true "foo"                          ',
            '       |   |   "bar"                                   ',
            '       |   false                                       ',
            '       "foo"                                           '
        ]);

        test('of Identifier', function (transpiledCode) {
            var foo = 'foo';
            var bar = 'bar';
            eval(transpiledCode);
        }, [
            'assert(foo === bar)',
            '       |   |   |   ',
            '       |   |   "bar"',
            '       |   false   ',
            '       "foo"       ',
        ]);

        test('of Identifier and StringLiteral', function (transpiledCode) {
            var foo = 'foo';
            eval(transpiledCode);
        }, [
            'assert(foo === "bar")',
            '       |   |         ',
            '       |   false     ',
            '       "foo"         ',
        ]);

        test('of StringLiteral', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert("foo" === "bar")',
            '             |         ',
            '             false     '
        ]);

        test('of NumberLiteral', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert(4 !== 4)',
            '         |     ',
            '         false '
        ]);

        test('of MemberExpression', function (transpiledCode) {
            var en = { foo: 'bar', toto: 'tata' };
            var fr = { toto: 'tata'};
            eval(transpiledCode);
        }, [
            'assert(en.foo === fr.toto)',
            '       |  |   |   |  |    ',
            '       |  |   |   |  "tata"',
            '       |  |   |   Object{toto:"tata"}',
            '       |  |   false       ',
            '       |  "bar"           ',
            '       Object{foo:"bar",toto:"tata"}'
        ]);

        test('of CallExpression', function (transpiledCode) {
            var en = { foo: function() { return 'bar';} };
            var fr = { toto: function() { return 'tata'; } };
            eval(transpiledCode);
        }, [
            'assert(en.foo() === fr.toto())',
            '       |  |     |   |  |      ',
            '       |  |     |   |  "tata" ',
            '       |  |     |   Object{toto:#function#}',
            '       |  "bar" false         ',
            '       Object{foo:#function#} '
        ]);

        test('non-Punctuator BinaryExpression operator', function (transpiledCode) {
            function Person (name) { this.name = name; };
            var foo = 'bob';
            eval(transpiledCode);
        }, [
            'assert(foo instanceof Person)',
            '       |   |          |      ',
            '       |   false      #function#',
            '       "bob"                 '
        ]);

        test('Loose equality', function (transpiledCode) {
            var truthy = '1';
            var falsy = false;
            eval(transpiledCode);
        }, [
            'assert(truthy == falsy)',
            '       |      |  |     ',
            '       |      |  false ',
            '       "1"    false    '
        ]);

        test('of NaN', function (transpiledCode) {
            var nan1 = NaN;
            var nan2 = NaN;
            eval(transpiledCode);
        }, [
            'assert(nan1 === nan2)',
            '       |    |   |    ',
            '       |    |   NaN  ',
            '       NaN  false    '
        ]);

        test('of Infinity', function (transpiledCode) {
            var positiveInfinity = Infinity;
            var negativeInfinity = -Infinity;
            eval(transpiledCode);
        }, [
            'assert(positiveInfinity === negativeInfinity)',
            '       |                |   |                ',
            '       |                |   -Infinity        ',
            '       Infinity         false                '
        ]);
    });

    describe('LogicalExpression', function () {
        test('of Identifiers', function (transpiledCode) {
            var x = false;
            var y = 0;
            var z = null;
            eval(transpiledCode);
        }, [
            'assert(x || y || z)',
            '       | |  | |  | ',
            '       | |  | |  null',
            '       | 0  0 null ',
            '       false       '
        ]);

        test('of Identifier evaluation order', function (transpiledCode) {
            var x = 'yeah';
            var y = 0;
            var z = true;
            eval(transpiledCode);
        }, [
            'assert(x && y && z)',
            '       | |  | |    ',
            '       | 0  0 0    ',
            '       "yeah"      '
        ]);

        test('of CallExpression and MemberExpression', function (transpiledCode) {
            var x = { foo: function(n) { return false; } };
            var y = function(n) { return null; };
            var z = { val: 0 };
            eval(transpiledCode);
        }, [
            'assert(x.foo() || y() || z.val)',
            '       | |     |  |   |  | |   ',
            '       | |     |  |   |  | 0   ',
            '       | |     |  |   0  Object{val:0}',
            '       | |     |  null         ',
            '       | false null            ',
            '       Object{foo:#function#}  '
        ]);
    });

    describe('ConditionalExpression', function () {
        test('of Identifiers, consequent', function (transpiledCode) {
            var foo = false;
            var bar = null;
            var baz = 0;
            eval(transpiledCode);
        }, [
            'assert(foo ? bar : baz)',
            '       |           |   ',
            '       false       0   '
        ]);
        test('of Identifiers, alternate', function (transpiledCode) {
            var foo = true;
            var bar = null;
            var baz = 0;
            eval(transpiledCode);
        }, [
            'assert(foo ? bar : baz)',
            '       |     |         ',
            '       true  null      '
        ]);
        test('of another ConditionalExpression', function (transpiledCode) {
            var falsy = null;
            var truthy = 'truth';
            var anotherFalsy = 0;
            eval(transpiledCode);
        }, [
            'assert(falsy ? truthy : truthy ? anotherFalsy : truthy)',
            '       |                |        |                     ',
            '       null             "truth"  0                     '
        ]);
    });

    test('ArrayExpression as an argument of CallExpression', function (transpiledCode) {
        var pop = function (ary) { return ary.pop(); };
        var zero = 0;
        var one = 1;
        var two = 2;
        eval(transpiledCode);
    }, [
        'assert(pop([zero, one, two]) === one)',
        '       |   ||     |    |     |   |   ',
        '       |   ||     |    |     |   1   ',
        '       |   |0     1    2     false   ',
        '       2   [0,1]                     '
    ]);

    test('ObjectExpression', function (transpiledCode) {
        eval(transpiledCode);
    }, [
        'assert.deepEqual({ foo: 0 }, { foo: 1 })',
        '                 |           |          ',
        '                 |           Object{foo:1}',
        '                 Object{foo:0}          '
    ]);

    describe('ObjectRestSpread', function () {
        test('Spread Properties', function (transpiledCode) {
            var a = 'a';
            var b = 'b';
            var obj = { foo: 'FOO', bar: 'BAR' };
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ b, ...obj }, { a, ...obj })',
            '                 |              |             ',
            '                 |              Object{a:"a",foo:"FOO",bar:"BAR"}',
            '                 Object{b:"b",foo:"FOO",bar:"BAR"}'
        ]);
    });

    describe('Function Bind Syntax', function () {
        test('avajs/ava#881', function (transpiledCode) {
            function validate(name) {
                return {
                    name: name,
                    valid: true,
                    value: this
                };
            }
            eval(transpiledCode);
        }, [
            'assert.deepEqual(true::validate("foo"), { valid: true, value: true, name: "bar" })',
            '                 |                      |                                         ',
            '                 |                      Object{valid:true,value:true,name:"bar"}  ',
            '                 Object{name:"foo",valid:true,value:true}                         '
        ]);
    });

});
<|endoftext|>


<commit_before>/*
 * script dependencies
 *
 * jQuery
 * socket.io
 */

$(document).ready( function($) {
  var socket = io();

  var $loginWrap = $('#login-wrap')
    , $chatWrap = $('#chat-wrap')
    , $loginError = $('#login-error-display')
    , $messageForm = $('#send-message')
    , $loginForm = $('#send-login')
    , $usernameBox = $('#username-box')
    , $messageBox = $('#message-box')
    , $messageDisplay = $('#chat-display')
    , $userlistWrap = $('#userlist-wrap')
    , $userlist = $('#userlist')
  ;

  // Start in login view.
  $chatWrap.hide();
  $loginWrap.show();

  $loginForm.submit(function(_event) {
    _event.preventDefault();

    socket.emit('user-login', {
      'time': Date.now()
    , 'user': $usernameBox.val()
    });

  });

  $messageForm.submit(function(_event) {
    _event.preventDefault();

    var message = $messageBox.val();

    socket.emit('message-server', {
      'time': Date.now()
    , 'message': message
    });

    $messageBox.val('');
  });

  // Userlist
  var userlist = new rp.html.ListDiv($userlist.prop('id'), {});
  userlist.initHtml();

  socket.on('user-login-response', function(_data) {
    if(_data.successful === true) {
      // Switch to chat view.
      $loginWrap.hide();
      $chatWrap.show();
    } else {
      $loginError.text(_data.error);
    }
  });

  socket.on('message-client', function(_data) {
    if(_data.error) {
      $messageDisplay.append('
' + '' + _data.error + '' + '
');
      return;
    }

    $messageDisplay.append('
' + '' + _data.user + ': ' + '' + _data.message + '
');
  });

  socket.on('user-signing', function(_data) {
    if(_data.type === 'SIGNIN') {
      userlist.addToList(_data.user);
      $messageDisplay.append('
' + '' + _data.user + ' joined' + '' + '
');
    } else if (_data.type === 'SIGNOUT') {
      userlist.removeFromList(_data.user);
      $messageDisplay.append('
' + '' + _data.user + ' left' + '' + '
');
    }
  });
});
<commit_msg>Hides userlist if not logged in.<commit_after>/*
 * script dependencies
 *
 * jQuery
 * socket.io
 */

$(document).ready( function($) {
  var socket = io();

  var $loginWrap = $('#login-wrap')
    , $chatWrap = $('#chat-wrap')
    , $loginError = $('#login-error-display')
    , $messageForm = $('#send-message')
    , $loginForm = $('#send-login')
    , $usernameBox = $('#username-box')
    , $messageBox = $('#message-box')
    , $messageDisplay = $('#chat-display')
    , $userlistWrap = $('#userlist-wrap')
    , $userlist = $('#userlist')
  ;

  // Start in login view.
  $chatWrap.hide();
  $userlistWrap.hide();
  $loginWrap.show();

  $loginForm.submit(function(_event) {
    _event.preventDefault();

    socket.emit('user-login', {
      'time': Date.now()
    , 'user': $usernameBox.val()
    });

  });

  $messageForm.submit(function(_event) {
    _event.preventDefault();

    var message = $messageBox.val();

    socket.emit('message-server', {
      'time': Date.now()
    , 'message': message
    });

    $messageBox.val('');
  });

  // Userlist
  var userlist = new rp.html.ListDiv($userlist.prop('id'), {});
  userlist.initHtml();

  socket.on('user-login-response', function(_data) {
    if(_data.successful === true) {
      // Switch to chat view.
      $loginWrap.hide();
      $chatWrap.show();
      $userlistWrap.show();
    } else {
      $loginError.text(_data.error);
    }
  });

  socket.on('message-client', function(_data) {
    if(_data.error) {
      $messageDisplay.append('
' + '' + _data.error + '' + '
');
      return;
    }

    $messageDisplay.append('
' + '' + _data.user + ': ' + '' + _data.message + '
');
  });

  socket.on('user-signing', function(_data) {
    if(_data.type === 'SIGNIN') {
      userlist.addToList(_data.user);
      $messageDisplay.append('
' + '' + _data.user + ' joined' + '' + '
');
    } else if (_data.type === 'SIGNOUT') {
      userlist.removeFromList(_data.user);
      $messageDisplay.append('
' + '' + _data.user + ' left' + '' + '
');
    }
  });
});
<|endoftext|>


<commit_before>$(document).ready(function() {
    $backToTopEle = $('

').appendTo($("body")).attr("title", "返回顶部").click(function() {
        $("html, body").animate({
            scrollTop: 0
        }, 120);
    }),
    $backToTopFun = function() {
        var st = $(document).scrollTop(),
            winh = $(window).height();
        (st > 0) ? $backToTopEle.show() : $backToTopEle.hide();
        //IE6下的定位
        if (!window.XMLHttpRequest) {
            $backToTopEle.css("top", st + winh - 166);
        }
    };
    $(window).bind("scroll", $backToTopFun);
    $backToTopFun();

    $(document).pjax('a', '#pjax-container')
});<commit_msg>添加pjax事件<commit_after>$(document).ready(function() {
    $backToTopEle = $('

').appendTo($("body")).attr("title", "返回顶部").click(function() {
        $("html, body").animate({
            scrollTop: 0
        }, 120);
    }),
    $backToTopFun = function() {
        var st = $(document).scrollTop(),
            winh = $(window).height();
        (st > 0) ? $backToTopEle.show() : $backToTopEle.hide();
        //IE6下的定位
        if (!window.XMLHttpRequest) {
            $backToTopEle.css("top", st + winh - 166);
        }
    };
    $(window).bind("scroll", $backToTopFun);
    $backToTopFun();

    $(document).pjax('a', '#pjax-container')

    $(document).on('pjax:send', function() {
        $('#loading').show()
    })

    $(document).on('pjax:complete', function() {
        $('#loading').hide()
    })

    $(document).on('pjax:timeout', function(event) {
        event.preventDefault()
    })
});<|endoftext|>


<commit_before>var gulp = require('gulp');
var plugins = require("gulp-load-plugins")({
    pattern: ['gulp-*', 'del'],
    lazy:false
});

var paths = {
    dest: 'buildjs/static/public'
}

gulp.task('scripts', function(){
    //combine all js files of the app
    gulp.src(['!./app/**/*_test.js','./app/**/*.js'])
        .pipe(plugins.jshint())
        .pipe(plugins.jshint.reporter('default'))
        .pipe(plugins.concat('app.js'))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('templates',function(){
    //combine all template files of the app into a js file
    gulp.src(['!./app/index.html',
        './app/**/*.html'])
        .pipe(plugins.angularTemplatecache('templates.js',{standalone:true}))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('css', function(){
    gulp.src('./app/**/*.css')
        .pipe(plugins.concat('app.css'))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('vendorJS', function(){
    //concatenate vendor JS files
    gulp.src(['!./bower_components/**/*.min.js',
        './bower_components/**/*.js'])
        .pipe(plugins.concat('lib.js'))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('vendorCSS', function(){
    //concatenate vendor CSS files
    gulp.src(['!./bower_components/**/*.min.css',
        './bower_components/**/*.css'])
        .pipe(plugins.concat('lib.css'))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('copy-index', function() {
    gulp.src('./app/index.html')
        .pipe(gulp.dest(paths.dest));
});

gulp.task('watch',function(){
    gulp.watch([
        'build/**/*.html',
        'build/**/*.js',
        'build/**/*.css'
    ], function(event) {
        return gulp.src(event.path)
            .pipe(plugins.connect.reload());
    });
    gulp.watch(['./app/**/*.js','!./app/**/*test.js'],['scripts']);
    gulp.watch(['!./app/index.html','./app/**/*.html'],['templates']);
    gulp.watch('./app/**/*.css',['css']);
    gulp.watch('./app/index.html',['copy-index']);

});

gulp.task('connect', plugins.connect.server({
    root: ['build'],
    port: 9000,
    livereload: true
}));

gulp.task('clean', function (done) {
    plugins.del([paths.dest], done);
});

gulp.task('build',['scripts','templates','css','copy-index','vendorJS','vendorCSS']);

gulp.task('default', ['clean'], function () {
    gulp.start('build');
});
<commit_msg>ensure valid vendor dependency order<commit_after>var gulp = require('gulp');
var plugins = require("gulp-load-plugins")({
    pattern: ['gulp-*', 'del'],
    lazy:false
});

var paths = {
    dest: 'buildjs/static/public'
}

gulp.task('scripts', function(){
    //combine all js files of the app
    gulp.src(['!./app/**/*_test.js','./app/**/*.js'])
        .pipe(plugins.jshint())
        .pipe(plugins.jshint.reporter('default'))
        .pipe(plugins.concat('app.js'))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('templates',function(){
    //combine all template files of the app into a js file
    gulp.src(['!./app/index.html',
        './app/**/*.html'])
        .pipe(plugins.angularTemplatecache('templates.js',{standalone:true}))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('css', function(){
    gulp.src('./app/**/*.css')
        .pipe(plugins.concat('app.css'))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('vendorJS', function(){
    //concatenate vendor JS files
		//NOTE: Using a glob pattern might cause a invalid concatenation order
		//      of the vendor dependencies => use https://github.com/ck86/main-bower-files to solve this issue
    gulp.src(['./bower_components/angular/angular.js', './bower_components/angular-route/angular-route.js'])
        .pipe(plugins.concat('lib.js'))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('vendorCSS', function(){
    //concatenate vendor CSS files
    gulp.src(['!./bower_components/**/*.min.css',
        './bower_components/**/*.css'])
        .pipe(plugins.concat('lib.css'))
        .pipe(gulp.dest(paths.dest));
});

gulp.task('copy-index', function() {
    gulp.src('./app/index.html')
        .pipe(gulp.dest(paths.dest));
});

gulp.task('watch',function(){
    gulp.watch([
        'build/**/*.html',
        'build/**/*.js',
        'build/**/*.css'
    ], function(event) {
        return gulp.src(event.path)
            .pipe(plugins.connect.reload());
    });
    gulp.watch(['./app/**/*.js','!./app/**/*test.js'],['scripts']);
    gulp.watch(['!./app/index.html','./app/**/*.html'],['templates']);
    gulp.watch('./app/**/*.css',['css']);
    gulp.watch('./app/index.html',['copy-index']);

});

gulp.task('connect', plugins.connect.server({
    root: ['build'],
    port: 9000,
    livereload: true
}));

gulp.task('clean', function (done) {
    plugins.del([paths.dest], done);
});

gulp.task('build',['scripts','templates','css','copy-index','vendorJS','vendorCSS']);

gulp.task('default', ['clean'], function () {
    gulp.start('build');
});
<|endoftext|>


<commit_before>const Promise = require(`bluebird`)
const _ = require(`lodash`)
const chalk = require(`chalk`)
const { bindActionCreators } = require(`redux`)

const tracer = require(`opentracing`).globalTracer()
const reporter = require(`gatsby-cli/lib/reporter`)
const getCache = require(`./get-cache`)
const createNodeId = require(`./create-node-id`)
const { createContentDigest } = require(`gatsby-core-utils`)
const {
  buildObjectType,
  buildUnionType,
  buildInterfaceType,
  buildInputObjectType,
  buildEnumType,
  buildScalarType,
} = require(`../schema/types/type-builders`)
const { emitter, store } = require(`../redux`)
const getPublicPath = require(`./get-public-path`)
const { getNonGatsbyCodeFrameFormatted } = require(`./stack-trace-utils`)
const { trackBuildError, decorateEvent } = require(`gatsby-telemetry`)

// Bind action creators per plugin so we can auto-add
// metadata to actions they create.
const boundPluginActionCreators = {}
const doubleBind = (boundActionCreators, api, plugin, actionOptions) => {
  const { traceId } = actionOptions
  if (boundPluginActionCreators[plugin.name + api + traceId]) {
    return boundPluginActionCreators[plugin.name + api + traceId]
  } else {
    const keys = Object.keys(boundActionCreators)
    const doubleBoundActionCreators = {}
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      const boundActionCreator = boundActionCreators[key]
      if (typeof boundActionCreator === `function`) {
        doubleBoundActionCreators[key] = (...args) => {
          // Let action callers override who the plugin is. Shouldn't be
          // used that often.
          if (args.length === 1) {
            return boundActionCreator(args[0], plugin, actionOptions)
          } else if (args.length === 2) {
            return boundActionCreator(args[0], args[1], actionOptions)
          }
          return undefined
        }
      }
    }
    boundPluginActionCreators[
      plugin.name + api + traceId
    ] = doubleBoundActionCreators
    return doubleBoundActionCreators
  }
}

const initAPICallTracing = parentSpan => {
  const startSpan = (spanName, spanArgs = {}) => {
    const defaultSpanArgs = { childOf: parentSpan }

    return tracer.startSpan(spanName, _.merge(defaultSpanArgs, spanArgs))
  }

  return {
    tracer,
    parentSpan,
    startSpan,
  }
}

const getLocalReporter = (activity, reporter) =>
  activity
    ? { ...reporter, panicOnBuild: activity.panicOnBuild.bind(activity) }
    : reporter

const runAPI = (plugin, api, args, activity) => {
  const gatsbyNode = require(`${plugin.resolve}/gatsby-node`)
  if (gatsbyNode[api]) {
    const parentSpan = args && args.parentSpan
    const spanOptions = parentSpan ? { childOf: parentSpan } : {}
    const pluginSpan = tracer.startSpan(`run-plugin`, spanOptions)

    pluginSpan.setTag(`api`, api)
    pluginSpan.setTag(`plugin`, plugin.name)

    const {
      loadNodeContent,
      getNodes,
      getNode,
      getNodesByType,
      hasNodeChanged,
      getNodeAndSavePathDependency,
    } = require(`../db/nodes`)
    const {
      publicActions,
      restrictedActionsAvailableInAPI,
    } = require(`../redux/actions`)
    const availableActions = {
      ...publicActions,
      ...(restrictedActionsAvailableInAPI[api] || {}),
    }
    const boundActionCreators = bindActionCreators(
      availableActions,
      store.dispatch
    )
    const doubleBoundActionCreators = doubleBind(
      boundActionCreators,
      api,
      plugin,
      { ...args, parentSpan: pluginSpan, activity }
    )

    const { config, program } = store.getState()

    const pathPrefix = (program.prefixPaths && config.pathPrefix) || ``
    const publicPath = getPublicPath({ ...config, ...program }, ``)

    const namespacedCreateNodeId = id => createNodeId(id, plugin.name)

    const tracing = initAPICallTracing(pluginSpan)

    const cache = getCache(plugin.name)

    // Ideally this would be more abstracted and applied to more situations, but right now
    // this can be potentially breaking so targeting `createPages` API and `createPage` action
    let actions = doubleBoundActionCreators
    let apiFinished = false
    if (api === `createPages`) {
      let alreadyDisplayed = false
      const createPageAction = actions.createPage
      // create new actions object with wrapped createPage action
      // doubleBoundActionCreators is memoized, so we can't just
      // reassign createPage field as this would cause this extra logic
      // to be used in subsequent APIs and we only want to target this `createPages` call.
      actions = {
        ...actions,
        createPage: (...args) => {
          createPageAction(...args)
          if (apiFinished && !alreadyDisplayed) {
            const warning = [
              reporter.stripIndent(`
              Action ${chalk.bold(
                `createPage`
              )} was called outside of its expected asynchronous lifecycle ${chalk.bold(
                `createPages`
              )} in ${chalk.bold(plugin.name)}.
              Ensure that you return a Promise from ${chalk.bold(
                `createPages`
              )} and are awaiting any asynchronous method invocations (like ${chalk.bold(
                `graphql`
              )} or http requests).
              For more info and debugging tips: see ${chalk.bold(
                `https://gatsby.dev/sync-actions`
              )}
            `),
            ]

            const possiblyCodeFrame = getNonGatsbyCodeFrameFormatted()
            if (possiblyCodeFrame) {
              warning.push(possiblyCodeFrame)
            }

            reporter.warn(warning.join(`\n\n`))
            alreadyDisplayed = true
          }
        },
      }
    }
    let localReporter = getLocalReporter(activity, reporter)

    const apiCallArgs = [
      {
        ...args,
        basePath: pathPrefix,
        pathPrefix: publicPath,
        boundActionCreators: actions,
        actions,
        loadNodeContent,
        store,
        emitter,
        getCache,
        getNodes,
        getNode,
        getNodesByType,
        hasNodeChanged,
        reporter: localReporter,
        getNodeAndSavePathDependency,
        cache,
        createNodeId: namespacedCreateNodeId,
        createContentDigest,
        tracing,
        schema: {
          buildObjectType,
          buildUnionType,
          buildInterfaceType,
          buildInputObjectType,
          buildEnumType,
          buildScalarType,
        },
      },
      plugin.pluginOptions,
    ]

    // If the plugin is using a callback use that otherwise
    // expect a Promise to be returned.
    if (gatsbyNode[api].length === 3) {
      return Promise.fromCallback(callback => {
        const cb = (err, val) => {
          pluginSpan.finish()
          callback(err, val)
          apiFinished = true
        }

        try {
          gatsbyNode[api](...apiCallArgs, cb)
        } catch (e) {
          trackBuildError(api, {
            error: e,
            pluginName: `${plugin.name}@${plugin.version}`,
          })
          throw e
        }
      })
    } else {
      const result = gatsbyNode[api](...apiCallArgs)
      pluginSpan.finish()
      return Promise.resolve(result).then(res => {
        apiFinished = true
        return res
      })
    }
  }

  return null
}

let apisRunningById = new Map()
let apisRunningByTraceId = new Map()
let waitingForCasacadeToFinish = []

module.exports = async (api, args = {}, { pluginSource, activity } = {}) =>
  new Promise(resolve => {
    const { parentSpan } = args
    const apiSpanArgs = parentSpan ? { childOf: parentSpan } : {}
    const apiSpan = tracer.startSpan(`run-api`, apiSpanArgs)

    apiSpan.setTag(`api`, api)
    _.forEach(args.traceTags, (value, key) => {
      apiSpan.setTag(key, value)
    })

    const plugins = store.getState().flattenedPlugins

    // Get the list of plugins that implement this API.
    // Also: Break infinite loops. Sometimes a plugin will implement an API and
    // call an action which will trigger the same API being called.
    // `onCreatePage` is the only example right now. In these cases, we should
    // avoid calling the originating plugin again.
    const implementingPlugins = plugins.filter(
      plugin => plugin.nodeAPIs.includes(api) && plugin.name !== pluginSource
    )

    const apiRunInstance = {
      api,
      args,
      pluginSource,
      resolve,
      span: apiSpan,
      startTime: new Date().toJSON(),
      traceId: args.traceId,
    }

    // Generate IDs for api runs. Most IDs we generate from the args
    // but some API calls can have very large argument objects so we
    // have special ways of generating IDs for those to avoid stringifying
    // large objects.
    let id
    if (api === `setFieldsOnGraphQLNodeType`) {
      id = `${api}${apiRunInstance.startTime}${args.type.name}${args.traceId}`
    } else if (api === `onCreateNode`) {
      id = `${api}${apiRunInstance.startTime}${args.node.internal.contentDigest}${args.traceId}`
    } else if (api === `preprocessSource`) {
      id = `${api}${apiRunInstance.startTime}${args.filename}${args.traceId}`
    } else if (api === `onCreatePage`) {
      id = `${api}${apiRunInstance.startTime}${args.page.path}${args.traceId}`
    } else {
      // When tracing is turned on, the `args` object will have a
      // `parentSpan` field that can be quite large. So we omit it
      // before calling stringify
      const argsJson = JSON.stringify(_.omit(args, `parentSpan`))
      id = `${api}|${apiRunInstance.startTime}|${apiRunInstance.traceId}|${argsJson}`
    }
    apiRunInstance.id = id

    if (args.waitForCascadingActions) {
      waitingForCasacadeToFinish.push(apiRunInstance)
    }

    if (apisRunningById.size === 0) {
      emitter.emit(`API_RUNNING_START`)
    }

    apisRunningById.set(apiRunInstance.id, apiRunInstance)
    if (apisRunningByTraceId.has(apiRunInstance.traceId)) {
      const currentCount = apisRunningByTraceId.get(apiRunInstance.traceId)
      apisRunningByTraceId.set(apiRunInstance.traceId, currentCount + 1)
    } else {
      apisRunningByTraceId.set(apiRunInstance.traceId, 1)
    }

    let stopQueuedApiRuns = false
    let onAPIRunComplete = null
    if (api === `onCreatePage`) {
      const path = args.page.path
      const actionHandler = action => {
        if (action.payload.path === path) {
          stopQueuedApiRuns = true
        }
      }
      emitter.on(`DELETE_PAGE`, actionHandler)
      onAPIRunComplete = () => {
        emitter.off(`DELETE_PAGE`, actionHandler)
      }
    }

    Promise.mapSeries(implementingPlugins, plugin => {
      if (stopQueuedApiRuns) {
        return null
      }

      let pluginName =
        plugin.name === `default-site-plugin` ? `gatsby-node.js` : plugin.name

      return new Promise(resolve => {
        resolve(runAPI(plugin, api, { ...args, parentSpan: apiSpan }, activity))
      }).catch(err => {
        decorateEvent(`BUILD_PANIC`, {
          pluginName: `${plugin.name}@${plugin.version}`,
        })

        let localReporter = getLocalReporter(activity, reporter)

        localReporter.panicOnBuild({
          id: `11321`,
          context: {
            pluginName,
            api,
            message: err instanceof Error ? err.message : err,
          },
          error: err instanceof Error ? err : undefined,
        })

        return null
      })
    }).then(results => {
      if (onAPIRunComplete) {
        onAPIRunComplete()
      }
      // Remove runner instance
      apisRunningById.delete(apiRunInstance.id)
      const currentCount = apisRunningByTraceId.get(apiRunInstance.traceId)
      apisRunningByTraceId.set(apiRunInstance.traceId, currentCount - 1)

      if (apisRunningById.size === 0) {
        emitter.emit(`API_RUNNING_QUEUE_EMPTY`)
      }

      // Filter empty results
      apiRunInstance.results = results.filter(result => !_.isEmpty(result))

      // Filter out empty responses and return if the
      // api caller isn't waiting for cascading actions to finish.
      if (!args.waitForCascadingActions) {
        apiSpan.finish()
        resolve(apiRunInstance.results)
      }

      // Check if any of our waiters are done.
      waitingForCasacadeToFinish = waitingForCasacadeToFinish.filter(
        instance => {
          // If none of its trace IDs are running, it's done.
          const apisByTraceIdCount = apisRunningByTraceId.get(instance.traceId)
          if (apisByTraceIdCount === 0) {
            instance.span.finish()
            instance.resolve(instance.results)
            return false
          } else {
            return true
          }
        }
      )
      return
    })
  })
<commit_msg>chore(gatsby): cleanup api runner promises (#19664)<commit_after>const _ = require(`lodash`)
const chalk = require(`chalk`)
const { bindActionCreators } = require(`redux`)

const tracer = require(`opentracing`).globalTracer()
const reporter = require(`gatsby-cli/lib/reporter`)
const getCache = require(`./get-cache`)
const createNodeId = require(`./create-node-id`)
const { createContentDigest } = require(`gatsby-core-utils`)
const {
  buildObjectType,
  buildUnionType,
  buildInterfaceType,
  buildInputObjectType,
  buildEnumType,
  buildScalarType,
} = require(`../schema/types/type-builders`)
const { emitter, store } = require(`../redux`)
const getPublicPath = require(`./get-public-path`)
const { getNonGatsbyCodeFrameFormatted } = require(`./stack-trace-utils`)
const { trackBuildError, decorateEvent } = require(`gatsby-telemetry`)

// Bind action creators per plugin so we can auto-add
// metadata to actions they create.
const boundPluginActionCreators = {}
const doubleBind = (boundActionCreators, api, plugin, actionOptions) => {
  const { traceId } = actionOptions
  if (boundPluginActionCreators[plugin.name + api + traceId]) {
    return boundPluginActionCreators[plugin.name + api + traceId]
  } else {
    const keys = Object.keys(boundActionCreators)
    const doubleBoundActionCreators = {}
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      const boundActionCreator = boundActionCreators[key]
      if (typeof boundActionCreator === `function`) {
        doubleBoundActionCreators[key] = (...args) => {
          // Let action callers override who the plugin is. Shouldn't be
          // used that often.
          if (args.length === 1) {
            return boundActionCreator(args[0], plugin, actionOptions)
          } else if (args.length === 2) {
            return boundActionCreator(args[0], args[1], actionOptions)
          }
          return undefined
        }
      }
    }
    boundPluginActionCreators[
      plugin.name + api + traceId
    ] = doubleBoundActionCreators
    return doubleBoundActionCreators
  }
}

const initAPICallTracing = parentSpan => {
  const startSpan = (spanName, spanArgs = {}) => {
    const defaultSpanArgs = { childOf: parentSpan }

    return tracer.startSpan(spanName, _.merge(defaultSpanArgs, spanArgs))
  }

  return {
    tracer,
    parentSpan,
    startSpan,
  }
}

const getLocalReporter = (activity, reporter) =>
  activity
    ? { ...reporter, panicOnBuild: activity.panicOnBuild.bind(activity) }
    : reporter

const runAPI = async (plugin, api, args, activity) => {
  const gatsbyNode = require(`${plugin.resolve}/gatsby-node`)
  if (gatsbyNode[api]) {
    const parentSpan = args && args.parentSpan
    const spanOptions = parentSpan ? { childOf: parentSpan } : {}
    const pluginSpan = tracer.startSpan(`run-plugin`, spanOptions)

    pluginSpan.setTag(`api`, api)
    pluginSpan.setTag(`plugin`, plugin.name)

    const {
      loadNodeContent,
      getNodes,
      getNode,
      getNodesByType,
      hasNodeChanged,
      getNodeAndSavePathDependency,
    } = require(`../db/nodes`)
    const {
      publicActions,
      restrictedActionsAvailableInAPI,
    } = require(`../redux/actions`)
    const availableActions = {
      ...publicActions,
      ...(restrictedActionsAvailableInAPI[api] || {}),
    }
    const boundActionCreators = bindActionCreators(
      availableActions,
      store.dispatch
    )
    const doubleBoundActionCreators = doubleBind(
      boundActionCreators,
      api,
      plugin,
      { ...args, parentSpan: pluginSpan, activity }
    )

    const { config, program } = store.getState()

    const pathPrefix = (program.prefixPaths && config.pathPrefix) || ``
    const publicPath = getPublicPath({ ...config, ...program }, ``)

    const namespacedCreateNodeId = id => createNodeId(id, plugin.name)

    const tracing = initAPICallTracing(pluginSpan)

    const cache = getCache(plugin.name)

    // Ideally this would be more abstracted and applied to more situations, but right now
    // this can be potentially breaking so targeting `createPages` API and `createPage` action
    let actions = doubleBoundActionCreators
    let apiFinished = false
    if (api === `createPages`) {
      let alreadyDisplayed = false
      const createPageAction = actions.createPage
      // create new actions object with wrapped createPage action
      // doubleBoundActionCreators is memoized, so we can't just
      // reassign createPage field as this would cause this extra logic
      // to be used in subsequent APIs and we only want to target this `createPages` call.
      actions = {
        ...actions,
        createPage: (...args) => {
          createPageAction(...args)
          if (apiFinished && !alreadyDisplayed) {
            const warning = [
              reporter.stripIndent(`
              Action ${chalk.bold(
                `createPage`
              )} was called outside of its expected asynchronous lifecycle ${chalk.bold(
                `createPages`
              )} in ${chalk.bold(plugin.name)}.
              Ensure that you return a Promise from ${chalk.bold(
                `createPages`
              )} and are awaiting any asynchronous method invocations (like ${chalk.bold(
                `graphql`
              )} or http requests).
              For more info and debugging tips: see ${chalk.bold(
                `https://gatsby.dev/sync-actions`
              )}
            `),
            ]

            const possiblyCodeFrame = getNonGatsbyCodeFrameFormatted()
            if (possiblyCodeFrame) {
              warning.push(possiblyCodeFrame)
            }

            reporter.warn(warning.join(`\n\n`))
            alreadyDisplayed = true
          }
        },
      }
    }
    let localReporter = getLocalReporter(activity, reporter)

    const apiCallArgs = [
      {
        ...args,
        basePath: pathPrefix,
        pathPrefix: publicPath,
        boundActionCreators: actions,
        actions,
        loadNodeContent,
        store,
        emitter,
        getCache,
        getNodes,
        getNode,
        getNodesByType,
        hasNodeChanged,
        reporter: localReporter,
        getNodeAndSavePathDependency,
        cache,
        createNodeId: namespacedCreateNodeId,
        createContentDigest,
        tracing,
        schema: {
          buildObjectType,
          buildUnionType,
          buildInterfaceType,
          buildInputObjectType,
          buildEnumType,
          buildScalarType,
        },
      },
      plugin.pluginOptions,
    ]

    // If the plugin is using a callback use that otherwise
    // expect a Promise to be returned.
    if (gatsbyNode[api].length === 3) {
      return new Promise((resolve, reject) => {
        const cb = (err, val) => {
          pluginSpan.finish()
          apiFinished = true
          if (err) reject(err)
          else resolve(val)
        }

        try {
          gatsbyNode[api](...apiCallArgs, cb)
        } catch (e) {
          trackBuildError(api, {
            error: e,
            pluginName: `${plugin.name}@${plugin.version}`,
          })
          throw e
        }
      })
    }

    const result = await gatsbyNode[api](...apiCallArgs)
    pluginSpan.finish()
    apiFinished = true
    return result
  }

  return null
}

let apiRunnersActive = 0
let apisRunningByTraceId = new Map()
let waitingForCasacadeToFinish = []

module.exports = async (api, args = {}, { pluginSource, activity } = {}) => {
  let resolve
  let promise = new Promise(res => (resolve = res)) // This is guaranteed to assign to `resolve` in sync

  const { parentSpan, traceId, traceTags, waitForCascadingActions } = args

  const apiSpanArgs = parentSpan ? { childOf: parentSpan } : {}
  const apiSpan = tracer.startSpan(`run-api`, apiSpanArgs)

  apiSpan.setTag(`api`, api)
  _.forEach(traceTags, (value, key) => {
    apiSpan.setTag(key, value)
  })

  const plugins = store.getState().flattenedPlugins

  // Get the list of plugins that implement this API.
  // Also: Break infinite loops. Sometimes a plugin will implement an API and
  // call an action which will trigger the same API being called.
  // `onCreatePage` is the only example right now. In these cases, we should
  // avoid calling the originating plugin again.
  const implementingPlugins = plugins.filter(
    plugin => plugin.nodeAPIs.includes(api) && plugin.name !== pluginSource
  )

  const apiRunInstance = {
    api,
    resolve,
    span: apiSpan,
    traceId,
  }

  if (waitForCascadingActions) {
    waitingForCasacadeToFinish.push(apiRunInstance)
  }

  if (apiRunnersActive === 0) {
    emitter.emit(`API_RUNNING_START`)
  }
  ++apiRunnersActive

  if (apisRunningByTraceId.has(apiRunInstance.traceId)) {
    const currentCount = apisRunningByTraceId.get(apiRunInstance.traceId)
    apisRunningByTraceId.set(apiRunInstance.traceId, currentCount + 1)
  } else {
    apisRunningByTraceId.set(apiRunInstance.traceId, 1)
  }

  let stopQueuedApiRuns = false
  let onAPIRunComplete = null
  if (api === `onCreatePage`) {
    const path = args.page.path
    const actionHandler = action => {
      if (action.payload.path === path) {
        stopQueuedApiRuns = true
      }
    }
    emitter.on(`DELETE_PAGE`, actionHandler)
    onAPIRunComplete = () => {
      emitter.off(`DELETE_PAGE`, actionHandler)
    }
  }

  let results = []
  for (const plugin of implementingPlugins) {
    if (stopQueuedApiRuns) {
      break
    }
    let result = await runPlugin(
      api,
      plugin,
      args,
      stopQueuedApiRuns,
      activity,
      apiSpan
    )
    results.push(result)
  }

  if (onAPIRunComplete) {
    onAPIRunComplete()
  }
  // Remove runner instance
  const currentCount = apisRunningByTraceId.get(apiRunInstance.traceId)
  apisRunningByTraceId.set(apiRunInstance.traceId, currentCount - 1)

  --apiRunnersActive
  if (apiRunnersActive === 0) {
    emitter.emit(`API_RUNNING_QUEUE_EMPTY`)
  }

  // Filter empty results
  apiRunInstance.results = results.filter(result => !_.isEmpty(result))

  // Filter out empty responses and return if the
  // api caller isn't waiting for cascading actions to finish.
  if (!waitForCascadingActions) {
    apiSpan.finish()
    resolve(apiRunInstance.results)
  }

  // Check if any of our waiters are done.
  waitingForCasacadeToFinish = waitingForCasacadeToFinish.filter(instance => {
    // If none of its trace IDs are running, it's done.
    const apisByTraceIdCount = apisRunningByTraceId.get(instance.traceId)
    if (apisByTraceIdCount === 0) {
      instance.span.finish()
      instance.resolve(instance.results)
      return false
    } else {
      return true
    }
  })

  // This promise will resolve with the results for all the plugin calls for this particular api call.
  // If args.waitForCascadingActions is true, it will wait for all concurrent calls with the same api to resolve.
  // If args.waitForCascadingActions is false, it should be resolved by the time the code reaches here
  return promise
}

function runPlugin(api, plugin, args, stopQueuedApiRuns, activity, apiSpan) {
  return new Promise(resolve => {
    resolve(runAPI(plugin, api, { ...args, parentSpan: apiSpan }, activity))
  }).catch(err => {
    let pluginName =
      plugin.name === `default-site-plugin` ? `gatsby-node.js` : plugin.name

    decorateEvent(`BUILD_PANIC`, {
      pluginName: `${plugin.name}@${plugin.version}`,
    })

    let localReporter = getLocalReporter(activity, reporter)

    localReporter.panicOnBuild({
      id: `11321`,
      context: {
        pluginName,
        api,
        message: err instanceof Error ? err.message : err,
      },
      error: err instanceof Error ? err : undefined,
    })

    return null
  })
}
<|endoftext|>


<commit_before>var daily;
var monthly;

function setDaily(msg) {
	if(msg.topic == 'VideoFeedbackDailyMonthly') {
		var payload = msg.payload.split(/,|:/);

		if(daily != payload[5].replace(/"/g,'')){
			daily = payload[5].replace(/"/g,'');

			monthly = payload[7].replace(/"/g,'');

			console.log("Topic: " + msg.topic + " Payload: " + msg.payload);
			/*console.log("totalD: " + daily);
			console.log("totalM: " + monthly);*/

			updateStat();
		}
	}
}

function updateStat(){
	var price = $('#price').val();
	price = price.replace(/,/g,'.');
	price = parseFloat(price);
	if(price === undefined)
		price = 1.3;

	$('#kwh-today').html(daily + " kWh");
	$('#money-today').html((daily*price).toFixed(2) + " kr");

	$('#kwh-month').html(monthly + " kWh");
	$('#money-month').html((monthly*price).toFixed(2) + " kr");
}
<commit_msg>jump to right time in video on price change<commit_after>var daily;
var monthly;
var price = 1.3;

function setDaily(msg) {
	if (msg.topic == 'VideoFeedbackDailyMonthly') {
		var payload = msg.payload.split(/,|:/);
		if (daily != payload[5].replace(/"/g,'')) {
			daily = payload[5].replace(/"/g,'');
			monthly = payload[7].replace(/"/g,'');
			console.log("Topic: " + msg.topic + " Payload: " + msg.payload);
			updateStats();
		}
	}
}

function getDailyCost() {
	return Math.floor(daily * price);
}

/* Update stats (power consumption) based on price per kWh */
function updateStats() {
	price = parseFloat($('#price').val().replace(/,/g,'.'));
	if (price === undefined)
		price = 1.3;

	/* If price is changed, jump to the right time */
	if (timestamps[getDailyCost()] !== undefined)
		video.currentTime = timestamps[getDailyCost()];

	$('#kwh-today').html(daily + " kWh");
	$('#money-today').html((daily*price).toFixed(2) + " kr");

	$('#kwh-month').html(monthly + " kWh");
	$('#money-month').html((monthly*price).toFixed(2) + " kr");
}
<|endoftext|>


<commit_before>import {range} from 'lodash'
import {Patch} from '@sanity/client'
import Observable from '@sanity/observable'

function generateId(n) {
  return ((n + 1) / 1.1111111111111).toString(32).substring(2)
}

function createDoc(_type, fields) {
  return Object.assign({_type}, fields)
}
function createBlogPost(number) {
  return createDoc('exampleBlog.blogpost', {
    title: `Blogpost ${number}`
  })
}
function createAuthor(number) {
  return createDoc('exampleBlog.author', {
    name: `Author ${number}`
  })
}

function createDB() {
  const docs = window.docs = []
  const index = window.idx = {}
  return {
    create,
    delete: del,
    getById,
    getAll() {
      return docs.filter(Boolean)
    },
    patch(spec) {
      // Todo: apply patch locally, then call update(patch.id, newDocument)
      return Promise.resolve({documentIds: spec.map(s => s.patch.id)})
    }
  }
  function indexOf(id) {
    return index[id]
  }
  // keep for later
  function update(_id, document) { // eslint-disable-line no-unused-vars
    const idx = indexOf(_id)
    docs[idx] = document
  }
  function getById(id) {
    return docs[indexOf(id)]
  }
  function del(id) {
    const idx = indexOf(id)
    delete index[id]
    docs[idx] = null
  }
  function create(doc) {
    if (doc._id) {
      throw new Error('Cannot create document with an id')
    }
    const nextIdx = docs.length
    const _id = `public/${generateId(nextIdx)}`
    const storedDoc = Object.assign({}, doc, {_id})
    docs.push(storedDoc)
    index[_id] = nextIdx
    return storedDoc
  }
}

const DB = createDB()
range(5)
  .map(createAuthor)
  .map(DB.create)

range(20)
  .map(createBlogPost)
  .map(DB.create)

const ID_QUERY = /\[_id\s*==\s*[$\w]+]/
export default {
  fetch(query, params) {
    // todo: reproject fields
    const [type] = query.split(/\[/)
    if (ID_QUERY.test(query)) {
      return Promise.resolve([DB.getById(params.id)])
    }
    return Promise.resolve(DB.getAll().filter(doc => doc._type === type))
  },
  getDocument(id) {
    return Promise.resolve(DB.getById(id))
  },
  create(doc) {
    return Promise.resolve({documentId: DB.create(doc)._id})
  },
  delete(id) {
    return Promise.resolve(DB.delete(id))
  },
  patch(id, operations) {
    return new Patch(id, operations, this)
  },
  listen() {
    return new Observable(observer => {

    })
  },
  mutate(spec) {
    return Promise.resolve(DB.patch(spec))
  }
}
<commit_msg>Emit welcome event<commit_after>import {range} from 'lodash'
import {Patch} from '@sanity/client'
import Observable from '@sanity/observable'

function generateId(n) {
  return ((n + 1) / 1.1111111111111).toString(32).substring(2)
}

function createDoc(_type, fields) {
  return Object.assign({_type}, fields)
}
function createBlogPost(number) {
  return createDoc('exampleBlog.blogpost', {
    title: `Blogpost ${number}`
  })
}
function createAuthor(number) {
  return createDoc('exampleBlog.author', {
    name: `Author ${number}`
  })
}

function createDB() {
  const docs = window.docs = []
  const index = window.idx = {}
  return {
    create,
    delete: del,
    getById,
    getAll() {
      return docs.filter(Boolean)
    },
    patch(spec) {
      // Todo: apply patch locally, then call update(patch.id, newDocument)
      return Promise.resolve({documentIds: spec.map(s => s.patch.id)})
    }
  }
  function indexOf(id) {
    return index[id]
  }
  // keep for later
  function update(_id, document) { // eslint-disable-line no-unused-vars
    const idx = indexOf(_id)
    docs[idx] = document
  }
  function getById(id) {
    return docs[indexOf(id)]
  }
  function del(id) {
    const idx = indexOf(id)
    delete index[id]
    docs[idx] = null
  }
  function create(doc) {
    if (doc._id) {
      throw new Error('Cannot create document with an id')
    }
    const nextIdx = docs.length
    const _id = `public/${generateId(nextIdx)}`
    const storedDoc = Object.assign({}, doc, {_id})
    docs.push(storedDoc)
    index[_id] = nextIdx
    return storedDoc
  }
}

const DB = createDB()
range(5)
  .map(createAuthor)
  .map(DB.create)

range(20)
  .map(createBlogPost)
  .map(DB.create)

const ID_QUERY = /\[_id\s*==\s*[$\w]+]/
export default {
  fetch(query, params) {
    // todo: reproject fields
    const [type] = query.split(/\[/)
    if (ID_QUERY.test(query)) {
      return Promise.resolve([DB.getById(params.id)])
    }
    return Promise.resolve(DB.getAll().filter(doc => doc._type === type))
  },
  getDocument(id) {
    return Promise.resolve(DB.getById(id))
  },
  create(doc) {
    return Promise.resolve({documentId: DB.create(doc)._id})
  },
  delete(id) {
    return Promise.resolve(DB.delete(id))
  },
  patch(id, operations) {
    return new Patch(id, operations, this)
  },
  listen() {
    return new Observable(observer => {
      observer.next({type: 'welcome'})
    })
  },
  mutate(spec) {
    return Promise.resolve(DB.patch(spec))
  }
}
<|endoftext|>


<commit_before>var util = require('./util'),
	assert = util.assert
	q = util.q,
	debug = util.debug

var gToken, gIndex, gTokens, gState, gAST

exports.parse = function(tokens) {
	gTokens = tokens
	gIndex = -1
	gToken = null
	gAST = []

	while (true) {
		advance()
		if (gIndex == gTokens.length) { break }
		gAST.push(parseStatement())
	}

	return gAST
}

var parseStatement = function() {
	switch(gToken.type) {
		case 'string':
		case 'number':
			return getLiteralValue()
		case 'symbol':
			return parseXML() // only XML statements begin with a symbol (<)
		case 'name':
		    switch (gToken.value) {
        		case 'let': return parseDeclaration()
        		case 'for': return parseForLoop()
        		case 'if': return parseIfStatement()
        		default: return parseAlias()
        	}

		default:
			throw new Error('Unknown parse statement token: ' + JSON.stringify(gToken))
	}
}

/*******************
 * Utility methods *
 *******************/
var advance = function(type, value, expressionType) {
	gToken = gTokens[++gIndex]
	function check(v1, v2) {
		assert.equal(v1, v2,
			['Expected a', q(type),
				value ? 'of value ' + q(value) : '',
				expressionType ? 'for ' + expressionType : '',
				'on line:', gToken.line,
				'column:', gToken.column,
				'but found a', q(gToken.type),
				'of value', q(gToken.value)].join(' ')
	)}
	if (type) { check(type, gToken.type) }
	if (value) {
		if (value instanceof Array) { for (var i=0, val; val=value[i]; i++) {
			if (val != gToken.value) { continue }
			value = val // allow for the check to pass if one of the values passed in matches
			break
		}}
		check(value, gToken.value)
	}
}
var peek = function(amount) { return gTokens[gIndex + (amount || 1)] }
var isAhead = function(amount, type, value) {
	var token = gTokens[gIndex + amount]
	if (type && type != token.type) { return false }
	if (value && value != token.value) { return false }
	return true
}

/******************************
 * Aliases and literal values *
 ******************************/
function parseAlias() {
 // TODO Parse dot notation
 return { type:'ALIAS', name:gToken.value }
}

function getLiteralValue() {
	assert(gToken.type == 'string' || gToken.type == 'number')
	return { type:gToken.type.toUpperCase(), value:gToken.value }
}

/*******
 * XML *
 *******/
var parseXML = function() {
	debug('parseXML')
	advance('name', null, 'XML tag')
	var tagName = gToken.value,
		attributes = parseXMLAttributes()

	advance('symbol', ['>', '/'], 'end of XML tag')
	if (gToken.value == '/') {
		advance('symbol', '>', 'self-closing XML tag')
		return { type:'XML', tag:tagName, attributes:attributes, content:[] }
	} else {
		var statements = []
		while(true) {
			if (isAhead(1, 'symbol', '<') && isAhead(2, 'symbol', '/')) { break }
			advance()
			statements.push(parseStatement())
		}

		advance('symbol', '<')
		advance('symbol', '/')
		advance('name', tagName, 'matching XML tags')
		advance('symbol', '>')

		return { type:'XML', tag:tagName, attributes:attributes, content:statements }
	}
}

var parseXMLAttributes = function() {
	debug('parseXMLAttributes')
	if (!peek('name')) { return [] } // no attributes
}

/****************
 * Declarations *
 ****************/
function parseDeclaration() {
	debug('parseDeclaration')
	advance('name', null, 'declaration')
	var name = gToken.value
	advance('symbol', '=', 'declaration')
	value = parseDeclarable()
	return { type:'DECLARATION', name:name, value:value }
}
function parseDeclarable() {
	debug('parseDeclarable')
	advance()
	switch(gToken.type) {
		case 'name':
		    return parseAlias()
		case 'symbol':
			// TODO Parse JSON literal
			return parseXML()
		case 'string':
		case 'number':
			return getLiteralValue()
		default:
			throw new Error('Unkown declarable token: ' + JSON.stringify(gToken))
	}
}

/*************
 * For loops *
 *************/
function parseForLoop() {
	debug('parseForLoop')
	throw new Error("For loops are not yet implemented")
}

/****************
 * If statement *
 ****************/
function parseIfStatement() {
	debug('parseIfStatement')
	throw new Error("If statements are not yet implemented")
}
<commit_msg>Strings with (, ), { and } can cause parens matching confusion. Use variable names to reference their values in the parsing code<commit_after>var util = require('./util'),
	assert = util.assert
	q = util.q,
	debug = util.debug

var LPAREN = '(',
    RPAREN = ')',
    LBLOCK = '{',
    RBLOCK = '}'

var gToken, gIndex, gTokens, gState, gAST

exports.parse = function(tokens) {
	gTokens = tokens
	gIndex = -1
	gToken = null
	gAST = []

	while (true) {
		advance()
		if (gIndex == gTokens.length) { break }
		gAST.push(parseStatement())
	}

	return gAST
}

var parseStatement = function() {
	switch(gToken.type) {
		case 'string':
		case 'number':
			return getLiteralValue()
		case 'symbol':
			return parseXML() // only XML statements begin with a symbol (<)
		case 'name':
		    switch (gToken.value) {
        		case 'let': return parseDeclaration()
        		case 'for': return parseForLoop()
        		case 'if': return parseIfStatement()
        		default: return parseAlias()
        	}

		default:
			throw new Error('Unknown parse statement token: ' + JSON.stringify(gToken))
	}
}

/*******************
 * Utility methods *
 *******************/
var advance = function(type, value, expressionType) {
	gToken = gTokens[++gIndex]
	function check(v1, v2) {
		assert.equal(v1, v2,
			['Expected a', q(type),
				value ? 'of value ' + q(value) : '',
				expressionType ? 'for ' + expressionType : '',
				'on line:', gToken.line,
				'column:', gToken.column,
				'but found a', q(gToken.type),
				'of value', q(gToken.value)].join(' ')
	)}
	if (type) { check(type, gToken.type) }
	if (value) {
		if (value instanceof Array) { for (var i=0, val; val=value[i]; i++) {
			if (val != gToken.value) { continue }
			value = val // allow for the check to pass if one of the values passed in matches
			break
		}}
		check(value, gToken.value)
	}
}
var peek = function(amount) { return gTokens[gIndex + (amount || 1)] }
var isAhead = function(amount, type, value) {
	var token = gTokens[gIndex + amount]
	if (type && type != token.type) { return false }
	if (value && value != token.value) { return false }
	return true
}

/******************************
 * Aliases and literal values *
 ******************************/
function parseAlias() {
 // TODO Parse dot notation
 return { type:'ALIAS', name:gToken.value }
}

function getLiteralValue() {
	assert(gToken.type == 'string' || gToken.type == 'number')
	return { type:gToken.type.toUpperCase(), value:gToken.value }
}

/*******
 * XML *
 *******/
var parseXML = function() {
	debug('parseXML')
	advance('name', null, 'XML tag')
	var tagName = gToken.value,
		attributes = parseXMLAttributes()

	advance('symbol', ['>', '/'], 'end of XML tag')
	if (gToken.value == '/') {
		advance('symbol', '>', 'self-closing XML tag')
		return { type:'XML', tag:tagName, attributes:attributes, content:[] }
	} else {
		var statements = []
		while(true) {
			if (isAhead(1, 'symbol', '<') && isAhead(2, 'symbol', '/')) { break }
			advance()
			statements.push(parseStatement())
		}

		advance('symbol', '<')
		advance('symbol', '/')
		advance('name', tagName, 'matching XML tags')
		advance('symbol', '>')

		return { type:'XML', tag:tagName, attributes:attributes, content:statements }
	}
}

var parseXMLAttributes = function() {
	debug('parseXMLAttributes')
	if (!peek('name')) { return [] } // no attributes
}

/****************
 * Declarations *
 ****************/
function parseDeclaration() {
	debug('parseDeclaration')
	advance('name', null, 'declaration')
	var name = gToken.value
	advance('symbol', '=', 'declaration')
	value = parseDeclarable()
	return { type:'DECLARATION', name:name, value:value }
}
function parseDeclarable() {
	debug('parseDeclarable')
	advance()
	switch(gToken.type) {
		case 'name':
		    return parseAlias()
		case 'symbol':
			// TODO Parse JSON literal
			return parseXML()
		case 'string':
		case 'number':
			return getLiteralValue()
		default:
			throw new Error('Unkown declarable token: ' + JSON.stringify(gToken))
	}
}

/*************
 * For loops *
 *************/
function parseForLoop() {
	debug('parseForLoop')
	throw new Error("For loops are not yet implemented")
}

/****************
 * If statement *
 ****************/
function parseIfStatement() {
	debug('parseIfStatement')
	throw new Error("If statements are not yet implemented")
}
<|endoftext|>


<commit_before>/*
documentation for emap
sample request URL: http://localhost:3000/api/emap/?pathwayIdList=GO:1901216 GO:2001252 GO:1905269
parameter:
pathwayIdList - [string] a list of pathwayIds (GO and REACTOME) delimited by whitespace
return:
[Object] {"unrecognized":[vector of pathwayIds], "duplicate": [vector of pathwayIds], "graph": [Object of node and edge info]}

Notes:
1. each pathwayId appears at most once in unrecognize, duplicate and geneInfo
2. If a pathwayId is unrecognized and duplicate, only report it in unrecognize.
3. If a pathwayId is recognized and duplicate, report it in duplicate and store info in graph.
*/
const pathwayInfoTable = require('./PathwayTable').pathwayInfoTable;
// const make_cytoscape = require('../../../../src/client/common/cy');
const generateNodeInfo = require('./generateInfo').generateNodeInfo;
const generateEdgeInfo = require('./generateInfo').generateEdgeInfo;
const _ = require('lodash');

// input ["GO:1902275", "GO:2001252", "GO:1905269", "GO:0051053"]
// returns a cytoscape object
const generateGraphInfo = (pathwayIdList) => {
  // check unrecognized and duplicates, modify pathwayIdList
  const unrecognized = [];
  const duplicate = [];
  for (let i = 0; i < pathwayIdList.length; ++i) {
    const pathwayId = pathwayIdList[i];
    if (!pathwayInfoTable.has(pathwayId)) {
      if (_.filter(unrecognized, elem => elem === pathwayId).length === 0) {
        unrecognized.push(pathwayId);
      }
      pathwayIdList.splice(pathwayIdList.indexOf(pathwayId), 1);
      --i;
    }
  }
  for (let i = 0; i < pathwayIdList.length; ++i) {
    const pathwayId = pathwayIdList[i];
    if ((_.filter(pathwayIdList, ele => ele === pathwayId)).length > 1) {
      if (_.filter(duplicate, ele => ele === pathwayId).length == 0) {
        duplicate.push(pathwayId);
      } else {
        pathwayIdList.splice(pathwayIdList.indexOf(pathwayId), 1);
        --i;
      }
    }
  }
  // generate node and edge info
  const elements = [];
  const cytoscapeJSON = {};
  cytoscapeJSON.nodes = [];
  cytoscapeJSON.edges = [];
  const nodeInfo = generateNodeInfo(pathwayIdList);
  _.forEach(nodeInfo, node => {
    //cytoscapeJSON.nodes.push(node.pathwayId);
    elements.push({ data: { id: node.pathwayId } });
  });
  const edgeInfo = generateEdgeInfo(pathwayIdList);
  _.forEach(edgeInfo, edge => {
    const sourceIndex = 0;
    const targetIndex = 1;
    const source = edge.edgeId.split('_')[sourceIndex];
    const target = edge.edgeId.split('_')[targetIndex];
    elements.push({
      data: {
        id: edge.edgeId,
        source: source,
        target: target,
        similarity: edge.similarity,
        intersection: edge.intersection
      }
    });
  });
  return { unrecognized: unrecognized, duplicate: duplicate, graph: elements };
};

module.exports = { generateGraphInfo };

//simple testing
//console.log(generateGraphInfo(["GO:1902275", "GO:2001252", "GO:1905269"]));
// const result = generateGraphInfo(["GO:1902275", "GO:2001252", "GO:1905269"]);
// console.log(JSON.stringify(result));<commit_msg>remove comment<commit_after>/*
documentation for emap
sample request URL: http://localhost:3000/api/emap/?pathwayIdList=GO:1901216 GO:2001252 GO:1905269
parameter:
pathwayIdList - [string] a list of pathwayIds (GO and REACTOME) delimited by whitespace
return:
[Object] {"unrecognized":[vector of pathwayIds], "duplicate": [vector of pathwayIds], "graph": [Object of node and edge info]}

Notes:
1. each pathwayId appears at most once in unrecognize, duplicate and geneInfo
2. If a pathwayId is unrecognized and duplicate, only report it in unrecognize.
3. If a pathwayId is recognized and duplicate, report it in duplicate and store info in graph.
*/
const pathwayInfoTable = require('./PathwayTable').pathwayInfoTable;
// const make_cytoscape = require('../../../../src/client/common/cy');
const generateNodeInfo = require('./generateInfo').generateNodeInfo;
const generateEdgeInfo = require('./generateInfo').generateEdgeInfo;
const _ = require('lodash');

// input ["GO:1902275", "GO:2001252", "GO:1905269", "GO:0051053"]
// returns a cytoscape object
const generateGraphInfo = (pathwayIdList) => {
  // check unrecognized and duplicates, modify pathwayIdList
  const unrecognized = [];
  const duplicate = [];
  for (let i = 0; i < pathwayIdList.length; ++i) {
    const pathwayId = pathwayIdList[i];
    if (!pathwayInfoTable.has(pathwayId)) {
      if (_.filter(unrecognized, elem => elem === pathwayId).length === 0) {
        unrecognized.push(pathwayId);
      }
      pathwayIdList.splice(pathwayIdList.indexOf(pathwayId), 1);
      --i;
    }
  }
  for (let i = 0; i < pathwayIdList.length; ++i) {
    const pathwayId = pathwayIdList[i];
    if ((_.filter(pathwayIdList, ele => ele === pathwayId)).length > 1) {
      if (_.filter(duplicate, ele => ele === pathwayId).length == 0) {
        duplicate.push(pathwayId);
      } else {
        pathwayIdList.splice(pathwayIdList.indexOf(pathwayId), 1);
        --i;
      }
    }
  }
  // generate node and edge info
  const elements = [];
  const cytoscapeJSON = {};
  cytoscapeJSON.nodes = [];
  cytoscapeJSON.edges = [];
  const nodeInfo = generateNodeInfo(pathwayIdList);
  _.forEach(nodeInfo, node => {
    elements.push({ data: { id: node.pathwayId } });
  });
  const edgeInfo = generateEdgeInfo(pathwayIdList);
  _.forEach(edgeInfo, edge => {
    const sourceIndex = 0;
    const targetIndex = 1;
    const source = edge.edgeId.split('_')[sourceIndex];
    const target = edge.edgeId.split('_')[targetIndex];
    elements.push({
      data: {
        id: edge.edgeId,
        source: source,
        target: target,
        similarity: edge.similarity,
        intersection: edge.intersection
      }
    });
  });
  return { unrecognized: unrecognized, duplicate: duplicate, graph: elements };
};

module.exports = { generateGraphInfo };

//simple testing
//console.log(generateGraphInfo(["GO:1902275", "GO:2001252", "GO:1905269"]));
// const result = generateGraphInfo(["GO:1902275", "GO:2001252", "GO:1905269"]);
// console.log(JSON.stringify(result));<|endoftext|>


<commit_before>import Vue from 'vue'
import Vuex from 'vuex'
import '@/directives'
import cloneDeep from 'lodash/cloneDeep'
import { options } from '@/store'
import Testing from '@/components/Testing'
import 'semantic-ui-css/semantic.js'
import 'semantic-ui-css/semantic.css'

// THIS HELPED A LOT
// https://github.com/johnnynotsolucky/samples/blob/master/vuejs-sample-1/test/unit/specs/List.spec.js

describe('Testing', () => {
  let testOptions

  beforeEach(() => {
    testOptions = cloneDeep(options)
  })

  it('has the correct name', () => {
    expect(Testing.name).to.equal('testing')
  })

  // We mock out the functionality which connects to and
  // listens for events from the fake event stream. This gives us full control
  // over emitted data, and mitigates uncontrollable dependencies.
  it('has dependable mutations', (done) => {
    const TEST_TITLE = 'Test Title'
    const TEST_TEXT = 'Test Text'
    const TEST_COLOR = 'red'

    function assertions () {
      expect(this.title).to.equal(TEST_TITLE)
      expect(this.text).to.equal(TEST_TEXT)
      expect(this.newNoteColor).to.deep.equal({ 'background-color': this.colors[TEST_COLOR] })
      done()
    }

    const stubbedStore = new Vuex.Store(testOptions)
    const mounted = function mounted () {
      this.title = TEST_TITLE
      this.text = TEST_TEXT
      this.NOTE_FORM_COLOR(TEST_COLOR)
    }
    const updated = function updated () {
      Vue.nextTick()
        .then(assertions.bind(this))
        .catch(done)
    }
    const Component = Vue.extend({ ...Testing, store: stubbedStore, updated, mounted })
    new Component().$mount() // eslint-disable-line no-new
  })

  it('submits form on button click', (done) => {
    // We stub our createNote action to make sure we're listening to the
    // correct EventEmitter
    sinon.stub(testOptions.actions, 'createNote').callsFake(({ commit }) => {
      done()
    })

    const stubbedStore = new Vuex.Store(testOptions)
    const mounted = function mounted () {
      $(this.$el.querySelector('button[type=submit]')).click()
    }
    const Component = Vue.extend({ ...Testing, store: stubbedStore, mounted })
    new Component().$mount() // eslint-disable-line no-new
  })
})
<commit_msg>Rename test<commit_after>import Vue from 'vue'
import Vuex from 'vuex'
import '@/directives'
import cloneDeep from 'lodash/cloneDeep'
import { options } from '@/store'
import Testing from '@/components/Testing'
import 'semantic-ui-css/semantic.js'
import 'semantic-ui-css/semantic.css'

// THIS HELPED A LOT
// https://github.com/johnnynotsolucky/samples/blob/master/vuejs-sample-1/test/unit/specs/List.spec.js

describe('Testing', () => {
  let testOptions

  beforeEach(() => {
    testOptions = cloneDeep(options)
  })

  it('has the correct name', () => {
    expect(Testing.name).to.equal('testing')
  })

  // We mock out the functionality which connects to and
  // listens for events from the fake event stream. This gives us full control
  // over emitted data, and mitigates uncontrollable dependencies.
  it('has dependable mutations', (done) => {
    const TEST_TITLE = 'Test Title'
    const TEST_TEXT = 'Test Text'
    const TEST_COLOR = 'red'

    function assertions () {
      expect(this.title).to.equal(TEST_TITLE)
      expect(this.text).to.equal(TEST_TEXT)
      expect(this.newNoteColor).to.deep.equal({ 'background-color': this.colors[TEST_COLOR] })
      done()
    }

    const stubbedStore = new Vuex.Store(testOptions)
    const mounted = function mounted () {
      this.title = TEST_TITLE
      this.text = TEST_TEXT
      this.NOTE_FORM_COLOR(TEST_COLOR)
    }
    const updated = function updated () {
      Vue.nextTick()
        .then(assertions.bind(this))
        .catch(done)
    }
    const Component = Vue.extend({ ...Testing, store: stubbedStore, updated, mounted })
    new Component().$mount() // eslint-disable-line no-new
  })

  it('calls action on form submit', (done) => {
    // We stub our createNote action to make sure we're listening to the
    // correct EventEmitter
    sinon.stub(testOptions.actions, 'createNote').callsFake(({ commit }) => {
      done()
    })

    const stubbedStore = new Vuex.Store(testOptions)
    const mounted = function mounted () {
      $(this.$el.querySelector('button[type=submit]')).click()
    }
    const Component = Vue.extend({ ...Testing, store: stubbedStore, mounted })
    new Component().$mount() // eslint-disable-line no-new
  })
})
<|endoftext|>


<commit_before>/**
 * Created by karolisrusenas on 04/04/2016.
 */
import React, {PropTypes} from 'react'
// import { push } from 'react-router-redux'
import AppBar from 'material-ui/lib/app-bar'
import LeftNav from 'material-ui/lib/left-nav'
import Menu from 'material-ui/lib/menus/menu'
import MenuItem from 'material-ui/lib/menus/menu-item'
import {Tabs, Tab} from 'material-ui'

export default class Navigation extends React.Component<void, Props, void> {
  static propTypes = {
    store: PropTypes.object.isRequired
  };

  constructor (props) {
    super(props)
    this.state = {open: false}
  }

  handleToggle = () => this.setState({open: !this.state.open});

  handleClose = () => this.setState({open: false});

  onRequestChange = (open) => this.setState({open})

  render () {
    let myTabs = (
      <Tabs>
        <Tab label='Logout' route='/logout'/>
      </Tabs>
    )

    return (

        <AppBar title='Hoverfly' onLeftIconButtonTouchTap={this.handleToggle} iconElementRight={myTabs}/>
        <LeftNav
          ref='leftNav'
          docked={false}
          open={this.state.open}
          onRequestChange={this.onRequestChange}
        >
          <Menu>
            <MenuItem primaryText='State'/>
            <MenuItem disabled primaryText='Records'/>
            <MenuItem disabled primaryText='Middlewares'/>
          </Menu>
        </LeftNav>

    )
  }
}

// Since this is not a <Route> component, we add History to the context
Navigation.contextTypes = {
  history: React.PropTypes.object
}

export default Navigation
<commit_msg>moving from cursed menuitems to tabs<commit_after>/**
 * Created by karolisrusenas on 04/04/2016.
 */
import React, {PropTypes} from 'react'
import AppBar from 'material-ui/lib/app-bar'
import {Tabs, Tab} from 'material-ui'

import {connect} from 'react-redux'
import {pushPath} from '../redux/modules/navigation'

type Props = {
  path: string,
  pushPath: Function
};

export default class Navigation extends React.Component<void, Props, void> {
  static propTypes = {
    // path: PropTypes.string.isRequired,
    pushPath: PropTypes.func.isRequired
  };

  constructor (props) {
    super(props)
    this.state = {open: false}
    this.handleActive = this.handleActive.bind(this)
    // this.goToPage = this.goToPage.bind(this)
  }

  handleToggle = () => this.setState({open: !this.state.open});

  handleClose = () => this.setState({open: false});

  onRequestChange = (open) => this.setState({open})

  handleActive (tab) {
    this.props.pushPath(tab.props.route)
  }

  render () {
    let myLeftTabs = (
      <Tabs>
        <Tab label='State' route='state' onActive={this.handleActive}/>
        <Tab label='Records' route='records' onActive={this.handleActive}/>
        <Tab label='Middleware' route='middleware' onActive={this.handleActive}/>
      </Tabs>
    )

    let myRightTabs = (
      <Tabs>
        <Tab label='Logout' route='/logout'/>
      </Tabs>
    )

    return (

        <AppBar
          onLeftIconButtonTouchTap={this.handleToggle}
          iconElementLeft={myLeftTabs} iconElementRight={myRightTabs}/>

    )
  }
}

// Since this is not a <Route> component, we add History to the context
Navigation.contextTypes = {
  history: React.PropTypes.object
}

const mapStateToProps = (state) => ({})

export default connect((mapStateToProps), {
  pushPath
})(Navigation)
<|endoftext|>


<commit_before>'use strict';
'require view';
'require uci';
'require rpc';
'require form';
'require fs';

var callLeds = rpc.declare({
	object: 'luci',
	method: 'getLEDs',
	expect: { '': {} }
});

return view.extend({
	load: function() {
		return Promise.all([
			callLeds(),
			L.resolveDefault(fs.list('/www' + L.resource('view/system/led-trigger')), [])
		]).then(function(data) {
			var plugins = data[1];
			var tasks = [];

			for (var i = 0; i < plugins.length; i++) {
				var m = plugins[i].name.match(/^(.+)\.js$/);

				if (plugins[i].type != 'file' || m == null)
					continue;

				tasks.push(L.require('view.system.led-trigger.' + m[1]).then(L.bind(function(name){
					return L.resolveDefault(L.require('view.system.led-trigger.' + name)).then(function(form) {
						return {
							name: name,
							form: form,
						};
					});
				}, this, m[1])));
			}

			return Promise.all(tasks).then(function(plugins) {
				var value = {};
				value[0] = data[0];
				value[1] = plugins;
				return value;
			});
		});
	},

	render: function(data) {
		var m, s, o, triggers = [];
		var leds = data[0];
		var plugins = data[1];

		for (var k in leds)
			for (var i = 0; i < leds[k].triggers.length; i++)
				triggers[i] = leds[k].triggers[i];

		m = new form.Map('system',
			_('LED Configuration'),
			_('Customizes the behaviour of the device LEDs if possible.'));

		s = m.section(form.GridSection, 'led', '');
		s.anonymous = true;
		s.addremove = true;
		s.sortable = true;
		s.addbtntitle = _('Add LED action');

		s.option(form.Value, 'name', _('Name'));

		o = s.option(form.ListValue, 'sysfs', _('LED Name'));
		Object.keys(leds).sort().forEach(function(name) {
			o.value(name)
		});

		o = s.option(form.ListValue, 'trigger', _('Trigger'));
		for (var i = 0; i < plugins.length; i++) {
			var plugin = plugins[i];

			if ( plugin.form.kernel == false )
				o.value(plugin.name, plugin.form.trigger);
			else
				for (var k = 0; k < triggers.length; k++)
					if ( plugin.name == triggers[k] )
						o.value(plugin.name, plugin.form.trigger);
		}

		s.addModalOptions = function(s) {
			for (var i = 0; i < plugins.length; i++) {
				var plugin = plugins[i];
				plugin.form.addFormOptions(s);
			}
		};

		return m.render();
	}
});
<commit_msg>luci-mod-system: fix uci led option remove callback<commit_after>'use strict';
'require view';
'require uci';
'require rpc';
'require form';
'require fs';

var callLeds = rpc.declare({
	object: 'luci',
	method: 'getLEDs',
	expect: { '': {} }
});

return view.extend({
	load: function() {
		return Promise.all([
			callLeds(),
			L.resolveDefault(fs.list('/www' + L.resource('view/system/led-trigger')), [])
		]).then(function(data) {
			var plugins = data[1];
			var tasks = [];

			for (var i = 0; i < plugins.length; i++) {
				var m = plugins[i].name.match(/^(.+)\.js$/);

				if (plugins[i].type != 'file' || m == null)
					continue;

				tasks.push(L.require('view.system.led-trigger.' + m[1]).then(L.bind(function(name){
					return L.resolveDefault(L.require('view.system.led-trigger.' + name)).then(function(form) {
						return {
							name: name,
							form: form,
						};
					});
				}, this, m[1])));
			}

			return Promise.all(tasks).then(function(plugins) {
				var value = {};
				value[0] = data[0];
				value[1] = plugins;
				return value;
			});
		});
	},

	render: function(data) {
		var m, s, o, triggers = [];
		var leds = data[0];
		var plugins = data[1];

		for (var k in leds)
			for (var i = 0; i < leds[k].triggers.length; i++)
				triggers[i] = leds[k].triggers[i];

		m = new form.Map('system',
			_('LED Configuration'),
			_('Customizes the behaviour of the device LEDs if possible.'));

		s = m.section(form.GridSection, 'led', '');
		s.anonymous = true;
		s.addremove = true;
		s.sortable = true;
		s.addbtntitle = _('Add LED action');

		s.option(form.Value, 'name', _('Name'));

		o = s.option(form.ListValue, 'sysfs', _('LED Name'));
		Object.keys(leds).sort().forEach(function(name) {
			o.value(name)
		});

		o = s.option(form.ListValue, 'trigger', _('Trigger'));
		for (var i = 0; i < plugins.length; i++) {
			var plugin = plugins[i];

			if ( plugin.form.kernel == false )
				o.value(plugin.name, plugin.form.trigger);
			else
				for (var k = 0; k < triggers.length; k++)
					if ( plugin.name == triggers[k] )
						o.value(plugin.name, plugin.form.trigger);
		}

		s.addModalOptions = function(s) {
			for (var i = 0; i < plugins.length; i++) {
				var plugin = plugins[i];
				plugin.form.addFormOptions(s);
			}

			var opts = s.getOption();

			var removeIfNoneActive = function(original_remove_fn, section_id) {
				var isAnyActive = false;

				for (var optname in opts) {
					if (opts[optname].ucioption != this.ucioption)
						continue;

					if (!opts[optname].isActive(section_id))
						continue;

					isAnyActive = true;
					break;
				}

				if (!isAnyActive)
					original_remove_fn.call(this, section_id);
			};

			for (var optname in opts) {
				if (!opts[optname].ucioption || optname == opts[optname].ucioption)
					continue;
				opts[optname].remove = removeIfNoneActive.bind(opts[optname], opts[optname].remove);
			}
		};

		return m.render();
	}
});
<|endoftext|>