<commit_before>(function () {
    var AutoAdd = {
        "folders": {},
        "folderId": -1,
        "fldTable": new STable(),
        "config": {

        },

        "init": function () {
            var self = this;

            utWebUI.request("get", "action=autoadd-getwatchedfolders", null, function (data) {
                $each(data.folders, function (val) {
                    self.fldTable.addRow([val.Path, val.Label], val.Id);

                    // add to local dictionary as well
                    self.folders[val.Id] = val;
                });
            });
        },

        "colDefs": [
            ["path",  240, TYPE_STRING],
            ["label", 235, TYPE_STRING]
        ],

        "formatRow": function (values, index) {
            var useidx = $chk(index);

            if (useidx)
                return values[index];
            else
                return values;
        },

        "onColReset": function () {
            var config = {
                  "colMask": 0
			    , "colOrder": this.colDefs.map(function (item, idx) { return idx; })
			    , "colWidth": this.colDefs.map(function (item, idx) { return item[1]; })
            };

            this.colDefs.each(function (item, idx) { if (!!item[3]) config.colMask |= (1 << idx); });
            this.fldTable.setConfig(config);
        },

        "onSelect": function (ev, id) {
            // id is folder id
            if(has(this.folders, id)) {
                this.folderId = id;
            } else {
                this.folderId = -1;
            }
        },

        "refreshTable": function () {
            this.fldTable.calcSize();
            this.fldTable.restoreScroll();
            this.fldTable.resizePads();
        }
    };

    var html = '<fieldset>' +
                 '<legend>Watched folders</legend>' +
                 '

' +
                 '<input type="button" class="btn" value="Remove" id="autoadd_remove_folders" />' +
               '</fieldset>' +

               '<fieldset>' +
                 '<legend>Add folder</legend>' +

                 '
' +
                   '
' +
                     'Path
' +
                     '<input type="text" id="autoadd_add_folder_path" class="tbox wide" />' +
                   '
' +
                   '
' +
                     'Label
' +
                     '<input type="text" id="autoadd_add_folder_label" class="tbox" /> ' +
                     '<input type="button" class="btn" value="Add" id="autoadd_add_folder" />' +
                   '
' +
                 '
' +
               '</fieldset>';

    var settings = new Element("div", {
        id: "dlgSettings-Plugins-AutoAdd",
        "class": "settings-pane",
        html: html
    });

    settings.inject($("dlgSettings-body"));

    AutoAdd.fldTable.create("autoadd-Folders", AutoAdd.colDefs, {
        "rowMultiSelect": false,
        "format": AutoAdd.formatRow.bind(AutoAdd),
        "onColReset": AutoAdd.onColReset.bind(AutoAdd),
        "onSelect": AutoAdd.onSelect.bind(AutoAdd),
    });

    AutoAdd.fldTable.setConfig({
        "rowMaxCount": utWebUI.limits.maxVirtTableRows,
        "rowMode": MODE_VIRTUAL,
        "colText": {
            "path": "Path",
            "label": "Label"
        }
    });

    utWebUI.stpanes.addTab("dlgSettings-Plugins-AutoAdd", "AutoAdd").show("dlgSettings-General");

    var tblSize = $("dlgSettings-Plugins-AutoAdd").getDimensions({ computeSize: true });
    AutoAdd.fldTable.resizeTo(tblSize.x - 15, tblSize.y - 160);

    SettingsManager.addEvent("paneChanged", function (id) {
        if (id != "dlgSettings-Plugins-AutoAdd") return;

        AutoAdd.refreshTable();
    });

    $("autoadd_add_folder").addEvent("click", function () {
        var d = [{ "Path": $("autoadd_add_folder_path").get("value"), "Label": $("autoadd_add_folder_label").get("value")}];

        utWebUI.request("post", "action=autoadd-setwatchedfolders", d, function (folders) {
            for (var i = 0; i < folders.length; i++) {
                AutoAdd.fldTable.addRow([folders[i].Path, folders[i].Label], folders[i].Id);

                $("autoadd_add_folder_path").set("value", "");
                $("autoadd_add_folder_label").set("value", "");
            }

            AutoAdd.refreshTable();
        });
    });

    $("autoadd_remove_folders").addEvent("click", function() {
        if(AutoAdd.folderId === -1) {
            alert("Select folder to remove");
            return;
        }

        var d = [AutoAdd.folderId];

        utWebUI.request("post", "action=autoadd-remwatchedfolders", d, function(data) {
            for(var i = 0; i < data.removed.length; i++) {
                AutoAdd.fldTable.removeRow(data.removed[i]);
            }

            AutoAdd.refreshTable();
        });
    });

    AutoAdd.init();

    window.AutoAdd = AutoAdd;
})();<commit_msg>Fix in AutoAdd js class when adding a folder and directly after removing it it would not remove.<commit_after>(function () {
    var AutoAdd = {
        "folders": {},
        "folderId": -1,
        "fldTable": new STable(),
        "config": {

        },

        "init": function () {
            var self = this;

            utWebUI.request("get", "action=autoadd-getwatchedfolders", null, function (data) {
                $each(data.folders, function (val) {
                    self.addFolder(val);
                });
            });
        },

        "colDefs": [
            ["path",  240, TYPE_STRING],
            ["label", 235, TYPE_STRING]
        ],

        "formatRow": function (values, index) {
            var useidx = $chk(index);

            if (useidx)
                return values[index];
            else
                return values;
        },

        "onColReset": function () {
            var config = {
                  "colMask": 0
			    , "colOrder": this.colDefs.map(function (item, idx) { return idx; })
			    , "colWidth": this.colDefs.map(function (item, idx) { return item[1]; })
            };

            this.colDefs.each(function (item, idx) { if (!!item[3]) config.colMask |= (1 << idx); });
            this.fldTable.setConfig(config);
        },

        "onSelect": function (ev, id) {
            // id is folder id
            if(has(this.folders, id)) {
                this.folderId = id;
            } else {
                this.folderId = -1;
            }
        },

        "addFolder": function(val) {
            this.fldTable.addRow([val.Path, val.Label], val.Id);

            // add to local dictionary as well
            this.folders[val.Id] = val;
        },

        "refreshTable": function () {
            this.fldTable.calcSize();
            this.fldTable.restoreScroll();
            this.fldTable.resizePads();
        }
    };

    var html = '<fieldset>' +
                 '<legend>Watched folders</legend>' +
                 '

' +
                 '<input type="button" class="btn" value="Remove" id="autoadd_remove_folders" />' +
               '</fieldset>' +

               '<fieldset>' +
                 '<legend>Add folder</legend>' +

                 '
' +
                   '
' +
                     'Path
' +
                     '<input type="text" id="autoadd_add_folder_path" class="tbox wide" />' +
                   '
' +
                   '
' +
                     'Label
' +
                     '<input type="text" id="autoadd_add_folder_label" class="tbox" /> ' +
                     '<input type="button" class="btn" value="Add" id="autoadd_add_folder" />' +
                   '
' +
                 '
' +
               '</fieldset>';

    var settings = new Element("div", {
        id: "dlgSettings-Plugins-AutoAdd",
        "class": "settings-pane",
        html: html
    });

    settings.inject($("dlgSettings-body"));

    AutoAdd.fldTable.create("autoadd-Folders", AutoAdd.colDefs, {
        "rowMultiSelect": false,
        "format": AutoAdd.formatRow.bind(AutoAdd),
        "onColReset": AutoAdd.onColReset.bind(AutoAdd),
        "onSelect": AutoAdd.onSelect.bind(AutoAdd),
    });

    AutoAdd.fldTable.setConfig({
        "rowMaxCount": utWebUI.limits.maxVirtTableRows,
        "rowMode": MODE_VIRTUAL,
        "colText": {
            "path": "Path",
            "label": "Label"
        }
    });

    utWebUI.stpanes.addTab("dlgSettings-Plugins-AutoAdd", "AutoAdd").show("dlgSettings-General");

    var tblSize = $("dlgSettings-Plugins-AutoAdd").getDimensions({ computeSize: true });
    AutoAdd.fldTable.resizeTo(tblSize.x - 15, tblSize.y - 160);

    SettingsManager.addEvent("paneChanged", function (id) {
        if (id != "dlgSettings-Plugins-AutoAdd") return;

        AutoAdd.refreshTable();
    });

    $("autoadd_add_folder").addEvent("click", function () {
        var d = [{ "Path": $("autoadd_add_folder_path").get("value"), "Label": $("autoadd_add_folder_label").get("value")}];

        utWebUI.request("post", "action=autoadd-setwatchedfolders", d, function (folders) {
            for (var i = 0; i < folders.length; i++) {
                AutoAdd.addFolder(folders[i]);

                $("autoadd_add_folder_path").set("value", "");
                $("autoadd_add_folder_label").set("value", "");
            }

            AutoAdd.refreshTable();
        });
    });

    $("autoadd_remove_folders").addEvent("click", function() {
        if(AutoAdd.folderId === -1) {
            alert("Select folder to remove");
            return;
        }

        var d = [AutoAdd.folderId];

        utWebUI.request("post", "action=autoadd-remwatchedfolders", d, function(data) {
            for(var i = 0; i < data.removed.length; i++) {
                AutoAdd.fldTable.removeRow(data.removed[i]);
            }

            AutoAdd.refreshTable();
        });
    });

    AutoAdd.init();

    window.AutoAdd = AutoAdd;
})();<|endoftext|>


<commit_before>// Generated on <%= (new Date).toISOString().split('T')[0] %> using
// <%= pkg.name %> <%= pkg.version %>
'use strict';

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

