<commit_before>import {typeFormatChoices, enumArray} from './types';

const parameterType = {
  'type': 'option',
  'columns': '4',
  'placeholder': 'Type name',
  'format': 'dropdown',
  'choices': ['string', 'integer', 'number', 'boolean', 'array']
};

const toplevelParameterType = JSON.parse(JSON.stringify(parameterType));
toplevelParameterType.conditions = {
  '../in': ['path', 'query', 'header', 'formData']
};
toplevelParameterType.choices.push({
  'key': 'file',
  'conditions': {
    '../in': 'formData'
  }
});

const parameterFormat = {
  'type': 'option',
  'format': 'dropdown',
  'choices': typeFormatChoices,
  'i18n': {
    'path': 'form.types.item.format'
  }
};

const toplevelParameterFormat = JSON.parse(JSON.stringify(parameterFormat));
toplevelParameterFormat.conditions = {
  '../in': ['path', 'query', 'header', 'formData']
};

const parameterCollectionFormat = {
  'type': 'option',
  'format': 'dropdown',
  'label': 'Collection format',
  'choices': ['csv', 'ssv', 'tsv', 'pipes'],
  'conditions': {
    '../type': 'array'
  }
};

const toplevelParameterCollectionFormat = JSON.parse(JSON.stringify(parameterCollectionFormat));
toplevelParameterCollectionFormat.conditions['../type'] = 'array';
toplevelParameterCollectionFormat.choices.push({
  'key': 'multi',
  'label': 'Parameter separation (foo=bar&foo=baz)',
  'conditions': [
    '../in': ['query', 'formData']
  ]
});

export const parameterItemDefinition = {
  'type': 'object',
  'Path': 'form.parameter',
  'i18n': {
    'keys': {
      'label': 'form.parameter.parameter.items.label'
    }
  },
  'hideValueIfEmpty': false,
  'children': {
    'type': parameterType,
    'format': parameterFormat,
    'collectionFormat': parameterCollectionFormat,
    'items': {
      'type': 'lazylink',
      'target': '/parameter-item-definition',
      'conditions': {
        '../type': 'array'
      }
    }
  }
};

const toplevelParameterItemDefinition = Object.assign({}, parameterItemDefinition);
toplevelParameterItemDefinition.conditions = {
  '../in': ['path', 'query', 'header', 'formData'],
  '../type': 'array'
};

const enumIfNotInBody = Object.assign({}, enumArray);
enumIfNotInBody.conditions = {
  '../in': ['path', 'query', 'header', 'formData']
};

export const parameter = {
  'type': 'selectable',
  'i18n': {
    'path': 'form.parameter',
    'interpolations': {
      'name': '${#/:child/name}'
    }
  },
  'setValueListeners': [
    (field, newValue) =>
      field.setType(newValue.hasOwnProperty('$ref') ? 'reference' : 'parameter')
  ],
  'types': {
    'parameter': {
      'i18n': {
        'path': 'form.parameter'
      },
      'setValueListeners': [
        (field, newValue) => {
          if (newValue.hasOwnProperty('in')) {
            field.children.in.setValue(newValue.in);
          }
        }
      ],
      'type': 'object',
      'children': {
        'name': {
          'type': 'text',
          'hideValueIfEmpty': false,
          'validation': ['required']
        },
        'in': {
          'type': 'option',
          'format': 'dropdown',
          'label': 'Location',
          'choices': ['path', 'query', 'header', 'formData', 'body'],
          'hideValueIfEmpty': false
        },
        'description': {
          'type': 'textarea'
        },
        'required': {
          'type': 'option',
          'format': 'checkbox'
        },
        'schema': {
          'type': 'lazylink',
          'target': '/global-definitions/types/:item',
          'overrides': {
            'labelFormat': 'Body schema',
            'legendChildren/name': null,
            'legendChildren/x-oad-type/columns': 8
          },
          'hideValueIfEmpty': false,
          'conditions': {
            '../in': 'body'
          }
        },
        'allowEmptyValue': {
          'type': 'option',
          'format': 'checkbox',
          'label': 'Allow empty value?',
          'conditions': {
            '../in': ['path', 'query', 'header', 'formData']
          }
        },
        'type': toplevelParameterType,
        'format': toplevelParameterFormat,
        'collectionFormat': toplevelParameterCollectionFormat,
        'items': toplevelParameterItemDefinition,
        'enum': enumIfNotInBody
      }
    },
    'reference': {
      'type': 'object',
      'i18n': {
        'path': 'form.parameter'
      },
      'children': {
        '$ref': {
          'type': 'option',
          'format': 'dropdown',
          'label': 'Target',
          'hideIfNoChoices': false,
          'choices': [{
            'key': '',
            'i18nKey': 'choose'
          }],
          'validation': ['required'],
          'dataSources': [{
            'source': '/global-definitions/parameters',
            'key': '#/parameters/${#:key}',
            'label': 'Parameter ${#:key}'
          }]
        }
      }
    }
  }
};

export const namedParameter = $.extend(true, {}, parameter);
namedParameter.keyKey = 'paramName';
namedParameter.keyPlaceholder = 'Enter name...';
namedParameter.i18n.interpolations = {
  'name': '${#:key}'
};
namedParameter.i18n.keys = {
  'label': 'form.global-definitions.parameters.item.label'
};
namedParameter.validation = ['noDuplicateKeys', 'keyRequired'];

export const parameters = {
  'type': 'array',
  'format': 'map',
  'collapseManagement': true,
  'isCollapsible': false,
  'addIndexToChildLabel': false,
  'keyField': 'paramName',
  'newItemText': 'New Parameter',
  'item': namedParameter
};
<commit_msg>Make parameter format half-width<commit_after>import {typeFormatChoices, enumArray} from './types';

const parameterType = {
  'type': 'option',
  'columns': '4',
  'placeholder': 'Type name',
  'format': 'dropdown',
  'choices': ['string', 'integer', 'number', 'boolean', 'array']
};

const toplevelParameterType = JSON.parse(JSON.stringify(parameterType));
toplevelParameterType.conditions = {
  '../in': ['path', 'query', 'header', 'formData']
};
toplevelParameterType.choices.push({
  'key': 'file',
  'conditions': {
    '../in': 'formData'
  }
});

const parameterFormat = {
  'type': 'option',
  'format': 'dropdown',
  'choices': typeFormatChoices,
  'columns': '4',
  'i18n': {
    'path': 'form.types.item.format'
  }
};

const toplevelParameterFormat = JSON.parse(JSON.stringify(parameterFormat));
toplevelParameterFormat.conditions = {
  '../in': ['path', 'query', 'header', 'formData']
};

const parameterCollectionFormat = {
  'type': 'option',
  'format': 'dropdown',
  'label': 'Collection format',
  'choices': ['csv', 'ssv', 'tsv', 'pipes'],
  'conditions': {
    '../type': 'array'
  }
};

const toplevelParameterCollectionFormat = JSON.parse(JSON.stringify(parameterCollectionFormat));
toplevelParameterCollectionFormat.conditions['../type'] = 'array';
toplevelParameterCollectionFormat.choices.push({
  'key': 'multi',
  'label': 'Parameter separation (foo=bar&foo=baz)',
  'conditions': [
    '../in': ['query', 'formData']
  ]
});

export const parameterItemDefinition = {
  'type': 'object',
  'Path': 'form.parameter',
  'i18n': {
    'keys': {
      'label': 'form.parameter.parameter.items.label'
    }
  },
  'hideValueIfEmpty': false,
  'children': {
    'type': parameterType,
    'format': parameterFormat,
    'collectionFormat': parameterCollectionFormat,
    'items': {
      'type': 'lazylink',
      'target': '/parameter-item-definition',
      'conditions': {
        '../type': 'array'
      }
    }
  }
};

const toplevelParameterItemDefinition = Object.assign({}, parameterItemDefinition);
toplevelParameterItemDefinition.conditions = {
  '../in': ['path', 'query', 'header', 'formData'],
  '../type': 'array'
};

const enumIfNotInBody = Object.assign({}, enumArray);
enumIfNotInBody.conditions = {
  '../in': ['path', 'query', 'header', 'formData']
};

export const parameter = {
  'type': 'selectable',
  'i18n': {
    'path': 'form.parameter',
    'interpolations': {
      'name': '${#/:child/name}'
    }
  },
  'setValueListeners': [
    (field, newValue) =>
      field.setType(newValue.hasOwnProperty('$ref') ? 'reference' : 'parameter')
  ],
  'types': {
    'parameter': {
      'i18n': {
        'path': 'form.parameter'
      },
      'setValueListeners': [
        (field, newValue) => {
          if (newValue.hasOwnProperty('in')) {
            field.children.in.setValue(newValue.in);
          }
        }
      ],
      'type': 'object',
      'children': {
        'name': {
          'type': 'text',
          'hideValueIfEmpty': false,
          'validation': ['required']
        },
        'in': {
          'type': 'option',
          'format': 'dropdown',
          'label': 'Location',
          'choices': ['path', 'query', 'header', 'formData', 'body'],
          'hideValueIfEmpty': false
        },
        'description': {
          'type': 'textarea'
        },
        'required': {
          'type': 'option',
          'format': 'checkbox'
        },
        'schema': {
          'type': 'lazylink',
          'target': '/global-definitions/types/:item',
          'overrides': {
            'labelFormat': 'Body schema',
            'legendChildren/name': null,
            'legendChildren/x-oad-type/columns': 8
          },
          'hideValueIfEmpty': false,
          'conditions': {
            '../in': 'body'
          }
        },
        'allowEmptyValue': {
          'type': 'option',
          'format': 'checkbox',
          'label': 'Allow empty value?',
          'conditions': {
            '../in': ['path', 'query', 'header', 'formData']
          }
        },
        'type': toplevelParameterType,
        'format': toplevelParameterFormat,
        'collectionFormat': toplevelParameterCollectionFormat,
        'items': toplevelParameterItemDefinition,
        'enum': enumIfNotInBody
      }
    },
    'reference': {
      'type': 'object',
      'i18n': {
        'path': 'form.parameter'
      },
      'children': {
        '$ref': {
          'type': 'option',
          'format': 'dropdown',
          'label': 'Target',
          'hideIfNoChoices': false,
          'choices': [{
            'key': '',
            'i18nKey': 'choose'
          }],
          'validation': ['required'],
          'dataSources': [{
            'source': '/global-definitions/parameters',
            'key': '#/parameters/${#:key}',
            'label': 'Parameter ${#:key}'
          }]
        }
      }
    }
  }
};

