<commit_before>// Generated on 2015-02-05 using generator-angular 0.11.0
'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',
    dist: 'dist'
  };

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

    // Project settings
    yeoman: appConfig,

    ngconstant: {
      options: {
        space: '  ',
        wrap: '"use strict";\n\n {%= __ngModule %}',
        name: 'config'
      },
      // Environment targets
      development: {
        options: {
          dest: '<%= yeoman.app %>/scripts/config.js'
        },
        constants: {
          ENV: {
            REGISTRY_API_ENDPOINT: 'https://index.docker.io',
            LORRY_API_ENDPOINT: 'http://localhost:9292'
          }
        }
      },
      production: {
        options: {
          dest: '.tmp/scripts/config.js'
        },
        constants: {
          ENV: {
            REGISTRY_API_ENDPOINT: 'https://index.docker.io',
            LORRY_API_ENDPOINT: process.env.LORRY_API_ENDPOINT
          }
        }
      }
    },

    // 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', '<%= yeoman.app %>/scripts/directives/**/*.html'],
        tasks: ['html2js', 'newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', '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
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      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'),
        ignores: ['<%= yeoman.app %>/scripts/FileSaver.js']
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

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

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      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}}\','
              }
            }
          }
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          sourcemap: true
        }
      }
    },

    // 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}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // pre-process angular templates
    html2js: {
      options: {
        base: 'app',
        rename: function (moduleName) {
          return '/' + moduleName;
        },
        useStrict: true,
        quoteChar: '\'',
        module: 'directive-templates'
      },
      dist: {
        src: [ '<%= yeoman.app %>/scripts/directives/**/*.html' ],
        dest: '<%= yeoman.app %>/scripts/directives/templates.js'
      }
    },

    // 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', 'uglifyjs'],
              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'
        ]
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    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', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

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

    // 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',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

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

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

  grunt.registerTask('configure', 'build the app.js with template config', function (target) {
    grunt.task.run(['template:' + target]);
  });

  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',
      'ngconstant:development',
      'wiredep',
      'html2js',
      'concurrent:server',
      'autoprefixer',
      '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',
    'ngconstant:development',
    'wiredep:test',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'html2js',
    'karma'
  ]);

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

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>fixing broken deploy...again<commit_after>// Generated on 2015-02-05 using generator-angular 0.11.0
'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',
    dist: 'dist'
  };

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

    // Project settings
    yeoman: appConfig,

    ngconstant: {
      options: {
        space: '  ',
        wrap: '"use strict";\n\n {%= __ngModule %}',
        name: 'config'
      },
      // Environment targets
      development: {
        options: {
          dest: '<%= yeoman.app %>/scripts/config.js'
        },
        constants: {
          ENV: {
            REGISTRY_API_ENDPOINT: 'https://index.docker.io',
            LORRY_API_ENDPOINT: 'http://localhost:9292'
          }
        }
      },
      production: {
        options: {
          dest: '.tmp/scripts/config.js'
        },
        constants: {
          ENV: {
            REGISTRY_API_ENDPOINT: 'https://index.docker.io',
            LORRY_API_ENDPOINT: process.env.LORRY_API_ENDPOINT
          }
        }
      }
    },

    // 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', '<%= yeoman.app %>/scripts/directives/**/*.html'],
        tasks: ['html2js', 'newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', '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
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      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'),
        ignores: ['<%= yeoman.app %>/scripts/FileSaver.js']
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

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

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      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}}\','
              }
            }
          }
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          sourcemap: true
        }
      }
    },

    // 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}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // pre-process angular templates
    html2js: {
      options: {
        base: 'app',
        rename: function (moduleName) {
          return '/' + moduleName;
        },
        useStrict: true,
        quoteChar: '\'',
        module: 'directive-templates'
      },
      dist: {
        src: [ '<%= yeoman.app %>/scripts/directives/**/*.html' ],
        dest: '<%= yeoman.app %>/scripts/directives/templates.js'
      }
    },

    // 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', 'uglifyjs'],
              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'
        ]
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    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', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

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

    // 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',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

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

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

  grunt.registerTask('configure', 'build the app.js with template config', function (target) {
    grunt.task.run(['template:' + target]);
  });

  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',
      'ngconstant:development',
      'wiredep',
      'html2js',
      'concurrent:server',
      'autoprefixer',
      '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',
    'ngconstant:development',
    'wiredep:test',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'html2js',
    'karma'
  ]);

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

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>const Build = require('github-build')

const data = {
  repo: process.env.TRAVIS_REPO_SLUG,
  sha: process.env.TRAVIS_PULL_REQUEST_SHA,
  token: process.env.github_token,
  label: 'perfbench',
  description: 'Running performance tests'
}
console.log(data)

const build = new Build(data)

let pass = () => {} // noop
let fail = () => process.exit(1)

/* If github token is given and we have commit sha */
if (process.env.github_token && process.env.TRAVIS_PULL_REQUEST_SHA) {
  build.start()
  pass = () => build.pass('Performance check passed 🚀')
  fail = () => build.fail('Performance check failed')
}

module.exports = { pass, fail }
<commit_msg>works without messageS?<commit_after>const Build = require('github-build')

const data = {
  repo: process.env.TRAVIS_REPO_SLUG,
  sha: process.env.TRAVIS_PULL_REQUEST_SHA,
  token: process.env.github_token,
  label: 'perfbench',
  description: 'Running performance tests'
}
console.log(data)

const build = new Build(data)

let pass = () => {} // noop
let fail = () => process.exit(1)

/* If github token is given and we have commit sha */
if (process.env.github_token && process.env.TRAVIS_PULL_REQUEST_SHA) {
  build.start()
  pass = () => build.pass()
  fail = () => build.fail()
}

module.exports = { pass, fail }
<|endoftext|>


<commit_before>o2.require("/js/DOMUtil.js");
o2.require("/js/ajax.js");

o2.popupDialog = {

  submitFunc          : null,
  currentOpenDialogId : null,
  dialogCloseIsSet    : false,

  init : function() {
    if (!document.getElementById("o2PopupDialog")) {
      var html;
      html  = '
';
      html += '
';
      html += '
';
      html += '
';
      html += '        <button type="button" class="close" data-dismiss="modal">×Close</button>';
      html += '

';
      html += '
';
      html += '

';
      html += '

';
      html += '
';
      html += '
';
      html += '
';
      $(document.body).append( $(html) );
    }
  },

  define : function(id, params) {
    if (!o2.popupDialog[id]) {
      o2.popupDialog[id] = {};
    }
    o2.popupDialog[id].buttons = [];
    o2.popupDialog[id].params = params;
  },

  addSubmitBtn : function(id, text, func) {
    func = func || function () {
      var form = o2.popupDialog.findForm( document.getElementById("o2PopupDialog") );
      if ( ( form && form.onsubmit && form.onsubmit.call(form) )  ||  (form && !form.onsubmit) ) {
        form.submit();
      }
      o2.popupDialog.hide();
    };
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : "btn-primary",
      "click" : func
    });
  },

  addCloseBtn : function(id, text) {
    o2.popupDialog[id].buttons.push({
      "text"       : text,
      "class"      : "btn-default",
      "isCloseBtn" : true
    });
  },

  addBtn : function(id, text, onClick, className) {
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : className,
      "click" : function () { eval(onClick) }
    });
  },

  display : function(id, extraParams) {
    o2.popupDialog.currentOpenDialogId = id;
    o2.popupDialog.clear();

    if (!o2.popupDialog[id]) {
      var params = {};
      var linkTag = document.getElementById(id);
      for (var i = 0; i < linkTag.attributes.length; i++) {
        var attr = linkTag.attributes[i];
        if (attr.name !== "id" && attr.name !== "class") {
          params[ attr.name ] = attr.value;
        }
      }
      o2.popupDialog.define(id, params);
      var submitText = params.submitText || params.submittext;
      if (submitText) {
        o2.popupDialog.addSubmitBtn(id, submitText);
      }
      var closeText = params.closeText || params.closetext;
      if (closeText) {
        o2.popupDialog.addCloseBtn(id, closeText);
      }
    }

    var params = o2.popupDialog[id].params;
    for (var key in extraParams) {
      params[key] = extraParams[key];
    }
    var contentId   = params.contentId   || params.contentid;
    var contentUrl  = params.contentUrl  || params.contenturl;
    var contentHtml = params.contentHtml || params.contenthtml;
    if (params.onClose) {
      var onClose = params.onClose;
      delete params.onClose;
      params.close = function() { eval(onClose); }
    }

    o2.popupDialog.drawButtons(id);
    $("#o2PopupDialog .modal-body"  ).css( "height", params.height );
    $("#o2PopupDialog .modal-dialog").css( "width",  params.width  );
    $("#o2PopupDialog").modal("toggle");
    if (!o2.popupDialog.dialogCloseIsSet) {
      o2.popupDialog.dialogCloseIsSet = true;
      $("#o2PopupDialog").on("dialogclose", function (event, ui) {
        o2.popupDialog.copyHtmlToHiddenContainer();
      } );
    }
    var popupDialog = document.getElementById("o2PopupDialog");
    $("#o2PopupDialog .modal-title").html(params.title);
    if (contentHtml) {
      $("#o2PopupDialog .modal-body").html(contentHtml);
    }
    else if (contentId) {
      $("#o2PopupDialog .modal-body").html( document.getElementById(contentId).innerHTML );
    }
    else if (contentUrl) {
      //popupDialog.parentNode.style.display = "none";
      o2.ajax.call({
        serverScript : contentUrl,
        target       : "o2PopupDialogBody",
        where        : "replace",
        onSuccess    : "var elm = document.getElementById('o2PopupDialog').parentNode; elm.id = '" + id + "'; elm.style.display = '';"
      });
    }
  },

  hide : function() {
    $("#o2PopupDialog").modal({ show : false });
  },

  findForm : function(elm) {
    for (var i = 0; i < elm.childNodes.length; i++) {
      var child = elm.childNodes[i];
      if (child.nodeType == 3) {
        continue;
      }
      if (child.nodeName.toLowerCase() === "form") {
        return child;
      }
      var form = o2.popupDialog.findForm(child);
      if (form) {
        return form;
      }
    }
    return null;
  },

  copyHtmlToHiddenContainer : function() {
    var id = o2.popupDialog.currentOpenDialogId;
    if (!id) {
      return;
    }
  },

  drawButtons : function(id) {
    var buttons = o2.popupDialog[id].buttons;
    for (var i = 0; i < buttons.length; i++) {
      o2.popupDialog.drawButton( id, buttons[i] );
    }
    o2.popupDialog[id].buttons = [];
  },

  drawButton : function(id, button) {
    var buttonElm = $(
        '<button type="button" class="btn '
      + button.class
      + '"'
      + (button.isCloseBtn ? " data-dismiss='modal'" : "")
      + '>'
      + button.text
      + '</button>'
    );
    buttonElm.click(button.click);
    $("#o2PopupDialog .modal-footer").append(buttonElm);
  },

  clear : function() {
    $( "#o2PopupDialogLabel"          ).html("");
    $( "#o2PopupDialogBody"           ).html("");
    $( "#o2PopupDialog .modal-footer" ).html("");
  },
};
<commit_msg>Merging in changes (r5488): "hide" works better than "show:false".<commit_after>o2.require("/js/DOMUtil.js");
o2.require("/js/ajax.js");