module.exports = function (grunt) {

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

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

  // Configurable paths
  var config = {
    app: 'app',
    dist: 'dist'
  };

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

    // Project settings
    config: config,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%%= config.app %>/scripts/{,*/}*.js'],
        tasks: ['jshint'],
        options: {
          livereload: true
        }
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },<% if (includeSass) { %>
      sass: {
        files: ['<%%= config.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['sass:server', 'autoprefixer']
      },<% } %>
      styles: {
        files: ['<%%= config.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: '<%%= connect.options.livereload %>'
        },
        files: [
          '<%%= config.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%%= config.app %>/images/{,*/}*'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        open: true,
        livereload: 35729,
        // Change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      livereload: {
        options: {
          middleware: function(connect) {
            return [
              connect.static('.tmp'),
              connect().use('/bower_components', connect.static('./bower_components')),
              connect.static(config.app)
            ];
          }
        }
      },
      dist: {
        options: {
          base: '<%%= config.dist %>',
          livereload: false
        }
      }
    },

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

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

    // Compiles Sass to CSS and generates necessary files if requested
    sass: {
      options: {<% if (includeLibSass) { %>
        sourceMap: true,
        includePaths: ['bower_components']
        <% } else { %>
        sourcemap: true,
        loadPath: 'bower_components'
      <% } %>},
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= config.app %>/styles',
          src: ['*.{scss,sass}'],
          dest: '.tmp/styles',
          ext: '.css'
        }]
      },
      server: {
        files: [{
          expand: true,
          cwd: '<%%= config.app %>/styles',
          src: ['*.{scss,sass}'],
          dest: '.tmp/styles',
          ext: '.css'
        }]
      }
    },<% } %>

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the HTML file
    wiredep: {
      app: {
        ignorePath: /^<%= config.app %>\/|\.\.\//,
        src: ['<%%= config.app %>/index.html']<% if (includeBootstrap) { %>,<% if (includeSass) { %>
        exclude: ['bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js']<% } else { %>
        exclude: ['bower_components/bootstrap/dist/js/bootstrap.js']<% } } %>
      }<% if (includeSass) { %>,
      sass: {
        src: ['<%%= config.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }<% } %>
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%%= config.dist %>/scripts/{,*/}*.js',
            '<%%= config.dist %>/styles/{,*/}*.css',
            '<%%= config.dist %>/images/{,*/}*.*',
            '<%%= config.dist %>/styles/fonts/{,*/}*.*',
            '<%%= config.dist %>/*.{ico,png}'
          ]
        }
      }
    },

    // 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: {
      options: {
        dest: '<%%= config.dist %>'
      },
      html: '<%%= config.app %>/index.html'
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      options: {
        assetsDirs: ['<%%= config.dist %>', '<%%= config.dist %>/images']
      },
      html: ['<%%= config.dist %>/{,*/}*.html'],
      css: ['<%%= config.dist %>/styles/{,*/}*.css']
    },

    // The following *-min tasks produce minified files in the dist folder
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= config.app %>/images',
          src: '{,*/}*.{gif,jpeg,jpg,png}',
          dest: '<%%= config.dist %>/images'
        }]
      }
    },

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

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

    // 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: {
    //       '<%%= config.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css',
    //         '<%%= config.app %>/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%%= config.dist %>/scripts/scripts.js': [
    //         '<%%= config.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= config.app %>',
          dest: '<%%= config.dist %>',
          src: [
            '*.{ico,png,txt}',
            'images/{,*/}*.webp',
            '{,*/}*.html',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          src: 'node_modules/apache-server-configs/dist/.htaccess',
          dest: '<%%= config.dist %>/.htaccess'
        }<% if (includeBootstrap) { %>, {
          expand: true,
          dot: true,
          cwd: '<% if (includeSass) {
              %>.<%
            } else {
              %>bower_components/bootstrap/dist<%
            } %>',
          src: '<% if (includeSass) {
              %>bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*<%
            } else {
              %>fonts/*<%
            } %>',
          dest: '<%%= config.dist %>'
        }<% } %>]
      },
      styles: {
        expand: true,
        dot: true,
        cwd: '<%%= config.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },<% if (includeModernizr) { %>

    // reference in your app
    modernizr: {
      dist: {
        devFile: 'bower_components/modernizr/modernizr.js',
        outputFile: '<%%= config.dist %>/scripts/vendor/modernizr.js',
        files: {
          src: [
            '<%%= config.dist %>/scripts/{,*/}*.js',
            '<%%= config.dist %>/styles/{,*/}*.css',
            '!<%%= config.dist %>/scripts/vendor/*'
          ]
        },
        uglify: true
      }
    },<% } %><% if (includeCache) { %>
    manifest: {
        generate: {
            options: {
                basePath: "<%= config.dist %>",
                network: ["*"],
                preferOnline: false,
                timestamp: true
            },
            src: [
                // Put HTML, CSS and JS first (not sure if it makes a difference)
            "**/*.html",
            "**/*.css",
            "**/*.js",
            // Then include everything else...
            "**/*.*",
            // .. but exclude these
            "!apple-touch-*",
            "!favicon.ico",
            "!cache.manifest",
            "!robots.txt"
                ],
            dest: "<%= config.dist %>/cache.manifest"
        },<% } %>

    // Run some tasks in parallel to speed up build process
    concurrent: {
      server: [<% if (includeSass) { %>
        'sass:server',
        'copy:styles'
      ],
      dist: [<% } if (includeSass) { %>
        'sass',<% } %>
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    }
  });

  grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
    if (grunt.option('allow-remote')) {
      grunt.config.set('connect.options.hostname', '0.0.0.0');
    }
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

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

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

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'cssmin',
    'uglify',
    'copy:dist',<% if (includeModernizr) { %>
    'modernizr',<% } %>
    'rev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'build'
  ]);
};
<commit_msg>fix some bugs<commit_after>// Generated on <%= (new Date).toISOString().split('T')[0] %> using
// <%= pkg.name %> <%= pkg.version %>
'use strict';

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

module.exports = function (grunt) {

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

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

  // Configurable paths
  var config = {
    app: 'app',
    dist: 'dist'
  };

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

    // Project settings
    config: config,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%%= config.app %>/scripts/{,*/}*.js'],
        tasks: ['jshint'],
        options: {
          livereload: true
        }
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },<% if (includeSass) { %>
      sass: {
        files: ['<%%= config.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['sass:server', 'autoprefixer']
      },<% } %>
      styles: {
        files: ['<%%= config.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: '<%%= connect.options.livereload %>'
        },
        files: [
          '<%%= config.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%%= config.app %>/images/{,*/}*'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        open: true,
        livereload: 35729,
        // Change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      livereload: {
        options: {
          middleware: function(connect) {
            return [
              connect.static('.tmp'),
              connect().use('/bower_components', connect.static('./bower_components')),
              connect.static(config.app)
            ];
          }
        }
      },
      dist: {
        options: {
          base: '<%%= config.dist %>',
          livereload: false
        }
      }
    },

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

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

    // Compiles Sass to CSS and generates necessary files if requested
    sass: {
      options: {<% if (includeLibSass) { %>
        sourceMap: true,
        includePaths: ['bower_components']
        <% } else { %>
        sourcemap: true,
        loadPath: 'bower_components'
      <% } %>},
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= config.app %>/styles',
          src: ['*.{scss,sass}'],
          dest: '.tmp/styles',
          ext: '.css'
        }]
      },
      server: {
        files: [{
          expand: true,
          cwd: '<%%= config.app %>/styles',
          src: ['*.{scss,sass}'],
          dest: '.tmp/styles',
          ext: '.css'
        }]
      }
    },<% } %>

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the HTML file
    wiredep: {
      app: {
        ignorePath: /^<%= config.app %>\/|\.\.\//,
        src: ['<%%= config.app %>/index.html']<% if (includeBootstrap) { %>,<% if (includeSass) { %>
        exclude: ['bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js']<% } else { %>
        exclude: ['bower_components/bootstrap/dist/js/bootstrap.js']<% } } %>
      }<% if (includeSass) { %>,
      sass: {
        src: ['<%%= config.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }<% } %>
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%%= config.dist %>/scripts/{,*/}*.js',
            '<%%= config.dist %>/styles/{,*/}*.css',
            '<%%= config.dist %>/images/{,*/}*.*',
            '<%%= config.dist %>/styles/fonts/{,*/}*.*',
            '<%%= config.dist %>/*.{ico,png}'
          ]
        }
      }
    },

    // 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: {
      options: {
        dest: '<%%= config.dist %>'
      },
      html: '<%%= config.app %>/index.html'
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      options: {
        assetsDirs: ['<%%= config.dist %>', '<%%= config.dist %>/images']
      },
      html: ['<%%= config.dist %>/{,*/}*.html'],
      css: ['<%%= config.dist %>/styles/{,*/}*.css']
    },

    // The following *-min tasks produce minified files in the dist folder
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= config.app %>/images',
          src: '{,*/}*.{gif,jpeg,jpg,png}',
          dest: '<%%= config.dist %>/images'
        }]
      }
    },

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

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

    // 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: {
    //       '<%%= config.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css',
    //         '<%%= config.app %>/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%%= config.dist %>/scripts/scripts.js': [
    //         '<%%= config.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= config.app %>',
          dest: '<%%= config.dist %>',
          src: [
            '*.{ico,png,txt}',
            'images/{,*/}*.webp',
            '{,*/}*.html',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          src: 'node_modules/apache-server-configs/dist/.htaccess',
          dest: '<%%= config.dist %>/.htaccess'
        }<% if (includeBootstrap) { %>, {
          expand: true,
          dot: true,
          cwd: '<% if (includeSass) {
              %>.<%
            } else {
              %>bower_components/bootstrap/dist<%
            } %>',
          src: '<% if (includeSass) {
              %>bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*<%
            } else {
              %>fonts/*<%
            } %>',
          dest: '<%%= config.dist %>'
        }<% } %>]
      },
      styles: {
        expand: true,
        dot: true,
        cwd: '<%%= config.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },<% if (includeModernizr) { %>

    // reference in your app
    modernizr: {
      dist: {
        devFile: 'bower_components/modernizr/modernizr.js',
        outputFile: '<%%= config.dist %>/scripts/vendor/modernizr.js',
        files: {
          src: [
            '<%%= config.dist %>/scripts/{,*/}*.js',
            '<%%= config.dist %>/styles/{,*/}*.css',
            '!<%%= config.dist %>/scripts/vendor/*'
          ]
        },
        uglify: true
      }
    },<% } %><% if (includeCache) { %>
    manifest: {
        generate: {
            options: {
                basePath: "<%%= config.dist %>",
                network: ["*"],
                preferOnline: false,
                timestamp: true
            },
            src: [
                // Put HTML, CSS and JS first (not sure if it makes a difference)
            "**/*.html",
            "**/*.css",
            "**/*.js",
            // Then include everything else...
            "**/*.*",
            // .. but exclude these
            "!apple-touch-*",
            "!favicon.ico",
            "!cache.manifest",
            "!robots.txt"
                ],
            dest: "<%%= config.dist %>/cache.manifest"
        }
    },<% } %>

    // Run some tasks in parallel to speed up build process
    concurrent: {
      server: [<% if (includeSass) { %>
        'sass:server',<% } %>
        'copy:styles'
      ],
      dist: [<% if (includeSass) { %>
        'sass',<% } %>
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    }
  });

  grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
    if (grunt.option('allow-remote')) {
      grunt.config.set('connect.options.hostname', '0.0.0.0');
    }
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

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

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

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'cssmin',
    'uglify',
    'copy:dist',<% if (includeModernizr) { %>
    'modernizr',<% } %>
    'rev',
    'usemin',
    'htmlmin'<% if (includeCache) { %>,
    'manifest:generate'<% } %>
  ]);

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


