<commit_before>module.exports = function (grunt)
{
    'use strict';

    grunt.loadNpmTasks('grunt-contrib-compass');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-replace');
    grunt.loadNpmTasks('grunt-shell');

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        opt : {
            timestamp: '<%= new Date().getTime() %>'
        },

        watch: {
            sass: {
                files: ['src/style/*.scss', 'src/style/*/sass/**'],
                tasks: ['sass', 'compress:theme']
            },

            theme: {
                files: ['!src/style/*/sass/**', '!src/style/*/js/**', 'src/style/*/**'],
                tasks: ['theme']
            },

            js: {
                files: 'src/style/*/js/**',
                tasks: ['jshint', 'uglify', 'compress:theme']
            }
        },

        compass: {
            dev: {
                options: {
                    config: 'config.rb',
                    force: true
                }
            }
        },

        copy: {
            branding: {
                files: [
                    {expand: true, cwd: 'bower_components/textpattern-branding/assets/img/', src: ['**'], dest: 'public/style/Textpattern/img/branding/'},
                    {expand: true, cwd: 'bower_components/textpattern-branding/assets/img/apple-touch-icon/textpattern/', src: ['**'], dest: 'public/'},
                    {expand: true, cwd: 'bower_components/textpattern-branding/assets/img/favicon/textpattern/', src: ['**'], dest: 'public/'},
                    {expand: true, cwd: 'bower_components/textpattern-branding/assets/img/windows-site-tile/textpattern/', src: ['**'], dest: 'public/'}
                ]
            },

            theme: {
                files: [
                    {expand: true, cwd: 'src/style/imports/', src: ['**'], dest: 'public/style/imports/'},
                    {expand: true, cwd: 'src/style/', src: ['Textpattern.css', '.htaccess'], dest: 'public/style/'},
                    {expand: true, cwd: 'src/style/Textpattern/', src: ['**', '!*.tpl', '!sass/**', '!js/**'], dest: 'public/style/Textpattern/'}
                ]
            }
        },

        replace: {
            theme: {
                options: {
                    patterns: [
                        {
                            match: 'timestamp',
                            replacement: '<%= opt.timestamp %>'
                        },
                        {
                            match: 'year',
                            replacement: '<%= new Date().getFullYear() %>'
                        }
                    ]
                },
                files: [
                    {expand: true, cwd: 'src/style/Textpattern/', src: ['*.tpl'], dest: 'public/style/Textpattern/'},
                    {expand: true, cwd: 'src/', src: ['*.html'], dest: 'public/'}
                ]
            }
        },

        jshint: {
            files: ['Gruntfile.js', 'src/style/*/js/*.js'],
            options: {
                bitwise: true,
                camelcase: true,
                curly: true,
                eqeqeq: true,
                es3: true,
                forin: true,
                immed: true,
                indent: 4,
                latedef: true,
                noarg: true,
                noempty: true,
                nonew: true,
                quotmark: 'single',
                undef: true,
                unused: true,
                strict: true,
                trailing: true,
                browser: true,
                globals: {
                    jQuery: true,
                    Zepto: true,
                    define: true,
                    module: true,
                    require: true,
                    requirejs: true,
                    responsiveNav: true,
                    prettyPrint: true
                }
            }
        },

        cssmin: {
            main: {
                files: {
                    'public/style/Textpattern/css/main.css': ['tmp/style/Textpattern/sass/main.css'],
                    'public/style/Textpattern/css/ie8.css': ['tmp/style/Textpattern/sass/ie8.css']
                }
            }
        },

        uglify: {
            dist: {
                options: {
                    preserveComments: 'some'
                },

                files: [
                    {
                        'public/style/Textpattern/js/main.js': ['src/style/Textpattern/js/main.js'],
                        'public/style/Textpattern/js/prettify.js': ['bower_components/google-code-prettify/src/prettify.js'],
                        'public/style/Textpattern/js/require.js': ['bower_components/requirejs/require.js'],
                        'public/style/Textpattern/js/cookie.js': ['bower_components/jquery.cookie/jquery.cookie.js'],
                        'public/style/Textpattern/js/responsivenav.js': ['bower_components/responsive-nav/responsive-nav.js'],
                        'public/style/Textpattern/js/autosize.js': ['bower_components/jquery-autosize/jquery.autosize.js'],
                        'public/style/Textpattern/js/html5shiv.js': ['bower_components/html5shiv/dist/html5shiv.js']
                    },
                    {
                        expand: true,
                        cwd: 'bower_components/google-code-prettify/src/',
                        src: 'lang-*.js',
                        dest: 'public/style/Textpattern/js/'
                    }
                ]
            }
        },

        compress: {
            theme: {
                options: {
                    mode: 'gzip'
                },
                files: [
                    {expand: true, src: ['public/style/**/*.js'], ext: '.js.gz'},
                    {expand: true, src: ['public/style/**/*.css'], ext: '.css.gz'},
                    {expand: true, src: ['public/style/**/*.svg'], ext: '.svg.gz'}
                ]
            }
        },

        shell: {
            setup: {
                command: [
                    'php src/setup/setup.php'
                ].join('&&'),
                options: {
                    stdout: true
                }
            },
            postsetup: {
                command: [
                    'php src/setup/post.php'
                ].join('&&'),
                options: {
                    stdout: true
                }
            }
        }
    });

    grunt.registerTask('test', ['jshint']);
    grunt.registerTask('sass', ['compass', 'cssmin']);
    grunt.registerTask('default', ['watch']);
    grunt.registerTask('build', ['jshint', 'theme', 'copy:branding', 'sass', 'uglify', 'compress:theme']);
    grunt.registerTask('theme', ['copy:theme', 'replace:theme']);
    grunt.registerTask('travis', ['jshint', 'compass']);
    grunt.registerTask('setup', ['shell:setup', 'build']);
    grunt.registerTask('postsetup', ['shell:postsetup']);
};
<commit_msg>Watch for html files.<commit_after>module.exports = function (grunt)
{
    'use strict';

    grunt.loadNpmTasks('grunt-contrib-compass');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-replace');
    grunt.loadNpmTasks('grunt-shell');

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        opt : {
            timestamp: '<%= new Date().getTime() %>'
        },

        watch: {
            sass: {
                files: ['src/style/*.scss', 'src/style/*/sass/**'],
                tasks: ['sass', 'compress:theme']
            },

            theme: {
                files: ['!src/style/*/sass/**', '!src/style/*/js/**', 'src/style/*/**', 'src/*.html'],
                tasks: ['theme']
            },

            js: {
                files: 'src/style/*/js/**',
                tasks: ['jshint', 'uglify', 'compress:theme']
            }
        },

        compass: {
            dev: {
                options: {
                    config: 'config.rb',
                    force: true
                }
            }
        },

        copy: {
            branding: {
                files: [
                    {expand: true, cwd: 'bower_components/textpattern-branding/assets/img/', src: ['**'], dest: 'public/style/Textpattern/img/branding/'},
                    {expand: true, cwd: 'bower_components/textpattern-branding/assets/img/apple-touch-icon/textpattern/', src: ['**'], dest: 'public/'},
                    {expand: true, cwd: 'bower_components/textpattern-branding/assets/img/favicon/textpattern/', src: ['**'], dest: 'public/'},
                    {expand: true, cwd: 'bower_components/textpattern-branding/assets/img/windows-site-tile/textpattern/', src: ['**'], dest: 'public/'}
                ]
            },

            theme: {
                files: [
                    {expand: true, cwd: 'src/style/imports/', src: ['**'], dest: 'public/style/imports/'},
                    {expand: true, cwd: 'src/style/', src: ['Textpattern.css', '.htaccess'], dest: 'public/style/'},
                    {expand: true, cwd: 'src/style/Textpattern/', src: ['**', '!*.tpl', '!sass/**', '!js/**'], dest: 'public/style/Textpattern/'}
                ]
            }
        },

        replace: {
            theme: {
                options: {
                    patterns: [
                        {
                            match: 'timestamp',
                            replacement: '<%= opt.timestamp %>'
                        },
                        {
                            match: 'year',
                            replacement: '<%= new Date().getFullYear() %>'
                        }
                    ]
                },
                files: [
                    {expand: true, cwd: 'src/style/Textpattern/', src: ['*.tpl'], dest: 'public/style/Textpattern/'},
                    {expand: true, cwd: 'src/', src: ['*.html'], dest: 'public/'}
                ]
            }
        },

        jshint: {
            files: ['Gruntfile.js', 'src/style/*/js/*.js'],
            options: {
                bitwise: true,
                camelcase: true,
                curly: true,
                eqeqeq: true,
                es3: true,
                forin: true,
                immed: true,
                indent: 4,
                latedef: true,
                noarg: true,
                noempty: true,
                nonew: true,
                quotmark: 'single',
                undef: true,
                unused: true,
                strict: true,
                trailing: true,
                browser: true,
                globals: {
                    jQuery: true,
                    Zepto: true,
                    define: true,
                    module: true,
                    require: true,
                    requirejs: true,
                    responsiveNav: true,
                    prettyPrint: true
                }
            }
        },

        cssmin: {
            main: {
                files: {
                    'public/style/Textpattern/css/main.css': ['tmp/style/Textpattern/sass/main.css'],
                    'public/style/Textpattern/css/ie8.css': ['tmp/style/Textpattern/sass/ie8.css']
                }
            }
        },

        uglify: {
            dist: {
                options: {
                    preserveComments: 'some'
                },

                files: [
                    {
                        'public/style/Textpattern/js/main.js': ['src/style/Textpattern/js/main.js'],
                        'public/style/Textpattern/js/prettify.js': ['bower_components/google-code-prettify/src/prettify.js'],
                        'public/style/Textpattern/js/require.js': ['bower_components/requirejs/require.js'],
                        'public/style/Textpattern/js/cookie.js': ['bower_components/jquery.cookie/jquery.cookie.js'],
                        'public/style/Textpattern/js/responsivenav.js': ['bower_components/responsive-nav/responsive-nav.js'],
                        'public/style/Textpattern/js/autosize.js': ['bower_components/jquery-autosize/jquery.autosize.js'],
                        'public/style/Textpattern/js/html5shiv.js': ['bower_components/html5shiv/dist/html5shiv.js']
                    },
                    {
                        expand: true,
                        cwd: 'bower_components/google-code-prettify/src/',
                        src: 'lang-*.js',
                        dest: 'public/style/Textpattern/js/'
                    }
                ]
            }
        },

        compress: {
            theme: {
                options: {
                    mode: 'gzip'
                },
                files: [
                    {expand: true, src: ['public/style/**/*.js'], ext: '.js.gz'},
                    {expand: true, src: ['public/style/**/*.css'], ext: '.css.gz'},
                    {expand: true, src: ['public/style/**/*.svg'], ext: '.svg.gz'}
                ]
            }
        },

        shell: {
            setup: {
                command: [
                    'php src/setup/setup.php'
                ].join('&&'),
                options: {
                    stdout: true
                }
            },
            postsetup: {
                command: [
                    'php src/setup/post.php'
                ].join('&&'),
                options: {
                    stdout: true
                }
            }
        }
    });

    grunt.registerTask('test', ['jshint']);
    grunt.registerTask('sass', ['compass', 'cssmin']);
    grunt.registerTask('default', ['watch']);
    grunt.registerTask('build', ['jshint', 'theme', 'copy:branding', 'sass', 'uglify', 'compress:theme']);
    grunt.registerTask('theme', ['copy:theme', 'replace:theme']);
    grunt.registerTask('travis', ['jshint', 'compass']);
    grunt.registerTask('setup', ['shell:setup', 'build']);
    grunt.registerTask('postsetup', ['shell:postsetup']);
};
<|endoftext|>


