<commit_before>/*global describe, it, before*/
var expect = require('unexpected');
var oconf = require('../../lib/index');

function testFile(filename) {
    return require('path').resolve(__dirname, '..', 'files', filename);
}

describe('Basic tests', function () {
    describe('base.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('base.cjson'));
        });
        it('Has foo = "overwrite this"', function () {
            expect(data, 'to have property', 'foo', 'overwrite this');
        });
        it('Has what = "this is from default.cjson."', function () {
            expect(data, 'to have property', 'what', 'this is from default.cjson.');
        });
        it('Only has "foo" and "what"-keys', function () {
            expect(data, 'to only have keys', ['foo', 'what']);
        });
    });
});

describe('#include behaviour', function () {
    describe('extend-base.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('extend-base.cjson'));
        });
        it('Has foo = "bar" (i.e. overwritten)', function () {
            expect(data, 'to have property', 'foo', 'bar');
        });
        it('Has what = "this is from default.cjson."', function () {
            expect(data, 'to have property', 'what', 'this is from default.cjson.');
        });
        it('Only has "foo" and "what"-keys', function () {
            expect(data, 'to only have keys', ['foo', 'what']);
        });
    });
    describe('extend-in-subobject.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('extend-in-subobject.cjson'));
        });
        it('Has subobject = contents of extend-base.cjson', function () {
            expect(data, 'to equal', {
                'subobject': {
                    'foo': 'bar',
                    'what': 'this is from default.cjson.'
                }
            });
        });
    });
    describe('extend-multiple.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('extend-multiple.cjson'));
        });
        it('should have properties from both extended files', function () {
            expect(data, 'to equal', {
                foo: 'bar',
                bar: 'foo'
            });
        });
    });
    describe('extend-nested.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('extend-nested.cjson'));
        });
        it('should have properties from both extended files', function () {
            expect(data, 'to equal', {
                foo: 'foo',
                bar: 'bar',
                baz: 'baz'
            });
        });
    });
    describe('list-of-includes.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('list-of-includes.cjson'));
        });
        it('should resolve includes in the list', function () {
            expect(data, 'to equal', [
                { foo: 'bar' }, { bar: 'foo' }
            ]);
        });
    });
    describe('loop1.cjson / loop2.cjson', function () {
        it('Loading loop1.cjson throws error', function () {
            expect(function () {
                oconf.load(testFile('loop1.cjson'));
            }, 'to throw', /^Loop in loaded files/);
        });
        it('Loading loop2.cjson throws error', function () {
            expect(function () {
                oconf.load(testFile('loop2.cjson'));
            }, 'to throw', /^Loop in loaded files/);
        });
    });
    describe('includeNonExistentFile.cjson', function () {
        it('should throw an error when nonExistentFile.cjson is not ignored', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'));
            }, 'to throw', /^ENOENT, no such file or directory/);
        });
        it('should not throw an error when nonExistentFile.cjson is ignored', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), {ignore: testFile('nonExistentFile.cjson')});
            }, 'not to throw');
        });
    });
    describe('ignore included files with globbing', function () {
        it('should not throw an error when ignoring by glob #1', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: '**/*.cjson' });
            }, 'not to throw');
        });
        it('should not throw an error when ignoring by glob #2', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: testFile('./**') });
            }, 'not to throw');
        });
        it('should not throw an error when ignoring by glob #3', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: testFile('../files/*') });
            }, 'not to throw');
        });
        it('should not throw an error when ignoring by glob #4', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: '../files/*.cjson', cwd: __dirname });
            }, 'not to throw');
        });
        it('should throw an error when ignoring by glob but including file not matched by glob', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: testFile('foo/*cjson') });
            }, 'to throw', /^ENOENT, no such file or directory/);
        });
    });
});

describe('#public behaviour', function () {
    describe('when loading with public:false (the default)', function () {
        describe('where the root object contains a #public property', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-base.cjson'));
            });
            it('should fold the #public properties down into the base structure', function () {
                expect(data, 'to equal', {
                    foo: 'do not expose to public',
                    what: 'what is public',
                    '#public': {
                        what: 'what is public'
                    }
                });
            });
        });

        describe('where a child object contains some #public properties', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-deep.cjson'));
            });
            it('should fold the #public properties down into the base structure', function () {
                expect(data, 'to equal', {
                    foo: "do not expose to public",
                    bar: {
                        quux: "super secret"
                    },
                    hello: {
                        earth: "mostly harmless",
                        answer: 42
                    },
                    '#public': {
                        hello: {
                            answer: 42
                        }
                    }
                });
            });
        });

        describe('where a child object in a child array contains some #public properties', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('array-with-object-with-public.cjson'));
            });
            it('should fold the #public properties down into the base structure', function () {
                expect(data, 'to equal', {
                    foo: [
                        {
                            bar: 'quux'
                        }
                    ],
                    '#public': {
                        foo: [
                            {
                                bar: 'quux'
                            }
                        ]
                    }
                });
            });
        });

        describe('where a child object in a child array contains some #public properties', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('array-with-object-with-array-with-object-with-public.cjson'));
            });
            it.skip('should fold the #public properties down into the base structure', function () {
                expect(data, 'to exhaustively satisfy', {
                    0: {
                        foo: [
                            {
                                bar: 'quux'
                            }
                        ]
                    },
                    '#public': [{
                        foo: [
                            {
                                bar: 'quux'
                            }
                        ]
                    }]
                }).and('to be an array');
            });
        });

        describe('when trying to overwrite a public property with a property that was declared public at another level', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-conflict.cjson'));
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where trying to overwrite a non-public property with a #public one', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-deep-with-include.cjson'));
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where trying to overwrite a #public property with a non-public one', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-deep-with-include.cjson'));
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where including a file that already has a #public property which we try to overwrite', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-deep-with-public-include.cjson'));
            });
            it('should overwrite the included #public property with our value', function () {
                expect(data, 'to equal', {
                    foo: "do not expose to public",
                    bar: {
                        quux: "super secret"
                    },
                    hello: {
                        earth: "mostly harmless",
                        answer: 'Insufficient data for meaningful answer'
                    },
                    '#public': {
                        hello: {
                            answer: 'Insufficient data for meaningful answer'
                        }
                    }
                });
            });
        });
    });

    describe('when loading with public:true', function () {
        describe('where the root object contains a #public property', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-base.cjson'), { public: true });
            });
            it('should fold the #public properties down into the base structure, and omit secret properties and leaves', function () {
                expect(data, 'to equal', {
                    what: 'what is public'
                });
            });
        });

        describe('where a child object contains some #public properties', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-deep.cjson'), { public: true });
            });
            it('should fold the #public properties down into the base structure, and omit secret properties and leaves', function () {
                expect(data, 'to equal', {
                    hello: {
                        answer: 42
                    }
                });
            });
        });

        describe('where trying to overwrite a non-public property with a #public one', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-deep-with-include.cjson'), { public: true });
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where trying to overwrite a #public property with a non-public one', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-deep-with-include.cjson'), { public: true });
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where including a file that overwrites a #public property with another public one', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-deep-with-public-include.cjson'), { public: true });
            });
            it('should overwrite the included #public property with our value, and omit secret properties and leaves', function () {
                expect(data, 'to equal', {
                    hello: {
                        answer: 'Insufficient data for meaningful answer'
                    }
                });
            });
        });

        describe('when there are no #public properties at all', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('base.cjson'), { public: true });
            });
            it('should return an empty object', function () {
                expect(data, 'to equal', {});
            });
        });
    });

    describe('with public-array.cjson', function () {
        it('throws an error', function () {
            expect(function () {
                oconf.load(testFile('public-array.cjson'));
            }, 'to throw', /^\#public must always be an object/);
        });
    });

    describe('with public-non-object.cjson', function () {
        it('throws an error', function () {
            expect(function () {
                oconf.load(testFile('public-non-object.cjson'));
            }, 'to throw', /^\#public must always be an object/);
        });
    });
});
<commit_msg>Add test for calling oconf.load with an array of filenames<commit_after>/*global describe, it, before*/
var expect = require('unexpected');
var oconf = require('../../lib/index');

function testFile(filename) {
    return require('path').resolve(__dirname, '..', 'files', filename);
}

describe('Basic tests', function () {
    describe('base.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('base.cjson'));
        });
        it('Has foo = "overwrite this"', function () {
            expect(data, 'to have property', 'foo', 'overwrite this');
        });
        it('Has what = "this is from default.cjson."', function () {
            expect(data, 'to have property', 'what', 'this is from default.cjson.');
        });
        it('Only has "foo" and "what"-keys', function () {
            expect(data, 'to only have keys', ['foo', 'what']);
        });
    });

    describe('calling load method with an array of config file names', function () {
        var data;
        before(function () {
            data = oconf.load([testFile('extend-base.cjson'), testFile('deep.cjson')]);
        });
        it('merges the right file into the left file', function () {
            expect(data, 'to equal', {
                foo: {
                    bar: 'qux'
                },
                what: 'this is from default.cjson.'
            });
        });
    });
});