<commit_before>'use strict';

var gulp     = require('gulp'),
	stylish    = require('jshint-stylish'),
	path       = require('path'),
	connect  	= require('gulp-connect'),
	http       = require('http'),
	open       = require('open'),
	fs         = require('fs'),
	chalk      = require('chalk'),
	args       = require('yargs').argv,
	browserSync = require('browser-sync'),
	runSequence = require('run-sequence'),
	map         = require('map-stream');

var gulpPlugins = require('gulp-load-plugins')();

var	SETTINGS = {
	src: {
		app: 'app/',
		css: 'app/css/',
		js: 'app/js/',
		templates: 'app/templates/',
		images: 'app/images/',
		fonts: 'app/fonts/',
		bower: 'bower_components/'
	},
	build: {
		app: 'build/',
		css: 'build/css/',
		js: 'build/js/',
		templates: 'build/templates/',
		images: 'build/images/',
		fonts: 'build/fonts/',
		bower: 'build/js/'
	},
	scss: 'scss/'
};

//server and live reload config
var serverConfig = {
	root : 'build',
	host : 'localhost',
	port : 9000,
	livereload: true
};

// jsHint Options.
var hintOptions = JSON.parse(fs.readFileSync('.jshintrc', 'utf8'));

// Flag for generating production code.
var isProduction = args.type === 'production';

/*============================================================
=                          Server (Live - Reload)            =
============================================================*/

gulp.task('local:server', function () {
	connect.server(serverConfig);
	console.log('Started connect web server on http://localhost:' + serverConfig.port + '.');
	open('http://localhost:' + serverConfig.port);
});

gulp.task('server', ['local:server'], function () {
	console.log('------------------>>>> firing server  <<<<-----------------------');
});

/*============================================================
=                          JS-HINT                          =
============================================================*/

gulp.task('js:hint', function () {

	console.log('-------------------------------------------------- JS - HINT');
	var stream = gulp.src([SETTINGS.src.js + 'app.js', '!' + SETTINGS.src.js + 'plugins/*.js', SETTINGS.src.js + '**/*.js', 'gulpfile.js'])
		.pipe(gulpPlugins.jshint(hintOptions))
		.pipe(gulpPlugins.jshint.reporter(stylish));
	return stream;
});

/*============================================================
=                          Concat                           =
============================================================*/

gulp.task('concat', ['concat:bower', 'concat:js', 'concat:css']);

gulp.task('concat:bower', function () {
	console.log('-------------------------------------------------- CONCAT :bower');

	var jsFilter = gulpPlugins.filter('**/*.js'),
		cssFilter = gulpPlugins.filter('**/*.css'),
		assetsFilter = gulpPlugins.filter(['!**/*.js', '!**/*.css', '!**/*.scss']);

	gulpPlugins.bowerFiles()
		.pipe(jsFilter)
		.pipe(gulpPlugins.concat('_bower.min.js'))
		.pipe(gulpPlugins.if(isProduction, gulpPlugins.uglify()))
		.pipe(gulp.dest(SETTINGS.build.bower))
		.pipe(jsFilter.restore())
		.pipe(cssFilter)
		.pipe(gulpPlugins.sass())
		.pipe(map(function (file, callback) {
			var relativePath = path.dirname(path.relative(path.resolve(SETTINGS.src.bower), file.path));

			// CSS path resolving
			// Taken from https://github.com/enyojs/enyo/blob/master/tools/minifier/minify.js
			var contents = file.contents.toString().replace(/url\([^)]*\)/g, function (match) {
				// find the url path, ignore quotes in url string
				var matches = /url\s*\(\s*(('([^']*)')|("([^"]*)")|([^'"]*))\s*\)/.exec(match),
					url = matches[3] || matches[5] || matches[6];

				// Don't modify data and http(s) urls
				if (/^data:/.test(url) || /^http(:?s)?:/.test(url)) {
					return 'url(' + url + ')';
				}
				return 'url(' + path.join(path.relative(SETTINGS.build.bower, SETTINGS.build.app), SETTINGS.build.bower, relativePath, url) + ')';
			});
			file.contents = new Buffer(contents);

			callback(null, file);
		}))
		.pipe(gulpPlugins.concat('_bower.css'))
		.pipe(gulp.dest(SETTINGS.build.bower))
		.pipe(cssFilter.restore())
		.pipe(assetsFilter)
		.pipe(gulp.dest(SETTINGS.build.bower))
		.pipe(assetsFilter.restore())
		.pipe(connect.reload());
});

gulp.task('concat:js', ['js:hint'], function () {

	console.log('-------------------------------------------------- CONCAT :js');
	gulp.src([SETTINGS.src.js + 'plugins/*.js', SETTINGS.src.js + 'app.js', SETTINGS.src.js + '*.js', SETTINGS.src.js + '**/*.js'])
	    .pipe(gulpPlugins.concat('all.js'))
	    .pipe(gulpPlugins.if(isProduction, gulpPlugins.uglify()))
	    .pipe(gulp.dest(SETTINGS.build.js))
	    .pipe(connect.reload());
});

gulp.task('convert:scss', function () {
	console.log('-------------------------------------------------- COVERT - scss');

    var stream = gulp.src(SETTINGS.src.css + 'application.scss')
       .pipe(gulpPlugins.sass({includePaths: [SETTINGS.src.css]}))
       .pipe(gulp.dest(SETTINGS.scss))
       .pipe(connect.reload());
    return stream;
});

gulp.task('concat:css', ['convert:scss'], function () {

	console.log('-------------------------------------------------- CONCAT :css ');
	gulp.src([SETTINGS.src.css + 'reset-api.css', SETTINGS.src.css + 'fonts.css', SETTINGS.scss + 'application.css', SETTINGS.src.css + '*.css'])
	    .pipe(gulpPlugins.concat('styles.css'))
	    .pipe(gulpPlugins.if(isProduction, gulpPlugins.minifyCss({keepSpecialComments: '*'})))
	    .pipe(gulp.dest(SETTINGS.build.css))
	    .pipe(connect.reload());
});

/*============================================================
=                          Minify				            =
============================================================*/

gulp.task('image:min', function () {
	gulp.src(SETTINGS.src.images + '**')
        .pipe(gulpPlugins.imagemin())
        .pipe(gulp.dest(SETTINGS.build.images))
        .pipe(connect.reload());
});

/*============================================================
=                           Copy                            =
============================================================*/

gulp.task('copy', ['copy:html', 'copy:images', 'copy:fonts', 'copy:html:root']);

gulp.task('copy:html', function () {

	console.log('-------------------------------------------------- COPY :html');
	gulp.src([SETTINGS.src.templates + '*.html', SETTINGS.src.templates + '**/*.html'])
		.pipe(gulpPlugins.if(isProduction, gulpPlugins.minifyHtml({comments: false, quotes: true, spare: true, empty: true, cdata: true})))
		.pipe(gulp.dest(SETTINGS.build.templates))
		.pipe(connect.reload());
});

gulp.task('copy:html:root', function () {

	console.log('-------------------------------------------------- COPY :html:root');
	gulp.src(SETTINGS.src.app + '*.html')
		.pipe(gulpPlugins.if(isProduction, gulpPlugins.minifyHtml({comments: false, quotes: true, spare: true, empty: true, cdata: true})))
		.pipe(gulp.dest(SETTINGS.build.app))
		.pipe(connect.reload());
});

gulp.task('copy:images', function () {

	console.log('-------------------------------------------------- COPY :images');
	gulp.src([SETTINGS.src.images + '*.*', SETTINGS.src.images + '**/*.*'])
		.pipe(gulp.dest(SETTINGS.build.images));
});