export const namedParameter = $.extend(true, {}, parameter);
namedParameter.keyKey = 'paramName';
namedParameter.keyPlaceholder = 'Enter name...';
namedParameter.i18n.interpolations = {
  'name': '${#:key}'
};
namedParameter.i18n.keys = {
  'label': 'form.global-definitions.parameters.item.label'
};
namedParameter.validation = ['noDuplicateKeys', 'keyRequired'];

export const parameters = {
  'type': 'array',
  'format': 'map',
  'collapseManagement': true,
  'isCollapsible': false,
  'addIndexToChildLabel': false,
  'keyField': 'paramName',
  'newItemText': 'New Parameter',
  'item': namedParameter
};
<|endoftext|>


<commit_before>// Global Modules
import 'es6-module-loader';

// Test Modules
import { expect, assert } from      'chai';
import simple, { mock } from        'simple-mock';

// System Modules
import fs from                      'fs';
import $LogProvider from            'angie-log';

// Angie Modules
import { Angie } from               '../../src/Angie';
import {
    $$InvalidDirectiveConfigError,
    $$InvalidServiceConfigError,
    $$InvalidFactoryConfigError
} from                              '../../src/util/$ExceptionsProvider';

const CWD = process.cwd();

describe('Angie', function() {
    let noop = () => undefined,
        app;

    beforeEach(function() {
        app = new Angie();
    });
    describe('constructor', function() {
        it('test constructor properly instantiates app properties', function() {
            expect(app.constants).to.deep.eq({});
            expect(app.configs).to.deep.eq([]);
            expect(app.services).to.deep.eq({});
            expect(app.Controllers).to.deep.eq({});
            expect(app.directives).to.deep.eq({});
            expect(app.$$registry).to.deep.eq({});
            expect(app.$dependencies).to.deep.eq([]);
        });
    });
    describe('$$register', function() {
        beforeEach(function() {
            mock($LogProvider, 'warn', noop);
        });
        it('test $register returns the app object', function() {
            expect(app.$$register()).to.deep.eq(app);
        });
        it('test $register called without a name fails', function() {
            app.$$register('directives', null, {});
            expect(app.$$registry).to.deep.eq({});
            expect(app.directives).to.deep.eq({});
            expect($LogProvider.warn).to.have.been.called;
        });
        it('test $register called without an obj fails', function() {
            app.$$register('directives', 'test', null);
            expect(app.$$registry).to.deep.eq({});
            expect(app.directives).to.deep.eq({});
            expect($LogProvider.warn).to.have.been.called;
        });
        it('test $register properly $registers a provider', function() {
            app.$$register('directives', 'test', 'test');
            expect(app.$$registry.test).to.eq('directives');
            expect(app.directives.test).to.deep.eq('test');
        });
    });
    describe('directive', function() {
        beforeEach(function() {
            mock(app, '$$register', noop);
        });
        it('test Controller and string type', function() {
            let obj = {
                Controller: 'test'
            };
            app.directive('test', function() {
                return obj;
            });
            expect(app.$$register.calls[0].args).to.deep.eq(
                [ 'directives', 'test', obj ]
            );
        });
        it('test Controller deleted if not string type', function() {
            let obj = {
                Controller: noop()
            };
            app.directive('test', function() {
                return obj;
            });
            expect(app.$$register.calls[0].args).to.deep.eq(
                [ 'directives', 'test', obj ]
            );
            expect(obj.Controller).to.be.undefined;
        });
        it(
            'test $ExceptionsProvider called when there is a not controller and ' +
            'directive is an API View',
            function() {
                expect(app.directive.bind(null, 'test', function() {
                    return {
                        type: 'APIView'
                    };
                })).to.throw($$InvalidDirectiveConfigError);
            }
        );
    });
    describe('constant, service, factory, Controller', function() {
        beforeEach(function() {
            mock(app, '$$register', noop);
        });
        it('test constant makes a call to $$register', function() {
            app.constant('test', 'test');
            expect(app.$$register.calls[0].args).to.deep.eq([
                'constants',
                'test',
                'test'
            ]);
        });
        describe('test service makes a call to $$register', function() {
            it('test object', function() {
                app.service('test', { test: 'test' });
                expect(app.$$register.calls[0].args).to.deep.eq([
                    'services',
                    'test',
                    { test: 'test' }
                ]);
            });
            it('test function', function() {
                expect(
                    app.service.bind(null, 'test', function test() {})
                ).to.throw($$InvalidServiceConfigError);
            });
            it('test string', function() {
                expect(
                    app.service.bind(null, 'test', 'test')
                ).to.throw($$InvalidServiceConfigError);
            });
        });
        describe('test factory makes a call to $$register', function() {
            it('test object', function() {
                expect(
                    app.factory.bind(null, 'test', { test: 'test' })
                ).to.throw($$InvalidFactoryConfigError);
            });
            it('test function', function() {
                let test = function() {};
                app.factory('test', test);
                expect(app.$$register.calls[0].args).to.deep.eq([
                    'factories',
                    'test',
                    test
                ]);
            });
            it('test string', function() {
                expect(
                    app.factory.bind(null, 'test', 'test')
                ).to.throw($$InvalidFactoryConfigError);
            });
        });
        it(
            'test Controller throws an error if not called with a function',
            function() {
                expect(app.Controller.bind(null, 'test', 'test')).to.throw();
            }
        );
        it('test Controller makes a call to $$register', function() {
            app.Controller('test', noop);
            expect(app.$$register.calls[0].args).to.deep.eq([
                'Controllers',
                'test',
                noop
            ]);
        });
        it('test controller makes a call to $$register', function() {
            app.controller('test', noop);
            expect(app.$$register.calls[0].args).to.deep.eq([
                'Controllers',
                'test',
                noop
            ]);
        });
    });
    describe('config', function() {
        beforeEach(function() {
            mock($LogProvider, 'warn', noop);
        });
        it('test config returns app', function() {
            expect(app.config()).to.deep.eq(app);
        });
        it('test config not added as string', function() {
            app.config('test');
            expect(app.configs).to.deep.eq([]);
            expect($LogProvider.warn).to.have.been.called;
        });
        it('test config added when called with function', function() {
            app.config(noop);
            expect(app.configs[0]).to.deep.eq({
                fn: noop
            });
            expect($LogProvider.warn).to.not.have.been.called;
        });
    });
    describe('$$tearDown', function() {
        beforeEach(function() {
            app.service('test', {});
        });
        it('test called with no name does nothing', function() {
            expect(app.$$tearDown()).to.deep.eq(app);
            expect(app.$$registry.test).to.eq('services');
            expect(app.services.test).to.deep.eq({});
        });
        it('test called with an improper service name', function() {
            expect(app.$$tearDown('test2')).to.deep.eq(app);
            expect(app.$$registry.test).to.eq('services');
            expect(app.services.test).to.deep.eq({});
        });
        it('test called with a proper service name', function() {
            expect(app.$$tearDown('test')).to.deep.eq(app);
            expect(app.$$registry.test).to.be.undefined;
            expect(app.service.test).to.be.undefined;
        });
        it('test called with many arguments', function() {
            app.service('test2', {});
            expect(app.$$tearDown('test', 'test2')).to.deep.eq(app);

            expect(app.$$registry.test).to.be.undefined;
            expect(app.service.test).to.be.undefined;

            expect(app.$$registry.test1).to.be.undefined;
            expect(app.service.test1).to.be.undefined;
        });
        it('test called with an array argument', function() {
            app.service('test2', {});
            expect(app.$$tearDown([ 'test', 'test2' ])).to.deep.eq(app);

            expect(app.$$registry.test).to.be.undefined;
            expect(app.service.test).to.be.undefined;

            expect(app.$$registry.test1).to.be.undefined;
            expect(app.service.test1).to.be.undefined;
        });
    });
    describe('$$loadDependencies', function() {
        beforeEach(function() {
            mock(fs, 'readFileSync', () => '{ "test": "test" }');
            mock($LogProvider, 'error', noop);
            mock(app, '$$bootstrap', () => new Promise());
        });
        afterEach(() => simple.restore());
        it('test called with no dependencies', function() {
            expect(app.$$loadDependencies().val).to.deep.eq([]);
        });
        it('test called with dependencies', function() {
            expect(app.$$loadDependencies([ 'test' ]).val.length).to.eq(1);
            assert(fs.readFileSync.called);
            expect(app.$$bootstrap).to.have.been.called;
        });
        it('test invalid JSON in AngieFile', function() {
            fs.readFileSync = () => '{,}';
            app.$$loadDependencies([ 'test' ]);
            expect($LogProvider.error).to.have.been.called;
            expect(app.$$bootstrap).to.not.have.been.called;
        });
    });
    describe('$$bootstrap', function() {
        let spy;

        beforeEach(function() {
            mock(fs, 'readdirSync', () => [ 'test' ]);
            mock(System, 'import', (v) => v);
            simple.mock(Promise, 'all');
            spy = simple.spy();
            app.configs = [
                {
                    fn: spy
                }
            ];
        });
        afterEach(() => simple.restore());
        xit('test $$bootstrap with node_modules', function() {
            fs.readdirSync.returnWith([ 'node_modules' ]);
            app.$$bootstrap();
            expect(System.import).to.not.have.been.called;
            expect(Promise.all.calls[0].args[0]).to.deep.eq([]);
            expect(spy).to.have.been.called;
            expect(app.configs).to.deep.eq([]);
        });
        xit('test $$bootstrap with non-js files', function() {
            app.$$bootstrap();
            expect(System.import).to.not.have.been.called;
            expect(Promise.all.calls[0].args[0]).to.deep.eq([]);
            expect(spy).to.have.been.called;
        });
        xit('test $$bootstrap', function() {
            fs.readdirSync.returnWith([ 'test.js' ]);
            expect(app.$$bootstrap().val).to.be.true;
            expect(System.import).to.have.been.called;
            expect(spy).to.have.been.called;
            expect(app.configs).to.deep.eq([]);
        });
    });
});<commit_msg>Added fixes for tests<commit_after>// Test Modules
import { expect, assert } from      'chai';
import simple, { mock } from        'simple-mock';

// System Modules
import fs from                      'fs';
import $LogProvider from            'angie-log';

// Angie Modules
import { Angie } from               '../../src/Angie';
import {
    $$InvalidDirectiveConfigError,
    $$InvalidServiceConfigError,
    $$InvalidFactoryConfigError
} from                              '../../src/util/$ExceptionsProvider';

const CWD = process.cwd();