describe('#include behaviour', function () {
    describe('extend-base.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('extend-base.cjson'));
        });
        it('Has foo = "bar" (i.e. overwritten)', function () {
            expect(data, 'to have property', 'foo', 'bar');
        });
        it('Has what = "this is from default.cjson."', function () {
            expect(data, 'to have property', 'what', 'this is from default.cjson.');
        });
        it('Only has "foo" and "what"-keys', function () {
            expect(data, 'to only have keys', ['foo', 'what']);
        });
    });
    describe('extend-in-subobject.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('extend-in-subobject.cjson'));
        });
        it('Has subobject = contents of extend-base.cjson', function () {
            expect(data, 'to equal', {
                'subobject': {
                    'foo': 'bar',
                    'what': 'this is from default.cjson.'
                }
            });
        });
    });
    describe('extend-multiple.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('extend-multiple.cjson'));
        });
        it('should have properties from both extended files', function () {
            expect(data, 'to equal', {
                foo: 'bar',
                bar: 'foo'
            });
        });
    });
    describe('extend-nested.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('extend-nested.cjson'));
        });
        it('should have properties from both extended files', function () {
            expect(data, 'to equal', {
                foo: 'foo',
                bar: 'bar',
                baz: 'baz'
            });
        });
    });
    describe('list-of-includes.cjson', function () {
        var data;
        before(function () {
            data = oconf.load(testFile('list-of-includes.cjson'));
        });
        it('should resolve includes in the list', function () {
            expect(data, 'to equal', [
                { foo: 'bar' }, { bar: 'foo' }
            ]);
        });
    });
    describe('loop1.cjson / loop2.cjson', function () {
        it('Loading loop1.cjson throws error', function () {
            expect(function () {
                oconf.load(testFile('loop1.cjson'));
            }, 'to throw', /^Loop in loaded files/);
        });
        it('Loading loop2.cjson throws error', function () {
            expect(function () {
                oconf.load(testFile('loop2.cjson'));
            }, 'to throw', /^Loop in loaded files/);
        });
    });
    describe('includeNonExistentFile.cjson', function () {
        it('should throw an error when nonExistentFile.cjson is not ignored', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'));
            }, 'to throw', /^ENOENT, no such file or directory/);
        });
        it('should not throw an error when nonExistentFile.cjson is ignored', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), {ignore: testFile('nonExistentFile.cjson')});
            }, 'not to throw');
        });
    });
    describe('ignore included files with globbing', function () {
        it('should not throw an error when ignoring by glob #1', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: '**/*.cjson' });
            }, 'not to throw');
        });
        it('should not throw an error when ignoring by glob #2', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: testFile('./**') });
            }, 'not to throw');
        });
        it('should not throw an error when ignoring by glob #3', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: testFile('../files/*') });
            }, 'not to throw');
        });
        it('should not throw an error when ignoring by glob #4', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: '../files/*.cjson', cwd: __dirname });
            }, 'not to throw');
        });
        it('should throw an error when ignoring by glob but including file not matched by glob', function () {
            expect(function () {
                oconf.load(testFile('includeNonExistentFile.cjson'), { ignore: testFile('foo/*cjson') });
            }, 'to throw', /^ENOENT, no such file or directory/);
        });
    });
});

describe('#public behaviour', function () {
    describe('when loading with public:false (the default)', function () {
        describe('where the root object contains a #public property', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-base.cjson'));
            });
            it('should fold the #public properties down into the base structure', function () {
                expect(data, 'to equal', {
                    foo: 'do not expose to public',
                    what: 'what is public',
                    '#public': {
                        what: 'what is public'
                    }
                });
            });
        });

        describe('where a child object contains some #public properties', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-deep.cjson'));
            });
            it('should fold the #public properties down into the base structure', function () {
                expect(data, 'to equal', {
                    foo: "do not expose to public",
                    bar: {
                        quux: "super secret"
                    },
                    hello: {
                        earth: "mostly harmless",
                        answer: 42
                    },
                    '#public': {
                        hello: {
                            answer: 42
                        }
                    }
                });
            });
        });

        describe('where a child object in a child array contains some #public properties', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('array-with-object-with-public.cjson'));
            });
            it('should fold the #public properties down into the base structure', function () {
                expect(data, 'to equal', {
                    foo: [
                        {
                            bar: 'quux'
                        }
                    ],
                    '#public': {
                        foo: [
                            {
                                bar: 'quux'
                            }
                        ]
                    }
                });
            });
        });

        describe('where a child object in a child array contains some #public properties', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('array-with-object-with-array-with-object-with-public.cjson'));
            });
            it.skip('should fold the #public properties down into the base structure', function () {
                expect(data, 'to exhaustively satisfy', {
                    0: {
                        foo: [
                            {
                                bar: 'quux'
                            }
                        ]
                    },
                    '#public': [{
                        foo: [
                            {
                                bar: 'quux'
                            }
                        ]
                    }]
                }).and('to be an array');
            });
        });

        describe('when trying to overwrite a public property with a property that was declared public at another level', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-conflict.cjson'));
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where trying to overwrite a non-public property with a #public one', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-deep-with-include.cjson'));
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where trying to overwrite a #public property with a non-public one', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-deep-with-include.cjson'));
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where including a file that already has a #public property which we try to overwrite', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-deep-with-public-include.cjson'));
            });
            it('should overwrite the included #public property with our value', function () {
                expect(data, 'to equal', {
                    foo: "do not expose to public",
                    bar: {
                        quux: "super secret"
                    },
                    hello: {
                        earth: "mostly harmless",
                        answer: 'Insufficient data for meaningful answer'
                    },
                    '#public': {
                        hello: {
                            answer: 'Insufficient data for meaningful answer'
                        }
                    }
                });
            });
        });
    });

    describe('when loading with public:true', function () {
        describe('where the root object contains a #public property', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-base.cjson'), { public: true });
            });
            it('should fold the #public properties down into the base structure, and omit secret properties and leaves', function () {
                expect(data, 'to equal', {
                    what: 'what is public'
                });
            });
        });

        describe('where a child object contains some #public properties', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-deep.cjson'), { public: true });
            });
            it('should fold the #public properties down into the base structure, and omit secret properties and leaves', function () {
                expect(data, 'to equal', {
                    hello: {
                        answer: 42
                    }
                });
            });
        });

        describe('where trying to overwrite a non-public property with a #public one', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-deep-with-include.cjson'), { public: true });
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where trying to overwrite a #public property with a non-public one', function () {
            it('should throw an error', function () {
                expect(function () {
                    oconf.load(testFile('public-deep-with-include.cjson'), { public: true });
                }, 'to throw', /^Unsupported combination of public and non/);
            });
        });

        describe('where including a file that overwrites a #public property with another public one', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('public-deep-with-public-include.cjson'), { public: true });
            });
            it('should overwrite the included #public property with our value, and omit secret properties and leaves', function () {
                expect(data, 'to equal', {
                    hello: {
                        answer: 'Insufficient data for meaningful answer'
                    }
                });
            });
        });

        describe('when there are no #public properties at all', function () {
            var data;
            before(function () {
                data = oconf.load(testFile('base.cjson'), { public: true });
            });
            it('should return an empty object', function () {
                expect(data, 'to equal', {});
            });
        });
    });

    describe('with public-array.cjson', function () {
        it('throws an error', function () {
            expect(function () {
                oconf.load(testFile('public-array.cjson'));
            }, 'to throw', /^\#public must always be an object/);
        });
    });

    describe('with public-non-object.cjson', function () {
        it('throws an error', function () {
            expect(function () {
                oconf.load(testFile('public-non-object.cjson'));
            }, 'to throw', /^\#public must always be an object/);
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var test = require('tap').test,
  parse = require('../../../lib/parsers/javascript'),
  inferName = require('../../../lib/infer/name')();

function toComment(fn, file) {
  return parse({
    file: file,
    source: fn instanceof Function ? '(' + fn.toString() + ')' : fn
  })[0];
}

function evaluate(fn, file) {
  return inferName(toComment(fn, file));
}

test('inferName', function (t) {
  t.equal(evaluate(function () {
    // ExpressionStatement (comment attached here)
    //   AssignmentExpression
    //     MemberExpression
    //     Identifier
    /** Test */
    exports.name = test;
  }).name, 'name', 'expression statement');

  t.equal(evaluate(function () {
    // ExpressionStatement
    //   AssignmentExpression
    //     MemberExpression (comment attached here)
    //     FunctionExpression
    /** Test */
    exports.name = function () {};
  }).name, 'name', 'expression statement, function');

  t.equal(evaluate(function () {
    exports = {
      // Property (comment attached here)
      //   Identifier
      //   FunctionExpression
      /** Test */
      name: test
    };
  }).name, 'name', 'property');

  t.equal(evaluate(function () {
    exports = {
      // Property
      //   Identifier (comment attached here)
      //   FunctionExpression
      /** Test */
      name: function () {}
    };
  }).name, 'name', 'property, function');

  t.equal(evaluate(function () {
    /** Test */
    function name() {}
    return name;
  }).name, 'name', 'function declaration');

  t.equal(evaluate(function () {
    /** Test */
    var name = function () {};
    return name;
  }).name, 'name', 'anonymous function expression');

  t.equal(evaluate(function () {
    /** Test */
    var name = function name2() {};
    return name;
  }).name, 'name', 'named function expression');

  t.equal(evaluate(function () {
    /**
     * Test
     * @name explicitName
     */
    function implicitName() {}
    return implicitName;
  }).name, 'explicitName', 'explicit name');

  t.equal(evaluate(function () {
    /** @alias explicitAlias */
    function implicitName() {}
  }).name, 'explicitAlias', 'explicit alias');

  t.equal(evaluate(function () {
    /** @class ExplicitClass */
    function ImplicitClass() {}
    return ImplicitClass;
  }).name, 'ExplicitClass', 'explicit class');

  t.equal(evaluate(function () {
    /** @class */
    function ImplicitClass() {}
    return ImplicitClass;
  }).name, 'ImplicitClass', 'anonymous class');

  t.equal(evaluate(function () {
    /**
     * @event explicitEvent
     */
    function implicitName() {}
    return implicitName;
  }).name, 'explicitEvent', 'explicitEvent');

  t.equal(evaluate(function () {
    /**
     * @typedef {Object} ExplicitTypedef
     */
    function implicitName() {}
    return implicitName;
  }).name, 'ExplicitTypedef', 'ExplicitTypedef');

  t.equal(evaluate(function () {
    /**
     * @callback explicitCallback
     */
    function implicitName() {}
    return implicitName;
  }).name, 'explicitCallback', 'explicitCallback');

  t.equal(evaluate(function () {
    /**
     * @module explicitModule
     */
    function implicitName() {}
    return implicitName;
  }).name, 'explicitModule');

  t.equal(evaluate(function () {
    /**
     * @module {Function} explicitModule
     */
    function implicitName() {}
    return implicitName;
  }).name, 'explicitModule');

  t.equal(evaluate(function () {
    /**
     * @module
     */
    function implicitName() {}
    return implicitName;
  }, '/path/inferred-from-file.js').name, 'inferred-from-file');

  t.equal(evaluate(function () {
    /**
     * @module
     */
  }, '/path/inferred-from-file.js').name, 'inferred-from-file');

  t.end();
});
<commit_msg>Clean up name inference unit tests<commit_after>'use strict';

var test = require('tap').test,
  parse = require('../../../lib/parsers/javascript'),
  inferName = require('../../../lib/infer/name')();

function toComment(fn, file) {
  return parse({
    file: file,
    source: fn instanceof Function ? '(' + fn.toString() + ')' : fn
  })[0];
}

function evaluate(fn, file) {
  return inferName(toComment(fn, file));
}

test('inferName', function (t) {
  t.equal(evaluate(function () {
    // ExpressionStatement (comment attached here)
    //   AssignmentExpression
    //     MemberExpression
    //     Identifier
    /** Test */
    exports.name = test;
  }).name, 'name', 'expression statement');

  t.equal(evaluate(function () {
    // ExpressionStatement
    //   AssignmentExpression
    //     MemberExpression (comment attached here)
    //     FunctionExpression
    /** Test */
    exports.name = function () {};
  }).name, 'name', 'expression statement, function');

  t.equal(evaluate(function () {
    exports = {
      // Property (comment attached here)
      //   Identifier
      //   FunctionExpression
      /** Test */
      name: test
    };
  }).name, 'name', 'property');

  t.equal(evaluate(function () {
    exports = {
      // Property
      //   Identifier (comment attached here)
      //   FunctionExpression
      /** Test */
      name: function () {}
    };
  }).name, 'name', 'property, function');

  t.equal(evaluate(function () {
    /** Test */
    function name() {}
  }).name, 'name', 'function declaration');

  t.equal(evaluate(function () {
    /** Test */
    var name = function () {};
  }).name, 'name', 'anonymous function expression');

  t.equal(evaluate(function () {
    /** Test */
    var name = function name2() {};
  }).name, 'name', 'named function expression');

  t.equal(evaluate(function () {
    /** @name explicitName */
    function implicitName() {}
  }).name, 'explicitName', 'explicit name');

  t.equal(evaluate(function () {
    /** @alias explicitAlias */
    function implicitName() {}
  }).name, 'explicitAlias', 'explicit alias');

  t.equal(evaluate(function () {
    /** @class ExplicitClass */
    function ImplicitClass() {}
  }).name, 'ExplicitClass', 'explicit class');

  t.equal(evaluate(function () {
    /** @class */
    function ImplicitClass() {}
  }).name, 'ImplicitClass', 'anonymous class');

  t.equal(evaluate(function () {
    /** @event explicitEvent */
    function implicitName() {}
  }).name, 'explicitEvent', 'explicitEvent');

  t.equal(evaluate(function () {
    /** @typedef {Object} ExplicitTypedef */
    function implicitName() {}
  }).name, 'ExplicitTypedef', 'ExplicitTypedef');

  t.equal(evaluate(function () {
    /** @callback explicitCallback */
    function implicitName() {}
  }).name, 'explicitCallback', 'explicitCallback');

  t.equal(evaluate(function () {
    /** @module explicitModule */
    function implicitName() {}
  }).name, 'explicitModule');

  t.equal(evaluate(function () {
    /** @module {Function} explicitModule */
    function implicitName() {}
  }).name, 'explicitModule');

  t.equal(evaluate(function () {
    /** @module */
    function implicitName() {}
  }, '/path/inferred-from-file.js').name, 'inferred-from-file');

  t.equal(evaluate(function () {
    /** @module */
  }, '/path/inferred-from-file.js').name, 'inferred-from-file');

  t.end();
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { InfoBar } from 'components';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])
@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: push})

export default class App extends Component {
    static propTypes = {
      children: PropTypes.object.isRequired,
      user: PropTypes.object,
      logout: PropTypes.func.isRequired,
      pushState: PropTypes.func.isRequired
    };

    static contextTypes = {
      store: PropTypes.object.isRequired
    };

    state = {
      navExpanded: false,
      loginUsername: false
    }

    componentWillReceiveProps(nextProps) {
      if (!this.props.user && nextProps.user) {
        // login
        this.props.pushState('/loginSuccess');
      } else if (this.props.user && !nextProps.user) {
        // logout
        this.props.pushState('/');
      }
    }

    onNavItemClick = () => {
      this.setState({ navExpanded: false });
    }
    onNavbarToggle = () => {
      this.setState({ navExpanded: ! this.state.navExpanded });
    }
    handleLogout = (event) => {
      event.preventDefault();
      this.props.logout();
    }

    render() {
      const {user, loginUsername} = this.state;
      const styles = require('./App.scss');

      return (

          <Helmet {...config.app.head}/>
          <Navbar fixedTop expanded={ this.state.navExpanded } onToggle={ this.onNavbarToggle }>
            <Navbar.Header>
              <Navbar.Brand>
                <IndexLink to="/" activeStyle={{color: '#d52b1e'}}>

                  {config.app.title} {user} { res.cookies }
                </IndexLink>
              </Navbar.Brand>
              <Navbar.Toggle/>
            </Navbar.Header>

            <Navbar.Collapse>

                <LinkContainer to="/community">
                  <NavItem eventKey={1} onClick={ this.onNavItemClick }>Community</NavItem>
                </LinkContainer>
                <LinkContainer to="/registrieren">
                  <NavItem eventKey={2} onClick={ this.onNavItemClick }>Mitglied werden</NavItem>
                </LinkContainer>
                <LinkContainer to="/kontakt">
                  <NavItem eventKey={3} onClick={ this.onNavItemClick }>Kontakt</NavItem>
                </LinkContainer>

            </Navbar.Collapse>
          </Navbar>

            {this.props.children}

          <InfoBar/>

            Copyright 2016 | Swiss React Community | React, Redux, Flux, React Native | Swiss-react.ch

      );
    }
  }
<commit_msg>new try v5.10aaaasssss77aaa<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { InfoBar } from 'components';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])
@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: push})