o2.popupDialog = {

  submitFunc          : null,
  currentOpenDialogId : null,
  dialogCloseIsSet    : false,

  init : function() {
    if (!document.getElementById("o2PopupDialog")) {
      var html;
      html  = '
';
      html += '
';
      html += '
';
      html += '
';
      html += '        <button type="button" class="close" data-dismiss="modal">×Close</button>';
      html += '

';
      html += '
';
      html += '

';
      html += '

';
      html += '
';
      html += '
';
      html += '
';
      $(document.body).append( $(html) );
    }
  },

  define : function(id, params) {
    if (!o2.popupDialog[id]) {
      o2.popupDialog[id] = {};
    }
    o2.popupDialog[id].buttons = [];
    o2.popupDialog[id].params = params;
  },

  addSubmitBtn : function(id, text, func) {
    func = func || function () {
      var form = o2.popupDialog.findForm( document.getElementById("o2PopupDialog") );
      if ( ( form && form.onsubmit && form.onsubmit.call(form) )  ||  (form && !form.onsubmit) ) {
        form.submit();
      }
      o2.popupDialog.hide();
    };
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : "btn-primary",
      "click" : func
    });
  },

  addCloseBtn : function(id, text) {
    o2.popupDialog[id].buttons.push({
      "text"       : text,
      "class"      : "btn-default",
      "isCloseBtn" : true
    });
  },

  addBtn : function(id, text, onClick, className) {
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : className,
      "click" : function () { eval(onClick) }
    });
  },

  display : function(id, extraParams) {
    o2.popupDialog.currentOpenDialogId = id;
    o2.popupDialog.clear();

    if (!o2.popupDialog[id]) {
      var params = {};
      var linkTag = document.getElementById(id);
      for (var i = 0; i < linkTag.attributes.length; i++) {
        var attr = linkTag.attributes[i];
        if (attr.name !== "id" && attr.name !== "class") {
          params[ attr.name ] = attr.value;
        }
      }
      o2.popupDialog.define(id, params);
      var submitText = params.submitText || params.submittext;
      if (submitText) {
        o2.popupDialog.addSubmitBtn(id, submitText);
      }
      var closeText = params.closeText || params.closetext;
      if (closeText) {
        o2.popupDialog.addCloseBtn(id, closeText);
      }
    }

    var params = o2.popupDialog[id].params;
    for (var key in extraParams) {
      params[key] = extraParams[key];
    }
    var contentId   = params.contentId   || params.contentid;
    var contentUrl  = params.contentUrl  || params.contenturl;
    var contentHtml = params.contentHtml || params.contenthtml;
    if (params.onClose) {
      var onClose = params.onClose;
      delete params.onClose;
      params.close = function() { eval(onClose); }
    }

    o2.popupDialog.drawButtons(id);
    $("#o2PopupDialog .modal-body"  ).css( "height", params.height );
    $("#o2PopupDialog .modal-dialog").css( "width",  params.width  );
    $("#o2PopupDialog").modal("toggle");
    if (!o2.popupDialog.dialogCloseIsSet) {
      o2.popupDialog.dialogCloseIsSet = true;
      $("#o2PopupDialog").on("dialogclose", function (event, ui) {
        o2.popupDialog.copyHtmlToHiddenContainer();
      } );
    }
    var popupDialog = document.getElementById("o2PopupDialog");
    $("#o2PopupDialog .modal-title").html(params.title);
    if (contentHtml) {
      $("#o2PopupDialog .modal-body").html(contentHtml);
    }
    else if (contentId) {
      $("#o2PopupDialog .modal-body").html( document.getElementById(contentId).innerHTML );
    }
    else if (contentUrl) {
      //popupDialog.parentNode.style.display = "none";
      o2.ajax.call({
        serverScript : contentUrl,
        target       : "o2PopupDialogBody",
        where        : "replace",
        onSuccess    : "var elm = document.getElementById('o2PopupDialog').parentNode; elm.id = '" + id + "'; elm.style.display = '';"
      });
    }
  },

  hide : function() {
    $("#o2PopupDialog").modal("hide");
  },

  findForm : function(elm) {
    for (var i = 0; i < elm.childNodes.length; i++) {
      var child = elm.childNodes[i];
      if (child.nodeType == 3) {
        continue;
      }
      if (child.nodeName.toLowerCase() === "form") {
        return child;
      }
      var form = o2.popupDialog.findForm(child);
      if (form) {
        return form;
      }
    }
    return null;
  },

  copyHtmlToHiddenContainer : function() {
    var id = o2.popupDialog.currentOpenDialogId;
    if (!id) {
      return;
    }
  },

  drawButtons : function(id) {
    var buttons = o2.popupDialog[id].buttons;
    for (var i = 0; i < buttons.length; i++) {
      o2.popupDialog.drawButton( id, buttons[i] );
    }
    o2.popupDialog[id].buttons = [];
  },

  drawButton : function(id, button) {
    var buttonElm = $(
        '<button type="button" class="btn '
      + button.class
      + '"'
      + (button.isCloseBtn ? " data-dismiss='modal'" : "")
      + '>'
      + button.text
      + '</button>'
    );
    buttonElm.click(button.click);
    $("#o2PopupDialog .modal-footer").append(buttonElm);
  },

  clear : function() {
    $( "#o2PopupDialogLabel"          ).html("");
    $( "#o2PopupDialogBody"           ).html("");
    $( "#o2PopupDialog .modal-footer" ).html("");
  },
};
<|endoftext|>


<commit_before>'use strict';

