<commit_before>
var _ = require("underscore");
var mysql = require("mysql");
var dao = require("../utils/dao");
var common = require("../utils/common");
var async = require("async");
var logger = null;

exports.init = function(conf){
  logger = conf.getLogger();
  logger.debug("Initializing Query Engine");
  //init dao
  dao.init(conf);
  //init memcache
  //int logger
  logger.debug("Query Engine initialized");
}
// method that builds queries
exports.build = function(req,cb){

  if(!req) cb(new Error("Invalid call to query.js build method input is null"));
  process.nextTick(function(){
    var query = req.model.query;
    var params = _.extend(query.defaults,req.search);
    //TODO move this logic to static methods inside param object
    params.escape = function(val){
      if(this[val]) return mysql.escape(this[val]);
      else          return this[val];
    }

    var output= {};
    output.display=req.model.display;
    output.sqls=[];
    output.joins={};

    // Main query building
    var main =  _.template(query.select, {p:params});
    output.sqls.push({"type":"main",  "query": main+" limit "+params.page+","+params.rowsPerPage });
    output.sqls.push({"type":"count", "query":"select count(*) as total from ("+main+") as tempAlias"});

    //Join query building
    var joins = query.joins;
    if(joins){
      for(var j in joins){
        var join = joins[j];
        var sql = _.template(join.select, {p:params});
        output.sqls.push({"type":j, "query":sql });
        output.joins[j] = {"join_type":join.type, "on":join.on}; // join charectersitcs
      }
    }

    cb(null,output);
  });
};

//method that execute queries (Executes and streams output for processing
exports.execute = function(req,cb){
  if(!req) cb(new Error("Invalid call to query.js execute method, input is null"));
  var sqls = req.sqls;
  var output = {};
  async.forEach(sqls,
    function (sql,callback){
      dao.execute(sql.query,function(err,rows){
        if(err) callback(err);
        else{
          var joinInfo = req.joins[sql.type];
          if(joinInfo){
            process.nextTick(function(){
              output[sql.type]=processJoin(rows,joinInfo);
              callback()
            });
          }else{
            output[sql.type]= rows;
            callback();
          }
        }
      });
    },
    function(err){
      if(err) cb(err);
      else    cb(null,output);
    }
  );
}

function processJoin(rows,joinInfo){
  var output = {};
  for(var r in rows){
    var joinFlag = common.getJoinFlag(rows[r],joinInfo.on,"^");
    output[joinFlag]=rows[r];
  }
  return output;
}<commit_msg>fixed query.js to keep page and rowsPerPage optional<commit_after>
var _ = require("underscore");
var mysql = require("mysql");
var dao = require("../utils/dao");
var common = require("../utils/common");
var async = require("async");
var logger = null;

exports.init = function(conf){
  logger = conf.getLogger();
  logger.debug("Initializing Query Engine");
  //init dao
  dao.init(conf);
  //init memcache
  //int logger
  logger.debug("Query Engine initialized");
}
// method that builds queries
exports.build = function(req,cb){

  if(!req) cb(new Error("Invalid call to query.js build method input is null"));
  process.nextTick(function(){
    var query = req.model.query;
    var params = _.extend(query.defaults,req.search);
    //TODO move this logic to static methods inside param object
    params.escape = function(val){
      if(this[val]) return mysql.escape(this[val]);
      else          return this[val];
    }

    var output= {};
    output.display=req.model.display;
    output.sqls=[];
    output.joins={};

    // Main query building
    var main =  _.template(query.select, {p:params});
    main += (params.page && params.rowsPerPage) ? " limit "+params.page+","+params.rowsPerPage : "";
    output.sqls.push({"type":"main",  "query": main });
    output.sqls.push({"type":"count", "query":"select count(*) as total from ("+main+") as tempAlias"});

    //Join query building
    var joins = query.joins;
    if(joins){
      for(var j in joins){
        var join = joins[j];
        var sql = _.template(join.select, {p:params});
        output.sqls.push({"type":j, "query":sql });
        output.joins[j] = {"join_type":join.type, "on":join.on}; // join charectersitcs
      }
    }

    cb(null,output);
  });
};

//method that execute queries (Executes and streams output for processing
exports.execute = function(req,cb){
  if(!req) cb(new Error("Invalid call to query.js execute method, input is null"));
  var sqls = req.sqls;
  var output = {};
  async.forEach(sqls,
    function (sql,callback){
      dao.execute(sql.query,function(err,rows){
        if(err) callback(err);
        else{
          var joinInfo = req.joins[sql.type];
          if(joinInfo){
            process.nextTick(function(){
              output[sql.type]=processJoin(rows,joinInfo);
              callback()
            });
          }else{
            output[sql.type]= rows;
            callback();
          }
        }
      });
    },
    function(err){
      if(err) cb(err);
      else    cb(null,output);
    }
  );
}

function processJoin(rows,joinInfo){
  var output = {};
  for(var r in rows){
    var joinFlag = common.getJoinFlag(rows[r],joinInfo.on,"^");
    output[joinFlag]=rows[r];
  }
  return output;
}
<|endoftext|>


<commit_before>/**
 * @file singleton.js
 * @author Vladimir Deminenko
 * @date 07.07.2017
 */

'use strict';

const ONE_SECOND_LENGTH = 1000;
const ONE_MINUTE_LENGTH = 60 * ONE_SECOND_LENGTH;
const ONE_HOUR_LENGTH = 60 * ONE_MINUTE_LENGTH;
const ONE_DAY_LENGTH = 24 * ONE_HOUR_LENGTH;

function getWeekDay(date) {
    const daysOfWeek = [
        'вс',
        'пн',
        'вт',
        'ср',
        'чт',
        'пт',
        'сб'
    ];

    return daysOfWeek[date.getDay()];
}

function getLocalDay(date) {
    return date.getUTCDay() + 1;
}

function getDateAgo(date, days) {
    return new Date(date - days * ONE_DAY_LENGTH).getDate();
}

function getLastDayOfMonth(year, month) {
    return new Date(new Date(year, month + 1, 1) - ONE_DAY_LENGTH).getDate();
}

function formatDate(date) {
    const options = {
        year: '2-digit',
        month: 'numeric',
        day: 'numeric'
    };

    return date.toLocaleString("ru", options);
}

function formatRelativeDate(date) {
    const options = {
        year: '2-digit',
        month: 'numeric',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric'
    };

    const relativeDate = new Date() - date;

    if (relativeDate < ONE_SECOND_LENGTH) {
        return 'только что';
    }

    if (relativeDate < ONE_MINUTE_LENGTH) {
        return `${Math.floor(relativeDate / ONE_SECOND_LENGTH)} сек. назад`;
    }

    if (relativeDate < ONE_HOUR_LENGTH) {
        return `${Math.floor(relativeDate / ONE_MINUTE_LENGTH)} мин. назад`;
    }

    return date.toLocaleString("ru", options).replace(',', '');
}

function closureSum(b) {
    return function (a) {
        return +a + +b;
    }
}

function makeBuffer() {
    let buffer = [];

    let cleanedBuffer = function (value) {
        if (arguments.length === 0) {
            return buffer.join('');
        }

        buffer.push(`${value}`);
    };

    cleanedBuffer.clear = function () {
        buffer.length = 0;
    };

    return cleanedBuffer;
}

function byField(fieldName) {
    let sortByAge = function (user1, user2) {
        return user1.age - user2.age;
    };

    let sortByName = function (user1, user2) {
        if (user1.name > user2.name) {
            return 1;
        }

        return -1;
    };

    if ('age' === fieldName.toLowerCase()) {
        return sortByAge;
    }

    return sortByName;
}

function inArray(arr) {
    return function (value) {
        return !!~arr.indexOf(value);
    }
}

function inBetween(a, b) {
    return function (value) {
        return value >= a && value <= b;
    }
}

function filter(arr, func) {
    let result = [];

    for (let i = 0; i < arr.length; i++) {
        let value = arr[i];

        if (func(value)) {
            result.push(value);
        }
    }

    return result;
}

function makeArmy() {
    let shooters = [];

    for (let i = 0; i < 10; i++) {
        let shooter = function () {
            return i;
        };

        shooters.push(shooter);
    }

    return shooters;
}
<commit_msg>homework-03<commit_after>/**
 * @file singleton.js
 * @author Vladimir Deminenko
 * @date 07.07.2017
 */

'use strict';

const ONE_SECOND_LENGTH = 1000;
const ONE_MINUTE_LENGTH = 60 * ONE_SECOND_LENGTH;
const ONE_HOUR_LENGTH = 60 * ONE_MINUTE_LENGTH;
const ONE_DAY_LENGTH = 24 * ONE_HOUR_LENGTH;

function getWeekDay(date) {
    const daysOfWeek = [
        'вс',
        'пн',
        'вт',
        'ср',
        'чт',
        'пт',
        'сб'
    ];

    return daysOfWeek[date.getDay()];
}

function getLocalDay(date) {
    return date.getUTCDay() + 1;
}

function getDateAgo(date, days) {
    return new Date(date - days * ONE_DAY_LENGTH).getDate();
}

function getLastDayOfMonth(year, month) {
    return new Date(new Date(year, month + 1, 1) - ONE_DAY_LENGTH).getDate();
}

function formatDate(date) {
    const options = {
        year: '2-digit',
        month: 'numeric',
        day: 'numeric'
    };

    return date.toLocaleString("ru", options);
}

function formatRelativeDate(date) {
    const options = {
        year: '2-digit',
        month: 'numeric',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric'
    };

    const relativeDate = new Date() - date;

    if (relativeDate < ONE_SECOND_LENGTH) {
        return 'только что';
    }

    if (relativeDate < ONE_MINUTE_LENGTH) {
        return `${Math.floor(relativeDate / ONE_SECOND_LENGTH)} сек. назад`;
    }

    if (relativeDate < ONE_HOUR_LENGTH) {
        return `${Math.floor(relativeDate / ONE_MINUTE_LENGTH)} мин. назад`;
    }

    return date.toLocaleString("ru", options).replace(',', '');
}

function closureSum(b) {
    return function (a) {
        return +a + +b;
    }
}

function makeBuffer() {
    let buffer = [];

    let cleanedBuffer = function (value) {
        if (arguments.length === 0) {
            return buffer.join('');
        }

        buffer.push(`${value}`);
    };

    cleanedBuffer.clear = function () {
        buffer.length = 0;
    };

    return cleanedBuffer;
}

function byField(fieldName) {
    let sortByAge = function (user1, user2) {
        return user1.age - user2.age;
    };

    let sortByName = function (user1, user2) {
        if (user1.name > user2.name) {
            return 1;
        }

        return -1;
    };

    if ('age' === fieldName.toLowerCase()) {
        return sortByAge;
    }

    return sortByName;
}

function inArray(arr) {
    return function (value) {
        return !!~arr.indexOf(value);
    };
}

function inBetween(a, b) {
    return function (value) {
        return value >= a && value <= b;
    };
}

function filter(arr, func) {
    let result = [];

    for (let i = 0; i < arr.length; i++) {
        let value = arr[i];

        if (func(value)) {
            result.push(value);
        }
    }

    return result;
}

function makeArmy() {
    let shooters = [];

    for (let i = 0; i < 10; i++) {
        let shooter = function () {
            return i;
        };

        shooters.push(shooter);
    }

    return shooters;
}
<|endoftext|>