describe('Angie', function() {
    let noop = () => undefined,
        app;

    beforeEach(function() {
        app = new Angie();
    });
    describe('constructor', function() {
        it('test constructor properly instantiates app properties', function() {
            expect(app.constants).to.deep.eq({});
            expect(app.configs).to.deep.eq([]);
            expect(app.services).to.deep.eq({});
            expect(app.Controllers).to.deep.eq({});
            expect(app.directives).to.deep.eq({});
            expect(app.$$registry).to.deep.eq({});
            expect(app.$dependencies).to.deep.eq([]);
        });
    });
    describe('$$register', function() {
        beforeEach(function() {
            mock($LogProvider, 'warn', noop);
        });
        it('test $register returns the app object', function() {
            expect(app.$$register()).to.deep.eq(app);
        });
        it('test $register called without a name fails', function() {
            app.$$register('directives', null, {});
            expect(app.$$registry).to.deep.eq({});
            expect(app.directives).to.deep.eq({});
            expect($LogProvider.warn).to.have.been.called;
        });
        it('test $register called without an obj fails', function() {
            app.$$register('directives', 'test', null);
            expect(app.$$registry).to.deep.eq({});
            expect(app.directives).to.deep.eq({});
            expect($LogProvider.warn).to.have.been.called;
        });
        it('test $register properly $registers a provider', function() {
            app.$$register('directives', 'test', 'test');
            expect(app.$$registry.test).to.eq('directives');
            expect(app.directives.test).to.deep.eq('test');
        });
    });
    describe('directive', function() {
        beforeEach(function() {
            mock(app, '$$register', noop);
        });
        it('test Controller and string type', function() {
            let obj = {
                Controller: 'test'
            };
            app.directive('test', function() {
                return obj;
            });
            expect(app.$$register.calls[0].args).to.deep.eq(
                [ 'directives', 'test', obj ]
            );
        });
        it('test Controller deleted if not string type', function() {
            let obj = {
                Controller: noop()
            };
            app.directive('test', function() {
                return obj;
            });
            expect(app.$$register.calls[0].args).to.deep.eq(
                [ 'directives', 'test', obj ]
            );
            expect(obj.Controller).to.be.undefined;
        });
        it(
            'test $ExceptionsProvider called when there is a not controller and ' +
            'directive is an API View',
            function() {
                expect(app.directive.bind(null, 'test', function() {
                    return {
                        type: 'APIView'
                    };
                })).to.throw($$InvalidDirectiveConfigError);
            }
        );
    });
    describe('constant, service, factory, Controller', function() {
        beforeEach(function() {
            mock(app, '$$register', noop);
        });
        it('test constant makes a call to $$register', function() {
            app.constant('test', 'test');
            expect(app.$$register.calls[0].args).to.deep.eq([
                'constants',
                'test',
                'test'
            ]);
        });
        describe('test service makes a call to $$register', function() {
            it('test object', function() {
                app.service('test', { test: 'test' });
                expect(app.$$register.calls[0].args).to.deep.eq([
                    'services',
                    'test',
                    { test: 'test' }
                ]);
            });
            it('test function', function() {
                expect(
                    app.service.bind(null, 'test', function test() {})
                ).to.throw($$InvalidServiceConfigError);
            });
            it('test string', function() {
                expect(
                    app.service.bind(null, 'test', 'test')
                ).to.throw($$InvalidServiceConfigError);
            });
        });
        describe('test factory makes a call to $$register', function() {
            it('test object', function() {
                expect(
                    app.factory.bind(null, 'test', { test: 'test' })
                ).to.throw($$InvalidFactoryConfigError);
            });
            it('test function', function() {
                let test = function() {};
                app.factory('test', test);
                expect(app.$$register.calls[0].args).to.deep.eq([
                    'factories',
                    'test',
                    test
                ]);
            });
            it('test string', function() {
                expect(
                    app.factory.bind(null, 'test', 'test')
                ).to.throw($$InvalidFactoryConfigError);
            });
        });
        it(
            'test Controller throws an error if not called with a function',
            function() {
                expect(app.Controller.bind(null, 'test', 'test')).to.throw();
            }
        );
        it('test Controller makes a call to $$register', function() {
            app.Controller('test', noop);
            expect(app.$$register.calls[0].args).to.deep.eq([
                'Controllers',
                'test',
                noop
            ]);
        });
        it('test controller makes a call to $$register', function() {
            app.controller('test', noop);
            expect(app.$$register.calls[0].args).to.deep.eq([
                'Controllers',
                'test',
                noop
            ]);
        });
    });
    describe('config', function() {
        beforeEach(function() {
            mock($LogProvider, 'warn', noop);
        });
        it('test config returns app', function() {
            expect(app.config()).to.deep.eq(app);
        });
        it('test config not added as string', function() {
            app.config('test');
            expect(app.configs).to.deep.eq([]);
            expect($LogProvider.warn).to.have.been.called;
        });
        it('test config added when called with function', function() {
            app.config(noop);
            expect(app.configs[0]).to.deep.eq({
                fn: noop
            });
            expect($LogProvider.warn).to.not.have.been.called;
        });
    });
    describe('$$tearDown', function() {
        beforeEach(function() {
            app.service('test', {});
        });
        it('test called with no name does nothing', function() {
            expect(app.$$tearDown()).to.deep.eq(app);
            expect(app.$$registry.test).to.eq('services');
            expect(app.services.test).to.deep.eq({});
        });
        it('test called with an improper service name', function() {
            expect(app.$$tearDown('test2')).to.deep.eq(app);
            expect(app.$$registry.test).to.eq('services');
            expect(app.services.test).to.deep.eq({});
        });
        it('test called with a proper service name', function() {
            expect(app.$$tearDown('test')).to.deep.eq(app);
            expect(app.$$registry.test).to.be.undefined;
            expect(app.service.test).to.be.undefined;
        });
        it('test called with many arguments', function() {
            app.service('test2', {});
            expect(app.$$tearDown('test', 'test2')).to.deep.eq(app);

            expect(app.$$registry.test).to.be.undefined;
            expect(app.service.test).to.be.undefined;

            expect(app.$$registry.test1).to.be.undefined;
            expect(app.service.test1).to.be.undefined;
        });
        it('test called with an array argument', function() {
            app.service('test2', {});
            expect(app.$$tearDown([ 'test', 'test2' ])).to.deep.eq(app);

            expect(app.$$registry.test).to.be.undefined;
            expect(app.service.test).to.be.undefined;

            expect(app.$$registry.test1).to.be.undefined;
            expect(app.service.test1).to.be.undefined;
        });
    });
    describe('$$loadDependencies', function() {
        beforeEach(function() {
            mock(fs, 'readFileSync', () => '{ "test": "test" }');
            mock($LogProvider, 'error', noop);
            mock(app, '$$bootstrap', () => new Promise());
        });
        afterEach(() => simple.restore());
        it('test called with no dependencies', function() {
            expect(app.$$loadDependencies().val).to.deep.eq([]);
        });
        it('test called with dependencies', function() {
            expect(app.$$loadDependencies([ 'test' ]).val.length).to.eq(1);
            assert(fs.readFileSync.called);
            expect(app.$$bootstrap).to.have.been.called;
        });
        it('test invalid JSON in AngieFile', function() {
            fs.readFileSync = () => '{,}';
            app.$$loadDependencies([ 'test' ]);
            expect($LogProvider.error).to.have.been.called;
            expect(app.$$bootstrap).to.not.have.been.called;
        });
    });
    describe('$$bootstrap', function() {
        let spy;

        beforeEach(function() {
            mock(fs, 'readdirSync', () => [ 'test' ]);
            simple.mock(Promise, 'all');
            spy = simple.spy();
            app.configs = [
                {
                    fn: spy
                }
            ];
        });
        afterEach(() => simple.restore());
        xit('test $$bootstrap with node_modules', function() {
            fs.readdirSync.returnWith([ 'node_modules' ]);
            app.$$bootstrap();
            expect(Promise.all.calls[0].args[0]).to.deep.eq([]);
            expect(spy).to.have.been.called;
            expect(app.configs).to.deep.eq([]);
        });
        xit('test $$bootstrap with non-js files', function() {
            app.$$bootstrap();
            expect(Promise.all.calls[0].args[0]).to.deep.eq([]);
            expect(spy).to.have.been.called;
        });
        xit('test $$bootstrap', function() {
            fs.readdirSync.returnWith([ 'test.js' ]);
            expect(app.$$bootstrap().val).to.be.true;
            expect(spy).to.have.been.called;
            expect(app.configs).to.deep.eq([]);
        });
    });
});<|endoftext|>


<commit_before>/**
 * This module extracts the walls from a matrix maze with each wall as an
 * object.
 * @module
 */
define([
  'lodash',
], function(_) {
  'use strict';

  var exports = {

    /**
     * @private
     * @param {Array<Array<Object>>} maze
     * @returns {Array<Object>}
     */
    __extractHorizontalWalls: function(maze) {
      var walls = [];
      _.forEach(maze, function(row, rowIndex) {
        // Don't add the sentinel node/cell to the original row
        row = _.clone(row);
        // Add a sentinel cell
        row.push({wall: false});
        var wall;
        _.forEach(row, function(cell, columnIndex) {
          if (cell.wall) {
            // Create an initial wall with width 1
            if (_.isUndefined(wall)) {
              wall = {y: rowIndex, x: columnIndex, height: 1, width: 1};
            }
            // A wall already exists
            else {
              // Increase the wall's width with 1 unit
              ++wall.width;
            }
          } else {
            // A wall has been created and now a floor cell was encountered
            if (!_.isUndefined(wall)) {
              // Put the wall into the collection of walls
              walls.push(wall);
              // Reset the wall variable, making it possible to create a new
              // initial wall when a wall cell is encountered
              wall = undefined;
            }
          }
        });
      });
      return walls;
    },

    /**
     * @private
     * @param {Array<Array<Object>>} maze
     * @returns {Array<Object>}
     */
    __extractVerticalWalls: function(maze) {
      // Don't add the sentinel row to the original maze
      maze = _.clone(maze);
      // Add a sentinel row
      maze.push(_.map(new Array(maze[0].length), function() {
        return {wall: false};
      }));
      var walls = [];
      for (var columnIndex = 0; columnIndex < maze[0].length; ++columnIndex) {
        var wall;
        for (var rowIndex = 0; rowIndex < maze.length; ++rowIndex) {
          var cell = maze[rowIndex][columnIndex];
          if (cell.wall) {
            // Create an initial wall with height 1
            if (_.isUndefined(wall)) {
              wall = {y: rowIndex, x: columnIndex, height: 1, width: 1};
            }
            // A wall already exists
            else {
              // Increase the wall's height with 1 unit
              ++wall.height;
            }
          } else {
            // A wall has been created and now a floor cell was encountered
            if (!_.isUndefined(wall)) {
              // Put the wall into the collection of walls
              walls.push(wall);
              // Reset the wall variable, making it possible to create a new
              // initial wall when a wall cell is encountered
              wall = undefined;
            }
          }
        }
      }
      return walls;
    },

    /**
     * Extract the walls from a matrix maze.
     *
     * @param {Array<Array<Object>>} maze A matrix maze.
     * @returns {Array<Object>} A list of wall objects.
     */
    extractWalls: function(maze) {
      return this.__extractHorizontalWalls(maze).concat(
        this.__extractVerticalWalls(maze)
      );
    },
  };

  return exports;
});
<commit_msg>Improve wallExtractor<commit_after>/**
 * This module extracts the walls from a matrix maze with each wall as an
 * object.
 *
 * @example
 * // Example usage
 * wallExtractor.extract(maze);
 * // Returns:
 * [{height: 1, width: 1, x: 0, y: 6}, {height: 5, width: 1, x: 1, y: 0}, ...]
 *
 * // Where the maze looks like:
 * matrixMaze.printMatrix(maze)
 * -W----##--
 * -W-##---#-
 * -W-##-#---
 * -W---#-#-#
 * -W##-#-#--
 * -----#-##-
 * W-##-#----
 * -#--#--###
 * ---##-##--
 * -#-------#
 * // The two walls from the extract function shown above have been highlighted
 * // with W characters
 *
 * @module
 */
