<commit_before>// Generated on 2015-06-18 using generator-angular 0.11.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Time how long tasks take. Can help when optimizing build times
    require('time-grunt')(grunt);

    // Configurable paths for the application
    var appConfig = {
        app: require('./bower.json').appPath || 'app',
        bowerPath: require('./bower.json').bowerPath || 'bower_components',
        test: require('./bower.json').testPath || 'test',
        res: require('./bower.json').resPath || 'res',
        dist: require('./bower.json').distPath || 'dist',
        docs: require('./bower.json').docPath || 'docs'
    };

    // Define the configuration for all the tasks
    grunt.initConfig({

        // Project settings
        yeoman: appConfig,

        // Watches files for changes and runs tasks based on the changed files
        watch: {
            bower: {
                files: ['bower.json'],
                tasks: ['wiredep']
            },
            js: {
                files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
                tasks: ['newer:jshint:all'],
                options: {
                    livereload: '<%= connect.options.livereload %>'
                }
            },
            sass: {
                files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
                tasks: ['sass', 'autoprefixer']
            },
            jsTest: {
                files: ['test/spec/{,*/}*.js'],
                tasks: ['newer:jshint:test', 'karma']
            },
            styles: {
                files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
                tasks: ['newer:copy:styles', 'autoprefixer']
            },
            gruntfile: {
                files: ['Gruntfile.js']
            },
            livereload: {
                options: {
                    livereload: '<%= connect.options.livereload %>'
                },
                files: [
                    '<%= yeoman.app %>/{,*/}*.html',
                    '.tmp/styles/{,*/}*.css',
                    '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },

        // The actual grunt server settings
        connect: {
            options: {
                port: 9000,
                // Change this to '0.0.0.0' to access the server from outside.
                hostname: 'localhost',
                livereload: 35729
            },
            proxies: [
                {
                    context: '/api',
                    host: 'localhost',
                    port: 9080
                }, {
                    context: '/login',
                    host: 'localhost',
                    port: 9080
                }, {
                    context: '/logout',
                    host: 'localhost',
                    port: 9080
                }
            ],
            livereload: {
                options: {
                    open: true,
                    middleware: function (connect) {
                        return [
                            connect.static('.tmp'),
                            connect().use('/bower_components', connect.static('./bower_components')),
                            connect().use('/fonts', connect.static('./bower_components/bootstrap-sass-official/assets/fonts/bootstrap')),
                            connect().use('/app/styles', connect.static('./app/styles')),
                            connect.static(appConfig.app),
                            require('grunt-connect-proxy/lib/utils').proxyRequest
                        ];
                    }
                }
            },
            test: {
                options: {
                    port: 9001,
                    middleware: function (connect) {
                        return [
                            connect.static('.tmp'),
                            connect.static('test'),
                            connect().use('/bower_components', connect.static('./bower_components')),
                            connect.static(appConfig.app)
                        ];
                    }
                }
            },
            dist: {
                options: {
                    open: true,
                    base: '<%= yeoman.dist %>'
                }
            }
        },

        // Make sure code styles are up to par and there are no obvious mistakes
        jshint: {
            options: {
                jshintrc: '.jshintrc',
                reporter: require('jshint-stylish')
            },
            all: {
                src: [
                    'Gruntfile.js',
                    '<%= yeoman.app %>/scripts/{,*/}*.js'
                ]
            },
            test: {
                options: {
                    jshintrc: '<%= yeoman.test %>/.jshintrc'
                },
                src: ['<%= yeoman.test %>/spec/{,*/}*.js']
            }
        },

        // Empties folders to start fresh
        clean: {
            dist: {
                files: [{
                    dot: true,
                    src: [
                        '.tmp',
                        '<%= yeoman.dist %>/{,*/}*',
                        '!<%= yeoman.dist %>/.git{,*/}*'
                    ]
                }]
            },
            server: '.tmp'
        },

        // Compiles Sass to CSS and generates necessary files if requested

        sass: {
            dist: {
                options: {
                    // sourceMap: true,
                    style: 'expanded',
                    includePaths: [
                        'bower_components/compass-mixins/lib/',
                        'bower_components/bootstrap-sass-official/assets/stylesheets/'
                    ]
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/styles',
                    src: ['**/*.scss'],
                    dest: '.tmp/styles',
                    ext: '.css'
                }]
            }

        },

        // Add vendor prefixed styles
        autoprefixer: {
            options: {
                browsers: ['last 1 version']
            },
            server: {
                options: {
                    map: true,
                },
                files: [{
                    expand: true,
                    cwd: '.tmp/styles/',
                    src: '{,*/}*.css',
                    dest: '.tmp/styles/'
                }]
            },
            dist: {
                files: [{
                    expand: true,
                    cwd: '.tmp/styles/',
                    src: '{,*/}*.css',
                    dest: '.tmp/styles/'
                }]
            }
        },

        // Automatically inject Bower components into the app
        wiredep: {
            app: {
                src: ['<%= yeoman.app %>/index.html'],
                ignorePath: /\.\.\.\//
            },
            test: {
                devDependencies: true,
                src: '<%= karma.unit.configFile %>',
                ignorePath: /\.\.\.\//,
                fileTypes: {
                    js: {
                        block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
                        detect: {
                            js: /'(.*\.js)'/gi
                        },
                        replace: {
                            js: '\'{{filePath}}\','
                        }
                    }
                }
            }
        },

        // Renames files for browser caching purposes
        filerev: {
            dist: {
                src: [
                    '<%= yeoman.dist %>/scripts/{,*/}*.js',
                    '<%= yeoman.dist %>/styles/{,*/}*.css',
                    '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },

        // Reads HTML for usemin blocks to enable smart builds that automatically
        // concat, minify and revision files. Creates configurations in memory so
        // additional tasks can operate on them
        useminPrepare: {
            html: '<%= yeoman.app %>/index.html',
            options: {
                dest: '<%= yeoman.dist %>',
                flow: {
                    html: {
                        steps: {
                            js: ['concat', 'uglify'],
                            css: ['cssmin']
                        },
                        post: {}
                    }
                }
            }
        },

        // Performs rewrites based on filerev and the useminPrepare configuration
        usemin: {
            html: ['<%= yeoman.dist %>/{,*/}*.html'],
            css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
            options: {
                assetsDirs: [
                    '<%= yeoman.dist %>',
                    '<%= yeoman.dist %>/images',
                    '<%= yeoman.dist %>/styles'
                ]
            }
        },
        imagemin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.{png,jpg,jpeg,gif}',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },

        svgmin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.svg',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },

        htmlmin: {
            dist: {
                options: {
                    collapseWhitespace: true,
                    conservativeCollapse: true,
                    collapseBooleanAttributes: true,
                    removeCommentsFromCDATA: true,
                    removeOptionalTags: true
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.dist %>',
                    src: ['*.html', 'views/{,*/}*.html'],
                    dest: '<%= yeoman.dist %>'
                }]
            }
        },

        // ng-annotate tries to make the code safe for minification automatically
        // by using the Angular long form for dependency injection.
        ngAnnotate: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '.tmp/concat/scripts',
                    src: '*.js',
                    dest: '.tmp/concat/scripts'
                }]
            }
        },

        // Replace Google CDN references
        cdnify: {
            dist: {
                html: ['<%= yeoman.dist %>/*.html']
            }
        },

        replace: {
            server: {
                src: ['.tmp/styles/*.css'],// source files array (supports minimatch)
                dest: '.tmp/styles/',// destination directory or file
                replacements: [{
                    from: 'fonts/',// string replacement
                    to: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/'
                }]

            },
            dist: {
                src: ['<%= yeoman.docs %>/schema-doc/*.html'],// source files array (supports minimatch)
                dest: '<%= yeoman.dist %>/docs/schema-doc/',// destination directory or file
                replacements: [{
                    from: '=\"http:\/\/',// string replacement
                    to: '="\/\/'
                }]
            }
        },

        // Copies remaining files to places other tasks can use
        copy: {
            dist: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= yeoman.app %>',
                    dest: '<%= yeoman.dist %>',
                    src: [
                        '*.{ico,png,txt}',
                        '.htaccess',
                        '*.html',
                        'templates/{,*/}*.html',
                        'views/{,*/}*.html',
                        'images/{,*/}*.{webp}',
                        'styles/fonts/{,*/}*.*'
                    ]
                }, {
                    expand: true,
                    cwd: '.tmp/images',
                    dest: '<%= yeoman.dist %>/images',
                    src: ['generated/*']
                }, {
                    expand: true,
                    cwd: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap',
                    src: '*',
                    dest: '<%= yeoman.dist %>/fonts'
                }]
            }
        },

        // Run some tasks in parallel to speed up the build process
        concurrent: {
            server: [],
            test: [],
            dist: [
                'imagemin',
                'svgmin'
            ]
        },

        // Test settings
        karma: {
            unit: {
                configFile: 'karma.conf.js',
                singleRun: true
            },

            dev: {
                configFile: 'karma.conf.js',
                singleRun: false,
                autoWatch: true
            }
        },

        open: {
            karma: {
                path: 'http://127.0.0.1:9080',
                options: {
                    delay: 2000
                }
            }
        }
    });

    grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['build', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'wiredep',
            'sass',
            'configureProxies:server',
            'concurrent:server',
            'replace:server',
            'autoprefixer:server',
            'connect:livereload',
            'watch'
        ]);
    });

    grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
        grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
        grunt.task.run(['serve:' + target]);
    });

    grunt.registerTask('test', [
        'clean:server',
        'wiredep',
        'concurrent:test',
        'autoprefixer',
        'connect:test',
        'karma:unit'
    ]);

    grunt.registerTask('build', [
        'clean:dist',
        'wiredep',
        'sass',
        'useminPrepare',
        'concurrent:dist',
        'autoprefixer',
        'concat',
        'ngAnnotate',
        'copy:dist',
        'cdnify',
        'replace:dist',
        'cssmin',
        'uglify',
        'filerev',
        'usemin',
        'htmlmin'
    ]);

    grunt.registerTask('debug', [
        'open:karma',
        'karma:dev'
    ]);

    grunt.registerTask('check', [
        'jshint',
        'build'
    ]);

    grunt.registerTask('default', [
        'check'
    ]);
};
<commit_msg>Fix e2e test setup error<commit_after>'use strict';