export default class App extends Component {
    static propTypes = {
      children: PropTypes.object.isRequired,
      user: PropTypes.object,
      logout: PropTypes.func.isRequired,
      pushState: PropTypes.func.isRequired
    };

    static contextTypes = {
      store: PropTypes.object.isRequired
    };

    state = {
      navExpanded: false,
      loginUsername: false
    }

    componentWillReceiveProps(nextProps) {
      if (!this.props.user && nextProps.user) {
        // login
        this.props.pushState('/loginSuccess');
      } else if (this.props.user && !nextProps.user) {
        // logout
        this.props.pushState('/');
      }
    }

    onNavItemClick = () => {
      this.setState({ navExpanded: false });
    }
    onNavbarToggle = () => {
      this.setState({ navExpanded: ! this.state.navExpanded });
    }
    handleLogout = (event) => {
      event.preventDefault();
      this.props.logout();
    }

    render() {
      const {user, loginUsername} = this.state;
      const styles = require('./App.scss');

      return (

          <Helmet {...config.app.head}/>
          <Navbar fixedTop expanded={ this.state.navExpanded } onToggle={ this.onNavbarToggle }>
            <Navbar.Header>
              <Navbar.Brand>
                <IndexLink to="/" activeStyle={{color: '#d52b1e'}}>

                  {config.app.title} {user}
                </IndexLink>
              </Navbar.Brand>
              <Navbar.Toggle/>
            </Navbar.Header>

            <Navbar.Collapse>

                <LinkContainer to="/community">
                  <NavItem eventKey={1} onClick={ this.onNavItemClick }>Community</NavItem>
                </LinkContainer>
                <LinkContainer to="/registrieren">
                  <NavItem eventKey={2} onClick={ this.onNavItemClick }>Mitglied werden</NavItem>
                </LinkContainer>
                <LinkContainer to="/kontakt">
                  <NavItem eventKey={3} onClick={ this.onNavItemClick }>Kontakt</NavItem>
                </LinkContainer>

            </Navbar.Collapse>
          </Navbar>

            {this.props.children}

          <InfoBar/>

            Copyright 2016 | Swiss React Community | React, Redux, Flux, React Native | Swiss-react.ch

      );
    }
  }
<|endoftext|>


<commit_before>(function(){
    var template_cache = {};

    $(function(){
        new Backbone.Router({
            routes: {
                '': index,
                ':unique_lga/lga_overview': route(lga_overview),
                ':unique_lga/lga_health': route(lga_sector, 'health'),
                ':unique_lga/lga_education': route(lga_sector, 'education'),
                ':unique_lga/lga_water': route(lga_sector, 'water'),
                ':unique_lga/facility_overview': route(facility_overview),
                ':unique_lga/facility_health': route(facility_sector, 'health'),
                ':unique_lga/facility_education': route(facility_sector, 'education'),
                ':unique_lga/facility_water': route(facility_sector, 'water')
            }
        });
        Backbone.history.start();
    });

    // Views
    function _lga_nav(lga, active_view, sector){
        var template = $('#lga_nav_template').html();
        var html = _.template(template, {
            lga: lga,
            active_view: active_view,
            sector: sector
        });
        $('#lga_nav').html(html);
    }

    function index(){
        render('#index_template', {});
        $('#zone-navigation .state-link').click(function(){
            $(this).next('.lga-list').toggle();
            return false;
        });
    }

    function lga_overview(lga){
        _lga_nav(lga, 'lga', 'overview');
        render('#lga_overview_template', {lga: lga});
        leaflet_overview(lga);
    }

    function lga_sector(lga, sector){
        _lga_nav(lga, 'lga', sector);
        render('#lga_sector_template', {
            lga: lga,
            sector: sector
        });
    }

    function facility_overview(lga){
        _lga_nav(lga, 'facility', 'overview');
        render('#facility_overview_template', {lga: lga});
        leaflet_facility(lga);
    }

    function facility_sector(lga, sector){
        _lga_nav(lga, 'facility', sector);
        render('#facility_sector_template', {lga: lga});
        showDataTable(sector, 0, lga.facilities);
    }

    // Helper Functions
    function route(view, sector){
        return function(unique_lga){
            var lga = NMIS.lgas[unique_lga];
            if (typeof lga === 'undefined'){
                var url = '/static/lgas/' + unique_lga + '.json';
                $.getJSON(url, function(lga){
                    NMIS.lgas[unique_lga] = lga;
                    view(lga, sector);
                });
            } else {
                view(lga, sector);
            }
        };
    }

    function render(template_id, context){
        var template = $(template_id).html();
        context.NMIS = NMIS;
        context.format_value = format_value;
        var html = _.template(template, context);
        $('#content .content').html(html);
    }

    function format_value(value){
        if (typeof value === 'undefined') return '-';
        if (_.isNumber(value) && value % 1 !== 0)
            return value.toFixed(2);
        return value;
    }

    function showDataTable(sector, table_index, facilities){
        var aoColumns = [];
        var table = NMIS.facility_tables[sector][table_index];
        console.log(table)
        _.each(table.indicators, function(indicator){
            console.log(indicator)
            aoColumns.push({
                sTitle: NMIS.indicators[indicator].name
            });
        });

        var aaData = [];
        _.each(facilities, function(facility){
            if (facility.sector === sector){
                var facility_data = [];
                _.each(table.indicators, function(indicator){
                    facility_data.push(facility[indicator]);
                });
                aaData.push(facility_data);
            }
        });

        $('#facilities_data_table').dataTable({
            aaData: aaData,
            aoColumns: aoColumns
        });
    }
})();