gulp.task('copy:fonts', function () {

	console.log('-------------------------------------------------- COPY :fonts');
	gulp.src([SETTINGS.src.fonts + '*', SETTINGS.src.fonts + '**/*'])
		.pipe(gulp.dest(SETTINGS.build.fonts));
});

/*=========================================================================================================
=												Watch

	Incase the watch fails due to limited number of watches available on your sysmtem, the execute this
	command on terminal

	$ echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
=========================================================================================================*/

gulp.task('watch', function () {

	console.log('watching all the files.....');

	var watchedFiles = [];

	watchedFiles.push(gulp.watch([SETTINGS.src.css + '*.css',  SETTINGS.src.css + '**/*.css'],  ['concat:css']));

	watchedFiles.push(gulp.watch([SETTINGS.src.css + '*.scss', SETTINGS.src.css + '**/*.scss'], ['concat:css']));

    watchedFiles.push(gulp.watch([SETTINGS.src.js + '*.js',    SETTINGS.src.js + '**/*.js'],    ['concat:js']));

    watchedFiles.push(gulp.watch([SETTINGS.src.app + '*.html'], ['copy:html:root']));

	watchedFiles.push(gulp.watch([SETTINGS.src.images + '*.*', SETTINGS.src.images + '**/*.*'], ['copy:images']));

	watchedFiles.push(gulp.watch([SETTINGS.src.fonts + '*.*',  SETTINGS.src.fonts + '**/*.*'],  ['copy:fonts']));

	watchedFiles.push(gulp.watch([SETTINGS.src.bower + '*.js', SETTINGS.src.bower + '**/*.js'], ['concat:bower']));

	watchedFiles.push(gulp.watch([SETTINGS.src.templates + '*.html', SETTINGS.src.templates + '**/*.html'], ['copy:html']));

	// Just to add log messages on Terminal, in case any file is changed
	var onChange = function (event) {
		if (event.type == 'deleted') {
			runSequence('clean');
			setTimeout(function () {
				runSequence('copy', 'concat', 'watch');
			}, 500);
		}
		console.log(chalk.red('-------------------------------------------------->>>> File ' + event.path + ' was ------->>>> ' + event.type));
	};

	watchedFiles.forEach(function (watchedFile) {
		watchedFile.on('change', onChange);
	});

});

/*============================================================
=                             Clean                          =
============================================================*/

var cleanFiles = function (files, logMessage) {
	console.log('-------------------------------------------------- CLEAN :' + logMessage);
	gulp.src(files, {read: false})
		.pipe(gulpPlugins.clean({force: true}));
};

gulp.task('clean', function () {
	cleanFiles([SETTINGS.build.app], 'all files');
});

gulp.task('clean:css', function () {
	cleanFiles([SETTINGS.build.css], 'css');
});

gulp.task('clean:js', function () {
	cleanFiles([SETTINGS.build.js], 'js');
});

gulp.task('clean:html', function () {
	cleanFiles([SETTINGS.build.templates], 'html');
});

gulp.task('clean:images', function () {
	cleanFiles([SETTINGS.build.images], 'images');
});

gulp.task('clean:fonts', function () {
	cleanFiles([SETTINGS.build.fonts + '*.*', SETTINGS.build.fonts + '**/*.*'], 'fonts');
});

gulp.task('clean:zip', function () {
	cleanFiles(['zip/**/*', '!zip/build-*.zip'], 'zip');
});

/*============================================================
=                             Zip                          =
============================================================*/

gulp.task('zip', function () {
    gulp.src([SETTINGS.build.app + '*', SETTINGS.build.app + '**/*'])
        .pipe(gulpPlugins.zip('build-' + new Date() + '.zip'))
        .pipe(gulp.dest('./zip/'));

    setTimeout(function () {
		runSequence('clean:zip');
    }, 500); // wait for file creation

});

/*============================================================
=                             Start                          =
============================================================*/

gulp.task('build', function () {
	console.log(chalk.blue('-------------------------------------------------- BUILD - Development Mode'));
	runSequence('copy', 'concat', 'watch');
});

gulp.task('build:prod', function () {
	console.log(chalk.blue('-------------------------------------------------- BUILD - Production Mode'));
	isProduction = true;
	runSequence('copy', 'concat', 'watch');
});

gulp.task('default', ['build', 'server']);

// Just in case you are too lazy to type: $ gulp --type production
gulp.task('prod', ['build:prod', 'server']);

/*============================================================
=                       Browser Sync                         =
============================================================*/

gulp.task('bs', function () {
    browserSync.init([SETTINGS.build.app + 'index.html', SETTINGS.build + 'templates/*.html', SETTINGS.build.css + '*css', SETTINGS.build.js + '*.js'], {
		proxy: {
            host: '127.0.0.1',
            port: SETTINGS.serverPort
        }
    });
});<commit_msg>added server port to brower sync<commit_after>'use strict';

var gulp     = require('gulp'),
	stylish    = require('jshint-stylish'),
	path       = require('path'),
	connect  	= require('gulp-connect'),
	http       = require('http'),
	open       = require('open'),
	fs         = require('fs'),
	chalk      = require('chalk'),
	args       = require('yargs').argv,
	browserSync = require('browser-sync'),
	runSequence = require('run-sequence'),
	map         = require('map-stream');

var gulpPlugins = require('gulp-load-plugins')();

var	SETTINGS = {
	src: {
		app: 'app/',
		css: 'app/css/',
		js: 'app/js/',
		templates: 'app/templates/',
		images: 'app/images/',
		fonts: 'app/fonts/',
		bower: 'bower_components/'
	},
	build: {
		app: 'build/',
		css: 'build/css/',
		js: 'build/js/',
		templates: 'build/templates/',
		images: 'build/images/',
		fonts: 'build/fonts/',
		bower: 'build/js/'
	},
	scss: 'scss/'
};

//server and live reload config
var serverConfig = {
	root : 'build',
	host : 'localhost',
	port : 9000,
	livereload: true
};

// jsHint Options.
var hintOptions = JSON.parse(fs.readFileSync('.jshintrc', 'utf8'));

// Flag for generating production code.
var isProduction = args.type === 'production';

/*============================================================
=                          Server (Live - Reload)            =
============================================================*/

gulp.task('local:server', function () {
	connect.server(serverConfig);
	console.log('Started connect web server on http://localhost:' + serverConfig.port + '.');
	open('http://localhost:' + serverConfig.port);
});

gulp.task('server', ['local:server'], function () {
	console.log('------------------>>>> firing server  <<<<-----------------------');
});

/*============================================================
=                          JS-HINT                          =
============================================================*/

gulp.task('js:hint', function () {

	console.log('-------------------------------------------------- JS - HINT');
	var stream = gulp.src([SETTINGS.src.js + 'app.js', '!' + SETTINGS.src.js + 'plugins/*.js', SETTINGS.src.js + '**/*.js', 'gulpfile.js'])
		.pipe(gulpPlugins.jshint(hintOptions))
		.pipe(gulpPlugins.jshint.reporter(stylish));
	return stream;
});

/*============================================================
=                          Concat                           =
============================================================*/

gulp.task('concat', ['concat:bower', 'concat:js', 'concat:css']);

gulp.task('concat:bower', function () {
	console.log('-------------------------------------------------- CONCAT :bower');

	var jsFilter = gulpPlugins.filter('**/*.js'),
		cssFilter = gulpPlugins.filter('**/*.css'),
		assetsFilter = gulpPlugins.filter(['!**/*.js', '!**/*.css', '!**/*.scss']);

	gulpPlugins.bowerFiles()
		.pipe(jsFilter)
		.pipe(gulpPlugins.concat('_bower.min.js'))
		.pipe(gulpPlugins.if(isProduction, gulpPlugins.uglify()))
		.pipe(gulp.dest(SETTINGS.build.bower))
		.pipe(jsFilter.restore())
		.pipe(cssFilter)
		.pipe(gulpPlugins.sass())
		.pipe(map(function (file, callback) {
			var relativePath = path.dirname(path.relative(path.resolve(SETTINGS.src.bower), file.path));

			// CSS path resolving
			// Taken from https://github.com/enyojs/enyo/blob/master/tools/minifier/minify.js
			var contents = file.contents.toString().replace(/url\([^)]*\)/g, function (match) {
				// find the url path, ignore quotes in url string
				var matches = /url\s*\(\s*(('([^']*)')|("([^"]*)")|([^'"]*))\s*\)/.exec(match),
					url = matches[3] || matches[5] || matches[6];

				// Don't modify data and http(s) urls
				if (/^data:/.test(url) || /^http(:?s)?:/.test(url)) {
					return 'url(' + url + ')';
				}
				return 'url(' + path.join(path.relative(SETTINGS.build.bower, SETTINGS.build.app), SETTINGS.build.bower, relativePath, url) + ')';
			});
			file.contents = new Buffer(contents);

			callback(null, file);
		}))
		.pipe(gulpPlugins.concat('_bower.css'))
		.pipe(gulp.dest(SETTINGS.build.bower))
		.pipe(cssFilter.restore())
		.pipe(assetsFilter)
		.pipe(gulp.dest(SETTINGS.build.bower))
		.pipe(assetsFilter.restore())
		.pipe(connect.reload());
});

gulp.task('concat:js', ['js:hint'], function () {

	console.log('-------------------------------------------------- CONCAT :js');
	gulp.src([SETTINGS.src.js + 'plugins/*.js', SETTINGS.src.js + 'app.js', SETTINGS.src.js + '*.js', SETTINGS.src.js + '**/*.js'])
	    .pipe(gulpPlugins.concat('all.js'))
	    .pipe(gulpPlugins.if(isProduction, gulpPlugins.uglify()))
	    .pipe(gulp.dest(SETTINGS.build.js))
	    .pipe(connect.reload());
});

