<commit_before>/* jshint camelcase: false */
module.exports = function (grunt) {
  'use strict';

  // check task runtime
  require('time-grunt')(grunt);

  grunt.initConfig({

    // load module meta data
    pkg: grunt.file.readJSON('package.json'),

    // define a src set of files for other tasks
    src: {
      lint: ['Gruntfile.js', 'index.js', 'lib/**/*.js', 'test/*.js'],
      complexity: ['index.js', 'lib/**/*.js'],
      test: ['test/*.js'],
      src: ['index.js', 'lib/**/*.js']
    },

    // clean automatically generated helper files & docs
    clean: {
      coverage: ['coverage', 'report/coverage'],
      report: ['report/complexity', 'report/api', 'report/docs'],
      reportZip: ['report.zip']
    },

    // speed up build by defining concurrent tasks
    concurrent: {
      test: ['lint', 'mochaTest', 'complexity'],
      docs: ['plato', 'documantix', 'yuidoc']
    },

    // linting
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: '<%= src.lint %>'
    },

    // testing
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          require: 'coverage/blanket'
        },
        src: '<%= src.test %>'
      },
      coverage: {
        options: {
          reporter: 'html-cov',
          quiet: true,
          captureFile: 'report/coverage/index.html'
        },
        src: '<%= src.test %>'
      },
      jsoncoverage: {
        options: {
          reporter: 'json-cov',
          quiet: true,
          captureFile: 'report/coverage/coverage.json'
        },
        src: '<%= src.test %>'
      }
    },

    // code metrics
    complexity: {
      generic: {
        src: '<%= src.complexity %>',
        options: {
          cyclomatic: 6,
          halstead: 22,
          maintainability: 58
        }
      }
    },
    plato: {
      generic: {
        options : {
          jshint : grunt.file.readJSON('.jshintrc')
        },
        files: {
          'report/complexity': '<%= src.complexity %>',
        }
      }
    },

    // api docs
    yuidoc: {
      compile: {
        name: '<%= pkg.name %>',
        description: '<%= pkg.description %>',
        version: '<%= pkg.version %>',
        url: '<%= pkg.homepage %>',
        options: {
          paths: '.',
          outdir: 'report/api'
        }
      }
    },

    // user docs
    documantix: {
      options: {
        header: 'dalekjs/dalekjs.com/master/assets/header.html',
        footer: 'dalekjs/dalekjs.com/master/assets/footer.html',
        target: 'report/docs',
        vars: {
          title: 'DalekJS - Documentation - Browser - Mozilla Firefox',
          desc: 'DalekJS - Documentation - Browser - Mozilla Firefox',
          docs: true
        }
      },
      src: ['index.js']
    },

    // add current timestamp to the html document
    includereplace: {
      dist: {
        options: {
          globals: {
            timestamp: '<%= grunt.template.today("dddd, mmmm dS, yyyy, h:MM:ss TT") %>'
          },
        },
        src: 'report/docs/*.html',
        dest: './'
      }
    },

    // up version, tag & commit
    bump: {
      options: {
        files: ['package.json'],
        commit: true,
        commitMessage: 'Release v%VERSION%',
        commitFiles: ['package.json'],
        createTag: true,
        tagName: '%VERSION%',
        tagMessage: '%VERSION%',
        push: true,
        pushTo: 'git@github.com:dalekjs/dalek-browser-firefox.git'
      }
    },

    // compress artifacts
    compress: {
      main: {
        options: {
          archive: 'report.zip'
        },
        files: [
          {src: ['report/**'], dest: '/'}
        ]
      }
    }

  });

  // prepare files & folders for grunt:plato & coverage
  grunt.registerTask('preparePlato', function () {
    var fs = require('fs');

    var platoDummyFolders = ['report', 'report/complexity', 'report/complexity/files', 'report/complexity/files/index_js', 'report/complexity/files/lib', 'report/complexity/files/lib/commands', 'report/complexity/files/lib_commands_marionette', 'report/complexity/files/lib_commands_webdriver', 'report/complexity/files/lib_webdriver_js', 'report/complexity/files/lib_marionette_js'];
    var platoDummyFiles = ['/report/complexity/report.history.json', '/report/complexity/files/report.history.json', '/report/complexity/files/index_js/report.history.json', '/report/complexity/files/lib_webdriver_js/report.history.json', '/report/complexity/files/lib_marionette_js/report.history.json'];

    // loopy loop
    ['/lib/commands/marionette/', '/lib/commands/webdriver/'].forEach(function (folder) {
      fs.readdirSync(__dirname + folder).forEach(function (file) {
        var platoFolder = '/report/complexity/files/' + folder.substring(1).replace(/\//g, '_') + file.replace('.js', '_js');
        platoDummyFolders.push(platoFolder);
        platoDummyFiles.push(platoFolder + '/report.history.json');
      });
    });

    // generate dirs for docs & reports
    platoDummyFolders.forEach(function (path) {
      if (!fs.existsSync(__dirname + '/' + path)) {
        fs.mkdirSync(__dirname + '/' + path);
      }
    });

    // store some dummy reports, so that grunt plato doesnt complain
    platoDummyFiles.forEach(function (file) {
      if (!fs.existsSync(__dirname + file)) {
        fs.writeFileSync(__dirname + file, '{}');
      }
    });
  });

  // prepare files & folders for coverage
  grunt.registerTask('prepareCoverage', function () {
    var fs = require('fs');

    // generate folders
    ['coverage', 'report', 'report/coverage'].forEach(function (folder) {
      if (!fs.existsSync(__dirname + '/' + folder)) {
        fs.mkdirSync(__dirname + '/' + folder);
      }
    });

    // generate code coverage helper file
    var coverageHelper = 'require("blanket")({pattern: [require("fs").realpathSync(__dirname + "/../index.js"), require("fs").realpathSync(__dirname + "/../lib/")]});';
    if (!fs.existsSync(__dirname + '/coverage/blanket.js')) {
      fs.writeFileSync(__dirname + '/coverage/blanket.js', coverageHelper);
    }
  });

  // generates a coverage badge
  grunt.registerTask('generateCoverageBadge', function () {
    var fs = require('fs');
    if (fs.existsSync(__dirname + '/node_modules/coverage-badge')) {
      if (fs.existsSync(__dirname + '/report/coverage/coverage.json')) {
        var green = [147,188,59];
        var yellow = [166,157,0];
        var red = [189,0,2];

        var getColor = function (coverage) {
          if (coverage > 90) {
            return mixColors(yellow, green, (coverage-90)/10);
          }

          if (coverage > 80) {
            return mixColors(red, yellow, (coverage-80)/10);
          }

          return createColor(red);
        };

        var mixColors = function (from, to, ratio) {
          var result = [], i;
          for (i=0; i<3; i++) {
            result[i] = Math.round(from[i] + (ratio * (to[i]-from[i])));
          }
          return createColor(result);
        };

        var createColor = function (values) {
          return 'rgba('+values[0]+','+values[1]+','+values[2]+',1)';
        };

        var Badge = require(__dirname + '/node_modules/coverage-badge/lib/Badge.js');
        var badgeFn = function(coverage) {
          coverage = Math.floor(Number(coverage));
          var badge = new Badge({
            box_color: getColor(coverage),
            box_text: coverage+'%',
            label_text: 'cov',
            height: 18,
            width: 49,
            box_width: 25,
            rounding: 0,
            padding: 0,
            label_font: '7pt DejaVu Sans',
            box_font: 'bold 7pt DejaVu Sans'
          });
          return badge.stream();
        };

        var coverage = JSON.parse(fs.readFileSync(__dirname + '/report/coverage/coverage.json')).coverage;
        var file = fs.createWriteStream(__dirname + '/report/coverage/coverage.png');
        badgeFn(coverage).pipe(file);
      }
    }
  });

  // archives the docs if a new version appears
  grunt.registerTask('archive', function () {
    var done = this.async();
    grunt.util.spawn({cmd: 'git', args: ['describe', '--abbrev=0', '--tags']}, function (error, result) {
      var lastTag = result.toString();
      if (grunt.file.isFile('_raw/docs/' + lastTag + '/firefox.html')) {
        grunt.log.ok('Nothing to archive');
        done();
        return true;
      }

      if (!grunt.file.isDir('_raw/docs/' + lastTag)) {
        grunt.file.mkdir('_raw/docs/' + lastTag);
      }

      grunt.file.copy('report/docs/firefox.html', '_raw/docs/' + lastTag + '/firefox.html');
      grunt.log.ok('Archived document with version: ' + lastTag);
      done();
    });
  });

  // releases a new canary build
  grunt.registerTask('release-canary', function () {
    var done = this.async();
    var pkg = grunt.config.get('pkg');
    var canaryPkg = grunt.util._.clone(pkg);

    Object.keys(canaryPkg.dependencies).forEach(function (pack) {
      if (pack.search('dalek') !== -1) {
        delete canaryPkg.dependencies[pack];
        canaryPkg.dependencies[pack + '-canary'] = 'latest';
      }
    });

    canaryPkg.name = canaryPkg.name + '-canary';
    canaryPkg.version = canaryPkg.version + '-' + grunt.template.today('yyyy-mm-dd-HH-MM-ss');

    grunt.file.write('package.json', JSON.stringify(canaryPkg, true, 2));

    var npm = require('npm');
    npm.load({}, function() {
      npm.registry.adduser(process.env.npmuser, process.env.npmpass, process.env.npmmail, function(err) {
        if (err) {
          grunt.log.error(err);
          grunt.file.write('package.json', JSON.stringify(pkg, true, 2));
          done(false);
        } else {
          npm.config.set('email', process.env.npmmail, 'user');
          npm.commands.publish([], function(err) {
            grunt.file.write('package.json', JSON.stringify(pkg, true, 2));
            grunt.log.ok('Published canary build to registry');
            done(!err);
          });
        }
      });
    });
  });

  // release a new version
  grunt.registerTask('release-package', function () {
    var done = this.async();
    var http = require('http');
    var pkg = grunt.config.get('pkg');
    var body = '';

    http.get('http://registry.npmjs.org/' + pkg.name, function(res) {
      res.on('data', function (data) {
        body += data;
      });

      res.on('end', function () {
        var versions = grunt.util._.pluck(JSON.parse(body).versions, 'version');
        var currVersion =  parseInt(pkg.version.replace(/\./gi, ''), 10);
        var availableVersions = versions.map(function (version) {
          return parseInt(version.replace(/\./gi, ''), 10);
        });

        if (!grunt.util._.contains(availableVersions, currVersion)) {
          var npm = require('npm');
          npm.load({}, function() {
            npm.registry.adduser(process.env.npmuser, process.env.npmpass, process.env.npmmail, function(err) {
              if (err) {
                grunt.log.error(err);
                done(false);
              } else {
                npm.config.set('email', process.env.npmmail, 'user');
                npm.commands.publish([], function(err) {
                  grunt.log.ok('Released new version: ', pkg.version);
                  done(!err);
                });
              }
            });
          });
        } else {
          done();
        }
      });
    });
  });

  // generate AUTHORS.md file
  grunt.registerTask('authors', function () {
    var done = this.async();
    grunt.util.spawn({cmd: 'git', args: ['shortlog']}, function (error, result) {
      var authorsRaw = result.toString();
      console.log(authorsRaw);
      done();
    });
  });

  // load 3rd party tasks
  require('load-grunt-tasks')(grunt);

  // define runner tasks
  grunt.registerTask('lint', 'jshint');
  grunt.registerTask('test', ['clean:coverage', 'prepareCoverage', 'concurrent:test', 'generateCoverageBadge']);
  grunt.registerTask('docs', ['clean:reportZip', 'clean:report', 'preparePlato', 'concurrent:docs', 'includereplace', 'compress']);
  grunt.registerTask('all', ['clean', 'test', 'docs']);

};
<commit_msg>chore(gruntfile): updated Gruntfile<commit_after>/* jshint camelcase: false */
module.exports = function (grunt) {
  'use strict';

  // check task runtime
  require('time-grunt')(grunt);

  grunt.initConfig({

    // load module meta data
    pkg: grunt.file.readJSON('package.json'),

    // define a src set of files for other tasks
    src: {
      lint: ['Gruntfile.js', 'index.js', 'lib/**/*.js', 'test/*.js'],
      complexity: ['index.js', 'lib/**/*.js'],
      test: ['test/*.js'],
      src: ['index.js', 'lib/**/*.js']
    },

    // clean automatically generated helper files & docs
    clean: {
      coverage: ['coverage', 'report/coverage'],
      report: ['report/complexity', 'report/api', 'report/docs'],
      reportZip: ['report.zip']
    },

    // speed up build by defining concurrent tasks
    concurrent: {
      test: ['lint', 'mochaTest', 'complexity'],
      docs: ['plato', 'documantix', 'yuidoc']
    },

    // linting
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: '<%= src.lint %>'
    },

    // testing
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          require: 'coverage/blanket'
        },
        src: '<%= src.test %>'
      },
      coverage: {
        options: {
          reporter: 'html-cov',
          quiet: true,
          captureFile: 'report/coverage/index.html'
        },
        src: '<%= src.test %>'
      },
      jsoncoverage: {
        options: {
          reporter: 'json-cov',
          quiet: true,
          captureFile: 'report/coverage/coverage.json'
        },
        src: '<%= src.test %>'
      }
    },

    // code metrics
    complexity: {
      generic: {
        src: '<%= src.complexity %>',
        options: {
          cyclomatic: 6,
          halstead: 22,
          maintainability: 56
        }
      }
    },
    plato: {
      generic: {
        options : {
          jshint : grunt.file.readJSON('.jshintrc')
        },
        files: {
          'report/complexity': '<%= src.complexity %>',
        }
      }
    },

    // api docs
    yuidoc: {
      compile: {
        name: '<%= pkg.name %>',
        description: '<%= pkg.description %>',
        version: '<%= pkg.version %>',
        url: '<%= pkg.homepage %>',
        options: {
          paths: '.',
          outdir: 'report/api'
        }
      }
    },

    // user docs
    documantix: {
      options: {
        header: 'dalekjs/dalekjs.com/master/assets/header.html',
        footer: 'dalekjs/dalekjs.com/master/assets/footer.html',
        target: 'report/docs',
        vars: {
          title: 'DalekJS - Documentation - Browser - Mozilla Firefox',
          desc: 'DalekJS - Documentation - Browser - Mozilla Firefox',
          docs: true
        }
      },
      src: ['index.js']
    },

    // add current timestamp to the html document
    includereplace: {
      dist: {
        options: {
          globals: {
            timestamp: '<%= grunt.template.today("dddd, mmmm dS, yyyy, h:MM:ss TT") %>'
          },
        },
        src: 'report/docs/*.html',
        dest: './'
      }
    },

    // up version, tag & commit
    bump: {
      options: {
        files: ['package.json'],
        commit: true,
        commitMessage: 'Release v%VERSION%',
        commitFiles: ['package.json'],
        createTag: true,
        tagName: '%VERSION%',
        tagMessage: '%VERSION%',
        push: true,
        pushTo: 'git@github.com:dalekjs/dalek-browser-firefox.git'
      }
    },

    // compress artifacts
    compress: {
      main: {
        options: {
          archive: 'report.zip'
        },
        files: [
          {src: ['report/**'], dest: '/'}
        ]
      }
    }

  });

  // prepare files & folders for grunt:plato & coverage
  grunt.registerTask('preparePlato', function () {
    var fs = require('fs');

    var platoDummyFolders = ['report', 'report/complexity', 'report/complexity/files', 'report/complexity/files/index_js', 'report/complexity/files/lib', 'report/complexity/files/lib/commands', 'report/complexity/files/lib_commands_marionette', 'report/complexity/files/lib_commands_webdriver', 'report/complexity/files/lib_webdriver_js', 'report/complexity/files/lib_marionette_js'];
    var platoDummyFiles = ['/report/complexity/report.history.json', '/report/complexity/files/report.history.json', '/report/complexity/files/index_js/report.history.json', '/report/complexity/files/lib_webdriver_js/report.history.json', '/report/complexity/files/lib_marionette_js/report.history.json'];

    // loopy loop
    ['/lib/commands/marionette/', '/lib/commands/webdriver/'].forEach(function (folder) {
      fs.readdirSync(__dirname + folder).forEach(function (file) {
        var platoFolder = '/report/complexity/files/' + folder.substring(1).replace(/\//g, '_') + file.replace('.js', '_js');
        platoDummyFolders.push(platoFolder);
        platoDummyFiles.push(platoFolder + '/report.history.json');
      });
    });

    // generate dirs for docs & reports
    platoDummyFolders.forEach(function (path) {
      if (!fs.existsSync(__dirname + '/' + path)) {
        fs.mkdirSync(__dirname + '/' + path);
      }
    });

    // store some dummy reports, so that grunt plato doesnt complain
    platoDummyFiles.forEach(function (file) {
      if (!fs.existsSync(__dirname + file)) {
        fs.writeFileSync(__dirname + file, '{}');
      }
    });
  });

  // prepare files & folders for coverage
  grunt.registerTask('prepareCoverage', function () {
    var fs = require('fs');

    // generate folders
    ['coverage', 'report', 'report/coverage'].forEach(function (folder) {
      if (!fs.existsSync(__dirname + '/' + folder)) {
        fs.mkdirSync(__dirname + '/' + folder);
      }
    });

    // generate code coverage helper file
    var coverageHelper = 'require("blanket")({pattern: [require("fs").realpathSync(__dirname + "/../index.js"), require("fs").realpathSync(__dirname + "/../lib/")]});';
    if (!fs.existsSync(__dirname + '/coverage/blanket.js')) {
      fs.writeFileSync(__dirname + '/coverage/blanket.js', coverageHelper);
    }
  });

  // generates a coverage badge
  grunt.registerTask('generateCoverageBadge', function () {
    var fs = require('fs');
    if (fs.existsSync(__dirname + '/node_modules/coverage-badge')) {
      if (fs.existsSync(__dirname + '/report/coverage/coverage.json')) {
        var green = [147,188,59];
        var yellow = [166,157,0];
        var red = [189,0,2];

        var getColor = function (coverage) {
          if (coverage > 90) {
            return mixColors(yellow, green, (coverage-90)/10);
          }

          if (coverage > 80) {
            return mixColors(red, yellow, (coverage-80)/10);
          }

          return createColor(red);
        };

        var mixColors = function (from, to, ratio) {
          var result = [], i;
          for (i=0; i<3; i++) {
            result[i] = Math.round(from[i] + (ratio * (to[i]-from[i])));
          }
          return createColor(result);
        };

        var createColor = function (values) {
          return 'rgba('+values[0]+','+values[1]+','+values[2]+',1)';
        };

        var Badge = require(__dirname + '/node_modules/coverage-badge/lib/Badge.js');
        var badgeFn = function(coverage) {
          coverage = Math.floor(Number(coverage));
          var badge = new Badge({
            box_color: getColor(coverage),
            box_text: coverage+'%',
            label_text: 'cov',
            height: 18,
            width: 49,
            box_width: 25,
            rounding: 0,
            padding: 0,
            label_font: '7pt DejaVu Sans',
            box_font: 'bold 7pt DejaVu Sans'
          });
          return badge.stream();
        };

        var coverage = JSON.parse(fs.readFileSync(__dirname + '/report/coverage/coverage.json')).coverage;
        var file = fs.createWriteStream(__dirname + '/report/coverage/coverage.png');
        badgeFn(coverage).pipe(file);
      }
    }
  });

  // archives the docs if a new version appears
  grunt.registerTask('archive', function () {
    var done = this.async();
    grunt.util.spawn({cmd: 'git', args: ['describe', '--abbrev=0', '--tags']}, function (error, result) {
      var lastTag = result.toString();
      if (grunt.file.isFile('_raw/docs/' + lastTag + '/firefox.html')) {
        grunt.log.ok('Nothing to archive');
        done();
        return true;
      }

      if (!grunt.file.isDir('_raw/docs/' + lastTag)) {
        grunt.file.mkdir('_raw/docs/' + lastTag);
      }

      grunt.file.copy('report/docs/firefox.html', '_raw/docs/' + lastTag + '/firefox.html');
      grunt.log.ok('Archived document with version: ' + lastTag);
      done();
    });
  });

  // releases a new canary build
  grunt.registerTask('release-canary', function () {
    var done = this.async();
    var pkg = grunt.config.get('pkg');
    var canaryPkg = grunt.util._.clone(pkg);

    Object.keys(canaryPkg.dependencies).forEach(function (pack) {
      if (pack.search('dalek') !== -1) {
        delete canaryPkg.dependencies[pack];
        canaryPkg.dependencies[pack + '-canary'] = 'latest';
      }
    });

    canaryPkg.name = canaryPkg.name + '-canary';
    canaryPkg.version = canaryPkg.version + '-' + grunt.template.today('yyyy-mm-dd-HH-MM-ss');

    grunt.file.write('package.json', JSON.stringify(canaryPkg, true, 2));

    var npm = require('npm');
    npm.load({}, function() {
      npm.registry.adduser(process.env.npmuser, process.env.npmpass, process.env.npmmail, function(err) {
        if (err) {
          grunt.log.error(err);
          grunt.file.write('package.json', JSON.stringify(pkg, true, 2));
          done(false);
        } else {
          npm.config.set('email', process.env.npmmail, 'user');
          npm.commands.publish([], function(err) {
            grunt.file.write('package.json', JSON.stringify(pkg, true, 2));
            grunt.log.ok('Published canary build to registry');
            done(!err);
          });
        }
      });
    });
  });

  // release a new version
  grunt.registerTask('release-package', function () {
    var done = this.async();
    var http = require('http');
    var pkg = grunt.config.get('pkg');
    var body = '';

    http.get('http://registry.npmjs.org/' + pkg.name, function(res) {
      res.on('data', function (data) {
        body += data;
      });

      res.on('end', function () {
        var versions = grunt.util._.pluck(JSON.parse(body).versions, 'version');
        var currVersion =  parseInt(pkg.version.replace(/\./gi, ''), 10);
        var availableVersions = versions.map(function (version) {
          return parseInt(version.replace(/\./gi, ''), 10);
        });

        if (!grunt.util._.contains(availableVersions, currVersion)) {
          var npm = require('npm');
          npm.load({}, function() {
            npm.registry.adduser(process.env.npmuser, process.env.npmpass, process.env.npmmail, function(err) {
              if (err) {
                grunt.log.error(err);
                done(false);
              } else {
                npm.config.set('email', process.env.npmmail, 'user');
                npm.commands.publish([], function(err) {
                  grunt.log.ok('Released new version: ', pkg.version);
                  done(!err);
                });
              }
            });
          });
        } else {
          done();
        }
      });
    });
  });

  // generate AUTHORS.md file
  grunt.registerTask('authors', function () {
    var done = this.async();
    grunt.util.spawn({cmd: 'git', args: ['shortlog']}, function (error, result) {
      var authorsRaw = result.toString();
      console.log(authorsRaw);
      done();
    });
  });

  // load 3rd party tasks
  require('load-grunt-tasks')(grunt);

  // define runner tasks
  grunt.registerTask('lint', 'jshint');
  grunt.registerTask('test', ['clean:coverage', 'prepareCoverage', 'concurrent:test', 'generateCoverageBadge']);
  grunt.registerTask('docs', ['clean:reportZip', 'clean:report', 'preparePlato', 'concurrent:docs', 'includereplace', 'compress']);
  grunt.registerTask('all', ['clean', 'test', 'docs']);

};
<|endoftext|>