module.exports = function (grunt) {

    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Time how long tasks take. Can help when optimizing build times
    require('time-grunt')(grunt);

    // Configurable paths for the application
    var appConfig = {
        app: require('./bower.json').appPath || 'app',
        bowerPath: require('./bower.json').bowerPath || 'bower_components',
        test: require('./bower.json').testPath || 'test',
        res: require('./bower.json').resPath || 'res',
        dist: require('./bower.json').distPath || 'dist',
        docs: require('./bower.json').docPath || 'docs'
    };

    // Define the configuration for all the tasks
    grunt.initConfig({

        // Project settings
        yeoman: appConfig,

        // Watches files for changes and runs tasks based on the changed files
        watch: {
            bower: {
                files: ['bower.json'],
                tasks: ['wiredep']
            },
            js: {
                files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
                tasks: ['newer:jshint:all'],
                options: {
                    livereload: '<%= connect.options.livereload %>'
                }
            },
            sass: {
                files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
                tasks: ['sass', 'autoprefixer']
            },
            jsTest: {
                files: ['test/spec/{,*/}*.js'],
                tasks: ['newer:jshint:test', 'karma']
            },
            styles: {
                files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
                tasks: ['newer:copy:styles', 'autoprefixer']
            },
            gruntfile: {
                files: ['Gruntfile.js']
            },
            livereload: {
                options: {
                    livereload: '<%= connect.options.livereload %>'
                },
                files: [
                    '<%= yeoman.app %>/{,*/}*.html',
                    '.tmp/styles/{,*/}*.css',
                    '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },

        // The actual grunt server settings
        connect: {
            options: {
                port: 9000,
                // Change this to '0.0.0.0' to access the server from outside.
                hostname: 'localhost',
                livereload: 35729
            },
            proxies: [
                {
                    context: '/api',
                    host: 'localhost',
                    port: 9080
                }, {
                    context: '/login',
                    host: 'localhost',
                    port: 9080
                }, {
                    context: '/logout',
                    host: 'localhost',
                    port: 9080
                }
            ],
            livereload: {
                options: {
                    open: true,
                    middleware: function (connect) {
                        return [
                            connect.static('.tmp'),
                            connect().use('/bower_components', connect.static('./bower_components')),
                            connect().use('/fonts', connect.static('./bower_components/bootstrap-sass-official/assets/fonts/bootstrap')),
                            connect().use('/app/styles', connect.static('./app/styles')),
                            connect.static(appConfig.app),
                            require('grunt-connect-proxy/lib/utils').proxyRequest
                        ];
                    }
                }
            },
            test: {
                options: {
                    port: 9001,
                    middleware: function (connect) {
                        return [
                            connect.static('.tmp'),
                            connect.static('test'),
                            connect().use('/bower_components', connect.static('./bower_components')),
                            connect.static(appConfig.app)
                        ];
                    }
                }
            },
            dist: {
                options: {
                    open: true,
                    base: '<%= yeoman.dist %>'
                }
            }
        },

        // Make sure code styles are up to par and there are no obvious mistakes
        jshint: {
            options: {
                jshintrc: '.jshintrc',
                reporter: require('jshint-stylish')
            },
            all: {
                src: [
                    'Gruntfile.js',
                    '<%= yeoman.app %>/scripts/{,*/}*.js'
                ]
            },
            test: {
                options: {
                    jshintrc: '<%= yeoman.test %>/.jshintrc'
                },
                src: ['<%= yeoman.test %>/spec/{,*/}*.js']
            }
        },

        // Empties folders to start fresh
        clean: {
            dist: {
                files: [{
                    dot: true,
                    src: [
                        '.tmp',
                        '<%= yeoman.dist %>/{,*/}*',
                        '!<%= yeoman.dist %>/.git{,*/}*'
                    ]
                }]
            },
            server: '.tmp'
        },

        // Compiles Sass to CSS and generates necessary files if requested

        sass: {
            dist: {
                options: {
                    // sourceMap: true,
                    style: 'expanded',
                    includePaths: [
                        'bower_components/compass-mixins/lib/',
                        'bower_components/bootstrap-sass-official/assets/stylesheets/'
                    ]
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/styles',
                    src: ['**/*.scss'],
                    dest: '.tmp/styles',
                    ext: '.css'
                }]
            }

        },

        // Add vendor prefixed styles
        autoprefixer: {
            options: {
                browsers: ['last 1 version']
            },
            server: {
                options: {
                    map: true,
                },
                files: [{
                    expand: true,
                    cwd: '.tmp/styles/',
                    src: '{,*/}*.css',
                    dest: '.tmp/styles/'
                }]
            },
            dist: {
                files: [{
                    expand: true,
                    cwd: '.tmp/styles/',
                    src: '{,*/}*.css',
                    dest: '.tmp/styles/'
                }]
            }
        },

        // Automatically inject Bower components into the app
        wiredep: {
            app: {
                src: ['<%= yeoman.app %>/index.html'],
                ignorePath: /\.\.\.\//
            },
            test: {
                devDependencies: true,
                src: '<%= karma.unit.configFile %>',
                ignorePath: /\.\.\.\//,
                fileTypes: {
                    js: {
                        block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
                        detect: {
                            js: /'(.*\.js)'/gi
                        },
                        replace: {
                            js: '\'{{filePath}}\','
                        }
                    }
                }
            }
        },

        // Renames files for browser caching purposes
        filerev: {
            dist: {
                src: [
                    '<%= yeoman.dist %>/scripts/{,*/}*.js',
                    '<%= yeoman.dist %>/styles/{,*/}*.css',
                    '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },

        // Reads HTML for usemin blocks to enable smart builds that automatically
        // concat, minify and revision files. Creates configurations in memory so
        // additional tasks can operate on them
        useminPrepare: {
            html: '<%= yeoman.app %>/index.html',
            options: {
                dest: '<%= yeoman.dist %>',
                flow: {
                    html: {
                        steps: {
                            js: ['concat', 'uglify'],
                            css: ['cssmin']
                        },
                        post: {}
                    }
                }
            }
        },

        // Performs rewrites based on filerev and the useminPrepare configuration
        usemin: {
            html: ['<%= yeoman.dist %>/{,*/}*.html'],
            css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
            options: {
                assetsDirs: [
                    '<%= yeoman.dist %>',
                    '<%= yeoman.dist %>/images',
                    '<%= yeoman.dist %>/styles'
                ]
            }
        },
        imagemin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.{png,jpg,jpeg,gif}',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },

        svgmin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.svg',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },

        htmlmin: {
            dist: {
                options: {
                    collapseWhitespace: true,
                    conservativeCollapse: true,
                    collapseBooleanAttributes: true,
                    removeCommentsFromCDATA: true,
                    removeOptionalTags: true
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.dist %>',
                    src: ['*.html', 'views/{,*/}*.html'],
                    dest: '<%= yeoman.dist %>'
                }]
            }
        },

        // ng-annotate tries to make the code safe for minification automatically
        // by using the Angular long form for dependency injection.
        ngAnnotate: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '.tmp/concat/scripts',
                    src: '*.js',
                    dest: '.tmp/concat/scripts'
                }]
            }
        },

        // Replace Google CDN references
        cdnify: {
            dist: {
                html: ['<%= yeoman.dist %>/*.html']
            }
        },

        replace: {
            server: {
                src: ['.tmp/styles/*.css'],// source files array (supports minimatch)
                dest: '.tmp/styles/',// destination directory or file
                replacements: [{
                    from: 'fonts/',// string replacement
                    to: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/'
                }]

            },
            dist: {
                src: ['<%= yeoman.docs %>/schema-doc/*.html'],// source files array (supports minimatch)
                dest: '<%= yeoman.dist %>/docs/schema-doc/',// destination directory or file
                replacements: [{
                    from: '=\"http:\/\/',// string replacement
                    to: '="\/\/'
                }]
            }
        },

        // Copies remaining files to places other tasks can use
        copy: {
            dist: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= yeoman.app %>',
                    dest: '<%= yeoman.dist %>',
                    src: [
                        '*.{ico,png,txt}',
                        '.htaccess',
                        '*.html',
                        'templates/{,*/}*.html',
                        'views/{,*/}*.html',
                        'images/{,*/}*.{webp}',
                        'styles/fonts/{,*/}*.*'
                    ]
                }, {
                    expand: true,
                    cwd: '.tmp/images',
                    dest: '<%= yeoman.dist %>/images',
                    src: ['generated/*']
                }, {
                    expand: true,
                    cwd: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap',
                    src: '*',
                    dest: '<%= yeoman.dist %>/fonts'
                }]
            }
        },

        // Run some tasks in parallel to speed up the build process
        concurrent: {
            server: [],
            test: [],
            dist: [
                'imagemin',
                'svgmin'
            ]
        },

        // Test settings
        karma: {
            unit: {
                configFile: 'karma.conf.js',
                singleRun: true
            },
            dev: {
                configFile: 'karma.conf.js',
                singleRun: false,
                autoWatch: true
            },
            ci: {
                configFile: 'karma.conf.ci.js'
            }
        },

        open: {
            karma: {
                path: 'http://127.0.0.1:9080',
                options: {
                    delay: 2000
                }
            }
        },
        shell: {
            'galen-ci': {
                command: './runGalenTests.ci.sh',
                options: {
                    stderr: true,
                    execOptions: {
                        cwd: './src/test/frontend/layout/'
                    }
                }
            }
        }
    });

    grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['build', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'wiredep',
            'sass',
            'configureProxies:server',
            'concurrent:server',
            'replace:server',
            'autoprefixer:server',
            'connect:livereload',
            'watch'
        ]);
    });

    grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
        grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
        grunt.task.run(['serve:' + target]);
    });

    grunt.registerTask('unit-tests', [
        'clean:server',
        'wiredep',
        'concurrent:test',
        'autoprefixer',
        'connect:test',
        'karma:unit'
    ]);

    grunt.registerTask('unit-tests-ci', [
        'clean:server',
        'wiredep',
        'concurrent:test',
        'autoprefixer',
        'connect:test',
        'karma:ci'
    ]);

    grunt.registerTask('e2e-tests-ci', [
        'shell:galen-ci'
    ]);

    grunt.registerTask('build', [
        'clean:dist',
        'wiredep',
        'sass',
        'useminPrepare',
        'concurrent:dist',
        'autoprefixer',
        'concat',
        'ngAnnotate',
        'copy:dist',
        'cdnify',
        'replace:dist',
        'cssmin',
        'uglify',
        'filerev',
        'usemin',
        'htmlmin'
    ]);

    grunt.registerTask('debug', [
        'open:karma',
        'karma:dev'
    ]);

    grunt.registerTask('check', [
        'jshint',
        'build'
    ]);

    grunt.registerTask('test', [
        'unit-tests'
    ]);

    grunt.registerTask('default', [
        'check'
    ]);
};
<|endoftext|>