gulp.task('convert:scss', function () {
	console.log('-------------------------------------------------- COVERT - scss');

    var stream = gulp.src(SETTINGS.src.css + 'application.scss')
       .pipe(gulpPlugins.sass({includePaths: [SETTINGS.src.css]}))
       .pipe(gulp.dest(SETTINGS.scss))
       .pipe(connect.reload());
    return stream;
});

gulp.task('concat:css', ['convert:scss'], function () {

	console.log('-------------------------------------------------- CONCAT :css ');
	gulp.src([SETTINGS.src.css + 'reset-api.css', SETTINGS.src.css + 'fonts.css', SETTINGS.scss + 'application.css', SETTINGS.src.css + '*.css'])
	    .pipe(gulpPlugins.concat('styles.css'))
	    .pipe(gulpPlugins.if(isProduction, gulpPlugins.minifyCss({keepSpecialComments: '*'})))
	    .pipe(gulp.dest(SETTINGS.build.css))
	    .pipe(connect.reload());
});

/*============================================================
=                          Minify				            =
============================================================*/

gulp.task('image:min', function () {
	gulp.src(SETTINGS.src.images + '**')
        .pipe(gulpPlugins.imagemin())
        .pipe(gulp.dest(SETTINGS.build.images))
        .pipe(connect.reload());
});

/*============================================================
=                           Copy                            =
============================================================*/

gulp.task('copy', ['copy:html', 'copy:images', 'copy:fonts', 'copy:html:root']);

gulp.task('copy:html', function () {

	console.log('-------------------------------------------------- COPY :html');
	gulp.src([SETTINGS.src.templates + '*.html', SETTINGS.src.templates + '**/*.html'])
		.pipe(gulpPlugins.if(isProduction, gulpPlugins.minifyHtml({comments: false, quotes: true, spare: true, empty: true, cdata: true})))
		.pipe(gulp.dest(SETTINGS.build.templates))
		.pipe(connect.reload());
});

gulp.task('copy:html:root', function () {

	console.log('-------------------------------------------------- COPY :html:root');
	gulp.src(SETTINGS.src.app + '*.html')
		.pipe(gulpPlugins.if(isProduction, gulpPlugins.minifyHtml({comments: false, quotes: true, spare: true, empty: true, cdata: true})))
		.pipe(gulp.dest(SETTINGS.build.app))
		.pipe(connect.reload());
});

gulp.task('copy:images', function () {

	console.log('-------------------------------------------------- COPY :images');
	gulp.src([SETTINGS.src.images + '*.*', SETTINGS.src.images + '**/*.*'])
		.pipe(gulp.dest(SETTINGS.build.images));
});

gulp.task('copy:fonts', function () {

	console.log('-------------------------------------------------- COPY :fonts');
	gulp.src([SETTINGS.src.fonts + '*', SETTINGS.src.fonts + '**/*'])
		.pipe(gulp.dest(SETTINGS.build.fonts));
});

/*=========================================================================================================
=												Watch

	Incase the watch fails due to limited number of watches available on your sysmtem, the execute this
	command on terminal

	$ echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
=========================================================================================================*/

gulp.task('watch', function () {

	console.log('watching all the files.....');

	var watchedFiles = [];

	watchedFiles.push(gulp.watch([SETTINGS.src.css + '*.css',  SETTINGS.src.css + '**/*.css'],  ['concat:css']));

	watchedFiles.push(gulp.watch([SETTINGS.src.css + '*.scss', SETTINGS.src.css + '**/*.scss'], ['concat:css']));

    watchedFiles.push(gulp.watch([SETTINGS.src.js + '*.js',    SETTINGS.src.js + '**/*.js'],    ['concat:js']));

    watchedFiles.push(gulp.watch([SETTINGS.src.app + '*.html'], ['copy:html:root']));

	watchedFiles.push(gulp.watch([SETTINGS.src.images + '*.*', SETTINGS.src.images + '**/*.*'], ['copy:images']));

	watchedFiles.push(gulp.watch([SETTINGS.src.fonts + '*.*',  SETTINGS.src.fonts + '**/*.*'],  ['copy:fonts']));

	watchedFiles.push(gulp.watch([SETTINGS.src.bower + '*.js', SETTINGS.src.bower + '**/*.js'], ['concat:bower']));

	watchedFiles.push(gulp.watch([SETTINGS.src.templates + '*.html', SETTINGS.src.templates + '**/*.html'], ['copy:html']));

	// Just to add log messages on Terminal, in case any file is changed
	var onChange = function (event) {
		if (event.type == 'deleted') {
			runSequence('clean');
			setTimeout(function () {
				runSequence('copy', 'concat', 'watch');
			}, 500);
		}
		console.log(chalk.red('-------------------------------------------------->>>> File ' + event.path + ' was ------->>>> ' + event.type));
	};

	watchedFiles.forEach(function (watchedFile) {
		watchedFile.on('change', onChange);
	});

});

/*============================================================
=                             Clean                          =
============================================================*/

var cleanFiles = function (files, logMessage) {
	console.log('-------------------------------------------------- CLEAN :' + logMessage);
	gulp.src(files, {read: false})
		.pipe(gulpPlugins.clean({force: true}));
};

gulp.task('clean', function () {
	cleanFiles([SETTINGS.build.app], 'all files');
});

gulp.task('clean:css', function () {
	cleanFiles([SETTINGS.build.css], 'css');
});

gulp.task('clean:js', function () {
	cleanFiles([SETTINGS.build.js], 'js');
});

gulp.task('clean:html', function () {
	cleanFiles([SETTINGS.build.templates], 'html');
});

gulp.task('clean:images', function () {
	cleanFiles([SETTINGS.build.images], 'images');
});

gulp.task('clean:fonts', function () {
	cleanFiles([SETTINGS.build.fonts + '*.*', SETTINGS.build.fonts + '**/*.*'], 'fonts');
});

gulp.task('clean:zip', function () {
	cleanFiles(['zip/**/*', '!zip/build-*.zip'], 'zip');
});

/*============================================================
=                             Zip                          =
============================================================*/

gulp.task('zip', function () {
    gulp.src([SETTINGS.build.app + '*', SETTINGS.build.app + '**/*'])
        .pipe(gulpPlugins.zip('build-' + new Date() + '.zip'))
        .pipe(gulp.dest('./zip/'));

    setTimeout(function () {
		runSequence('clean:zip');
    }, 500); // wait for file creation

});

/*============================================================
=                             Start                          =
============================================================*/

gulp.task('build', function () {
	console.log(chalk.blue('-------------------------------------------------- BUILD - Development Mode'));
	runSequence('copy', 'concat', 'watch');
});

gulp.task('build:prod', function () {
	console.log(chalk.blue('-------------------------------------------------- BUILD - Production Mode'));
	isProduction = true;
	runSequence('copy', 'concat', 'watch');
});

gulp.task('default', ['build', 'server']);

// Just in case you are too lazy to type: $ gulp --type production
gulp.task('prod', ['build:prod', 'server']);

/*============================================================
=                       Browser Sync                         =
============================================================*/