<commit_before>'use strict';

const port = process.env.MB_PORT || 2525;

module.exports = grunt => {

    require('time-grunt')(grunt);

    grunt.loadTasks('tasks');
    grunt.loadNpmTasks('grunt-mocha-test');
    grunt.loadNpmTasks('grunt-jsdoc');
    grunt.loadNpmTasks('grunt-mountebank');
    grunt.loadNpmTasks('grunt-eslint');
    grunt.loadNpmTasks('grunt-css');

    grunt.initConfig({
        mochaTest: {
            unit: {
                options: {
                    reporter: 'spec'
                },
                src: ['test/**/*.js']
            },
            functional: {
                options: {
                    reporter: 'spec'
                },
                src: ['functionalTest/**/*.js']
            },
            performance: {
                options: { reporter: 'spec' },
                src: ['performanceTest/**/*.js']
            }
        },
        eslint: {
            target: [
                'Gruntfile.js',
                'src/**/*.js',
                'tasks/**/*.js',
                'test/**/*.js',
                'functionalTest/**/*.js',
                'performanceTest/**/*.js',
                'bin/mb'
            ]
        },
        jsdoc: {
            dist: {
                src: ['src/**/*.js'],
                options: {
                    destination: 'docs',
                    configure: '.jsdoc',
                    pedantic: true,
                    readme: 'CONTRIBUTING.md',
                    package: 'dist/mountebank/package.json' // use dist to get correct version
                }
            }
        },
        mb: {
            options: {
                path: 'bin/mb',
                pathEnvironmentVariable: 'MB_EXECUTABLE'
            },
            restart: ['--port', port, '--pidfile', 'mb-grunt.pid', '--logfile', 'mb-grunt.log', '--allowInjection', '--mock', '--debug', '--localOnly'],
            stop: ['--pidfile', 'mb-grunt.pid']
        },
        csslint: {
            strict: {
                options: {
                    important: 2,
                    ids: 2
                },
                all: [
                    'src/**/*.css',
                    '!src/**/jquery-ui.css'
                ]
            }
        }
    });

    grunt.registerTask('setAirplaneMode', () => {
        process.env.MB_AIRPLANE_MODE = 'true';
    });

    grunt.registerTask('inProcessImposters', () => {
        const fs = require('fs');
        if (fs.existsSync('protocols.json')) {
            fs.unlinkSync('protocols.json');
        }
    });

    grunt.registerTask('outOfProcessImposters', () => {
        const protocols = {
            smtp: { createCommand: 'node src/models/smtp/index.js' },
            http: { createCommand: 'node src/models/http/index.js' },
            https: { createCommand: 'node src/models/https/index.js' },
            tcp: { createCommand: 'node src/models/tcp/index.js' }
        };
        require('fs').writeFileSync('protocols.json', JSON.stringify(protocols, null, 2));
    });

    grunt.registerTask('test:unit', 'Run the unit tests', ['mochaTest:unit']);
    grunt.registerTask('test:functional', 'Run the functional tests',
        ['mb:restart', 'try', 'mochaTest:functional', 'finally', 'mb:stop', 'checkForErrors']);
    grunt.registerTask('test:performance', 'Run the performance tests', ['mochaTest:performance']);
    grunt.registerTask('test', 'Run all non-performance tests', ['test:unit', 'test:functional']);
    grunt.registerTask('lint', 'Run all lint checks', ['jsCheck', 'deadCheck', 'eslint']);
    grunt.registerTask('default', ['test', 'lint']);
    grunt.registerTask('airplane', 'Build that avoids tests requiring network access', ['setAirplaneMode', 'default']);

    // Package-specific testing
    grunt.registerTask('test:tarball:x64', 'Run tests against packaged tarball',
        ['dist:tarball:x64', 'install:tarball:x64', 'test:functional']);
    grunt.registerTask('test:zip', 'Run tests against packaged zipfile',
        ['download:zip', 'install:zip', 'test']);
    grunt.registerTask('test:npm', 'Run tests against npm package',
        ['dist:npm', 'install:npm', 'test:functional']);
    grunt.registerTask('test:pkg', 'Run tests against OSX pkg file',
        ['dist', 'version', 'dist:package:osxpkg', 'install:pkg', 'test']);
    grunt.registerTask('test:deb', 'Run tests against Debian package',
        ['dist:package:deb', 'install:deb', 'test:functional']);
    grunt.registerTask('test:rpm', 'Run tests against Red Hat package',
        ['dist:package:rpm', 'install:rpm', 'test:functional']);
};
<commit_msg>Still troubleshooting ECONNRESET on Windows<commit_after>'use strict';

const port = process.env.MB_PORT || 2525;

module.exports = grunt => {

    require('time-grunt')(grunt);

    grunt.loadTasks('tasks');
    grunt.loadNpmTasks('grunt-mocha-test');
    grunt.loadNpmTasks('grunt-jsdoc');
    grunt.loadNpmTasks('grunt-mountebank');
    grunt.loadNpmTasks('grunt-eslint');
    grunt.loadNpmTasks('grunt-css');

    grunt.initConfig({
        mochaTest: {
            unit: {
                options: {
                    reporter: 'spec'
                },
                src: ['test2/**/*.js']
            },
            functional: {
                options: {
                    reporter: 'spec'
                },
                // src: ['functionalTest/**/*.js']
                src: ['functionalTest/html/feedTest.js']
            },
            performance: {
                options: { reporter: 'spec' },
                src: ['performanceTest/**/*.js']
            }
        },
        eslint: {
            target: [
                'Gruntfile.js',
                'src/**/*.js',
                'tasks/**/*.js',
                'test/**/*.js',
                'functionalTest/**/*.js',
                'performanceTest/**/*.js',
                'bin/mb'
            ]
        },
        jsdoc: {
            dist: {
                src: ['src/**/*.js'],
                options: {
                    destination: 'docs',
                    configure: '.jsdoc',
                    pedantic: true,
                    readme: 'CONTRIBUTING.md',
                    package: 'dist/mountebank/package.json' // use dist to get correct version
                }
            }
        },
        mb: {
            options: {
                path: 'bin/mb',
                pathEnvironmentVariable: 'MB_EXECUTABLE'
            },
            restart: ['--port', port, '--pidfile', 'mb-grunt.pid', '--logfile', 'mb-grunt.log', '--allowInjection', '--mock', '--debug', '--localOnly'],
            stop: ['--pidfile', 'mb-grunt.pid']
        },
        csslint: {
            strict: {
                options: {
                    important: 2,
                    ids: 2
                },
                all: [
                    'src/**/*.css',
                    '!src/**/jquery-ui.css'
                ]
            }
        }
    });

    grunt.registerTask('setAirplaneMode', () => {
        process.env.MB_AIRPLANE_MODE = 'true';
    });

    grunt.registerTask('inProcessImposters', () => {
        const fs = require('fs');
        if (fs.existsSync('protocols.json')) {
            fs.unlinkSync('protocols.json');
        }
    });

    grunt.registerTask('outOfProcessImposters', () => {
        const protocols = {
            smtp: { createCommand: 'node src/models/smtp/index.js' },
            http: { createCommand: 'node src/models/http/index.js' },
            https: { createCommand: 'node src/models/https/index.js' },
            tcp: { createCommand: 'node src/models/tcp/index.js' }
        };
        require('fs').writeFileSync('protocols.json', JSON.stringify(protocols, null, 2));
    });

    grunt.registerTask('test:unit', 'Run the unit tests', ['mochaTest:unit']);
    grunt.registerTask('test:functional', 'Run the functional tests',
        ['mb:restart', 'try', 'mochaTest:functional', 'finally', 'mb:stop', 'checkForErrors']);
    grunt.registerTask('test:performance', 'Run the performance tests', ['mochaTest:performance']);
    grunt.registerTask('test', 'Run all non-performance tests', ['test:unit', 'test:functional']);
    grunt.registerTask('lint', 'Run all lint checks', ['jsCheck', 'deadCheck', 'eslint']);
    grunt.registerTask('default', ['test', 'lint']);
    grunt.registerTask('airplane', 'Build that avoids tests requiring network access', ['setAirplaneMode', 'default']);

    // Package-specific testing
    grunt.registerTask('test:tarball:x64', 'Run tests against packaged tarball',
        ['dist:tarball:x64', 'install:tarball:x64', 'test:functional']);
    grunt.registerTask('test:zip', 'Run tests against packaged zipfile',
        ['download:zip', 'install:zip', 'test']);
    grunt.registerTask('test:npm', 'Run tests against npm package',
        ['dist:npm', 'install:npm', 'test:functional']);
    grunt.registerTask('test:pkg', 'Run tests against OSX pkg file',
        ['dist', 'version', 'dist:package:osxpkg', 'install:pkg', 'test']);
    grunt.registerTask('test:deb', 'Run tests against Debian package',
        ['dist:package:deb', 'install:deb', 'test:functional']);
    grunt.registerTask('test:rpm', 'Run tests against Red Hat package',
        ['dist:package:rpm', 'install:rpm', 'test:functional']);
};
<|endoftext|>