<commit_before>"use strict";

theToolController.controller("CommentAreaController", function ($scope, $http, $routeParams, MemberFactory, CommentFactory) {

  $scope.loading = true;

  $scope.commentData = {
    markdown: ""
  };

  MemberFactory.Member.get({id: "me"}, function (me) {
    $scope.me = me;
  });

  MemberFactory.Member.getAll(function (members) {
    $scope.members = members;
  });

  loadComments();

  function loadComments() {
    $scope.loading = true;

    if ($scope.thread.indexOf("company-") != -1) {
      CommentFactory.Company.getAll({id: $scope.thread.split("-")[1]}, gotComments);
    }

    function gotComments(comments) {
      $scope.comments = comments;

      $scope.loading = false;
    }
  }

  $scope.postComment = function () {
    if ($scope.commentData.markdown === ""){
      $scope.emptyComment = true;
      return;
    }

    CommentFactory.Comment.create({
      thread: $scope.thread,
      member: $scope.me.id,
      markdown: $scope.commentData.markdown,
      html: $scope.convertMarkdownToHtml($scope.commentData.markdown),
      posted: Date.now()
    }, function (response) {
      loadComments();
    });
  }

  $scope.quoteComment = function (comment) {
    $scope.commentData.markdown = "> **" + comment.member + " said:**\n> " + comment.markdown.split("\n").join("\n> ") + "\n";
  };

  $scope.deleteComment = function (comment) {
    CommentFactory.Comment.delete({id: comment._id}, function () {
      loadComments();
    });
  };

  $scope.getMember = function (memberId) {
    return $scope.members.filter(function(o) {
      return o.id == memberId;
    })[0];
  };

  $scope.convertTextToHtml = function(text) {
    var urlExp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var mailExp = /[\w\.\-]+\@([\w\-]+\.)+[\w]{2,4}(?![^<]*>)/ig;

    return text.replace(/\n/g, '
').replace(urlExp,"$1").replace(mailExp,"$&");
  };

  $scope.convertNewLinesToHtml = function(text) {
    return '
'+text.replace(/\n/g, '
')+'
';
  };

  $scope.convertMarkdownToHtml = function(text) {
    return '
' + text + '
';
  };

  $scope.timeSince =function (date) {
    date = new Date(date);
    var seconds = Math.floor((Date.now() - date) / 1000);

    var suffix = 'ago';
    if(seconds < 0){
      seconds = Math.abs(seconds);
      suffix = 'to go';
    }

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
        return interval + " years " + suffix;
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + " months " + suffix;
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + " days " + suffix;
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + " hours " + suffix;
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + " minutes " + suffix;
    }
    return Math.floor(seconds) + " seconds " + suffix;
  };

});
<commit_msg>markdown is derpy<commit_after>"use strict";