<commit_before>(function () {
  "use strict";
  window.FourthWall = window.FourthWall || {};

  FourthWall.PullView = Backbone.View.extend({
    tagName: 'li',

    initialize: function () {
      this.model.on('change', this.render, this);
    },

    render: function () {
      this.$el.removeClass();

      if (!this.model.get('user')) {
        // FIXME: Should never get here but does after master was
        // failing
        return;
      }

      this.$el.addClass(this.ageClass(this.model.get('elapsed_time')));

      if (FourthWall.importantUsers.length > 0 && $.inArray(this.model.get('user').login, FourthWall.importantUsers) == -1) {
        this.$el.addClass('unimportant-user');
      }

      if (this.model.comment.get('thumbsup')) {
        this.$el.addClass("thumbsup");
      }

      var suffix = "";
      if (this.model.comment.get('numComments') !== 1) {
        suffix = "s";
      }

      if (this.model.info.get('mergeable') === false){
        var statusString = '
No auto merge
';
      } else if (this.model.status.get('state')){
        var state = this.model.status.get('state');
        var statusString = '
Status: ' + state + '
';
      } else {
        var statusString = '
No status
';
      }

      var commentCount = 0;
      if (this.model.comment.get('numComments')){
        commentCount = commentCount + this.model.comment.get('numComments');
      }
      if (this.model.info.get('review_comments')){
        commentCount = commentCount + this.model.info.get('review_comments');
      }

      this.$el.html([
        '',
        statusString,
        '
', this.model.get('repo'), '
',
        '
',
        this.secondsToTime(this.model.get('elapsed_time')),
        '
',
        '
',
        '',this.model.get('user').login,'',
        ': ',
        this.escape(this.model.get('title')),
        ' (#',
        this.model.get('number'),
        ')',
        '
',
        '
 ' + commentCount + " comment" + suffix + '
',
      ].join(''));
    },

    escape: function (string) {
      return $('
').text(string).html();
    },

    ageClass: function (seconds) {
      var hours = 3600;
      if (seconds > (6 * hours)) {
        return "age-old";
      } else if (seconds > (2 * hours)) {
        return "age-aging";
      } else {
        return "age-fresh";
      }
    },

    secondsToTime: function (seconds) {
      var days    = Math.floor(seconds / 86400);
      var hours   = Math.floor((seconds - (days * 86400)) / 3600);
      var minutes = Math.floor((seconds - (days * 86400) - (hours * 3600)) / 60);

      if (hours   < 10) {hours   = "0"+hours;}
      if (minutes < 10) {minutes = "0"+minutes;}
      if (days == 1) {
        days = days + " day";
      } else if (days > 1) {
        days = days + " days";
      } else {
        days = "";
      }
      return days + ' ' + hours + 'h ' + minutes + 'm';
    }
  });

}());
<commit_msg>Open pull view repo links in a new tab.<commit_after>(function () {
  "use strict";
  window.FourthWall = window.FourthWall || {};

  FourthWall.PullView = Backbone.View.extend({
    tagName: 'li',

    initialize: function () {
      this.model.on('change', this.render, this);
    },

    render: function () {
      this.$el.removeClass();

      if (!this.model.get('user')) {
        // FIXME: Should never get here but does after master was
        // failing
        return;
      }

      this.$el.addClass(this.ageClass(this.model.get('elapsed_time')));

      if (FourthWall.importantUsers.length > 0 && $.inArray(this.model.get('user').login, FourthWall.importantUsers) == -1) {
        this.$el.addClass('unimportant-user');
      }

      if (this.model.comment.get('thumbsup')) {
        this.$el.addClass("thumbsup");
      }

      var suffix = "";
      if (this.model.comment.get('numComments') !== 1) {
        suffix = "s";
      }

      if (this.model.info.get('mergeable') === false){
        var statusString = '
No auto merge
';
      } else if (this.model.status.get('state')){
        var state = this.model.status.get('state');
        var statusString = '
Status: ' + state + '
';
      } else {
        var statusString = '
No status
';
      }

      var commentCount = 0;
      if (this.model.comment.get('numComments')){
        commentCount = commentCount + this.model.comment.get('numComments');
      }
      if (this.model.info.get('review_comments')){
        commentCount = commentCount + this.model.info.get('review_comments');
      }

      this.$el.html([
        '',
        statusString,
        '
', this.model.get('repo'), '
',
        '
',
        this.secondsToTime(this.model.get('elapsed_time')),
        '
',
        '
',
        '',this.model.get('user').login,'',
        ': ',
        this.escape(this.model.get('title')),
        ' (#',
        this.model.get('number'),
        ')',
        '
',
        '
 ' + commentCount + " comment" + suffix + '
',
      ].join(''));
    },

    escape: function (string) {
      return $('
').text(string).html();
    },

    ageClass: function (seconds) {
      var hours = 3600;
      if (seconds > (6 * hours)) {
        return "age-old";
      } else if (seconds > (2 * hours)) {
        return "age-aging";
      } else {
        return "age-fresh";
      }
    },

    secondsToTime: function (seconds) {
      var days    = Math.floor(seconds / 86400);
      var hours   = Math.floor((seconds - (days * 86400)) / 3600);
      var minutes = Math.floor((seconds - (days * 86400) - (hours * 3600)) / 60);

      if (hours   < 10) {hours   = "0"+hours;}
      if (minutes < 10) {minutes = "0"+minutes;}
      if (days == 1) {
        days = days + " day";
      } else if (days > 1) {
        days = days + " days";
      } else {
        days = "";
      }
      return days + ' ' + hours + 'h ' + minutes + 'm';
    }
  });

}());
<|endoftext|>


<commit_before>/* GIT-ignore/glob file resolver
 *
 * Priorities:
 * - Resolve explicit file-names (FILENAME.EXT)
 * - Load ignore-patterns (!NOT_THIS, !*.NOT_EXT)
 * - Resolve simple shell-patterns (DIR/*)
 * - Expand glob-patterns (Things with **.EXT)
 *
 * For now, we just use glob and then filter out results. If that doesn't work
 * (either matching doesn't feel right or not fast enough), we may want to
 * redo it.
 *
 * Glob doesn't do ignores quite the way we like, but minmatch does seem to
 * implement most of what we want, so we could 'just' add some code to apply
 * ignore-patterns early + multiple arguments.
 */

var async = require('async'),
    Path = require('path'), // Import with an upper case name so it's less likely to collide with a variable name
    minimatch = require('minimatch'),
    glob = require('glob-papandreou'),
    fs = require('fs');

function resolve(matchList, baseDir, callback) {
    // Split out ignore-patterns
    var okList = [],
        ignoreList = [];

    for (var i = 0; i< matchList.length; i += 1) {
        if (matchList[i][0] === '!') {
            ignoreList.push(matchList[i].substr(1));
        } else {
            okList.push(matchList[i]);
        }
    }

    return async.map(okList, function (match, cb) {
        // Stat it!
        fs.stat(Path.resolve(baseDir, match), function (err, stats) {
            // If it stat'ed successfully and it's a file
            if (stats && stats.isFile()) {
                return cb(undefined, [match]);
            }

            function isNotIgnored(filename) {
                return !ignoreList.some(function (ignore) {
                    if (minimatch(filename, ignore, { nocase: true })) {
                        return true;
                    }

                    return false;
                });
            }

            // GLOB IT!
            glob(match, { mark: true, cwd: baseDir, filter: isNotIgnored }, function (err, files) {
                files = files && files.filter(function (file) {
                    return file[file.length - 1] !== '/';
                });
                return cb(err, files);
            });
        });
    }, function (err, res) {
        // Collect results
        // TODO: De-duplicate
        return callback(err, !err && Array.prototype.concat.apply([], res));
    });
}

module.exports = resolve;
<commit_msg>Lint gitFileResolver.js<commit_after>/* GIT-ignore/glob file resolver
 *
 * Priorities:
 * - Resolve explicit file-names (FILENAME.EXT)
 * - Load ignore-patterns (!NOT_THIS, !*.NOT_EXT)
 * - Resolve simple shell-patterns (DIR/*)
 * - Expand glob-patterns (Things with **.EXT)
 *
 * For now, we just use glob and then filter out results. If that doesn't work
 * (either matching doesn't feel right or not fast enough), we may want to
 * redo it.
 *
 * Glob doesn't do ignores quite the way we like, but minmatch does seem to
 * implement most of what we want, so we could 'just' add some code to apply
 * ignore-patterns early + multiple arguments.
 */

var async = require('async'),
    Path = require('path'), // Import with an upper case name so it's less likely to collide with a variable name
    minimatch = require('minimatch'),
    glob = require('glob-papandreou'),
    fs = require('fs');

function resolve(matchList, baseDir, callback) {
    // Split out ignore-patterns
    var okList = [],
        ignoreList = [];

    for (var i = 0; i < matchList.length; i += 1) {
        if (matchList[i][0] === '!') {
            ignoreList.push(matchList[i].substr(1));
        } else {
            okList.push(matchList[i]);
        }
    }

    return async.map(okList, function (match, cb) {
        // Stat it!
        fs.stat(Path.resolve(baseDir, match), function (err, stats) {
            // If it stat'ed successfully and it's a file
            if (stats && stats.isFile()) {
                return cb(undefined, [match]);
            }

            function isNotIgnored(filename) {
                return !ignoreList.some(function (ignore) {
                    if (minimatch(filename, ignore, { nocase: true })) {
                        return true;
                    }

                    return false;
                });
            }

            // GLOB IT!
            glob(match, { mark: true, cwd: baseDir, filter: isNotIgnored }, function (err, files) {
                files = files && files.filter(function (file) {
                    return file[file.length - 1] !== '/';
                });
                return cb(err, files);
            });
        });
    }, function (err, res) {
        // Collect results
        // TODO: De-duplicate
        return callback(err, !err && Array.prototype.concat.apply([], res));
    });
}

module.exports = resolve;
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter
var vcsurl = require('vcsurl')
var request = require('request')
var path = require('path')
var fs = require('fs-extra')
var util = require('util')
var extractZip = require('./zip').extractZip
var cwd = process.cwd()

function GithubDownloader (user, repo, ref, dir) {
  this.user = user
  this.repo = repo
  this.ref = ref || 'master'
  this.dir = dir
  this._log = []
  this._getZip = false
}
util.inherits(GithubDownloader, EventEmitter)

GithubDownloader.prototype.start = function () {
  var _this = this
  var initialUrl = 'https://api.github.com/repos/' + this.user + '/' + this.repo + '/contents/'
  var initialUrlRef = this.ref ? '?ref=' + this.ref : ''
  var rawUrl = 'https://raw.github.com/' + this.user + '/' + this.repo + '/' + this.ref + '/'
  var pending = 0
  var gonnaProcess = 0

  gonnaProcess += 1
  requestJSON.call(this, initialUrl + initialUrlRef, processItems)

  function processItems (items) {
    pending += items.length
    gonnaProcess -= 1
    items.forEach(handleItem)
    checkDone()
  }

  function handleItem (item) {
    if (item.type === 'dir') {
      var dir = path.join(_this.dir, item.path)
      fs.mkdirs(dir, function (err) {
        if (err) _this.emit('error', err)
        _this._log.push(dir)
        gonnaProcess += 1
        requestJSON.call(_this, initialUrl + item.path + initialUrlRef, processItems)
        _this.emit('dir', item.path)
        pending -= 1
        checkDone()
      })
    } else if (item.type === 'file') {
      var file = path.join(_this.dir, item.path)
      fs.createFile(file, function (err) {
        if (err) _this.emit('error', err)
        request.get(rawUrl + item.path).pipe(fs.createWriteStream(file)).on('close', function () {
          _this._log.push(file)
          _this.emit('file', item.path)
          pending -= 1
          checkDone()
        })
      })
    } else {
      _this.emit('Error', new Error(JSON.stringify(item, null, 2) + '\n does not have type.'))
    }
  }

  function checkDone () {
    // console.log('PENDING: ' + pending + ' gonnaProcess: ' + gonnaProcess)
    if (pending === 0 && gonnaProcess === 0 && !this._getZip) {
      _this.emit('end')
    }
  }

  return this
}

module.exports = function GithubDownload (params, dir) {
  if (typeof params === 'string') {
    var pieces = params.split('#')
    var ref = pieces[1]
    var url = (vcsurl(pieces[0]) || pieces[0]).split('/')
    params = {user: url[url.length - 2], repo: url[url.length - 1], ref: ref}
  }

  if (typeof params !== 'object') {
    throw new Error('Invalid parameter type. Should be repo URL string or object containing repo and user.')
  }

  // console.dir(params)

  dir = dir || process.cwd()
  var gh = new GithubDownloader(params.user, params.repo, params.ref, dir)
  return gh.start()
}

// PRIVATE METHODS

function requestJSON (url, callback) {
  var _this = this
  request({url: url}, function (err, resp, body) {
    if (err) return this.emit('error', err)
    if (resp.statusCode === 403) return downloadZip.call(_this)
    if (resp.statusCode !== 200) _this.emit('error', new Error(url + ': returned ' + resp.statusCode + '\n\nbody:\n' + body))

    callback(JSON.parse(body))
  })
}

function downloadZip () {
  var _this = this
  if (_this._getZip) return
  _this._getZip = true

  _this._log.forEach(function (file) {
    fs.remove(file)
  })

  var tmpdir = generateTempDir()
  var zipBaseDir = _this.repo + '-' + _this.ref
  var zipFile = path.join(tmpdir, zipBaseDir + '.zip')

  var zipUrl = 'https://nodeload.github.com/' + _this.user + '/' + _this.repo + '/zip/' + _this.ref
  _this.emit('zip', zipUrl)

  // console.log(zipUrl)
  fs.mkdir(tmpdir, function (err) {
    if (err) _this.emit('error', err)
    request.get(zipUrl).pipe(fs.createWriteStream(zipFile)).on('close', function () {
      // fs.createReadStream(zipFile).pipe(unzip.Extract({path: tmpdir})).on('close', function() {
      extractZip.call(_this, zipFile, tmpdir, function (extractedFolderName) {
        var oldPath = path.join(tmpdir, extractedFolderName)
        // console.log(oldPath)
        fs.rename(oldPath, _this.dir, function (err) {
          if (err) _this.emit('error', err)
          fs.remove(tmpdir, function (err) {
            if (err) _this.emit('error', err)
            _this.emit('end')
          })
        })
      })
    })
  })

}

function generateTempDir () {
  return path.join(cwd, Date.now().toString() + '-' + Math.random().toString().substring(2))
}
<commit_msg>Fixed linting issues<commit_after>var EventEmitter = require('events').EventEmitter
var vcsurl = require('vcsurl')
var request = require('request')
var path = require('path')
var fs = require('fs-extra')
var util = require('util')
var extractZip = require('./zip').extractZip
var cwd = process.cwd()

function GithubDownloader (user, repo, ref, dir) {
  this.user = user
  this.repo = repo
  this.ref = ref || 'master'
  this.dir = dir
  this._log = []
  this._getZip = false
}
util.inherits(GithubDownloader, EventEmitter)

GithubDownloader.prototype.start = function () {
  var _this = this
  var initialUrl = 'https://api.github.com/repos/' + this.user + '/' + this.repo + '/contents/'
  var initialUrlRef = this.ref ? '?ref=' + this.ref : ''
  var rawUrl = 'https://raw.github.com/' + this.user + '/' + this.repo + '/' + this.ref + '/'
  var pending = 0
  var gonnaProcess = 0

  gonnaProcess += 1
  requestJSON.call(this, initialUrl + initialUrlRef, processItems)

  function processItems (items) {
    pending += items.length
    gonnaProcess -= 1
    items.forEach(handleItem)
    checkDone()
  }

  function handleItem (item) {
    if (item.type === 'dir') {
      var dir = path.join(_this.dir, item.path)
      fs.mkdirs(dir, function (err) {
        if (err) _this.emit('error', err)
        _this._log.push(dir)
        gonnaProcess += 1
        requestJSON.call(_this, initialUrl + item.path + initialUrlRef, processItems)
        _this.emit('dir', item.path)
        pending -= 1
        checkDone()
      })
    } else if (item.type === 'file') {
      var file = path.join(_this.dir, item.path)
      fs.createFile(file, function (err) {
        if (err) _this.emit('error', err)
        request.get(rawUrl + item.path).pipe(fs.createWriteStream(file)).on('close', function () {
          _this._log.push(file)
          _this.emit('file', item.path)
          pending -= 1
          checkDone()
        })
      })
    } else {
      _this.emit('Error', new Error(JSON.stringify(item, null, 2) + '\n does not have type.'))
    }
  }

  function checkDone () {
    // console.log('PENDING: ' + pending + ' gonnaProcess: ' + gonnaProcess)
    if (pending === 0 && gonnaProcess === 0 && !this._getZip) {
      _this.emit('end')
    }
  }

  return this
}

module.exports = function GithubDownload (params, dir) {
  if (typeof params === 'string') {
    var pieces = params.split('#')
    var ref = pieces[1]
    var url = (vcsurl(pieces[0]) || pieces[0]).split('/')
    params = {user: url[url.length - 2], repo: url[url.length - 1], ref: ref}
  }

  if (typeof params !== 'object') {
    throw new Error('Invalid parameter type. Should be repo URL string or object containing repo and user.')
  }

  // console.dir(params)

  dir = dir || process.cwd()
  var gh = new GithubDownloader(params.user, params.repo, params.ref, dir)
  return gh.start()
}

// PRIVATE METHODS

function requestJSON (url, callback) {
  var _this = this
  request({url: url}, function (err, resp, body) {
    if (err) return this.emit('error', err)
    if (resp.statusCode === 403) return downloadZip.call(_this)
    if (resp.statusCode !== 200) _this.emit('error', new Error(url + ': returned ' + resp.statusCode + '\n\nbody:\n' + body))

    callback(JSON.parse(body))
  })
}

function downloadZip () {
  var _this = this
  if (_this._getZip) return
  _this._getZip = true

  _this._log.forEach(function (file) {
    fs.remove(file)
  })

  var tmpdir = generateTempDir()
  var zipBaseDir = _this.repo + '-' + _this.ref
  var zipFile = path.join(tmpdir, zipBaseDir + '.zip')

  var zipUrl = 'https://nodeload.github.com/' + _this.user + '/' + _this.repo + '/zip/' + _this.ref
  _this.emit('zip', zipUrl)

  // console.log(zipUrl)
  fs.mkdir(tmpdir, function (err) {
    if (err) _this.emit('error', err)
    request.get(zipUrl).pipe(fs.createWriteStream(zipFile)).on('close', function () {
      extractZip.call(_this, zipFile, tmpdir, function (extractedFolderName) {
        var oldPath = path.join(tmpdir, extractedFolderName)
        fs.rename(oldPath, _this.dir, function (err) {
          if (err) _this.emit('error', err)
          fs.remove(tmpdir, function (err) {
            if (err) _this.emit('error', err)
            _this.emit('end')
          })
        })
      })
    })
  })
}

function generateTempDir () {
  return path.join(cwd, Date.now().toString() + '-' + Math.random().toString().substring(2))
}
<|endoftext|>


<commit_before>var request = require('request');

module.exports = {listeners: [
{
	type: "equals",
	query: ".minion",
	callback: function(reply, message, api){
		reddit(["MinionHate", "WackyTicTacs"], "http://i.imgur.com/L07nbhn.jpg", reply, message, api);
	}
}, {
	type: "equals",
	query: ".corgi",
	callback: function(reply, message, api){
		reddit(["corgi", "BabyCorgis"], "http://i.imgur.com/djeivlK.gif", reply, message, api);
	}
}, {
	type: "equals",
	query: ".doge",
	callback: function(reply, message, api){
		reddit(["doge", "supershibe"], "http://i.imgur.com/WMiliXD.jpg", reply, message, api);
	}
}
]};

function reddit(subs, fail, reply, message, api){
	if(api.type === "messenger")
		api.sendTypingIndicator(message.thread_id);
	var url = "https://www.reddit.com/r/" + subs[Math.floor(Math.random() * subs.length)] + "/top/.json?sort=top&t=week";

	request(url, function(err, res, body){
		try{
			var posts = JSON.parse(body).data.children;
			var index = Math.floor(Math.random() * posts.length);
			var attempts = 0;
			while(!posts[index].data.url || posts[index].data.url.indexOf("i.imgur.com") === -1){
				index = Math.floor(Math.random() * posts.length);
				if(++attempts > 10)
					return reply({attachment: request(fail)});
			}
			var post = posts[index].data.url;
			console.log(post);

			if(api.type === "messenger"){
				var image = request(post);

				if(image)
					reply({attachment: image});
				else
					reply({attachment: request(fail)});
			}else
				reply(post);
		}catch(e){
			reply({attachment: request(fail)});
		}
	});
}
<commit_msg>Possums!<commit_after>var request = require('request');

module.exports = {listeners: [
{
	type: "equals",
	query: ".minion",
	callback: function(reply, message, api){
		reddit(["MinionHate", "WackyTicTacs"], "http://i.imgur.com/L07nbhn.jpg", reply, message, api);
	}
}, {
	type: "equals",
	query: ".corgi",
	callback: function(reply, message, api){
		reddit(["corgi", "BabyCorgis"], "http://i.imgur.com/djeivlK.gif", reply, message, api);
	}
}, {
	type: "equals",
	query: ".doge",
	callback: function(reply, message, api){
		reddit(["doge", "supershibe"], "http://i.imgur.com/WMiliXD.jpg", reply, message, api);
	}
}, {
	type: "regex",
	query: /.o?pos+um/i,
	callback: function(reply, message, api){
		reddit(["Possums"], "https://i.imgur.com/T0wMPRg.jpg", reply, message, api);
	}
}
]};

function reddit(subs, fail, reply, message, api){
	if(api.type === "messenger")
		api.sendTypingIndicator(message.thread_id);
	var url = "https://www.reddit.com/r/" + subs[Math.floor(Math.random() * subs.length)] + "/top/.json?sort=top&t=year";

	request(url, function(err, res, body){
		try{
			var posts = JSON.parse(body).data.children;
			var index = Math.floor(Math.random() * posts.length);
			var attempts = 0;
			while(!posts[index].data.url || (posts[index].data.url.indexOf("i.imgur.com") === -1 && posts[index].data.url.indexOf("i.redditmedia.com") === -1)){
				index = Math.floor(Math.random() * posts.length);
				if(++attempts > 50)
					return reply({attachment: request(fail)});
			}
			var post = posts[index].data.url;
			console.log(post);

			if(api.type === "messenger"){
				var image = request(post);

				if(image)
					reply({attachment: image});
				else
					reply({attachment: request(fail)});
			}else
				reply(post);
		}catch(e){
			reply({attachment: request(fail)});
		}
	});
}
<|endoftext|>


<commit_before>

  var camera, scene, renderer;
  var mesh;

  var lastVelocity = 0,
      lastTime = new Date(),
      lastPosition = 0;

  init();
  animate();
  initGyro();

  function init() {

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    //

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth /
      window.innerHeight, 1, 1000 );
      camera.position.z = 600;

      scene = new THREE.Scene();

      var geometry = new THREE.BoxGeometry( 200, 200, 200 );

      var texture = THREE.ImageUtils.loadTexture( 'textures/crate.gif' );
      texture.anisotropy = renderer.getMaxAnisotropy();

      var material = new THREE.MeshBasicMaterial( { map: texture } );

      mesh = new THREE.Mesh( geometry, material );
      scene.add( mesh );

      //

      window.addEventListener( 'resize', onWindowResize, false );

    }

    function velocity (lastVelocity, acceleration, timeStep) {
      return lastVelocity + (acceleration * timeStep);
    }

    function position (lastPosition, lastVelocity, acceleration, timeStep) {
      return lastPosition + lastVelocity * timeStep +
          (0.5 * acceleration * timeStep * timeStep);
    }

    function initGyro() {
      console.log("start tracking");
      gyro.frequency = 10;

      gyro.startTracking(function(o) {
        var yNoiseUpper = 0.2,
          yNoiseLower = -0.13;

        if (parseFloat(o.y.toFixed(2)) >= yNoiseUpper ||
            parseFloat(o.y.toFixed(2)) <= yNoiseLower) {

          if (parseFloat(o.y.toFixed(2)) >= yNoiseUpper) {

          }
          var yAcceleration = o.y.toFixed(3),
          needsRender = false,
          currentTime = new Date(),

          // dividing by 1000 to decrease velocity by 1000 and position by
          // 100000
          timeStep = (currentTime - lastTime) / 1000;

          console.log("y-acceleration: "  + o.y.toFixed(3));

          lastVelocity = velocity(lastVelocity, yAcceleration, timeStep);
          lastPosition = position(lastPosition, lastVelocity, yAcceleration, timeStep);
          console.log("Velocity: " + lastVelocity);
          console.log("Position: " + lastPosition);
          lastTime = currentTime;

          // if (newY <= 400 && newY >= -400) {
          //   mesh.position.y = newY;
          //   needsRender = true;
          // }

          if (needsRender) {
            renderer.render( scene, camera );
            console.log(mesh.position.y);
          }

          // o.z
          // o.alpha
          // o.beta
          // o.gamma
        }

        if (parseFloat(o.x.toFixed(1)) >= 0.5) {
          console.log("x-acceleration: "  + o.x.toFixed(3));
        }

        if (parseFloat(o.z.toFixed(1)) >= 9.8) {
          console.log("z-acceleration: "  + o.z.toFixed(3));
        }
      });
    }

    function onWindowResize() {

      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();

      renderer.setSize( window.innerWidth, window.innerHeight );

    }

    function animate() {

      requestAnimationFrame( animate );

      renderer.render( scene, camera );

    }
<commit_msg>adjusting noise bounds<commit_after>

  var camera, scene, renderer;
  var mesh;

  var lastVelocity = 0,
      lastTime = new Date(),
      lastPosition = 0;

  init();
  animate();
  initGyro();

  function init() {

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    //

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth /
      window.innerHeight, 1, 1000 );
      camera.position.z = 600;

      scene = new THREE.Scene();

      var geometry = new THREE.BoxGeometry( 200, 200, 200 );

      var texture = THREE.ImageUtils.loadTexture( 'textures/crate.gif' );
      texture.anisotropy = renderer.getMaxAnisotropy();

      var material = new THREE.MeshBasicMaterial( { map: texture } );

      mesh = new THREE.Mesh( geometry, material );
      scene.add( mesh );

      //

      window.addEventListener( 'resize', onWindowResize, false );

    }

    function velocity (lastVelocity, acceleration, timeStep) {
      return lastVelocity + (acceleration * timeStep);
    }

    function position (lastPosition, lastVelocity, acceleration, timeStep) {
      return lastPosition + lastVelocity * timeStep +
          (0.5 * acceleration * timeStep * timeStep);
    }

    function initGyro() {
      console.log("start tracking");
      gyro.frequency = 10;

      gyro.startTracking(function(o) {
        var yNoiseUpper = 0.2,
          yNoiseLower = -0.2;

        if (parseFloat(o.y.toFixed(2)) >= yNoiseUpper ||
            parseFloat(o.y.toFixed(2)) <= yNoiseLower) {

          if (parseFloat(o.y.toFixed(2)) >= yNoiseUpper) {

          }
          var yAcceleration = o.y.toFixed(3),
          needsRender = false,
          currentTime = new Date(),

          // dividing by 1000 to decrease velocity by 1000 and position by
          // 100000
          timeStep = (currentTime - lastTime) / 1000;

          console.log("y-acceleration: "  + o.y.toFixed(3));

          lastVelocity = velocity(lastVelocity, yAcceleration, timeStep);
          lastPosition = position(lastPosition, lastVelocity, yAcceleration, timeStep);
          console.log("Velocity: " + lastVelocity);
          console.log("Position: " + lastPosition);
          lastTime = currentTime;

          // if (newY <= 400 && newY >= -400) {
          //   mesh.position.y = newY;
          //   needsRender = true;
          // }

          if (needsRender) {
            renderer.render( scene, camera );
            console.log(mesh.position.y);
          }

          // o.z
          // o.alpha
          // o.beta
          // o.gamma
        }

        if (parseFloat(o.x.toFixed(1)) >= 0.5) {
          console.log("x-acceleration: "  + o.x.toFixed(3));
        }

        if (parseFloat(o.z.toFixed(1)) >= 9.8) {
          console.log("z-acceleration: "  + o.z.toFixed(3));
        }
      });
    }

    function onWindowResize() {

      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();

      renderer.setSize( window.innerWidth, window.innerHeight );

    }

    function animate() {

      requestAnimationFrame( animate );

      renderer.render( scene, camera );

    }