module.exports = function (grunt) {
  var webpack = require('webpack');
  require('time-grunt')(grunt);

  var webpack_karma = {
    output: {
      library: 'storage',
      libraryTarget: 'umd',
      pathinfo: true
    },
    devtool: 'eval',
    module: {
      postLoaders: [{
        test: /\.js$/,
        exclude: /(node_modules)\//,
        loader: 'istanbul-instrumenter'
      }]
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        mangle: false
      }),
      new webpack.DefinePlugin({
        NODE_ENV: JSON.stringify('production')
      })
    ]
  };

  grunt.initConfig({
    webpack: {
      options: {
        entry: './lib/index.js',
        plugins: [
          new webpack.optimize.UglifyJsPlugin({
            mangle: false
          }),
          new webpack.DefinePlugin({
            NODE_ENV: JSON.stringify('production')
          })
        ]
      },

      min: {
        output: {
          filename: './dist/storage.min.js',
          library: 'storage',
          libraryTarget: 'umd'
        }
      },

      dev: {
        output: {
          filename: './dist/storage.min.debug.js',
          library: 'storage',
          libraryTarget: 'umd',
          pathinfo: true
        },
        devtool: 'eval',
        stats: {
          // Configure the console output
          colors: true,
          modules: true,
          reasons: true
        }
      },

      watch: {
        output: {
          filename: './dist/storage.min.debug.js',
          library: 'storage',
          libraryTarget: 'umd',
          pathinfo: true
        },
        devtool: 'eval',
        stats: {
          // Configure the console output
          colors: true,
          modules: true,
          reasons: true
        },

        watch: true,  // Use this in combination with the watch option
        // You need to keep the grunt process alive

        keepalive: true // don't finish the grunt task
        // Use this in combination with the watch option
      }
    },

    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      lib: {
        src: [
          'lib/**/*.js'
          //'storage.debug.js'
        ]
      },
      tests: {
        src: [
          'test/*.js',
          'Gruntfile.js',
          'karma.conf.js'
        ]
      }
    },

    karma: {
      options: {
        configFile: 'karma.conf.js'
      },

      local: {
        // list of files / patterns to load in the browser
        files: [
          { src: 'node_modules/lodash/dist/lodash.js'},
          { src: 'dist/storage.min.debug.js'},
          { src: 'test/*.js'}
        ],
        browsers: [
          'Chrome'
          //'Firefox'
        ],
        // coverage reporter generates the coverage
        reporters: [
          'dots'
        ],
        // optionally, configure the reporter
        coverageReporter: {
          type: 'html',
          dir: 'test/coverage'
        }
      },

      cov: {
        browsers: [
          'Chrome'
        ],
        preprocessors: {
          'lib/index.js': ['webpack', 'sourcemap']
        },
        webpack: webpack_karma,
        // coverage reporter generates the coverage
        reporters: [
          'dots',
          'coverage'
        ],
        // optionally, configure the reporter
        coverageReporter: {
          type: 'html',
          dir: 'test/coverage'
        }
      },

      phantom: {
        browserNoActivityTimeout : 60000, //default 10000
        browsers: [
          'PhantomJS'
        ],
        preprocessors: {
          'lib/index.js': ['webpack']
        },
        webpack: webpack_karma,
        // coverage reporter generates the coverage
        reporters: [
          'dots',
          'coverage'
        ],
        // optionally, configure the reporter
        coverageReporter: {
          type: 'lcovonly',
          dir: 'test/coverage'
        }
      },

      sauce: {
        // list of files / patterns to load in the browser
        files: [
          { src: 'node_modules/lodash/dist/lodash.js'},
          { src: 'dist/storage.min.debug.js'},
          { src: 'test/*.js'}
        ],
        reporters: [
          'dots',
          'saucelabs'
        ],
        browsers: [
          'sauce_chrome',
          //'sauce_chrome_linux',
          'sauce_firefox',
          //'sauce_firefox_linux',
          'sauce_safari',
          //'sauce_ie_8',
          'sauce_ie_9',
          'sauce_ie_10',
          'sauce_ie_11'
        ]
      }
    },

    coveralls: {
      options: {
        coverageDir: 'test/coverage',
        recursive: true
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-karma');
  grunt.loadNpmTasks('grunt-karma-coveralls');
  grunt.loadNpmTasks("grunt-webpack");

  grunt.registerTask('default', [
    'build',
    'test'
  ]);

  grunt.registerTask('lint', [
    'jshint'
  ]);

  grunt.registerTask('build', [
    //'lint',
    //'complexity',
    'webpack:min',
    'webpack:dev'
  ]);

  grunt.registerTask('watch', [
    'webpack:watch'
  ]);

  grunt.registerTask('test', [
    'webpack:dev',
    'karma:local'
  ]);

  grunt.registerTask('cov', [
    'karma:cov'
  ]);

  grunt.registerTask('travis', [
    'build',
    'karma:phantom',
    'karma:sauce'
  ]);
};<commit_msg>up gruntfile<commit_after>'use strict';

module.exports = function (grunt) {
  var webpack = require('webpack');
  require('time-grunt')(grunt);

  var webpack_karma = {
    output: {
      library: 'storage',
      libraryTarget: 'umd',
      pathinfo: true
    },
    devtool: 'eval',
    module: {
      postLoaders: [{
        test: /\.js$/,
        exclude: /(node_modules)\//,
        loader: 'istanbul-instrumenter'
      }]
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        mangle: false
      }),
      new webpack.DefinePlugin({
        NODE_ENV: JSON.stringify('production')
      })
    ]
  };

  grunt.initConfig({
    webpack: {
      options: {
        entry: './lib/index.js',
        plugins: [
          new webpack.optimize.UglifyJsPlugin({
            mangle: false
          }),
          new webpack.DefinePlugin({
            NODE_ENV: JSON.stringify('production')
          })
        ]
      },

      min: {
        output: {
          filename: './dist/storage.min.js',
          library: 'storage',
          libraryTarget: 'umd'
        }
      },

      dev: {
        output: {
          filename: './dist/storage.min.debug.js',
          library: 'storage',
          libraryTarget: 'umd',
          pathinfo: true
        },
        devtool: 'eval',
        stats: {
          // Configure the console output
          colors: true,
          modules: true,
          reasons: true
        }
      },

      watch: {
        output: {
          filename: './dist/storage.min.debug.js',
          library: 'storage',
          libraryTarget: 'umd',
          pathinfo: true
        },
        devtool: 'eval',
        stats: {
          // Configure the console output
          colors: true,
          modules: true,
          reasons: true
        },

        watch: true,  // Use this in combination with the watch option
        // You need to keep the grunt process alive

        keepalive: true // don't finish the grunt task
        // Use this in combination with the watch option
      }
    },

    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      lib: {
        src: [
          'lib/**/*.js'
          //'storage.debug.js'
        ]
      },
      tests: {
        src: [
          'test/*.js',
          'Gruntfile.js',
          'karma.conf.js'
        ]
      }
    },

    karma: {
      options: {
        configFile: 'karma.conf.js'
      },

      local: {
        // list of files / patterns to load in the browser
        files: [
          { src: 'node_modules/lodash/dist/lodash.js'},
          { src: 'dist/storage.min.debug.js'},
          { src: 'test/*.js'}
        ],
        browsers: [
          'Chrome'
          //'Firefox'
        ],
        // coverage reporter generates the coverage
        reporters: [
          'dots'
        ],
        // optionally, configure the reporter
        coverageReporter: {
          type: 'html',
          dir: 'test/coverage'
        }
      },

      cov: {
        browsers: [
          'Chrome'
        ],
        preprocessors: {
          'lib/index.js': ['webpack', 'sourcemap']
        },
        webpack: webpack_karma,
        // coverage reporter generates the coverage
        reporters: [
          'dots',
          'coverage'
        ],
        // optionally, configure the reporter
        coverageReporter: {
          type: 'html',
          dir: 'test/coverage'
        }
      },

      phantom: {
        browserNoActivityTimeout : 60000, //default 10000
        browsers: [
          'PhantomJS'
        ],
        preprocessors: {
          'lib/index.js': ['webpack']
        },
        webpack: webpack_karma,
        // coverage reporter generates the coverage
        reporters: [
          'dots',
          'coverage'
        ],
        // optionally, configure the reporter
        coverageReporter: {
          type: 'lcovonly',
          dir: 'test/coverage'
        }
      },

      sauce: {
        // list of files / patterns to load in the browser
        files: [
          { src: 'node_modules/lodash/dist/lodash.js'},
          { src: 'dist/storage.min.debug.js'},
          { src: 'test/*.js'}
        ],
        reporters: [
          'dots',
          'saucelabs'
        ],
        browsers: [
          'sauce_chrome',
          //'sauce_chrome_linux',
          'sauce_firefox',
          //'sauce_firefox_linux',
          'sauce_safari',
          //'sauce_ie_8',
          'sauce_ie_9',
          'sauce_ie_10',
          'sauce_ie_11'
        ]
      }
    },

    coveralls: {
      options: {
        coverageDir: 'test/coverage',
        recursive: true
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-karma');
  grunt.loadNpmTasks('grunt-karma-coveralls');
  grunt.loadNpmTasks("grunt-webpack");

  grunt.registerTask('default', ['build', 'test']);
  grunt.registerTask('lint', ['jshint']);

  grunt.registerTask('build', [
    //'lint',
    //'complexity',
    'webpack:min',
    'webpack:dev'
  ]);

  grunt.registerTask('watch', ['webpack:watch']);
  grunt.registerTask('test', ['webpack:dev', 'karma:local']);
  grunt.registerTask('cov', ['karma:cov']);
  grunt.registerTask('travis', [
    'build',
    'karma:phantom',
    'karma:sauce'
  ]);
};<|endoftext|>


<commit_before>'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);

	grunt.initConfig({

    //Test application locally in Amazon AWS Lambda environment
    lambda_invoke: {
      default: {
        options: {
          handler: 'handler',
          file_name: 'index.js',
          event: 'event.json'
        }
      }
    },

    //Package for deployment to Amazon AWS Lambda
    lambda_package: {
      default: {
        options: {
          include_time: true,
          package_folder: './',
          dist_folder:  'dist'
        }
      }
    },

    // Tell grunt which files to watch for changes
    watch: {
      options: {
        spawn: false,
      },
      gruntfile: {
          files: 'Gruntfile.js',
          tasks: ['jshint:gruntfile']
      },
      config: {
        files: 'config/*.json',
        tasks: ['test']
      },
      src: {
          files: ['index.js', 'scripts/*.js'],
          tasks: ['test']
      },
      test: {
          files: '<%= jshint.test.src %>',
          tasks: ['test']
      }
    },

    // Define test configuration
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          clearRequireCache: true,
          quiet: false
        },
        src: ['test/*.spec.js']
      },
    },

    //Deploy to Amazon AWS Lambda
    /*  Specify your AWS creditionals in ~/aws/credentials in the following format:
    		[default]
				aws_access_key_id = <YOUR_ACCESS_KEY_ID>
				aws_secret_access_key = <YOUR_SECRET_ACCESS_KEY>

				More Detail:  https://www.npmjs.com/package/grunt-aws-lambda
    */
    lambda_deploy: {
      default: {
        //Update deployment location here
        arn: 'arn:aws:lambda:us-east-1:651084418096:function:alexa-pokitdok',
        options: {
	        timeout : 5,
	        memory: 128
        }
      }
    },

    copy: {
       // Copy the production configuration file, to the default config file,
       // since AWS Lambda does not support environment variables, we must use default.json
      prodConfig: {
        files: [{
          src: ['config/production.json'],
          dest: 'config/default.json'
        }]
      },
       // Copy the dev configuration file, to the default config file,
       // this is only necessary if you have not configured your local environment
       // variable to 'export NODE_ENV=dev'
      devConfig: {
        files: [{
          src: ['config/dev.json'],
          dest: 'config/default.json'
        }]
      },
       // Copy the example default configuration to the actual default config file. This
       // is useful only when you are starting out your project
      exampleConfig: {
        files: [{
          src: ['config/default.example.json'],
          dest: 'config/default.json'
        }]
      },
    },

    clean: {
      //Delete extra directories included in the Pokitdok package that are unnecessary and cause deployment errors
      pokitdok: ['node_modules/pokitdok-nodejs/.idea', 'node_modules/pokitdok-nodejs/venv']
    },

	  // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        options: {
          force: false,
          verbose: true
        },
        src: [
          'index.js',
          'Gruntfile.js',
          'scripts/{,*/}*.js',
          'test/{,*/}*.js'
        ]
      },
      gruntfile: {
        src: 'Gruntfile.js'
      },
      test: {
        src: 'test/{,*/}*.js'
      }
    }

	});

  //Register grunt tasks
  //---------------------

  grunt.registerTask('test', [
    'jshint:all',
    'mochaTest'
  ]);

	grunt.registerTask('build', [
    //'test',
    'clean:pokitdok',
		'lambda_package'
	]);

	grunt.registerTask('deploy', [
    'build',
		'lambda_deploy'
	]);

	grunt.registerTask('default', [
    'test',
    'watch'
  ]);

};<commit_msg>Updated build to workaround issue with lambda_package task<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);

	grunt.initConfig({

    //Test application locally in Amazon AWS Lambda environment
    lambda_invoke: {
      default: {
        options: {
          handler: 'handler',
          file_name: 'index.js',
          event: 'event.json'
        }
      }
    },

    //Package for deployment to Amazon AWS Lambda
    lambda_package: {
      default: {
        options: {
          include_time: true,
          package_folder: './',
          dist_folder:  'dist'
        }
      }
    },

    // Tell grunt which files to watch for changes
    watch: {
      options: {
        spawn: false,
      },
      gruntfile: {
          files: 'Gruntfile.js',
          tasks: ['jshint:gruntfile']
      },
      config: {
        files: 'config/*.json',
        tasks: ['test']
      },
      src: {
          files: ['index.js', 'scripts/*.js'],
          tasks: ['test']
      },
      test: {
          files: '<%= jshint.test.src %>',
          tasks: ['test']
      }
    },

    // Define test configuration
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          clearRequireCache: true,
          quiet: false
        },
        src: ['test/*.spec.js']
      },
    },

    //Deploy to Amazon AWS Lambda
    /*  Specify your AWS creditionals in ~/aws/credentials in the following format:
    		[default]
				aws_access_key_id = <YOUR_ACCESS_KEY_ID>
				aws_secret_access_key = <YOUR_SECRET_ACCESS_KEY>

				More Detail:  https://www.npmjs.com/package/grunt-aws-lambda
    */
    lambda_deploy: {
      default: {
        //Update deployment location here
        arn: 'arn:aws:lambda:us-east-1:651084418096:function:alexa-pokitdok',
        options: {
	        timeout : 5,
	        memory: 128
        }
      }
    },

    copy: {
       // Copy the production configuration file, to the default config file,
       // since AWS Lambda does not support environment variables, we must use default.json
      prodConfig: {
        files: [{
          src: ['config/production.json'],
          dest: 'config/default.json'
        }]
      },
       // Copy the dev configuration file, to the default config file,
       // this is only necessary if you have not configured your local environment
       // variable to 'export NODE_ENV=dev'
      devConfig: {
        files: [{
          src: ['config/dev.json'],
          dest: 'config/default.json'
        }]
      },
       // Copy the example default configuration to the actual default config file. This
       // is useful only when you are starting out your project
      exampleConfig: {
        files: [{
          src: ['config/default.example.json'],
          dest: 'config/default.json'
        }]
      },
    },

    clean: {
      //Delete extra directories included in the Pokitdok package that are unnecessary and cause deployment errors
      pokitdok: ['node_modules/pokitdok-nodejs/.idea', 'node_modules/pokitdok-nodejs/venv']
    },

	  // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        options: {
          force: false,
          verbose: true
        },
        src: [
          'index.js',
          'Gruntfile.js',
          'scripts/{,*/}*.js',
          'test/{,*/}*.js'
        ]
      },
      gruntfile: {
        src: 'Gruntfile.js'
      },
      test: {
        src: 'test/{,*/}*.js'
      }
    }

	});

  //Register grunt tasks
  //---------------------

  grunt.registerTask('test', [
    'jshint:all',
    'mochaTest'
  ]);

	grunt.registerTask('build', [
    'jshint:all',
    //'mochaTest',    // lambda_package does not execute successfully when unit tests are performed in the same build task
    'clean:pokitdok',
		'lambda_package'
	]);

	grunt.registerTask('deploy', [
    'build',
		'lambda_deploy'
	]);

	grunt.registerTask('default', [
    'test',
    'watch'
  ]);

};<|endoftext|>