define([
  'lodash',
], function(_) {
  'use strict';

  var exports = {

    /**
     * Add sentinel nodes to the end of the columns and rows.
     *
     *
All of these added nodes are floor nodes and they are put in to make
     * the loops in this module easier to work with. With these sentinel nodes
     * there is no need to handle the last cell in a row or column in a special
     * way.

     *
     * @param {Array.<Array.<Object>>} maze A maze matrix.
     * @param maze.wall {boolean}
     */
    __addSentinelCells: function(maze) {
      // Add a sentinel cell to each row
      _.forEach(maze, function(row) {
        row.push({wall: false});
      });

      // Add a sentinel row
      maze.push(_.map(new Array(maze[0].length), function() {
        return {wall: false};
      }));
    },

    /**
     * Get the horizontal wall starting at (y, x) and as long as possible with
     * increasing x values.
     *
     * @param {Array.<Array.<Object>>} maze A maze matrix.
     * @param maze.wall {boolean}
     * @param {number} y
     * @param {number} x
     * @returns {Array.<Object>} An array of objects with x and y coordinates.
     */
    __getHorizontalWallStrip: function(maze, y, x) {
      var wall = [];
      for (var columnIndex = x; columnIndex < maze[0].length; ++columnIndex) {
        var cell = maze[y][columnIndex];
        if (cell.wall) {
          wall.push({y: y, x: columnIndex});
        } else {
          return wall;
        }
      }
    },

    /**
     * Get the vertical wall starting at (y, x) and as long as possible with
     * increasing y values.
     *
     * @param {Array.<Array.<Object>>} maze A maze matrix.
     * @param maze.wall {boolean}
     * @param {number} y
     * @param {number} x
     * @returns {Array.<Object>} An array of objects with x and y coordinates.
     */
    __getVerticalWallStrip: function(maze, y, x) {
      var wall = [];
      for (var rowIndex = y; rowIndex < maze.length; ++rowIndex) {
        var cell = maze[rowIndex][x];
        if (cell.wall) {
          wall.push({y: rowIndex, x: x});
        } else {
          return wall;
        }
      }
    },

    /**
     * @param {Array.<Array.<Object>>} maze A maze matrix.
     * @param maze.wall {boolean}
     * @param {Array.<Object>} wall An array of wall cells to change to floors.
     * @param wall.x {number}
     * @param wall.y {number}
     */
    __removeWall: function(maze, wall) {
      _.forEach(wall, function(cell) {
        maze[cell.y][cell.x].wall = false;
      });
    },

    /**
     * Extract the walls from a matrix maze.
     *
     * @param {Array<Array<Object>>} maze A matrix maze.
     * @returns {Array<Object>} A list of wall objects with attributes `x`,
     *   `y`, `width` and `height`.
     */
    extract: function(maze) {
      // Make a copy of the maze
      maze = _.clone(maze, true);
      this.__addSentinelCells(maze);

      var walls = [];

      for (var columnIndex = 0; columnIndex < maze[0].length - 1; ++columnIndex) {
        for (var rowIndex = 0; rowIndex < maze.length - 1; ++rowIndex) {
          if (!maze[rowIndex][columnIndex].wall) {
            // Ignore the cell if it's a floor tile
            continue;
          }
          // Get a horizontal wall starting at the current cell
          var horizontalWall = this.__getHorizontalWallStrip(
            maze, rowIndex, columnIndex
          );
          // Get a vertical wall starting at the current cell
          var verticalWall = this.__getVerticalWallStrip(
            maze, rowIndex, columnIndex
          );
          var longestWall;
          if (horizontalWall.length >= verticalWall.length) {
            longestWall = horizontalWall;
            walls.push({
              y: rowIndex,
              x: columnIndex,
              width: longestWall.length,
              height: 1
            });
          } else {
            longestWall = verticalWall;
            walls.push({
              y: rowIndex,
              x: columnIndex,
              width: 1,
              height: longestWall.length
            });
          }
          // Remove the picked wall from the maze so none of its cells are
          // unnecessarily added in multple walls
          this.__removeWall(maze, longestWall);
        }
      }

      return walls;
    },
  };

  return exports;
});
<|endoftext|>


<commit_before>/*
 USAGE (example: line chart)
 1. c+p this template to a new file (line.js)
 2. change puddingChartName to puddingChartLine
 3. in graphic file: import './pudding-chart/line'
 4a. const charts = d3.selectAll('.thing').data(data).puddingChartLine();
 4b. const chart = d3.select('.thing').datum(datum).puddingChartLine();
*/

d3.selection.prototype.puddingChartName = function init(options) {
	function createChart(el) {
		const $sel = d3.select(el);
		let data = $sel.datum();
		// dimension stuff
		let width = 0;
		let height = 0;
		const marginTop = 0;
		const marginBottom = 0;
		const marginLeft = 0;
		const marginRight = 0;

		// scales
		const scaleX = null;
		const scaleY = null;

		// dom elements
		let $svg = null;
		let $axis = null;
		let $vis = null;

		// helper functions

		const Chart = {
			// called once at start
			init() {
				$svg = $sel.append('svg').attr('class', 'pudding-chart');
				const $g = $svg.append('g');

				// offset chart for margins
				$g.attr('transform', `translate(${marginLeft}, ${marginTop})`);

				// create axis
				$axis = $svg.append('g').attr('class', 'g-axis');

				// setup viz group
				$vis = $g.append('g').attr('class', 'g-vis');

				Chart.resize();
				Chart.render();
			},
			// on resize, update new dimensions
			resize() {
				// defaults to grabbing dimensions from container element
				width = $sel.node().offsetWidth - marginLeft - marginRight;
				height = $sel.node().offsetHeight - marginTop - marginBottom;
				$svg
					.attr('width', width + marginLeft + marginRight)
					.attr('height', height + marginTop + marginBottom);
				return Chart;
			},
			// update scales and render chart
			render() {
				return Chart;
			},
			// get / set data
			data(val) {
				if (!arguments.length) return data;
				data = val;
				$sel.datum(data);
				Chart.render();
				return Chart;
			}
		};
		Chart.init();

		return Chart;
	}

	// create charts
	const charts = this.nodes().map(createChart);
	return charts.length > 1 ? charts : charts.pop();
};
<commit_msg>update base pudding chart<commit_after>/*
 USAGE (example: line chart)
 1. c+p this template to a new file (line.js)
 2. change puddingChartName to puddingChartLine
 3. in graphic file: import './pudding-chart/line'
 4a. const charts = d3.selectAll('.thing').data(data).puddingChartLine();
 4b. const chart = d3.select('.thing').datum(datum).puddingChartLine();
*/

d3.selection.prototype.puddingChartName = function init(options) {
  function createChart(el) {
    // dom elements
    const $chart = d3.select(el);
    let $svg = null;
    let $axis = null;
    let $vis = null;

    // data
    let data = $chart.datum();

    // dimensions
    let width = 0;
    let height = 0;
    const MARGIN_TOP = 0;
    const MARGIN_BOTTOM = 0;
    const MARGIN_LEFT = 0;
    const MARGIN_RIGHT = 0;

    // scales
    const scaleX = null;
    const scaleY = null;

    // helper functions

    const Chart = {
      // called once at start
      init() {
        $svg = $chart.append('svg').attr('class', 'pudding-chart');
        const $g = $svg.append('g');

        // offset chart for margins
        $g.attr('transform', `translate(${MARGIN_LEFT}, ${MARGIN_TOP})`);

        // create axis
        $axis = $svg.append('g').attr('class', 'g-axis');

        // setup viz group
        $vis = $g.append('g').attr('class', 'g-vis');
      },
      // on resize, update new dimensions
      resize() {
        // defaults to grabbing dimensions from container element
        width = $chart.node().offsetWidth - MARGIN_LEFT - MARGIN_RIGHT;
        height = $chart.node().offsetHeight - MARGIN_TOP - MARGIN_BOTTOM;
        $svg
          .attr('width', width + MARGIN_LEFT + MARGIN_RIGHT)
          .attr('height', height + MARGIN_TOP + MARGIN_BOTTOM);
        return Chart;
      },
      // update scales and render chart
      render() {
        return Chart;
      },
      // get / set data
      data(val) {
        if (!arguments.length) return data;
        data = val;
        $chart.datum(data);
        return Chart;
      },
    };
    Chart.init();

    return Chart;
  }

  // create charts
  const charts = this.nodes().map(createChart);
  return charts.length > 1 ? charts : charts.pop();
};
<|endoftext|>


<commit_before>// Copyright 2002-2012, University of Colorado

var scenery = scenery || {};

(function(){
  "use strict";

  /*
   * isBefore: whether this points to before the node (and its children) have been rendered, or after
   */
  scenery.TrailPointer = function( trail, isBefore ) {
    this.trail = trail;

    this.isBefore = isBefore;
    this.isAfter = !isBefore;
  };
  var TrailPointer = scenery.TrailPointer;

  TrailPointer.prototype = {
    constructor: TrailPointer,

    // return the equivalent pointer that swaps before and after (may return null if it doesn't exist)
    getSwappedPointer: function() {
      var newTrail = this.isBefore ? this.trail.previous() : this.trail.next();

      if ( newTrail === null ) {
        return null;
      } else {
        return new TrailPointer( newTrail, !this.isBefore );
      }
    }
  };

})();

<commit_msg>Trail pointer comparison<commit_after>// Copyright 2002-2012, University of Colorado

var scenery = scenery || {};