<|endoftext|>


<commit_before>'use strict';

var Immutable = require('immutable');
var xtend = require('xtend');
var Handler = require('./handlers');
var { translatePoint } = require('../util');

/**
 * Square geometry object
 *
 * @param {Object} map - Instance of MapboxGL Map
 * @param {Object} drawStore - The overall drawStore for this session
 * @param {Object} data - GeoJSON polygon feature
 * @return {Square} this
 */
function Square(map, drawStore, data) {

  this.initialize(map, drawStore, 'Polygon', data);

  // event handlers
  this.onMouseDown = this._onMouseDown.bind(this);
  this.onMouseMove = this._onMouseMove.bind(this);
  this.completeDraw = this._completeDraw.bind(this);

}

Square.prototype = xtend(Handler, {

  startDraw() {
    this._map.fire('draw.start', { featureType: 'square' });
    this._map.getContainer().classList.add('mapboxgl-draw-activated');
    this._map.getContainer().addEventListener('mousedown', this.onMouseDown, true);
  },

  _onMouseDown(e) {
    this._map.getContainer().removeEventListener('mousedown', this.onMouseDown, true);
    this._map.getContainer().addEventListener('mousemove', this.onMouseMove, true);

    var c = this._map.unproject([e.x, e.y]);
    var arr = [];
    var i = -1;
    while (++i < 5) {
      arr.push([ c.lng, c.lat]);
    }
    this.coordinates = this.coordinates.push(Immutable.fromJS(arr));
  },

  _onMouseMove(e) {
    e.stopPropagation();
    e.preventDefault();

    if (!this.started) {
      this.started = true;
      this._map.getContainer().addEventListener('mouseup', this.completeDraw, true);
    }

    var c = this._map.unproject([e.x, e.y]);
    var orig = this.coordinates.get(0).get(0);
    this.coordinates = this.coordinates.setIn([0, 1], [ orig.get(0), c.lat ]);
    this.coordinates = this.coordinates.setIn([0, 2], [ c.lng, c.lat ]);
    this.coordinates = this.coordinates.setIn([0, 3], [ c.lng, orig.get(1)]);

    this.feature = this.feature.setIn(['geometry', 'coordinates'], this.coordinates);
    this.store.update(this.feature.toJS());
  },

  _completeDraw() {
    this._map.getContainer().classList.remove('mapboxgl-draw-activated');
    this._map.getContainer().removeEventListener('mousemove', this.onMouseMove, true);
    this._map.getContainer().removeEventListener('mouseup', this.completeDraw, true);

    this._done('square');
  },

  moveVertex(init, curr, vertex) {
    if (!this.movingVertex) {
      this.movingVertex = true;

      var coords = vertex.geometry.coordinates;
      var diff = Infinity;

      var c = this.feature.getIn(['geometry', 'coordinates', 0]);

      for (var i = 0; i < c.size; i++) {
        var v = c.get(i);
        //var d = Math.sqrt(Math.pow(v.get(0) - coords[0], 2) + Math.pow(v.get(1) - coords[1], 2));
        var d = Math.abs(v.get(0) - coords[0]) + Math.abs(v.get(1) - coords[1]);
        if (d < diff) {
          this.vertexIdx = i;
          diff = d;
        }
      }

      this.initCoords = this.feature.getIn(['geometry', 'coordinates', 0, this.vertexIdx]);
    }

    var dx = curr.x - init.x;
    var dy = curr.y - init.y;
    var newPoint = translatePoint(this.initCoords.toJS(), dx, dy, this._map);

    this.feature = this.feature.setIn(['geometry', 'coordinates', 0, this.vertexIdx], Immutable.fromJS(newPoint));

    var x = newPoint[0];
    var y = newPoint[1];

    switch (this.vertexIdx) {
      case 0:
        this.feature = this._setV(1, [ x, this._getV(1).get(1) ]);
        this.feature = this._setV(3, [ this._getV(3).get(0), y ]);
        break;
      case 1:
        this.feature = this._setV(0, [ x, this._getV(0).get(1) ]);
        this.feature = this._setV(2, [ this._getV(2).get(0), y ]);
        break;
      case 2:
        this.feature = this._setV(1, [ this._getV(1).get(0), y ]);
        this.feature = this._setV(3, [ x, this._getV(3).get(1) ]);
        break;
      case 3:
        this.feature = this._setV(0, [ this._getV(0).get(0), y ]);
        this.feature = this._setV(2, [ x, this._getV(2).get(1) ]);
        break;
    }

    // always reset last point to equal the first point
    this.feature = this._setV(4, this._getV(0).toJS());

    this.store.update(this.feature.toJS());
  },

  /**
   * Given and index and a val, set that vertex in `this.feature`
   *
   * @param {Number} idx - index
   * @param {Array<Number>} val - new coordinates
   * @return {Object} an Immutable Map of a GeoJSON feature
   * @private
   */
  _setV(idx, val) {
    return this.feature.setIn(['geometry', 'coordinates', 0, idx], Immutable.fromJS(val));
  },

  /**
   * Given an index, returns the vertex in the features list of coordinates
   *
   * @param {Number} idx - index of the vertex you want
   * @return {Array<Number>} Immutable List
   * @private
   */
  _getV(idx) {
    return this.feature.getIn(['geometry', 'coordinates', 0, idx]);
  }

});