<commit_before>"use strict";

module.exports = function(grunt) {

    grunt.initConfig({
        dirs: {
            dest: "_site",
            src: "source"
        },

        // Copy files that don't need compilation to dist/
        copy: {
            dist: {
                files: [
                    {dest: "<%= dirs.dest %>/", src: "assets/js/jquery*.min.js", expand: true, cwd: "<%= dirs.src %>/"},
                ]
            }
        },

        jekyll: {
            site: {
                options: {
                    bundleExec: true
                }
            }
        },

        htmlmin: {
            dist: {
                options: {
                    collapseWhitespace: true,
                    ignoreCustomComments: [/^\s*google(off|on):\s/],
                    minifyCSS: true,
                    minifyJS: true,
                    removeAttributeQuotes: true,
                    removeComments: true
                },
                expand: true,
                cwd: "<%= dirs.dest %>",
                dest: "<%= dirs.dest %>",
                src: [
                    "**/*.html",
                    "!404.html"
                ]
            }
        },

        xmlmin: {
            dist: {
                expand: true,
                cwd: "<%= dirs.dest %>",
                dest: "<%= dirs.dest %>",
                src: [
                    "**/*.xml"
                ]
            }
        },

        concat: {
            css: {
                src: ["<%= dirs.src %>/assets/css/bootstrap.css",
                      "<%= dirs.src %>/assets/css/font-awesome.css",
                      "<%= dirs.src %>/assets/css/jquery.fancybox.css",
                      "<%= dirs.src %>/assets/css/style.css"],
                dest: "<%= dirs.dest %>/assets/css/pack.css"
            },
            js: {
                src: ["<%= dirs.src %>/assets/js/plugins.js",
                      "<%= dirs.src %>/assets/js/bootstrap.js",
                      "<%= dirs.src %>/assets/js/jquery.mousewheel.js",
                      "<%= dirs.src %>/assets/js/jquery.fancybox.js"],
                dest: "<%= dirs.dest %>/assets/js/pack.js"
            },
            jsIE: {
                src: ["<%= dirs.src %>/assets/js/html5shiv.js",
                      "<%= dirs.src %>/assets/js/respond.js"],
                dest: "<%= dirs.dest %>/assets/js/html5shiv-respond.min.js"
            }
        },

        uncss: {
            options: {
                ignore: [
                    /(#|\.)fancybox(\-[a-zA-Z]+)?/,
                    // needed for Bootstrap's transitions
                    ".fade",
                    ".fade.in",
                    ".navbar-collapse.in",
                    ".collapse",
                    ".collapse.in",
                    ".navbar-collapse",
                    ".navbar-collapse.in",
                    ".collapsing",
                    /(#|\.)navbar(\-[a-zA-Z]+)?/,
                    /(#|\.)dropdown(\-[a-zA-Z]+)?/,
                    ".open > .dropdown-menu",
                    ".open > a",
                    // needed for the `<noscript>` warning; remove them when fixed in uncss
                    ".alert-danger",
                    ".visible-xs",
                    ".noscript-warning",
                    // currently only in a IE conditional so uncss doesn't see it
                    ".close",
                    ".alert-dismissible"
                ],
                htmlroot: "<%= dirs.dest %>",
                ignoreSheets: [/fonts.googleapis/]
            },
            dist: {
                src: "<%= dirs.dest %>/**/*.html",
                dest: "<%= concat.css.dest %>"
            }
        },

        cssmin: {
            minify: {
                options: {
                    keepSpecialComments: 0,
                    compatibility: "ie8"
                },
                files: {
                    "<%= uncss.dist.dest %>": "<%= concat.css.dest %>"
                }
            }
        },

        uglify: {
            options: {
                compress: {
                    warnings: false
                },
                mangle: true,
                preserveComments: false
            },
            minify: {
                files: {
                    "<%= concat.js.dest %>": "<%= concat.js.dest %>"
                }
            },
            minifyIE: {
                files: {
                    "<%= concat.jsIE.dest %>": "<%= concat.jsIE.dest %>"
                }
            }
        },

        filerev: {
            css: {
                src: "<%= dirs.dest %>/assets/css/**/{,*/}*.css"
             },
            js: {
                src: [
                    "<%= dirs.dest %>/assets/js/**/{,*/}*.js",
                    "!<%= dirs.dest %>/assets/js/jquery*.min.js"
                ]
            },
            images: {
                src: [
                    "<%= dirs.dest %>/assets/img/**/*.{jpg,jpeg,gif,png}",
                    "!<%= dirs.dest %>/assets/img/logo-144x144.png",
                    "!<%= dirs.dest %>/assets/img/logo-256x256.png",
                    "!<%= dirs.dest %>/assets/img/TileImage.png"
                ]
            }
        },

        useminPrepare: {
            html: "<%= dirs.dest %>/index.html",
            options: {
                dest: "<%= dirs.dest %>",
                root: "<%= dirs.dest %>"
            }
        },

        usemin: {
            css: "<%= dirs.dest %>/assets/css/pack*.css",
            html: "<%= dirs.dest %>/**/*.html",
            options: {
                assetsDirs: ["<%= dirs.dest %>/", "<%= dirs.dest %>/assets/img/"]
            }
        },

        connect: {
            options: {
                hostname: "localhost",
                livereload: 35729,
                port: 8000
            },
            livereload: {
                options: {
                    base: "<%= dirs.dest %>/",
                    open: true  // Automatically open the webpage in the default browser
                }
            }
        },

        watch: {
            options: {
                livereload: "<%= connect.options.livereload %>"
            },
            dev: {
                files: ["<%= dirs.src %>/**", ".jshintrc", "_config.yml", "Gruntfile.js"],
                tasks: "dev"
            },
            build: {
                files: ["<%= dirs.src %>/**", ".jshintrc", "_config.yml", "Gruntfile.js"],
                tasks: "build"
            }
        },

        csslint: {
            options: {
                csslintrc: ".csslintrc"
            },
            src: "<%= dirs.src %>/assets/css/style.css"
        },

        bootlint: {
            options: {
                relaxerror: ["W002"]
            },
            files: ["<%= dirs.dest %>/**/*.html", "!<%= dirs.dest %>/404.html"]
        },

        jshint: {
            options: {
                jshintrc: ".jshintrc"
            },
            files: {
                src: "Gruntfile.js"
            }
        },

        validation: {
            options: {
                charset: "utf-8",
                doctype: "HTML5",
                failHard: true,
                reset: true
            },
            files: {
                src: "<%= dirs.dest %>/**/*.html"
            }
        },

        clean: {
            dist: "<%= dirs.dest %>/"
        }

    });

    // Load any grunt plugins found in package.json.
    require("load-grunt-tasks")(grunt, {scope: "devDependencies"});
    require("time-grunt")(grunt);

    grunt.registerTask("build", [
        "clean",
        "jekyll",
        "useminPrepare",
        "copy",
        "concat",
        "uncss",
        "cssmin",
        "uglify",
        "filerev",
        "usemin",
        "htmlmin",
        "xmlmin"
    ]);

    grunt.registerTask("test", [
        "build",
        "csslint",
        "bootlint",
        "jshint",
        "validation"
    ]);

    grunt.registerTask("dev", [
        "jekyll",
        "useminPrepare",
        "copy",
        "concat",
        "filerev",
        "usemin"
    ]);

    grunt.registerTask("server", [
        "build",
        "connect",
        "watch:build"
    ]);

    grunt.registerTask("default", [
        "dev",
        "connect",
        "watch:dev"
    ]);

};
<commit_msg>Update UnCSS config.<commit_after>"use strict";

module.exports = function(grunt) {

    grunt.initConfig({
        dirs: {
            dest: "_site",
            src: "source"
        },

        // Copy files that don't need compilation to dist/
        copy: {
            dist: {
                files: [
                    {dest: "<%= dirs.dest %>/", src: "assets/js/jquery*.min.js", expand: true, cwd: "<%= dirs.src %>/"},
                ]
            }
        },

        jekyll: {
            site: {
                options: {
                    bundleExec: true
                }
            }
        },

        htmlmin: {
            dist: {
                options: {
                    collapseWhitespace: true,
                    ignoreCustomComments: [/^\s*google(off|on):\s/],
                    minifyCSS: true,
                    minifyJS: true,
                    removeAttributeQuotes: true,
                    removeComments: true
                },
                expand: true,
                cwd: "<%= dirs.dest %>",
                dest: "<%= dirs.dest %>",
                src: [
                    "**/*.html",
                    "!404.html"
                ]
            }
        },

        xmlmin: {
            dist: {
                expand: true,
                cwd: "<%= dirs.dest %>",
                dest: "<%= dirs.dest %>",
                src: [
                    "**/*.xml"
                ]
            }
        },

        concat: {
            css: {
                src: ["<%= dirs.src %>/assets/css/bootstrap.css",
                      "<%= dirs.src %>/assets/css/font-awesome.css",
                      "<%= dirs.src %>/assets/css/jquery.fancybox.css",
                      "<%= dirs.src %>/assets/css/style.css"],
                dest: "<%= dirs.dest %>/assets/css/pack.css"
            },
            js: {
                src: ["<%= dirs.src %>/assets/js/plugins.js",
                      "<%= dirs.src %>/assets/js/bootstrap.js",
                      "<%= dirs.src %>/assets/js/jquery.mousewheel.js",
                      "<%= dirs.src %>/assets/js/jquery.fancybox.js"],
                dest: "<%= dirs.dest %>/assets/js/pack.js"
            },
            jsIE: {
                src: ["<%= dirs.src %>/assets/js/html5shiv.js",
                      "<%= dirs.src %>/assets/js/respond.js"],
                dest: "<%= dirs.dest %>/assets/js/html5shiv-respond.min.js"
            }
        },

        uncss: {
            options: {
                ignore: [
                    /(#|\.)fancybox(\-[a-zA-Z]+)?/,
                    // Bootstrap selectors added via JS
                    /\w\.in/,
                    ".fade",
                    ".collapse",
                    ".collapsing",
                    /(#|\.)navbar(\-[a-zA-Z]+)?/,
                    /(#|\.)dropdown(\-[a-zA-Z]+)?/,
                    /(#|\.)(open)/,
                    // currently only in a IE conditional, so uncss doesn't see it
                    ".close",
                    ".alert-dismissible"
                ],
                htmlroot: "<%= dirs.dest %>",
                ignoreSheets: [/fonts.googleapis/],
                stylesheets: ["/assets/css/pack.css"]
            },
            dist: {
                src: "<%= dirs.dest %>/**/*.html",
                dest: "<%= concat.css.dest %>"
            }
        },

        cssmin: {
            minify: {
                options: {
                    keepSpecialComments: 0,
                    compatibility: "ie8"
                },
                files: {
                    "<%= uncss.dist.dest %>": "<%= concat.css.dest %>"
                }
            }
        },

        uglify: {
            options: {
                compress: {
                    warnings: false
                },
                mangle: true,
                preserveComments: false
            },
            minify: {
                files: {
                    "<%= concat.js.dest %>": "<%= concat.js.dest %>"
                }
            },
            minifyIE: {
                files: {
                    "<%= concat.jsIE.dest %>": "<%= concat.jsIE.dest %>"
                }
            }
        },

        filerev: {
            css: {
                src: "<%= dirs.dest %>/assets/css/**/{,*/}*.css"
             },
            js: {
                src: [
                    "<%= dirs.dest %>/assets/js/**/{,*/}*.js",
                    "!<%= dirs.dest %>/assets/js/jquery*.min.js"
                ]
            },
            images: {
                src: [
                    "<%= dirs.dest %>/assets/img/**/*.{jpg,jpeg,gif,png}",
                    "!<%= dirs.dest %>/assets/img/logo-144x144.png",
                    "!<%= dirs.dest %>/assets/img/logo-256x256.png",
                    "!<%= dirs.dest %>/assets/img/TileImage.png"
                ]
            }
        },

        useminPrepare: {
            html: "<%= dirs.dest %>/index.html",
            options: {
                dest: "<%= dirs.dest %>",
                root: "<%= dirs.dest %>"
            }
        },

        usemin: {
            css: "<%= dirs.dest %>/assets/css/pack*.css",
            html: "<%= dirs.dest %>/**/*.html",
            options: {
                assetsDirs: ["<%= dirs.dest %>/", "<%= dirs.dest %>/assets/img/"]
            }
        },

        connect: {
            options: {
                hostname: "localhost",
                livereload: 35729,
                port: 8000
            },
            livereload: {
                options: {
                    base: "<%= dirs.dest %>/",
                    open: true  // Automatically open the webpage in the default browser
                }
            }
        },

        watch: {
            options: {
                livereload: "<%= connect.options.livereload %>"
            },
            dev: {
                files: ["<%= dirs.src %>/**", ".jshintrc", "_config.yml", "Gruntfile.js"],
                tasks: "dev"
            },
            build: {
                files: ["<%= dirs.src %>/**", ".jshintrc", "_config.yml", "Gruntfile.js"],
                tasks: "build"
            }
        },

        csslint: {
            options: {
                csslintrc: ".csslintrc"
            },
            src: "<%= dirs.src %>/assets/css/style.css"
        },

        bootlint: {
            options: {
                relaxerror: ["W002"]
            },
            files: ["<%= dirs.dest %>/**/*.html", "!<%= dirs.dest %>/404.html"]
        },

        jshint: {
            options: {
                jshintrc: ".jshintrc"
            },
            files: {
                src: "Gruntfile.js"
            }
        },

        validation: {
            options: {
                charset: "utf-8",
                doctype: "HTML5",
                failHard: true,
                reset: true
            },
            files: {
                src: "<%= dirs.dest %>/**/*.html"
            }
        },

        clean: {
            dist: "<%= dirs.dest %>/"
        }

    });

    // Load any grunt plugins found in package.json.
    require("load-grunt-tasks")(grunt, {scope: "devDependencies"});
    require("time-grunt")(grunt);

    grunt.registerTask("build", [
        "clean",
        "jekyll",
        "useminPrepare",
        "copy",
        "concat",
        "uncss",
        "cssmin",
        "uglify",
        "filerev",
        "usemin",
        "htmlmin",
        "xmlmin"
    ]);

    grunt.registerTask("test", [
        "build",
        "csslint",
        "bootlint",
        "jshint",
        "validation"
    ]);

    grunt.registerTask("dev", [
        "jekyll",
        "useminPrepare",
        "copy",
        "concat",
        "filerev",
        "usemin"
    ]);

    grunt.registerTask("server", [
        "build",
        "connect",
        "watch:build"
    ]);

    grunt.registerTask("default", [
        "dev",
        "connect",
        "watch:dev"
    ]);

};
<|endoftext|>


<commit_before>o2.require("/js/DOMUtil.js");
o2.require("/js/ajax.js");

o2.popupDialog = {

  submitFunc          : null,
  currentOpenDialogId : null,

  init : function() {
    if (!document.getElementById("o2PopupDialog")) {
      var html;
      html  = '
';
      html += '
';
      html += '
';
      html += '
';
      html += '        <button type="button" class="close" data-dismiss="modal">×Close</button>';
      html += '

';
      html += '
';
      html += '

';
      html += '

';
      html += '
';
      html += '
';
      html += '
';
      $(document.body).append( $(html) );
    }
  },

  define : function(id, params) {
    if (!o2.popupDialog[id]) {
      o2.popupDialog[id] = {};
    }
    o2.popupDialog[id].buttons = [];
    o2.popupDialog[id].params = params;
  },

  addSubmitBtn : function(id, text, func) {
    func = func || function () {
      var form = o2.popupDialog.findForm( document.getElementById("o2PopupDialog") );
      if ( ( form && form.onsubmit && form.onsubmit.call(form) )  ||  (form && !form.onsubmit) ) {
        form.submit();
      }
      o2.popupDialog.hide();
    };
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : "btn-primary",
      "click" : func
    });
  },

  addCloseBtn : function(id, text) {
    o2.popupDialog[id].buttons.push({
      "text"       : text,
      "class"      : "btn-default",
      "isCloseBtn" : true
    });
  },

  addBtn : function(id, text, onClick, className) {
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : className,
      "click" : function () { eval(onClick) }
    });
  },

  display : function(id, extraParams) {
    o2.popupDialog.currentOpenDialogId = id;
    o2.popupDialog.clear();

    if (!o2.popupDialog[id]) {
      o2.popupDialog.define(id, {});
    }
    var submitText = o2.popupDialog[id].params.submitText || o2.popupDialog[id].params.submittext;
    if (submitText) {
      o2.popupDialog.addSubmitBtn(id, submitText);
    }
    var closeText = o2.popupDialog[id].params.closeText || o2.popupDialog[id].params.closetext;
    if (closeText) {
      o2.popupDialog.addCloseBtn(id, closeText);
    }

    var params = o2.popupDialog[id].params;
    for (var key in extraParams) {
      params[key] = extraParams[key];
    }
    var contentId   = params.contentId   || params.contentid;
    var contentUrl  = params.contentUrl  || params.contenturl;
    var contentHtml = params.contentHtml || params.contenthtml;
    if (params.onClose) {
      var onClose = params.onClose;
      params.close = function() { eval(onClose); }
    }

    o2.popupDialog.drawButtons(id);
    $("#o2PopupDialog .modal-body"  ).css( "height", params.height );
    $("#o2PopupDialog .modal-dialog").css( "width",  params.width  );
    $("#o2PopupDialog").modal("toggle");
    var popupDialog = document.getElementById("o2PopupDialog");
    $("#o2PopupDialog .modal-title").html(params.title);
    if (contentHtml) {
      $("#o2PopupDialog .modal-body").html(contentHtml);
    }
    else if (contentId) {
      $("#o2PopupDialog .modal-body").html( document.getElementById(contentId).innerHTML );
    }
    else if (contentUrl) {
      //popupDialog.parentNode.style.display = "none";
      o2.ajax.call({
        serverScript : contentUrl,
        target       : "o2PopupDialogBody",
        where        : "replace",
        onSuccess    : "var elm = document.getElementById('o2PopupDialog').parentNode; elm.id = '" + id + "'; elm.style.display = '';"
      });
    }
  },

  hide : function() {
    $("#o2PopupDialog").modal("hide");
  },

  findForm : function(elm) {
    for (var i = 0; i < elm.childNodes.length; i++) {
      var child = elm.childNodes[i];
      if (child.nodeType == 3) {
        continue;
      }
      if (child.nodeName.toLowerCase() === "form") {
        return child;
      }
      var form = o2.popupDialog.findForm(child);
      if (form) {
        return form;
      }
    }
    return null;
  },

  copyHtmlToHiddenContainer : function() {
    var id = o2.popupDialog.currentOpenDialogId;
    if (!id) {
      return;
    }
  },

  drawButtons : function(id) {
    var buttons = o2.popupDialog[id].buttons;
    for (var i = 0; i < buttons.length; i++) {
      o2.popupDialog.drawButton( id, buttons[i] );
    }
    o2.popupDialog[id].buttons = [];
  },

  drawButton : function(id, button) {
    var buttonElm = $(
        '<button type="button" class="btn '
      + button.class
      + '"'
      + (button.isCloseBtn ? " data-dismiss='modal'" : "")
      + '>'
      + button.text
      + '</button>'
    );
    buttonElm.click(button.click);
    $("#o2PopupDialog .modal-footer").append(buttonElm);
  },

  clear : function() {
    $( "#o2PopupDialogLabel"          ).html("");
    $( "#o2PopupDialogBody"           ).html("");
    $( "#o2PopupDialog .modal-footer" ).html("");
  },
};
<commit_msg>Merging in changes (r5501): Making onClose work for popup dialogs.<commit_after>o2.require("/js/DOMUtil.js");
o2.require("/js/ajax.js");

o2.popupDialog = {

  submitFunc          : null,
  currentOpenDialogId : null,

  init : function() {
    if (!document.getElementById("o2PopupDialog")) {
      var html;
      html  = '
';
      html += '
';
      html += '
';
      html += '
';
      html += '        <button type="button" class="close" data-dismiss="modal">×Close</button>';
      html += '

';
      html += '
';
      html += '

';
      html += '

';
      html += '
';
      html += '
';
      html += '
';
      $(document.body).append( $(html) );
    }
  },

  define : function(id, params) {
    if (!o2.popupDialog[id]) {
      o2.popupDialog[id] = {};
    }
    o2.popupDialog[id].buttons = [];
    o2.popupDialog[id].params = params;
  },

  addSubmitBtn : function(id, text, func) {
    func = func || function () {
      var form = o2.popupDialog.findForm( document.getElementById("o2PopupDialog") );
      if ( ( form && form.onsubmit && form.onsubmit.call(form) )  ||  (form && !form.onsubmit) ) {
        form.submit();
      }
      o2.popupDialog.hide();
    };
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : "btn-primary",
      "click" : func
    });
  },

  addCloseBtn : function(id, text) {
    o2.popupDialog[id].buttons.push({
      "text"       : text,
      "class"      : "btn-default",
      "isCloseBtn" : true
    });
  },

  addBtn : function(id, text, onClick, className) {
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : className,
      "click" : function () { eval(onClick) }
    });
  },

  display : function(id, extraParams) {
    o2.popupDialog.currentOpenDialogId = id;
    o2.popupDialog.clear();

    if (!o2.popupDialog[id]) {
      o2.popupDialog.define(id, {});
    }
    var submitText = o2.popupDialog[id].params.submitText || o2.popupDialog[id].params.submittext;
    if (submitText) {
      o2.popupDialog.addSubmitBtn(id, submitText);
    }
    var closeText = o2.popupDialog[id].params.closeText || o2.popupDialog[id].params.closetext;
    if (closeText) {
      o2.popupDialog.addCloseBtn(id, closeText);
    }

    var params = o2.popupDialog[id].params;
    for (var key in extraParams) {
      params[key] = extraParams[key];
    }
    var contentId   = params.contentId   || params.contentid;
    var contentUrl  = params.contentUrl  || params.contenturl;
    var contentHtml = params.contentHtml || params.contenthtml;
    $("#o2PopupDialog").unbind();
    if (params.onClose) {
      $("#o2PopupDialog").on("hide.bs.modal", function() { eval(params.onClose); console.log("closing");});
    }

    o2.popupDialog.drawButtons(id);
    $("#o2PopupDialog .modal-body"  ).css( "height", params.height );
    $("#o2PopupDialog .modal-dialog").css( "width",  params.width  );
    $("#o2PopupDialog").modal("toggle");

    var popupDialog = document.getElementById("o2PopupDialog");
    $("#o2PopupDialog .modal-title").html(params.title);
    if (contentHtml) {
      $("#o2PopupDialog .modal-body").html(contentHtml);
    }
    else if (contentId) {
      $("#o2PopupDialog .modal-body").html( document.getElementById(contentId).innerHTML );
    }
    else if (contentUrl) {
      //popupDialog.parentNode.style.display = "none";
      o2.ajax.call({
        serverScript : contentUrl,
        target       : "o2PopupDialogBody",
        where        : "replace",
        onSuccess    : "var elm = document.getElementById('o2PopupDialog').parentNode; elm.id = '" + id + "'; elm.style.display = '';"
      });
    }
  },

  hide : function() {
    $("#o2PopupDialog").modal("hide");
  },

  findForm : function(elm) {
    for (var i = 0; i < elm.childNodes.length; i++) {
      var child = elm.childNodes[i];
      if (child.nodeType == 3) {
        continue;
      }
      if (child.nodeName.toLowerCase() === "form") {
        return child;
      }
      var form = o2.popupDialog.findForm(child);
      if (form) {
        return form;
      }
    }
    return null;
  },

  copyHtmlToHiddenContainer : function() {
    var id = o2.popupDialog.currentOpenDialogId;
    if (!id) {
      return;
    }
  },

  drawButtons : function(id) {
    var buttons = o2.popupDialog[id].buttons;
    for (var i = 0; i < buttons.length; i++) {
      o2.popupDialog.drawButton( id, buttons[i] );
    }
    o2.popupDialog[id].buttons = [];
  },

  drawButton : function(id, button) {
    var buttonElm = $(
        '<button type="button" class="btn '
      + button.class
      + '"'
      + (button.isCloseBtn ? " data-dismiss='modal'" : "")
      + '>'
      + button.text
      + '</button>'
    );
    buttonElm.click(button.click);
    $("#o2PopupDialog .modal-footer").append(buttonElm);
  },

  clear : function() {
    $( "#o2PopupDialogLabel"          ).html("");
    $( "#o2PopupDialogBody"           ).html("");
    $( "#o2PopupDialog .modal-footer" ).html("");
  },
};
<|endoftext|>