<commit_before>/*

Copyright 2011, Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

 * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
 * Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

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

 */

Refine.DefaultImportingController = function(createProjectUI) {
  this._createProjectUI = createProjectUI;

  this._fileSelectionPanel = createProjectUI.addCustomPanel();
  this._parsingPanel = createProjectUI.addCustomPanel();

  for (var i = 0; i < Refine.DefaultImportingController.sources.length; i++) {
    var sourceSelectionUI = Refine.DefaultImportingController.sources[i];
    sourceSelectionUI.ui = new sourceSelectionUI.uiClass(this);

    createProjectUI.addSourceSelectionUI(sourceSelectionUI);
  }
};
Refine.CreateProjectUI.controllers.push(Refine.DefaultImportingController);

Refine.DefaultImportingController.sources = [];
Refine.DefaultImportingController.parserUIs = {};

Refine.DefaultImportingController.prototype._startOver = function() {
  if (this._jobID) {
    Refine.CreateProjectUI.cancelImportingJob(this._jobID);
  }

  this._disposeFileSelectionPanel();
  this._disposeFileSelectionPanel();

  delete this._fileSelectionPanelElmts;
  delete this._parsingPanelElmts;

  delete this._jobID;
  delete this._job;
  delete this._extensions;

  delete this._format;
  delete this._parserOptions;
  delete this._projectName;

  this._createProjectUI.showSourceSelectionPanel();
};

Refine.DefaultImportingController.prototype.startImportJob = function(form, progressMessage, callback) {
  var self = this;
  $.post(
      "command/core/create-importing-job",
      null,
      function(data) {
        var jobID = self._jobID = data.jobID;

        form.attr("method", "post")
        .attr("enctype", "multipart/form-data")
        .attr("accept-charset", "UTF-8")
        .attr("target", "create-project-iframe")
        .attr("action", "command/core/importing-controller?" + $.param({
          "controller": "core/default-importing-controller",
          "jobID": jobID,
          "subCommand": "load-raw-data"
        }));
        form[0].submit();

        var start = new Date();
        var timerID = window.setInterval(
          function() {
            self._createProjectUI.pollImportJob(
              start, jobID, timerID,
              function(job) {
                return job.config.hasData;
              },
              function(jobID, job) {
                self._job = job;
                self._onImportJobReady();
                if (callback) {
                  callback(jobID, job);
                }
              },
              function(job) {
                alert(job.config.error + '\n' + job.config.errorDetails);
                self._startOver();
              }
            );
          },
          1000
        );
        self._createProjectUI.showImportProgressPanel(progressMessage, function() {
          // stop the iframe
          $('#create-project-iframe')[0].contentWindow.stop();

          // stop the timed polling
          window.clearInterval(timerID);

          // explicitly cancel the import job
          Refine.CreateProjectUI.cancelImportingJob(jobID);

          self._createProjectUI.showSourceSelectionPanel();
        });
      },
      "json"
  );
};

Refine.DefaultImportingController.prototype._onImportJobReady = function() {
  this._prepareData();
  if (this._job.config.retrievalRecord.files.length > 1) {
    this._showFileSelectionPanel();
  } else {
    this._showParsingPanel(false);
  }
};

Refine.DefaultImportingController.prototype._prepareData = function() {
  var extensionMap = {};
  var extensionList = [];

  var files = this._job.config.retrievalRecord.files;
  var fileSelection = this._job.config.fileSelection;
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    file.selected = false;

    var slash = file.fileName.lastIndexOf('/');
    var dot = file.fileName.lastIndexOf('.');
    if (dot > slash) {
      var extension = file.fileName.substring(dot);
      if (extension in extensionMap) {
        extensionMap[extension].count++;
      } else {
        extensionMap[extension] = { extension: extension, count: 1 };
        extensionList.push(extensionMap[extension]);
      }
    }
  }
  for (var i = 0; i < fileSelection.length; i++) {
    files[fileSelection[i]].selected = true;
  }

  extensionList.sort(function(a, b) {
    return b.count - a.count;
  });
  this._extensions = extensionList;
};

Refine.DefaultImportingController.prototype._ensureFormatParserUIHasInitializationData = function(format, onDone) {
  if (!(format in this._parserOptions)) {
    var self = this;
    var dismissBusy = DialogSystem.showBusy($.i18n._('core-index-import')["inspecting"]);
    $.post(
      "command/core/importing-controller?" + $.param({
        "controller": "core/default-importing-controller",
        "jobID": this._jobID,
        "subCommand": "initialize-parser-ui",
        "format": format
      }),
      null,
      function(data) {
        dismissBusy();

        if (data.options) {
          self._parserOptions[format] = data.options;
          onDone();
        }
      },
      "json"
    );
  } else {
    onDone();
  }
};

Refine.DefaultImportingController.prototype.updateFormatAndOptions = function(options, callback) {
  var self = this;
  $.post(
    "command/core/importing-controller?" + $.param({
      "controller": "core/default-importing-controller",
      "jobID": this._jobID,
      "subCommand": "update-format-and-options"
    }),
    {
      "format" : this._format,
      "options" : JSON.stringify(options)
    },
    function(o) {
      if (o.status == 'error') {
        if (o.message) {
          alert(o.message);
        } else {
          var messages = [];
          $.each(o.errors, function() { messages.push(this.message); });
          alert(messages.join('\n\n'));
        }
      } else {
        callback(o);
      }
    },
    "json"
  );
};

Refine.DefaultImportingController.prototype.getPreviewData = function(callback, numRows) {
  var self = this;
  var result = {};

  $.post(
    "command/core/get-models?" + $.param({ "importingJobID" : this._jobID }),
    null,
    function(data) {
      for (var n in data) {
        if (data.hasOwnProperty(n)) {
          result[n] = data[n];
        }
      }

      $.post(
        "command/core/get-rows?" + $.param({
          "importingJobID" : self._jobID,
          "start" : 0,
          "limit" : numRows || 100 // More than we parse for preview anyway
        }),
        null,
        function(data) {
          result.rowModel = data;
          callback(result);
        },
        "jsonp"
      );
    },
    "json"
  );
};

Refine.DefaultImportingController.prototype._createProject = function() {
  if ((this._formatParserUI) && this._formatParserUI.confirmReadyToCreateProject()) {
    var projectName = $.trim(this._parsingPanelElmts.projectNameInput[0].value);
    if (projectName.length === 0) {
      window.alert($.i18n._('core-index-import')["warning-name"]);
      this._parsingPanelElmts.projectNameInput.focus();
      return;
    }

    var self = this;
    var options = this._formatParserUI.getOptions();
    options.projectName = projectName;
    $.post(
      "command/core/importing-controller?" + $.param({
        "controller": "core/default-importing-controller",
        "jobID": this._jobID,
        "subCommand": "create-project"
      }),
      {
        "format" : this._format,
        "options" : JSON.stringify(options)
      },
      function(o) {
        if (o.status == 'error') {
          alert(o.message);
          return;
        }

        var start = new Date();
        var timerID = window.setInterval(
          function() {
            self._createProjectUI.pollImportJob(
                start,
                self._jobID,
                timerID,
                function(job) {
                  return "projectID" in job.config;
                },
                function(jobID, job) {
                  Refine.CreateProjectUI.cancelImportingJob(jobID);
                  document.location = "project?project=" + job.config.projectID;
                },
                function(job) {
                  alert($.i18n._('core-index-import')["errors"]+'\n' + Refine.CreateProjectUI.composeErrorMessage(job));
                  self._onImportJobReady();
                }
            );
          },
          1000
        );
        self._createProjectUI.showImportProgressPanel($.i18n._('core-index-import')["creating-proj"], function() {
          // stop the timed polling
          window.clearInterval(timerID);

          // explicitly cancel the import job
          Refine.CreateProjectUI.cancelImportingJob(self._jobID);

          self._createProjectUI.showSourceSelectionPanel();
        });
      },
      "json"
    );
  }
};
<commit_msg>fix issue #540 to skip the empty URL when submit the import form<commit_after>/*

Copyright 2011, Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

 * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
 * Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

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

 */

Refine.DefaultImportingController = function(createProjectUI) {
  this._createProjectUI = createProjectUI;

  this._fileSelectionPanel = createProjectUI.addCustomPanel();
  this._parsingPanel = createProjectUI.addCustomPanel();

  for (var i = 0; i < Refine.DefaultImportingController.sources.length; i++) {
    var sourceSelectionUI = Refine.DefaultImportingController.sources[i];
    sourceSelectionUI.ui = new sourceSelectionUI.uiClass(this);

    createProjectUI.addSourceSelectionUI(sourceSelectionUI);
  }
};
Refine.CreateProjectUI.controllers.push(Refine.DefaultImportingController);