<commit_before>var util = require('util');
var EventEmitter = require('events').EventEmitter;

function CB(id) {
    this.btServiceIds = ['ae0e019cef7511e981b42a2ae2dbcce4'];

    this._id = id;
    this._gmCh = null;
    this._dev = null;
    this._moving = false;
    this._position = 0;
    this._stepsPerUnit = 1;
    this._backlash = 0;
    this._lastDirection = 0;
}

util.inherits(CB, EventEmitter);

CB.prototype._connectBt = function(btPeripheral, callback) {
    var self = this;
    btPeripheral.connect(function(err1) {
        if (err1) {
            if (callback) callback(false);
            return;
        }
        console.log('CB(' + self._id + '): connecting via BLE');
        setTimeout(function(){
            btPeripheral.discoverServices(self.btServiceIds, function(err2, services) {
                if (services && services[0]) {
                    services[0].discoverCharacteristics([], function(err, characteristics) {
                        //console.log("characteristics:", characteristics);
                        self._writeCh = null;
                        self._readCh = null;
                        self._dev = null;
                        for (var i = 0; i < characteristics.length; i++) {
                            ch = characteristics[i];
                            console.log("ch.uuid", ch.uuid);
                            if (ch.uuid == "ae0e0408ef7511e981b42a2ae2dbcce4") {
                                self._writeCh = ch;
                            } else if (ch.uuid == "ae0e055cef7511e981b42a2ae2dbcce4") {
                                self._readCh = ch;
                            }
                        }
                        if (self._writeCh && self._readCh) {
                            try {
                                console.log("CB(" + self._id + "): subscribing...");
                                self._readCh.subscribe(function(){
                                    self._dev = btPeripheral;
                                    self._dev.connected = true;
                                    self.connected = true;
                                    self._dev.type = "bt";
                                    self._readCh.on('data', function(data, isNotification) {
                                        self._parseIncoming(data);
                                    });
                                    console.log("CB(" + self._id + "): connected!");
                                    self._init();
                                    if (callback) callback(true);
                                });
                            } catch(err3) {
                                btPeripheral.disconnect();
                                console.log("CB(" + self._id + "): exception while connecting: ", err3);
                                if (callback) callback(false);
                            }
                        } else {
                            console.log("CB(" + self._id + "): couldn't locate characteristics, disconnecting... ", err);
                            btPeripheral.disconnect();
                            if (callback) callback(false);
                        }
                    });
                } else {
                    console.log("CB(" + self._id + "): couldn't locate services, disconnecting... ", err2);
                    btPeripheral.disconnect();
                    if (callback) callback(false);
                }

            });
        }, 1000);

        btPeripheral.once('disconnect', function() {
            console.log("CB(" + self._id + "): disconnected");
            self._dev = null;
            self.connected = false;
            //clearInterval(self.statusIntervalHandle);
            self.emit("status", self.getStatus());
        });

    });
}

CB.prototype._init = function() {
    var self = this;
    self._writeCh.write(new Buffer("S\n"));
}

CB.prototype._parseIncoming = function(data) {
    if(data.length != 5) return;

    this._moving = data.readUInt8(0) & 0x01;
    this._position = data.readUInt32LE(1);

    console.log("CB(" + this._id + "): moving: ", this._moving, ", position:", this._position);
}

CB.prototype.connect = function(device, callback) {
    if (device && device.connect) {
        this._moving = false;
        console.log("CB(" + this._id + "): connecting...");
        this._connectBt(device, callback);
    } else {
        console.log("CB(" + this._id + "): invalid device, cannot connect");
        if (callback) callback("invalid device");
    }
}

CB.prototype.disconnect = function() {
    console.log("CB(" + this._id + "): disconnecting...");
    if (this._dev && this._dev.connected) {
        this.connected = false;
        this._dev.connected = false;
        this._dev.disconnect();
    } else {
        this._dev = null;
    }
    this.emit("status", this.getStatus());
}

CB.prototype.getStatus = function() {
    var type = (this._dev && this._dev.type) ? this._dev.type : null;
    return {
        connected: this._dev && this._dev.connected,
        connectionType: type,
        position: this._position / this._stepsPerUnit,
        backlash: this._backlash,
        moving: this._moving
    }
}

CB.prototype.disable = function(motor) {
    this._enabled = false;
}

CB.prototype.enable = function(motor) {
    this._enabled = true;
}