<commit_before>// @flow
const Dockerode = require('simple-dockerode')

import type { $Request, $Response } from "express";

import { exec as execSync } from "child_process";
import jsesc from "jsesc";
import Logger from "../logger/logger.model";
import { promisify } from "util";
import { timeout, TimeoutError } from "promise-timeout";

const exec = promisify(execSync);

// Compile java code
// export function compile(req: $Request, res: $Response) {
//   const fileName = req.body.fileName;
//   let dirName = `users/${req.body.user._id}/`;
//   const dateTime = new Date();
//   dirName += dateTime.getMonth();
//   dirName += dateTime.getDate();
//   dirName += dateTime.getFullYear();
//
//   // make a directory for this user, if doesn't exist already
//   exec(
//     `mkdir -p ${dirName}`,
//     { timeout: 10000 }, // Process will time out if running for > 10 seconds.
//     (error, stdout, stderr) => {
//       if (error) {
//         return res.status(200).send(stderr);
//       }
//
//       const escapedCode = jsesc(req.body.code, {
//         wrap: true
//       });
//       exec(
//         `echo ${escapedCode} > ${dirName}/${fileName}`,
//         { timeout: 10000 }, // Process will time out if running for > 10 seconds.
//         (error, stdout, stderr) => {
//           if (error) {
//             return res.status(200).send(stderr);
//           }
//           compileJavaFile(`${dirName}/${fileName}`, dirName, res);
//         }
//       );
//     }
//   );
// }
//
// // run java code
// export function run(req: $Request, res: $Response) {
//   let dirName = `users/${req.body.user._id}/`;
//   const dateTime = new Date();
//   dirName += dateTime.getMonth();
//   dirName += dateTime.getDate();
//   dirName += dateTime.getFullYear();
//   const execFile = req.body.fileName.replace(".c", "");
//   const cmd = `"${dirName}/${execFile}"`;
//   exec(
//     cmd,
//     { timeout: 10000 }, // Process will time out if running for > 10 seconds.
//     (error, stdout, stderr) => {
//       if (error) {
//         return res.status(200).send(error);
//       }
//       return res.status(200).send({ stdout, stderr });
//     }
//   );
// }
//
// function compileJavaFile(srcFile, dirName, res) {
//   const execFile = srcFile.replace(".c", "");
//   // exec is asynchronous
//   exec(
//     `gcc "${srcFile}" -o "${execFile}"`,
//     { timeout: 10000 }, // Process will time out if running for > 10 seconds.
//     (error, stdout, stderr) => {
//       if (error) {
//         return res.status(200).send(stderr);
//       }
//       return res.send(stdout);
//     }
//   );
// }