gulp.task('bs', function () {
    browserSync.init([SETTINGS.build.app + 'index.html', SETTINGS.build + 'templates/*.html', SETTINGS.build.css + '*css', SETTINGS.build.js + '*.js'], {
		proxy: {
            host: '127.0.0.1',
            port: serverConfig.port
        }
    });
});<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('foundation.core.animation', [])
    .service('FoundationAnimation', FoundationAnimation)
  ;

  function FoundationAnimation() {
    var animations = [];
    var service = {};

    var initClasses        = ['ng-enter', 'ng-leave'];
    var activeClasses      = ['ng-enter-active', 'ng-leave-active'];
    var activeGenericClass = 'is-active';
    var events = [
      'webkitAnimationEnd', 'mozAnimationEnd',
      'MSAnimationEnd', 'oanimationend',
      'animationend', 'webkitTransitionEnd',
      'otransitionend', 'transitionend'
    ];

    service.animate = animate;
    service.toggleAnimation = toggleAnimation;

    return service;

    function toggleAnimation(element, futureState) {
      if(futureState) {
        element.addClass(activeGenericClass);
      } else {
        element.removeClass(activeGenericClass);
      }
    }

    function animate(element, futureState, animationIn, animationOut) {
      var timedOut = true;
      var self = this;
      self.cancelAnimation = cancelAnimation;

      var animationClass = futureState ? animationIn: animationOut;
      var activation = futureState;
      var initClass = activation ? initClasses[0] : initClasses[1];
      var activeClass = activation ? activeClasses[0] : activeClasses[1];
      //stop animation
      registerElement(element);
      reset();
      element.addClass(animationClass);
      element.addClass(initClass);

      element.addClass(activeGenericClass);

      //force a "tick"
      reflow();

      //activate
      element[0].style.transitionDuration = '';
      element.addClass(activeClass);

      element.one(events.join(' '), function() {
        finishAnimation();
      });

      setTimeout(function() {
        if(timedOut) {
          finishAnimation();
        }
      }, 3000);

      function finishAnimation() {
        deregisterElement(element);
        reset(); //reset all classes
        element[0].style.transitionDuration = '';
        element.removeClass(!activation ? activeGenericClass : ''); //if not active, remove active class
        reflow();
        timedOut = false;
      }

      function cancelAnimation(element) {
        deregisterElement(element);
        angular.element(element).off(events.join(' ')); //kill all animation event handlers
        timedOut = false;
      }

      function registerElement(el) {
        var elObj = {
          el: el,
          animation: self
        };

        //kill in progress animations
        var inProgress = animations.filter(function(obj) {
          return obj.el === el;
        });
        if(inProgress.length > 0) {
          var target = inProgress[0].el[0];

          inProgress[0].animation.cancelAnimation(target);
        }

        animations.push(elObj);
      }

      function deregisterElement(el) {
        var index;
        var currentAnimation = animations.filter(function(obj, ind) {
          if(obj.el === el) {
            index = ind;
          }
        });

        if(index >= 0) {
          animations.splice(index, 1);
        }

      }

      function reflow() {
        return element[0].offsetWidth;
      }

      function reset() {
        element[0].style.transitionDuration = 0;
        element.removeClass(initClasses.join(' ') + ' ' + activeClasses.join(' ') + ' ' + animationIn + ' ' + animationOut);
      }
    }
  }

})();
<commit_msg>javascript adjustment to animations<commit_after>(function() {
  'use strict';

  angular.module('foundation.core.animation', [])
    .service('FoundationAnimation', FoundationAnimation)
  ;

  function FoundationAnimation() {
    var animations = [];
    var service = {};

    var initClasses        = ['ng-enter', 'ng-leave'];
    var activeClasses      = ['ng-enter-active', 'ng-leave-active'];
    var activeGenericClass = 'is-active';
    var events = [
      'webkitAnimationEnd', 'mozAnimationEnd',
      'MSAnimationEnd', 'oanimationend',
      'animationend', 'webkitTransitionEnd',
      'otransitionend', 'transitionend'
    ];

    service.animate = animate;
    service.toggleAnimation = toggleAnimation;

    return service;

    function toggleAnimation(element, futureState) {
      if(futureState) {
        element.addClass(activeGenericClass);
      } else {
        element.removeClass(activeGenericClass);
      }
    }

    function animate(element, futureState, animationIn, animationOut) {
      var timedOut = true;
      var self = this;
      self.cancelAnimation = cancelAnimation;

      var animationClass = futureState ? animationIn: animationOut;
      var activation = futureState;
      var initClass = activation ? initClasses[0] : initClasses[1];
      var activeClass = activation ? activeClasses[0] : activeClasses[1];
      //stop animation
      registerElement(element);
      reset();
      element.addClass(animationClass);
      element.addClass(initClass);

      element.addClass(activeGenericClass);

      //force a "tick"
      reflow();

      //activate
      element[0].style.transitionDuration = '';
      element.addClass(activeClass);

      element.on(events.join(' '), eventHandler);

      function eventHandler(e) {
        if (element[0] === e.path[0]) {
          clearTimeout(animationTimeout);
          finishAnimation();
        }
      }

      var animationTimeout = setTimeout(function() {
        if(timedOut) {
          finishAnimation();
        }
      }, 3000);

      function finishAnimation() {
        deregisterElement(element);
        reset(); //reset all classes
        element[0].style.transitionDuration = '';
        element.removeClass(!activation ? activeGenericClass : ''); //if not active, remove active class
        reflow();
        timedOut = false;
        element.off(events.join(' '), eventHandler);
      }

      function cancelAnimation(element) {
        deregisterElement(element);
        angular.element(element).off(events.join(' ')); //kill all animation event handlers
        timedOut = false;
      }

      function registerElement(el) {
        var elObj = {
          el: el,
          animation: self
        };

        //kill in progress animations
        var inProgress = animations.filter(function(obj) {
          return obj.el === el;
        });
        if(inProgress.length > 0) {
          var target = inProgress[0].el[0];

          inProgress[0].animation.cancelAnimation(target);
        }

        animations.push(elObj);
      }

      function deregisterElement(el) {
        var index;
        var currentAnimation = animations.filter(function(obj, ind) {
          if(obj.el === el) {
            index = ind;
          }
        });

        if(index >= 0) {
          animations.splice(index, 1);
        }

      }

      function reflow() {
        return element[0].offsetWidth;
      }

      function reset() {
        element[0].style.transitionDuration = 0;
        element.removeClass(initClasses.join(' ') + ' ' + activeClasses.join(' ') + ' ' + animationIn + ' ' + animationOut);
      }
    }
  }

})();
<|endoftext|>


<commit_before>import EventPost from 'flarum/components/EventPost';
import extractText from 'flarum/utils/extractText';

/**
 * The `DiscussionRenamedPost` component displays a discussion event post
 * indicating that the discussion has been renamed.
 *
 * ### Props
 *
 * - All of the props for EventPost
 */
export default class DiscussionRenamedPost extends EventPost {
  icon() {
    return 'pencil';
  }

  description(data) {
    const renamed = app.translator.trans('core.forum.post_stream.discussion_renamed_text', data);
    const oldName = app.translator.trans('core.forum.post_stream.discussion_renamed_old_text', data);

    return {renamed};
  }

  descriptionData() {
    const post = this.props.post;
    const oldTitle = post.content()[0];
    const newTitle = post.content()[1];

    return {
      'old': oldTitle,
      'new': {newTitle}
    };
  }
}
<commit_msg>Fix locale key<commit_after>import EventPost from 'flarum/components/EventPost';
import extractText from 'flarum/utils/extractText';

/**
 * The `DiscussionRenamedPost` component displays a discussion event post
 * indicating that the discussion has been renamed.
 *
 * ### Props
 *
 * - All of the props for EventPost
 */
export default class DiscussionRenamedPost extends EventPost {
  icon() {
    return 'pencil';
  }

  description(data) {
    const renamed = app.translator.trans('core.forum.post_stream.discussion_renamed_text', data);
    const oldName = app.translator.trans('core.forum.post_stream.discussion_renamed_old_tooltip', data);

    return {renamed};
  }

  descriptionData() {
    const post = this.props.post;
    const oldTitle = post.content()[0];
    const newTitle = post.content()[1];

    return {
      'old': oldTitle,
      'new': {newTitle}
    };
  }
}
<|endoftext|>


<commit_before>var isBrowser  = require('is-browser');
var plask      = isBrowser ? {} : require('plask');
var now        = require("performance-now");

var WindowImpl = require('./WindowImpl');
var Context    = require('pex-context/Context');

function WindowImplPlask(){
    WindowImpl.call(this);

    this.plaskObj = null;
    this.title = '';
}

WindowImplPlask.prototype = Object.create(WindowImpl.prototype);
WindowImplPlask.prototype.constructor = WindowImplPlask;

WindowImplPlask.prototype.setFullScreen = function(){
    this.plaskObj.setFullScreen(this.title);
    this.fullScreen = !this.fullScreen;
};