CB.prototype.move = function(motor, amount, callback) {
    if (this._moving) {
        if (callback) callback("CB(" + this._id + "): motor already running");
        return console.log("CB(" + this._id + "): motor already running");
    }

    var steps = Math.round(amount * this._stepsPerUnit);

    console.log("CB(" + this._id + "): moving motor", steps, "steps");
    if(!this._enabled) this.enable();

    this._moving = true;

    var self = this;
    self._writeCh.write('M' + steps.toString(), function(err) {
        self._moving = true;
        if (!err) {
            var n = 0;
            var check = function() {
                setTimeout(function() {
                    if(self._moving || self._moving === undefined) {
                        n++;
                        if(n > 500) {
                            console.log("CB(" + self._id + "): ERROR: timed out waiting for move");
                            if (callback) callback("timeout");
                            self._moving = false;
                        } else {
                            check(); // keep checking until stop
                        }
                    } else {
                        console.log("CB(" + self._id + "): position:", self._position);
                        if (callback) callback(null, self._position / self._stepsPerUnit);
                    }
                }, 300);
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}

CB.prototype.constantMove = function(motor, speed, callback) {
    console.log("CB(" + this._id + "): moving motor at speed ", speed, "%");
    if(!this._enabled) this.enable();

    var self = this;
    dataBuf.writeUInt16LE(speed ? 0x01 : 0x00, 1);
    self._moving = true;

    self._constantSpeed = speed;

    if(self._watchdog) {
        clearTimeout(self._watchdog);
        self._watchdog = null;
    }
    if(self._moveTimer) {
        clearTimeout(self._moveTimer);
        self._moveTimer = null;
    }
    if(speed) {
        self._watchdog = setTimeout(function(){
            console.log("CB(" + self._id + "): stopping via watchdog");
            self._constantSpeed = 0;
            clearTimeout(self._moveTimer);
            self._moveTimer = null;
        }, 3000);
    }

    var sendMove = function() {
        if(self._constantSpeed) {
            self.move(motor, self._constantSpeed, function() {
                if (callback) callback(null, self._position / self._stepsPerUnit);
                if(speed) {
                    self._moveTimer = setTimeout(function() {
                        sendMove();
                    }, 100);
                }
            });
        } else {
            if (callback) callback(null, self._position / self._stepsPerUnit);
        }
    }
    sendMove();
}

CB.prototype.resetMotorPosition = function(motor, callback) {
    this.setMotorPosition(motor, 0, callback);
}

CB.prototype.setMotorPosition = function(motor, position, callback) {
    var self = this;
    var check = function() {
        if(self._moving) {
            setTimeout(check, 200); // keep checking until stop
        } else {
            if(!position) position = 0;
            self._position = Math.round(position);
            self._writeCh.write('P' + self._position.toString());
            if (callback) callback();
        }
    }
    check();
}

CB.prototype.setMotorBacklash = function(motor, backlash, callback) {
    this._backlash = backlash;
    if (callback) callback(this._backlash);
}

CB.prototype.getMotorBacklash = function(motor, callback) {
    if (callback) callback(this._backlash);
}

module.exports = CB;
<commit_msg>motion testing<commit_after>var util = require('util');
var EventEmitter = require('events').EventEmitter;

function CB(id) {
    this.btServiceIds = ['ae0e019cef7511e981b42a2ae2dbcce4'];

    this._id = id;
    this._gmCh = null;
    this._dev = null;
    this._moving = false;
    this._position = 0;
    this._stepsPerUnit = 1;
    this._backlash = 0;
    this._lastDirection = 0;
}

util.inherits(CB, EventEmitter);

CB.prototype._connectBt = function(btPeripheral, callback) {
    var self = this;
    btPeripheral.connect(function(err1) {
        if (err1) {
            if (callback) callback(false);
            return;
        }
        console.log('CB(' + self._id + '): connecting via BLE');
        setTimeout(function(){
            btPeripheral.discoverServices(self.btServiceIds, function(err2, services) {
                if (services && services[0]) {
                    services[0].discoverCharacteristics([], function(err, characteristics) {
                        //console.log("characteristics:", characteristics);
                        self._writeCh = null;
                        self._readCh = null;
                        self._dev = null;
                        for (var i = 0; i < characteristics.length; i++) {
                            ch = characteristics[i];
                            //console.log("ch.uuid", ch.uuid);
                            console.log("ch", ch);
                            if (ch.uuid == "ae0e0408ef7511e981b42a2ae2dbcce4") {
                                self._writeCh = ch;
                            } else if (ch.uuid == "ae0e055cef7511e981b42a2ae2dbcce4") {
                                self._readCh = ch;
                            }
                        }
                        if (self._writeCh && self._readCh) {
                            try {
                                console.log("CB(" + self._id + "): subscribing...");
                                self._readCh.subscribe(function(){
                                    self._dev = btPeripheral;
                                    self._dev.connected = true;
                                    self.connected = true;
                                    self._dev.type = "bt";
                                    self._readCh.on('data', function(data, isNotification) {
                                        self._parseIncoming(data);
                                    });
                                    console.log("CB(" + self._id + "): connected!");
                                    self._init();
                                    if (callback) callback(true);
                                });
                            } catch(err3) {
                                btPeripheral.disconnect();
                                console.log("CB(" + self._id + "): exception while connecting: ", err3);
                                if (callback) callback(false);
                            }
                        } else {
                            console.log("CB(" + self._id + "): couldn't locate characteristics, disconnecting... ", err);
                            btPeripheral.disconnect();
                            if (callback) callback(false);
                        }
                    });
                } else {
                    console.log("CB(" + self._id + "): couldn't locate services, disconnecting... ", err2);
                    btPeripheral.disconnect();
                    if (callback) callback(false);
                }

            });
        }, 1000);

        btPeripheral.once('disconnect', function() {
            console.log("CB(" + self._id + "): disconnected");
            self._dev = null;
            self.connected = false;
            //clearInterval(self.statusIntervalHandle);
            self.emit("status", self.getStatus());
        });

    });
}

CB.prototype._init = function() {
    var self = this;
    self._writeCh.write(new Buffer("S\n"));
}

CB.prototype._parseIncoming = function(data) {
    if(data.length != 5) return;

    this._moving = data.readUInt8(0) & 0x01;
    this._position = data.readUInt32LE(1);

    console.log("CB(" + this._id + "): moving: ", this._moving, ", position:", this._position);
}

CB.prototype.connect = function(device, callback) {
    if (device && device.connect) {
        this._moving = false;
        console.log("CB(" + this._id + "): connecting...");
        this._connectBt(device, callback);
    } else {
        console.log("CB(" + this._id + "): invalid device, cannot connect");
        if (callback) callback("invalid device");
    }
}

CB.prototype.disconnect = function() {
    console.log("CB(" + this._id + "): disconnecting...");
    if (this._dev && this._dev.connected) {
        this.connected = false;
        this._dev.connected = false;
        this._dev.disconnect();
    } else {
        this._dev = null;
    }
    this.emit("status", this.getStatus());
}

CB.prototype.getStatus = function() {
    var type = (this._dev && this._dev.type) ? this._dev.type : null;
    return {
        connected: this._dev && this._dev.connected,
        connectionType: type,
        position: this._position / this._stepsPerUnit,
        backlash: this._backlash,
        moving: this._moving
    }
}

CB.prototype.disable = function(motor) {
    this._enabled = false;
}

CB.prototype.enable = function(motor) {
    this._enabled = true;
}

CB.prototype.move = function(motor, amount, callback) {
    if (this._moving) {
        if (callback) callback("CB(" + this._id + "): motor already running");
        return console.log("CB(" + this._id + "): motor already running");
    }

    var steps = Math.round(amount * this._stepsPerUnit);

    console.log("CB(" + this._id + "): moving motor", steps, "steps");
    if(!this._enabled) this.enable();

    this._moving = true;

    var self = this;
    self._writeCh.write('M' + steps.toString(), function(err) {
        self._moving = true;
        if (!err) {
            var n = 0;
            var check = function() {
                setTimeout(function() {
                    if(self._moving || self._moving === undefined) {
                        n++;
                        if(n > 500) {
                            console.log("CB(" + self._id + "): ERROR: timed out waiting for move");
                            if (callback) callback("timeout");
                            self._moving = false;
                        } else {
                            check(); // keep checking until stop
                        }
                    } else {
                        console.log("CB(" + self._id + "): position:", self._position);
                        if (callback) callback(null, self._position / self._stepsPerUnit);
                    }
                }, 300);
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}

CB.prototype.constantMove = function(motor, speed, callback) {
    console.log("CB(" + this._id + "): moving motor at speed ", speed, "%");
    if(!this._enabled) this.enable();

    var self = this;
    dataBuf.writeUInt16LE(speed ? 0x01 : 0x00, 1);
    self._moving = true;

    self._constantSpeed = speed;

    if(self._watchdog) {
        clearTimeout(self._watchdog);
        self._watchdog = null;
    }
    if(self._moveTimer) {
        clearTimeout(self._moveTimer);
        self._moveTimer = null;
    }
    if(speed) {
        self._watchdog = setTimeout(function(){
            console.log("CB(" + self._id + "): stopping via watchdog");
            self._constantSpeed = 0;
            clearTimeout(self._moveTimer);
            self._moveTimer = null;
        }, 3000);
    }

    var sendMove = function() {
        if(self._constantSpeed) {
            self.move(motor, self._constantSpeed, function() {
                if (callback) callback(null, self._position / self._stepsPerUnit);
                if(speed) {
                    self._moveTimer = setTimeout(function() {
                        sendMove();
                    }, 100);
                }
            });
        } else {
            if (callback) callback(null, self._position / self._stepsPerUnit);
        }
    }
    sendMove();
}

CB.prototype.resetMotorPosition = function(motor, callback) {
    this.setMotorPosition(motor, 0, callback);
}

CB.prototype.setMotorPosition = function(motor, position, callback) {
    var self = this;
    var check = function() {
        if(self._moving) {
            setTimeout(check, 200); // keep checking until stop
        } else {
            if(!position) position = 0;
            self._position = Math.round(position);
            self._writeCh.write('P' + self._position.toString());
            if (callback) callback();
        }
    }
    check();
}

CB.prototype.setMotorBacklash = function(motor, backlash, callback) {
    this._backlash = backlash;
    if (callback) callback(this._backlash);
}

CB.prototype.getMotorBacklash = function(motor, callback) {
    if (callback) callback(this._backlash);
}

module.exports = CB;
<|endoftext|>


<commit_before>#!/usr/bin/env node
require('babel-polyfill'); // eslint-disable-line import/no-unassigned-import

// npm modules
const core = require('@commitlint/core');
const chalk = require('chalk');
const meow = require('meow');
const {pick} = require('lodash');
const stdin = require('get-stdin');

const pkg = require('./package');
const help = require('./help');

/**
 * Behavioural rules
 */
const rules = {
	fromStdin: (input, flags) => input.length === 0 &&
		flags.from === null &&
		flags.to === null &&
		!flags.edit
};

const configuration = {
	string: ['from', 'to', 'extends'],
	boolean: ['edit', 'help', 'version', 'quiet', 'color'],
	alias: {
		c: 'color',
		e: 'edit',
		f: 'from',
		t: 'to',
		q: 'quiet',
		h: 'help',
		v: 'version',
		x: 'extends'
	},
	description: {
		color: 'toggle colored output',
		edit: 'read last commit message found in ./git/COMMIT_EDITMSG',
		extends: 'array of shareable configurations to extend',
		from: 'lower end of the commit range to lint; applies if edit=false',
		to: 'upper end of the commit range to lint; applies if edit=false',
		quiet: 'toggle console output'
	},
	default: {
		color: true,
		edit: false,
		from: null,
		to: null,
		quiet: false
	},
	unknown(arg) {
		throw new Error(`unknown flags: ${arg}`);
	}
};

const cli = meow({
	help: `[input] reads from stdin if --edit, --from and --to are omitted\n${help(configuration)}`,
	description: `${pkg.name}@${pkg.version} - ${pkg.description}`
}, configuration);

const load = seed => core.load(seed);

function main(options) {
	const {input: raw, flags} = options;
	const fromStdin = rules.fromStdin(raw, flags);

	const range = pick(flags, 'edit', 'from', 'to');
	const input = fromStdin ? stdin() : core.read(range);
	const fmt = new chalk.constructor({enabled: flags.color});

	return input
		.then(raw => Array.isArray(raw) ? raw : [raw])
		.then(messages => Promise.all(messages.map(commit => {
			return load(getSeed(flags))
				.then(opts => core.lint(commit, opts.rules))
				.then(report => {
					const formatted = core.format(report, {color: flags.color});

					if (!flags.quiet) {
						console.log(`${fmt.grey('⧗')}   input: ${fmt.bold(commit.split('\n')[0])}`);
						console.log(formatted.join('\n'));
					}

					if (report.errors.length > 0) {
						const error = new Error(formatted[formatted.length - 1]);
						error.type = pkg.name;
						throw error;
					}
					return console.log('');
				});
		})
	));
}

function getSeed({extends: e}) {
	return e ? {extends: e.split(', ')} : {};
}

// Start the engine
main(cli)
	.catch(err =>
		setTimeout(() => {
			if (err.type === pkg.name) {
				process.exit(1);
			}
			throw err;
		})
	);

// Catch unhandled rejections globally
process.on('unhandledRejection', (reason, promise) => {
	console.log('Unhandled Rejection at: Promise ', promise, ' reason: ', reason);
	throw reason;
});
<commit_msg>fix(cli): remove destructuring for node 4 support<commit_after>#!/usr/bin/env node
require('babel-polyfill'); // eslint-disable-line import/no-unassigned-import

// npm modules
const core = require('@commitlint/core');
const chalk = require('chalk');
const meow = require('meow');
const pick = require('lodash').pick;
const stdin = require('get-stdin');

const pkg = require('./package');
const help = require('./help');

/**
 * Behavioural rules
 */
const rules = {
	fromStdin: (input, flags) => input.length === 0 &&
		flags.from === null &&
		flags.to === null &&
		!flags.edit
};

const configuration = {
	string: ['from', 'to', 'extends'],
	boolean: ['edit', 'help', 'version', 'quiet', 'color'],
	alias: {
		c: 'color',
		e: 'edit',
		f: 'from',
		t: 'to',
		q: 'quiet',
		h: 'help',
		v: 'version',
		x: 'extends'
	},
	description: {
		color: 'toggle colored output',
		edit: 'read last commit message found in ./git/COMMIT_EDITMSG',
		extends: 'array of shareable configurations to extend',
		from: 'lower end of the commit range to lint; applies if edit=false',
		to: 'upper end of the commit range to lint; applies if edit=false',
		quiet: 'toggle console output'
	},
	default: {
		color: true,
		edit: false,
		from: null,
		to: null,
		quiet: false
	},
	unknown(arg) {
		throw new Error(`unknown flags: ${arg}`);
	}
};

const cli = meow({
	help: `[input] reads from stdin if --edit, --from and --to are omitted\n${help(configuration)}`,
	description: `${pkg.name}@${pkg.version} - ${pkg.description}`
}, configuration);

const load = seed => core.load(seed);

function main(options) {
	const {input: raw, flags} = options;
	const fromStdin = rules.fromStdin(raw, flags);

	const range = pick(flags, 'edit', 'from', 'to');
	const input = fromStdin ? stdin() : core.read(range);
	const fmt = new chalk.constructor({enabled: flags.color});

	return input
		.then(raw => Array.isArray(raw) ? raw : [raw])
		.then(messages => Promise.all(messages.map(commit => {
			return load(getSeed(flags))
				.then(opts => core.lint(commit, opts.rules))
				.then(report => {
					const formatted = core.format(report, {color: flags.color});

					if (!flags.quiet) {
						console.log(`${fmt.grey('⧗')}   input: ${fmt.bold(commit.split('\n')[0])}`);
						console.log(formatted.join('\n'));
					}

					if (report.errors.length > 0) {
						const error = new Error(formatted[formatted.length - 1]);
						error.type = pkg.name;
						throw error;
					}
					return console.log('');
				});
		})
	));
}

function getSeed({extends: e}) {
	return e ? {extends: e.split(', ')} : {};
}

// Start the engine
main(cli)
	.catch(err =>
		setTimeout(() => {
			if (err.type === pkg.name) {
				process.exit(1);
			}
			throw err;
		})
	);

// Catch unhandled rejections globally
process.on('unhandledRejection', (reason, promise) => {
	console.log('Unhandled Rejection at: Promise ', promise, ' reason: ', reason);
	throw reason;
});
<|endoftext|>


<commit_before>'use strict';

/* Services */
angular.module('webActivitiesApp.framework', [])

.factory("framework", [ '$q', function($q) {
	/**
	 * WebActivities global instance
	 */
	var webActivities = {};

	/*
	 * ======================================================================
	 * Internal methods
	 * ======================================================================
	 */

	var resolveUrl = function(app, path) {
		path = path.replace("%v", app.version);
		path = path.replace("%d", new Date().getTime());
		var src = path.indexOf("http") == 0 ? path : app.path + (path.indexOf("/") == 0 ? path : "/" + path);
		return src;
	};
	var composeActivityId = function(appId, activityId) {
		return appId + "@" + activityId;
	};
	var dirname = function(path) {
		return path.replace(/\\/g, '/').replace(/\/[^\/]*$/, '');
	};
	var resolveStartMode = function(mode) {
		for ( var i in webActivities.startMode) {
			if (i == mode) {
				return webActivities.startMode[i];
			}
		}
		return webActivities.startMode.UNKNOWN;
	};

	// Create a new context
	var createContext = function(stackItem, _closeDefer) {
		return new ActivityContext(webActivities, stackItem, _closeDefer, $q);
	};

	/*
	 * ======================================================================
	 * Internal variables
	 * ======================================================================
	 */
	var apps = {};
	var activities = {};
	var activityStack = new Stack();
	var listeners = {};
	var notifies = [];

	/*
	 * ======================================================================
	 * Public methods
	 * ======================================================================
	 */
	webActivities.status = {};
	webActivities.status.REGISTERED = 0;
	webActivities.status.STARTING = 2;
	webActivities.status.STARTED = 4;

	webActivities.activity = {};
	webActivities.activity.status = {};
	webActivities.activity.status.CREATED = 0;
	webActivities.activity.status.ACTIVE = 2;
	webActivities.activity.status.PAUSED = 4;
	webActivities.activity.status.STOPPED = 8;

	webActivities.bus = new Bus();

	webActivities.pushLayer = function(options) {
		return webActivities.broadcast("pushLayer", options || {});
	};

	webActivities.popLayer = function() {
		return webActivities.broadcast("popLayer", {});
	};

	webActivities.currentStack = function() {
		return activityStack;
	};

	webActivities.startMode = {};
	webActivities.startMode.CHILD = function(stackItem, options) {
		var d = $q.defer();
		$q.when(webActivities.pauseActivity({
			mode : 'hidden'
		})).then(function() {
			webActivities.currentStack().push(stackItem);
			d.resolve();
		});
		return d.promise;
	};
	webActivities.startMode.CHILD_POPUP = function(stackItem, options) {
		var d = $q.defer();
		$q.when(webActivities.pauseActivity({
			mode : 'visible'
		})).then(function() {
			webActivities.pushLayer(options).then(function() {
				stackItem.openMode = 'CHILD_POPUP';
				webActivities.currentStack().push(stackItem);
				d.resolve();
			});
		});
		return d.promise;
	};
	webActivities.startMode.ROOT = function(stackItem, options) {
		var d = $q.defer();
		$q.when(webActivities.stopAllActivities()).then(function() {
			webActivities.currentStack().push(stackItem);
			d.resolve();
		});
		return d.promise;
	};
	webActivities.startMode.UNKNOWN = function(stackItem) {
		var d = $q.defer();
		alert('Start mode unknown');
		return d.promise;
	};

	/* spostare su utils */
	webActivities.resolveUrl = resolveUrl;
	webActivities.dirname = dirname;
	webActivities.composeActivityId = composeActivityId;
	/* */

	webActivities.listApps = function() {
		return $.extend({}, apps);
	};

	webActivities.listNotifies = function() {
		return notifies.slice();
	};

	webActivities.removeNotify = function(index) {
		notifies.splice(index, 1);
	};

	webActivities.broadcast = function(type, parameters) {
		var promises = [];
		for ( var e in listeners[type]) {
			try {
				promises.push(listeners[type][e](type, parameters));
			} catch (ex) {
				Logger.error(ex);
			}
		}
		return $q.all(promises);
	};

	webActivities.on = function(l, fn) {
		if (!$.isArray(listeners[l])) {
			listeners[l] = [];
		}
		listeners[l].push(fn);
	};

	webActivities.sendMessage = function(source, msg) {
		var items = webActivities.currentStack().getAll();
		var i = 0;
		for (i in items) {
			var item = items[i];
			var ls = item.context.getMessageListeners();
			var l = 0;
			for (l in ls) {
				if ($.isFunction(ls[l])) {
					ls[l](source, msg);
				}
			}
		}
	};

	webActivities.notify = function(type, message, options) {
		notifies.push({
			type : type,
			message : message,
			options : options
		});
		return webActivities.broadcast("showNotify", {
			type : type,
			message : message,
			options : options
		});
	};

	webActivities.installApp = function(appDefinitionUrl) {
		$.getJSON(appDefinitionUrl).done(function(appDefinition) {

			var application = new Application(webActivities, appDefinition, appDefinitionUrl);
			$.each(application.activities, function(i, activity) {
				activities[activity.id] = activity;
			});

			apps[application.id] = application;
			webActivities.broadcast('appInstalled', application);

		}).fail(function(a, e) {
			Logger.error("Unable to register application <" + appDefinitionUrl + "> " + e);
		});
	};

	webActivities.startApp = function(appId, preventStartActivity, callback) {
		var app = apps[appId];
		if (!app) {
			Logger.error("The application <" + appId + "> doesn't exists");
		} else if (app.status == webActivities.status.REGISTERED) {
			webActivities.broadcast('appStarting', app);
			app.status = webActivities.status.STARTING;
			var resourcesIncluded = "";
			if ($.isArray(app.resources)) {
				$.each(app.resources, function(index, value) {
					resourcesIncluded += "<script src='" + resolveUrl(app, value) + "' type='application/javascript'><\/script>";
				});
			}
			var iframe = $('<iframe />', {
				style : "border: 0; width: 0; height: 0"
			}).appendTo($("#app-class-loader"));
			var doc = iframe[0].contentWindow.window.document;
			doc.open();
			doc.write("<script type=\"text/javascript\">var top = null; var opener = null; var parent = null; window.opener = null; window.parent = null;</script>" + resourcesIncluded);
			doc.close();

			app.iframe = iframe;
			iframe.load(function() {
				app.status = webActivities.status.STARTED;
				webActivities.broadcast('appStarted', $.extend({}, app));
				if (!preventStartActivity) {
					webActivities.startMainActivity(appId);
				}
				if (callback) {
					callback(app);
				}
			});
		} else if (app.status == webActivities.status.STARTING) {
			// do nothing... wait for start
		} else if (app.status == webActivities.status.STARTED) {
			if (!preventStartActivity) {
				webActivities.startMainActivity(appId);
			}
		}
	};

	webActivities.startMainActivity = function(appId) {
		var app = apps[appId];
		if (!app) {
			Logger.error("The application <" + appId + "> doesn't exists");
		} else if (app.status != webActivities.status.STARTED) {
			Logger.error("The application <" + appId + "> isn't started");
		} else if (!app.main) {
			Logger.log("The application <" + appId + "> not have a main activity");
		} else {
			webActivities.startActivity(app.main, appId, null, webActivities.startMode.ROOT);
		}
	};

	webActivities.getCurrentActivity = function() {
		return webActivities.currentStack().peek();
	};

	webActivities.getActivityStack = function() {
		return webActivities.currentStack().getAll();
	};

	webActivities.pauseActivity = function(options) {
		var d = $q.defer();
		var item = webActivities.currentStack().peek();
		if (item == null) {
			d.resolve();
		} else {
			var context = item.context;
			$q.when(context.getPause()()).then(function() {
				item.status = webActivities.activity.status.PAUSED;
				if (options.mode == 'hidden') {
					webActivities.broadcast('hideActivity', {
						view : item.iframe,
						activity : item.activity
					}).then(function() {
						d.resolve();
					});
				} else if (options.mode == 'visible') {
					d.resolve();
				}
				;
			});
		}
		return d.promise;
	};

	webActivities.resumeActivity = function(previousStackItem, disableEffects) {
		var d = $q.defer();
		var item = webActivities.currentStack().peek();
		if (item == null) {
			d.resolve();
		} else {
			var context = item.context;
			$q.when(context.getResume()()).then(function() {
				item.status = webActivities.activity.status.ACTIVE;
				webActivities.broadcast('displayActivity', {
					view : item.iframe,
					activity : item.activity,
					disableEffects : disableEffects
				}).then(function() {
					d.resolve();
				});
			});
		}
		return d.promise;
	};

	webActivities.stopActivity = function() {
		var d = $q.defer();
		var item = webActivities.currentStack().peek();
		if (item == null) {
			d.resolve();
		} else {
			var context = item.context;
			$q.when(context.getStop()()).then(function() {
				var item = webActivities.currentStack().pop();
				item.status = webActivities.activity.status.STOPPED;
				webActivities.broadcast('destroyActivity', {
					view : item.iframe,
					activity : item.activity
				}).then(function() {
					var q = null;
					var disableEffects = false;
					if (item.openMode == 'CHILD_POPUP') {
						q = webActivities.popLayer();
						disableEffects = true;
					}
					$q.when(q).then(function() {
						$q.when(webActivities.resumeActivity(item, disableEffects)).then(function() {
							item.context.getCloseDefer().resolve(item.context.getResult());
							d.resolve();
						});
					});

				});

			});
		}
		return d.promise;
	};

	webActivities.stopAllPopupActivities = function() {
		var d = $q.defer();
		var stop = function() {
			var item = webActivities.currentStack().peek();
			$q.when(webActivities.stopActivity()).then(function() {
				if (webActivities.currentStack().getCount() > 0 && item.openMode != 'CHILD_POPUP') {
					stop();
				} else {
					d.resolve();
				}
			});
		};
		stop();
		return d.promise;
	};

	webActivities.stopAllActivities = function() {
		var d = $q.defer();
		var stop = function() {
			$q.when(webActivities.stopActivity()).then(function() {
				if (webActivities.currentStack().getCount() > 0) {
					stop();
				} else {
					d.resolve();
				}
			});
		};
		stop();
		return d.promise;
	};

	webActivities.selectActivityForIntent = function(intent) {
		var matchings = [];
		$.each(activities, function(i, a) {
			if ($.isArray(a.intentFilters)) {
				$.each(a.intentFilters, function(x, f) {
					if (f == intent.intentType) {
						matchings.push(a);
						return false;
					}
				});
			}
		});

		if (matchings.length == 1) {
			return $q.when(matchings[0]);
		}
		if (matchings.length > 0) {
			return webActivities.broadcast("makeUserSelectOneActivity", {
				activities : matchings
			}).then(function(results) {
				return results[0];
			});
		}
		return $q.reject();
	};

	webActivities.startActivity = function(activityId, appId, parameters, startMode, startOptions, closeDefer) {

		if (closeDefer == null) {
			closeDefer = $q.defer();
		}

		var activity = activities[composeActivityId(appId, activityId)];

		if (activity == null) {
			Logger.error("Activity <" + activityId + "> in app <" + appId + "> not found");
		} else {
			var app = apps[activity.app];
			if (app == null) {
				Logger.error("Application <" + activity.app + "> is not installed");
			} else if (app.status == webActivities.status.REGISTERED) {
				webActivities.startApp(activity.app, true, function(app) {
					webActivities.startActivity(activityId, appId, parameters, startMode, startOptions, closeDefer);
				});
			} else {

				var stackItem = {
					activity : activity,
					iframe : null,
					context : null,
					instance : null,
					status : null
				};

				webActivities.broadcast('activityStarting', $.extend({}, activity));
				stackItem.context = createContext(stackItem, closeDefer);

				startMode(stackItem, startOptions).then(function(activity, stackItem) {
					return function() {
						// Run the app
						stackItem.status = webActivities.activity.status.CREATED;
						stackItem.instance = new app.iframe[0].contentWindow.window[activity.activator](stackItem.context, parameters);
						webActivities.broadcast('activityStarted', $.extend({}, activity));
					};
				}(activity, stackItem));
			}

		}
	};

	webActivities.executeIntent = function(intent, startOptions) {
		var q = $q.defer();
		if (intent.intentType == IntentType.START_ACTIVITY) {
			if (intent.app && intent.activity) {
				webActivities.startActivity(intent.activity, intent.app, intent.parameters, resolveStartMode(intent.startMode), startOptions, q);
			}
		} else {
			if (intent.intentType) {
				webActivities.selectActivityForIntent(intent).then(function(act) {
					webActivities.startActivity(act.id, act.app, intent.parameters, resolveStartMode(intent.startMode), startOptions, q);
				});
			}
		}
		return q.promise;
	};

	return webActivities;
} ])

//
;

<commit_msg>Corretto errore su scelta multipla<commit_after>'use strict';

/* Services */
angular.module('webActivitiesApp.framework', [])

.factory("framework", [ '$q', function($q) {
	/**
	 * WebActivities global instance
	 */
	var webActivities = {};

	/*
	 * ======================================================================
	 * Internal methods
	 * ======================================================================
	 */

	var resolveUrl = function(app, path) {
		path = path.replace("%v", app.version);
		path = path.replace("%d", new Date().getTime());
		var src = path.indexOf("http") == 0 ? path : app.path + (path.indexOf("/") == 0 ? path : "/" + path);
		return src;
	};
	var composeActivityId = function(appId, activityId) {
		return appId + "@" + activityId;
	};
	var dirname = function(path) {
		return path.replace(/\\/g, '/').replace(/\/[^\/]*$/, '');
	};
	var resolveStartMode = function(mode) {
		for ( var i in webActivities.startMode) {
			if (i == mode) {
				return webActivities.startMode[i];
			}
		}
		return webActivities.startMode.UNKNOWN;
	};

	// Create a new context
	var createContext = function(stackItem, _closeDefer) {
		return new ActivityContext(webActivities, stackItem, _closeDefer, $q);
	};

	/*
	 * ======================================================================
	 * Internal variables
	 * ======================================================================
	 */
	var apps = {};
	var activities = {};
	var activityStack = new Stack();
	var listeners = {};
	var notifies = [];

	/*
	 * ======================================================================
	 * Public methods
	 * ======================================================================
	 */
	webActivities.status = {};
	webActivities.status.REGISTERED = 0;
	webActivities.status.STARTING = 2;
	webActivities.status.STARTED = 4;

	webActivities.activity = {};
	webActivities.activity.status = {};
	webActivities.activity.status.CREATED = 0;
	webActivities.activity.status.ACTIVE = 2;
	webActivities.activity.status.PAUSED = 4;
	webActivities.activity.status.STOPPED = 8;

	webActivities.bus = new Bus();

	webActivities.pushLayer = function(options) {
		return webActivities.broadcast("pushLayer", options || {});
	};

	webActivities.popLayer = function() {
		return webActivities.broadcast("popLayer", {});
	};

	webActivities.currentStack = function() {
		return activityStack;
	};

	webActivities.startMode = {};
	webActivities.startMode.CHILD = function(stackItem, options) {
		var d = $q.defer();
		$q.when(webActivities.pauseActivity({
			mode : 'hidden'
		})).then(function() {
			webActivities.currentStack().push(stackItem);
			d.resolve();
		});
		return d.promise;
	};
	webActivities.startMode.CHILD_POPUP = function(stackItem, options) {
		var d = $q.defer();
		$q.when(webActivities.pauseActivity({
			mode : 'visible'
		})).then(function() {
			webActivities.pushLayer(options).then(function() {
				stackItem.openMode = 'CHILD_POPUP';
				webActivities.currentStack().push(stackItem);
				d.resolve();
			});
		});
		return d.promise;
	};
	webActivities.startMode.ROOT = function(stackItem, options) {
		var d = $q.defer();
		$q.when(webActivities.stopAllActivities()).then(function() {
			webActivities.currentStack().push(stackItem);
			d.resolve();
		});
		return d.promise;
	};
	webActivities.startMode.UNKNOWN = function(stackItem) {
		var d = $q.defer();
		alert('Start mode unknown');
		return d.promise;
	};

	/* spostare su utils */
	webActivities.resolveUrl = resolveUrl;
	webActivities.dirname = dirname;
	webActivities.composeActivityId = composeActivityId;
	/* */

	webActivities.listApps = function() {
		return $.extend({}, apps);
	};

	webActivities.listNotifies = function() {
		return notifies.slice();
	};

	webActivities.removeNotify = function(index) {
		notifies.splice(index, 1);
	};

	webActivities.broadcast = function(type, parameters) {
		var promises = [];
		for ( var e in listeners[type]) {
			try {
				promises.push(listeners[type][e](type, parameters));
			} catch (ex) {
				Logger.error(ex);
			}
		}
		return $q.all(promises);
	};

	webActivities.on = function(l, fn) {
		if (!$.isArray(listeners[l])) {
			listeners[l] = [];
		}
		listeners[l].push(fn);
	};

	webActivities.sendMessage = function(source, msg) {
		var items = webActivities.currentStack().getAll();
		var i = 0;
		for (i in items) {
			var item = items[i];
			var ls = item.context.getMessageListeners();
			var l = 0;
			for (l in ls) {
				if ($.isFunction(ls[l])) {
					ls[l](source, msg);
				}
			}
		}
	};

	webActivities.notify = function(type, message, options) {
		notifies.push({
			type : type,
			message : message,
			options : options
		});
		return webActivities.broadcast("showNotify", {
			type : type,
			message : message,
			options : options
		});
	};

	webActivities.installApp = function(appDefinitionUrl) {
		$.getJSON(appDefinitionUrl).done(function(appDefinition) {

			var application = new Application(webActivities, appDefinition, appDefinitionUrl);
			$.each(application.activities, function(i, activity) {
				activities[activity.id] = activity;
			});

			apps[application.id] = application;
			webActivities.broadcast('appInstalled', application);

		}).fail(function(a, e) {
			Logger.error("Unable to register application <" + appDefinitionUrl + "> " + e);
		});
	};

	webActivities.startApp = function(appId, preventStartActivity, callback) {
		var app = apps[appId];
		if (!app) {
			Logger.error("The application <" + appId + "> doesn't exists");
		} else if (app.status == webActivities.status.REGISTERED) {
			webActivities.broadcast('appStarting', app);
			app.status = webActivities.status.STARTING;
			var resourcesIncluded = "";
			if ($.isArray(app.resources)) {
				$.each(app.resources, function(index, value) {
					resourcesIncluded += "<script src='" + resolveUrl(app, value) + "' type='application/javascript'><\/script>";
				});
			}
			var iframe = $('<iframe />', {
				style : "border: 0; width: 0; height: 0"
			}).appendTo($("#app-class-loader"));
			var doc = iframe[0].contentWindow.window.document;
			doc.open();
			doc.write("<script type=\"text/javascript\">var top = null; var opener = null; var parent = null; window.opener = null; window.parent = null;</script>" + resourcesIncluded);
			doc.close();

			app.iframe = iframe;
			iframe.load(function() {
				app.status = webActivities.status.STARTED;
				webActivities.broadcast('appStarted', $.extend({}, app));
				if (!preventStartActivity) {
					webActivities.startMainActivity(appId);
				}
				if (callback) {
					callback(app);
				}
			});
		} else if (app.status == webActivities.status.STARTING) {
			// do nothing... wait for start
		} else if (app.status == webActivities.status.STARTED) {
			if (!preventStartActivity) {
				webActivities.startMainActivity(appId);
			}
		}
	};

	webActivities.startMainActivity = function(appId) {
		var app = apps[appId];
		if (!app) {
			Logger.error("The application <" + appId + "> doesn't exists");
		} else if (app.status != webActivities.status.STARTED) {
			Logger.error("The application <" + appId + "> isn't started");
		} else if (!app.main) {
			Logger.log("The application <" + appId + "> not have a main activity");
		} else {
			webActivities.startActivity(app.main, appId, null, webActivities.startMode.ROOT);
		}
	};

	webActivities.getCurrentActivity = function() {
		return webActivities.currentStack().peek();
	};

	webActivities.getActivityStack = function() {
		return webActivities.currentStack().getAll();
	};

	webActivities.pauseActivity = function(options) {
		var d = $q.defer();
		var item = webActivities.currentStack().peek();
		if (item == null) {
			d.resolve();
		} else {
			var context = item.context;
			$q.when(context.getPause()()).then(function() {
				item.status = webActivities.activity.status.PAUSED;
				if (options.mode == 'hidden') {
					webActivities.broadcast('hideActivity', {
						view : item.iframe,
						activity : item.activity
					}).then(function() {
						d.resolve();
					});
				} else if (options.mode == 'visible') {
					d.resolve();
				}
				;
			});
		}
		return d.promise;
	};

	webActivities.resumeActivity = function(previousStackItem, disableEffects) {
		var d = $q.defer();
		var item = webActivities.currentStack().peek();
		if (item == null) {
			d.resolve();
		} else {
			var context = item.context;
			$q.when(context.getResume()()).then(function() {
				item.status = webActivities.activity.status.ACTIVE;
				webActivities.broadcast('displayActivity', {
					view : item.iframe,
					activity : item.activity,
					disableEffects : disableEffects
				}).then(function() {
					d.resolve();
				});
			});
		}
		return d.promise;
	};

	webActivities.stopActivity = function() {
		var d = $q.defer();
		var item = webActivities.currentStack().peek();
		if (item == null) {
			d.resolve();
		} else {
			var context = item.context;
			$q.when(context.getStop()()).then(function() {
				var item = webActivities.currentStack().pop();
				item.status = webActivities.activity.status.STOPPED;
				webActivities.broadcast('destroyActivity', {
					view : item.iframe,
					activity : item.activity
				}).then(function() {
					var q = null;
					var disableEffects = false;
					if (item.openMode == 'CHILD_POPUP') {
						q = webActivities.popLayer();
						disableEffects = true;
					}
					$q.when(q).then(function() {
						$q.when(webActivities.resumeActivity(item, disableEffects)).then(function() {
							item.context.getCloseDefer().resolve(item.context.getResult());
							d.resolve();
						});
					});

				});

			});
		}
		return d.promise;
	};

	webActivities.stopAllPopupActivities = function() {
		var d = $q.defer();
		var stop = function() {
			var item = webActivities.currentStack().peek();
			$q.when(webActivities.stopActivity()).then(function() {
				if (webActivities.currentStack().getCount() > 0 && item.openMode != 'CHILD_POPUP') {
					stop();
				} else {
					d.resolve();
				}
			});
		};
		stop();
		return d.promise;
	};

	webActivities.stopAllActivities = function() {
		var d = $q.defer();
		var stop = function() {
			$q.when(webActivities.stopActivity()).then(function() {
				if (webActivities.currentStack().getCount() > 0) {
					stop();
				} else {
					d.resolve();
				}
			});
		};
		stop();
		return d.promise;
	};

	webActivities.selectActivityForIntent = function(intent) {
		var matchings = [];
		$.each(activities, function(i, a) {
			if ($.isArray(a.intentFilters)) {
				$.each(a.intentFilters, function(x, f) {
					if (f == intent.intentType) {
						matchings.push(a);
						return false;
					}
				});
			}
		});

		if (matchings.length == 1) {
			return $q.when(matchings[0]);
		}
		if (matchings.length > 0) {
			return webActivities.broadcast("makeUserSelectOneActivity", {
				activities : matchings
			}).then(function(results) {
				return results[0];
			});
		}
		return $q.reject();
	};

	webActivities.startActivity = function(activityId, appId, parameters, startMode, startOptions, closeDefer) {

		if (closeDefer == null) {
			closeDefer = $q.defer();
		}

		var activity = activities[composeActivityId(appId, activityId)];

		if (activity == null) {
			Logger.error("Activity <" + activityId + "> in app <" + appId + "> not found");
		} else {
			var app = apps[activity.app];
			if (app == null) {
				Logger.error("Application <" + activity.app + "> is not installed");
			} else if (app.status == webActivities.status.REGISTERED) {
				webActivities.startApp(activity.app, true, function(app) {
					webActivities.startActivity(activityId, appId, parameters, startMode, startOptions, closeDefer);
				});
			} else {

				var stackItem = {
					activity : activity,
					iframe : null,
					context : null,
					instance : null,
					status : null
				};

				webActivities.broadcast('activityStarting', $.extend({}, activity));
				stackItem.context = createContext(stackItem, closeDefer);

				startMode(stackItem, startOptions).then(function(activity, stackItem) {
					return function() {
						// Run the app
						stackItem.status = webActivities.activity.status.CREATED;
						stackItem.instance = new app.iframe[0].contentWindow.window[activity.activator](stackItem.context, parameters);
						webActivities.broadcast('activityStarted', $.extend({}, activity));
					};
				}(activity, stackItem));
			}

		}
	};

	webActivities.executeIntent = function(intent, startOptions) {
		var q = $q.defer();
		if (intent.intentType == IntentType.START_ACTIVITY) {
			if (intent.app && intent.activity) {
				webActivities.startActivity(intent.activity, intent.app, intent.parameters, resolveStartMode(intent.startMode), startOptions, q);
			}
		} else {
			if (intent.intentType) {
				webActivities.selectActivityForIntent(intent).then(function(act) {
					webActivities.startActivity(act.name, act.app, intent.parameters, resolveStartMode(intent.startMode), startOptions, q);
				});
			}
		}
		return q.promise;
	};

	return webActivities;
} ])

//
;

<|endoftext|>


<commit_before>function  PersonObject(YearOfBirth, Sex)
{
	//Active
	this.Active=0;
	//Sex
	this.Sex=-1;
	//Alive
	this.Alive=1;
	this.Birth=0;
	this.Death=3E9;
	this.GeneralDeath=3E9;
	this.IDUDeath=3E9;
	this.HCVDeath=3E9;
	this.HIVDeath=3E9;
	//Location
	this.location=new EventVector;
	//Alcohol
	this.Alcohol=3E9;//Date of alcoholism (increases linearly with time, probability

	this.HCV = new HCVObject(YearOfBirth);//may need to declare this in function

	//this.HIV = new HCVObject();
	this.HIV={};
	this.HIV.Infected=false;
	this.HIV.Time=0;
	this.HIV.Treatment=false;
	//this.IDU
	this.IDU={};

	//QALY
	//this.QualityCalculation=function(time){(this.HCV, this.IDU, this.HIV, this.Age, time);}//
	//this.QALY(this.HCV, this.IDU, this.HIV, this.Age)//

	//Simulate general mortality

}

PersonObject.prototype.Age= function (Year){//using prototyping for speed
	return Year-this.YearOfBirth;
};
<commit_msg>Add comment<commit_after>function  PersonObject(YearOfBirth, Sex)
{
	//Active
	this.Active=0;
	//Sex
	this.Sex=-1;
	//Alive
	this.Alive=1;
	this.Birth=0;
	this.Death=3E9;
	this.GeneralDeath=3E9;
	this.IDUDeath=3E9;
	this.HCVDeath=3E9;
	this.HIVDeath=3E9;
	//Location
	this.location=new EventVector;
	//Alcohol
	this.Alcohol=3E9;//Date of alcoholism (increases linearly with time, probability

	this.HCV = new HCVObject(YearOfBirth);//may need to declare this in function to reduce the size of the memory footprint

	//this.HIV = new HCVObject();
	this.HIV={};
	this.HIV.Infected=false;
	this.HIV.Time=0;
	this.HIV.Treatment=false;
	//this.IDU
	this.IDU={};

	//QALY
	//this.QualityCalculation=function(time){(this.HCV, this.IDU, this.HIV, this.Age, time);}//
	//this.QALY(this.HCV, this.IDU, this.HIV, this.Age)//

	//Simulate general mortality

}

PersonObject.prototype.Age= function (Year){//using prototyping for speed
	return Year-this.YearOfBirth;
};
<|endoftext|>


<commit_before>(function () {
  function mailtoLink(to, options) {
    var result = ['mailto:'];

    if (isString(to)) {
      result.push(to);
    } else if (Array.isArray(to)) {
      result.push(to.join(','));
    } else {
      options = to;
    }

    var queryString = [];
    options = options || {};
    if (options.subject) {
      queryString.push('subject=' + encodeURIComponent(options.subject));
    }
    if (options.cc) {
      queryString.push('cc=' + options.cc);
    }
    if (options.bcc) {
      queryString.push('bcc=' + options.bcc);
    }
    if (options.body) {
      queryString.push('body=' + encodeURIComponent(options.body).replace(/%0A/g, '%0D%0A'));
    }

    if (queryString.length) {
      result.push('?', queryString.join('&'));
    }

    return result.join('');
  }

  function isString(value) {
    return Object.prototype.toString.call(value) === '[object String]';
  }

  if (typeof module !== 'undefined') {
    module.exports = mailtoLink;
  } else {
    this.mailtoLink = mailtoLink;
  }
})();
<commit_msg>Take advantage of JS string coercion for To: arrays<commit_after>(function () {
  function mailtoLink(to, options) {
    var result = ['mailto:'];

    if (isString(to) || Array.isArray(to)) {
      result.push(to);
    } else {
      options = to;
    }

    var queryString = [];
    options = options || {};
    if (options.subject) {
      queryString.push('subject=' + encodeURIComponent(options.subject));
    }
    if (options.cc) {
      queryString.push('cc=' + options.cc);
    }
    if (options.bcc) {
      queryString.push('bcc=' + options.bcc);
    }
    if (options.body) {
      queryString.push('body=' + encodeURIComponent(options.body).replace(/%0A/g, '%0D%0A'));
    }

    if (queryString.length) {
      result.push('?', queryString.join('&'));
    }

    return result.join('');
  }

  function isString(value) {
    return Object.prototype.toString.call(value) === '[object String]';
  }

  if (typeof module !== 'undefined') {
    module.exports = mailtoLink;
  } else {
    this.mailtoLink = mailtoLink;
  }
})();
<|endoftext|>


<commit_before>var nodegit = require("../");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
var path = "/tmp/nodegit-github-2factor-demo";

var token = "{Your GitHub user token}";
var repoOwner = "{The orgname or username that owns the repo}";
var repoName = "{The name of the repo}";

// To clone with 2 factor auth enabled, you have to use a github oauth token
// over https, it can't be done with actual 2 factor.
// https://github.com/blog/1270-easier-builds-and-deployments-using-git-over-https-and-oauth

// The token has to be included in the URL if the repo is private.
// Otherwise, github just wont respond, so a normal credential callback
// wont work.
var repoUrl = "https://" + token +
  ":-oauth-basic@github.com/" +
  repoOwner + "/" +
  repoName + ".git";

var opts = { ignoreCertErrors: 1};

// If the repo is public, you can use a callback instead
var repoUrl = "https://github.com/" + repoOwner + "/" + repoName + ".git";

var opts = {
  remoteCallbacks: {
    credentials: function() {
      return nodegit.Cred.userpassPlaintextNew (token, "x-oauth-basic");
    },
    certificateCheck: function() {
      return 1;
    }
  }
};

fse.remove(path).then(function() {
  nodegit.Clone(repoUrl, path, opts)
    .done(function(repo) {
      if (repo instanceof nodegit.Repository) {
        console.info("We cloned the repo!");
      }
      else {
        console.error("Something borked :(");
      }
    });
});
<commit_msg>Update cloneFromGithubWith2Factor.js<commit_after>var nodegit = require("../");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
var path = "/tmp/nodegit-github-2factor-demo";

var token = "{Your GitHub user token}";
var repoOwner = "{The orgname or username that owns the repo}";
var repoName = "{The name of the repo}";

// To clone with 2 factor auth enabled, you have to use a github oauth token
// over https, it can't be done with actual 2 factor.
// https://github.com/blog/1270-easier-builds-and-deployments-using-git-over-https-and-oauth

// The token has to be included in the URL if the repo is private.
// Otherwise, github just wont respond, so a normal credential callback
// wont work.
var repoUrl = "https://" + token +
  ":-oauth-basic@github.com/" +
  repoOwner + "/" +
  repoName + ".git";

// If the repo is public, you can use a callback instead
var repoUrl = "https://github.com/" + repoOwner + "/" + repoName + ".git";

var opts = {
  remoteCallbacks: {
    credentials: function() {
      return nodegit.Cred.userpassPlaintextNew (token, "x-oauth-basic");
    },
    certificateCheck: function() {
      return 1;
    }
  }
};

fse.remove(path).then(function() {
  nodegit.Clone(repoUrl, path, opts)
    .done(function(repo) {
      if (repo instanceof nodegit.Repository) {
        console.info("We cloned the repo!");
      }
      else {
        console.error("Something borked :(");
      }
    });
});
<|endoftext|>