const docker = new Dockerode();

/** Starts `container` if it is not already running, then returns it.
*/
function startUbuntuContainerIfNecessary(container) {
  return container.inspect().then(data => {
    if (data.State.Running) {
      console.log("Container is already started, returning it now");
      return container;
    } else {
      return container.start().then(container => {
        console.log("Successful start, returning the container");
        return container;
      }).catch(err => {
        let errMsg = "Failed start: " + err;
        console.log(errMsg);
        return Promise.reject(errMsg);
      });
    }
  }).catch(err => {
    let errMsg = "Error inspecting container: " + err;
    console.log(errMsg);
    return Promise.reject(errMsg);
  });
}

/** Creates, starts, and returns an ubuntu Docker container, or starts and returns the existing one if it already exists.
*/
function createAndStartUbuntuContainer(containerName) {
  return docker.createContainer({
    Image: 'ubuntu',
    AttachStdin: false,
    AttachStdout: true,
    AttachStderr: true,
    Cmd: ['bash', '-c', 'touch a; tail -f a'],
    name: containerName
  }).then(container => {
    console.log("Successful creation, starting and returning the container now");
    return startUbuntuContainerIfNecessary(container);
  }).catch(err => {
    if (err.json.message.includes(`Conflict. The container name "/${containerName}" is already in use`)) {
      console.log(`Container ${containerName} already exists, starting and returning it now`);
      let container = docker.getContainer(containerName);
      return startUbuntuContainerIfNecessary(container);
    } else {
      let errMsg = "Failed creation: " + err;
      console.log(errMsg);
      return Promise.reject(errMsg);
    }
  });
}