module.exports = Square;
<commit_msg>fix square for new vertex finding<commit_after>'use strict';

var Immutable = require('immutable');
var xtend = require('xtend');
var Handler = require('./handlers');
var { translatePoint } = require('../util');

/**
 * Square geometry object
 *
 * @param {Object} map - Instance of MapboxGL Map
 * @param {Object} drawStore - The overall drawStore for this session
 * @param {Object} data - GeoJSON polygon feature
 * @return {Square} this
 */
function Square(map, drawStore, data) {

  this.initialize(map, drawStore, 'Polygon', data);

  // event handlers
  this.onMouseDown = this._onMouseDown.bind(this);
  this.onMouseMove = this._onMouseMove.bind(this);
  this.completeDraw = this._completeDraw.bind(this);

}

Square.prototype = xtend(Handler, {

  startDraw() {
    this._map.fire('draw.start', { featureType: 'square' });
    this._map.getContainer().classList.add('mapboxgl-draw-activated');
    this._map.getContainer().addEventListener('mousedown', this.onMouseDown, true);
  },

  _onMouseDown(e) {
    this._map.getContainer().removeEventListener('mousedown', this.onMouseDown, true);
    this._map.getContainer().addEventListener('mousemove', this.onMouseMove, true);

    var c = this._map.unproject([e.x, e.y]);
    var arr = [];
    var i = -1;
    while (++i < 5) {
      arr.push([ c.lng, c.lat]);
    }
    this.coordinates = this.coordinates.push(Immutable.fromJS(arr));
  },

  _onMouseMove(e) {
    e.stopPropagation();
    e.preventDefault();

    if (!this.started) {
      this.started = true;
      this._map.getContainer().addEventListener('mouseup', this.completeDraw, true);
    }

    var c = this._map.unproject([e.x, e.y]);
    var orig = this.coordinates.get(0).get(0);
    this.coordinates = this.coordinates.setIn([0, 1], [ orig.get(0), c.lat ]);
    this.coordinates = this.coordinates.setIn([0, 2], [ c.lng, c.lat ]);
    this.coordinates = this.coordinates.setIn([0, 3], [ c.lng, orig.get(1)]);

    this.feature = this.feature.setIn(['geometry', 'coordinates'], this.coordinates);
    this.store.update(this.feature.toJS());
  },

  _completeDraw() {
    this._map.getContainer().classList.remove('mapboxgl-draw-activated');
    this._map.getContainer().removeEventListener('mousemove', this.onMouseMove, true);
    this._map.getContainer().removeEventListener('mouseup', this.completeDraw, true);

    this._done('square');
  },

  moveVertex(init, curr, idx) {
    if (!this.movingVertex) {
      this.movingVertex = true;
      this.initCoords = this.feature.getIn(['geometry', 'coordinates', 0, idx]);
    }

    var dx = curr.x - init.x;
    var dy = curr.y - init.y;
    var newPoint = translatePoint(this.initCoords.toJS(), dx, dy, this._map);

    this.feature = this.feature.setIn(['geometry', 'coordinates', 0, idx], Immutable.fromJS(newPoint));

    var x = newPoint[0];
    var y = newPoint[1];

    switch (idx) {
      case 0:
        this.feature = this._setV(1, [ x, this._getV(1).get(1) ]);
        this.feature = this._setV(3, [ this._getV(3).get(0), y ]);
        break;
      case 1:
        this.feature = this._setV(0, [ x, this._getV(0).get(1) ]);
        this.feature = this._setV(2, [ this._getV(2).get(0), y ]);
        break;
      case 2:
        this.feature = this._setV(1, [ this._getV(1).get(0), y ]);
        this.feature = this._setV(3, [ x, this._getV(3).get(1) ]);
        break;
      case 3:
        this.feature = this._setV(0, [ this._getV(0).get(0), y ]);
        this.feature = this._setV(2, [ x, this._getV(2).get(1) ]);
        break;
    }

    // always reset last point to equal the first point
    this.feature = this._setV(4, this._getV(0).toJS());

    this.store.update(this.feature.toJS());
  },

  /**
   * Given and index and a val, set that vertex in `this.feature`
   *
   * @param {Number} idx - index
   * @param {Array<Number>} val - new coordinates
   * @return {Object} an Immutable Map of a GeoJSON feature
   * @private
   */
  _setV(idx, val) {
    return this.feature.setIn(['geometry', 'coordinates', 0, idx], Immutable.fromJS(val));
  },

  /**
   * Given an index, returns the vertex in the features list of coordinates
   *
   * @param {Number} idx - index of the vertex you want
   * @return {Array<Number>} Immutable List
   * @private
   */
  _getV(idx) {
    return this.feature.getIn(['geometry', 'coordinates', 0, idx]);
  }

});