function leaflet_overview(lga){
    var map_div = $(".map")[0];
    var lat_lng = new L.LatLng(lga.latitude, lga.longitude);
    var map_zoom = 9;
    var summary_map = L.map(map_div, {})
            .setView(lat_lng, map_zoom);
    var tileset = "nigeria_base";
    var tile_server = "http://{s}.tiles.mapbox.com/v3/modilabs." +
                      tileset +
                      "/{z}/{x}/{y}.png";
    L.tileLayer(tile_server, {
        minZoom: 6,
        maxZoom: 11
    }).addTo(summary_map);
}

function leaflet_facility(lga){
    var map_div = $("#facility_overview_map")[0];
    var lat_lng = new L.LatLng(lga.latitude, lga.longitude);
    var map_zoom = 9; //TODO: adding nw and se for bounding box
    var facility_map = L.map(map_div, {})
            .setView(lat_lng, map_zoom);
    var tileset = "nigeria_overlays_white";
    var tile_server = "http://{s}.tiles.mapbox.com/v3/modilabs." +
                      tileset +
                      "/{z}/{x}/{y}.png";
    var lga_layer = new L.TileLayer(tile_server, {
        minZoom: 6,
        maxZoom: 11
    });
    var osm_server = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
    var osm_layer = new L.TileLayer(osm_server, {
        minZoom: 0,
        maxZoom: 18
    });
    var google_layer = new L.Google("SATELLITE", {
        minZoom: 0,
        maxZoom: 18
    });

    //osm_layer.addTo(facility_map);
    facility_map.addLayer(google_layer);
    lga_layer.addTo(facility_map);

    //now we add facilities
    var facilities = lga.facilities;
    for (var i = 0; i < facilities.length; i++){
        var fac = facilities[i];
        var gps = fac.gps.split(" ");
        var mark = new L.Marker([gps[0], gps[1]]);
        var popup_name = fac.facility_name || 'Water Point';
        var popup_photo = "https://formhub.org/attachment/" +
                          "small" +
                          "?media_file=ossap/attachments/" +
                          fac.formhub_photo_id;
        var popup = "
" + popup_name + "
" +
            "";

        mark.on('mouseover', mark.openPopup.bind(mark))
            .on('mouseout', mark.closePopup.bind(mark))
            .addTo(facility_map).bindPopup(popup);

    }

}
<commit_msg>Small cleanup for code review<commit_after>(function(){
    var template_cache = {};

    $(function(){
        new Backbone.Router({
            routes: {
                '': index,
                ':unique_lga/lga_overview': route(lga_overview),
                ':unique_lga/lga_health': route(lga_sector, 'health'),
                ':unique_lga/lga_education': route(lga_sector, 'education'),
                ':unique_lga/lga_water': route(lga_sector, 'water'),
                ':unique_lga/facility_overview': route(facility_overview),
                ':unique_lga/facility_health': route(facility_sector, 'health'),
                ':unique_lga/facility_education': route(facility_sector, 'education'),
                ':unique_lga/facility_water': route(facility_sector, 'water')
            }
        });
        Backbone.history.start();
    });

    // Views
    // ============
    function _lga_nav(lga, active_view, sector){
        var template = $('#lga_nav_template').html();
        var html = _.template(template, {
            lga: lga,
            active_view: active_view,
            sector: sector
        });
        $('#lga_nav').html(html);
    }

    function index(){
        render('#index_template', {});
        $('#zone-navigation .state-link').click(function(){
            $(this).next('.lga-list').toggle();
            return false;
        });
    }

    function lga_overview(lga){
        _lga_nav(lga, 'lga', 'overview');
        render('#lga_overview_template', {lga: lga});
        leaflet_overview(lga);
    }

    function leaflet_overview(lga){
        var map_div = $('.map')[0];
        var lat_lng = new L.LatLng(lga.latitude, lga.longitude);
        var map_zoom = 9;
        var summary_map = L.map(map_div, {})
                .setView(lat_lng, map_zoom);
        var tileset = 'nigeria_base';
        var tile_server = 'http://{s}.tiles.mapbox.com/v3/modilabs.' +
                          tileset +
                          '/{z}/{x}/{y}.png';
        L.tileLayer(tile_server, {
            minZoom: 6,
            maxZoom: 11
        }).addTo(summary_map);
    }

    function lga_sector(lga, sector){
        _lga_nav(lga, 'lga', sector);
        render('#lga_sector_template', {
            lga: lga,
            sector: sector
        });
    }

    function facility_overview(lga){
        _lga_nav(lga, 'facility', 'overview');
        render('#facility_overview_template', {lga: lga});
        leaflet_facility(lga);
    }

    function leaflet_facility(lga){
        var map_div = $("#facility_overview_map")[0];
        var lat_lng = new L.LatLng(lga.latitude, lga.longitude);
        var map_zoom = 9; //TODO: adding nw and se for bounding box
        var facility_map = L.map(map_div, {})
                .setView(lat_lng, map_zoom);
        var tileset = "nigeria_overlays_white";
        var tile_server = "http://{s}.tiles.mapbox.com/v3/modilabs." +
                          tileset +
                          "/{z}/{x}/{y}.png";
        var lga_layer = new L.TileLayer(tile_server, {
            minZoom: 6,
            maxZoom: 11
        });
        var osm_server = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
        var osm_layer = new L.TileLayer(osm_server, {
            minZoom: 0,
            maxZoom: 18
        });
        var google_layer = new L.Google("SATELLITE", {
            minZoom: 0,
            maxZoom: 18
        });

        //osm_layer.addTo(facility_map);
        facility_map.addLayer(google_layer);
        lga_layer.addTo(facility_map);

        //now we add facilities
        var facilities = lga.facilities;
        for (var i = 0; i < facilities.length; i++){
            var fac = facilities[i];
            var gps = fac.gps.split(" ");
            var mark = new L.Marker([gps[0], gps[1]]);
            var popup_name = fac.facility_name || 'Water Point';
            var popup_photo = "https://formhub.org/attachment/" +
                              "small" +
                              "?media_file=ossap/attachments/" +
                              fac.formhub_photo_id;
            var popup = "
" + popup_name + "
" +
                "";

            mark.on('mouseover', mark.openPopup.bind(mark))
                .on('mouseout', mark.closePopup.bind(mark))
                .addTo(facility_map).bindPopup(popup);
        }
    }

    function facility_sector(lga, sector){
        _lga_nav(lga, 'facility', sector);
        render('#facility_sector_template', {lga: lga});
        showDataTable(sector, 0, lga.facilities);
    }

    function showDataTable(sector, table_index, facilities){
        var aoColumns = [];
        var table = NMIS.facility_tables[sector][table_index];

        _.each(table.indicators, function(indicator){
            aoColumns.push({
                sTitle: NMIS.indicators[indicator].name
            });
        });

        var aaData = [];
        _.each(facilities, function(facility){
            if (facility.sector === sector){
                var facility_data = [];
                _.each(table.indicators, function(indicator){
                    facility_data.push(facility[indicator]);
                });
                aaData.push(facility_data);
            }
        });

        $('#facilities_data_table').dataTable({
            aaData: aaData,
            aoColumns: aoColumns
        });
    }

    // Helper Functions
    // ==========================
    function route(view, sector){
        return function(unique_lga){
            var lga = NMIS.lgas[unique_lga];
            if (typeof lga === 'undefined'){
                var url = '/static/lgas/' + unique_lga + '.json';
                $.getJSON(url, function(lga){
                    NMIS.lgas[unique_lga] = lga;
                    view(lga, sector);
                });
            } else {
                view(lga, sector);
            }
        };
    }

    function render(template_id, context){
        var template = $(template_id).html();
        context.NMIS = NMIS;
        context.format_value = format_value;
        var html = _.template(template, context);
        $('#content .content').html(html);
    }

    function format_value(value){
        if (typeof value === 'undefined') return '-';
        if (_.isNumber(value) && value % 1 !== 0)
            return value.toFixed(2);
        return value;
    }
})();

<|endoftext|>


<commit_before>
function filterMachines(f) {
	$('.machines-buttons .quick-button').removeClass('active');
	$('.machines-buttons .btn-'+f).addClass('active');
	if (f === 'all') f = '*';
	else f = '.'+f;
	$('#machines-loader').isotope( { filter: f } );
}