Refine.DefaultImportingController.sources = [];
Refine.DefaultImportingController.parserUIs = {};

Refine.DefaultImportingController.prototype._startOver = function() {
  if (this._jobID) {
    Refine.CreateProjectUI.cancelImportingJob(this._jobID);
  }

  this._disposeFileSelectionPanel();
  this._disposeFileSelectionPanel();

  delete this._fileSelectionPanelElmts;
  delete this._parsingPanelElmts;

  delete this._jobID;
  delete this._job;
  delete this._extensions;

  delete this._format;
  delete this._parserOptions;
  delete this._projectName;

  this._createProjectUI.showSourceSelectionPanel();
};

Refine.DefaultImportingController.prototype.startImportJob = function(form, progressMessage, callback) {
  var self = this;

  $(form).find('input:text').filter(function() {
		return this.value === "";
  }).attr("disabled", "disabled");

  $.post(
      "command/core/create-importing-job",
      null,
      function(data) {
        var jobID = self._jobID = data.jobID;

        form.attr("method", "post")
        .attr("enctype", "multipart/form-data")
        .attr("accept-charset", "UTF-8")
        .attr("target", "create-project-iframe")
        .attr("action", "command/core/importing-controller?" + $.param({
          "controller": "core/default-importing-controller",
          "jobID": jobID,
          "subCommand": "load-raw-data"
        }));
        form[0].submit();

        var start = new Date();
        var timerID = window.setInterval(
          function() {
            self._createProjectUI.pollImportJob(
              start, jobID, timerID,
              function(job) {
                return job.config.hasData;
              },
              function(jobID, job) {
                self._job = job;
                self._onImportJobReady();
                if (callback) {
                  callback(jobID, job);
                }
              },
              function(job) {
                alert(job.config.error + '\n' + job.config.errorDetails);
                self._startOver();
              }
            );
          },
          1000
        );
        self._createProjectUI.showImportProgressPanel(progressMessage, function() {
          // stop the iframe
          $('#create-project-iframe')[0].contentWindow.stop();

          // stop the timed polling
          window.clearInterval(timerID);

          // explicitly cancel the import job
          Refine.CreateProjectUI.cancelImportingJob(jobID);

          self._createProjectUI.showSourceSelectionPanel();
        });
      },
      "json"
  );
};

Refine.DefaultImportingController.prototype._onImportJobReady = function() {
  this._prepareData();
  if (this._job.config.retrievalRecord.files.length > 1) {
    this._showFileSelectionPanel();
  } else {
    this._showParsingPanel(false);
  }
};

Refine.DefaultImportingController.prototype._prepareData = function() {
  var extensionMap = {};
  var extensionList = [];

  var files = this._job.config.retrievalRecord.files;
  var fileSelection = this._job.config.fileSelection;
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    file.selected = false;

    var slash = file.fileName.lastIndexOf('/');
    var dot = file.fileName.lastIndexOf('.');
    if (dot > slash) {
      var extension = file.fileName.substring(dot);
      if (extension in extensionMap) {
        extensionMap[extension].count++;
      } else {
        extensionMap[extension] = { extension: extension, count: 1 };
        extensionList.push(extensionMap[extension]);
      }
    }
  }
  for (var i = 0; i < fileSelection.length; i++) {
    files[fileSelection[i]].selected = true;
  }

  extensionList.sort(function(a, b) {
    return b.count - a.count;
  });
  this._extensions = extensionList;
};

Refine.DefaultImportingController.prototype._ensureFormatParserUIHasInitializationData = function(format, onDone) {
  if (!(format in this._parserOptions)) {
    var self = this;
    var dismissBusy = DialogSystem.showBusy($.i18n._('core-index-import')["inspecting"]);
    $.post(
      "command/core/importing-controller?" + $.param({
        "controller": "core/default-importing-controller",
        "jobID": this._jobID,
        "subCommand": "initialize-parser-ui",
        "format": format
      }),
      null,
      function(data) {
        dismissBusy();

        if (data.options) {
          self._parserOptions[format] = data.options;
          onDone();
        }
      },
      "json"
    );
  } else {
    onDone();
  }
};

Refine.DefaultImportingController.prototype.updateFormatAndOptions = function(options, callback) {
  var self = this;
  $.post(
    "command/core/importing-controller?" + $.param({
      "controller": "core/default-importing-controller",
      "jobID": this._jobID,
      "subCommand": "update-format-and-options"
    }),
    {
      "format" : this._format,
      "options" : JSON.stringify(options)
    },
    function(o) {
      if (o.status == 'error') {
        if (o.message) {
          alert(o.message);
        } else {
          var messages = [];
          $.each(o.errors, function() { messages.push(this.message); });
          alert(messages.join('\n\n'));
        }
      } else {
        callback(o);
      }
    },
    "json"
  );
};

Refine.DefaultImportingController.prototype.getPreviewData = function(callback, numRows) {
  var self = this;
  var result = {};

  $.post(
    "command/core/get-models?" + $.param({ "importingJobID" : this._jobID }),
    null,
    function(data) {
      for (var n in data) {
        if (data.hasOwnProperty(n)) {
          result[n] = data[n];
        }
      }

      $.post(
        "command/core/get-rows?" + $.param({
          "importingJobID" : self._jobID,
          "start" : 0,
          "limit" : numRows || 100 // More than we parse for preview anyway
        }),
        null,
        function(data) {
          result.rowModel = data;
          callback(result);
        },
        "jsonp"
      );
    },
    "json"
  );
};

Refine.DefaultImportingController.prototype._createProject = function() {
  if ((this._formatParserUI) && this._formatParserUI.confirmReadyToCreateProject()) {
    var projectName = $.trim(this._parsingPanelElmts.projectNameInput[0].value);
    if (projectName.length === 0) {
      window.alert($.i18n._('core-index-import')["warning-name"]);
      this._parsingPanelElmts.projectNameInput.focus();
      return;
    }

    var self = this;
    var options = this._formatParserUI.getOptions();
    options.projectName = projectName;
    $.post(
      "command/core/importing-controller?" + $.param({
        "controller": "core/default-importing-controller",
        "jobID": this._jobID,
        "subCommand": "create-project"
      }),
      {
        "format" : this._format,
        "options" : JSON.stringify(options)
      },
      function(o) {
        if (o.status == 'error') {
          alert(o.message);
          return;
        }

        var start = new Date();
        var timerID = window.setInterval(
          function() {
            self._createProjectUI.pollImportJob(
                start,
                self._jobID,
                timerID,
                function(job) {
                  return "projectID" in job.config;
                },
                function(jobID, job) {
                  Refine.CreateProjectUI.cancelImportingJob(jobID);
                  document.location = "project?project=" + job.config.projectID;
                },
                function(job) {
                  alert($.i18n._('core-index-import')["errors"]+'\n' + Refine.CreateProjectUI.composeErrorMessage(job));
                  self._onImportJobReady();
                }
            );
          },
          1000
        );
        self._createProjectUI.showImportProgressPanel($.i18n._('core-index-import')["creating-proj"], function() {
          // stop the timed polling
          window.clearInterval(timerID);

          // explicitly cancel the import job
          Refine.CreateProjectUI.cancelImportingJob(self._jobID);

          self._createProjectUI.showSourceSelectionPanel();
        });
      },
      "json"
    );
  }
};
<|endoftext|>


<commit_before>"use strict";

angular.module("subutai.settings-network.controller", [])
    .controller("SettingsNetworkCtrl", SettingsNetworkCtrl);

SettingsNetworkCtrl.$inject = ["$scope", "SettingsNetworkSrv", "SweetAlert"];
function SettingsNetworkCtrl($scope, SettingsNetworkSrv, SweetAlert) {
    var vm = this;
    vm.config = {};

    function getConfig() {
        SettingsNetworkSrv.getConfig().success(function (data) {
            console.log(data);
            vm.config = data;
        });
    }

    getConfig();

    vm.updateConfig = updateConfig;
    function updateConfig() {
        if (vm.config.startRange == undefined) {
            vm.config.startRange = 0
        }

        if (vm.config.endRange == undefined) {
            vm.config.endRange = 65535
        }

        if (parseInt(vm.config.startRange) < 0 || parseInt(vm.config.startRange) > 65535) {
            SweetAlert.swal("ERROR!", 'start range should be 0..65535', "error");
        }
        else if (parseInt(vm.config.endRange) < 0 || parseInt(vm.config.endRange) > 65535) {
            SweetAlert.swal("ERROR!", 'end range should be 0..65535', "error");
        }
        else {
            SettingsNetworkSrv.updateConfig(vm.config).success(function (data) {
                SweetAlert.swal("Success!", "Your settings were saved.", "success");
            }).error(function (error) {
                SweetAlert.swal("ERROR!", "Save config error: " + error.replace(/\\n/g, " "), "error");
            });
        }
    }
}<commit_msg>* Added validation to p2p ports range.<commit_after>"use strict";

angular.module("subutai.settings-network.controller", [])
    .controller("SettingsNetworkCtrl", SettingsNetworkCtrl);