theToolController.controller("CommentAreaController", function ($scope, $http, $routeParams, MemberFactory, CommentFactory) {

  $scope.loading = true;

  $scope.commentData = {
    markdown: ""
  };

  MemberFactory.Member.get({id: "me"}, function (me) {
    $scope.me = me;
  });

  MemberFactory.Member.getAll(function (members) {
    $scope.members = members;
  });

  loadComments();

  function loadComments() {
    $scope.loading = true;

    if ($scope.thread.indexOf("company-") != -1) {
      CommentFactory.Company.getAll({id: $scope.thread.split("-")[1]}, gotComments);
    }
    else if ($scope.thread.indexOf("speaker-") != -1) {
      CommentFactory.Speaker.getAll({id: $scope.thread.split("-")[1]}, gotComments);
    }

    function gotComments(comments) {
      $scope.comments = comments;

      $scope.loading = false;
    }
  }

  $scope.postComment = function () {
    if ($scope.commentData.markdown === ""){
      $scope.emptyComment = true;
      return;
    }

    CommentFactory.Comment.create({
      thread: $scope.thread,
      member: $scope.me.id,
      markdown: $scope.commentData.markdown,
      html: $scope.convertMarkdownToHtml($scope.commentData.markdown),
      posted: Date.now()
    }, function (response) {
      loadComments();
    });
  }

  $scope.quoteComment = function (comment) {
    $scope.commentData.markdown = "> **" + $scope.getMember(comment.member).name + " said:**\n> " + comment.markdown.split("\n").join("\n> ") + "\n\n";
  };

  $scope.deleteComment = function (comment) {
    CommentFactory.Comment.delete({id: comment._id}, function () {
      loadComments();
    });
  };

  $scope.getMember = function (memberId) {
    return $scope.members.filter(function(o) {
      return o.id == memberId;
    })[0];
  };

  $scope.convertTextToHtml = function(text) {
    var urlExp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var mailExp = /[\w\.\-]+\@([\w\-]+\.)+[\w]{2,4}(?![^<]*>)/ig;

    return text.replace(/\n/g, '
').replace(urlExp,"$1").replace(mailExp,"$&");
  };

  $scope.convertNewLinesToHtml = function(text) {
    return '
'+text.replace(/\n/g, '
')+'
';
  };

  $scope.convertMarkdownToHtml = function(text) {
    return '
' + text + '
';
  };

  $scope.timeSince =function (date) {
    date = new Date(date);
    var seconds = Math.floor((Date.now() - date) / 1000);

    var suffix = 'ago';
    if(seconds < 0){
      seconds = Math.abs(seconds);
      suffix = 'to go';
    }

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
        return interval + " years " + suffix;
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + " months " + suffix;
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + " days " + suffix;
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + " hours " + suffix;
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + " minutes " + suffix;
    }
    return Math.floor(seconds) + " seconds " + suffix;
  };

});
<|endoftext|>