var cloudlyVMSmanager  = {
    template: '',
    actualMachines: '',
    colors : {
		'#36a9e1':'lightBlue',
		'#78cd51':'green',
		'#333366':'darkGreen',
		'#eae874':'yellow',
		'#fa603d':'lightOrange',
		'#ff5454':'red',
		'#CBD4E4':'silver',
		'#e84c8a':'pink',
		'#000000':'black'
		},
    initAction: function(){
        var $this = this;
        $('#machines-loader').isotope({
            itemSelector: '.vms-machine'
        });
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/box-template/',
            data: '',
            success: function(res){
                $this.template = res;
                setInterval(function(){
                    $this.loadMachinesData();
                },1000);
            }
        });
    },
    loadMachinesData: function(){
        var actualMachines = $(".vms-machine");

        var $this = this;
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/vms/',
            data: '',
            success: function(res){
                var jsonData = $.parseJSON(res);
                $this.checkRemoved(jsonData,actualMachines);
                $this.parseMachinesData(jsonData);

            }
        });
    },
    parseMachinesData: function(jsonData){
        var $this = this;
        if(jsonData){
            $.each(jsonData,function(vms,data){
                //exist VMS
                if($('#'+vms).length){
                    $this.updateVMS(vms,data);
                }
                else {
                    $this.addVMS(vms,data);
                }
            });
        }
    },
    updateVMS: function(vms,data){
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        $('#'+vms).find('.value').html(data.state);

        var panel = $("#"+vms).find('.panel');

        $.each(this.colors,function(code,color){
                if(panel.hasClass(color) && panel.attr('class').indexOf(data.vmcolor) === -1){
                        $(panel).removeClass(color).addClass(data.vmcolor)
                        //console.log('VM '+vms+' changed color: '+color+' to: '+data.vmcolor+' and actual has class: '+panel.attr('class'));
                        return;
                }
        });

    },
    addVMS: function(vms,data){
        var template = this.template;
        template = template.replace('{@vmlink@}',data.link);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vmtitle@}',data.vmtitle);
        template = template.replace('{@vmcolor@}',data.vmcolor);
        template = template.replace('{@averge@}',data.averge);
        template = template.replace("{@state@}", data.state);

        template = $(template);
        //console.log(template);
        var prepend = $('#machines-loader').prepend(template);
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        prepend.isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });

    },
    checkRemoved: function(machines,actualMachines){
        var machineIds = 'testVMS';
	var $container = $('#machines-loader');
        $.each(machines,function(vms,value){
            machineIds += vms+',';
        });

        $.each(actualMachines,function(index,item){
            var id = $(item).attr('id');
            if(machineIds.indexOf(id) < 0){
                $container.isotope( 'remove', item ).isotope('layout');
            }
        });

    },
    reloadPositions: function(){
            $('#machines-loader').isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });
    },
    addBlank: function(){
        this.addVMS('testVMS',{"averge":"0.0,0.0,0.0,0.0","state":"Running"});

    }
}

$(document).ready (function() {

	var btns = ['all','critical','offline', windows', 'linux', 'bsd', cloud'];
	for (var i = 0; i < btns.length; ++i) {
	    (function(){
		var type = btns[i];
		var btn = $('.machines-buttons .btn-'+type);
		btn.click(function() { filterMachines(type); });
	    })();
	}

        cloudlyVMSmanager.initAction();

});

<commit_msg>fixing broken syntaxs on the dashboard js<commit_after>
function filterMachines(f) {
	$('.machines-buttons .quick-button').removeClass('active');
	$('.machines-buttons .btn-'+f).addClass('active');
	if (f === 'all') f = '*';
	else f = '.'+f;
	$('#machines-loader').isotope( { filter: f } );
}

var cloudlyVMSmanager  = {
    template: '',
    actualMachines: '',
    colors : {
		'#36a9e1':'lightBlue',
		'#78cd51':'green',
		'#333366':'darkGreen',
		'#eae874':'yellow',
		'#fa603d':'lightOrange',
		'#ff5454':'red',
		'#CBD4E4':'silver',
		'#e84c8a':'pink',
		'#000000':'black'
		},
    initAction: function(){
        var $this = this;
        $('#machines-loader').isotope({
            itemSelector: '.vms-machine'
        });
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/box-template/',
            data: '',
            success: function(res){
                $this.template = res;
                setInterval(function(){
                    $this.loadMachinesData();
                },1000);
            }
        });
    },
    loadMachinesData: function(){
        var actualMachines = $(".vms-machine");

        var $this = this;
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/vms/',
            data: '',
            success: function(res){
                var jsonData = $.parseJSON(res);
                $this.checkRemoved(jsonData,actualMachines);
                $this.parseMachinesData(jsonData);

            }
        });
    },
    parseMachinesData: function(jsonData){
        var $this = this;
        if(jsonData){
            $.each(jsonData,function(vms,data){
                //exist VMS
                if($('#'+vms).length){
                    $this.updateVMS(vms,data);
                }
                else {
                    $this.addVMS(vms,data);
                }
            });
        }
    },
    updateVMS: function(vms,data){
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        $('#'+vms).find('.value').html(data.state);

        var panel = $("#"+vms).find('.panel');

        $.each(this.colors,function(code,color){
                if(panel.hasClass(color) && panel.attr('class').indexOf(data.vmcolor) === -1){
                        $(panel).removeClass(color).addClass(data.vmcolor)
                        //console.log('VM '+vms+' changed color: '+color+' to: '+data.vmcolor+' and actual has class: '+panel.attr('class'));
                        return;
                }
        });

    },
    addVMS: function(vms,data){
        var template = this.template;
        template = template.replace('{@vmlink@}',data.link);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vmtitle@}',data.vmtitle);
        template = template.replace('{@vmcolor@}',data.vmcolor);
        template = template.replace('{@averge@}',data.averge);
        template = template.replace("{@state@}", data.state);

        template = $(template);
        //console.log(template);
        var prepend = $('#machines-loader').prepend(template);
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        prepend.isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });

    },
    checkRemoved: function(machines,actualMachines){
        var machineIds = 'testVMS';
	var $container = $('#machines-loader');
        $.each(machines,function(vms,value){
            machineIds += vms+',';
        });

        $.each(actualMachines,function(index,item){
            var id = $(item).attr('id');
            if(machineIds.indexOf(id) < 0){
                $container.isotope( 'remove', item ).isotope('layout');
            }
        });

    },
    reloadPositions: function(){
            $('#machines-loader').isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });
    },
    addBlank: function(){
        this.addVMS('testVMS',{"averge":"0.0,0.0,0.0,0.0","state":"Running"});

    }
}

$(document).ready (function() {

	var btns = ['all','critical','offline', 'windows', 'linux', 'bsd', cloud'];
	for (var i = 0; i < btns.length; ++i) {
	    (function(){
		var type = btns[i];
		var btn = $('.machines-buttons .btn-'+type);
		btn.click(function() { filterMachines(type); });
	    })();
	}

        cloudlyVMSmanager.initAction();

});

<|endoftext|>


<commit_before>$(function(){
	i18n.init({
		resGetPath: language_path
	}, function(err, t) {
		var auto_selected_lang = ''; //現在はデフォルトは英語

		if (i18n.lng() === 'en' || i18n.lng() === 'ja') {
			/* キャッシュがあるとき */
			auto_selected_lang = i18n.lng();
		}
		else {
			/*キャッシュがなく、どの言語にするべきか、わからない場合。*/
			auto_selected_lang = (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage || navigator.browserLanguage)).substr(0, 2);
		}
		i18n.setLng(auto_selected_lang);
		$("div#mainTopic").i18n();
	});

	function change_lang() {
		$("div#mainTopic").i18n();
	}

	function set_font_ja() {
		change_lang();
		$("#mainTopic").css('font-family', '"skia","Meiryo","Hiragino Kaku Gothic Pro"');
		$("#home #mainTopic header #aboutme h1").fitText(1.5,{minFontSize:'12px',maxFontSize: '72px'});
		$("#home #mainTopic header #aboutme p").fitText(1.9,{minFontSize:'9px',maxFontSize: '64px'});

		$("#home #mainTopic article section h2").fitText(1.4,{minFontSize:'28px',maxFontSize: '72px'});
		$("#home #mainTopic article section p").fitText(3.8,{minFontSize:'14px',maxFontSize: '48px'});
		$("#home #mainTopic article section .hobbies h3").fitText(1.3,{minFontSize:'11px',maxFontSize: '62px'});
		$("#home #mainTopic article section .hobbies p").fitText(1.5,{minFontSize:'9px',maxFontSize: '54px'});
		$("#home #mainTopic article section ul > li").fitText(2.1,{minFontSize:'12px',maxFontSize: '74px'});
		$("#home #mainTopic article section ul > ul > li").fitText(2.3,{minFontSize:'10px',maxFontSize: '54px'});
	}

	function set_font_en() {
		change_lang();
		$("#mainTopic").css('font-family', '"Skia","Meiryo","Hiragino Kaku Gothic Pro"');
		$("#home #mainTopic header #aboutme h1").fitText(1.0,{minFontSize:'12px',maxFontSize: '72px'});
		$("#home #mainTopic header #aboutme p").fitText(1.4,{minFontSize:'9px',maxFontSize: '64px'});

		$("#home #mainTopic article section h2").fitText(1.4,{minFontSize:'22px',maxFontSize: '72px'});
		$("#home #mainTopic article section p").fitText(2.2,{minFontSize:'16px',maxFontSize: '38px'});
		$("#home #mainTopic article section .hobbies h3").fitText(1.3,{minFontSize:'11px',maxFontSize: '42px'});
		$("#home #mainTopic article section .hobbies p").fitText(1.4,{minFontSize:'9px',maxFontSize: '38px'});
		$("#home #mainTopic article section ul > li").fitText(2.0,{minFontSize:'12px',maxFontSize: '74px'});
		$("#home #mainTopic article section ul > ul > li").fitText(2.4,{minFontSize:'10px',maxFontSize: '54px'});
	}

	var auto_selected_lang = i18n.lng().substr(0,2);
	if (auto_selected_lang === "ja") { set_font_ja(); }
	else if (auto_selected_lang === "en") { set_font_en(); }
	//else { set_font_en(); }

	$("#trans-ja").click(function() {
		i18n.init({ lng: "ja", fallbackLng: "ja" }).done(function() {
			set_font_ja();
		});
	});
	$("#trans-en").click(function() {
		i18n.init({ lng: "en", fallbackLng: "en" }).done(function() {
			set_font_en();
		});
	});

});
<commit_msg>Fix a bug of a responsive view on the iOS.<commit_after>$(function(){
	i18n.init({
		resGetPath: language_path
	}, function(err, t) {
		var auto_selected_lang = ''; //現在はデフォルトは英語

		if (i18n.lng() === 'en' || i18n.lng() === 'ja') {
			/* キャッシュがあるとき */
			auto_selected_lang = i18n.lng();
		}
		else {
			/*キャッシュがなく、どの言語にするべきか、わからない場合。*/
			auto_selected_lang = (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage || navigator.browserLanguage)).substr(0, 2);
		}
		i18n.setLng(auto_selected_lang);
		$("div#mainTopic").i18n();
	});

	function change_lang() {
		$("div#mainTopic").i18n();
	}

	function set_font_ja() {
		change_lang();
		$("#mainTopic").css('font-family', '"skia","Meiryo","Hiragino Kaku Gothic Pro"');
		$("#home #mainTopic header #aboutme h1").fitText(1.5,{minFontSize:'12px',maxFontSize: '72px'});
		$("#home #mainTopic header #aboutme p").fitText(1.9,{minFontSize:'9px',maxFontSize: '64px'});

		$("#home #mainTopic article section h2").fitText(1.4,{minFontSize:'28px',maxFontSize: '72px'});
		$("#home #mainTopic article section p").fitText(3.8,{minFontSize:'14px',maxFontSize: '48px'});
		$("#home #mainTopic article section .hobbies h3").fitText(1.3,{minFontSize:'11px',maxFontSize: '62px'});
		$("#home #mainTopic article section .hobbies p").fitText(1.5,{minFontSize:'9px',maxFontSize: '54px'});
		$("#home #mainTopic article section ul > li").fitText(2.1,{minFontSize:'12px',maxFontSize: '74px'});
		$("#home #mainTopic article section ul > ul > li").fitText(2.3,{minFontSize:'10px',maxFontSize: '54px'});
		$("#home #mainTopic article section ul > ul > li").fitText(2.4,{minFontSize:'7px',maxFontSize: '54px'});
	}

	function set_font_en() {
		change_lang();
		$("#mainTopic").css('font-family', '"Skia","Meiryo","Hiragino Kaku Gothic Pro"');
		$("#home #mainTopic header #aboutme h1").fitText(1.0,{minFontSize:'12px',maxFontSize: '72px'});
		$("#home #mainTopic header #aboutme p").fitText(1.4,{minFontSize:'9px',maxFontSize: '64px'});

		$("#home #mainTopic article section h2").fitText(1.4,{minFontSize:'22px',maxFontSize: '72px'});
		$("#home #mainTopic article section p").fitText(2.2,{minFontSize:'16px',maxFontSize: '38px'});
		$("#home #mainTopic article section .hobbies h3").fitText(1.3,{minFontSize:'11px',maxFontSize: '42px'});
		$("#home #mainTopic article section .hobbies p").fitText(1.4,{minFontSize:'9px',maxFontSize: '38px'});
		$("#home #mainTopic article section ul > li").fitText(2.0,{minFontSize:'12px',maxFontSize: '74px'});
		$("#home #mainTopic article section ul > ul > li").fitText(2.4,{minFontSize:'7px',maxFontSize: '54px'});
	}

	var auto_selected_lang = i18n.lng().substr(0,2);
	if (auto_selected_lang === "ja") { set_font_ja(); }
	else if (auto_selected_lang === "en") { set_font_en(); }
	//else { set_font_en(); }

	$("#trans-ja").click(function() {
		i18n.init({ lng: "ja", fallbackLng: "ja" }).done(function() {
			set_font_ja();
		});
	});
	$("#trans-en").click(function() {
		i18n.init({ lng: "en", fallbackLng: "en" }).done(function() {
			set_font_en();
		});
	});

});
<|endoftext|>