function runCommandWithinContainer(cmd, container) {
  let timeLimitInSeconds = 10;
  let timeLimitInMilliseconds = timeLimitInSeconds * 1000;

  // Constructor for the type of object to which our returned Promise should resolve/reject
  let createResult = (stdout, stderr, execWasSuccessful, errorMsg) => {
    return {
      stdout,
      stderr,
      execWasSuccessful,
      errorMsg
    }
  }

  let execPromise = container.exec(cmd, {
    stdout: true,
    stderr: true
  });

  return timeout(execPromise, timeLimitInMilliseconds).then(
    results => {
      // TODO: kill and remove container
      console.log("We did it!!!");
      return createResult(results.stdout, results.stderr, true, null);
    },
    err => {
      if (err instanceof TimeoutError) {
        let errorMsg = `Timeout error: exec took longer than ${timeLimitInSeconds} seconds`;
        console.log(errorMsg);
        return createResult(null, null, false, errorMsg);
      } else {
        console.log("Error running exec: ", err);
        return createResult(null, null, false, err);
      }
    });
}

function myTest() {
  let cmd = ['echo', 'Hi'];
  let ubuntuContainerName = "ubuuuuuntuContaiiiiiner";
  createAndStartUbuntuContainer(ubuntuContainerName).then(
    ubuntuContainer => {
      runCommandWithinContainer(cmd, ubuntuContainer).then(result => {
        console.log("Now result is: ", result);
      }).catch(err => {
        console.log("Error: ", err);
      });
    },
    err => {
      console.log("No ubuntu container available to run the command!");
      console.log("Error received: ", err);
    });
}