<commit_before>/*! ssrtojson 21-11-2014 12:50 */
var SSRSearch=function(){"use strict";function a(a){var b=typeof a;return"function"===b||"object"===b&&!!a}function b(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push(b+"="+a[b]);return c.join("&")}function c(a){var b=a.split(",");return{ostLL:b[0],nordLL:b[1],ostUR:b[2],nordUR:b[3]}}function d(a,b){var c,d={};for(c in a)a.hasOwnProperty(c)&&(d[c]=a[c]);for(c in b)b.hasOwnProperty(c)&&(d[c]=b[c]);return d}var e=Function.prototype.bind,f=Array.prototype.slice,g=function(){},h=function(b,c){var d,h;return e&&b.bind===e?e.apply(b,f.call(arguments,1)):(d=f.call(arguments,2),h=function(){if(!(this instanceof h))return b.apply(c,d.concat(f.call(arguments)));g.prototype=b.prototype;var e=new g;g.prototype=null;var i=b.apply(e,d.concat(f.call(arguments)));return a(i)?i:e})},i=function(a){function b(a,b){var c=new DOMParser,d=c.parseFromString(a,"text/xml");return d.getElementsByTagName(b)[0]}function c(a,b){var c,d=[],e=a.childNodes,f=e.length;for(c=0;f>c;c++)e[c].nodeName===b&&d.push(e[c]);return d}function d(a,b){var c,d=a,e=b.length;for(c=0;e>c;c++)d=d.getElementsByTagName(b[c])[0];try{return d.childNodes[0].nodeValue}catch(f){return null}}function e(a){var b,c,e={},f=["ssrId","navnetype","kommunenavn","fylkesnavn","stedsnavn","aust","nord","skrivemaatestatus","spraak","skrivemaatenavn","epsgKode"],g=f.length,h={};for(c=0;g>c;c++)b=f[c],"nord"===b?h.lat=parseFloat(d(a,[b])):"aust"===b?h.lon=parseFloat(d(a,[b])):e[b]=d(a,[b]);return e.position=h,e}function f(a){var b=a.position;return delete a.position,{type:"Feature",geometry:{type:"Point",coordinates:[b.lon,b.lat]},properties:a}}function g(a){var b,c={type:"FeatureCollection",features:[]},d=a.length;for(b=0;d>b;b++)c.features.push(f(a[b]));return c}function h(a){var b,d=c(a,"stedsnavn"),f=[],g=d.length;for(b=0;g>b;b++)f.push(e(d[b]));return f}var i=b(a,"sokRes"),j="true"===d(i,["sokStatus","ok"]),k=d(i,["sokStatus","melding"]),l=parseInt(d(i,["totaltAntallTreff"]),10),m=h(i);return{sokStatus:{ok:j,melding:k},totaltAntallTreff:l,stedsnavn:m,geoJson:g(m)}},j=function(){this.isIE8=window.XDomainRequest?!0:!1};j.prototype.createRequest=function(){return this.isIE8?new window.XDomainRequest:new XMLHttpRequest},j.prototype.get=function(a,b,c){this.request=this.createRequest(),this.error=c,this.success=b,this.isIE8?(this.request.onload=h(this.handler,this),this.request.open("GET",a,!0),this.request.send()):(this.request.open("GET",a,!0),this.request.onreadystatechange=h(this.handler,this),this.request.send())},j.prototype.handler=function(){4===this.request.readyState&&(200===this.request.status?this.success(this.request.responseText):this.error(this.request.responseText))};var k=function(){this.corsRequest=new j,this.baseUrl="https://ws.geonorge.no/SKWS3Index/ssr/sok"};k.prototype.createUrl=function(a){a=d({page:0,maxRows:9,epsg:4258},a);var e={navn:a.query,antPerSide:a.maxRows,epsgKode:a.epsg,eksakteForst:"true",side:a.page};return a.bbox&&(e=d(e,c(a.bbox))),this.baseUrl+"?"+b(e)},k.prototype.search=function(a,b,c){this.orgSuccess=b,this.corsRequest.get(this.createUrl(a),h(this.success,this),c)},k.prototype.success=function(a){this.orgSuccess(i(a))};var l=new k;return{search:function(a,b,c){l.search(a,b,c)}}};<commit_msg>Build for<commit_after>/*! ssrtojson 21-11-2014 12:52 */
var SSRSearch=function(){"use strict";function a(a){var b=typeof a;return"function"===b||"object"===b&&!!a}function b(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push(b+"="+a[b]);return c.join("&")}function c(a){var b=a.split(",");return{ostLL:b[0],nordLL:b[1],ostUR:b[2],nordUR:b[3]}}function d(a,b){var c,d={};for(c in a)a.hasOwnProperty(c)&&(d[c]=a[c]);for(c in b)b.hasOwnProperty(c)&&(d[c]=b[c]);return d}var e=Function.prototype.bind,f=Array.prototype.slice,g=function(){},h=function(b,c){var d,h;return e&&b.bind===e?e.apply(b,f.call(arguments,1)):(d=f.call(arguments,2),h=function(){if(!(this instanceof h))return b.apply(c,d.concat(f.call(arguments)));g.prototype=b.prototype;var e=new g;g.prototype=null;var i=b.apply(e,d.concat(f.call(arguments)));return a(i)?i:e})},i=function(a){function b(a,b){var c=new DOMParser,d=c.parseFromString(a,"text/xml");return d.getElementsByTagName(b)[0]}function c(a,b){var c,d=[],e=a.childNodes,f=e.length;for(c=0;f>c;c++)e[c].nodeName===b&&d.push(e[c]);return d}function d(a,b){var c,d=a,e=b.length;for(c=0;e>c;c++)d=d.getElementsByTagName(b[c])[0];try{return d.childNodes[0].nodeValue}catch(f){return null}}function e(a){var b,c,e={},f=["ssrId","navnetype","kommunenavn","fylkesnavn","stedsnavn","aust","nord","skrivemaatestatus","spraak","skrivemaatenavn","epsgKode"],g=f.length,h={};for(c=0;g>c;c++)b=f[c],"nord"===b?h.lat=parseFloat(d(a,[b])):"aust"===b?h.lon=parseFloat(d(a,[b])):e[b]=d(a,[b]);return e.position=h,e}function f(a){var b=a.position;return delete a.position,{type:"Feature",geometry:{type:"Point",coordinates:[b.lon,b.lat]},properties:a}}function g(a){var b,c={type:"FeatureCollection",features:[]},d=a.length;for(b=0;d>b;b++)c.features.push(f(a[b]));return c}function h(a){var b,d=c(a,"stedsnavn"),f=[],g=d.length;for(b=0;g>b;b++)f.push(e(d[b]));return f}var i=b(a,"sokRes"),j="true"===d(i,["sokStatus","ok"]),k=d(i,["sokStatus","melding"]),l=parseInt(d(i,["totaltAntallTreff"]),10),m=h(i);return{sokStatus:{ok:j,melding:k},totaltAntallTreff:l,stedsnavn:m,geoJson:g(m)}},j=function(){this.isIE8=window.XDomainRequest?!0:!1};j.prototype.createRequest=function(){return this.isIE8?new window.XDomainRequest:new XMLHttpRequest},j.prototype.get=function(a,b,c){this.request=this.createRequest(),this.error=c,this.success=b,this.isIE8?(this.request.onload=h(this.handler,this),this.request.open("GET",a,!0),this.request.send()):(this.request.open("GET",a,!0),this.request.onreadystatechange=h(this.handler,this),this.request.send())},j.prototype.handler=function(){4===this.request.readyState&&(200===this.request.status?this.success(this.request.responseText):this.error(this.request.responseText))};var k=function(){this.corsRequest=new j,this.baseUrl="https://ws.geonorge.no/SKWS3Index/ssr/sok"};k.prototype.createUrl=function(a){a=d({page:0,maxRows:9,epsg:4258},a);var e={navn:a.query,antPerSide:a.maxRows,epsgKode:a.epsg,eksakteForst:"true",side:a.page};return a.bbox&&(e=d(e,c(a.bbox))),this.baseUrl+"?"+b(e)},k.prototype.search=function(a,b,c){this.orgSuccess=b,this.corsRequest.get(this.createUrl(a),h(this.success,this),c)},k.prototype.success=function(a){this.orgSuccess(i(a))};var l=new k;return{search:function(a,b,c){l.search(a,b,c)}}};<|endoftext|>


<commit_before>module.exports = function(grunt) {
    var browsers = [{
        browserName: "firefox",
        version: "19",
        platform: "XP"
    }, {
        browserName: "chrome",
        platform: "XP"
    }, {
        browserName: "chrome",
        platform: "linux"
    }, {
        browserName: "internet explorer",
        platform: "WIN8",
        version: "11"
    }, {
        browserName: "internet explorer",
        platform: "WIN8",
        version: "10"
    }, {
        browserName: "internet explorer",
        platform: "VISTA",
        version: "9"
    }, {
        browserName: "internet explorer",
        platform: "VISTA",
        version: "8"
    }];

    grunt.initConfig({
        connect: {
            server: {
                options: {
                    base: "",
                    hostname: "",
                    port: 9999
                }
            }
        },
        'saucelabs-jasmine': {
            all: {
                options: {
                    urls: ["http://127.0.0.1:9999/spec/index.html"],
                    tunnelTimeout: 5,
                    build: process.env.TRAVIS_JOB_ID,
                    concurrency: 3,
                    browsers: browsers,
                    testname: "jasmine tests"
                }
            }
        },
        watch: {}
    });

    // Loading dependencies
    for (var key in grunt.file.readJSON("package.json").devDependencies) {
        if (key !== "grunt" && key.indexOf("grunt") === 0) grunt.loadNpmTasks(key);
    }

    grunt.registerTask("serve", ["connect", "watch"]);
    grunt.registerTask("saucelabs-test", ["connect", "saucelabs-jasmine"]);
};
<commit_msg>adding project name to saucelabs id and fixing bad browser definition<commit_after>module.exports = function(grunt) {
    var browsers = [{
        browserName: "firefox",
        version: "19",
        platform: "XP"
    }, {
        browserName: "chrome",
        platform: "XP"
    }, {
        browserName: "chrome",
        platform: "linux"
    }, {
        browserName: "internet explorer",
        platform: "WIN8.1",
        version: "11"
    }, {
        browserName: "internet explorer",
        platform: "WIN8",
        version: "10"
    }, {
        browserName: "internet explorer",
        platform: "VISTA",
        version: "9"
    }, {
        browserName: "internet explorer",
        platform: "VISTA",
        version: "8"
    }];

    grunt.initConfig({
        connect: {
            server: {
                options: {
                    base: "",
                    hostname: "",
                    port: 9999
                }
            }
        },
        'saucelabs-jasmine': {
            all: {
                options: {
                    urls: ["http://127.0.0.1:9999/spec/index.html"],
                    tunnelTimeout: 5,
                    build: process.env.TRAVIS_JOB_ID,
                    concurrency: 3,
                    browsers: browsers,
                    testname: "topiarist tests"
                }
            }
        },
        watch: {}
    });

    // Loading dependencies
    for (var key in grunt.file.readJSON("package.json").devDependencies) {
        if (key !== "grunt" && key.indexOf("grunt") === 0) grunt.loadNpmTasks(key);
    }

    grunt.registerTask("serve", ["connect", "watch"]);
    grunt.registerTask("saucelabs-test", ["connect", "saucelabs-jasmine"]);
};
<|endoftext|>


<commit_before>var config = require('config');
var FeedbackModal = require('feedback-modal');
var FilterView = require('filter-view');
var HelpMeChoose = require('help-me-choose-view');
var LeafletTransitiveLayer = require('Leaflet.TransitiveLayer');
var LocationsView = require('locations-view');
var log = require('./client/log')('planner-page');
var showMapView = require('map-view');
var OptionsView = require('options-view');
var PlannerNav = require('planner-nav');
var querystring = require('querystring');
var scrollbarSize = require('scrollbar-size');
var scrolling = require('scrolling');
var session = require('session');
var textModal = require('text-modal');
var transitive = require('transitive');
var ua = require('user-agent');
var view = require('view');
var showWelcomeWizard = require('welcome-flow');
var showPlannerWalkthrough = require('planner-walkthrough');
var geocode = require('geocode');

var FROM = config.geocode().start_address;
var TO = config.geocode().end_address;
var isMobile = window.innerWidth <= 480;
var center = config.geocode().center.split(',').map(parseFloat);

var View = view(require('./template.html'), function(view, model) {
  view.scrollable = view.find('.scrollable');
  view.panelFooter = view.find('.footer');

  if (scrollbarSize > 0) {
    if (ua.os.name === 'Windows' || ua.browser.name !== 'Chrome')
      view.scrollable.style.marginRight = -scrollbarSize + 'px';

    // Scrollbars are fun and implemented the same on every OS/Browser...right
    if (ua.os.name === 'Windows' && ua.browser.name === 'Chrome')
      view.scrollable.style.paddingRight = scrollbarSize + 'px';
  }
});

/**
 * Expose `render`
 */