module.exports = Square;
<|endoftext|>


<commit_before>define(function (require, exports) {
	'use strict';

	/**
	 * Bracket modules
	 */
	var CommandManager = brackets.getModule('command/CommandManager');
	var Dialog = brackets.getModule('widgets/Dialogs');
	var Project = brackets.getModule('project/ProjectManager');
	var FileUtils = brackets.getModule('file/FileUtils');

	/**
	 * Extension modules
	 */
	var osFtpCommon = require('src/common');
	var osFtpDomain  = require('src/domain');
	var osFtpHandlers = require('src/handlers');
	var osFtpGlobals = require('src/globals');
	var osFtpMenu = require('src/menu');
	var osFtpPackage = require('src/package');
	var osFtpScripts = require('src/scripts');
	var osFtpStrings = require('strings');
	var osFtpSelectDialog = require('src/listSelectionDialog');
	var osFtpSitesManager = require('src/sitesManager');

	/**
	 * Global variables
	 */
	var osFtpPreferences;

	/**
	 * Exported functions
	 */
	exports.addSite    = addSite;
	exports.removeSite = removeSite;
	exports.enableEditSite = enableEditSite;
	exports.disableEditSite = disableEditSite;
	exports.invokeFtpScript = invokeFtpScript;
	exports.uploadDirectory = uploadDirectory;
	exports.handleCancel = handleCancel;
	exports.handleEscape = handleEscape;
	exports.disableListeners = disableListeners;
	exports.setAndSavePref = setAndSavePref;

	/**
	 * Add a site by registering the site as a command and adding it to the context menus
	 * @param {Object} site Site object containing information about this site
	 */
	function addSite(site) {

		//log this call
		osFtpCommon.consoleDebug('handlersHelpers.addSite(' + site.name + ');');

		if (osFtpSitesManager.getSitesArray().length > 0){
			enableEditSite();
			enableFtpProject();
		}

		osFtpPackage.getPackage(function(packageJson, cmdId, cmdLabel) {

			var newCmdId = packageJson.name + cmdId;
			var editId = packageJson.name + osFtpGlobals.COMMAND_EDIT_SITE_ID;

			//register command and add a context menu to create a site
			CommandManager.register(cmdLabel, newCmdId, osFtpHandlers.handleRunSite);
			osFtpMenu.addToContextMenus(newCmdId, false, editId, false);

		}, site.getCommandId(), site.getCommandLabel());
	}

	/**
	 * Remove a site from menu
	 *
	 */

	function removeSite(site) {
		osFtpCommon.consoleDebug('handlersHelpers.remove(' + site.name + ')');

		//remove site from context menu
		osFtpPackage.getPackage(function(packageJson, cmdId) {

			var newCmdId = packageJson.name + cmdId;

			//register command and add a context menu to create a site
			osFtpMenu.removeFromContextMenus(newCmdId);

		}, site.getCommandId());

		if (osFtpSitesManager.getSitesArray().length === 0){
			disableEditSite();
			disableFtpProject();
		}
	}

	/**
	 * Enables the edit command for an added site
	 */
	function enableEditSite() {

		//log this call
		osFtpCommon.consoleDebug('enableEditSite();');

		osFtpPackage.getPackage(function(packageJson) {

			var editId = packageJson.name + osFtpGlobals.COMMAND_EDIT_SITE_ID;
			var newId = packageJson.name + osFtpGlobals.COMMAND_NEW_SITE_ID;

			//register command and add a context menu to create a site
			CommandManager.register(osFtpStrings.COMMAND_EDIT_SITE_LABEL, editId, osFtpHandlers.handleEditSite);
			osFtpMenu.addToContextMenus(editId, false, newId, false);
		});
	}

	/**
	 * Disables the edit command for sites (cannot deregister the command)
	 */
	function disableEditSite() {
		//log this call
		osFtpCommon.consoleDebug('handlersHelpers.disableEditSite();');

		osFtpPackage.getPackage(function(packageJson) {

			var editId = packageJson.name + osFtpGlobals.COMMAND_EDIT_SITE_ID;

			//remove from the menu
			osFtpMenu.removeFromContextMenus(editId);
		});
	}

	/**
     * Enable the FTP project command
	 **/
	function enableFtpProject(){
		osFtpCommon.consoleDebug('enableFtpProject()');

		osFtpPackage.getPackage(function(packageJson) {

			var editId    = packageJson.name + osFtpGlobals.COMMAND_EDIT_SITE_ID;
			var ftpSiteId = packageJson.name + osFtpGlobals.COMMAND_FTP_PROJECT_ID;

			//register command and add a context menu to create a site
			CommandManager.register(osFtpStrings.COMMAND_FTP_PROJECT_LABEL, ftpSiteId, osFtpHandlers.handleUploadProject);
			osFtpMenu.addToContextMenus(ftpSiteId, false, editId, false);
		});
	}

	/**
	 * Disable FTP project command
	 **/
	function disableFtpProject(){
		osFtpCommon.consoleDebug('disableFtpProject()');

		osFtpPackage.getPackage(function(packageJson) {
			var ftpProjectId = packageJson.name + osFtpGlobals.COMMAND_FTP_PROJECT_ID;

			//remove from the menu
			osFtpMenu.removeFromContextMenus(ftpProjectId);
		});
	}

	/**
	 * [[Description]]
	 * @param {Object} site Object representing the site to upload to
	 */
	function invokeFtpScript(ftpScript, length) {

		//if the script is defined
		if (osFtpCommon.isSet(ftpScript)) {

			//select the file name we want to create
			var scriptFileName = osFtpGlobals.FTP_SCRIPT_FILE_NAME + osFtpGlobals.FTP_SCRIPT_FILE_EXTENSION;

			//invoke node js to build and run our ftp script file
			osFtpDomain.runFtpCommandStdin(length, scriptFileName, ftpScript);

		}
	}

	/**
	 * [[Description]]
	 * @param {Object} site Object representing the site to upload to
	 */
	function uploadDirectory(site, fileList) {
		osFtpCommon.consoleDebug("handlersHelpers.uploadDirectory()");

		//show dialog
		var dlgInputList = [];
		var rootDir = osFtpStrings.SELECTED_EMPTY;
		if (fileList.length > 0){
			rootDir = Project.getProjectRoot().fullPath;

			for (var index = 0; index < fileList.length; index++){
				dlgInputList.push(FileUtils.getRelativeFilename(rootDir, fileList[index].fullPath));
			}
		}

		var selectDialog = osFtpSelectDialog.newDialog(dlgInputList, rootDir);
		selectDialog.show();
		selectDialog.collapseAll();
		selectDialog.checkAll();

		selectDialog.dialog.done(function(buttonId){
			if (buttonId === 'ok'){
				//log that we are saving this site
				osFtpCommon.consoleDebug('Dialog closed with save');

				var selectedList = selectDialog.getSelectedList();
				fileList = [];
				for (var index in selectedList){
					var obj = osFtpCommon.relativePathToFile(selectedList[index], rootDir);
					fileList.push(obj);
				}

				osFtpCommon.consoleDebug(fileList);
				//build our ftp script
				var ftpScript = osFtpScripts.generateUploadScript(fileList, site);

				//invoke script
				invokeFtpScript(ftpScript, fileList.length);
			}
		});
	}

	/**
	 * Handle CANCEL button for all dialogs
	 * @param {Object} dialog Dialog object
	 */
	function handleCancel(dialog) {

		//listen for cancel (modal doesnt have standard id= attribute, it's data-button-id
		$('button[data-button-id="' + Dialog.DIALOG_BTN_CANCEL + '"').click(function () {

			//log that the user wants to close
			osFtpCommon.consoleDebug('Dialog closed without save');

			//turn off listeners
			disableListeners();

			//close the dialog
			dialog.close();

		});

	}

	/**
	 * Handle escape button for all dialogs
	 * @param {Object} dialog Dialog object
	 */
	function handleEscape(dialog) {

		//listener for escape key
		$(document).keyup(function (event) {

			//close if escape key is pressed
			if (event.which == osFtpGlobals.ESCAPE_KEY) {

				//log that the user wants to close
				osFtpCommon.consoleDebug('Dialog escaped without save');

				//turn off listeners
				disableListeners();

				//close the dialog
				dialog.close();

			}

		});

	}

	/**
	 * Disable all active listeners
	 */
	function disableListeners() {

		//turn off OK listener
		$('button[data-button-id="' + Dialog.DIALOG_BTN_OK + '"').off('click');

		//turn off ESCAPE listener
		$(document).off('keyup');

		//turn off CANCEL listener
		$('button[data-button-id="' + Dialog.DIALOG_BTN_CANCEL + '"').off('click');

	}

	/**
	 * Set a preference value with its key and save
	 * @param {String} prefFile Preference file
	 * @param {String} key      Preference key value
	 * @param {Object} value    Any variable type associated with the key
	 */
	function setAndSavePref(prefFile, key, value) {

		//set in preferences
		osFtpPreferences.set(key, value);

		//save
		osFtpPreferences.save(prefFile);
	}

});
<commit_msg>I hate For in loop!!!!<commit_after>define(function (require, exports) {
	'use strict';

	/**
	 * Bracket modules
	 */
	var CommandManager = brackets.getModule('command/CommandManager');
	var Dialog = brackets.getModule('widgets/Dialogs');
	var Project = brackets.getModule('project/ProjectManager');
	var FileUtils = brackets.getModule('file/FileUtils');

	/**
	 * Extension modules
	 */
	var osFtpCommon = require('src/common');
	var osFtpDomain  = require('src/domain');
	var osFtpHandlers = require('src/handlers');
	var osFtpGlobals = require('src/globals');
	var osFtpMenu = require('src/menu');
	var osFtpPackage = require('src/package');
	var osFtpScripts = require('src/scripts');
	var osFtpStrings = require('strings');
	var osFtpSelectDialog = require('src/listSelectionDialog');
	var osFtpSitesManager = require('src/sitesManager');

	/**
	 * Global variables
	 */
	var osFtpPreferences;

	/**
	 * Exported functions
	 */
	exports.addSite    = addSite;
	exports.removeSite = removeSite;
	exports.enableEditSite = enableEditSite;
	exports.disableEditSite = disableEditSite;
	exports.invokeFtpScript = invokeFtpScript;
	exports.uploadDirectory = uploadDirectory;
	exports.handleCancel = handleCancel;
	exports.handleEscape = handleEscape;
	exports.disableListeners = disableListeners;
	exports.setAndSavePref = setAndSavePref;

	/**
	 * Add a site by registering the site as a command and adding it to the context menus
	 * @param {Object} site Site object containing information about this site
	 */
	function addSite(site) {

		//log this call
		osFtpCommon.consoleDebug('handlersHelpers.addSite(' + site.name + ');');

		if (osFtpSitesManager.getSitesArray().length > 0){
			enableEditSite();
			enableFtpProject();
		}

		osFtpPackage.getPackage(function(packageJson, cmdId, cmdLabel) {

			var newCmdId = packageJson.name + cmdId;
			var editId = packageJson.name + osFtpGlobals.COMMAND_EDIT_SITE_ID;

			//register command and add a context menu to create a site
			CommandManager.register(cmdLabel, newCmdId, osFtpHandlers.handleRunSite);
			osFtpMenu.addToContextMenus(newCmdId, false, editId, false);

		}, site.getCommandId(), site.getCommandLabel());
	}

	/**
	 * Remove a site from menu
	 *
	 */

	function removeSite(site) {
		osFtpCommon.consoleDebug('handlersHelpers.remove(' + site.name + ')');

		//remove site from context menu
		osFtpPackage.getPackage(function(packageJson, cmdId) {

			var newCmdId = packageJson.name + cmdId;

			//register command and add a context menu to create a site
			osFtpMenu.removeFromContextMenus(newCmdId);

		}, site.getCommandId());

		if (osFtpSitesManager.getSitesArray().length === 0){
			disableEditSite();
			disableFtpProject();
		}
	}

	/**
	 * Enables the edit command for an added site
	 */
	function enableEditSite() {

		//log this call
		osFtpCommon.consoleDebug('enableEditSite();');

		osFtpPackage.getPackage(function(packageJson) {

			var editId = packageJson.name + osFtpGlobals.COMMAND_EDIT_SITE_ID;
			var newId = packageJson.name + osFtpGlobals.COMMAND_NEW_SITE_ID;

			//register command and add a context menu to create a site
			CommandManager.register(osFtpStrings.COMMAND_EDIT_SITE_LABEL, editId, osFtpHandlers.handleEditSite);
			osFtpMenu.addToContextMenus(editId, false, newId, false);
		});
	}

	/**
	 * Disables the edit command for sites (cannot deregister the command)
	 */
	function disableEditSite() {
		//log this call
		osFtpCommon.consoleDebug('handlersHelpers.disableEditSite();');

		osFtpPackage.getPackage(function(packageJson) {

			var editId = packageJson.name + osFtpGlobals.COMMAND_EDIT_SITE_ID;

			//remove from the menu
			osFtpMenu.removeFromContextMenus(editId);
		});
	}

	/**
     * Enable the FTP project command
	 **/
	function enableFtpProject(){
		osFtpCommon.consoleDebug('enableFtpProject()');

		osFtpPackage.getPackage(function(packageJson) {

			var editId    = packageJson.name + osFtpGlobals.COMMAND_EDIT_SITE_ID;
			var ftpSiteId = packageJson.name + osFtpGlobals.COMMAND_FTP_PROJECT_ID;

			//register command and add a context menu to create a site
			CommandManager.register(osFtpStrings.COMMAND_FTP_PROJECT_LABEL, ftpSiteId, osFtpHandlers.handleUploadProject);
			osFtpMenu.addToContextMenus(ftpSiteId, false, editId, false);
		});
	}

	/**
	 * Disable FTP project command
	 **/
	function disableFtpProject(){
		osFtpCommon.consoleDebug('disableFtpProject()');

		osFtpPackage.getPackage(function(packageJson) {
			var ftpProjectId = packageJson.name + osFtpGlobals.COMMAND_FTP_PROJECT_ID;

			//remove from the menu
			osFtpMenu.removeFromContextMenus(ftpProjectId);
		});
	}

	/**
	 * [[Description]]
	 * @param {Object} site Object representing the site to upload to
	 */
	function invokeFtpScript(ftpScript, length) {

		//if the script is defined
		if (osFtpCommon.isSet(ftpScript)) {

			//select the file name we want to create
			var scriptFileName = osFtpGlobals.FTP_SCRIPT_FILE_NAME + osFtpGlobals.FTP_SCRIPT_FILE_EXTENSION;

			//invoke node js to build and run our ftp script file
			osFtpDomain.runFtpCommandStdin(length, scriptFileName, ftpScript);

		}
	}

	/**
	 * [[Description]]
	 * @param {Object} site Object representing the site to upload to
	 */
	function uploadDirectory(site, fileList) {
		osFtpCommon.consoleDebug("handlersHelpers.uploadDirectory()");

		//show dialog
		var dlgInputList = [];
		var rootDir = osFtpStrings.SELECTED_EMPTY;
		if (fileList.length > 0){
			rootDir = Project.getProjectRoot().fullPath;

			for (var index = 0; index < fileList.length; index++){
				dlgInputList.push(FileUtils.getRelativeFilename(rootDir, fileList[index].fullPath));
			}
		}

		var selectDialog = osFtpSelectDialog.newDialog(dlgInputList, rootDir);
		selectDialog.show();
		selectDialog.collapseAll();
		selectDialog.checkAll();

		selectDialog.dialog.done(function(buttonId){
			if (buttonId === 'ok'){
				//log that we are saving this site
				osFtpCommon.consoleDebug('Dialog closed with save');

				var selectedList = selectDialog.getSelectedList();
				fileList = [];
				for (var index = 0; index < selectedList.length; index++){
					var obj = osFtpCommon.relativePathToFile(selectedList[index], rootDir);
					fileList.push(obj);
				}

				osFtpCommon.consoleDebug(fileList);
				//build our ftp script
				var ftpScript = osFtpScripts.generateUploadScript(fileList, site);

				//invoke script
				invokeFtpScript(ftpScript, fileList.length);
			}
		});
	}

	/**
	 * Handle CANCEL button for all dialogs
	 * @param {Object} dialog Dialog object
	 */
	function handleCancel(dialog) {

		//listen for cancel (modal doesnt have standard id= attribute, it's data-button-id
		$('button[data-button-id="' + Dialog.DIALOG_BTN_CANCEL + '"').click(function () {

			//log that the user wants to close
			osFtpCommon.consoleDebug('Dialog closed without save');

			//turn off listeners
			disableListeners();

			//close the dialog
			dialog.close();

		});

	}

	/**
	 * Handle escape button for all dialogs
	 * @param {Object} dialog Dialog object
	 */
	function handleEscape(dialog) {

		//listener for escape key
		$(document).keyup(function (event) {

			//close if escape key is pressed
			if (event.which == osFtpGlobals.ESCAPE_KEY) {

				//log that the user wants to close
				osFtpCommon.consoleDebug('Dialog escaped without save');

				//turn off listeners
				disableListeners();

				//close the dialog
				dialog.close();

			}

		});

	}

	/**
	 * Disable all active listeners
	 */
	function disableListeners() {

		//turn off OK listener
		$('button[data-button-id="' + Dialog.DIALOG_BTN_OK + '"').off('click');

		//turn off ESCAPE listener
		$(document).off('keyup');

		//turn off CANCEL listener
		$('button[data-button-id="' + Dialog.DIALOG_BTN_CANCEL + '"').off('click');

	}

	/**
	 * Set a preference value with its key and save
	 * @param {String} prefFile Preference file
	 * @param {String} key      Preference key value
	 * @param {Object} value    Any variable type associated with the key
	 */
	function setAndSavePref(prefFile, key, value) {

		//set in preferences
		osFtpPreferences.set(key, value);

		//save
		osFtpPreferences.save(prefFile);
	}

});
<|endoftext|>