myTest();

export async function compileLogger(req: $Request, res: $Response) {
  try {
    const userId = req.user.id;
    const loggerId = req.params.id;
    const logger = await Logger.findById(loggerId);
    if (!logger) {
      return res.status(400).json({
        error: `No logger found;`
      });
    }
    //console.log(logger);
    const dirName = "users/" + userId + "/" + loggerId;
    await exec("mkdir -p " + dirName);
    const escapedCode = jsesc(logger.code, {
      wrap: true
    });
    await exec(`echo ${escapedCode} > ${dirName}/${logger.className}.c`);
    const gcc = `gcc "${dirName}/${logger.className}.c" -o "${dirName}/${logger.className}" -lm`;
    //console.log(gcc);
    const result = await exec(gcc, {
      timeout: 10000
    });
    //console.error("result object", result);
    return res
      .status(200)
      .json({ error: false, stdout: result.stdout, stderr: result.stderr });
  } catch (err) {
    //console.error(err);
    return res
      .status(200)
      .json({ error: true, stdout: err.stdout, stderr: err.stderr });
  }
}

export async function runLogger(req: $Request, res: $Response) {
  try {
    const userId = req.user.id;
    const loggerId = req.params.id;
    const logger = await Logger.findById(loggerId);
    if (!logger) {
      return res.status(400).json({
        error: `No logger found;`
      });
    }
    const dirName = "users/" + userId + "/" + loggerId;
    const cmd = `"${dirName}/${logger.className}"`;
    const result = await exec(cmd, { timeout: 10000 });
    return res
      .status(200)
      .json({ error: false, stdout: result.stdout, stderr: result.stderr });
  } catch (err) {
    return res
      .status(200)
      .json({ error: true, stdout: err.stdout, stderr: err.stderr });
  }
}
<commit_msg>Refactoring<commit_after>// @flow
const Dockerode = require('simple-dockerode')

import type { $Request, $Response } from "express";

import { exec as execSync } from "child_process";
import jsesc from "jsesc";
import Logger from "../logger/logger.model";
import { promisify } from "util";
import { timeout, TimeoutError } from "promise-timeout";

const exec = promisify(execSync);

// Compile java code
// export function compile(req: $Request, res: $Response) {
//   const fileName = req.body.fileName;
//   let dirName = `users/${req.body.user._id}/`;
//   const dateTime = new Date();
//   dirName += dateTime.getMonth();
//   dirName += dateTime.getDate();
//   dirName += dateTime.getFullYear();
//
//   // make a directory for this user, if doesn't exist already
//   exec(
//     `mkdir -p ${dirName}`,
//     { timeout: 10000 }, // Process will time out if running for > 10 seconds.
//     (error, stdout, stderr) => {
//       if (error) {
//         return res.status(200).send(stderr);
//       }
//
//       const escapedCode = jsesc(req.body.code, {
//         wrap: true
//       });
//       exec(
//         `echo ${escapedCode} > ${dirName}/${fileName}`,
//         { timeout: 10000 }, // Process will time out if running for > 10 seconds.
//         (error, stdout, stderr) => {
//           if (error) {
//             return res.status(200).send(stderr);
//           }
//           compileJavaFile(`${dirName}/${fileName}`, dirName, res);
//         }
//       );
//     }
//   );
// }
//
// // run java code
// export function run(req: $Request, res: $Response) {
//   let dirName = `users/${req.body.user._id}/`;
//   const dateTime = new Date();
//   dirName += dateTime.getMonth();
//   dirName += dateTime.getDate();
//   dirName += dateTime.getFullYear();
//   const execFile = req.body.fileName.replace(".c", "");
//   const cmd = `"${dirName}/${execFile}"`;
//   exec(
//     cmd,
//     { timeout: 10000 }, // Process will time out if running for > 10 seconds.
//     (error, stdout, stderr) => {
//       if (error) {
//         return res.status(200).send(error);
//       }
//       return res.status(200).send({ stdout, stderr });
//     }
//   );
// }
//
// function compileJavaFile(srcFile, dirName, res) {
//   const execFile = srcFile.replace(".c", "");
//   // exec is asynchronous
//   exec(
//     `gcc "${srcFile}" -o "${execFile}"`,
//     { timeout: 10000 }, // Process will time out if running for > 10 seconds.
//     (error, stdout, stderr) => {
//       if (error) {
//         return res.status(200).send(stderr);
//       }
//       return res.send(stdout);
//     }
//   );
// }

const docker = new Dockerode();

/** Starts `container` if it is not already running, then returns it.
*/
function startUbuntuContainerIfNecessary(container) {
  return container.inspect().then(data => {
    if (data.State.Running) {
      console.log("Container is already started, returning it now");
      return container;
    } else {
      return container.start().then(container => {
        console.log("Successful start, returning the container");
        return container;
      }).catch(err => {
        let errMsg = "Failed start: " + err;
        console.log(errMsg);
        return Promise.reject(errMsg);
      });
    }
  }).catch(err => {
    let errMsg = "Error inspecting container: " + err;
    console.log(errMsg);
    return Promise.reject(errMsg);
  });
}

/** Creates, starts, and returns an ubuntu Docker container, or starts and returns the existing one if it already exists.
*/
function createAndStartUbuntuContainer(containerName) {
  return docker.createContainer({
    Image: 'ubuntu',
    AttachStdin: false,
    AttachStdout: true,
    AttachStderr: true,
    Cmd: ['bash', '-c', 'touch a; tail -f a'],
    name: containerName
  }).then(container => {
    console.log("Successful creation, starting and returning the container now");
    return startUbuntuContainerIfNecessary(container);
  }).catch(err => {
    if (err.json.message.includes(`Conflict. The container name "/${containerName}" is already in use`)) {
      console.log(`Container ${containerName} already exists, starting and returning it now`);
      let container = docker.getContainer(containerName);
      return startUbuntuContainerIfNecessary(container);
    } else {
      let errMsg = "Failed creation: " + err;
      console.log(errMsg);
      return Promise.reject(errMsg);
    }
  });
}

function runCommandWithinContainer(cmd, container) {
  let timeLimitInSeconds = 10;
  let timeLimitInMilliseconds = timeLimitInSeconds * 1000;

  let execPromise = container.exec(cmd, {
    stdout: true,
    stderr: true
  });

  return timeout(execPromise, timeLimitInMilliseconds).then(
    results => {
      // TODO: kill and remove container
      return {
        stdout: results.stdout,
        stderr: results.stderr,
        execWasSuccessful: true,
        execError: null
      };
    },
    err => {
      return {
        stdout: null,
        stderr: null,
        execWasSuccessful: false,
        execError: (err instanceof TimeoutError) ? `Timeout error: exec took longer than ${timeLimitInSeconds} seconds` : err
      }
    });
}

function myTest() {
  let cmd = ['echo', 'Hi'];
  let ubuntuContainerName = "ubuuuuuntuContaiiiiiner";
  createAndStartUbuntuContainer(ubuntuContainerName).then(
    ubuntuContainer => {
      runCommandWithinContainer(cmd, ubuntuContainer).then(result => {
        console.log("Now result is: ", result);
      }).catch(err => {
        console.log("Error: ", err);
      });
    },
    err => {
      console.log("No ubuntu container available to run the command!");
      console.log("Error received: ", err);
    });
}

myTest();

export async function compileLogger(req: $Request, res: $Response) {
  try {
    const userId = req.user.id;
    const loggerId = req.params.id;
    const logger = await Logger.findById(loggerId);
    if (!logger) {
      return res.status(400).json({
        error: `No logger found;`
      });
    }
    //console.log(logger);
    const dirName = "users/" + userId + "/" + loggerId;
    await exec("mkdir -p " + dirName);
    const escapedCode = jsesc(logger.code, {
      wrap: true
    });
    await exec(`echo ${escapedCode} > ${dirName}/${logger.className}.c`);
    const gcc = `gcc "${dirName}/${logger.className}.c" -o "${dirName}/${logger.className}" -lm`;
    //console.log(gcc);
    const result = await exec(gcc, {
      timeout: 10000
    });
    //console.error("result object", result);
    return res
      .status(200)
      .json({ error: false, stdout: result.stdout, stderr: result.stderr });
  } catch (err) {
    //console.error(err);
    return res
      .status(200)
      .json({ error: true, stdout: err.stdout, stderr: err.stderr });
  }
}

export async function runLogger(req: $Request, res: $Response) {
  try {
    const userId = req.user.id;
    const loggerId = req.params.id;
    const logger = await Logger.findById(loggerId);
    if (!logger) {
      return res.status(400).json({
        error: `No logger found;`
      });
    }
    const dirName = "users/" + userId + "/" + loggerId;
    const cmd = `"${dirName}/${logger.className}"`;
    const result = await exec(cmd, { timeout: 10000 });
    return res
      .status(200)
      .json({ error: false, stdout: result.stdout, stderr: result.stderr });
  } catch (err) {
    return res
      .status(200)
      .json({ error: true, stdout: err.stdout, stderr: err.stderr });
  }
}
<|endoftext|>