SettingsNetworkCtrl.$inject = ["$scope", "SettingsNetworkSrv", "SweetAlert"];
function SettingsNetworkCtrl($scope, SettingsNetworkSrv, SweetAlert) {
    var vm = this;
    vm.config = {};

    function getConfig() {
        SettingsNetworkSrv.getConfig().success(function (data) {
            console.log(data);
            vm.config = data;
        });
    }

    getConfig();

    vm.updateConfig = updateConfig;
    function updateConfig() {
        if (vm.config.startRange == undefined) {
            vm.config.startRange = 0
        }

        if (vm.config.endRange == undefined) {
            vm.config.endRange = 65535
        }

        if (parseInt(vm.config.startRange) < 0 || parseInt(vm.config.startRange) > 65535) {
            SweetAlert.swal("ERROR!", 'start range should be 0..65535', "error");
        }
        else if (parseInt(vm.config.endRange) < 0 || parseInt(vm.config.endRange) > 65535) {
            SweetAlert.swal("ERROR!", 'end range should be 0..65535', "error");
        }
        else if (parseInt(vm.config.startRange) > parseInt(vm.config.endRange)) {
            SweetAlert.swal("ERROR!", 'Start range can not be bigger than End range', "error");
        }
        else {
            SettingsNetworkSrv.updateConfig(vm.config).success(function (data) {
                SweetAlert.swal("Success!", "Your settings were saved.", "success");
            }).error(function (error) {
                SweetAlert.swal("ERROR!", "Save config error: " + error.replace(/\\n/g, " "), "error");
            });
        }
    }
}<|endoftext|>


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

    var app = angular.module('directive.codemirror', []);

    var btemplate = "<!DOCTYPE html>\n\n  \n  \n";
    var atemplate = "\n  \n";
    var empty = ''+
                '
'+
                '
'+
                'Preview Area

';

    app.directive('framepreview', function(){
        return {
            'restrict': 'A',
            'scope': {
                'content': '=cmBind',
            },
            'link': function(scope, element, attrs, ngModel) {
                var iframe = element[0];
                var preview = iframe.contentDocument || iframe.contentWindow.document;

                preview.write(empty);

                scope.$watch('content', function(v1, v2){
                    updatePreview(v1||empty);
                });

                function updatePreview(value) {
                    if(!iframe) return;
                    preview.open();
                    preview.write(value);
                    preview.close();
                }
            }
        };
    });

    app.directive('codemirror', function(){
        var base_conf = {
            extraKeys: {'Ctrl-J': 'toMatchingTag', 'Ctrl-Space': 'autocomplete'},
            lineNumbers: true,
            matchBrackets: true,
            matchTags: { bothTags: true },
            mode:'htmlmixed',
            tabSize: 4,
            theme: 'monokai'
        };

        return {
            'restrict': 'A',
            'templateUrl': '/static/templates/directive.codemirror.html',
            'require': '?ngModel',
            'scope': {
                'initialModel': '='
            },
            'controller': ['$scope', '$element', '$document', '$attrs',
                function($scope, $element, $document, $attrs){
                    $scope.code_id = 'code-' + Math.random().toString(16).substring(2);
                }
            ],
            'link': function(scope, element, attrs, ngModel) {
                if(!ngModel) return;

                var textarea, editor;
                var conf = angular.copy(base_conf);

                if(!ngModel.$viewValue && scope.initialModel) {
                    ngModel.$setViewValue(angular.copy(scope.initialModel));
                }

                function readEditor() {
                    function _read() {
                        var content = editor.getValue();
                        ngModel.$setViewValue(content);
                    }
                    if (scope.$$phase || scope.$parent.$$phase) {
                        _read();
                    } else {
                        scope.$apply(_read);
                    }
                }

                function renderOnEditor(value) {
                    if(!(editor && value.substring)) return;

                    if(value.substring(0, btemplate.length) !== btemplate) {
                        value = btemplate + value;
                    }
                    if(value.substring(value.length - atemplate.length) !== atemplate) {
                        value = value + atemplate;
                    }

                    editor.setValue(value);
                    editor.markText({line:0, ch:0},
                                    {line:4, ch:0},
                                    {atomic: true, readOnly: true, inclusiveLeft: true});

                    var lastLine = editor.lineCount();
                    editor.markText({line:lastLine-3, ch:1000},
                                    {line:lastLine, ch:0},
                                    {atomic: true, readOnly: true, inclusiveRight: true});
                }

                ngModel.$render = function(){
                    renderOnEditor(ngModel.$viewValue || '');
                };

                scope.$watch('$scope', function(){
                    textarea = document.getElementById(scope.code_id);

                    editor = new CodeMirror.fromTextArea(textarea, conf);
                    renderOnEditor(ngModel.$viewValue || '');
                    editor.on('change', readEditor);

                    var pid = setInterval(function(){
                        if(document.getElementById(scope.code_id)) {
                            editor.refresh();
                        } else {
                            clearInterval(pid);
                        }
                    }, 500);
                });
            }
        };
    });
})(window.angular);
<commit_msg>better place to start initial data in codemirror<commit_after>(function(angular) {
    'use strict';

    var app = angular.module('directive.codemirror', []);

    var btemplate = "<!DOCTYPE html>\n\n  \n  \n";
    var atemplate = "\n  \n";
    var empty = ''+
                '
'+
                '
'+
                'Preview Area

';

    app.directive('framepreview', function(){
        return {
            'restrict': 'A',
            'scope': {
                'content': '=cmBind',
            },
            'link': function(scope, element, attrs, ngModel) {
                var iframe = element[0];
                var preview = iframe.contentDocument || iframe.contentWindow.document;

                preview.write(empty);

                scope.$watch('content', function(v1, v2){
                    updatePreview(v1||empty);
                });

                function updatePreview(value) {
                    if(!iframe) return;
                    preview.open();
                    preview.write(value);
                    preview.close();
                }
            }
        };
    });

    app.directive('codemirror', function(){
        var base_conf = {
            extraKeys: {'Ctrl-J': 'toMatchingTag', 'Ctrl-Space': 'autocomplete'},
            lineNumbers: true,
            matchBrackets: true,
            matchTags: { bothTags: true },
            mode:'htmlmixed',
            tabSize: 4,
            theme: 'monokai'
        };

        return {
            'restrict': 'A',
            'templateUrl': '/static/templates/directive.codemirror.html',
            'require': '?ngModel',
            'scope': {
                'initialModel': '='
            },
            'controller': ['$scope', '$element', '$document', '$attrs',
                function($scope, $element, $document, $attrs){
                    $scope.code_id = 'code-' + Math.random().toString(16).substring(2);
                }
            ],
            'link': function(scope, element, attrs, ngModel) {
                if(!ngModel) return;

                var textarea, editor;
                var conf = angular.copy(base_conf);

                function readEditor() {
                    function _read() {
                        var content = editor.getValue();
                        ngModel.$setViewValue(content);
                    }
                    if (scope.$$phase || scope.$parent.$$phase) {
                        _read();
                    } else {
                        scope.$apply(_read);
                    }
                }

                function renderOnEditor(value) {
                    if(!(editor && value.substring)) return;

                    if(value.substring(0, btemplate.length) !== btemplate) {
                        value = btemplate + value;
                    }
                    if(value.substring(value.length - atemplate.length) !== atemplate) {
                        value = value + atemplate;
                    }

                    editor.setValue(value);
                    editor.markText({line:0, ch:0},
                                    {line:4, ch:0},
                                    {atomic: true, readOnly: true, inclusiveLeft: true});

                    var lastLine = editor.lineCount();
                    editor.markText({line:lastLine-3, ch:1000},
                                    {line:lastLine, ch:0},
                                    {atomic: true, readOnly: true, inclusiveRight: true});
                }

                ngModel.$render = function(){
                    renderOnEditor(ngModel.$viewValue || '');
                };

                scope.$watch('$scope', function(){
                    textarea = document.getElementById(scope.code_id);

                    if(!ngModel.$viewValue && scope.initialModel) {
                        ngModel.$setViewValue(angular.copy(scope.initialModel));
                    }

                    editor = new CodeMirror.fromTextArea(textarea, conf);
                    renderOnEditor(ngModel.$viewValue || '');
                    editor.on('change', readEditor);

                    var pid = setInterval(function(){
                        if(document.getElementById(scope.code_id)) {
                            editor.refresh();
                        } else {
                            clearInterval(pid);
                        }
                    }, 500);
                });

            }
        };
    });
})(window.angular);
<|endoftext|>


<commit_before>var sqlite3 = require('sqlite3').verbose(),
    _ = require('lodash');