<commit_before>(function() {

  var breakpoints = { width: [ ], height: [ ] };

	(function() {
		parseCssGetBreakpoints( );
		createActionPanel( );
	})();

	function parseCssGetBreakpoints( ) {

		var mediaSizeSelectorsInPx = [ ];

		(function() {
			parseCssGetMediaSizeSelectorsInPx( );
			for ( var i=0; i<mediaSizeSelectorsInPx.length; i++ ) {
				var breakpoint = getBreakpointFromMediaSizeSelector( mediaSizeSelectorsInPx[ i ] );
				if (
					typeof( breakpoint.type ) != 'undefined' &&
					breakpoints[ breakpoint.type ].indexOf( breakpoint.px ) == -1
				) {
					breakpoints[ breakpoint.type ].push( breakpoint.px );
				}
			}
			breakpoints.width = breakpoints.width.sort(function(a, b){return a - b;});
			breakpoints.height = breakpoints.height.sort(function(a, b){return a - b;});
		})();

		function parseCssGetMediaSizeSelectorsInPx( ) {

			var emToPxRatio;
			var mediaSizeSelectors = [ ];

			(function() {
				emToPxRatio = getEmInPxRatio( );
				parseCssGetMediaSizeSelectors( );
				for ( var i=0; i<mediaSizeSelectors.length; i++ ) {
					mediaSizeSelectorsInPx[ i ] = mediaSizeSelectors[ i ];
					mediaSizeSelectorsInPx[ i ].px = convertSizeInPixel( mediaSizeSelectors[ i ].value );
				}
			})();

			function parseCssGetMediaSizeSelectors( ) {

				(function() {
					var mediaSelectors = parseCssGetMediaSelectors( );
					for( var i=0; i<mediaSelectors.length; i++ ) {
						addMediaSizeSelectorsFromMediaSelector( mediaSelectors[ i ] );
					}
				})();

				function parseCssGetMediaSelectors( ) {

					return (function() {
						var rules = parseCssGetRules( );
						var mediaSelectors = [ ];
						for( var i=0; i<rules.length; i++ ) {
							if ( isMediaRule( rules[ i ] ) ) {
								mediaSelectors.push( rules[ i ].media.mediaText );
							}
						}
						return mediaSelectors;
					})();

					function parseCssGetRules( ) {
						var rules = [ ];
						for( var i=0; i<document.styleSheets.length; i++ ) {
							try {
								for( var j=0; j<document.styleSheets[ i ].cssRules.length; j++ ) {
									rules.push( document.styleSheets[ i ].cssRules[ j ] );
								}
							} catch ( exception ) {
								// External stylesheet
							}
						}
						return rules;
					}

					function isMediaRule( rule ) {
						return ( typeof( rule.media ) != 'undefined' );
					}
				}

				function addMediaSizeSelectorsFromMediaSelector( mediaSelector ) {

					(function() {
						var mediaSelectorParts = mediaSelector.split( '(' );
						for ( var i=1; i<mediaSelectorParts.length; i++ ) {
							if ( isMediaRulePartASizeSelector( mediaSelectorParts[ i ] ) ) {
								mediaSizeSelectors.push( getSizeSelectorFromMediaSelectorPart( mediaSelectorParts[ i ] ) );
							}
						}
					})();

					function isMediaRulePartASizeSelector( mediaSelectorPart ) {
						return ( mediaSelectorPart.indexOf( ':' ) != -1 );
					}

					function getSizeSelectorFromMediaSelectorPart( mediaSelectorPart ) {
						return {
							property: mediaSelectorPart.split( ':' )[ 0 ].trim( ),
							value: mediaSelectorPart.split( ':' )[ 1 ].split( ')' )[ 0 ].trim( )
						};
					}
				}
			}

			function convertSizeInPixel( size ) {

				var size = size;

				return (function() {
					extractUnitFromSize( );
					convertEmToPixel( );
					return roundPixel( );
				})();

				function extractUnitFromSize( ) {
					size = {
						number: Number( size.replace( /[^\d\.]/g, '' ) ),
						unit: size.replace( /[\d\.]/g, '' )
					};
				}

				function convertEmToPixel( ) {
					if ( size.unit == 'em' || size.unit == 'rem' ) {
						size = size.number * emToPxRatio;
					} else if ( size.unit == 'px' ) {
						size = size.number;
					}
				}

				function roundPixel( ) {
					return Math.round(size*100)/100;
				}
			}

			function getEmInPxRatio( ) {
				return Number( getComputedStyle( document.body.parentNode, null).fontSize.replace( /[^\d\.]/g, '' ) );
			}
		}

		function getBreakpointFromMediaSizeSelector( mediaSizeSelectorInPx ) {
			var breakpoint = { };
			if ( typeof ( mediaSizeSelectorInPx.px ) != 'undefined' ) {
				breakpoint.px = mediaSizeSelectorInPx.px;
				if ( mediaSizeSelectorInPx.property == 'min-width' ||  mediaSizeSelectorInPx.property == 'min-height' ) {
					breakpoint.px--;
				}
				breakpoint.px = Math.ceil(breakpoint.px);
				if ( breakpoint.px > 0 ) {
					if ( mediaSizeSelectorInPx.property == 'max-width' ||  mediaSizeSelectorInPx.property == 'min-width' ) {
						breakpoint.type = 'width';
					} else if ( mediaSizeSelectorInPx.property == 'max-height' ||  mediaSizeSelectorInPx.property == 'min-height' ) {
						breakpoint.type = 'height';
					}
				}
			}
			return breakpoint;
		}
	}

	function createActionPanel( ) {

		var fluidZones = { width: [ ], height: [ ] };

		(function() {
			getFluidZonesFromBreakpoints( );
			displayFluidZonesActionPanel( );
		})();

        function getFluidZonesFromBreakpoints( ) {

            (function() {
                formatFluidZonesByDirection( 'width' );
                formatFluidZonesByDirection( 'height' );
            })();

            function formatFluidZonesByDirection( direction ) {
                if ( breakpoints[ direction ].length != 0 ) {
                    var old;
                    for ( var i=0; i<breakpoints[ direction ].length; i++ ) {
                        var point = breakpoints[ direction ][ i ] ;
                        var zone = [ ];
                        if ( old == null ) {
                            zone.push( null );
                        } else if ( old + 1 != point ) {
                            zone.push( old + 1 );
                        }
                        zone.push( point );
                        fluidZones[ direction ].push( zone );
                        old = point;
                    }
                    fluidZones[ direction ].push( [ old + 1, '← ' + direction ] );
                }
            }
        }
		function displayFluidZonesActionPanel( ) {

			var resizedWindow;

			(function() {
				var panel = createPanelElement( );
				if ( breakpoints.width.length == 0 && breakpoints.height.length == 0 ) {
					panel.addInformationToPanel( 'No breakpoint found' );
				} else {
					for ( var j=0; j<fluidZones.height.length; j++ ) {
						panel.addFluidZoneToPanel( 'height', fluidZones.height[ j ] );
						panel.addBreakLineToPanel( );
					}
					panel.addFluidZoneToPanel( 'no', ' ' );
					for ( var i=fluidZones.width.length-1; i>-1; i-- ) {
						panel.addFluidZoneToPanel( 'width', fluidZones.width[ i ] );
					}
					panel.addBreakLineToPanel( );
				}
			})();

			function createPanelElement( ) {

				// internal
				var panel = document.getElementById( 'panelResize' );
				if ( panel == null ) {
					panel = document.createElement( 'div' );
					panel.setAttribute( 'id', 'panelResize' );
					panel.setAttribute( 'style', 'position: fixed; bottom:10px; right: 10px; z-index: 999999; text-align: left;' );
					document.body.appendChild( panel );
				}

				// private panel methods
				function addPanelElement( element ) {
					element.setAttribute( 'style', 'text-align: center; background: rgba(0, 0, 0, 0.8); border-radius: 10px; padding: 10px; margin: 0 0 2px 2px; min-width: 80px; box-sizing: content-box; -moz-box-sizing: content-box; float: right; color: white; font-weight: normal; font-size: 16px; line-height: 16px; ' );
					panel.appendChild( element );
				}

				// public panel methods
				return {
					addFluidZoneToPanel: function( direction, values ) {

						var values = values;

						(function() {
							var zone = document.createElement( 'span' );
							zone.innerHTML = ' ';
							for ( var i=0; i<values.length; i++ ) {
								zone.appendChild( createResizeElement( i ) );
							}
							addPanelElement( zone );
						})();

						function createResizeElement( i ) {

							var element;

							return (function() {
								if ( typeof( values[ i ] ) == 'number' ) {
									createResizeButtonElement( i );
								} else {
									createResizeTextElement( );
								}
								element.innerHTML = values[ i ];
								element.setAttribute( 'style', 'color: white; font-weight: bold; font-size: 16px; text-decoration: none; border: 0; float: ' + ( values.length == 1 ? 'none' : i == 0 ? 'left' : 'right' ) );
								return element;
							})();

							function createResizeTextElement( ) {
								element = document.createElement( 'span' );
							}

							function createResizeButtonElement( ) {
								element = document.createElement( 'a' );
								element.setAttribute( 'href', 'javascript:;' );
								element.addEventListener( 'click', function( ) {
									var size = { };
									var alternate = direction == 'width' ? 'height' : 'width';
									var Direction = direction.charAt( 0 ).toUpperCase( ) + direction.substr( 1 );
									var Alternate = alternate.charAt( 0 ).toUpperCase( ) + alternate.substr( 1 );
									var existingPopup = ( resizedWindow != null && ! resizedWindow.closed );
									size[ alternate ] = 600;
									if ( existingPopup ) {
										size[ alternate ] = resizedWindow[ 'outer' + Alternate ];
										resizedWindow.close( );
									}
									resizedWindow = window.open( window.location + '#', 'resized', 'resizable,scrollbars=1,width=800,height=600' );
									var resizePopup = function( ) {
										var innerSize;
										if ( /AppleWebKit/.test(navigator.userAgent) ) {
											innerSize = resizedWindow.document.documentElement[ 'client' + Direction ];
										} else {
											innerSize = resizedWindow[ 'inner' + Direction ];
										}
										size[ direction ] = values[ i ] + resizedWindow[ 'outer' + Direction ] - innerSize;
										resizedWindow.resizeTo( size.width, size.height );
										resizedWindow.focus( );
									};
									var interval = setInterval( function( ) {
										if ( resizedWindow.document.readyState !== 'complete' ) {
											clearInterval( interval );
											resizePopup( );
										}
									}, 100);
								}, false );
							}
						}
					},
					addInformationToPanel: function( message ) {
						var information = document.createElement( 'span' );
						information.innerHTML = message;
						addPanelElement( information );
					},
					addBreakLineToPanel: function( ) {
						var br = document.createElement( 'br' );
						br.setAttribute( 'style', 'clear: both' );
						panel.appendChild( br );
					}
				}
			}
		}
	}
})();