(function(){
  "use strict";

  /*
   * isBefore: whether this points to before the node (and its children) have been rendered, or after
   */
  scenery.TrailPointer = function( trail, isBefore ) {
    this.trail = trail;

    this.isBefore = isBefore;
    this.isAfter = !isBefore;
  };
  var TrailPointer = scenery.TrailPointer;

  TrailPointer.prototype = {
    constructor: TrailPointer,

    // return the equivalent pointer that swaps before and after (may return null if it doesn't exist)
    getSwappedPointer: function() {
      var newTrail = this.isBefore ? this.trail.previous() : this.trail.next();

      if ( newTrail === null ) {
        return null;
      } else {
        return new TrailPointer( newTrail, !this.isBefore );
      }
    },

    getBeforePointer: function() {
      return this.isBefore ? this : this.getSwappedPointer();
    },

    getAfterPointer: function() {
      return this.isAfter ? this : this.getSwappedPointer();
    },

    /*
     * In the render order, will return 0 if the pointers are equivalent, -1 if this pointer is before the
     * other pointer, and 1 if this pointer is after the other pointer.
     */
    compare: function( other ) {
      phet.assert( other !== null );

      var a = this.getBeforePointer();
      var b = other.getBeforePointer();

      if ( a !== null && b !== null ) {
        // normal (non-degenerate) case
        return a.trail.compare( b.trail );
      } else {
        // null "before" point is equivalent to the "after" pointer on the last rendered node.
        if ( a === b ) {
          return 0; // uniqueness guarantees they were the same
        } else {
          return a === null ? 1 : -1;
        }
      }
    },

    eachNodeBetween: function( other, callback ) {
      var comparison = this.trail.compare( other.trail );
    }
  };

})();

<|endoftext|>


<commit_before>import React from 'react';

import SwipeView from './scopes.swipe-view';
import UserList from './scopes.user-list';

class Main extends React.Component {
  render() {
    let chats = [
      {
        id: 1,
        firstName: 'Joshua',
        lastName: 'Torres',
        lastMessage: 'Nam porttitor blandit accu...',
        imageSource: 'http://placehold.it/50x50',
        lastMessageDate: '17:03',
        unreadMessagesLength: 7,
      },
      {
        id: 2,
        firstName: 'Vincent',
        lastName: 'Gray',
        lastMessage: 'Accusamus, ducimus hic qui...',
        imageSource: 'http://placehold.it/50x50',
        lastMessageDate: '17:03',
        unreadMessagesLength: 4,
      },
      {
        id: 3,
        firstName: 'Marthia',
        lastName: 'Diaz',
        lastMessage: 'Cupiditate sit laudantium ...',
        imageSource: 'http://placehold.it/50x50',
        lastMessageDate: '17:03',
        unreadMessagesLength: 2,
      },
    ];

    let contacts = [
      {
        id: 4,
        firstName: 'John',
        lastName: 'Doe',
        description: 'Frontend Developer',
        imageSource: 'http://placehold.it/50x50',
        lastSeenDate: '17:03',
      },
      {
        id: 5,
        firstName: 'Paul',
        lastName: 'Graham',
        description: 'Interaction Designer',
        imageSource: 'http://placehold.it/50x50',
        lastSeenDate: '17:03',
      },
      {
        id: 6,
        firstName: 'Shirley',
        lastName: 'Reid',
        description: 'Backend Developer',
        imageSource: 'http://placehold.it/50x50',
        lastSeenDate: '17:03',
      },
    ];

    return (
      <main className="s-main">
        <SwipeView oneSlidePerSwipe={true}>
          <UserList users={ chats }/>
          <UserList users={ contacts }/>
          <UserList users={ chats }/>
        </SwipeView>
      </main>
    );
  }
}

export default Main;
<commit_msg>remove duplicate list used for example<commit_after>import React from 'react';

import SwipeView from './scopes.swipe-view';
import UserList from './scopes.user-list';

class Main extends React.Component {
  render() {
    let chats = [
      {
        id: 1,
        firstName: 'Joshua',
        lastName: 'Torres',
        lastMessage: 'Nam porttitor blandit accu...',
        imageSource: 'http://placehold.it/50x50',
        lastMessageDate: '17:03',
        unreadMessagesLength: 7,
      },
      {
        id: 2,
        firstName: 'Vincent',
        lastName: 'Gray',
        lastMessage: 'Accusamus, ducimus hic qui...',
        imageSource: 'http://placehold.it/50x50',
        lastMessageDate: '17:03',
        unreadMessagesLength: 4,
      },
      {
        id: 3,
        firstName: 'Marthia',
        lastName: 'Diaz',
        lastMessage: 'Cupiditate sit laudantium ...',
        imageSource: 'http://placehold.it/50x50',
        lastMessageDate: '17:03',
        unreadMessagesLength: 2,
      },
    ];

    let contacts = [
      {
        id: 4,
        firstName: 'John',
        lastName: 'Doe',
        description: 'Frontend Developer',
        imageSource: 'http://placehold.it/50x50',
        lastSeenDate: '17:03',
      },
      {
        id: 5,
        firstName: 'Paul',
        lastName: 'Graham',
        description: 'Interaction Designer',
        imageSource: 'http://placehold.it/50x50',
        lastSeenDate: '17:03',
      },
      {
        id: 6,
        firstName: 'Shirley',
        lastName: 'Reid',
        description: 'Backend Developer',
        imageSource: 'http://placehold.it/50x50',
        lastSeenDate: '17:03',
      },
    ];

    return (
      <main className="s-main">
        <SwipeView oneSlidePerSwipe={true}>
          <UserList users={ chats }/>
          <UserList users={ contacts }/>
        </SwipeView>
      </main>
    );
  }
}

export default Main;
<|endoftext|>


<commit_before>'use strict';