module.exports = function(ctx, next) {
  log('render');

  var plan = ctx.plan;
  var query = querystring.parse(window.location.search);

  // Set up the views
  var views = {
    'filter-view': new FilterView(plan),
    'locations-view': new LocationsView(plan),
    'options-view': new OptionsView(plan),
    'planner-nav': new PlannerNav(session)
  };

  ctx.view = new View(views);
  ctx.view.on('rendered', function() {
    // Set plan to loading
    plan.loading(true);

    for (var key in views) {
      views[key].emit('rendered', views[key]);
    }

    // Show the map
    var map = showMapView(ctx.view.find('.MapView'));

    // Create the transitive layer
    var transitiveLayer = new LeafletTransitiveLayer(transitive);

    // Set the transitive layer
    map.addLayer(transitiveLayer);

    // Update map on plan change
    updateMapOnPlanChange(plan, map, transitive, transitiveLayer);

    /*
    map.on('click', function (e) {
          var from = plan.from_ll();
          var to = plan.to_ll();
          if (!plan.coordinateIsValid(from)) {
            plan.journey({
          places: [
            {
              place_id: 'from',
              place_lat: e.latlng.lat,
              place_lon: e.latlng.lng,
              place_name: 'From'
            },
            {
              place_id: 'to',
              place_lat: (plan.to_ll() ? plan.to_ll().lat : 0),
              place_lon: (plan.to_ll() ? plan.to_ll().lng : 0),
              place_name: 'To'
            }
          ]
        });
        plan.setAddress('from', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
            plan.updateRoutes();
        });
          } else if (!plan.coordinateIsValid(to)) {
        plan.journey({
          places: [
            {
              place_id: 'from',
              place_lat: plan.from_ll().lat,
              place_lon: plan.from_ll().lng,
              place_name: 'From'
            },
            {
              place_id: 'to',
              place_lat: e.latlng.lat,
              place_lon: e.latlng.lng,
              place_name: 'To'
            }
          ]
        });
        plan.setAddress('to', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
            plan.updateRoutes();
        });
          }
    });
    */

    // Clear plan & cookies for now, plan will re-save automatically on save
      var from = plan.from_ll();
      var to = plan.to_ll();
      plan.clearStore();

    // If it's a shared URL or welcome is complete skip the welcome screen
    if ((query.from && query.to)) {
      showQuery(query);
    } else {
      if (plan.coordinateIsValid(from) && plan.coordinateIsValid(to)) {
	plan.setAddresses(
	  from.lng + ',' + from.lat, // from
	  to.lng + ',' + to.lat, // to
	  function (err, res) {
	    plan.updateRoutes();
	    console.log("aqui la data del plan 4 ->", plan.dataplan);
	  }
	);
        plan.updateRoutes();
        console.log("aqui la data del plan 3 ->", plan.dataplan);
      } else {
	  console.log(from);
	  console.log(to);
	plan.loading(false);
      }
    }
  });

  plan.on('updating options', function() {
    ctx.view.panelFooter.classList.add('hidden');
  });

  plan.on('updating options complete', function(res) {
    if (res && !res.err) ctx.view.panelFooter.classList.remove('hidden');
  });

  next();
};

/**
 * Reverse Commute
 */

View.prototype.reverseCommute = function(e) {
  e.preventDefault();
  var plan = session.plan();
  plan.set({
    from: plan.to(),
    from_id: plan.to_id(),
    from_ll: plan.to_ll(),
    to: plan.from(),
    to_id: plan.from_id(),
    to_ll: plan.from_ll()
  });

  plan.updateRoutes();

  console.log("aqui la data del plan 5 ->", plan.dataplan);
};

/**
 * Scroll
 */

View.prototype.scroll = function(e) {
  e.preventDefault();
  this.scrollable.scrollTop += (this.scrollable.scrollHeight / 5);
};

/**
 * On submit
 */

View.prototype.onsubmit = function(e) {
  e.preventDefault();
};

/**
 * Help Me Choose
 */

View.prototype.helpMeChoose = function(e) {
  HelpMeChoose(session.plan().options()).show();
};

/**
 * Show feedback modal
 */
View.prototype.feedback = function(e) {
  e.preventDefault();
  FeedbackModal().show();
};

/**
 * Hide Side Panel
 */

View.prototype.hideSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(' + width + 'px, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding': '0'
  });

  setTimeout(function () {
    map.invalidateSize();
  }, 2100)
};

/**
 * Show Side Panel
 */

View.prototype.showSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(0, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding-right': '320px'
  });

  setTimeout(function () {
    var plan = session.plan();
    map.invalidateSize();

    plan = session.plan();
//    plan.updateRoutes();
    transitive.updateData(plan.journey());
  }, 2100)
};

/**
 * Show Journey
 */

function showQuery(query) {
  var plan = session.plan();
  // If no querystring, see if we have them in the plan already
  var from = query.from || plan.from() || FROM;
  var to = query.to || plan.to() || TO;
  var sameAddresses = from === plan.from() && to === plan.to();

  // Set plan from querystring
  if (query.modes) plan.setModes(query.modes);
  if (query.start_time !== undefined) plan.start_time(parseInt(query.start_time, 10));
  if (query.end_time !== undefined) plan.end_time(parseInt(query.end_time, 10));
  if (query.days !== undefined) plan.days(query.days);

  // If has valid coordinates, load
  if (plan.validCoordinates() && sameAddresses) {
    plan.journey({
      places: plan.generatePlaces()
    });
    plan.updateRoutes();

    console.log("aqui la data del plan 1 ->", plan.dataplan);
  } else {
      if (!plan.validCoordinates()) {
	  plan.loading(false);
	  return;
      } else {
    // Set addresses and update the routes
    plan.setAddresses(from, to, function(err) {
      if (err) {
        log.error('%e', err);
      } else {
        plan.journey({
          places: plan.generatePlaces()
        });
        plan.updateRoutes();

        console.log("aqui la data del plan 2 ->", plan.dataplan);
      }
    });
}
  }
}

/**
 * Update Map on plan change
 */

function updateMapOnPlanChange(plan, map, transitive, transitiveLayer) {
  // Register plan update events

  plan.on('change journey', function(journey) {

    if (journey && !isMobile) {
      try {
        console.log("aqui la data del plan 7 ->", plan.dataplan);
        log('updating data');

        var datajourney = journey;
        if (!(plan.dataplan === undefined)) {
            showMapView.cleanRoute();
            var itineraries = plan.dataplan;
            for (i = 0; i < itineraries.length; i++) {
                for (ii=0; ii < itineraries[i].legs.length; ii++) {

                        console.log("jalan los codigos",  itineraries[i].legs[ii].legGeometry.points);
                        showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points);
                }
            }

        }

        /*
        if (!(datajourney.streetEdges === undefined)) {
            console.log("data journey 2" , datajourney.streetEdges);
            for (i = 0; i < datajourney.streetEdges.length; i++) {
                console.log("data data 7 -> ", datajourney.streetEdges[i].geometry.points);

                showMapView.drawRouteAmigo(datajourney.streetEdges[i].geometry.points);
            }
            //geometry.points
        }
        */
        //transitive.updateData(journey);
        //map.fitBounds(transitiveLayer.getBounds());
      } catch (e) {
	    map.setView([center[1], center[0]], config.geocode().zoom);
      }
    }
  });
}
<commit_msg>adding console<commit_after>var config = require('config');
var FeedbackModal = require('feedback-modal');
var FilterView = require('filter-view');
var HelpMeChoose = require('help-me-choose-view');
var LeafletTransitiveLayer = require('Leaflet.TransitiveLayer');
var LocationsView = require('locations-view');
var log = require('./client/log')('planner-page');
var showMapView = require('map-view');
var OptionsView = require('options-view');
var PlannerNav = require('planner-nav');
var querystring = require('querystring');
var scrollbarSize = require('scrollbar-size');
var scrolling = require('scrolling');
var session = require('session');
var textModal = require('text-modal');
var transitive = require('transitive');
var ua = require('user-agent');
var view = require('view');
var showWelcomeWizard = require('welcome-flow');
var showPlannerWalkthrough = require('planner-walkthrough');
var geocode = require('geocode');

var FROM = config.geocode().start_address;
var TO = config.geocode().end_address;
var isMobile = window.innerWidth <= 480;
var center = config.geocode().center.split(',').map(parseFloat);

var View = view(require('./template.html'), function(view, model) {
  view.scrollable = view.find('.scrollable');
  view.panelFooter = view.find('.footer');

  if (scrollbarSize > 0) {
    if (ua.os.name === 'Windows' || ua.browser.name !== 'Chrome')
      view.scrollable.style.marginRight = -scrollbarSize + 'px';

    // Scrollbars are fun and implemented the same on every OS/Browser...right
    if (ua.os.name === 'Windows' && ua.browser.name === 'Chrome')
      view.scrollable.style.paddingRight = scrollbarSize + 'px';
  }
});

/**
 * Expose `render`
 */

module.exports = function(ctx, next) {
  log('render');

  var plan = ctx.plan;
  var query = querystring.parse(window.location.search);

  // Set up the views
  var views = {
    'filter-view': new FilterView(plan),
    'locations-view': new LocationsView(plan),
    'options-view': new OptionsView(plan),
    'planner-nav': new PlannerNav(session)
  };

  ctx.view = new View(views);
  ctx.view.on('rendered', function() {
    // Set plan to loading
    plan.loading(true);

    for (var key in views) {
      views[key].emit('rendered', views[key]);
    }

    // Show the map
    var map = showMapView(ctx.view.find('.MapView'));

    // Create the transitive layer
    var transitiveLayer = new LeafletTransitiveLayer(transitive);

    // Set the transitive layer
    map.addLayer(transitiveLayer);

    // Update map on plan change
    updateMapOnPlanChange(plan, map, transitive, transitiveLayer);

    /*
    map.on('click', function (e) {
          var from = plan.from_ll();
          var to = plan.to_ll();
          if (!plan.coordinateIsValid(from)) {
            plan.journey({
          places: [
            {
              place_id: 'from',
              place_lat: e.latlng.lat,
              place_lon: e.latlng.lng,
              place_name: 'From'
            },
            {
              place_id: 'to',
              place_lat: (plan.to_ll() ? plan.to_ll().lat : 0),
              place_lon: (plan.to_ll() ? plan.to_ll().lng : 0),
              place_name: 'To'
            }
          ]
        });
        plan.setAddress('from', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
            plan.updateRoutes();
        });
          } else if (!plan.coordinateIsValid(to)) {
        plan.journey({
          places: [
            {
              place_id: 'from',
              place_lat: plan.from_ll().lat,
              place_lon: plan.from_ll().lng,
              place_name: 'From'
            },
            {
              place_id: 'to',
              place_lat: e.latlng.lat,
              place_lon: e.latlng.lng,
              place_name: 'To'
            }
          ]
        });
        plan.setAddress('to', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
            plan.updateRoutes();
        });
          }
    });
    */

    // Clear plan & cookies for now, plan will re-save automatically on save
      var from = plan.from_ll();
      var to = plan.to_ll();
      plan.clearStore();

    // If it's a shared URL or welcome is complete skip the welcome screen
    if ((query.from && query.to)) {
      showQuery(query);
    } else {
      if (plan.coordinateIsValid(from) && plan.coordinateIsValid(to)) {
	plan.setAddresses(
	  from.lng + ',' + from.lat, // from
	  to.lng + ',' + to.lat, // to
	  function (err, res) {
	    plan.updateRoutes();
	    console.log("aqui la data del plan 4 ->", plan.dataplan);
	  }
	);
        plan.updateRoutes();
        console.log("aqui la data del plan 3 ->", plan.dataplan);
      } else {
	  console.log(from);
	  console.log(to);
	plan.loading(false);
      }
    }
  });

  plan.on('updating options', function() {
    ctx.view.panelFooter.classList.add('hidden');
  });

  plan.on('updating options complete', function(res) {
    if (res && !res.err) ctx.view.panelFooter.classList.remove('hidden');
  });

  next();
};