<commit_msg>Add a link to the project page<commit_after>(function() {

  var breakpoints = { width: [ ], height: [ ] };

	(function() {
		parseCssGetBreakpoints( );
		createActionPanel( );
	})();

	function parseCssGetBreakpoints( ) {

		var mediaSizeSelectorsInPx = [ ];

		(function() {
			parseCssGetMediaSizeSelectorsInPx( );
			for ( var i=0; i<mediaSizeSelectorsInPx.length; i++ ) {
				var breakpoint = getBreakpointFromMediaSizeSelector( mediaSizeSelectorsInPx[ i ] );
				if (
					typeof( breakpoint.type ) != 'undefined' &&
					breakpoints[ breakpoint.type ].indexOf( breakpoint.px ) == -1
				) {
					breakpoints[ breakpoint.type ].push( breakpoint.px );
				}
			}
			breakpoints.width = breakpoints.width.sort(function(a, b){return a - b;});
			breakpoints.height = breakpoints.height.sort(function(a, b){return a - b;});
		})();

		function parseCssGetMediaSizeSelectorsInPx( ) {

			var emToPxRatio;
			var mediaSizeSelectors = [ ];

			(function() {
				emToPxRatio = getEmInPxRatio( );
				parseCssGetMediaSizeSelectors( );
				for ( var i=0; i<mediaSizeSelectors.length; i++ ) {
					mediaSizeSelectorsInPx[ i ] = mediaSizeSelectors[ i ];
					mediaSizeSelectorsInPx[ i ].px = convertSizeInPixel( mediaSizeSelectors[ i ].value );
				}
			})();

			function parseCssGetMediaSizeSelectors( ) {

				(function() {
					var mediaSelectors = parseCssGetMediaSelectors( );
					for( var i=0; i<mediaSelectors.length; i++ ) {
						addMediaSizeSelectorsFromMediaSelector( mediaSelectors[ i ] );
					}
				})();

				function parseCssGetMediaSelectors( ) {

					return (function() {
						var rules = parseCssGetRules( );
						var mediaSelectors = [ ];
						for( var i=0; i<rules.length; i++ ) {
							if ( isMediaRule( rules[ i ] ) ) {
								mediaSelectors.push( rules[ i ].media.mediaText );
							}
						}
						return mediaSelectors;
					})();

					function parseCssGetRules( ) {
						var rules = [ ];
						for( var i=0; i<document.styleSheets.length; i++ ) {
							try {
								for( var j=0; j<document.styleSheets[ i ].cssRules.length; j++ ) {
									rules.push( document.styleSheets[ i ].cssRules[ j ] );
								}
							} catch ( exception ) {
								// External stylesheet
							}
						}
						return rules;
					}

					function isMediaRule( rule ) {
						return ( typeof( rule.media ) != 'undefined' );
					}
				}

				function addMediaSizeSelectorsFromMediaSelector( mediaSelector ) {

					(function() {
						var mediaSelectorParts = mediaSelector.split( '(' );
						for ( var i=1; i<mediaSelectorParts.length; i++ ) {
							if ( isMediaRulePartASizeSelector( mediaSelectorParts[ i ] ) ) {
								mediaSizeSelectors.push( getSizeSelectorFromMediaSelectorPart( mediaSelectorParts[ i ] ) );
							}
						}
					})();

					function isMediaRulePartASizeSelector( mediaSelectorPart ) {
						return ( mediaSelectorPart.indexOf( ':' ) != -1 );
					}

					function getSizeSelectorFromMediaSelectorPart( mediaSelectorPart ) {
						return {
							property: mediaSelectorPart.split( ':' )[ 0 ].trim( ),
							value: mediaSelectorPart.split( ':' )[ 1 ].split( ')' )[ 0 ].trim( )
						};
					}
				}
			}

			function convertSizeInPixel( size ) {

				var size = size;

				return (function() {
					extractUnitFromSize( );
					convertEmToPixel( );
					return roundPixel( );
				})();

				function extractUnitFromSize( ) {
					size = {
						number: Number( size.replace( /[^\d\.]/g, '' ) ),
						unit: size.replace( /[\d\.]/g, '' )
					};
				}

				function convertEmToPixel( ) {
					if ( size.unit == 'em' || size.unit == 'rem' ) {
						size = size.number * emToPxRatio;
					} else if ( size.unit == 'px' ) {
						size = size.number;
					}
				}

				function roundPixel( ) {
					return Math.round(size*100)/100;
				}
			}

			function getEmInPxRatio( ) {
				return Number( getComputedStyle( document.body.parentNode, null).fontSize.replace( /[^\d\.]/g, '' ) );
			}
		}

		function getBreakpointFromMediaSizeSelector( mediaSizeSelectorInPx ) {
			var breakpoint = { };
			if ( typeof ( mediaSizeSelectorInPx.px ) != 'undefined' ) {
				breakpoint.px = mediaSizeSelectorInPx.px;
				if ( mediaSizeSelectorInPx.property == 'min-width' ||  mediaSizeSelectorInPx.property == 'min-height' ) {
					breakpoint.px--;
				}
				breakpoint.px = Math.ceil(breakpoint.px);
				if ( breakpoint.px > 0 ) {
					if ( mediaSizeSelectorInPx.property == 'max-width' ||  mediaSizeSelectorInPx.property == 'min-width' ) {
						breakpoint.type = 'width';
					} else if ( mediaSizeSelectorInPx.property == 'max-height' ||  mediaSizeSelectorInPx.property == 'min-height' ) {
						breakpoint.type = 'height';
					}
				}
			}
			return breakpoint;
		}
	}

	function createActionPanel( ) {

		var fluidZones = { width: [ ], height: [ ] };

		(function() {
			getFluidZonesFromBreakpoints( );
			displayFluidZonesActionPanel( );
		})();

        function getFluidZonesFromBreakpoints( ) {

            (function() {
                formatFluidZonesByDirection( 'width' );
                formatFluidZonesByDirection( 'height' );
            })();

            function formatFluidZonesByDirection( direction ) {
                if ( breakpoints[ direction ].length != 0 ) {
                    var old;
                    for ( var i=0; i<breakpoints[ direction ].length; i++ ) {
                        var point = breakpoints[ direction ][ i ] ;
                        var zone = [ ];
                        if ( old == null ) {
                            zone.push( null );
                        } else if ( old + 1 != point ) {
                            zone.push( old + 1 );
                        }
                        zone.push( point );
                        fluidZones[ direction ].push( zone );
                        old = point;
                    }
                    fluidZones[ direction ].push( [ old + 1, '← ' + direction ] );
                }
            }
        }
		function displayFluidZonesActionPanel( ) {

			var resizedWindow;

			(function() {
				var panel = createPanelElement( );
				if ( breakpoints.width.length == 0 && breakpoints.height.length == 0 ) {
					panel.addInformationToPanel( 'No breakpoint found' );
				} else {
					for ( var j=0; j<fluidZones.height.length; j++ ) {
						panel.addFluidZoneToPanel( 'height', fluidZones.height[ j ] );
						panel.addBreakLineToPanel( );
					}
					panel.addFluidZoneToPanel( 'no', ['Breaq'], 'http://tzi.fr/CSS/Responsive/Breaq-bookmarklet' );
					for ( var i=fluidZones.width.length-1; i>-1; i-- ) {
						panel.addFluidZoneToPanel( 'width', fluidZones.width[ i ] );
					}
					panel.addBreakLineToPanel( );
				}
			})();

			function createPanelElement( ) {

				// internal
				var panel = document.getElementById( 'panelResize' );
				if ( panel == null ) {
					panel = document.createElement( 'div' );
					panel.setAttribute( 'id', 'panelResize' );
					panel.setAttribute( 'style', 'position: fixed; bottom:10px; right: 10px; z-index: 999999; text-align: left;' );
					document.body.appendChild( panel );
				}

				// private panel methods
				function addPanelElement( element ) {
					element.setAttribute( 'style', 'text-align: center; background: rgba(0, 0, 0, 0.8); border-radius: 10px; padding: 10px; margin: 0 0 2px 2px; min-width: 80px; box-sizing: content-box; -moz-box-sizing: content-box; float: right; color: white; font-weight: normal; font-size: 16px; line-height: 16px; ' );
					panel.appendChild( element );
				}

				// public panel methods
				return {
					addFluidZoneToPanel: function( direction, values, href ) {

						(function() {
							var zone = document.createElement( 'span' );
							zone.innerHTML = ' ';
							for ( var i=0; i<values.length; i++ ) {
								zone.appendChild( createResizeElement( i ) );
							}
							addPanelElement( zone );
						})();

						function createResizeElement( i ) {

							var element;

							return (function() {
								if ( typeof( values[ i ] ) == 'number' ) {
									createResizeButtonElement( i );
								} else if (href) {
									createResizeLinkElement( );
								} else {
                                    createResizeTextElement( );
                                }
								element.innerHTML = values[ i ];
								element.setAttribute( 'style', 'color: white; font-weight: bold; font-size: 16px; text-decoration: none; border: 0; float: ' + ( values.length == 1 ? 'none' : i == 0 ? 'left' : 'right' ) );
								return element;
							})();

                            function createResizeLinkElement( ) {
                                element = document.createElement( 'a' );
                                element.setAttribute('href', href);
                                element.setAttribute('target', '_blank');
                            }

							function createResizeTextElement( ) {
								element = document.createElement( 'span' );
							}

							function createResizeButtonElement( ) {
								element = document.createElement( 'a' );
								element.setAttribute( 'href', 'javascript:;' );
								element.addEventListener( 'click', function( ) {
									var size = { };
									var alternate = direction == 'width' ? 'height' : 'width';
									var Direction = direction.charAt( 0 ).toUpperCase( ) + direction.substr( 1 );
									var Alternate = alternate.charAt( 0 ).toUpperCase( ) + alternate.substr( 1 );
									var existingPopup = ( resizedWindow != null && ! resizedWindow.closed );
									size[ alternate ] = 600;
									if ( existingPopup ) {
										size[ alternate ] = resizedWindow[ 'outer' + Alternate ];
										resizedWindow.close( );
									}
									resizedWindow = window.open( window.location + '#', 'resized', 'resizable,scrollbars=1,width=800,height=600' );
									var resizePopup = function( ) {
										var innerSize;
										if ( /AppleWebKit/.test(navigator.userAgent) ) {
											innerSize = resizedWindow.document.documentElement[ 'client' + Direction ];
										} else {
											innerSize = resizedWindow[ 'inner' + Direction ];
										}
										size[ direction ] = values[ i ] + resizedWindow[ 'outer' + Direction ] - innerSize;
										resizedWindow.resizeTo( size.width, size.height );
										resizedWindow.focus( );
									};
									var interval = setInterval( function( ) {
										if ( resizedWindow.document.readyState !== 'complete' ) {
											clearInterval( interval );
											resizePopup( );
										}
									}, 100);
								}, false );
							}
						}
					},
					addInformationToPanel: function( message ) {
						var information = document.createElement( 'span' );
						information.innerHTML = message;
						addPanelElement( information );
					},
					addBreakLineToPanel: function( ) {
						var br = document.createElement( 'br' );
						br.setAttribute( 'style', 'clear: both' );
						panel.appendChild( br );
					}
				}
			}
		}
	}
})();

<|endoftext|>


<commit_before><commit_msg>Had forgotten the “g” flag in the apostrophe replacing regex.<commit_after><|endoftext|>