// Manages all connections to the Hamster database.
module.exports = function(DATABASE_LOCATION) {
  var self = this || {};
  self.db = new sqlite3.Database(DATABASE_LOCATION);

  // Used to track and create the tag for commits.
  self.COMMIT_TAG = {
    name: 'commit',
    id: null
  };

  self.START_MESSAGE = 'Start of day';

  self.SCHEME = {
    workCategory: 1,

    tables: {
      autoIncrement: 'SQLITE_SEQUENCE',
      task: 'facts',
      taskTagMap: 'fact_tags',
      tag: 'tags',
      activity: 'activities'
    }
  }

  // Given a list of objects retrieves an id, 1 if none could be found.
  self.retrieveId = function(list) {
    id = _.max(_.pluck(list, 'id')) + 1;
    return (id > -1) ? id : 1;
  };

  // Gets the next auto increment value for the given table and passes that into the first argument for the callback.
  self.getNextAutoIncrementFor = function(table, callback){
    self.db.all('SELECT * FROM '+self.SCHEME.tables.autoIncrement+' where name="'+table+'"', function(err, data) {
      if (err) {throw err};
      callback(data[0].seq);
    });
  };

  // Returns the time in the format: yyyy-mm-dd hh:mm:ss for hamster.
  self.formatDate = function(date) {
    date = new Date(date);
    var partOfDay = date.toTimeString().split(' ')[0],
        partOfYear = date.toISOString().split('T')[0];

    return partOfYear + ' ' + partOfDay;
  };

  // Creates a new commit tag if necessary. Calls the callback when done. May be async. other arguments:
  // createStartOfDay: if false no start of day task will be created. If there are no tasks this can cause the commit logging to crash.
  self.init = function(callback, createStartOfDay) {
    self.db.serialize(function() {
      self.db.all('SELECT * FROM '+self.SCHEME.tables.tag, function(err, data) {
        if (err) {throw err};

        data.forEach(function(tag) {
          if (tag.name === self.COMMIT_TAG.name){
            self.COMMIT_TAG.id = tag.id;
          }
        });

        if (self.COMMIT_TAG.id === null){
          console.log('"' + self.COMMIT_TAG.name + '" tag not found, creating it.');

          self.getNextAutoIncrementFor(self.SCHEME.tables.tag, function(increment) {
            self.COMMIT_TAG.id = increment + 1;
            self.createStartOfDay(createStartOfDay, callback);
          });

          self.db.run('INSERT INTO '+self.SCHEME.tables.tag+'(name,autocomplete) VALUES ("'+self.COMMIT_TAG.name+'","true")');
        } else {
          self.createStartOfDay(createStartOfDay, callback);
        }
      });
    });
  };

  // Creates a start of day task starting now and ending one minute from now. Calls the callback once done.
  self.createStartOfDay = function(canCreate, callback) {
    if (!canCreate){
      callback();
    } else {
      self.insertActivity(self.START_MESSAGE, function(activityId) {
        self.db.all('SELECT * FROM '+self.SCHEME.tables.activity, function(err, data) {
          if (err) {throw err};

          console.log('Inserting start of day into hamster database on', new Date());

          var oneMinuteFromNow = new Date((new Date).getTime() + 60000),
              id = self.retrieveId(data);
          self.db.run('INSERT INTO '+self.SCHEME.tables.task+'(id,activity_id,start_time,end_time) VALUES (?,?,?,?)',
            [id, activityId, self.formatDate(new Date() + ''), self.formatDate(oneMinuteFromNow + '')], function() {
              callback();
          });
        });
      });
    }
  };

  // Inserts an activity given the description if it does not already exist. Calls the callback with the id of the activity.
  self.insertActivity = function(description, callback){
    self.db.all('SELECT * FROM '+self.SCHEME.tables.activity, function(err, data) {
      if (err) {throw err};

      var activityId = null;
      data.forEach(function(tag) {
        if (tag.name === description){
          activityId = tag.id;
        }
      });

      if (activityId === null){
        activityId = self.retrieveId(data);

        self.db.run('INSERT INTO '+self.SCHEME.tables.activity+'(id,name,category_id,search_name) VALUES (?,?,?,?)',
          [activityId, description, self.SCHEME.workCategory, description.toLowerCase()],
        function(err) {
          if (err) {throw err};

          callback(activityId);
        });
      } else {
        callback(activityId);
      }
    });
  };

  self.addTagToTask = function(taskId) {
    self.db.run('INSERT INTO '+self.SCHEME.tables.taskTagMap+'(fact_id,tag_id) VALUES (?,?)', [taskId, self.COMMIT_TAG.id]);
  };

  // Inserts a commit fact with the correct timestamps, if it does not already exist. The start time is determined from the previous task.
  self.insertTask = function(description, end, hasTag, callback) {
    end = self.formatDate(end);

    self.insertActivity(description, function(activityId) {
      self.db.all('SELECT * FROM '+self.SCHEME.tables.task + ' ORDER BY end_time', function(err, data) {
        if (err) {throw err};

        var id = null,
            start = null;
        data.forEach(function(tag, index) {
          if (tag.activity_id === activityId && tag.end_time == end){
            id = tag.id;
          }

          if (index === data.length - 1){
            start = tag.end_time;
          }
        });

        if (start === null){
          throw('Error: There must be a time defined before a commit is logged.');
        }

        // Has this task already been inserted
        if (id === null){
          id = self.retrieveId(data);

          console.log('Inserting', description, 'into hamster database.');
          self.db.run('INSERT INTO '+self.SCHEME.tables.task+'(id,activity_id,start_time,end_time) VALUES (?,?,?,?)',
            [id, activityId, start, end], function() {
              if (hasTag){
                self.addTagToTask(id, callback);
              } else if (_.isFunction(callback)) {
                callback();
              }
          });
        }
      });
    });
  };

  // Closes the database.
  self.exit = function() {
    self.db.close();
  };

  return self;
};<commit_msg>(fix) Start of day now inserts at the start of the day<commit_after>var sqlite3 = require('sqlite3').verbose(),
    _ = require('lodash');

// Manages all connections to the Hamster database.
module.exports = function(DATABASE_LOCATION) {
  var self = this || {};
  self.db = new sqlite3.Database(DATABASE_LOCATION);

  // Used to track and create the tag for commits.
  self.COMMIT_TAG = {
    name: 'commit',
    id: null
  };

  self.START_MESSAGE = 'Start of day';

  self.SCHEME = {
    workCategory: 1,

    tables: {
      autoIncrement: 'SQLITE_SEQUENCE',
      task: 'facts',
      taskTagMap: 'fact_tags',
      tag: 'tags',
      activity: 'activities'
    }
  }

  // Given a list of objects retrieves an id, 1 if none could be found.
  self.retrieveId = function(list) {
    id = _.max(_.pluck(list, 'id')) + 1;
    return (id > -1) ? id : 1;
  };

  // Gets the next auto increment value for the given table and passes that into the first argument for the callback.
  self.getNextAutoIncrementFor = function(table, callback){
    self.db.all('SELECT * FROM '+self.SCHEME.tables.autoIncrement+' where name="'+table+'"', function(err, data) {
      if (err) {throw err};
      callback(data[0].seq);
    });
  };

  // Returns the time in the format: yyyy-mm-dd hh:mm:ss for hamster.
  self.formatDate = function(date) {
    date = new Date(date);
    var partOfDay = date.toTimeString().split(' ')[0],
        partOfYear = date.toISOString().split('T')[0];

    return partOfYear + ' ' + partOfDay;
  };

  // Creates a new commit tag if necessary. Calls the callback when done. May be async. other arguments:
  // createStartOfDay: if false no start of day task will be created. If there are no tasks this can cause the commit logging to crash.
  self.init = function(callback, createStartOfDay) {
    self.db.serialize(function() {
      self.db.all('SELECT * FROM '+self.SCHEME.tables.tag, function(err, data) {
        if (err) {throw err};

        data.forEach(function(tag) {
          if (tag.name === self.COMMIT_TAG.name){
            self.COMMIT_TAG.id = tag.id;
          }
        });

        if (self.COMMIT_TAG.id === null){
          console.log('"' + self.COMMIT_TAG.name + '" tag not found, creating it.');

          self.getNextAutoIncrementFor(self.SCHEME.tables.tag, function(increment) {
            self.COMMIT_TAG.id = increment + 1;
            self.createStartOfDay(createStartOfDay, callback);
          });

          self.db.run('INSERT INTO '+self.SCHEME.tables.tag+'(name,autocomplete) VALUES ("'+self.COMMIT_TAG.name+'","true")');
        } else {
          self.createStartOfDay(createStartOfDay, callback);
        }
      });
    });
  };

  // Creates a start of day task starting now and ending one minute from now. Calls the callback once done.
  self.createStartOfDay = function(canCreate, callback) {
    if (!canCreate){
      callback();
    } else {
      var oneMinuteFromNow = new Date((new Date).getTime() + 60000);
      self.insertTask(self.START_MESSAGE, oneMinuteFromNow, false, callback, new Date());
    }
  };

  // Inserts an activity given the description if it does not already exist. Calls the callback with the id of the activity.
  self.insertActivity = function(description, callback){
    self.db.all('SELECT * FROM '+self.SCHEME.tables.activity, function(err, data) {
      if (err) {throw err};

      var activityId = null;
      data.forEach(function(tag) {
        if (tag.name === description){
          activityId = tag.id;
        }
      });

      if (activityId === null){
        activityId = self.retrieveId(data);

        self.db.run('INSERT INTO '+self.SCHEME.tables.activity+'(id,name,category_id,search_name) VALUES (?,?,?,?)',
          [activityId, description, self.SCHEME.workCategory, description.toLowerCase()],
        function(err) {
          if (err) {throw err};

          callback(activityId);
        });
      } else {
        callback(activityId);
      }
    });
  };

  self.addTagToTask = function(taskId) {
    self.db.run('INSERT INTO '+self.SCHEME.tables.taskTagMap+'(fact_id,tag_id) VALUES (?,?)', [taskId, self.COMMIT_TAG.id]);
  };

  // Inserts a commit fact with the correct timestamps, if it does not already exist. The start time is determined from the previous task or from the
  // sent in start if defined.
  self.insertTask = function(description, end, hasTag, callback, start) {
    end = self.formatDate(end);
    if (_.isDate(start)) {
      start = self.formatDate(start);
    }

    self.insertActivity(description, function(activityId) {
      self.db.all('SELECT * FROM '+self.SCHEME.tables.task + ' ORDER BY end_time', function(err, data) {
        if (err) {throw err};

        var id = null;
        data.forEach(function(tag, index) {
          if (tag.activity_id === activityId && tag.end_time == end){
            id = tag.id;
          }

          if (index === data.length - 1 && _.isEmpty(start)){
            start = tag.end_time;
          }
        });

        if (start === null){
          throw('Error: There must be a time defined before a commit is logged.');
        }

        // Has this task already been inserted
        if (id === null){
          id = self.retrieveId(data);

          console.log('Inserting', description, 'into hamster database at', end, '.');
          self.db.run('INSERT INTO '+self.SCHEME.tables.task+'(id,activity_id,start_time,end_time) VALUES (?,?,?,?)',
            [id, activityId, start, end], function() {
              if (hasTag){
                self.addTagToTask(id, callback);
              } else if (_.isFunction(callback)) {
                callback();
              }
          });
        }
      });
    });
  };

  // Closes the database.
  self.exit = function() {
    self.db.close();
  };

  return self;
};<|endoftext|>