/**
 * Reverse Commute
 */

View.prototype.reverseCommute = function(e) {
  e.preventDefault();
  var plan = session.plan();
  plan.set({
    from: plan.to(),
    from_id: plan.to_id(),
    from_ll: plan.to_ll(),
    to: plan.from(),
    to_id: plan.from_id(),
    to_ll: plan.from_ll()
  });

  plan.updateRoutes();

  console.log("aqui la data del plan 5 ->", plan.dataplan);
};

/**
 * Scroll
 */

View.prototype.scroll = function(e) {
  e.preventDefault();
  this.scrollable.scrollTop += (this.scrollable.scrollHeight / 5);
};

/**
 * On submit
 */

View.prototype.onsubmit = function(e) {
  e.preventDefault();
};

/**
 * Help Me Choose
 */

View.prototype.helpMeChoose = function(e) {
  HelpMeChoose(session.plan().options()).show();
};

/**
 * Show feedback modal
 */
View.prototype.feedback = function(e) {
  e.preventDefault();
  FeedbackModal().show();
};

/**
 * Hide Side Panel
 */

View.prototype.hideSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(' + width + 'px, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding': '0'
  });

  setTimeout(function () {
    map.invalidateSize();
  }, 2100)
};

/**
 * Show Side Panel
 */

View.prototype.showSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(0, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding-right': '320px'
  });

  setTimeout(function () {
    var plan = session.plan();
    map.invalidateSize();

    plan = session.plan();
//    plan.updateRoutes();
    transitive.updateData(plan.journey());
  }, 2100)
};

/**
 * Show Journey
 */

function showQuery(query) {
  var plan = session.plan();
  // If no querystring, see if we have them in the plan already
  var from = query.from || plan.from() || FROM;
  var to = query.to || plan.to() || TO;
  var sameAddresses = from === plan.from() && to === plan.to();

  // Set plan from querystring
  if (query.modes) plan.setModes(query.modes);
  if (query.start_time !== undefined) plan.start_time(parseInt(query.start_time, 10));
  if (query.end_time !== undefined) plan.end_time(parseInt(query.end_time, 10));
  if (query.days !== undefined) plan.days(query.days);

  // If has valid coordinates, load
  if (plan.validCoordinates() && sameAddresses) {
    plan.journey({
      places: plan.generatePlaces()
    });
    plan.updateRoutes();

    console.log("aqui la data del plan 1 ->", plan.dataplan);
  } else {
      if (!plan.validCoordinates()) {
	  plan.loading(false);
	  return;
      } else {
    // Set addresses and update the routes
    plan.setAddresses(from, to, function(err) {
      if (err) {
        log.error('%e', err);
      } else {
        plan.journey({
          places: plan.generatePlaces()
        });
        plan.updateRoutes();

        console.log("aqui la data del plan 2 ->", plan.dataplan);
      }
    });
}
  }
}

/**
 * Update Map on plan change
 */

function updateMapOnPlanChange(plan, map, transitive, transitiveLayer) {
  // Register plan update events

  plan.on('change journey', function(journey) {

    if (journey && !isMobile) {
      try {
        console.log("aqui la data del plan 7 ->", plan.dataplan);
        log('updating data');

        var datajourney = journey;
        if (!(plan.dataplan === undefined)) {
            var itineraries = plan.dataplan;
            for (i = 0; i < itineraries.length; i++) {
                for (ii=0; ii < itineraries[i].legs.length; ii++) {

                        console.log("jalan los codigos",  itineraries[i].legs[ii].legGeometry.points);
                        showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points);
                }
            }

        }

        /*
        if (!(datajourney.streetEdges === undefined)) {
            console.log("data journey 2" , datajourney.streetEdges);
            for (i = 0; i < datajourney.streetEdges.length; i++) {
                console.log("data data 7 -> ", datajourney.streetEdges[i].geometry.points);

                showMapView.drawRouteAmigo(datajourney.streetEdges[i].geometry.points);
            }
            //geometry.points
        }
        */
        //transitive.updateData(journey);
        //map.fitBounds(transitiveLayer.getBounds());
      } catch (e) {
	    map.setView([center[1], center[0]], config.geocode().zoom);
      }
    }
  });
}
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';

import {
  View,
  Navigator,
} from 'react-native';

export default class Scene extends React.Component {
  componentDidMount() {
    const { delegate } = this.props;

    if (delegate) {
      const navigationDelegate = delegate.constructor.navigationDelegate;

      if (navigationDelegate && navigationDelegate.id) {
        const navigationDelegateCopy = Object.assign({}, delegate.constructor.navigationDelegate)

        const navigationContext = delegate.props.navigator.navigationContext;
        const delegateId = delegate.constructor.navigationDelegate.id;

        setTimeout(() => {
          const events = delegate.constructor.navigationDelegate._events;
          navigationDelegateCopy._events = events;

          if (events && events.length) {
            this._events = events.slice();

            events.forEach((eventName) => {
              this[`_${eventName}Sub`] = navigationContext.addListener(
                eventName,
                ({data: {route, e}}) => {
                  delegateId ===
                  route.component.navigationDelegate.id ?
                    (delegate[eventName] ? delegate[eventName](e) : () => {}) :
                    null
                }
              );
            });
          }
        }, 300);

        const delegateUnmountHandler = delegate.componentWillUnmount;

        delegate.componentWillUnmount = () => {
          delegateUnmountHandler && delegateUnmountHandler.bind(delegate)()

          const events = this._events;

          if (events && events.length) {
            events.forEach((eventName) => {
              this[`_${eventName}Sub`].remove();
              this[`_${eventName}Sub`] = null;
            });
          }

          this._events = null;

          // restore here because we might change it by navBar.updateUI etc...
          delegate.constructor.navigationDelegate = navigationDelegateCopy;
        }
      }
    }
  }

  render() {
    return (
      <View
        style={[
          {
            flex: 1,
            paddingTop: this.props.paddingTop ?
              Scene.navBarHeight :
              0,
          },
          this.props.style,
        ]}>
          {this.props.children}
        </View>
    )
  }

  static propTypes = {
    style: View.propTypes.style,
    paddingTop: PropTypes.bool,
    delegate: (props, propName) => {
      if (props[propName] && !(props[propName] instanceof React.Component)) {
        return new Error('Scene delegate should be instance of React.Component');
      }
    },
  };

  static defaultProps = {
    paddingTop: true,
  };

  static navBarHeight = Navigator.NavigationBar.Styles.General.TotalNavHeight;
}
<commit_msg>Added ability to listen scene 'willfocus' and 'didfocus'<commit_after>import React, { PropTypes } from 'react';

import {
  View,
  Navigator,
} from 'react-native';

export default class Scene extends React.Component {
  componentDidMount() {
    const { delegate } = this.props;

    if (delegate) {
      const navigationDelegate = delegate.constructor.navigationDelegate;

      if (navigationDelegate && navigationDelegate.id) {
        const navigationDelegateCopy = Object.assign({}, delegate.constructor.navigationDelegate)

        const navigationContext = delegate.props.navigator.navigationContext;
        const delegateId = delegate.constructor.navigationDelegate.id;

        setTimeout(() => {
          const events = delegate.constructor.navigationDelegate._events;
          navigationDelegateCopy._events = events;

          if (events && events.length) {
            this._events = events.concat(['willfocus', 'didfocus']);

            this._events.forEach((eventName) => {
              this[`_${eventName}Sub`] = navigationContext.addListener(
                eventName,
                ({data: {route, e}}) => {
                  delegateId ===
                  route.component.navigationDelegate.id ?
                    (delegate[eventName] ? delegate[eventName](e) : () => {}) :
                    null
                }
              );
            });
          }
        }, 300);

        const delegateUnmountHandler = delegate.componentWillUnmount;

        delegate.componentWillUnmount = () => {
          delegateUnmountHandler && delegateUnmountHandler.bind(delegate)()

          const events = this._events;

          if (events && events.length) {
            events.forEach((eventName) => {
              this[`_${eventName}Sub`].remove();
              this[`_${eventName}Sub`] = null;
            });
          }

          this._events = null;

          // restore here because we might change it by navBar.updateUI etc...
          delegate.constructor.navigationDelegate = navigationDelegateCopy;
        }
      }
    }
  }

  render() {
    return (
      <View
        style={[
          {
            flex: 1,
            paddingTop: this.props.paddingTop ?
              Scene.navBarHeight :
              0,
          },
          this.props.style,
        ]}>
          {this.props.children}
        </View>
    )
  }

  static propTypes = {
    style: View.propTypes.style,
    paddingTop: PropTypes.bool,
    delegate: (props, propName) => {
      if (props[propName] && !(props[propName] instanceof React.Component)) {
        return new Error('Scene delegate should be instance of React.Component');
      }
    },
  };

  static defaultProps = {
    paddingTop: true,
  };

  static navBarHeight = Navigator.NavigationBar.Styles.General.TotalNavHeight;
}
<|endoftext|>


<commit_before>var command = require('../command');

var DEFAULT_TIMEOUT_SECONDS = 60;

function pathToMessageType(path) {
  return path
           .split('?')[0]
           .replace(/\/+$/, '')
           .replace(/\/+/g, '.');
}

module.exports = {
  'droonga-get': new command.HTTPRequestResponse({
    method:    'GET',
    path:      /^\/droonga\/(.+)/,
    onRequest: function(request, connection) {
      var messageType = pathToMessageType(request.params[0]);
      var body = {};
      body.timeout = body.timeout || request.query.timeout || DEFAULT_TIMEOUT_SECONDS;
      connection.emit(messageType, body);
    }
  }),
  // XXX dangerous! this must be disabled on public services.
  'droonga-post': new command.HTTPRequestResponse({
    method:    'POST',
    path:      /^\/droonga\/(.+)/,
    onRequest: function(request, connection) {
      var messageType = pathToMessageType(request.params[0]);
      var body = '';
      request.on('data', function(chunk) {
        body += chunk;
      });
      request.on('end', function() {
        body = JSON.parse(body);
        body.timeout = body.timeout || request.query.timeout || DEFAULT_TIMEOUT_SECONDS;
        body.type = body.type || 'droonga-' + messageType;
        connection.emit(messageType, body);
      });
    }
  }),
  'droonga-streaming:watch': new command.HTTPStreaming({
    dataset:            'Watch',
    path:               '/droonga-streaming/watch',
    method:             'GET',
    subscription:       'watch.subscribe',
    unsubscription:     'watch.unsubscribe',
    messageType:        'watch.publish',
    createSubscription: function(request) {
      return {
        condition: request.query.condition
      };
    },
    translate:          function(message) {
      return message;
    }
  })
};
<commit_msg>Remove duplicated definition of default timeout seconds.<commit_after>var command = require('../command');