angular.module('users').controller('ChatController', ['$scope','$http',
	function($scope, $http) {

		var bubbles = 1;
        var maxBubbles = 8;
        var server;

        var user = "Mike";
        var customerid = "123";

        $scope.avatar_urlSelf = '/modules/users/img/identicons/Unknown-2.png';
        $scope.avatar_urlOther = '/modules/users/img/identicons/Unknown-3.png';

         $scope.sendMessage = function(msg) {
             alert("Messege sent = " + msg);
             var objToSend =
                {
                    "name" : user,
                    "id" : customerid,
                    "text" : msg
                }

            $http.post('/supportkit/mentormessege', objToSend).
            then(function(response) {
                alert (JSON.stringify(alert));
            }, function(response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                alert("Some sort of error with response");
            });
        }

        function statCtrl($scope) {

                // the last received msg
                $scope.msg = {};

                // handles the callback from the received event
                var handleCallback = function (msg) {
                        alert(JSON.stringify(msg));
                        $scope.$apply(function () {
                                $scope.msg = JSON.parse(msg.data)
                        });
                }

                var source = new EventSource('/supportkit/mentor/message');
                source.addEventListener('message', handleCallback, false);
        }

        var socket = io.connect('http://localhost:3000');
                socket.on('news', function (data) {
                console.log(data);
                socket.emit('my other event', { my: 'data' });
        });

        $scope.addBubble = function(avatar, text) {

            // Get the bytes of the image and convert it to a BASE64 encoded string and then
            // we use data URI to add dynamically the image data
            var avatarUri = "data:image/png;base64," + avatar.toBase64();

            var bubble = $('

' + text + '

');
            $("#msgText").val("");

            $(".bubble-container:last")
                .after(bubble);

            if (bubbles >= maxBubbles) {
                var first = $(".bubble-container:first")
                    .remove();
                bubbles--;
            }

            bubbles++;
            $('.bubble-container').show(250, function showNext() {
                if (!($(this).is(":visible"))) {
                    bubbles++;
                }

                $(this).next(".bubble-container")
                    .show(250, showNext);

                $("#wrapper").scrollTop(9999999);
            });
        }

	}

]);<commit_msg>socket setup client<commit_after>'use strict';

angular.module('users').controller('ChatController', ['$scope','$http',
	function($scope, $http) {

		var bubbles = 1;
        var maxBubbles = 8;
        var server;

        var user = "Mike";
        var customerid = "123";

        $scope.avatar_urlSelf = '/modules/users/img/identicons/Unknown-2.png';
        $scope.avatar_urlOther = '/modules/users/img/identicons/Unknown-3.png';

         $scope.sendMessage = function(msg) {
             alert("Messege sent = " + msg);
             var objToSend =
                {
                    "name" : user,
                    "id" : customerid,
                    "text" : msg
                }

            $http.post('/supportkit/mentormessege', objToSend).
            then(function(response) {
                alert (JSON.stringify(alert));
            }, function(response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                alert("Some sort of error with response");
            });
        }

        function statCtrl($scope) {

                // the last received msg
                $scope.msg = {};

                // handles the callback from the received event
                var handleCallback = function (msg) {
                        alert(JSON.stringify(msg));
                        $scope.$apply(function () {
                                $scope.msg = JSON.parse(msg.data)
                        });
                }

                var source = new EventSource('/supportkit/mentor/message');
                source.addEventListener('message', handleCallback, false);
        }

        var socket = io.connect('http://localhost:3000');
        socket.on('connect', function () {
                socket.emit('mentorinit', { name: 'ZeeSha' });
        });

        $scope.addBubble = function(avatar, text) {

            // Get the bytes of the image and convert it to a BASE64 encoded string and then
            // we use data URI to add dynamically the image data
            var avatarUri = "data:image/png;base64," + avatar.toBase64();

            var bubble = $('

' + text + '

');
            $("#msgText").val("");

            $(".bubble-container:last")
                .after(bubble);

            if (bubbles >= maxBubbles) {
                var first = $(".bubble-container:first")
                    .remove();
                bubbles--;
            }

            bubbles++;
            $('.bubble-container').show(250, function showNext() {
                if (!($(this).is(":visible"))) {
                    bubbles++;
                }

                $(this).next(".bubble-container")
                    .show(250, showNext);

                $("#wrapper").scrollTop(9999999);
            });
        }

	}

]);<|endoftext|>


<commit_before>var t = casper.test,
    baseUrl = casper.baseUrl;

casper.start();

casper
    .describe("Require > Simple View Layout")
    .setup('#foo', function() {
        spf.configure({
            views: {
                foo: 'require/layoutview'
            }
        }).start();
    })
    .then(function() {
        t.assertEval(function() { return spf.app.currentView.name == 'Required Layout' },
            'The correct view class was used');
        t.assertVisible('#layout_1',
            'Layout 1 is visible');
        t.assertVisible('div#custom',
            'Custom div (appended by view) is visible');
    });

casper
    .describe("Require > Layout with slots")
    .setup('#foo', function() {
        spf.configure({
            views: {
                foo: {
                    layout: '#layout_1',
                    slots: {
                        '#slot_1_1': 'require/view1',
                        '#slot_1_2': 'require/view2'
                    }
                },
                bar: {
                    layout: '#layout_2',
                    slots: {
                        '#slot_2_1': 'require/view1',
                        '#slot_2_2': 'require/view2'
                    }
                }
            }
        }).start();
    })
    .then(function() {
        t.assertVisible('#layout_1',
            'Layout 1 is visible');
        t.assertText('#slot_1_1 h2', 'ViewOne',
            'ViewOne slot initialized');
        t.assertText('#slot_1_2 h2', 'ViewTwo',
            'ViewTwo slot initialized');
    })
    .thenOpen(baseUrl + '#bar')
    .then(function() {
        t.assertVisible('#layout_2',
            'Layout 2 is visible');
        t.assertText('#slot_2_1 h2', 'ViewOne',
            'ViewOne slot initialized');
        t.assertText('#slot_2_2 h2', 'ViewTwo',
            'ViewTwo slot initialized');
    });

casper
    .describe("Require > Global views")
    .setup('#foo', function() {
        spf.configure({
            globalViews: ['require/globaltest1'],
            views: {
                'foo': '#layout_1'
            }
        }).start();
    })
    .then(function() {
        t.assertEvalEquals(function() { return spf.app.globals.length }, 1,
            'Globals were initialized');
        t.assertText('#test1', 'GlobalTest1',
            'GlobalTest1 was initialized');
    });

casper.run(function() {
    t.done();
});<commit_msg>Additional test for nested require.js views<commit_after>var t = casper.test,
    baseUrl = casper.baseUrl;

casper.start();

casper
    .describe("Require > Simple View Layout")
    .setup('#foo', function() {
        spf.configure({
            views: {
                foo: 'require/layoutview'
            }
        }).start();
    })
    .then(function() {
        t.assertEval(function() { return spf.app.currentView.name == 'Required Layout' },
            'The correct view class was used');
        t.assertVisible('#layout_1',
            'Layout 1 is visible');
        t.assertVisible('div#custom',
            'Custom div (appended by view) is visible');
    });

casper
    .describe("Require > Layout with slots")
    .setup('#foo', function() {
        spf.configure({
            views: {
                foo: {
                    layout: '#layout_1',
                    slots: {
                        '#slot_1_1': 'require/view1',
                        '#slot_1_2': 'require/view2'
                    }
                },
                bar: {
                    layout: '#layout_2',
                    slots: {
                        '#slot_2_1': 'require/view1',
                        '#slot_2_2': 'require/view2'
                    }
                }
            }
        }).start();
    })
    .then(function() {
        t.assertVisible('#layout_1',
            'Layout 1 is visible');
        t.assertText('#slot_1_1 h2', 'ViewOne',
            'ViewOne slot initialized');
        t.assertText('#slot_1_2 h2', 'ViewTwo',
            'ViewTwo slot initialized');
    })
    .thenOpen(baseUrl + '#bar')
    .then(function() {
        t.assertVisible('#layout_2',
            'Layout 2 is visible');
        t.assertText('#slot_2_1 h2', 'ViewOne',
            'ViewOne slot initialized');
        t.assertText('#slot_2_2 h2', 'ViewTwo',
            'ViewTwo slot initialized');
    });

casper
    .describe("Require > Global views")
    .setup('#foo', function() {
        spf.configure({
            globalViews: ['require/globaltest1'],
            views: {
                'foo': '#layout_1'
            }
        }).start();
    })
    .then(function() {
        t.assertEvalEquals(function() { return spf.app.globals.length }, 1,
            'Globals were initialized');
        t.assertText('#test1', 'GlobalTest1',
            'GlobalTest1 was initialized');
    });

casper
    .describe("Require > Nested Slots in template-based views")
    .setup('#foo', function() {
        spf.configure({
            views: {
                foo: {
                    layout: '#template_2',
                    id: 'foo',
                    slots: {
                        'div.slot1': {
                            layout: '#template_2',
                            slots: {
                                'div.slot1' : 'require/view1'
                            }
                        }
                    }
                }
            }
        }).start();
    })
    .then(function() {
        t.assertAtRoute('#foo', 'foo', 'foo');
        t.assertText('#foo h2', 'Layout Template Test',
            'View foo is using the correct template');
        t.assertText('#foo div.slot1 div > h2', 'Layout Template Test',
            'Slot using the right template');
        t.assertText('#foo div.slot1 div.slot1 h2', 'ViewOne',
            'Nested slot using the ViewOne view');
    });

casper.run(function() {
    t.done();
});<|endoftext|>


<commit_before>'use strict';

const Rollup = require('broccoli-rollup');
const path = require('path');
const existsSync = require('exists-sync');

module.exports = class RollupWithDependencies extends Rollup {
  /*
   Overriding the `build` tree here to allow us to force non-relative imports
   to be evaluated at the top level of the input path.

   So given:

   ```
   input/
   service-a/
   index.js
   other.js
   service-b.js
   ```

   We would resolve the following:

   * `import b from 'service-b';` from `service-a/index.js` would resolve to the top level `service-b`
   * `import a from 'service-a';` from `service-b.js` would resolve to `service-a/index.js`

   */
  build() {
    let plugins = this.rollupOptions.plugins || [];
    let inputPath = this.inputPaths[0];

    plugins.push({
      resolveId(importee, importer) {
        let modulePath = path.join(inputPath, `${importee}.js`);
        if (existsSync(modulePath)) {
          return modulePath;
        }

        // allow service-worker/addon-name/index.js fallback
        modulePath = path.join(inputPath, importee, 'index.js');
        if (existsSync(modulePath)) {
          return modulePath;
        }
      }
    });

    this.rollupOptions.plugins = plugins;

    super.build();
  }
};
<commit_msg>Fix rollup build<commit_after>'use strict';

const Rollup = require('broccoli-rollup');
const path = require('path');
const existsSync = require('exists-sync');

module.exports = class RollupWithDependencies extends Rollup {
  /*
   Overriding the `build` tree here to allow us to force non-relative imports
   to be evaluated at the top level of the input path.

   So given:

   ```
   input/
   service-a/
   index.js
   other.js
   service-b.js
   ```

   We would resolve the following:

   * `import b from 'service-b';` from `service-a/index.js` would resolve to the top level `service-b`
   * `import a from 'service-a';` from `service-b.js` would resolve to `service-a/index.js`

   */
  build() {
    let plugins = this.rollupOptions.plugins || [];
    let inputPath = this.inputPaths[0];

    plugins.push({
      resolveId(importee, importer) {
        let modulePath = path.join(inputPath, `${importee}.js`);
        if (existsSync(modulePath)) {
          return modulePath;
        }

        // allow service-worker/addon-name/index.js fallback
        modulePath = path.join(inputPath, importee, 'index.js');
        if (existsSync(modulePath)) {
          return modulePath;
        }
      }
    });

    this.rollupOptions.plugins = plugins;

    return super.build();
  }
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var glob = require('glob')
var path = require('path')
var _ = require('lodash')
var async = require('async')
var teenytest = require('../../index')

var globLocator = process.argv[2] || 'test/*.js'

async.series(_.map(glob.sync(globLocator), function (file) {
  return function (cb) {
    teenytest.plugins.unregisterAll()
    console.log('Running test in "' + file + '"')
    require(path.resolve(process.cwd(), file))(cb)
  }
}), function (er) {
  if (er) { throw er }
  console.log('Looks good!')
})
<commit_msg>Ensure that only passing tests exit 0<commit_after>#!/usr/bin/env node

var glob = require('glob')
var path = require('path')
var _ = require('lodash')
var async = require('async')
var teenytest = require('../../index')

var globLocator = process.argv[2] || 'test/*.js'
var passing = false

async.series(_.map(glob.sync(globLocator), function (file) {
  return function (cb) {
    teenytest.plugins.unregisterAll()
    console.log('Running test in "' + file + '"')
    require(path.resolve(process.cwd(), file))(cb)
  }
}), function (er) {
  if (er) { throw er }
  console.log('Looks good!')
  passing = true
})

process.on('exit', function () {
  if (!passing) {
    console.error('You fail!')
    process.exit(1)
  }
})

<|endoftext|>


<commit_before>'use strict';
// Generated by CoffeeScript 1.4.0
/*

Timeout route
=============

The `timeout` route will wait for the provided period (in millisenconds) before executing the following route.

```javascript
var app = new shell();
app.configure(function() {
  app.use(shell.router({
    shell: app
  }));
});
app.cmd('restart', [
  my_app.routes.stop,
  shell.routes.timeout(1000),
  my_app.routes.start
]);
```
*/

module.exports = function fnTimeout(timeout) {
  return function returnTimeout(req, res, next) {
    return setTimeout(timeout, next);
  };
};
<commit_msg>[fix] Fix timeout error<commit_after>'use strict';
// Generated by CoffeeScript 1.4.0
/*

Timeout route
=============

The `timeout` route will wait for the provided period (in millisenconds) before executing the following route.

```javascript
var app = new shell();
app.configure(function() {
  app.use(shell.router({
    shell: app
  }));
});
app.cmd('restart', [
  my_app.routes.stop,
  shell.routes.timeout(1000),
  my_app.routes.start
]);
```
*/

module.exports = function fnTimeout(timeout) {
  return function returnTimeout(req, res, next) {
    return setTimeout(next, timeout);
  };
};

<|endoftext|>


<commit_before>// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=397704
// To debug code on page load in cordova-simulate or on Android devices/emulators: launch your app, set breakpoints,
// and then run "window.location.reload()" in the JavaScript Console.
(function () {
    "use strict";

    document.addEventListener('deviceready', onDeviceReady.bind(this), false);

    function onDeviceReady() {
        window.plugins.webintent.onNewIntent(function (url) {
            if (url.indexOf("box:/") > 2) {
                console.log(url);
                url = url.split("callback/");
                url = url[1];
                //setTimeout(function () { window.open("index.html/" + url, "_blank"); }, 200);
            }
        });

        // Handle the Cordova pause and resume events
        document.addEventListener( 'pause', onPause.bind( this ), false );
        document.addEventListener( 'resume', onResume.bind( this ), false );

        // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
        var parentElement = document.getElementById('deviceready');
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
    };

    function onResume() {
        // TODO: This application has been suspended. Save application state here.
    };

    function onPause() {
        // TODO: This application has been suspended. Save application state here.
    };

} )();
<commit_msg>Update index.js<commit_after>// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=397704
// To debug code on page load in cordova-simulate or on Android devices/emulators: launch your app, set breakpoints,
// and then run "window.location.reload()" in the JavaScript Console.
(function () {
    "use strict";

    document.addEventListener('deviceready', onDeviceReady.bind(this), false);

    function onDeviceReady() {
        navigator.splashscreen.hide();
        window.plugins.webintent.onNewIntent(function (url) {
            if (url.indexOf("box:/") > 2) {
                console.log(url);
                url = url.split("callback/");
                url = url[1];
                //setTimeout(function () { window.open("index.html/" + url, "_blank"); }, 200);
            }
        });

        // Handle the Cordova pause and resume events
        document.addEventListener( 'pause', onPause.bind( this ), false );
        document.addEventListener( 'resume', onResume.bind( this ), false );

        // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
        var parentElement = document.getElementById('deviceready');
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
    };

    function onResume() {
        // TODO: This application has been suspended. Save application state here.
    };

    function onPause() {
        // TODO: This application has been suspended. Save application state here.
    };

} )();
<|endoftext|>


<commit_before>/*global describe:true, it:true, before:true, after:true */

var
	chai = require('chai'),
	assert = chai.assert,
	expect = chai.expect,
	should = chai.should()
	;

var
	polyclay = require('../lib/polyclay'),
	mixins = require('../lib/mixins'),
	util = require('util')
	;

describe('mixins', function()
{
	var Model1, Model2;

	var model1 =
	{
		properties:
		{
			name: 'string',
		},
		required: [ 'created', 'name' ],
	};

	var model2 =
	{
		properties:
		{
			foozle: 'string',
		},
		required: [ 'modified', 'foozle' ],
	};

	var HasTimestamps =
	{
		properties:
		{
			created: 'date',
			modified: 'date'
		},
		methods:
		{
			touch: function() { this.modified = Date.now(); }
		}
	};

	var HasVersion =
	{
		properties:
		{
			version: 'number'
		},
		methods:
		{
			upgrade: function() { this.version++; }
		},
		custom:
		{
			fred:
			{
				getter: function() { return this._antifred; },
				setter: function(f) { this._fred = f; this._antifred = f + ' NOT!'; }
			}
		}
	};

	beforeEach(function()
	{
		Model1 = polyclay.Model.buildClass(model1);
		Model2 = polyclay.Model.buildClass(model2);
	});

	it('adds properties to a model prototype', function()
	{
		mixins.mixin(Model1, HasTimestamps);
		var instance = new Model1();
		var proto = Object.getPrototypeOf(instance);

		var property = Object.getOwnPropertyDescriptor(proto, 'created');
		property.should.be.an('object');
		property.should.have.property('get');
		property.should.have.property('set');
	});

	it('adds methods to a model prototype', function()
	{
		mixins.mixin(Model1, HasTimestamps);
		Model1.prototype.should.have.property('touch');
		Model1.prototype.touch.should.be.a('function');
	});

	it('adds custom getters & setters for custom properties', function()
	{
		mixins.mixin(Model1, HasVersion);
		var instance = new Model1();
		var proto = Object.getPrototypeOf(instance);

		var property = Object.getOwnPropertyDescriptor(proto, 'fred');
		property.should.be.an('object');
		property.should.have.property('get');
		property.should.have.property('set');

		instance.fred = 'foo';
		instance._antifred.should.equal('foo NOT!');
	});

	it('can add more than one mixin to a prototype', function()
	{
		mixins.mixin(Model1, HasTimestamps);
		mixins.mixin(Model1, HasVersion);
		Model1.prototype.should.have.property('touch');
		Model1.prototype.touch.should.be.a('function');
		Model1.prototype.should.have.property('upgrade');
		Model1.prototype.upgrade.should.be.a('function');
	});

});
<commit_msg>A tiny bit of jshint cleanup.<commit_after>/*global describe:true, it:true, before:true, after:true, beforeEach: true */

var
	chai = require('chai'),
	assert = chai.assert,
	expect = chai.expect,
	should = chai.should()
	;

var
	polyclay = require('../lib/polyclay'),
	mixins = require('../lib/mixins'),
	util = require('util')
	;

describe('mixins', function()
{
	var Model1, Model2;

	var model1 =
	{
		properties:
		{
			name: 'string',
		},
		required: [ 'created', 'name' ],
	};

	var model2 =
	{
		properties:
		{
			foozle: 'string',
		},
		required: [ 'modified', 'foozle' ],
	};

	var HasTimestamps =
	{
		properties:
		{
			created: 'date',
			modified: 'date'
		},
		methods:
		{
			touch: function() { this.modified = Date.now(); }
		}
	};

	var HasVersion =
	{
		properties:
		{
			version: 'number'
		},
		methods:
		{
			upgrade: function() { this.version++; }
		},
		custom:
		{
			fred:
			{
				getter: function() { return this._antifred; },
				setter: function(f) { this._fred = f; this._antifred = f + ' NOT!'; }
			}
		}
	};

	beforeEach(function()
	{
		Model1 = polyclay.Model.buildClass(model1);
		Model2 = polyclay.Model.buildClass(model2);
	});

	it('adds properties to a model prototype', function()
	{
		mixins.mixin(Model1, HasTimestamps);
		var instance = new Model1();
		var proto = Object.getPrototypeOf(instance);

		var property = Object.getOwnPropertyDescriptor(proto, 'created');
		property.should.be.an('object');
		property.should.have.property('get');
		property.should.have.property('set');
	});

	it('adds methods to a model prototype', function()
	{
		mixins.mixin(Model1, HasTimestamps);
		Model1.prototype.should.have.property('touch');
		Model1.prototype.touch.should.be.a('function');
	});

	it('adds custom getters & setters for custom properties', function()
	{
		mixins.mixin(Model1, HasVersion);
		var instance = new Model1();
		var proto = Object.getPrototypeOf(instance);

		var property = Object.getOwnPropertyDescriptor(proto, 'fred');
		property.should.be.an('object');
		property.should.have.property('get');
		property.should.have.property('set');

		instance.fred = 'foo';
		instance._antifred.should.equal('foo NOT!');
	});

	it('can add more than one mixin to a prototype', function()
	{
		mixins.mixin(Model1, HasTimestamps);
		mixins.mixin(Model1, HasVersion);
		Model1.prototype.should.have.property('touch');
		Model1.prototype.touch.should.be.a('function');
		Model1.prototype.should.have.property('upgrade');
		Model1.prototype.upgrade.should.be.a('function');
	});

});
<|endoftext|>


<commit_before><commit_msg>Adjustments for array of all values<commit_after><|endoftext|>


<commit_before>/* See license.txt for terms of usage */

"use strict";

const { exist, addNewLayer } = require("./common.js");
const { closeTab } = require("sdk/tabs/utils");

/**
 * Add layer and check that it's properly created.
 */
exports["test Add Layer"] = function(assert, done) {
  addNewLayer().then(config => {
    let popup = config.popup;
    let layer = config.layer;

    // Check the layer store. There should be one layer at this moment.
    assert.equal(popup.store.layers.length, 1, "There must be one layer");

    // Check if the panel content displays new layer.
    let selector = "img.layerImage[data-id='" + layer.id + "']";
    exist(popup, selector).then(result => {
      assert.ok(result.data.args, "The layer must exist in the popup panel");

      // Clean up
      config.popup.hide().then(() => {
        closeTab(config.tab);
        done();
      });
    });
  });
};

require("sdk/test").run(exports);
<commit_msg>Remove layer also in the add layer test<commit_after>/* See license.txt for terms of usage */

"use strict";

const { exist, addNewLayer, removeLayer } = require("./common.js");
const { closeTab } = require("sdk/tabs/utils");

/**
 * Add layer and check that it's properly created.
 */
exports["test Add Layer"] = function(assert, done) {
  addNewLayer().then(config => {
    let popup = config.popup;
    let layer = config.layer;

    // Check the layer store. There should be one layer at this moment.
    assert.equal(popup.store.layers.length, 1, "There must be one layer");

    // Check if the panel content displays new layer.
    let selector = "img.layerImage[data-id='" + layer.id + "']";
    exist(popup, selector).then(result => {
      assert.ok(result.data.args, "The layer must exist in the popup panel");

      // Clean up
      removeLayer(popup, layer.id).then(() => {
        config.popup.hide().then(() => {
          closeTab(config.tab);
          done();
        });
      });
    });
  });
};

require("sdk/test").run(exports);
<|endoftext|>


<commit_before>'use strict';

var assert = require('chai').assert,
    sinon = require('sinon'),
    fluxex = require('../'),
    actions = require('./testAction'),
    app = require('./testApp');

describe('a fluxex app', function () {
    it('can be constructed by undefined', function (done) {
        var A = new app();
        done();
    });

    it('can be constructed by number', function (done) {
        var F = new app(123);
        done();
    });

    it('can be constructed by object', function (done) {
        var F = new app({a: 3});
        done();
    });

    it('creates stores automatically when be constructed', function (done) {
        var F = new app({stores: {sampleStore: {a: 1}}});

        assert.equal(1, F.getStore('sampleStore').get('a'));
        done();
    });

    it('will throw when no this.stores defined', function (done) {
        assert.throws(function () {
            var App = function () {
                fluxex.apply(this, arguments);
            }
            new App();
        }, Error, 'Your app should define this.stores !!');
        done();
    });

    it('will throw when no store info defined', function (done) {
        assert.throws(function () {
            fluxex.createApp();
        }, Error, 'You should create app with information of stores as first parameter');
        done();
    });

    it('will throw when no HtmlJsx provided', function (done) {
        assert.throws(function () {
            fluxex.createApp({fakeStore: '...'});
        }, Error, 'You should create app with HtmlJsx as second parameter');
        done();
    });

    it('will throw when initStore() be called externally', function (done) {
        assert.throws(function () {
            var App = new app();
            App.initStore();
        }, Error, '.initStore() should not be called externally!');
        done();
    });

    it('can .get() and .set()', function (done) {
        var App = new app({a: 2});

        App.set('a', 3);
        assert.equal(3, App.get('a'));
        done();
    });

    describe('.getStore()', function () {
        it('should return instance', function (done) {
            var App = new app({a: 2}),
                Store = App.getStore('sampleStore');

            console.log(Store.prototype);
            assert.equal('function', typeof Store.emitChange);
            done();
        });
    });

    describe('.dispatch()', function () {
        it('should throw when no name provided', function (done) {
            assert.throws(function () {
                var App = new app();
                App.dispatch();
            }, Error, 'Can not dispatch without name!');
            done();
        });

        it('should return a promise', function (done) {
            var App = new app();

            assert.equal('function', typeof App.dispatch('test').then);
            done();
        });

        it('should return rejected promise when no store handle it', function (done) {
            var App = new app();

            App.dispatch('_none_').catch(function (E) {
                assert.equal('No store handled the "_none_" action. Maybe you forget to provide "handle__none_" method in a store?', E.message);
                done();
            });
        });

        it('should throw when dispatch in dispatch', function (done) {
            var D = require('domain').create();

            D.on('error', function (E) {
                D.exit();
                assert.equal('Can not dispatch "more_dispatch" action when previous "dispatch" action is not done!', E.message);
                D.dispose();
                done();
            });

            D.run(function () {
                var App = new app();
                App.dispatch('dispatch', App);
            });
        });
    });

    describe('.executeAction()', function () {
        it('should return a promise', function (done) {
            var App = new app();

            App.executeAction().catch(function () {
                done();
            });
        });

        it('should return a rejected promise when no action provided', function (done) {
            var App = new app();

            App.executeAction().catch(function (E) {
                assert.equal('.executeAction() require a action creator function as first parameter!', E.message);
                done();
            });
        });

        it('should return a rejected promise when the action do not return a promise', function (done) {
            var App = new app();

            App.executeAction(function (){}).catch(function (E) {
                assert.equal('Execute an action creator that do not return a promise!', E.message);
                done();
            });
        });

        it('should execute action well', function (done) {
            var App = new app();

            App.executeAction(actions.sampleAction, 3).then(function() {
                done();
            });
        });
    });
});
<commit_msg>coverage<commit_after>'use strict';

var assert = require('chai').assert,
    sinon = require('sinon'),
    fluxex = require('../'),
    react = require('react'),
    actions = require('./testAction'),
    app = require('./testApp');

describe('a fluxex app', function () {
    it('can be constructed by undefined', function (done) {
        var A = new app();
        done();
    });

    it('can be constructed by number', function (done) {
        var F = new app(123);
        done();
    });

    it('can be constructed by object', function (done) {
        var F = new app({a: 3});
        done();
    });

    it('creates stores automatically when be constructed', function (done) {
        var F = new app({stores: {sampleStore: {a: 1}}});

        assert.equal(1, F.getStore('sampleStore').get('a'));
        done();
    });

    it('will throw when no this.stores defined', function (done) {
        assert.throws(function () {
            var App = function () {
                fluxex.apply(this, arguments);
            }
            new App();
        }, Error, 'Your app should define this.stores !!');
        done();
    });

    it('will throw when no store info defined', function (done) {
        assert.throws(function () {
            fluxex.createApp();
        }, Error, 'You should create app with information of stores as first parameter');
        done();
    });

    it('will throw when no HtmlJsx provided', function (done) {
        assert.throws(function () {
            fluxex.createApp({fakeStore: '...'});
        }, Error, 'You should create app with HtmlJsx as second parameter');
        done();
    });

    it('will throw when .initStore() be called externally', function (done) {
        assert.throws(function () {
            var App = new app();
            App.initStore();
        }, Error, '.initStore() should not be called externally!');
        done();
    });

    it('will throw when .getHtmlJsx() with wrong module name', function (done) {
        assert.throws(function () {
            var App = new app();
            App.getHtmlJsx();
        }, Error, 'Cannot find module \'noneed_htmlJsx\'');
        done();
    });

    it('will react.render() with self', function (done) {
        var App = new app({c: 3});

        sinon.stub(react, 'withContext', function (obj, cb) {
            global.document = {body: {parentNode: {parentNode: 0}}};
            cb();
        });

        sinon.stub(App, 'getHtmlJsx').returns('123');
        sinon.stub(react, 'render');

        App.initClient();

        assert.strictEqual(App, react.withContext.getCall(0).args[0].fluxex);
        assert.equal('123', react.render.getCall(0).args[0]);
        delete global.document;

        react.withContext.restore();
        react.render.restore();

        done();
    });

    it('can .get() and .set()', function (done) {
        var App = new app({a: 2});

        App.set('a', 3);
        assert.equal(3, App.get('a'));
        done();
    });

    describe('.getStore()', function () {
        it('should return instance', function (done) {
            var App = new app({a: 2}),
                Store = App.getStore('sampleStore');

            console.log(Store.prototype);
            assert.equal('function', typeof Store.emitChange);
            done();
        });
    });

    describe('.dispatch()', function () {
        it('should throw when no name provided', function (done) {
            assert.throws(function () {
                var App = new app();
                App.dispatch();
            }, Error, 'Can not dispatch without name!');
            done();
        });

        it('should return a promise', function (done) {
            var App = new app();

            assert.equal('function', typeof App.dispatch('test').then);
            done();
        });

        it('should return rejected promise when no store handle it', function (done) {
            var App = new app();

            App.dispatch('_none_').catch(function (E) {
                assert.equal('No store handled the "_none_" action. Maybe you forget to provide "handle__none_" method in a store?', E.message);
                done();
            });
        });

        it('should throw when dispatch in dispatch', function (done) {
            var D = require('domain').create();

            D.on('error', function (E) {
                D.exit();
                assert.equal('Can not dispatch "more_dispatch" action when previous "dispatch" action is not done!', E.message);
                D.dispose();
                done();
            });

            D.run(function () {
                var App = new app();
                App.dispatch('dispatch', App);
            });
        });
    });

    describe('.executeAction()', function () {
        it('should return a promise', function (done) {
            var App = new app();

            App.executeAction().catch(function () {
                done();
            });
        });

        it('should return a rejected promise when no action provided', function (done) {
            var App = new app();

            App.executeAction().catch(function (E) {
                assert.equal('.executeAction() require a action creator function as first parameter!', E.message);
                done();
            });
        });

        it('should return a rejected promise when the action do not return a promise', function (done) {
            var App = new app();

            App.executeAction(function (){}).catch(function (E) {
                assert.equal('Execute an action creator that do not return a promise!', E.message);
                done();
            });
        });

        it('should execute action well', function (done) {
            var App = new app();

            App.executeAction(actions.sampleAction, 3).then(function() {
                done();
            });
        });
    });
});
<|endoftext|>


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

'use strict';

var an = require('../index');
var assert = require('assert');

describe('canAnalyze', function() {
  it('should return true if it contains blank-container defs with no ipAddress', function(){
    var sys = {
      containerDefinitions: [{
        type: 'blank-container'
      }, {
        type: 'docker'
      }]
    };
    assert(an.canAnalyze(sys));
  });

  it('should return false if it contains blank-container def with ipAddress', function() {
    var sys = {
      containerDefinitions: [{
        type: 'blank-container',
        specific: {
          ipAddress: '192.168.5.2'
        }
      }, {
        type: 'docker'
      }]
    };
    assert(!an.canAnalyze(sys));
  });

  it('should return false if it contains a blank-container def with priveIpAddress', function() {
    var sys = {
      containerDefinitions: [{
        type: 'blank-container',
        specific: {
          privateIpAddress: '192.168.5.2'
        }
      }, {
        type: 'docker'
      }]
    };
    assert(!an.canAnalyze(sys));
  });

  it('should return false if it contains a blank-container def with priveIpAddress', function() {
    var sys = {
      containerDefinitions: [{
        type: 'blank-container',
        specific: {
          ipaddress: '192.168.5.2'
        }
      }, {
        type: 'docker'
      }]
    };
    assert(!an.canAnalyze(sys));
  });

  it('should return false if it contains something else', function(){
    var sys = {
      containerDefinitions: [{
        type: 'aws-ami'
      }, {
        type: 'docker'
      }]
    };
    assert(!an.canAnalyze(sys));
  });

  it('should return true if it contains blank-container def and a process def', function(){
    var sys = {
      containerDefinitions: [{
        type: 'blank-container'
      }, {
        type: 'process'
      }]
    };
    assert(an.canAnalyze(sys));
  });
});
<commit_msg>fixed tests<commit_after>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var an = require('../index');
var assert = require('assert');

describe('canAnalyze', function() {
  it('should return true if it contains blank-container defs with no ipAddress', function(){
    var sys = {
      topology:{ containers: [{
        type: 'blank-container'
      }, {
        type: 'docker'
      }]}
    };
    assert(an.canAnalyze(sys));
  });

  it('should return false if it contains blank-container def with ipAddress', function() {
    var sys = {
      topology: {containers: [{
        type: 'blank-container',
        specific: {
          ipAddress: '192.168.5.2'
        }
      }, {
        type: 'docker'
      }]}
    };
    assert(!an.canAnalyze(sys));
  });

  it('should return false if it contains a blank-container def with priveIpAddress', function() {
    var sys = {
      topology: { containers: [{
        type: 'blank-container',
        specific: {
          privateIpAddress: '192.168.5.2'
        }
      }, {
        type: 'docker'
      }]}
    };
    assert(!an.canAnalyze(sys));
  });

  it('should return false if it contains a blank-container def with priveIpAddress', function() {
    var sys = {
      topology: { containers: [{
        type: 'blank-container',
        specific: {
          ipaddress: '192.168.5.2'
        }
      }, {
        type: 'docker'
      }]}
    };
    assert(!an.canAnalyze(sys));
  });

  it('should return false if it contains something else', function(){
    var sys = {
      topology: { containers: [{
        type: 'aws-ami'
      }, {
        type: 'docker'
      }]}
    };
    assert(!an.canAnalyze(sys));
  });

  it('should return true if it contains blank-container def and a process def', function(){
    var sys = {
      topology: { containers: [{
        type: 'blank-container'
      }, {
        type: 'process'
      }]}
    };
    assert(an.canAnalyze(sys));
  });
});
<|endoftext|>


<commit_before>Backbone.GSModel = Backbone.Model.extend({

	get: function(attr) {
		// Call the getter if available
		if (_.isFunction(this.getters[attr])) {
			return this.getters[attr].call(this);
		}

		return Backbone.Model.prototype.get.call(this, attr);
	},

	set: function(key, value, options) {
		// Normalize the key-value into an object
		if (_.isObject(key) || key == null) {
			attrs = key;
			options = value;
		} else {
			attrs = {};
			attrs[key] = value;
		}

		// Go over all the set attributes and call the setter if available
		for (attr in attrs) {
			if (_.isFunction(this.setters[attr])) {
				attrs[attr] = this.setters[attr].call(this, attrs[attr]);
			}
		}

		return Backbone.Model.prototype.set.call(this, attrs, options);
	},

	getters: {},

	setters: {}

});<commit_msg>Bug fix: Turn the attrs and attr into local vars<commit_after>Backbone.GSModel = Backbone.Model.extend({

	get: function(attr) {
		// Call the getter if available
		if (_.isFunction(this.getters[attr])) {
			return this.getters[attr].call(this);
		}

		return Backbone.Model.prototype.get.call(this, attr);
	},

	set: function(key, value, options) {
		var attrs, attr;

		// Normalize the key-value into an object
		if (_.isObject(key) || key == null) {
			attrs = key;
			options = value;
		} else {
			attrs = {};
			attrs[key] = value;
		}

		// Go over all the set attributes and call the setter if available
		for (attr in attrs) {
			if (_.isFunction(this.setters[attr])) {
				attrs[attr] = this.setters[attr].call(this, attrs[attr]);
			}
		}

		return Backbone.Model.prototype.set.call(this, attrs, options);
	},

	getters: {},

	setters: {}

});<|endoftext|>