<commit_before>// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later

//= require ./content_view
app.views.Comment = app.views.Content.extend({
  templateName: "comment",
  className : "comment media",
  tooltipSelector: "time",

  events : function() {
    return _.extend({}, app.views.Content.prototype.events, {
      "click .comment_delete": "destroyModel",
      "click .comment_report": "report"
    });
  },

  initialize : function(options){
    this.templateName = options.templateName || this.templateName;
    this.model.on("change", this.render, this);
  },

  presenter : function() {
    return _.extend(this.defaultPresenter(), {
      canRemove: this.canRemove(),
      text: app.helpers.textFormatter(this.model.get("text"), this.model.get("mentioned_people"))
    });
  },

  ownComment : function() {
    return app.currentUser.authenticated() && this.model.get("author").diaspora_id === app.currentUser.get("diaspora_id");
  },

  postOwner : function() {
    return  app.currentUser.authenticated() && this.model.get("parent").author.diaspora_id === app.currentUser.get("diaspora_id");
  },

  canRemove : function() {
    return app.currentUser.authenticated() && (this.ownComment() || this.postOwner());
  }
});

app.views.ExpandedComment = app.views.Comment.extend({
  postRenderTemplate : function(){
  }
});
// @license-end
<commit_msg>Set video click handler at app.views.ExpandedComment<commit_after>// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later

//= require ./content_view
app.views.Comment = app.views.Content.extend({
  templateName: "comment",
  className : "comment media",
  tooltipSelector: "time",

  events : function() {
    return _.extend({}, app.views.Content.prototype.events, {
      "click .comment_delete": "destroyModel",
      "click .comment_report": "report"
    });
  },

  initialize : function(options){
    this.templateName = options.templateName || this.templateName;
    this.model.on("change", this.render, this);
  },

  presenter : function() {
    return _.extend(this.defaultPresenter(), {
      canRemove: this.canRemove(),
      text: app.helpers.textFormatter(this.model.get("text"), this.model.get("mentioned_people"))
    });
  },

  ownComment : function() {
    return app.currentUser.authenticated() && this.model.get("author").diaspora_id === app.currentUser.get("diaspora_id");
  },

  postOwner : function() {
    return  app.currentUser.authenticated() && this.model.get("parent").author.diaspora_id === app.currentUser.get("diaspora_id");
  },

  canRemove : function() {
    return app.currentUser.authenticated() && (this.ownComment() || this.postOwner());
  }
});

app.views.ExpandedComment = app.views.Comment.extend({
  postRenderTemplate : function(){
    this.bindMediaEmbedThumbClickEvent();
  }
});
// @license-end
<|endoftext|>


<commit_before>var LostDoc = LostDoc || {};

new function (LostDoc) {

    LostDoc.Layout = function (settings, userSettings) {

        this._settings = {
            'handleSelector': '.handle',
            'containerSelector': '#wrapper',
            'leftColumnSelector': 'div.left-col-outer',
            'rightColumnSelector': 'div.right-col-outer',
            'explicitWidthSelector': '.explicit-width',
            'resizingClass': 'resizing',
            'detachableContentSelector': '.detachable',
            'detachedContentClass': 'detached',
            'detachedContentTop': '50'
        };

        if (settings != null) {
            $.extend(this._settings, settings);
        }

        if (!userSettings.layout) {
            userSettings.layout = {
                leftColWidth: 20
            };
        }

        this._userSettings = userSettings;

        this._leftColWidthPercent = this._userSettings.layout.leftColWidth;

        this._handle = $(this._settings.handleSelector);
        this._container = $(this._settings.containerSelector);
        this._leftColumn = $(this._settings.leftColumnSelector);
        this._rightColumn = $(this._settings.rightColumnSelector);
        this._leftContent = this._leftColumn.find(this._settings.detachableContentSelector);
        this._rightContent = this._rightColumn.find(this._settings.detachableContentSelector);
        this._leftContentTop = this._leftContent.offset().top;
        this._rightContentTop = this._rightContent.offset().top;

        this._leftDetachedContentTop = Math.min(this._leftContentTop, this._settings.detachedContentTop);
        this._rightDetachedContentTop = Math.min(this._rightContentTop, this._settings.detachedContentTop);

        $(window).on("resize", this._onResize.bind(this));
        $(window).on("scroll", this._onScroll.bind(this));

        var mouseDown = this._handle.bind('mousedown', function (e) {
            $('body').addClass(this._settings.resizingClass);

            this._oldClientX = e.clientX;

            this._leftColtWidth = this._leftColumn.width();

            var mouseMove = $(document).bind('mousemove', function (e) {
                var offset = this._oldClientX - e.clientX;

                // TODO move constants into settings
                this._leftColWidthPercent = Math.max(10, Math.min(70, this._pxToPercentage(this._leftColtWidth - offset)));
                // console.log(offset, this._leftColWidthPercent);
                this._resize();
            }.bind(this));
        }.bind(this));

        var mouseUp = $(document).bind('mouseup', function () {
            $(document).unbind('mousemove');

            this._userSettings.layout.leftColWidth = this._leftColWidthPercent;
            this._userSettings.save();
            $('body').removeClass(this._settings.resizingClass);
        }.bind(this));

        this._resize();
    };

    LostDoc.Layout.prototype._onResize = function (ev) {
        var leftColWidth = this._container.width() * (this._leftColWidthPercent / 100);
        var newLeftColWidthPercent = this._pxToPercentage(leftColWidth);

        if (newLeftColWidthPercent != this._leftColWidthPercent) {
            this._leftColWidthPercent = newLeftColWidthPercent;
            this._resize();
        }
        this._scroll();
    };

    LostDoc.Layout.prototype._onScroll = function (ev) {
        this._scroll();
    };

    LostDoc.Layout.prototype._pxToPercentage = function (px) {
        var containerWidth = this._container.width();
        var temp = parseFloat(px) / parseFloat(containerWidth);
        var percentage = Math.round(10000 * temp) / 100;
        return percentage;
    };

    LostDoc.Layout.prototype._resize = function () {
        var leftWidth = this._leftColWidthPercent + '%';
        var rightWidth = (100 - this._leftColWidthPercent) + '%';

        this._handle.css('left', leftWidth);

        this._leftColumn.css('width', leftWidth);
        if (this._leftContent && this._isDetached(this._leftContent)) {
            this._leftContent.css('width', leftWidth);
        }

        this._rightColumn.css('width', rightWidth);
        if (this._rightContent && this._isDetached(this._rightContent)) {
            this._rightContent.css('width', rightWidth);
        }
    };

    LostDoc.Layout.prototype._scroll = function () {

        var leftWidth = this._leftColWidthPercent + '%';
        var rightWidth = (100 - this._leftColWidthPercent) + '%';

        if (this._leftContent) {
            this._sticky(this._leftContent, this._leftDetachedContentTop, leftWidth);
        }

        if (this._rightContent) {
            this._sticky(this._rightContent, this._rightDetachedContentTop, rightWidth);
        }
    };

    LostDoc.Layout.prototype._sticky = function (content, contentTop, contentWidth) {
        var wndHeight = $(window).height();

        var contentHeight = content.height();
        if (contentHeight < wndHeight) {
            // sticky left
            console.log("detachable", content);

            var currentTop = content.offset().top;

            console.log("offset", currentTop);

            if (!this._isDetached(content) && currentTop <= contentTop) {
                this._detach(content, contentTop, contentWidth);
                console.log("detaching", content);
            } else if (this._isDetached(content) && currentTop <= contentTop) {
                this._attach(content);
                console.log("attaching", content);
            }
        } else {
            this._attach(content);
        }
    };

    LostDoc.Layout.prototype._isDetached = function (detachable) {
        return detachable.hasClass(this._settings.detachedContentClass);
    };

    LostDoc.Layout.prototype._attach = function (detachable) {
        detachable.removeClass(this._settings.detachedContentClass);
        detachable.css('top', null);
        detachable.css('width', null);
    };

    LostDoc.Layout.prototype._detach = function (detachable, top, width) {
        detachable.addClass(this._settings.detachedContentClass);
        detachable.css('top', top + 'px');
        detachable.css('width', width + '%');
    };
}(LostDoc); // note that the namespace is instantiated immediately
<commit_msg>Fixed broken sticky nav<commit_after>var LostDoc = LostDoc || {};