function pathToMessageType(path) {
  return path
           .split('?')[0]
           .replace(/\/+$/, '')
           .replace(/\/+/g, '.');
}

module.exports = {
  'droonga-get': new command.HTTPRequestResponse({
    method:    'GET',
    path:      /^\/droonga\/(.+)/,
    onRequest: function(request, connection) {
      var messageType = pathToMessageType(request.params[0]);
      var body = {};
      body.timeout = body.timeout || request.query.timeout;
      connection.emit(messageType, body);
    }
  }),
  // XXX dangerous! this must be disabled on public services.
  'droonga-post': new command.HTTPRequestResponse({
    method:    'POST',
    path:      /^\/droonga\/(.+)/,
    onRequest: function(request, connection) {
      var messageType = pathToMessageType(request.params[0]);
      var body = '';
      request.on('data', function(chunk) {
        body += chunk;
      });
      request.on('end', function() {
        body = JSON.parse(body);
        body.timeout = body.timeout || request.query.timeout;
        body.type = body.type || 'droonga-' + messageType;
        connection.emit(messageType, body);
      });
    }
  }),
  'droonga-streaming:watch': new command.HTTPStreaming({
    dataset:            'Watch',
    path:               '/droonga-streaming/watch',
    method:             'GET',
    subscription:       'watch.subscribe',
    unsubscription:     'watch.unsubscribe',
    messageType:        'watch.publish',
    createSubscription: function(request) {
      return {
        condition: request.query.condition
      };
    },
    translate:          function(message) {
      return message;
    }
  })
};
<|endoftext|>


<commit_before>function onload()
{
  document.getElementById("header").innerHTML =
    "
 Budgie Blog
" +
    "
" +
      "Life with Apollo the Budgerigar" +
    "
"
    ;

  document.getElementById("contentList").innerHTML =
    "
 Table of Contents!!!
" +
    "
" +
      "
 Home
" +
    "
" +
    "
" +
      "
 Why I got a budgie
" +
    "
" +
    "
" +
      "
 Alex the Parrot
" +
    "
" +
    "
" +
      "
 Choosing Apollo
" +
    "
" +
    "
" +
      "
 Cage, toys, and perches
" +
    "
" +
    "
" +
      "
 Food and poop
" +
    "
" +
    "
" +
      "
 Taming and training
"
    "
"
    ;
}
<commit_msg>removed test<commit_after>function onload()
{
  document.getElementById("header").innerHTML =
    "
 Budgie Blog
" +
    "
" +
      "Life with Apollo the Budgerigar" +
    "
"
    ;

  document.getElementById("contentList").innerHTML =
    "
 Table of Contents
" +
    "
" +
      "
 Home
" +
    "
" +
    "
" +
      "
 Why I got a budgie
" +
    "
" +
    "
" +
      "
 Alex the Parrot
" +
    "
" +
    "
" +
      "
 Choosing Apollo
" +
    "
" +
    "
" +
      "
 Cage, toys, and perches
" +
    "
" +
    "
" +
      "
 Food and poop
" +
    "
" +
    "
" +
      "
 Taming and training
"
    "
"
    ;
}
<|endoftext|>


<commit_before>import 'whatwg-fetch';
import auth from 'utils/auth';
/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON from the request
 */
function parseJSON(response) {
  return response.json ? response.json() : response;
}

/**
 * Checks if a network request came back fine, and throws an error if not
 *
 * @param  {object} response   A response from a network request
 *
 * @return {object|undefined} Returns either the response, or throws an error
 */
function checkStatus(response, checkToken = true) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  if (response.status === 401 && auth.getToken() && checkToken) {
    return checkTokenValidity(response);
  }

  return parseJSON(response).then(responseFormatted => {
    const error = new Error(response.statusText);
    error.response = response;
    error.response.payload = responseFormatted;
    throw error;
  });
}

function checkTokenValidity(response) {
  const options = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${auth.getToken()}`,
    },
  };

  if (auth.getToken()) {
    return fetch(`${strapi.backendURL}/user/me`, options)
    .then(resp => {
      if (response.status === 401) {
        const { origin } = window.location;
        window.location = `${origin}/admin/plugins/users-permissions/auth/login`;

        auth.clearAppStorage();
      }

      return checkStatus(response, false);
    });
  }
}

/**
 * Format query params
 *
 * @param params
 * @returns {string}
 */
function formatQueryParams(params) {
  return Object.keys(params)
    .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
    .join('&');
}

/**
* Server restart watcher
* @param response
* @returns {object} the response data
*/
function serverRestartWatcher(response) {
  return new Promise((resolve, reject) => {
    fetch(`${strapi.backendURL}/_health`, {
      method: 'HEAD',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json',
        'Keep-Alive': false
      }
    })
      .then(() => {
        resolve(response);
      })
      .catch(err => {
        setTimeout(() => {
          return serverRestartWatcher(response)
            .then(resolve);
        }, 100);
      });
  });
}

/**
 * Requests a URL, returning a promise
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 *
 * @return {object}           The response data
 */
export default function request(url, options = {}, shouldWatchServerRestart = false) {
 // Set headers
  if (!options.headers) {
    options.headers = Object.assign({
      'Content-Type': 'application/json',
    }, options.headers, {
      'X-Forwarded-Host': 'strapi',
    });
  }

  const token = auth.getToken();

  if (token) {
    options.headers = Object.assign({
      'Authorization': `Bearer ${token}`,
    }, options.headers);
  }

  // Add parameters to url
  url = _.startsWith(url, '/') ? `${strapi.backendURL}${url}` : url;

  if (options && options.params) {
    const params = formatQueryParams(options.params);
    url = `${url}?${params}`;
  }

  // Stringify body object
  if (options && options.body) {
    options.body = JSON.stringify(options.body);
  }

  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then((response) => {
      if (shouldWatchServerRestart) {
        return serverRestartWatcher(response);
      }

      return response;
  });
}
<commit_msg>Update branch Merge branch 'master' of https://github.com/strapi/strapi into add-overlay-blocker<commit_after>import 'whatwg-fetch';
import auth from 'utils/auth';
/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON from the request
 */
function parseJSON(response) {
  return response.json ? response.json() : response;
}

/**
 * Checks if a network request came back fine, and throws an error if not
 *
 * @param  {object} response   A response from a network request
 *
 * @return {object|undefined} Returns either the response, or throws an error
 */
function checkStatus(response, checkToken = true) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  if (response.status === 401 && auth.getToken() && checkToken) {
    return checkTokenValidity(response);
  }

  return parseJSON(response).then(responseFormatted => {
    const error = new Error(response.statusText);
    error.response = response;
    error.response.payload = responseFormatted;
    throw error;
  });
}

function checkTokenValidity(response) {
  const options = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${auth.getToken()}`,
    },
  };

  if (auth.getToken()) {
    return fetch(`${strapi.backendURL}/user/me`, options)
    .then(resp => {
      if (response.status === 401) {
        window.location = `${strapi.remoteURL}/plugins/users-permissions/auth/login`;

        auth.clearAppStorage();
      }

      return checkStatus(response, false);
    });
  }
}

/**
 * Format query params
 *
 * @param params
 * @returns {string}
 */
function formatQueryParams(params) {
  return Object.keys(params)
    .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
    .join('&');
}

/**
* Server restart watcher
* @param response
* @returns {object} the response data
*/
function serverRestartWatcher(response) {
  return new Promise((resolve, reject) => {
    fetch(`${strapi.backendURL}/_health`, {
      method: 'HEAD',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json',
        'Keep-Alive': false
      }
    })
      .then(() => {
        resolve(response);
      })
      .catch(err => {
        setTimeout(() => {
          return serverRestartWatcher(response)
            .then(resolve);
        }, 100);
      });
  });
}

/**
 * Requests a URL, returning a promise
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 *
 * @return {object}           The response data
 */
export default function request(url, options = {}, shouldWatchServerRestart = false) {
 // Set headers
  if (!options.headers) {
    options.headers = Object.assign({
      'Content-Type': 'application/json',
    }, options.headers, {
      'X-Forwarded-Host': 'strapi',
    });
  }

  const token = auth.getToken();

  if (token) {
    options.headers = Object.assign({
      'Authorization': `Bearer ${token}`,
    }, options.headers);
  }

  // Add parameters to url
  url = _.startsWith(url, '/') ? `${strapi.backendURL}${url}` : url;

  if (options && options.params) {
    const params = formatQueryParams(options.params);
    url = `${url}?${params}`;
  }

  // Stringify body object
  if (options && options.body) {
    options.body = JSON.stringify(options.body);
  }

  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then((response) => {
      if (shouldWatchServerRestart) {
        return serverRestartWatcher(response);
      }

      return response;
  });
}
<|endoftext|>


<commit_before>var gulp        = require('gulp');
var browserSync = require('browser-sync');
var typeScript  = require('gulp-typescript');
var del         = require('del');
var concat      = require('gulp-concat');
var browserify  = require('browserify');
var tsify       = require('tsify');
var source      = require('vinyl-source-stream');
var buffer      = require('vinyl-buffer');
//commment
var bases = {
  app: 'app/',
  dist: 'dist/',
};

gulp.task('clean', function()
{
  del.sync(bases.dist);
});

gulp.task('build', ['typeScriptIt'], function()
{
  gulp.src(bases.app+'**/*.html')
  .pipe(gulp.dest(bases.dist))
  .pipe(browserSync.reload({stream : true}));
});

gulp.task('browserSync', function()
{
  browserSync({
    server: {
      baseDir: bases.dist
    }
  });
});

gulp.task('watchfiles', function()
{
  gulp.watch(bases.app+'**/*.html', ['build']);
  gulp.watch([bases.app+'**/*.ts'],   ['typeScriptIt']);
});

gulp.task('typeScriptIt', function()
{
  browserify({ entries: bases.app+'App.ts', debug: true })
  .plugin(tsify)
  .bundle()
  .pipe(source('App.js'))
  .pipe(buffer())
  .pipe(gulp.dest(bases.dist))
  .pipe(browserSync.reload({stream : true}));

});

gulp.task('default', ['clean', 'build', 'browserSync', 'watchfiles']);
<commit_msg>Add comment<commit_after>var gulp        = require('gulp');
var browserSync = require('browser-sync');
var typeScript  = require('gulp-typescript');
var del         = require('del');
var concat      = require('gulp-concat');
var browserify  = require('browserify');
var tsify       = require('tsify');
var source      = require('vinyl-source-stream');
var buffer      = require('vinyl-buffer');
//comment
var bases = {
  app: 'app/',
  dist: 'dist/',
};

gulp.task('clean', function()
{
  del.sync(bases.dist);
});