<commit_before>//$('#side-menu').metisMenu();

//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(window).bind("load resize", function() {
  topOffset = 71;
  width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
  if (width < 768) {
    $('div.navbar-collapse').addClass('collapse')
    topOffset = 100; // 2-row-menu
  } else {
    $('div.navbar-collapse').removeClass('collapse')
  }

  height = (this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height;
  height = height - topOffset;
  if (height < 1) height = 1;
  if (height > topOffset) {
    $("#page-wrapper").css("min-height", (height) + "px");
  }
});

var lys = {};

lys.fa_icon = function(e) {
  switch(e.msg.build.status) {
    case 'success':   return {icon: 'check',    color: 'green'};
    case 'failed':    return {icon: 'warning',  color: 'firebrick'};
    case 'scheduled': return {icon: 'calendar', color: ''};
    case 'working':   return {icon: 'gear',     color: ''};
    default:          return {icon: 'gear',     color: ''};
  }
};

lys.handleEvent = function(e) {
  switch(e.msg.type) {
    case 'build_create':
      console.log('adding build');
      var elems = document.getElementsByClassName('lys-builds');
      for(i = 0; i < elems.length; i++) {
        if(elems[i].classList.contains('list-group')) {
          var new_item = elems[i].insertBefore(document.createElement('a'), elems[i].childNodes[0]);
          new_item.className = 'list-group-item';
          new_item.setAttribute('href', '/repo/' + e.msg.repo + '/builds/' + e.msg.build.number);
          new_item.innerText = ' ' + e.msg.repo + ' ';
          var icon = new_item.insertBefore(document.createElement('i'), new_item.childNodes[0]);
          icon.className = 'fa fa-' + lys.fa_icon(e).icon + ' fa-fw';
          icon.style.color = lys.fa_icon(e).color;
          var number = new_item.appendChild(document.createElement('b'));
          number.className = 'pull-left';
          number.innerText = '#' + e.msg.build.number;
          var date = new_item.appendChild(document.createElement('span'));
          date.className = 'pull-right text-muted small';
          date.innerHTML = '' + e.msg.build.date + '';
        }
      }
      break;
    case 'build_update':
      console.log('updating build');
      var elems = document.getElementsByClassName('lys-builds');
      for(i = 0; i < elems.length; i++) {
        if(elems[i].classList.contains('list-group')) {
          for(ii = 0; ii < elems[i].childNodes.length; ii++) {
            if(elems[i].childNodes[ii].getAttribute === undefined) {
              continue;
            }
            if(elems[i].childNodes[ii].getAttribute('href') === ('/repo/' + e.msg.repo + '/builds/' + e.msg.build.number)) {
              elems[i].childNodes[ii].childNodes[0].className = 'fa fa-' + lys.fa_icon(e).icon + ' fa-fw';
              elems[i].childNodes[ii].childNodes[0].style.color = lys.fa_icon(e).color;
              elems[i].childNodes[ii].childNodes[3].innerHTML = '' + e.msg.build.date ? e.msg.build.date : '' + '';
            }
          }
        }
      }
      break;
  }
};

lys.handle = function(data) {
  if(!this.initialized) {
    console.log('remote ver.', data.ver);
    this.initialized = true;
  } else {
    switch(data.type) {
      case 'error':     console.log('error:', data.err, data.msg); break;
      case 'success':   console.log('success:', data.msg); break;
      case 'msg':       lys.handleEvent(data); break;
      case 'keepalive': console.log('keepalive'); break;
      default:          console.log('unknown msg type', data.type);
    }
  }
};

window.addEventListener('load', function() {
  lys.ws           = new WebSocket('wss://' + window.location.host + '/realtime');
  lys.ws.onopen    = function()  {
    console.log('websocket opened');
    if(document.getElementsByClassName('lys-builds').length > 0) {
      lys.ws.send('sub builds');
    }
  };
  lys.ws.onclose   = function()  { console.log('websocket closed'); };
  lys.ws.onmessage = function(m) { lys.handle(JSON.parse(m.data)); };
});<commit_msg>Secure WebSocket if over HTTPS<commit_after>//$('#side-menu').metisMenu();

//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(window).bind("load resize", function() {
  topOffset = 71;
  width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
  if (width < 768) {
    $('div.navbar-collapse').addClass('collapse')
    topOffset = 100; // 2-row-menu
  } else {
    $('div.navbar-collapse').removeClass('collapse')
  }

  height = (this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height;
  height = height - topOffset;
  if (height < 1) height = 1;
  if (height > topOffset) {
    $("#page-wrapper").css("min-height", (height) + "px");
  }
});

var lys = {};

lys.fa_icon = function(e) {
  switch(e.msg.build.status) {
    case 'success':   return {icon: 'check',    color: 'green'};
    case 'failed':    return {icon: 'warning',  color: 'firebrick'};
    case 'scheduled': return {icon: 'calendar', color: ''};
    case 'working':   return {icon: 'gear',     color: ''};
    default:          return {icon: 'gear',     color: ''};
  }
};

lys.handleEvent = function(e) {
  switch(e.msg.type) {
    case 'build_create':
      console.log('adding build');
      var elems = document.getElementsByClassName('lys-builds');
      for(i = 0; i < elems.length; i++) {
        if(elems[i].classList.contains('list-group')) {
          var new_item = elems[i].insertBefore(document.createElement('a'), elems[i].childNodes[0]);
          new_item.className = 'list-group-item';
          new_item.setAttribute('href', '/repo/' + e.msg.repo + '/builds/' + e.msg.build.number);
          new_item.innerText = ' ' + e.msg.repo + ' ';
          var icon = new_item.insertBefore(document.createElement('i'), new_item.childNodes[0]);
          icon.className = 'fa fa-' + lys.fa_icon(e).icon + ' fa-fw';
          icon.style.color = lys.fa_icon(e).color;
          var number = new_item.appendChild(document.createElement('b'));
          number.className = 'pull-left';
          number.innerText = '#' + e.msg.build.number;
          var date = new_item.appendChild(document.createElement('span'));
          date.className = 'pull-right text-muted small';
          date.innerHTML = '' + e.msg.build.date + '';
        }
      }
      break;
    case 'build_update':
      console.log('updating build');
      var elems = document.getElementsByClassName('lys-builds');
      for(i = 0; i < elems.length; i++) {
        if(elems[i].classList.contains('list-group')) {
          for(ii = 0; ii < elems[i].childNodes.length; ii++) {
            if(elems[i].childNodes[ii].getAttribute === undefined) {
              continue;
            }
            if(elems[i].childNodes[ii].getAttribute('href') === ('/repo/' + e.msg.repo + '/builds/' + e.msg.build.number)) {
              elems[i].childNodes[ii].childNodes[0].className = 'fa fa-' + lys.fa_icon(e).icon + ' fa-fw';
              elems[i].childNodes[ii].childNodes[0].style.color = lys.fa_icon(e).color;
              elems[i].childNodes[ii].childNodes[3].innerHTML = '' + e.msg.build.date ? e.msg.build.date : '' + '';
            }
          }
        }
      }
      break;
  }
};