new function (LostDoc) {

    LostDoc.Layout = function (settings, userSettings) {

        this._settings = {
            'handleSelector': '.handle',
            'containerSelector': '#wrapper',
            'leftColumnSelector': 'div.left-col-outer',
            'rightColumnSelector': 'div.right-col-outer',
            'explicitWidthSelector': '.explicit-width',
            'resizingClass': 'resizing',
            'detachableContentSelector': '.detachable',
            'detachedContentClass': 'detached',
            'detachedContentTop': '25'
        };

        if (settings != null) {
            $.extend(this._settings, settings);
        }

        if (!userSettings.layout) {
            userSettings.layout = {
                leftColWidth: 20
            };
        }

        this._userSettings = userSettings;

        this._leftColWidthPercent = this._userSettings.layout.leftColWidth;

        this._handle = $(this._settings.handleSelector);
        this._container = $(this._settings.containerSelector);
        this._leftColumn = $(this._settings.leftColumnSelector);
        this._rightColumn = $(this._settings.rightColumnSelector);
        this._leftContent = this._leftColumn.find(this._settings.detachableContentSelector);
        this._rightContent = this._rightColumn.find(this._settings.detachableContentSelector);
        this._leftContentTop = this._leftContent.offset().top;
        this._rightContentTop = this._rightContent.offset().top;

        this._leftDetachedContentTop = Math.min(this._leftContentTop, this._settings.detachedContentTop);
        this._rightDetachedContentTop = Math.min(this._rightContentTop, this._settings.detachedContentTop);

        $(window).on("resize", this._onResize.bind(this));
        $(window).on("scroll", this._onScroll.bind(this));

        var mouseDown = this._handle.bind('mousedown', function (e) {
            $('body').addClass(this._settings.resizingClass);

            this._oldClientX = e.clientX;

            this._leftColtWidth = this._leftColumn.width();

            var mouseMove = $(document).bind('mousemove', function (e) {
                var offset = this._oldClientX - e.clientX;

                // TODO move constants into settings
                this._leftColWidthPercent = Math.max(10, Math.min(70, this._pxToPercentage(this._leftColtWidth - offset)));
                // console.log(offset, this._leftColWidthPercent);
                this._resize();
            }.bind(this));
        }.bind(this));

        var mouseUp = $(document).bind('mouseup', function () {
            $(document).unbind('mousemove');

            this._userSettings.layout.leftColWidth = this._leftColWidthPercent;
            this._userSettings.save();
            $('body').removeClass(this._settings.resizingClass);
        }.bind(this));

        this._resize();
    };

    LostDoc.Layout.prototype._onResize = function (ev) {
        var leftColWidth = this._container.width() * (this._leftColWidthPercent / 100);
        var newLeftColWidthPercent = this._pxToPercentage(leftColWidth);

        if (newLeftColWidthPercent != this._leftColWidthPercent) {
            this._leftColWidthPercent = newLeftColWidthPercent;
            this._resize();
        }
        this._scroll();
    };

    LostDoc.Layout.prototype._onScroll = function (ev) {
        this._scroll();
    };

    LostDoc.Layout.prototype._pxToPercentage = function (px) {
        var containerWidth = this._container.width();
        var temp = parseFloat(px) / parseFloat(containerWidth);
        var percentage = Math.round(10000 * temp) / 100;
        return percentage;
    };

    LostDoc.Layout.prototype._resize = function () {
        var leftWidth = this._leftColWidthPercent + '%';
        var rightWidth = (100 - this._leftColWidthPercent) + '%';

        this._handle.css('left', leftWidth);

        this._leftColumn.css('width', leftWidth);
        if (this._leftContent && this._isDetached(this._leftContent)) {
            this._leftContent.css('width', leftWidth);
        }

        this._rightColumn.css('width', rightWidth);
        if (this._rightContent && this._isDetached(this._rightContent)) {
            this._rightContent.css('width', rightWidth);
        }
    };

    LostDoc.Layout.prototype._scroll = function () {

        var leftWidth = this._leftColWidthPercent + '%';
        var rightWidth = (100 - this._leftColWidthPercent) + '%';

        if (this._leftContent) {
            this._sticky(this._leftContent, this._leftDetachedContentTop, leftWidth);
        }

        if (this._rightContent) {
            this._sticky(this._rightContent, this._rightDetachedContentTop, rightWidth);
        }
    };

    LostDoc.Layout.prototype._sticky = function (content, contentTop, contentWidth) {
        var wndHeight = $(window).height();
        var scrollTop = $(window).scrollTop();
        var contentHeight = content.height();

        if (contentHeight < wndHeight) {
            //console.log("detachable", content);

            var offset = content.offset().top - scrollTop;

            //console.log("offset", offset);
            //console.log("contentTop", contentTop);
            //console.log("isDetached", this._isDetached(content));

            if (!this._isDetached(content) && offset <= contentTop) {
                this._detach(content, contentTop, contentWidth);
                //console.log("detaching", content);
            } else if (this._isDetached(content) && scrollTop <= contentTop) {
                this._attach(content);
                //console.log("attaching", content);
            }
        } else {
            this._attach(content);
        }
    };

    LostDoc.Layout.prototype._isDetached = function (detachable) {
        return detachable.hasClass(this._settings.detachedContentClass);
    };

    LostDoc.Layout.prototype._attach = function (detachable) {
        detachable.removeClass(this._settings.detachedContentClass);
        detachable.css('top', null);
        detachable.css('width', null);
    };

    LostDoc.Layout.prototype._detach = function (detachable, top, width) {
        detachable.addClass(this._settings.detachedContentClass);
        detachable.css('top', top + 'px');
        detachable.css('width', width + '%');
    };
}(LostDoc); // note that the namespace is instantiated immediately
<|endoftext|>


<commit_before>ManageIQ.angular.app.component('widgetMenu', {
  bindings: {
    id: '<',
  },
  controllerAs: 'vm',
  controller: ['$http', 'miqService', function($http, miqService) {
    var vm = this;
    vm.widgetMenuModel = {shortcuts: []};
    vm.shortcutsMissing = function() {
      return vm.widgetMenuModel.shortcuts.length === 0;
    };
    this.$onInit = function() {
      $http.get('/dashboard/widget_menu_data/' + vm.id)
        .then(function(response) { vm.widgetMenuModel = response.data; })
        .catch(miqService.handleFailure);
      vm.div_id = 'dd_w' + vm.id + '_box';
    };
  }],
  template: [
    '
',
    '
',
    '
',
    '
',
    __('No shortcuts are authorized for this user, contact your Administrator'),
    '
',
    '
',
    '',
    '',
    '{{shortcut.description}}',
    '',
    '	',
    '
',
    '
',
    '
',
    '
',
  ].join("\n"),
});
<commit_msg>Fix HTML<commit_after>ManageIQ.angular.app.component('widgetMenu', {
  bindings: {
    id: '<',
  },
  controllerAs: 'vm',
  controller: ['$http', 'miqService', function($http, miqService) {
    var vm = this;
    vm.widgetMenuModel = {shortcuts: []};

    vm.shortcutsMissing = function() {
      return vm.widgetMenuModel.shortcuts.length === 0;
    };

    this.$onInit = function() {
      $http.get('/dashboard/widget_menu_data/' + vm.id)
        .then(function(response) { vm.widgetMenuModel = response.data; })
        .catch(miqService.handleFailure);
      vm.div_id = 'dd_w' + vm.id + '_box';
    };
  }],
  template: [
    '
',
    '
',
    '
',
    '
',
    __('No shortcuts are authorized for this user, contact your Administrator'),
    '
',
    '
',
    '        ',
    '          ',
    '{{shortcut.description}}',
    '          ',
    '        	',
    '
',
    '
',
    '
',
    '
',
  ].join("\n"),
});
<|endoftext|>


<commit_before>
M.BillsView = M.BaseView.extend({
  className: 'bills',

  collection: new M.Bills(),

  tagName: 'ul',

  templatePath: 'bills/index',

  events: {
    'click .condensed-bill': 'showBill',
    'submit #create-bill-form': 'handleSubmit'
  },

  initialize: function() {
    this.listenTo(this.collection, 'sync', this.handleSync);
    this.listenTo(this.collection, 'error', this.handleError);
    this.collection.fetch();
  },

  render: function() {
    this.$el.html(this.template({ bills: this.collection.toJSON() }));
    $('#money').html(this.el);
    this.populateCategories();
    this.populateRepeatIntervals();

    return this;
  },

  handleSync: function() {
    this.render();
  },

  handleError: function(collection, response, options) {
    $('#money').text(response.status + ' ' + response.statusText);
  },

  showBill: function(e) {
    this.trigger('m:show:bill', e.target.dataset.id);
  },

  handleSubmit: function(e) {
    e.preventDefault();

    var props = this.createAttributesObject(this.$('#create-bill-form').serializeArray());
    var newBill = this.collection.create(props, { wait: true });

    if (newBill.isValid()) {
      this.setValidationResponse('waiting...');
    } else {
      this.setValidationResponse(newBill.validationError);
    }
  },

  populateCategories: function() {
    var categoriesView = new M.CategoriesView();
    categoriesView.render();
  },

  populateRepeatIntervals: function() {
    var repeatIntervalsView = new M.RepeatIntervalsView();
    repeatIntervalsView.render();
  }
});
<commit_msg>ADD WARNING<commit_after>
M.BillsView = M.BaseView.extend({
  className: 'bills',

  collection: new M.Bills(),

  tagName: 'ul',

  templatePath: 'bills/index',

  events: {
    'click .condensed-bill': 'showBill',
    'submit #create-bill-form': 'handleSubmit'
  },

  initialize: function() {
    this.listenTo(this.collection, 'sync', this.handleSync);
    this.listenTo(this.collection, 'error', this.handleError);
    this.collection.fetch();
  },

  render: function() {
    this.$el.html(this.template({ bills: this.collection.toJSON() }));
    $('#money').html(this.el);
    this.populateCategories();
    this.populateRepeatIntervals();

    return this;
  },

  handleSync: function() {
    this.render();
  },

  handleError: function(collection, response, options) {
    $('#money').text(response.status + ' ' + response.statusText);
  },

  showBill: function(e) {
    this.trigger('m:show:bill', e.target.dataset.id);
  },

  handleSubmit: function(e) {
    e.preventDefault();

    var props = this.createAttributesObject(this.$('#create-bill-form').serializeArray());
    // FIXME: CONVERT date format and tags to array here
    var newBill = this.collection.create(props, { wait: true });

    if (newBill.isValid()) {
      this.setValidationResponse('waiting...');
    } else {
      this.setValidationResponse(newBill.validationError);
    }
  },

  populateCategories: function() {
    var categoriesView = new M.CategoriesView();
    categoriesView.render();
  },

  populateRepeatIntervals: function() {
    var repeatIntervalsView = new M.RepeatIntervalsView();
    repeatIntervalsView.render();
  }
});
<|endoftext|>