WindowImplPlask.create = function(windowPex,settings){
    settings.type = settings.type || '3d';
    settings.multisample = settings.multisample === undefined ? true : settings.multisample;
    settings.title = settings.title || 'pex';

    var impl = new WindowImplPlask();

    var obj = {};
    obj.settings = settings;
    obj.init = function(){
        this.framerate(60);

        var mouse = windowPex._mouse;

        this.on('mouseDown', function(e) {
            mouse.handleMouseDown({
                x        : e.x,
                y        : e.y,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('mouseUp', function(e) {
            mouse.handleMouseUp({
                x        : e.x,
                y        : e.y,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('mouseMoved', function(e) {
            mouse.handleMouseMove({
                x        : e.x,
                y        : e.y,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('mouseDragged', function(e) {
            //mouse move events are not fired while dragging
            mouse.handleMouseMove({
                x        : e.x,
                y        : e.y,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('scrollWheel', function(e) {
            mouse.handleMouseScroll({
                dx       : e.dx,
                dy       : e.dy,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        var keyboard = windowPex._keyboard;

        this.on('keyDown', function(e) {
            keyboard.handleKeyDown({
                str      : '',
                keyCode  : e.keyCode,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
            keyboard.handleKeyPress({
                str      : e.str,
                keyCode  : e.keyCode,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('keyUp', function(e) {
            keyboard.handleKeyUp({
                str      : '',
                keyCode  : e.keyCode,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        impl.plaskObj = this;
        impl.width    = this.width;
        impl.height   = this.height;

        windowPex._impl = impl;
        windowPex._ctx  = new Context(this.gl);

        windowPex.init();
    };

    obj.draw = function(){
        windowPex._time._update(now());
        windowPex.draw();
    };

    plask.simpleWindow(obj);

    return impl;
};

module.exports = WindowImplPlask;

<commit_msg>WindowImplPlask forward fullScreen setting to fullscreen required in Plask<commit_after>var isBrowser  = require('is-browser');
var plask      = isBrowser ? {} : require('plask');
var now        = require("performance-now");

var WindowImpl = require('./WindowImpl');
var Context    = require('pex-context/Context');

function WindowImplPlask(){
    WindowImpl.call(this);

    this.plaskObj = null;
    this.title = '';
}

WindowImplPlask.prototype = Object.create(WindowImpl.prototype);
WindowImplPlask.prototype.constructor = WindowImplPlask;

WindowImplPlask.prototype.setFullScreen = function(){
    this.plaskObj.setFullScreen(this.title);
    this.fullScreen = !this.fullScreen;
};

WindowImplPlask.create = function(windowPex,settings){
    settings.type = settings.type || '3d';
    settings.multisample = settings.multisample === undefined ? true : settings.multisample;
    settings.title = settings.title || 'pex';
    settings.fullscreen = settings.fullScreen;

    var impl = new WindowImplPlask();

    var obj = {};
    obj.settings = settings;
    obj.init = function(){
        this.framerate(60);

        var mouse = windowPex._mouse;

        this.on('mouseDown', function(e) {
            mouse.handleMouseDown({
                x        : e.x,
                y        : e.y,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('mouseUp', function(e) {
            mouse.handleMouseUp({
                x        : e.x,
                y        : e.y,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('mouseMoved', function(e) {
            mouse.handleMouseMove({
                x        : e.x,
                y        : e.y,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('mouseDragged', function(e) {
            //mouse move events are not fired while dragging
            mouse.handleMouseMove({
                x        : e.x,
                y        : e.y,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('scrollWheel', function(e) {
            mouse.handleMouseScroll({
                dx       : e.dx,
                dy       : e.dy,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        var keyboard = windowPex._keyboard;

        this.on('keyDown', function(e) {
            keyboard.handleKeyDown({
                str      : '',
                keyCode  : e.keyCode,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
            keyboard.handleKeyPress({
                str      : e.str,
                keyCode  : e.keyCode,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        this.on('keyUp', function(e) {
            keyboard.handleKeyUp({
                str      : '',
                keyCode  : e.keyCode,
                altKey   : e.option,
                shiftKey : e.shift,
                ctrlKey  : e.ctrl,
                metaKey  : e.cmd
            });
        });

        impl.plaskObj = this;
        impl.width    = this.width;
        impl.height   = this.height;

        windowPex._impl = impl;
        windowPex._ctx  = new Context(this.gl);

        windowPex.init();
    };

    obj.draw = function(){
        windowPex._time._update(now());
        windowPex.draw();
    };

    plask.simpleWindow(obj);

    return impl;
};

module.exports = WindowImplPlask;
<|endoftext|>


<commit_before>/*jshint globalstrict:false, strict:false, maxlen: 500 */
/*global assertEqual, AQL_EXECUTE, AQL_EXPLAIN */

////////////////////////////////////////////////////////////////////////////////
/// @brief tests for primary index
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");
var helper = require("@arangodb/aql-helper");
var db = require("@arangodb").db;

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////

function explainSuite () {
  var cn = "UnitTestsAhuacatlPrimary";
  var c;

  var explain = function (query, params) {
    return helper.getCompactPlan(AQL_EXPLAIN(query, params, { optimizer: { rules: [ "-all", "+use-indexes" ] } })).map(function(node) { return node.type; });
  };

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db._drop(cn);
      c = db._create(cn);

      for (var i = 0; i < 100; ++i) {
        c.save({ _key: "testkey" + i, value: i });
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

    tearDown : function () {
      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test lookup by non-existing _key
////////////////////////////////////////////////////////////////////////////////

    testKeyNotExisting : function () {
      var keys = [
        'foobar',
        'baz',
        '123',
        '',
        ' this key is not valid',
        ' testkey1',
        'testkey100',
        'testkey1000',
        1,
        100,
        false,
        true,
        null
      ];
      var query = "FOR i IN " + cn + " FILTER i._key == @key RETURN i";

      keys.forEach(function(key) {
        assertEqual([ "SingletonNode", "ScatterNode", "RemoteNode", "IndexNode", "RemoteNode", "GatherNode", "CalculationNode", "FilterNode", "ReturnNode" ], explain(query, { key: key }));
        assertEqual([ ], AQL_EXECUTE(query, { key: key }).json);
      });
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test lookup by existing _key
////////////////////////////////////////////////////////////////////////////////

    testKeyExisting : function () {
      var query = "FOR i IN " + cn + " FILTER i._key == @key RETURN i.value";
      for (var i = 0; i < 100; ++i) {
        assertEqual([ "SingletonNode", "ScatterNode", "RemoteNode", "IndexNode", "RemoteNode", "GatherNode", "CalculationNode", "FilterNode", "CalculationNode", "ReturnNode" ], explain(query, { key: "testkey" + i }));
        assertEqual([ i ], AQL_EXECUTE(query, { key: "testkey" + i }).json);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test lookup by non-existing _id
////////////////////////////////////////////////////////////////////////////////

    testIdNotExisting : function () {
      var ids = [
        '_users/testkey10',
        ' ' + cn + '/testkey10',
        'othercollection/testkey1',
        'othercollection/testkey10',
        cn + '/testkey100',
        cn + '/testkey101',
        cn + '/testkey1000',
        cn + '/testkey-1',
        'foobar',
        'baz',
        '123',
        '',
        ' this key is not valid',
        ' testkey1',
        'testkey100',
        'testkey1000',
        1,
        100,
        false,
        true,
        null
      ];
      var query = "FOR i IN " + cn + " FILTER i._id == @id RETURN i";

      ids.forEach(function(id) {
        assertEqual([ "SingletonNode", "ScatterNode", "RemoteNode", "IndexNode", "RemoteNode", "GatherNode", "CalculationNode", "FilterNode", "ReturnNode" ], explain(query, { id: id }));
        assertEqual([ ], AQL_EXECUTE(query, { id: id }).json);
      });
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test lookup by existing _id
////////////////////////////////////////////////////////////////////////////////

    testIdExisting : function () {
      var query = "FOR i IN " + cn + " FILTER i._id == @id RETURN i.value";
      for (var i = 0; i < 100; ++i) {
        assertEqual([ "SingletonNode", "ScatterNode", "RemoteNode", "IndexNode", "RemoteNode", "GatherNode", "CalculationNode", "FilterNode", "CalculationNode", "ReturnNode" ], explain(query, { id: cn + "/testkey" + i }));
        assertEqual([ i ], AQL_EXECUTE(query, { id: cn + "/testkey" + i }).json);
      }
    },

    testInvalidValuesinList : function () {
      var query = "FOR x IN @idList FOR i IN " + cn + " FILTER i._id == x SORT i.value RETURN i.value";
      var bindParams = {
        idList: [
          null,
          cn + "/testkey1", // Find this
          "blub/bla",
          "noKey",
          cn + "/testkey2", // And this
          123456,
          { "the": "foxx", "is": "wrapped", "in":"objects"},
          [15, "man", "on", "the", "dead", "mans", "chest"],
          cn + "/testkey3" // And this
        ]
      };
      assertEqual([ 1, 2, 3], AQL_EXECUTE(query, bindParams).json);
    },

    testInvalidValuesInINFilter : function () {
      var query = "FOR i IN " + cn + " FILTER i._id IN @idList SORT i.value RETURN i.value";
      var bindParams = {
        idList: [
          null,
          cn + "/testkey1", // Find this
          "blub/bla",
          "noKey",
          cn + "/testkey2", // And this
          123456,
          { "the": "foxx", "is": "wrapped", "in":"objects"},
          [15, "man", "on", "the", "dead", "mans", "chest"],
          cn + "/testkey3" // And this
        ]
      };
      require("internal").db._explain(query, bindParams);
      assertEqual([ 1, 2, 3], AQL_EXECUTE(query, bindParams).json);
    }
  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////

jsunity.run(explainSuite);

return jsunity.done();

<commit_msg>removed useless explain<commit_after>/*jshint globalstrict:false, strict:false, maxlen: 500 */
/*global assertEqual, AQL_EXECUTE, AQL_EXPLAIN */

////////////////////////////////////////////////////////////////////////////////
/// @brief tests for primary index
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");
var helper = require("@arangodb/aql-helper");
var db = require("@arangodb").db;

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////

function explainSuite () {
  var cn = "UnitTestsAhuacatlPrimary";
  var c;

  var explain = function (query, params) {
    return helper.getCompactPlan(AQL_EXPLAIN(query, params, { optimizer: { rules: [ "-all", "+use-indexes" ] } })).map(function(node) { return node.type; });
  };

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db._drop(cn);
      c = db._create(cn);

      for (var i = 0; i < 100; ++i) {
        c.save({ _key: "testkey" + i, value: i });
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

    tearDown : function () {
      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test lookup by non-existing _key
////////////////////////////////////////////////////////////////////////////////

    testKeyNotExisting : function () {
      var keys = [
        'foobar',
        'baz',
        '123',
        '',
        ' this key is not valid',
        ' testkey1',
        'testkey100',
        'testkey1000',
        1,
        100,
        false,
        true,
        null
      ];
      var query = "FOR i IN " + cn + " FILTER i._key == @key RETURN i";

      keys.forEach(function(key) {
        assertEqual([ "SingletonNode", "ScatterNode", "RemoteNode", "IndexNode", "RemoteNode", "GatherNode", "CalculationNode", "FilterNode", "ReturnNode" ], explain(query, { key: key }));
        assertEqual([ ], AQL_EXECUTE(query, { key: key }).json);
      });
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test lookup by existing _key
////////////////////////////////////////////////////////////////////////////////

    testKeyExisting : function () {
      var query = "FOR i IN " + cn + " FILTER i._key == @key RETURN i.value";
      for (var i = 0; i < 100; ++i) {
        assertEqual([ "SingletonNode", "ScatterNode", "RemoteNode", "IndexNode", "RemoteNode", "GatherNode", "CalculationNode", "FilterNode", "CalculationNode", "ReturnNode" ], explain(query, { key: "testkey" + i }));
        assertEqual([ i ], AQL_EXECUTE(query, { key: "testkey" + i }).json);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test lookup by non-existing _id
////////////////////////////////////////////////////////////////////////////////

    testIdNotExisting : function () {
      var ids = [
        '_users/testkey10',
        ' ' + cn + '/testkey10',
        'othercollection/testkey1',
        'othercollection/testkey10',
        cn + '/testkey100',
        cn + '/testkey101',
        cn + '/testkey1000',
        cn + '/testkey-1',
        'foobar',
        'baz',
        '123',
        '',
        ' this key is not valid',
        ' testkey1',
        'testkey100',
        'testkey1000',
        1,
        100,
        false,
        true,
        null
      ];
      var query = "FOR i IN " + cn + " FILTER i._id == @id RETURN i";

      ids.forEach(function(id) {
        assertEqual([ "SingletonNode", "ScatterNode", "RemoteNode", "IndexNode", "RemoteNode", "GatherNode", "CalculationNode", "FilterNode", "ReturnNode" ], explain(query, { id: id }));
        assertEqual([ ], AQL_EXECUTE(query, { id: id }).json);
      });
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test lookup by existing _id
////////////////////////////////////////////////////////////////////////////////

    testIdExisting : function () {
      var query = "FOR i IN " + cn + " FILTER i._id == @id RETURN i.value";
      for (var i = 0; i < 100; ++i) {
        assertEqual([ "SingletonNode", "ScatterNode", "RemoteNode", "IndexNode", "RemoteNode", "GatherNode", "CalculationNode", "FilterNode", "CalculationNode", "ReturnNode" ], explain(query, { id: cn + "/testkey" + i }));
        assertEqual([ i ], AQL_EXECUTE(query, { id: cn + "/testkey" + i }).json);
      }
    },

    testInvalidValuesinList : function () {
      var query = "FOR x IN @idList FOR i IN " + cn + " FILTER i._id == x SORT i.value RETURN i.value";
      var bindParams = {
        idList: [
          null,
          cn + "/testkey1", // Find this
          "blub/bla",
          "noKey",
          cn + "/testkey2", // And this
          123456,
          { "the": "foxx", "is": "wrapped", "in":"objects"},
          [15, "man", "on", "the", "dead", "mans", "chest"],
          cn + "/testkey3" // And this
        ]
      };
      assertEqual([ 1, 2, 3], AQL_EXECUTE(query, bindParams).json);
    },

    testInvalidValuesInINFilter : function () {
      var query = "FOR i IN " + cn + " FILTER i._id IN @idList SORT i.value RETURN i.value";
      var bindParams = {
        idList: [
          null,
          cn + "/testkey1", // Find this
          "blub/bla",
          "noKey",
          cn + "/testkey2", // And this
          123456,
          { "the": "foxx", "is": "wrapped", "in":"objects"},
          [15, "man", "on", "the", "dead", "mans", "chest"],
          cn + "/testkey3" // And this
        ]
      };
      assertEqual([ 1, 2, 3], AQL_EXECUTE(query, bindParams).json);
    }
  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////

jsunity.run(explainSuite);

return jsunity.done();

<|endoftext|>


<commit_before>(function($){

	var countdown=function(){

	}

	var proto=countdown.prototype;

	proto.constructor=countdown;

	proto.convert(time){
		var result=[];
		var dayTime=1000*60*60*24,
			hourTime=1000*60*60,
			minuteTime=1000*60,
			secondTime=1000;

		var day=Math.floor(time/dayTime);
		var	hour=Math.floor((time-day*dayTime)/hourTime);
		var minute=Math.floor((time-day*dayTime-hour*hourTime)/minuteTime);
		var second=Math.floor((time-day*dayTime-hour*hourTime-minute*minuteTime)/secondTime);
		console.log('day:'+day+'hour:'+hour+'minute:'+minute+'second:'+second);
		result.push(second);
		result.push(minute);
		result.push(hour);
		result.push(day);
		return result;
	}

})($)
<commit_msg>update<commit_after>(function($){

	var countdown=function(){

	}

	var handle;

	var proto=countdown.prototype;

	proto.constructor=countdown;

	proto.convert=function(time){
		var result=[];
		var dayTime=1000*60*60*24,
			hourTime=1000*60*60,
			minuteTime=1000*60,
			secondTime=1000;

		var day=Math.floor(time/dayTime);
		var	hour=Math.floor((time-day*dayTime)/hourTime);
		var minute=Math.floor((time-day*dayTime-hour*hourTime)/minuteTime);
		var second=Math.floor((time-day*dayTime-hour*hourTime-minute*minuteTime)/secondTime);
		console.log('day:'+day+'hour:'+hour+'minute:'+minute+'second:'+second);
		result.push(second);
		result.push(minute);
		result.push(hour);
		result.push(day);
		return result;
	}

	proto.start=function(){
		var $countdown=this.children();
		setTimeInterval(function(){
			var _date=new Date();
			var _arr=proto.convert(_date.getTime());
			$countdown.eq(0).text=_arr[0];
			$countdown.eq(1).text=_arr[1];
			$countdown.eq(2).text=_arr[2];
			$countdown.eq(3).text=_arr[3];
		})
	}

	proto.stop=function(){
		handle.clearInterval();
		return;
	}

})($)
<|endoftext|>


<commit_before>/**
 * Created with JetBrains WebStorm.
 * User: Alex
 * Date: 17.9.15
 * Time: 7.26
 * To change this template use File | Settings | File Templates.
 */
'use strict'
var str = "";
var i = 0;
var path = document.querySelectorAll("path");

function select(event) {
    var id = event.target.id;
    var elem = document.querySelector("#" + id + "> .marker");
    var color = window.getComputedStyle(elem).backgroundColor;
    for (i = 0; i < path.length; i++) {
        if ((path[i].getAttribute('fill')).slice(0,15) == (color.slice(0,15))) {
            str = path[i].getAttribute('d');
            path[i].setAttribute('d', "M 0.5 0.5  L 0.5 0  A 0.5 0.5 0 0 1 1 0.5 z");
            path[i].setAttribute('stroke', "red");
            path[i].setAttribute('stroke-width', "0.01");
            document.querySelector("svg > text").innerHTML = "25%";
            break;
        }
    }
}

function unSelect(event) {
    path[i].setAttribute('d', str);
    path[i].setAttribute('stroke', "none");
    document.querySelector("svg > text").innerHTML = "100%";
}

function calculatePie() {
    var data = {a: 20, b: 120, c: 300};
    var sum = 0;
    var r = 0.5;

    for (var key in data) {
        sum += data[key];
}
    var deg = sum/360;
    var angel = {};
    var x = {};
    var y = {};
    var angelSum = 0;

    for (key in data) {
        angel[key] = data[key]/deg;
    if (angelSum <=90){
        if ((angel[key] >= 90) && (angel[key] <= 180)) {
            x[key] = r + r * Math.sin(Math.PI - (angel[key]*Math.PI/180));
            y[key] = r + r * Math.sin(Math.PI * (1/2 - (1 - (angel[key]/180))));
        } else {
             if (angel[key] < 90){
                x[key] = r + r * Math.sin(Math.PI * angel[key]/180);
                y[key] = r - r * Math.sin(Math.PI/2 - (angel[key]*Math.PI/180));
             } else {
            // in this place code are building half circle
                var ang = angel[key] - 180;
                x[key] = r * Math.sin(Math.PI * (1/2 - (ang/180)));
                y[key] = r * Math.sin(ang * Math.PI/180);
                }
            }
        angelSum += angel[key];
    }
        if ((angelSum > 90) && (angelSum <= 180)){
            if ((angel[key] >= 90) && (angel[key] <= 180)) {
                x[key] = r + r * Math.sin(Math.PI - (angel[key]*Math.PI/180));
                y[key] = r + r * Math.sin(Math.PI * (1/2 - (1 - (angel[key]/180))));
            } else {
                if (angel[key] < 90){
                    x[key] = r * Math.sin(Math.PI * (1/2 - (angel[key]/180)));
                    y[key] = r * Math.sin(angel[key]*Math.PI/180);
                } else {
                    // in this place code are building half circle
                    var ang = angel[key] - 180;
                    x[key] = r * Math.sin(Math.PI * (1/2 - (ang/180)));
                    y[key] = r * Math.sin(ang * Math.PI/180);
                }
            }
            angelSum += angel[key];
        }
        if ((angelSum > 180) && (angelSum <= 270)){
            if ((angel[key] >= 90) && (angel[key] <= 180)) {
                x[key] = r + r * Math.sin(Math.PI - (angel[key]*Math.PI/180));
                y[key] = r + r * Math.sin(Math.PI * (1/2 - (1 - (angel[key]/180))));
            } else {
                if (angel[key] < 90){
                    x[key] = r - r * Math.sin(Math.PI * (angel[key]/180 - 1));
                    y[key] = r * Math.sin(angel[key]*Math.PI/180);
                } else {
                    // in this place code are building half circle
                    var ang = angel[key] - 180;
                    x[key] = r * Math.sin(Math.PI * (1/2 - (ang/180)));
                    y[key] = r * Math.sin(ang * Math.PI/180);
                }
            }
            angelSum += angel[key];
        }
        if ((angelSum > 270) && (angelSum <= 360)){
            if ((angel[key] >= 90) && (angel[key] <= 180)) {
                x[key] = r + r * Math.sin(Math.PI - (angel[key]*Math.PI/180));
                y[key] = r + r * Math.sin(Math.PI * (1/2 - (1 - (angel[key]/180))));
            } else {
                if (angel[key] < 90){
                    x[key] = r * Math.sin(Math.PI * (1/2 - (angel[key]/180)));
                    y[key] = r * Math.sin(angel[key]*Math.PI/180);
                } else {
                    // in this place code are building half circle
                    var ang = angel[key] - 180;
                    x[key] = r * Math.sin(Math.PI * (1/2 - (ang/180)));
                    y[key] = r * Math.sin(ang * Math.PI/180);
                }
            }
            angelSum += angel[key];
        }
        buildPie(x, y);
    }
}

function buildPie(x, y) {
    var color = 0;
    var center = "M 0.5 0.5 ";
    var path = '';
    var start = "L 0.5 0 "
    var svg = document.querySelector(".demo-char > svg");
    for (var key in x){
        path = path + '<path d=\"' + center + start + 'A 0.5 0.5 0 0 1 ' + x[key] + ' ' + y[key] + ' z\" ' +
            'fill=\"rgba(' + color +', ' + color +', 255, 0.75)\" />';
        start = 'L ' + x[key] + ' ' + y[key] + ' ';
        color += 100;

    }
    document.querySelector("#svg").innerHTML = path;
      //  <path d="M 0.5 0.5  L 0.5 0.1  A 0.4 0.4 0 0 1 0.9 0.5 z"  fill="rgba(100, 255, 255, 0.75)" />
}

calculatePie();

<commit_msg>Delete pieChart.js<commit_after><|endoftext|>