lys.handle = function(data) {
  if(!this.initialized) {
    console.log('remote ver.', data.ver);
    this.initialized = true;
  } else {
    switch(data.type) {
      case 'error':     console.log('error:', data.err, data.msg); break;
      case 'success':   console.log('success:', data.msg); break;
      case 'msg':       lys.handleEvent(data); break;
      case 'keepalive': console.log('keepalive'); break;
      default:          console.log('unknown msg type', data.type);
    }
  }
};

window.addEventListener('load', function() {
  lys.ws           = new WebSocket('ws' + (window.location.protocol == 'https' ? 's' : '') + '://' + window.location.host + '/realtime');
  lys.ws.onopen    = function()  {
    console.log('websocket opened');
    if(document.getElementsByClassName('lys-builds').length > 0) {
      lys.ws.send('sub builds');
    }
  };
  lys.ws.onclose   = function()  { console.log('websocket closed'); };
  lys.ws.onmessage = function(m) { lys.handle(JSON.parse(m.data)); };
});<|endoftext|>


<commit_before>var marker;
var latlng = {};
var map

function initialize() {
    var mapOptions = {
		center: new google.maps.LatLng(
		    40.724531899999995,
		    -73.7971586),
		zoom: 16,
		mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    marker = new google.maps.Marker({
		map: map,
		draggable: true
	})

    latlong = loadLocation(map);

}
google.maps.event.addDomListener(window, 'load', initialize);

function loadLocation (){

	function getLocation(pos){
		latlng["latitude"] = pos.coords.latitude;
		latlng["longitude"] = pos.coords.longitude;
		setMarker();
	}

	var load = function() {
		if (navigator.geolocation) {
			console.log("Loading location now....");
		    navigator.geolocation.getCurrentPosition(getLocation, function(error){
				    switch(error.code) {
					    case error.PERMISSION_DENIED:
							console.log("User denied permission.");
							break;
					    case error.POSITION_UNAVAILABLE:
							console.log("Geolocation/GPS unavailable.");
							break;
					    case error.TIMEOUT:
							console.log("Geolocation request timed out.");
							break;
					    case error.UNKNOWN_ERROR:
							console.log("Something wack happened.");
							break;
			    }

			});
		}
	}();

	function setMarker(){
		console.log(latlng);
		var pos = new google.maps.LatLng(latlng.latitude, latlng.longitude);
		marker = new google.maps.Marker({
			map: map,
		    position: pos,
		    animation: google.maps.Animation.DROP,
		    draggable: true
		});
		map.panTo(marker.getPosition());
	};

};
<commit_msg>Markers are draggable.<commit_after>var marker;
var defaultMarker = {
	animation: google.maps.Animation.DROP,
	draggable: true
}

var latlng = {};
var map;

function setMarker(marker){
	return function(latlng){
		var pos = new google.maps.LatLng(latlng.latitude, latlng.longitude);
		marker = new google.maps.Marker({
			map: map,
		    position: pos,
		    animation: defaultMarker.animation,
		    draggable: defaultMarker.draggable
		});
		map.panTo(marker.getPosition());
		google.maps.event.addListener(marker, 'dragend', function(){
   			map.panTo(marker.getPosition());
   		});
	}
};
function toggleBounce() {
  	if (marker.getAnimation() != null) {
    	marker.setAnimation(null);
  	} else {
    	marker.setAnimation(google.maps.Animation.BOUNCE);
  	}
}

function initialize() {
    var mapOptions = {
		center: new google.maps.LatLng(
		    40.724531899999995,
		    -73.7971586),
		zoom: 16,
		mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    latlong = loadLocation(setMarker(marker), function(error){
	    switch(error.code) {
		    case error.PERMISSION_DENIED:
				console.log("User denied permission.");
				break;
		    case error.POSITION_UNAVAILABLE:
				console.log("Geolocation/GPS unavailable.");
				break;
		    case error.TIMEOUT:
				console.log("Geolocation request timed out.");
				break;
		    case error.UNKNOWN_ERROR:
				console.log("Something wack happened.");
				break;
    	}
    });

}
google.maps.event.addDomListener(window, 'load', initialize);

//Callbacks
function loadLocation (callback, error){

	function getLocation(pos){
		latlng["latitude"] = pos.coords.latitude;
		latlng["longitude"] = pos.coords.longitude;
		callback(latlng);
	}

	var load = function() {
		if (navigator.geolocation) {
			console.log("Loading location now....");
		    navigator.geolocation.getCurrentPosition(getLocation, error);
		}
	}();

};
<|endoftext|>


<commit_before>"use strict";

const path = require("path");
const dao = require(path.resolve("src/dao/pokemon"));
const pagarMeProvider = require(path.resolve("src/provider/pagarme"));
const request = require("request-promise");

const controller = {

	getAll: function(req, res) {

		dao.findAll().then(function(results) {
			res.status(200).json(results);
		}).catch(function(error) {
			res.status(500).json(error);
		});

	},

	buy: function(req, res) {

		const _filter = {
			name: req.body.pokemon.name
		},
		_pokemon = req.body.pokemon || {},
		_creditCard = req.body.credit_card || {};

		dao.findOne(_filter)
		.then(function(fetchedPokemon) {

			if (!fetchedPokemon) {

				res.status(400).send({
					statusText: "Bad Request",
					validations: [{
						property: "name",
						messages: ["Pokémon not registered!"]
					}]
				});

			} else if (fetchedPokemon.stock < _pokemon.quantity) {

				res.status(400).send({
					statusText: "Bad Request",
					validations: [{
						property: "quantity",
						messages: ["Not enought " + fetchedPokemon.name + " in stock: " + fetchedPokemon.stock]
					}]
				});

			} else {

				var _data = {
					pokemon: fetchedPokemon,
					creditCard: _creditCard
				};

				_data.pokemon.quantity = _pokemon.quantity;

				pagarMeProvider.buyPokemon(_data)
					.then(function (body){
						if (body.status === "paid") {

							fetchedPokemon.stock = fetchedPokemon.stock - _pokemon.quantity;
							fetchedPokemon.save()
								.then(function() {
									res.send(body);
								})
						} else {

							const messages = body.errors || ["Buy operation error"];

							res.status(400).send({
								statusText: "Bad Request",
								validations: [{
									property: "body",
									messages: messages
								}]
							});
						}
					})
					.catch(function (err){
						res.status(err.response.statusCode).send(err.response.body);
					})

			}

		});

	},

	create: function(req, res) {
		const pokemon = req.body;

		dao.create(pokemon).then(function(createdPokemon) {
			res.status(200).json(createdPokemon);
		}).catch(function(error) {
			res.status(500).json(error);
		});
	}

};

module.exports = controller;<commit_msg>NAMING .<commit_after>"use strict";

const path = require("path");
const dao = require(path.resolve("src/dao/pokemon"));
const pagarMeProvider = require(path.resolve("src/provider/pagarme"));
const request = require("request-promise");

const controller = {

	getAll: function(req, res) {

		dao.findAll().then(function(results) {
			res.status(200).json(results);
		}).catch(function(error) {
			res.status(500).json(error);
		});

	},

	buy: function(req, res) {

		const _filter = {
			name: req.body.pokemon.name
		},
		_pokemon = req.body.pokemon || {},
		_creditCard = req.body.credit_card || {};

		dao.findOne(_filter)
		.then(function(fetchedPokemon) {

			if (!fetchedPokemon) {

				res.status(400).send({
					statusText: "Bad Request",
					validations: [{
						property: "name",
						messages: ["Pokémon not registered!"]
					}]
				});

			} else if (fetchedPokemon.stock < _pokemon.quantity) {

				res.status(400).send({
					statusText: "Bad Request",
					validations: [{
						property: "quantity",
						messages: ["Not enought " + fetchedPokemon.name + " in stock: " + fetchedPokemon.stock]
					}]
				});

			} else {

				var _data = {
					pokemon: fetchedPokemon,
					creditCard: _creditCard
				};

				_data.pokemon.quantity = _pokemon.quantity;

				pagarMeProvider.buyPokemon(_data)
					.then(function (body) {

						const _messages = body.errors || ["Buy operation error"];

						if (body.status === "paid") {

							fetchedPokemon.stock = fetchedPokemon.stock - _pokemon.quantity;
							fetchedPokemon.save()
								.then(function() {
									res.send(body);
								})
						} else {

							res.status(400).send({
								statusText: "Bad Request",
								validations: [{
									property: "body",
									messages: _messages
								}]
							});
						}
					})
					.catch(function (err){
						res.status(err.response.statusCode).send(err.response.body);
					})

			}

		});

	},

	create: function(req, res) {
		const pokemon = req.body;

		dao.create(pokemon).then(function(createdPokemon) {
			res.status(200).json(createdPokemon);
		}).catch(function(error) {
			res.status(500).json(error);
		});
	}

};

module.exports = controller;<|endoftext|>


<commit_before>//Global configuration uese for tests.
require('babel-core/register')({
    presets: [
        'stage-0',
        'react',
        'es2015'
    ],
    plugins: [
        'transform-class-properties',
        'transform-decorators-legacy'
    ]
});

const chai = require('chai');
const chaiSubset = require('chai-subset');
chai.use(chaiSubset);
/*eslint-disable */
const should  = chai.should();
global.expect = require('chai').expect;
/*eslint-enable */

global.React = require('react');
global.ReactDOM = require('react-dom');
global.expect = chai.expect;
global.TestUtils = require('react-addons-test-utils');
/*eslint-disable */
//let {shallowRenderer} = TestUtils;
/*eslint-enable */

process.on('unhandledRejection', (error)=>{
    console.error('Unhandled Promise Rejection:');
    console.error(error && error.stack || error);
});
console.log('Test: bootload done');
<commit_msg>Correcting missing global in unit test<commit_after>//Global configuration uese for tests.
require('babel-core/register')({
    presets: [
        'stage-0',
        'react',
        'es2015'
    ],
    plugins: [
        'transform-class-properties',
        'transform-decorators-legacy'
    ]
});

const chai = require('chai');
const chaiSubset = require('chai-subset');
chai.use(chaiSubset);
/*eslint-disable */
const should  = chai.should();
global.expect = require('chai').expect;
/*eslint-enable */

global.__DEV__ = process.env.DEV ? JSON.parse(process.env.DEV) : true;
global.React = require('react');
global.ReactDOM = require('react-dom');
global.expect = chai.expect;
global.TestUtils = require('react-addons-test-utils');
/*eslint-disable */
//let {shallowRenderer} = TestUtils;
/*eslint-enable */

process.on('unhandledRejection', (error)=>{
    console.error('Unhandled Promise Rejection:');
    console.error(error && error.stack || error);
});
console.log('Test: bootload done');
<|endoftext|>


<commit_before>var vs=require("./validateselection");
var vsmilestone=require("./validatemilestone");
var mark=require("./mark");
var docfilestore=require("../stores/docfile");
var markupstore=require("../stores/markup");

var isIntertextDeletable=function(markup) {
	var file=markup.target[0];
	if (Array.isArray(file)) {
		for (var i in markup.target) {
			var m=markup.target[i];
			if (!docfilestore.docOf(m[0]))return false;
		}
		return true;
	} else {
		return !!docfilestore.docOf(file);
	}
}

var deletIntertext=function(markup) {

	var file=markup.target[0];
	if (Array.isArray(markup.target[0])) {
		for (var i in markup.target) {
			var m=markup.target[i];
			markupstore.removeByMid(m[1],m[0]);
		}
	} else {
		markupstore.removeByMid(markup.target[1],markup.target[0]);
	}
}

var types={

	"important":{validate:vs.singleone,label:"重點",
							editor:require("./simple"), mark:mark.singleone}
	,"title":{validate:vs.singleone,label:"大標",editor:require("./simple"),mark:mark.singleone}
	,"dictionary":{validate:vs.singleone,label:"字典"}
	,"partofspeech":{validate:vs.singleone,label:"詞性"}
	,"intertext":{validate:vs.multi,label:"互文", mark:mark.dualone, editor:require("./quote"),
						isDeletable: isIntertextDeletable,onDelete:deletIntertext}
	,"quote":{validate:vs.dualone,label:"出處", mark:mark.oneway, editor:require("./quote")}
  ,"causeeffect":{validate:vs.singletwo,label:"因果",mark:mark.singletwo,editor:require("./simple")}
  ,"historyculture":{validate:vs.singletwomore,label:"歷史文化",mark:mark.singletwo,editor:require("./simple")}
  ,"part":{validate:vs.singletwomore,label:"部份",mark:mark.singletwo,editor:require("./simple")}
  ,"individual":{validate:vs.singletwomore,label:"總別",mark:mark.singletwo,editor:require("./simple")}
  ,"synonym":{validate:vs.singletwomore,label:"同義",mark:mark.singletwo,editor:require("./simple")}
  ,"signifier":{validate:vs.singletwo,label:"能所",mark:mark.singletwo,editor:require("./simple")}
  ,"extsignifier":{validate:vs.dualone,label:"能所",mark:mark.dualone,editor:require("./simple"),
		isDeletable: isIntertextDeletable,onDelete:deletIntertext}

  ,"ritual":{validate:vs.singletwo,label:"儀軌",mark:mark.singletwo,editor:require("./simple")}
  ,"extritual":{validate:vs.dualone,label:"儀軌",mark:mark.dualone,editor:require("./simple"),
		isDeletable: isIntertextDeletable,onDelete:deletIntertext}

  ,"authorbg":{validate:vs.singletwo,label:"作者背景",mark:mark.singletwo,editor:require("./simple")}
  ,"extauthorbg":{validate:vs.dualone,label:"作者背景",mark:mark.dualone,editor:require("./simple"),
		isDeletable: isIntertextDeletable,onDelete:deletIntertext}

	,"milestone":{validate:vsmilestone.milestone,label:"界石",editor:require("./simple"), mark:mark.milestone}
	,"explaination":{validate:vs.singletwomore,label:"創見",mark:mark.singletwo,editor:require("./simple")}
	,"definition":{validate:vs.singletwomore,label:"內釋",mark:mark.singletwo,editor:require("./simple")}
	,"extdefinition":{validate:vs.dualonemore,label:"外釋",mark:mark.dualonemore,editor:require("./simple"),
		isDeletable: isIntertextDeletable,onDelete:deletIntertext}
	,"causeeffect2":{label:"果：",hidden:true}
	,"intertext2":{label:"互文：",hidden:true}
	,"part2":{label:"部份：",hidden:true}
	,"signifier2":{label:"所指：",hidden:true}
	,"synonym2":{label:"同義詞",hidden:true}
  ,"definition2"	:{label:"定義：",hidden:true}
  ,"extdefinition2"	:{label:"定義：",hidden:true}
  ,"explaination2"	:{label:"說明：",hidden:true}
  ,"extsignifier2"	:{label:"所指：",hidden:true}
  ,"historyculture2"	:{label:"歷史文化：",hidden:true}
  ,"individual2":{label:"別相：",hidden:true}
  ,"ritual2":{label:"儀軌：",hidden:true}
  ,"extritual2":{label:"儀軌：",hidden:true}
  ,"authorbg2":{label:"作者背景：",hidden:true}
  ,"extauthorbg2":{label:"作者背景：",hidden:true}
}

var getAvailableType=function(selections) {
	var out=[];
	for (var i in types) {
		if (types[i].validate && types[i].validate(selections) && !types[i].hidden){
			out.push(i);
		}
	}
	return out;
}
module.exports={getAvailableType:getAvailableType, types:types,
	milestone_novalidate:mark.milestone_novalidate};<commit_msg>rename explanation to insight<commit_after>var vs=require("./validateselection");
var vsmilestone=require("./validatemilestone");
var mark=require("./mark");
var docfilestore=require("../stores/docfile");
var markupstore=require("../stores/markup");

var isIntertextDeletable=function(markup) {
	var file=markup.target[0];
	if (Array.isArray(file)) {
		for (var i in markup.target) {
			var m=markup.target[i];
			if (!docfilestore.docOf(m[0]))return false;
		}
		return true;
	} else {
		return !!docfilestore.docOf(file);
	}
}

var deletIntertext=function(markup) {

	var file=markup.target[0];
	if (Array.isArray(markup.target[0])) {
		for (var i in markup.target) {
			var m=markup.target[i];
			markupstore.removeByMid(m[1],m[0]);
		}
	} else {
		markupstore.removeByMid(markup.target[1],markup.target[0]);
	}
}

var types={
	"important":{validate:vs.singleone,label:"重點",
							editor:require("./simple"), mark:mark.singleone}
	,"explaination":{validate:vs.singleone,label:"創見",mark:mark.singleone,editor:require("./simple")}
	,"intertext":{validate:vs.multi,label:"互文", mark:mark.dualone, editor:require("./quote"),
						isDeletable: isIntertextDeletable,onDelete:deletIntertext}
	,"quote":{validate:vs.dualone,label:"出處", mark:mark.oneway, editor:require("./quote")}
  ,"causeeffect":{validate:vs.singletwo,label:"因果",mark:mark.singletwo,editor:require("./simple")}
  ,"historyculture":{validate:vs.singletwomore,label:"歷史文化",mark:mark.singletwo,editor:require("./simple")}
  ,"part":{validate:vs.singletwomore,label:"部份",mark:mark.singletwo,editor:require("./simple")}
  ,"individual":{validate:vs.singletwomore,label:"總別",mark:mark.singletwo,editor:require("./simple")}
  ,"synonym":{validate:vs.singletwomore,label:"同義",mark:mark.singletwo,editor:require("./simple")}
  ,"signifier":{validate:vs.singletwo,label:"能所",mark:mark.singletwo,editor:require("./simple")}
  ,"extsignifier":{validate:vs.dualone,label:"能所",mark:mark.dualone,editor:require("./simple"),
		isDeletable: isIntertextDeletable,onDelete:deletIntertext}

  ,"ritual":{validate:vs.singletwo,label:"儀軌",mark:mark.singletwo,editor:require("./simple")}
  ,"extritual":{validate:vs.dualone,label:"儀軌",mark:mark.dualone,editor:require("./simple"),
		isDeletable: isIntertextDeletable,onDelete:deletIntertext}

  ,"authorbg":{validate:vs.singletwo,label:"作者背景",mark:mark.singletwo,editor:require("./simple")}
  ,"extauthorbg":{validate:vs.dualone,label:"作者背景",mark:mark.dualone,editor:require("./simple"),
		isDeletable: isIntertextDeletable,onDelete:deletIntertext}

	,"milestone":{validate:vsmilestone.milestone,label:"界石",editor:require("./simple"), mark:mark.milestone}
	,"definition":{validate:vs.singletwomore,label:"內釋",mark:mark.singletwo,editor:require("./simple")}
	,"extdefinition":{validate:vs.dualonemore,label:"外釋",mark:mark.dualonemore,editor:require("./simple"),
		isDeletable: isIntertextDeletable,onDelete:deletIntertext}
	,"causeeffect2":{label:"果：",hidden:true}
	,"intertext2":{label:"互文：",hidden:true}
	,"part2":{label:"部份：",hidden:true}
	,"signifier2":{label:"所指：",hidden:true}
	,"synonym2":{label:"同義詞",hidden:true}
  ,"definition2"	:{label:"定義：",hidden:true}
  ,"extdefinition2"	:{label:"定義：",hidden:true}
  ,"extsignifier2"	:{label:"所指：",hidden:true}
  ,"historyculture2"	:{label:"歷史文化：",hidden:true}
  ,"individual2":{label:"別相：",hidden:true}
  ,"ritual2":{label:"儀軌：",hidden:true}
  ,"extritual2":{label:"儀軌：",hidden:true}
  ,"authorbg2":{label:"作者背景：",hidden:true}
  ,"extauthorbg2":{label:"作者背景：",hidden:true}
}

var getAvailableType=function(selections) {
	var out=[];
	for (var i in types) {
		if (types[i].validate && types[i].validate(selections) && !types[i].hidden){
			out.push(i);
		}
	}
	return out;
}
module.exports={getAvailableType:getAvailableType, types:types,
	milestone_novalidate:mark.milestone_novalidate};<|endoftext|>