gulp.task('build', ['typeScriptIt'], function()
{
  gulp.src(bases.app+'**/*.html')
  .pipe(gulp.dest(bases.dist))
  .pipe(browserSync.reload({stream : true}));
});

gulp.task('browserSync', function()
{
  browserSync({
    server: {
      baseDir: bases.dist
    }
  });
});

gulp.task('watchfiles', function()
{
  gulp.watch(bases.app+'**/*.html', ['build']);
  gulp.watch([bases.app+'**/*.ts'],   ['typeScriptIt']);
});

gulp.task('typeScriptIt', function()
{
  browserify({ entries: bases.app+'App.ts', debug: true })
  .plugin(tsify)
  .bundle()
  .pipe(source('App.js'))
  .pipe(buffer())
  .pipe(gulp.dest(bases.dist))
  .pipe(browserSync.reload({stream : true}));

});

gulp.task('default', ['clean', 'build', 'browserSync', 'watchfiles']);
<|endoftext|>


<commit_before>'use strict';

var Runtime = require('../.');

it('onHandle is called before and after each site', function(done){
  var count = 0;

  var runtime = Runtime.create({
    onHandle: function(){
      ++count;
    }
  });

  function one(next){ next(); }
  function two(next){ next(); }

  runtime.stack(one, two)(function(err){
    if(err){ return done(err); }
    count.should.be.eql(4);
    done();
  });
});

it('nested: onHandle is called before and after each site', function(done){
  var count = 0;

  var runtime = Runtime.create({
    onHandle: function(){
      ++count;
    }
  });

  function one(next){ next(); }
  function two(next){ next(); }

  runtime.stack(one, runtime.stack(two))(function(err){
    if(err){ return done(err); }
    count.should.be.eql(6);
    done();
  });
});

it('context for each stack can be given {context: [Object]}', function(done){
  var runtime = Runtime.create();

  runtime.stack(function one(next){
    this.params.should.be.eql(1);
    next();
  }, {context: {params: 1}})(function(err){
    if(err){ return done(err); }
    done();
  });
});

it('can be reused with no side-effects', function(done){
  var count = 0;
  var runtime = Runtime.create();

  var stack = runtime.stack(function one(next){
    ++count;
    this.param = ++this.param;
    this.param.should.be.eql(1);
    next();
  }, {context: {param: 0}});

  runtime.stack(stack, stack)(function(err){
    if(err){ done(err); }
    count.should.be.eql(2);
    done();
  });
});
<commit_msg>forgot to use return<commit_after>'use strict';

var Runtime = require('../.');

it('onHandle is called before and after each site', function(done){
  var count = 0;

  var runtime = Runtime.create({
    onHandle: function(){
      ++count;
    }
  });

  function one(next){ next(); }
  function two(next){ next(); }

  runtime.stack(one, two)(function(err){
    if(err){ return done(err); }
    count.should.be.eql(4);
    done();
  });
});

it('nested: onHandle is called before and after each site', function(done){
  var count = 0;

  var runtime = Runtime.create({
    onHandle: function(){
      ++count;
    }
  });

  function one(next){ next(); }
  function two(next){ next(); }

  runtime.stack(one, runtime.stack(two))(function(err){
    if(err){ return done(err); }
    count.should.be.eql(6);
    done();
  });
});

it('context for each stack can be given {context: [Object]}', function(done){
  var runtime = Runtime.create();

  runtime.stack(function one(next){
    this.params.should.be.eql(1);
    next();
  }, {context: {params: 1}})(function(err){
    if(err){ return done(err); }
    done();
  });
});

it('can be reused with no side-effects', function(done){
  var count = 0;
  var runtime = Runtime.create();

  var stack = runtime.stack(function one(next){
    ++count;
    this.param = ++this.param;
    this.param.should.be.eql(1);
    next();
  }, {context: {param: 0}});

  runtime.stack(stack, stack)(function(err){
    if(err){ return done(err); }
    count.should.be.eql(2);
    done();
  });
});
<|endoftext|>


<commit_before>/*
 * grunt-version-file
 * https://github.com/cfogelberg/grunt-version-file
 *
 * Copyright (c) 2014 Christo Fogelberg
 * Licensed under the MIT license.
 *
 * Class SRP: Register GVF with Grunt as a plugin
 */

"use strict";

var GruntVersionFileConfig = require("../lib/grunt_version_file");
var GeneratorManager = require("../lib/generator_manager");
var JsonCreator = require("../lib/json_creator");
var VersionFileWriter = require("../lib/version_file_writer");

function GruntVersionFile(task) {
  this.task = task;
  this.options = task.options(GruntVersionFile.Defaults);
}

GruntVersionFile.prototype.run = function() {
  var config = new GruntVersionFileConfig(this.options);
  new VersionFileWriter().write_version_file({
    json_object_creator: new JsonCreator({
      generator_manager: new GeneratorManager({
        generator_dir: config.generator_dir(),
        generator_list: config.generator_list()
      })
    }),
    out: config.out_filepath()
  });
};

GruntVersionFile.Defaults = {
  generator_dir: "generators",
  generator_list: [
    "datestring",
    "npm_version"
  ]
};

GruntVersionFile.task_name = "version_file";
GruntVersionFile.task_description = "Writes a JSON version file for this build";
GruntVersionFile.register_with_grunt = function(grunt) {
  grunt.registerMultiTask(GruntVersionFile.task_name, GruntVersionFile.task_description, function() {
    var task = new GruntVersionFile(this);
    task.run();
  });
};

// Add variables Grunt expects in camelc case...
GruntVersionFile.taskName = GruntVersionFile.task_name;
GruntVersionFile.taskDescription = GruntVersionFile.task_description;
GruntVersionFile.registerWithGrunt = GruntVersionFile.register_with_grunt;

module.exports = GruntVersionFile;
<commit_msg>grunt_version_file.js - typo bug fixes<commit_after>/*
 * grunt-version-file
 * https://github.com/cfogelberg/grunt-version-file
 *
 * Copyright (c) 2014 Christo Fogelberg
 * Licensed under the MIT license.
 *
 * Class SRP: Register GVF with Grunt as a plugin
 */

"use strict";

var GruntVersionFileConfig = require("../lib/grunt_version_file_config");
var GeneratorManager = require("../lib/generator_manager");
var JsonCreator = require("../lib/json_creator");
var VersionFileWriter = require("../lib/version_file_writer");

function GruntVersionFile(task) {
  this.task = task;
  this.options = task.options(GruntVersionFile.Defaults);
}

GruntVersionFile.prototype.run = function() {
  var config = new GruntVersionFileConfig(this.options);
  new VersionFileWriter().write_version_file({
    json_creator: new JsonCreator({
      generator_manager: new GeneratorManager({
        generator_dir: config.generator_dir(),
        generator_list: config.generator_list()
      })
    }),
    out: config.out_filepath()
  });
};

GruntVersionFile.Defaults = {
  generator_dir: "generators",
  generator_list: [
    "datestring",
    "npm_version"
  ]
};

GruntVersionFile.task_name = "version_file";
GruntVersionFile.task_description = "Writes a JSON version file for this build";
GruntVersionFile.register_with_grunt = function(grunt) {
  grunt.registerMultiTask(GruntVersionFile.task_name, GruntVersionFile.task_description, function() {
    var task = new GruntVersionFile(this);
    task.run();
  });
};

// Add variables Grunt expects in camelc case...
GruntVersionFile.taskName = GruntVersionFile.task_name;
GruntVersionFile.taskDescription = GruntVersionFile.task_description;
GruntVersionFile.registerWithGrunt = GruntVersionFile.register_with_grunt;

module.exports = GruntVersionFile;
<|endoftext|>


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

// For example, to find the nodeStepHash of "The Life Exotic" nodes:

// brew install jq
// ./getBungieManifest.js
// ./manifestDig.js manifest/world_sql_content_c7ea5036ed3278fe06a7a8feae87bf94.content 'The Life Exotic' DestinyTalentGridDefinition | jq '.nodes[].steps[] | select(.nodeStepName == "The Life Exotic") | .["nodeStepHash"]' | sort | uniq

var fs = require('fs');
var sqlite3 = require('sqlite3').verbose();

var target = process.argv[3];

var tables = (process.argv[4] || '').split(',');

var db = new sqlite3.Database(process.argv[2], sqlite3.OPEN_READONLY);

function dig(object, target, table, result) {
  if (typeof object === 'object') {
    for (var key in object) {
      if (key === target) {
        console.log(result);
      } else {
        dig(object[key], target, table, result);
      }
    }
  } else if (Array.isArray(object)) {
    object.forEach(function(val) {
      dig(val, target, table, result);
    });
  } else if (object == target) {
    console.log(result);
  }
}

db.serialize(function () {
  db.each("select name from sqlite_master where type='table'", function (err, table) {
    if (tables.indexOf(table.name) >= 0) {
      db.all("select * from " + table.name, function (err, result) {
        (result || []).forEach(function(entry) {
          if (entry.id === target) {
            console.log(entry.json);
          } else {
            try {
              var doc = JSON.parse(entry.json);
              dig(doc, target, table.name, entry.json);
            } catch(e) {
              console.error(e, entry.json);
            }
          }
        });
      });
    }
  });
});
<commit_msg>Fix table filter<commit_after>#!/usr/bin/env node

// For example, to find the nodeStepHash of "The Life Exotic" nodes:

// brew install jq
// ./getBungieManifest.js
// ./manifestDig.js manifest/world_sql_content_c7ea5036ed3278fe06a7a8feae87bf94.content 'The Life Exotic' DestinyTalentGridDefinition | jq '.nodes[].steps[] | select(.nodeStepName == "The Life Exotic") | .["nodeStepHash"]' | sort | uniq

var fs = require('fs');
var sqlite3 = require('sqlite3').verbose();

var target = process.argv[3];

var tables = (process.argv[4] || '').split(',');
if (tables.length == 1 && !tables[0].length) {
  tables = [];
}

var db = new sqlite3.Database(process.argv[2], sqlite3.OPEN_READONLY);

function dig(object, target, table, result) {
  if (typeof object === 'object') {
    for (var key in object) {
      if (key === target) {
        console.log(result);
      } else {
        dig(object[key], target, table, result);
      }
    }
  } else if (Array.isArray(object)) {
    object.forEach(function(val) {
      dig(val, target, table, result);
    });
  } else if (object == target) {
    console.log(result);
  }
}

db.serialize(function () {
  db.each("select name from sqlite_master where type='table'", function (err, table) {
    if (!tables.length || tables.indexOf(table.name) >= 0) {
      db.all("select * from " + table.name, function (err, result) {
        (result || []).forEach(function(entry) {
          if (entry.id === target) {
            console.log(entry.json);
          } else {
            try {
              var doc = JSON.parse(entry.json);
              dig(doc, target, table.name, entry.json);
            } catch(e) {
              console.error(e, entry.json);
            }
          }
        });
      });
    }
  });
});
<|endoftext|>