<commit_before>$( document ).ready(function() {

        // Initiate the chart
        $('#container2').highcharts('Map', {

            chart: {
            backgroundColor: '#043D51',
        },

        title : {
            text : 'Paycoin Network Map',
            style: {
                color: '#E0E0E3',
                fontFamily: '"Montserrat", sans-serif',
                textTransform: 'uppercase',
                fontSize: '25px',
            }
        },
            mapNavigation: {
                enabled: true,
                buttonOptions: {
                    verticalAlign: 'bottom'
                }
            },

            colorAxis: {
                min: 0,
                minColor: '#086B8E',
                maxColor: '#01151C',
                stops: [
                    [0, '#086B8E'],
                    [0.67, '#044055'],
                    [1, '#01151C']
                ]
            },

            series : [{
                data : cdata,
                mapData: Highcharts.maps['custom/world-highres'],
                joinBy: 'hc-key',
                nullColor: '#086B8E',
                name: 'Random data',
                states: {
                    hover: {
                        color: '#076C8D'
                    }
                },
                dataLabels: {
                    enabled: true,
                    format: '{point.name}'
                }
            }]
        });

});<commit_msg>more work<commit_after>$( document ).ready(function() {

        // Initiate the chart
        $('#container2').highcharts('Map', {

            chart: {
            backgroundColor: '#043D51',
        },

        title : {
            text : 'Paycoin Network Map',
            style: {
                color: '#E0E0E3',
                fontFamily: '"Montserrat", sans-serif',
                textTransform: 'uppercase',
                fontSize: '25px',
            }
        },
            mapNavigation: {
                enabled: true,
                buttonOptions: {
                    verticalAlign: 'bottom'
                }
            },

            colorAxis: {
                min: 1,
                minColor: '#086B8E',
                maxColor: '#043547',
            },

            series : [{
                data : cdata,
                mapData: Highcharts.maps['custom/world-highres'],
                joinBy: 'hc-key',
                nullColor: '#6aa6bb',
                name: 'Random data',
                states: {
                    hover: {
                        color: '#076C8D'
                    }
                },
                dataLabels: {
                    enabled: true,
                    format: '{point.name}'
                }
            }]
        });

});<|endoftext|>


<commit_before>function pc_notification(message) {
	$.notify.defaults({ className: "success" });
	//$.notify(message, { globalPosition:"top center" });
	$.notify(message, { globalPosition:"top right" });
}
<commit_msg>remove<commit_after><|endoftext|>


<commit_before>const shell = require('shell');
const _ = require('underscore');
const loophole = require('loophole');

const errorController = require('../controllers/errorController');

function RemoteRevision(hash, remote) {
  this.hash = hash;
  this.remote = remote;
}

// ================
// Class Methods
// ================

RemoteRevision.create = function(hash, remoteUrl) {
  return new RemoteRevision(hash, remoteUrl);
}

// ================
// Instance Methods
// ================

_.extend(RemoteRevision.prototype, {

  githubTemplate: 'https://github.com/<%- project %>/<%- repo %>/commit/<%- revision %>',

  bitbucketTemplate: 'https://bitbucket.org/<%- project %>/<%- repo %>/commits/<%- revision %>',

  open: function() {
    var url = this.url();
    if (url) {
      shell.openExternal(url);
    }
  },

  url: function() {
    var template = this.getTemplate();

    if (!template) {
      return;
    }

    // create data object used to render template string
    var data = this.parseProjectAndRepo();
    data.revision = this.hash;

    // return a rendered url
    return template(data);
  },

  parseProjectAndRepo: function() {
    var pattern = /\:(.*)\/(.*)\.git/;
    var matches = this.remote.match(pattern);
    return {
      project: matches[1],
      repo: matches[2]
    };
  },

  safeTemplate: function(templateString) {
    return loophole.allowUnsafeNewFunction(function() {
      return _.template(templateString);
    });
  },

  getTemplate: function() {
    if (this.isGithub()) {
      return this.safeTemplate(this.githubTemplate);
    }

    if (this.isBitbucket()) {
      return this.safeTemplate(this.bitbucketTemplate);
    }

    if (atom.config.get('git-blame.useCustomUrlTemplateIfStandardRemotesFail')) {
      var customUrlTemplate = atom.config.get('git-blame.customCommitUrlTemplateString');

      // if the user hasnt entered a template string...inform them
      if (/^Example/.test(customUrlTemplate)) {
        // TODO inform user
        errorController.showError('no-custom-url-specified-error');
        return;
      }

      return this.safeTemplate(customUrlTemplate);
    }
  },

  isGithub: function() {
    return /github.com/.test(this.remote);
  },

  isBitbucket: function() {
    return /bitbucket.org/.test(this.remote);
  }

});

// Exports
module.exports = RemoteRevision;
<commit_msg>fix error messages when no custom url defined<commit_after>const shell = require('shell');
const _ = require('underscore');
const loophole = require('loophole');

const errorController = require('../controllers/errorController');

function RemoteRevision(hash, remote) {
  this.hash = hash;
  this.remote = remote;
}

// ================
// Class Methods
// ================

RemoteRevision.create = function(hash, remoteUrl) {
  return new RemoteRevision(hash, remoteUrl);
}

// ================
// Instance Methods
// ================

_.extend(RemoteRevision.prototype, {

  githubTemplate: 'https://github.com/<%- project %>/<%- repo %>/commit/<%- revision %>',

  bitbucketTemplate: 'https://bitbucket.org/<%- project %>/<%- repo %>/commits/<%- revision %>',

  open: function() {
    var url = this.url();
    if (url) {
      shell.openExternal(url);
    }
  },

  url: function() {
    var template = this.getTemplate();

    if (!template) {
      errorController.showError('error-no-custom-url-specified');
      return;
    }

    // create data object used to render template string
    var data = this.parseProjectAndRepo();
    data.revision = this.hash;

    // return a rendered url
    return template(data);
  },

  parseProjectAndRepo: function() {
    var pattern = /\:(.*)\/(.*)\.git/;
    var matches = this.remote.match(pattern);
    return {
      project: matches[1],
      repo: matches[2]
    };
  },

  safeTemplate: function(templateString) {
    return loophole.allowUnsafeNewFunction(function() {
      return _.template(templateString);
    });
  },

  getTemplate: function() {
    if (this.isGithub()) {
      return this.safeTemplate(this.githubTemplate);
    }

    if (this.isBitbucket()) {
      return this.safeTemplate(this.bitbucketTemplate);
    }

    if (atom.config.get('git-blame.useCustomUrlTemplateIfStandardRemotesFail')) {
      var customUrlTemplate = atom.config.get('git-blame.customCommitUrlTemplateString');

      // if the user hasnt entered a template string...inform them
      if (/^Example/.test(customUrlTemplate)) {
        // TODO inform user
        errorController.showError('error-no-custom-url-specified');
        return;
      }

      return this.safeTemplate(customUrlTemplate);
    }
  },

  isGithub: function() {
    return /github.com/.test(this.remote);
  },

  isBitbucket: function() {
    return /bitbucket.org/.test(this.remote);
  }

});

// Exports
module.exports = RemoteRevision;
<|endoftext|>


<commit_before>
function RestRoutingViewModel() {
    var self = this;

    self.available_method    = ko.observableArray(['GET',
                                                   'POST',
                                                   'PUT',
                                                   'DELETE',
                                                   'OPTIONS',
                                                   'HEAD',
                                                   'TRACE'
                                                  ]);
    self.method              = ko.observable();
    self.address             = ko.observable();
    self.format              = ko.observable();
    self.field_list          = ko.observableArray();
    self.field_edit          = ko.observable();
    self.field_selected      = ko.observable();
    self.content             = ko.observable();

    self.return_code         = ko.observable();
    self.return_content_type = ko.observable();
    self.content_length      = ko.observable();
    self.all_headers         = ko.observableArray();
    self.answer              = ko.observable();

    self.can_send = function() {
        if (self.address() === undefined) {
            return false;
        }
        return _.isEmpty(self.address().trim()) === false;
    };

    self.is_add_available = function() {
        return true;
    };

    self.is_remove_available = function() {
        return true;
    };

    self.remove_field = function() {
        var selected = self.field_selected();
        if (selected === undefined) {
            return report_error('No field was selected to be removed');
        }

        if (! _.isEmpty(selected.trim())) {
            if (_.indexOf(self.field_list(), selected) > -1) {
              self.field_list.remove(selected);
            } else {
                report_error('Unable to find selected field to remove');
            }
        } else {
            report_error('The selected field to be removed is empty');
        }

    };

    self.add_field = function() {
        var field = self.field_edit();
        if (field === undefined) {
            return report_error('Field Edit is empty');
        }
        if (! _.isEmpty(field.trim())) {
            if (_.indexOf(self.field_list(), field) === -1) {
                self.field_list.push(field);
            } else {
                report_error('Field alreay exists in the list');
            }
        }
    };

    self.execRest = function() {
        var params = {method: self.method(),
                      address: self.address(),
                      format: self.format() || '',
                      content: self.content() || ''};
        $.post('/request', params).
            done(function(data, req_status, req_obj) {
                if (_.has(data, 'return_code')) {
                    self.return_code(data.return_code);
                }

                if (_.has(data, 'content_type')) {
                    self.return_content_type(data.content_type);
                }

                if (_.has(data, 'body')) {
                    self.answer(data.body);
                }

                if (_.has(data, 'content_length')) {
                    self.content_length(data.content_length);
                }

                if (_.has(data, 'all_headers')) {
                    self.all_headers(data.all_headers);
                }

            }).
        error(function(){
            console.log(arguments.length);
        });

    };
}

var rest_client;
$(function(){
    rest_client = new RestRoutingViewModel();
    ko.applyBindings(rest_client);
});
<commit_msg>added error report on a trim based empty field<commit_after>
function RestRoutingViewModel() {
    var self = this;

    self.available_method    = ko.observableArray(['GET',
                                                   'POST',
                                                   'PUT',
                                                   'DELETE',
                                                   'OPTIONS',
                                                   'HEAD',
                                                   'TRACE'
                                                  ]);
    self.method              = ko.observable();
    self.address             = ko.observable();
    self.format              = ko.observable();
    self.field_list          = ko.observableArray();
    self.field_edit          = ko.observable();
    self.field_selected      = ko.observable();
    self.content             = ko.observable();

    self.return_code         = ko.observable();
    self.return_content_type = ko.observable();
    self.content_length      = ko.observable();
    self.all_headers         = ko.observableArray();
    self.answer              = ko.observable();

    self.can_send = function() {
        if (self.address() === undefined) {
            return false;
        }
        return _.isEmpty(self.address().trim()) === false;
    };

    self.is_add_available = function() {
        return true;
    };

    self.is_remove_available = function() {
        return true;
    };

    self.remove_field = function() {
        var selected = self.field_selected();
        if (selected === undefined) {
            return report_error('No field was selected to be removed');
        }

        if (! _.isEmpty(selected.trim())) {
            if (_.indexOf(self.field_list(), selected) > -1) {
              self.field_list.remove(selected);
            } else {
                report_error('Unable to find selected field to remove');
            }
        } else {
            report_error('The selected field to be removed is empty');
        }

    };

    self.add_field = function() {
        var field = self.field_edit();
        if (field === undefined) {
            return report_error('Field Edit is empty');
        }
        if (! _.isEmpty(field.trim())) {
            if (_.indexOf(self.field_list(), field) === -1) {
                self.field_list.push(field);
            } else {
                report_error('Field alreay exists in the list');
            }
        } else {
            report_error('The field to be added is empty');
        }
    };

    self.execRest = function() {
        var params = {method: self.method(),
                      address: self.address(),
                      format: self.format() || '',
                      content: self.content() || ''};
        $.post('/request', params).
            done(function(data, req_status, req_obj) {
                if (_.has(data, 'return_code')) {
                    self.return_code(data.return_code);
                }

                if (_.has(data, 'content_type')) {
                    self.return_content_type(data.content_type);
                }

                if (_.has(data, 'body')) {
                    self.answer(data.body);
                }

                if (_.has(data, 'content_length')) {
                    self.content_length(data.content_length);
                }

                if (_.has(data, 'all_headers')) {
                    self.all_headers(data.all_headers);
                }

            }).
        error(function(){
            console.log(arguments.length);
        });

    };
}

var rest_client;
$(function(){
    rest_client = new RestRoutingViewModel();
    ko.applyBindings(rest_client);
});
<|endoftext|>


<commit_before>// Includes
var http = require('./http.js').func;
var getVerification = require('./getVerification.js').func;
var promise = require('./promise.js');

// Args
exports.required = ['url', 'events'];
exports.optional = ['customOpt', 'getBody', 'jar'];

function general (jar, url, inputs, events, customOpt, body) {
  return function (resolve, reject) {
    for (var input in events) {
      inputs[input] = events[input];
    }
    var httpOpt = {
      url: url,
      options: {
        resolveWithFullResponse: true,
        method: 'POST',
        form: inputs,
        jar: jar
      }
    };
    if (customOpt) {
      Object.assign(httpOpt.options, customOpt);
    }
    http(httpOpt).then(function (res) {
      resolve({
        res: res,
        body: body
      });
    });
  };
}

exports.func = function (args) {
  var jar = args.jar;
  var url = args.url;
  return getVerification({url: url, jar: jar, getBody: args.getBody})
  .then(function (response) {
    return promise(general(jar, url, response.inputs, args.events, args.http, response.body));
  });
};
<commit_msg>Add ignoreCache option and http option<commit_after>// Includes
var http = require('./http.js').func;
var getVerification = require('./getVerification.js').func;
var promise = require('./promise.js');

// Args
exports.required = ['url', 'events'];
exports.optional = ['http', 'ignoreCache', 'getBody', 'jar'];

function general (jar, url, inputs, events, customOpt, body) {
  return function (resolve, reject) {
    for (var input in events) {
      inputs[input] = events[input];
    }
    var httpOpt = {
      url: url,
      options: {
        resolveWithFullResponse: true,
        method: 'POST',
        form: inputs,
        jar: jar
      }
    };
    if (customOpt) {
      if (customOpt.url) {
        delete customOpt.url;
      }
      Object.assign(httpOpt.options, customOpt);
    }
    http(httpOpt).then(function (res) {
      resolve({
        res: res,
        body: body
      });
    });
  };
}

exports.func = function (args) {
  var jar = args.jar;
  var url = args.url;
  var custom = args.http;
  return getVerification({url: custom ? (custom.url || url) : url, jar: jar, ignoreCache: args.ignoreCache, getBody: args.getBody})
  .then(function (response) {
    return promise(general(jar, url, response.inputs, args.events, args.http, response.body));
  });
};
<|endoftext|>


<commit_before>
module.exports = errorHandler

var cbCalled = false
  , log = require("./log.js")
  , npm = require("../../npm.js")
  , rm = require("rimraf")
  , constants = require("constants")
  , itWorked = false
  , path = require("path")
  , ini = require("./ini.js")

process.on("exit", function (code) {
  // console.error("exit", code)
  if (!ini.resolved) return
  if (code) itWorked = false
  if (itWorked) log("ok")
  else {
    if (!cbCalled) {
      log.error("cb() never called!\n ")
    }
    log.error([""
              ,"Additional logging details can be found in:"
              ,"    " + path.resolve("npm-debug.log")
              ].join("\n"))
    log.win("not ok")
  }
  itWorked = false // ready for next exit
})

function errorHandler (er) {
  // console.error("errorHandler", er)
  if (!ini.resolved) {
    // logging won't work unless we pretend that it's ready
    er = er || new Error("Exit prior to config file resolving.")
    console.error(er.stack || er.message)
  }

  if (cbCalled) {
    er = er || new Error("Callback called more than once.")
  }

  cbCalled = true
  if (!er) return exit(0)
  if (!(er instanceof Error)) {
    log.error(er)
    return exit(1)
  }

  var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/)
  if (m) {
    m = m[1]
    if (!constants[m] && !npm[m]) constants[m] = {}
    er.errno = npm[m] || constants[m]
  }

  switch (er.errno) {
  case constants.ECONNREFUSED:
    log.error(er)
    log.error(["If you are using Cygwin, please set up your /etc/resolv.conf"
              ,"See step 4 in this wiki page:"
              ,"    http://github.com/ry/node/wiki/Building-node.js-on-Cygwin-%28Windows%29"
              ,"If you are not using Cygwin, please report this"
              ,"at <http://github.com/isaacs/npm/issues>"
              ,"or email it to <npm-@googlegroups.com>"
              ].join("\n"))
    break

  case constants.EACCES:
  case constants.EPERM:
    log.error(er)
    log.error(["",
              "Please use 'sudo' or log in as root to run this command."
              ,""
              ,"    sudo npm "
                +npm.config.get("argv").original.map(JSON.stringify).join(" ")
              ,""
              ,"or set the 'unsafe-perm' config var to true."
              ,""
              ,"    npm config set unsafe-perm true"
              ].join("\n"))
    break

  case npm.ELIFECYCLE:
    log.error(er.message)
    log.error(["","Failed at the "+er.pkgid+" "+er.stage+" script."
              ,"This is most likely a problem with the "+er.pkgname+" package,"
              ,"not with npm itself."
              ,"Tell the author that this fails on your system:"
              ,"    "+er.script
              ,"You can get their info via:"
              ,"    npm owner ls "+er.pkgname
              ,"There is likely additional logging output above."
              ].join("\n"))
    break

  case npm.EJSONPARSE:
    log.error(er.message)
    log.error("File: "+er.file)
    log.error(["Failed to parse package.json data."
              ,"package.json must be actual JSON, not just JavaScript."
              ,"","This is not a bug in npm."
              ,"Tell the package author to fix their package.json file."
              ].join("\n"), "JSON.parse")
    break

  case npm.E404:
    if (er.pkgid && er.pkgid !== "-") {
      var msg = ["'"+er.pkgid+"' is not in the npm registry."
                ,"You could maybe bug the author to publish it"]
      if (er.pkgid.match(/^node[\.\-]|[\.\-]js$/)) {
        var s = er.pkgid.replace(/^node[\.\-]|[\.\-]js$/g, "")
        if (s !== er.pkgid) {
          s = s.replace(/[^a-z0-9]/g, ' ')
          msg.push("Maybe try 'npm search " + s + "'")
        }
      }
      msg.push("Note that you can also install from a tarball or folder.")
      log.error(msg.join("\n"), "404")
    }
    break

  case npm.EPUBLISHCONFLICT:
    log.error(["Cannot publish over existing version."
              ,"Bump the 'version' field, set the --force flag, or"
              ,"    npm unpublish '"+er.pkgid+"'"
              ,"and try again"
              ].join("\n"), "publish fail" )
    break

  case npm.EISGIT:
    log.error([er.message
              ,"    "+er.path
              ,"Refusing to remove it. Update manually,"
              ,"or move it out of the way first."
              ].join("\n"), "git" )
    break

  case npm.ECYCLE:
    log.error([er.message
              ,"While installing: "+er.pkgid
              ,"Found a pathological dependency case that npm cannot solve."
              ,"Please report this to the package author."
              ].join("\n"))
    break

  case npm.EENGINE:
    log.error([er.message
              ,"Not compatible with your version of node/npm: "+er.pkgid
              ,"Required: "+JSON.stringify(er.required)
              ,"Actual:   "
              +JSON.stringify({npm:npm.version
                              ,node:npm.config.get("node-version")})
              ].join("\n"))
    break

  case constants.EEXIST:
    log.error([er.message
              ,"File exists: "+er.path
              ,"Move it away, and try again."].join("\n"))
    break

  default:
    log.error(er)
    log.error(["Report this *entire* log at:"
              ,"    <http://github.com/isaacs/npm/issues>"
              ,"or email it to:"
              ,"    <npm-@googlegroups.com>"
              ].join("\n"))
    break
  }

  var os = require("os")
  log.error("")
  log.error(os.type() + " " + os.release(), "System")
  log.error(process.argv
            .map(JSON.stringify).join(" "), "command")
  log.error(process.cwd(), "cwd")
  log.error(process.version, "node -v")
  log.error(npm.version, "npm -v")
  exit(typeof er.errno === "number" ? er.errno : 1)
}

function exit (code) {
  var doExit = npm.config.get("_exit")
  log.verbose([code, doExit], "exit")

  if (code) writeLogFile(reallyExit)
  else rm("npm-debug.log", function () { rm(npm.tmp, reallyExit) })

  function reallyExit() {
    itWorked = !code
    //if (!itWorked) {
      if (!doExit) process.emit("exit", code)
      else process.exit(code)
    //}
  }
}

function writeLogFile (cb) {
  var fs = require("graceful-fs")
    , fstr = fs.createWriteStream("npm-debug.log")
    , util = require("util")

  log.history.forEach(function (m) {
    var lvl = log.LEVEL[m.level]
      , pref = m.pref ? " " + m.pref : ""
      , b = lvl + pref + " "
      , eol = process.platform === "win32" ? "\r\n" : "\n"
      , msg = typeof m.msg === "string" ? m.msg
            : msg instanceof Error ? msg.stack || msg.message
            : util.inspect(m.msg, 0, 4)
    fstr.write(new Buffer(b
                         +(msg.split(/\r?\n+/).join(eol+b))
                         + eol))
  })
  fstr.end()
  fstr.on("close", cb)
}
<commit_msg>Report extra info on the error object<commit_after>
module.exports = errorHandler

var cbCalled = false
  , log = require("./log.js")
  , npm = require("../../npm.js")
  , rm = require("rimraf")
  , constants = require("constants")
  , itWorked = false
  , path = require("path")
  , ini = require("./ini.js")

process.on("exit", function (code) {
  // console.error("exit", code)
  if (!ini.resolved) return
  if (code) itWorked = false
  if (itWorked) log("ok")
  else {
    if (!cbCalled) {
      log.error("cb() never called!\n ")
    }
    log.error([""
              ,"Additional logging details can be found in:"
              ,"    " + path.resolve("npm-debug.log")
              ].join("\n"))
    log.win("not ok")
  }
  itWorked = false // ready for next exit
})

function errorHandler (er) {
  // console.error("errorHandler", er)
  if (!ini.resolved) {
    // logging won't work unless we pretend that it's ready
    er = er || new Error("Exit prior to config file resolving.")
    console.error(er.stack || er.message)
  }

  if (cbCalled) {
    er = er || new Error("Callback called more than once.")
  }

  cbCalled = true
  if (!er) return exit(0)
  if (!(er instanceof Error)) {
    log.error(er)
    return exit(1)
  }

  var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/)
  if (m) {
    m = m[1]
    if (!constants[m] && !npm[m]) constants[m] = {}
    er.errno = npm[m] || constants[m]
  }

  switch (er.errno) {
  case constants.ECONNREFUSED:
    log.error(er)
    log.error(["If you are using Cygwin, please set up your /etc/resolv.conf"
              ,"See step 4 in this wiki page:"
              ,"    http://github.com/ry/node/wiki/Building-node.js-on-Cygwin-%28Windows%29"
              ,"If you are not using Cygwin, please report this"
              ,"at <http://github.com/isaacs/npm/issues>"
              ,"or email it to <npm-@googlegroups.com>"
              ].join("\n"))
    break

  case constants.EACCES:
  case constants.EPERM:
    log.error(er)
    log.error(["",
              "Please use 'sudo' or log in as root to run this command."
              ,""
              ,"    sudo npm "
                +npm.config.get("argv").original.map(JSON.stringify).join(" ")
              ,""
              ,"or set the 'unsafe-perm' config var to true."
              ,""
              ,"    npm config set unsafe-perm true"
              ].join("\n"))
    break

  case npm.ELIFECYCLE:
    log.error(er.message)
    log.error(["","Failed at the "+er.pkgid+" "+er.stage+" script."
              ,"This is most likely a problem with the "+er.pkgname+" package,"
              ,"not with npm itself."
              ,"Tell the author that this fails on your system:"
              ,"    "+er.script
              ,"You can get their info via:"
              ,"    npm owner ls "+er.pkgname
              ,"There is likely additional logging output above."
              ].join("\n"))
    break

  case npm.EJSONPARSE:
    log.error(er.message)
    log.error("File: "+er.file)
    log.error(["Failed to parse package.json data."
              ,"package.json must be actual JSON, not just JavaScript."
              ,"","This is not a bug in npm."
              ,"Tell the package author to fix their package.json file."
              ].join("\n"), "JSON.parse")
    break

  case npm.E404:
    if (er.pkgid && er.pkgid !== "-") {
      var msg = ["'"+er.pkgid+"' is not in the npm registry."
                ,"You could maybe bug the author to publish it"]
      if (er.pkgid.match(/^node[\.\-]|[\.\-]js$/)) {
        var s = er.pkgid.replace(/^node[\.\-]|[\.\-]js$/g, "")
        if (s !== er.pkgid) {
          s = s.replace(/[^a-z0-9]/g, ' ')
          msg.push("Maybe try 'npm search " + s + "'")
        }
      }
      msg.push("Note that you can also install from a tarball or folder.")
      log.error(msg.join("\n"), "404")
    }
    break

  case npm.EPUBLISHCONFLICT:
    log.error(["Cannot publish over existing version."
              ,"Bump the 'version' field, set the --force flag, or"
              ,"    npm unpublish '"+er.pkgid+"'"
              ,"and try again"
              ].join("\n"), "publish fail" )
    break

  case npm.EISGIT:
    log.error([er.message
              ,"    "+er.path
              ,"Refusing to remove it. Update manually,"
              ,"or move it out of the way first."
              ].join("\n"), "git" )
    break

  case npm.ECYCLE:
    log.error([er.message
              ,"While installing: "+er.pkgid
              ,"Found a pathological dependency case that npm cannot solve."
              ,"Please report this to the package author."
              ].join("\n"))
    break

  case npm.EENGINE:
    log.error([er.message
              ,"Not compatible with your version of node/npm: "+er.pkgid
              ,"Required: "+JSON.stringify(er.required)
              ,"Actual:   "
              +JSON.stringify({npm:npm.version
                              ,node:npm.config.get("node-version")})
              ].join("\n"))
    break

  case constants.EEXIST:
    log.error([er.message
              ,"File exists: "+er.path
              ,"Move it away, and try again."].join("\n"))
    break

  default:
    log.error(er)
    log.error(["Report this *entire* log at:"
              ,"    <http://github.com/isaacs/npm/issues>"
              ,"or email it to:"
              ,"    <npm-@googlegroups.com>"
              ].join("\n"))
    break
  }

  var os = require("os")
  log.error("")
  log.error(os.type() + " " + os.release(), "System")
  log.error(process.argv
            .map(JSON.stringify).join(" "), "command")
  log.error(process.cwd(), "cwd")
  log.error(process.version, "node -v")
  log.error(npm.version, "npm -v")
  if (er.file) log.error(er.file, "file")
  if (er.path) log.error(er.path, "path")
  if (er.type) log.error(er.type, "type")
  if (er.arguments) log.error(er.arguments, "arguments")
  if (er.code) log.error(er.code, "code")
  if (er.errno) log.error(er.errno, "errno")
  exit(typeof er.errno === "number" ? er.errno : 1)
}

function exit (code) {
  var doExit = npm.config.get("_exit")
  log.verbose([code, doExit], "exit")

  if (code) writeLogFile(reallyExit)
  else rm("npm-debug.log", function () { rm(npm.tmp, reallyExit) })

  function reallyExit() {
    itWorked = !code
    //if (!itWorked) {
      if (!doExit) process.emit("exit", code)
      else process.exit(code)
    //}
  }
}

function writeLogFile (cb) {
  var fs = require("graceful-fs")
    , fstr = fs.createWriteStream("npm-debug.log")
    , util = require("util")

  log.history.forEach(function (m) {
    var lvl = log.LEVEL[m.level]
      , pref = m.pref ? " " + m.pref : ""
      , b = lvl + pref + " "
      , eol = process.platform === "win32" ? "\r\n" : "\n"
      , msg = typeof m.msg === "string" ? m.msg
            : msg instanceof Error ? msg.stack || msg.message
            : util.inspect(m.msg, 0, 4)
    fstr.write(new Buffer(b
                         +(msg.split(/\r?\n+/).join(eol+b))
                         + eol))
  })
  fstr.end()
  fstr.on("close", cb)
}
<|endoftext|>


<commit_before>define(['jquery', 'appearanceUtils'], function($, utils) {
   return {
      // where
      selector: function(pull) {
         return pull.state == 'open';
      },
      // order by
      sort: function(pull) {
         return pull.created_at;
      },
      // Allows custom modifications of each pull's display
      adjust: function(pull, node) {
         // If the pull is over 30 days old...
         if (Date.now() - (new Date(pull.created_at)) > 2590000000 ) {
            // Mark it in red
            $(node).addClass('bg-warning');
         }
      },
      navbar: "#restore-buttons",
      // Functions to stick status information in indicators at the bottom of each pull
      indicators: {
         qa_remaining: function qa_remaining(pull, node) {
            var required = pull.status.qa_req;
            var remaining = required - pull.status.QA.length;
            node.text("QA " + remaining + "/" + required);
         },
         cr_remaining: function cr_remaining(pull, node) {
            var required = pull.status.cr_req;
            var remaining = required - pull.status.CR.length;
            node.text("CR " + remaining + "/" + required);
         },
         status: function status(pull, node) {
            node.text(pull.status.commitStatus);
         },
         user_icon: function user_icon(pull, node) {
            if (pull.is_mine()) {
               node.append('');
            }
         }
      },
      // Functions to run when events happen
      triggers: {
         // Functions to run on each column
         column: {
            onCreate: function() {
            },
            onUpdate: function() {
            }
         },
         // Functions to run on each indicator
         indicators: {
            onCreate: function() {
            },
            onUpdate: function() {
            }
         }
      },
      columns: [
         {
            title: "Special Pulls",
            id: "uniqPulls",
            selector: function(pull) {
               return (pull.deploy_blocked() || pull.status.ready) && !pull.dev_blocked();
            },
            sort: function(pull) {
               return pull.deploy_blocked() ? 0 : 1;
            },
            adjust: function(pull, node) {
               if (pull.deploy_blocked()) {
                  node.addClass('list-group-item-danger');
               }
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "dev_blocked Pulls",
            id: "blockPulls",
            selector: function(pull) {
               return pull.dev_blocked();
            }
         },
         {
            title: "CR Pulls",
            id: "crPulls",
            selector: function(pull) {
               return !pull.cr_done() && !pull.dev_blocked();
            }
         },
         {
            title: "QA Pulls",
            id: "qaPulls",
            selector: function(pull) {
               return !pull.qa_done() && !pull.dev_blocked();
            }
         }
      ]
   };
});
<commit_msg>show how many CRs, QAs have been left, not remaining<commit_after>define(['jquery', 'appearanceUtils'], function($, utils) {
   return {
      // where
      selector: function(pull) {
         return pull.state == 'open';
      },
      // order by
      sort: function(pull) {
         return pull.created_at;
      },
      // Allows custom modifications of each pull's display
      adjust: function(pull, node) {
         // If the pull is over 30 days old...
         if (Date.now() - (new Date(pull.created_at)) > 2590000000 ) {
            // Mark it in red
            $(node).addClass('bg-warning');
         }
      },
      navbar: "#restore-buttons",
      // Functions to stick status information in indicators at the bottom of each pull
      indicators: {
         qa_remaining: function qa_remaining(pull, node) {
            var required = pull.status.qa_req;
            var completed = pull.status.QA.length;
            node.text("QA " + completed + "/" + required);
         },
         cr_remaining: function cr_remaining(pull, node) {
            var required = pull.status.cr_req;
            var completed = pull.status.CR.length;
            node.text("CR " + completed + "/" + required);
         },
         status: function status(pull, node) {
            node.text(pull.status.commitStatus);
         },
         user_icon: function user_icon(pull, node) {
            if (pull.is_mine()) {
               node.append('');
            }
         }
      },
      // Functions to run when events happen
      triggers: {
         // Functions to run on each column
         column: {
            onCreate: function() {
            },
            onUpdate: function() {
            }
         },
         // Functions to run on each indicator
         indicators: {
            onCreate: function() {
            },
            onUpdate: function() {
            }
         }
      },
      columns: [
         {
            title: "Special Pulls",
            id: "uniqPulls",
            selector: function(pull) {
               return (pull.deploy_blocked() || pull.status.ready) && !pull.dev_blocked();
            },
            sort: function(pull) {
               return pull.deploy_blocked() ? 0 : 1;
            },
            adjust: function(pull, node) {
               if (pull.deploy_blocked()) {
                  node.addClass('list-group-item-danger');
               }
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "dev_blocked Pulls",
            id: "blockPulls",
            selector: function(pull) {
               return pull.dev_blocked();
            }
         },
         {
            title: "CR Pulls",
            id: "crPulls",
            selector: function(pull) {
               return !pull.cr_done() && !pull.dev_blocked();
            }
         },
         {
            title: "QA Pulls",
            id: "qaPulls",
            selector: function(pull) {
               return !pull.qa_done() && !pull.dev_blocked();
            }
         }
      ]
   };
});
<|endoftext|>


<commit_before>'use strict';
const fs = require('fs-extra');
const path = require('path');
const fkill = require('fkill');
const spawn = require('child_process').spawn;
const assign = require('lodash/assign');
const isRunning = require('is-running');

const errors = require('../errors');
const ProcessManager = require('../process-manager');

const PID_FILE = '.ghostpid';

/**
 * Local process manager. This is pretty much guaranteed to work on any OS and
 * system, so it is used as the fallback if any other process manager doesn't work
 *
 * @class LocalProcess
 */
class LocalProcess extends ProcessManager {
    /**
     * Starts the local process
     *
     * @param {string} cwd CWD of the ghost instance
     * @param {string} environment Current running environment
     * @return Promise<void>
     *
     * @method start
     * @public
     */
    start(cwd, environment) {
        return new Promise((resolve, reject) => {
            let cp = spawn('ghost', ['run'], {
                cwd: cwd,
                detached: true,
                stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
                env: assign({}, process.env, {NODE_ENV: environment})
            });

            // Stick the pid into the pidfile so we can stop the process later
            fs.writeFileSync(path.join(cwd, PID_FILE), cp.pid);

            cp.on('error', reject);

            cp.on('exit', (code) => {
                fs.removeSync(path.join(cwd, PID_FILE));
                reject(new errors.GhostError(`Ghost process exited with code: ${code}`));
            });

            // Wait until Ghost tells us that it's started correctly, then resolve
            cp.on('message', (msg) => {
                if (msg.error) {
                    fs.removeSync(path.join(cwd, PID_FILE));

                    return reject(new errors.GhostError(msg));
                }

                if (msg.started) {
                    cp.disconnect();
                    cp.unref();
                    return resolve();
                }
            });
        });
    }

    /**
     * Stops an instance
     *
     * @param {string} cwd Current working directory
     * @return Promise<void>
     *
     * @method stop
     * @public
     */
    stop(cwd) {
        let pid;

        try {
            pid = parseInt(fs.readFileSync(path.join(cwd, PID_FILE)));
        } catch (e) {
            if (e.code === 'ENOENT') {
                // pid was not found, exit
                return;
            }

            throw e;
        }

        return fkill(pid).catch((error) => {
            // TODO: verify windows outputs same error message as mac/linux
            if (!error.message.match(/No such process/)) {
                throw error;
            }
        }).then(() => {
            fs.removeSync(path.join(cwd, PID_FILE));
        });
    }

    /**
     * Called by the `ghost run` sub-process, this notifies the parent process that
     * Ghost has started
     *
     * @method success
     * @public
     */
    success() {
        if (process.send) {process.send({started: true});}
    }

    /**
     * Called by the `ghost run` sub-process, this notifies the parent process
     * that an error has occurred.
     *
     * @param {Error} error
     *
     * @method error
     * @public
     */
    error(error) {
        if (process.send) {process.send({error: true, message: error.message});}
    }

    /**
     * Checks if the Ghost instance is running
     *
     * @param {string} cwd
     * @return bool Whether or not the process is still running
     *
     * @method isRunning
     * @public
     */
    isRunning(cwd) {
        let pidfile = path.join(cwd, PID_FILE);

        if (!fs.existsSync(pidfile)) {
            // Even if the process exists, if the file has been deleted we really can't
            // determine if it's still running, so just assume it's not.
            return false;
        }

        let pid = parseInt(fs.readFileSync(pidfile));
        let running = isRunning(pid);

        if (!running) {
            // If not running, cleanup the pid file
            fs.removeSync(pidfile);
        }

        return running;
    }

    /**
     * Because this process manager should work on every system,
     * just return true here
     */
    static willRun() {
        return true;
    }
};

module.exports = LocalProcess;
<commit_msg>fix(windows): fix local process manager on windows<commit_after>'use strict';
const fs = require('fs-extra');
const path = require('path');
const fkill = require('fkill');
const spawn = require('child_process').spawn;
const assign = require('lodash/assign');
const isRunning = require('is-running');

const errors = require('../errors');
const ProcessManager = require('../process-manager');

const PID_FILE = '.ghostpid';

/**
 * Local process manager. This is pretty much guaranteed to work on any OS and
 * system, so it is used as the fallback if any other process manager doesn't work
 *
 * @class LocalProcess
 */
class LocalProcess extends ProcessManager {
    /**
     * Starts the local process
     *
     * @param {string} cwd CWD of the ghost instance
     * @param {string} environment Current running environment
     * @return Promise<void>
     *
     * @method start
     * @public
     */
    start(cwd, environment) {
        let isWindows = process.platorm === 'win32';

        return new Promise((resolve, reject) => {
            let cp = spawn('node', [process.argv[1] , 'run'], {
                cwd: cwd,
                detached: true,
                // IPC doesn't work on windows, so we just use 'ignore'
                stdio: isWindows ? 'ignore' : ['ignore', 'ignore', 'ignore', 'ipc'],
                env: assign({}, process.env, {NODE_ENV: environment})
            });

            // Stick the pid into the pidfile so we can stop the process later
            fs.writeFileSync(path.join(cwd, PID_FILE), cp.pid);

            cp.on('error', reject);

            cp.on('exit', (code) => {
                fs.removeSync(path.join(cwd, PID_FILE));
                reject(new errors.GhostError(`Ghost process exited with code: ${code}`));
            });

            if (isWindows) {
                cp.disconnect();
                cp.unref();
                return resolve();
            }

            // Wait until Ghost tells us that it's started correctly, then resolve
            cp.on('message', (msg) => {
                if (msg.error) {
                    fs.removeSync(path.join(cwd, PID_FILE));

                    return reject(new errors.GhostError(msg));
                }

                if (msg.started) {
                    cp.disconnect();
                    cp.unref();
                    return resolve();
                }
            });
        });
    }

    /**
     * Stops an instance
     *
     * @param {string} cwd Current working directory
     * @return Promise<void>
     *
     * @method stop
     * @public
     */
    stop(cwd) {
        let pid;

        try {
            pid = parseInt(fs.readFileSync(path.join(cwd, PID_FILE)));
        } catch (e) {
            if (e.code === 'ENOENT') {
                // pid was not found, exit
                return;
            }

            throw e;
        }

        return fkill(pid, {force: true}).catch((error) => {
            // TODO: verify windows outputs same error message as mac/linux
            if (!error.message.match(/No such process/)) {
                throw error;
            }
        }).then(() => {
            fs.removeSync(path.join(cwd, PID_FILE));
        });
    }

    /**
     * Called by the `ghost run` sub-process, this notifies the parent process that
     * Ghost has started
     *
     * @method success
     * @public
     */
    success() {
        if (process.send) {process.send({started: true});}
    }

    /**
     * Called by the `ghost run` sub-process, this notifies the parent process
     * that an error has occurred.
     *
     * @param {Error} error
     *
     * @method error
     * @public
     */
    error(error) {
        if (process.send) {process.send({error: true, message: error.message});}
    }

    /**
     * Checks if the Ghost instance is running
     *
     * @param {string} cwd
     * @return bool Whether or not the process is still running
     *
     * @method isRunning
     * @public
     */
    isRunning(cwd) {
        let pidfile = path.join(cwd, PID_FILE);

        if (!fs.existsSync(pidfile)) {
            // Even if the process exists, if the file has been deleted we really can't
            // determine if it's still running, so just assume it's not.
            return false;
        }

        let pid = parseInt(fs.readFileSync(pidfile));
        let running = isRunning(pid);

        if (!running) {
            // If not running, cleanup the pid file
            fs.removeSync(pidfile);
        }

        return running;
    }

    /**
     * Because this process manager should work on every system,
     * just return true here
     */
    static willRun() {
        return true;
    }
};

module.exports = LocalProcess;
<|endoftext|>


<commit_before>var sinon = require('sinon');
var _assert = require('assert');
var utils = require('./utils.js');
var match = utils.match;

module.exports = assert;

function assert(value, message) {
    if (!value) {
        _assert.fail(value, true, message, '==', assert);
    }
}

assert.equals = function (actual, expected, message) {
    if (!sinon.deepEqual(actual, expected)) {
        _assert.fail(actual, expected, message, 'equals', assert.equals);
    }
};

assert.same = function (actual, expected) {
    _assert.strictEqual(actual, expected);
};

assert.match = function (actual, expected, message) {
    if (!match(actual, expected)) {
        _assert.fail(actual, expected, message, 'match', assert.match);
    }
};

assert.defined = function (value, message) {
    if (typeof value === 'undefined') {
        _assert.fail(value, true, message, 'defined', assert.defined);
    }
};

assert.isNull = function (value) {
    assert.same(value, null);
};

assert.exception = function (callback) {
    _assert.throws(callback);
};

assert.startsWith = function (actual, expected, message) {
    if (!actual.startsWith(expected)) {
        _assert.fail(actual, expected, message, 'startsWith');
    }
};

assert.startsWith = function (actual, expected, message) {
    if (!actual.endsWith(expected)) {
        _assert.fail(actual, expected, message, 'endsWith');
    }
};

assert.called = sinon.assert.called;
assert.calledOnce = sinon.assert.calledOnce;
assert.calledTwice = sinon.assert.calledTwice;
assert.calledThrice = sinon.assert.calledThrice;
assert.calledWith = sinon.assert.calledWith;

assert.calledOnceWith = function (stub) {
    var args = Array.prototype.slice.call(arguments, 1);
    calledXWith(1, stub, args);
};

assert.calledTwiceWith = function (stub) {
    var args = Array.prototype.slice.call(arguments, 1);
    calledXWith(2, stub, args);
};

assert.calledThriceWith = function (stub) {
    var args = Array.prototype.slice.call(arguments, 1);
    calledXWith(3, stub, args);
};

function calledXWith(times, stub, expectedArgs) {
    assert(stub.callCount >= 1, 'Stub not called at least ' + times + ' time(s)');

    var equalsCount = 0;
    for (var i = 0; i < stub.callCount; i++) {
        var actualArgsToMatch = stub.getCall(i).args.slice(0, expectedArgs.length);
        if (sinon.deepEqual(actualArgsToMatch, expectedArgs)) {
            equalsCount++;
        }
    }
    var message = 'Stub not called ' + times + ' time(s) with argument(s): ' + expectedArgs.map(JSON.stringify).join(', ');
    assert.equals(equalsCount, times, message);
}<commit_msg>Fixed assert.startsWith and assert.endsWith<commit_after>var sinon = require('sinon');
var _assert = require('assert');
var utils = require('./utils.js');
var match = utils.match;

module.exports = assert;

function assert(value, message) {
    if (!value) {
        _assert.fail(value, true, message, '==', assert);
    }
}

assert.equals = function (actual, expected, message) {
    if (!sinon.deepEqual(actual, expected)) {
        _assert.fail(actual, expected, message, 'equals', assert.equals);
    }
};

assert.same = function (actual, expected) {
    _assert.strictEqual(actual, expected);
};

assert.match = function (actual, expected, message) {
    if (!match(actual, expected)) {
        _assert.fail(actual, expected, message, 'match', assert.match);
    }
};

assert.defined = function (value, message) {
    if (typeof value === 'undefined') {
        _assert.fail(value, true, message, 'defined', assert.defined);
    }
};

assert.isNull = function (value) {
    assert.same(value, null);
};

assert.exception = function (callback) {
    _assert.throws(callback);
};

assert.startsWith = function (actual, expected, message) {
    if (!actual.startsWith(expected)) {
        _assert.fail(actual, expected, message, 'startsWith');
    }
};

assert.endsWith = function (actual, expected, message) {
    if (!actual.endsWith(expected)) {
        _assert.fail(actual, expected, message, 'endsWith');
    }
};

assert.called = sinon.assert.called;
assert.calledOnce = sinon.assert.calledOnce;
assert.calledTwice = sinon.assert.calledTwice;
assert.calledThrice = sinon.assert.calledThrice;
assert.calledWith = sinon.assert.calledWith;

assert.calledOnceWith = function (stub) {
    var args = Array.prototype.slice.call(arguments, 1);
    calledXWith(1, stub, args);
};

assert.calledTwiceWith = function (stub) {
    var args = Array.prototype.slice.call(arguments, 1);
    calledXWith(2, stub, args);
};

assert.calledThriceWith = function (stub) {
    var args = Array.prototype.slice.call(arguments, 1);
    calledXWith(3, stub, args);
};

function calledXWith(times, stub, expectedArgs) {
    assert(stub.callCount >= 1, 'Stub not called at least ' + times + ' time(s)');

    var equalsCount = 0;
    for (var i = 0; i < stub.callCount; i++) {
        var actualArgsToMatch = stub.getCall(i).args.slice(0, expectedArgs.length);
        if (sinon.deepEqual(actualArgsToMatch, expectedArgs)) {
            equalsCount++;
        }
    }
    var message = 'Stub not called ' + times + ' time(s) with argument(s): ' + expectedArgs.map(JSON.stringify).join(', ');
    assert.equals(equalsCount, times, message);
}<|endoftext|>


<commit_before>function WordChecker(word, board) {
	this.possibleCombos = [];
	this.confirmedCombos = []

	this.checkWord = function() {
		this.findPossibleFirsts();
		do {
			this.traceOutPossiblesOneDie();
		} while (this.possibleCombos.length != 0);
	}

	this.wordExcerpt = function(word, start, len) {
		var chars = []
		for (var i=0; i<len; i++) {
			chars.push(word[start+i]);
		}
		return chars.join("");
	}

	this.findPossibleFirsts = function() {
		var i = 0;
		for (var tr=1; tr<=SIDE; tr++){ // go thru each row
			for (var td=1; td<=SIDE; td++){ // go thru each col
				var die = board.dice[i]
				var textLength = die.face.length;
				if (die.face === this.wordExcerpt(word, 0, textLength)) {
					this.possibleCombos.push([die]);
				}
			i += 1;
			}
		}
	}

	this.traceOutPossiblesOneDie = function() {
		var newPossibles = [];
		for (var i=0; i<this.possibleCombos.length; i++) {
			var numLettersSoFar = 0;
			// go thru each possible combo and determine the number of letter so far
			for (var j=0; j<this.possibleCombos[i].length; j++) {
				numLettersSoFar += this.possibleCombos[i][j].face.length;
				if (numLettersSoFar === word.length) {
					this.confirmedCombos[this.confirmedCombos.length] = clone(this.possibleCombos[i]);
				}
			}
			// then for each of the neighbors of the last die in the combo
			var lastDie = this.possibleCombos[i][this.possibleCombos[i].length-1]
			numNeighbors = lastDie.neighbors.length;
			for (var n=0; n<numNeighbors ; n++) {
				var neighbor = lastDie.neighbors[n];
				if (neighbor.face === this.wordExcerpt(word, numLettersSoFar, neighbor.face.length)) {
					var currentArray = clone(this.possibleCombos[i]);
					currentArray[currentArray.length] = neighbor;
					newPossibles[newPossibles.length] = currentArray;
				}
			}
		}
		this.possibleCombos = newPossibles;
	}

}<commit_msg>add function to highlight tiles of valid words<commit_after>function WordChecker(word, board) {
	this.possibleCombos = [];
	this.confirmedCombos = []

	this.checkWord = function() {
		this.findPossibleFirsts();
		do {
			this.traceOutPossiblesOneDie();
		} while (this.possibleCombos.length != 0);
		// REMOVE ANY COMBOS WITH OVERLAPPING DUPLICATES?????
		this.highlightWord(0);
	}

	this.highlightWord = function(ind) {
		if (this.confirmedCombos.length > 0) {
			for (var i=0; i<this.confirmedCombos[ind].length; i++) {
				console.log("HEY" + i);
				this.confirmedCombos[ind][i].dom.css("background-color", "pink");
			}
		}
	}

	this.wordExcerpt = function(word, start, len) {
		var chars = []
		for (var i=0; i<len; i++) {
			chars.push(word[start+i]);
		}
		return chars.join("");
	}

	this.findPossibleFirsts = function() {
		var i = 0;
		for (var tr=1; tr<=SIDE; tr++){ // go thru each row
			for (var td=1; td<=SIDE; td++){ // go thru each col
				var die = board.dice[i]
				var textLength = die.face.length;
				if (die.face === this.wordExcerpt(word, 0, textLength)) {
					this.possibleCombos.push([die]);
				}
			i += 1;
			}
		}
	}

	this.traceOutPossiblesOneDie = function() {
		var newPossibles = [];
		for (var i=0; i<this.possibleCombos.length; i++) {
			var numLettersSoFar = 0;
			// go thru each possible combo and determine the number of letter so far
			for (var j=0; j<this.possibleCombos[i].length; j++) {
				numLettersSoFar += this.possibleCombos[i][j].face.length;
				if (numLettersSoFar === word.length) {
					this.confirmedCombos[this.confirmedCombos.length] = clone(this.possibleCombos[i]);
				}
			}
			// then for each of the neighbors of the last die in the combo
			var lastDie = this.possibleCombos[i][this.possibleCombos[i].length-1]
			numNeighbors = lastDie.neighbors.length;
			for (var n=0; n<numNeighbors ; n++) {
				var neighbor = lastDie.neighbors[n];
				if (neighbor.face === this.wordExcerpt(word, numLettersSoFar, neighbor.face.length)) {
					var currentArray = clone(this.possibleCombos[i]);
					currentArray[currentArray.length] = neighbor;
					newPossibles[newPossibles.length] = currentArray;
				}
			}
		}
		this.possibleCombos = newPossibles;
	}

}<|endoftext|>


<commit_before>'use strict';
angular.module('Thermostats').controller('mapCtrl', function ($http) { // eslint-disable-line prefer-arrow-callback

  const mapCtrl = this;
  mapCtrl.zip = mapCtrl.error = '';
  mapCtrl.heat = mapCtrl.cool = 60;
  mapCtrl.noheat = mapCtrl.nocool = false;
  mapCtrl.show = 'heat';

	// Grabs whole country summary data from API
  const retrieveData = () => {
    return $http.get('/api/summary')
    .then(response => {
      const rawtemps = response.data,
            temps = {
              heat: {},
              cool: {}
            };
      rawtemps.forEach(temp => {
        temps.heat[`US-${temp.abbr}`] = temp.data.heat;
        temps.cool[`US-${temp.abbr}`] = temp.data.cool;
      })
      return temps;
    });
  }

	// Generates and populates map with initial data
  const buildMap = (temps) => {
    $('#map').vectorMap({
      map: 'us_lcc_en',
      backgroundColor: '#214244',
      series: {
        regions: [{
          values: temps.heat,
          scale: ['#ffeded', '#ff0000'],
          min: 30,
          max: 90
        }]
      },
      onRegionClick: (e, code) => { // eslint-disable-line no-unused-vars
				// console.log(code.slice(3)); // grabs state abbreviation
        $('#input-modal').modal();
      },
      onRegionTipShow: (e, label, code) => {
        const h_data = temps.heat[code],
              c_data = temps.cool[code];
        if (h_data && c_data) {
          label.html(`${label.html()}<br>Avg Heat - ${h_data}°<br>Avg Cool - ${c_data}°`);
        }
      }
    });
    const mapObject = $('#map').vectorMap('get', 'mapObject');
    return mapObject;
  }

  let mapData;
  retrieveData().then(temps => {
    const promisedData = {
      mapObject: buildMap(temps),
      mapTemps: temps
    }
    return promisedData;
  }).then(promisedData => { mapData = promisedData });

  // Switches display of data between heating and cooling
	// also cross-purposed to update map data after form submission
  mapCtrl.swap = () => {
    const map = mapData.mapObject.series.regions[0];
    if (mapCtrl.show === 'heat') {
      map.setValues(mapData.mapTemps.heat);
      map.setScale(['#ffeded', '#ff0000']);
    } else {
      map.setValues(mapData.mapTemps.cool);
      map.setScale(['#0000ff', '#ededff']);
    }
  }

	// Clears form data
  mapCtrl.clear = () => {
    mapCtrl.zip = mapCtrl.error = '';
    mapCtrl.heat = mapCtrl.cool = 60;
    mapCtrl.noheat = mapCtrl.nocool = null;
    $('.error-block').collapse('hide');
  }

	// Submits form data for new temperature to the database
  mapCtrl.send = () => {
    $http.post('/api', {
      zip: mapCtrl.zip,
      heat: mapCtrl.heat,
      cool: mapCtrl.cool,
      noheat: mapCtrl.noheat,
      nocool: mapCtrl.nocool
    })
    .then(succResp => {
      const failMessages = [
        'Blank lookup (you must provide a ZIP Code and/or City/State combination).',
        'Invalid ZIP Code.'
      ];
      if (failMessages.includes(succResp.data.message)) {
        $('.error-block').collapse('show');
        mapCtrl.error = 'Please provide a valid ZIP Code.';
        mapCtrl.zip = '';
      } else {
        retrieveData().then(temps => {
          mapData.mapTemps = temps;
          mapCtrl.swap();
        });
        mapCtrl.clear();
        $('#input-modal').modal('hide');
      }
    }, failResp => {
      console.log('Post failure:', failResp); // eslint-disable-line no-console
    });
  };
});
<commit_msg>Added F to mouseover info block<commit_after>'use strict';
angular.module('Thermostats').controller('mapCtrl', function ($http) { // eslint-disable-line prefer-arrow-callback

  const mapCtrl = this;
  mapCtrl.zip = mapCtrl.error = '';
  mapCtrl.heat = mapCtrl.cool = 60;
  mapCtrl.noheat = mapCtrl.nocool = false;
  mapCtrl.show = 'heat';

	// Grabs whole country summary data from API
  const retrieveData = () => {
    return $http.get('/api/summary')
    .then(response => {
      const rawtemps = response.data,
            temps = {
              heat: {},
              cool: {}
            };
      rawtemps.forEach(temp => {
        temps.heat[`US-${temp.abbr}`] = temp.data.heat;
        temps.cool[`US-${temp.abbr}`] = temp.data.cool;
      })
      return temps;
    });
  }

	// Generates and populates map with initial data
  const buildMap = (temps) => {
    $('#map').vectorMap({
      map: 'us_lcc_en',
      backgroundColor: '#214244',
      series: {
        regions: [{
          values: temps.heat,
          scale: ['#ffeded', '#ff0000'],
          min: 30,
          max: 90
        }]
      },
      onRegionClick: (e, code) => { // eslint-disable-line no-unused-vars
				// console.log(code.slice(3)); // grabs state abbreviation
        $('#input-modal').modal();
      },
      onRegionTipShow: (e, label, code) => {
        const h_data = temps.heat[code],
              c_data = temps.cool[code];
        if (h_data && c_data) {
          label.html(`${label.html()}<br>Avg Heat - ${h_data}°F<br>Avg Cool - ${c_data}°F`);
        }
      }
    });
    const mapObject = $('#map').vectorMap('get', 'mapObject');
    return mapObject;
  }

  let mapData;
  retrieveData().then(temps => {
    const promisedData = {
      mapObject: buildMap(temps),
      mapTemps: temps
    }
    return promisedData;
  }).then(promisedData => { mapData = promisedData });

  // Switches display of data between heating and cooling
	// also cross-purposed to update map data after form submission
  mapCtrl.swap = () => {
    const map = mapData.mapObject.series.regions[0];
    if (mapCtrl.show === 'heat') {
      map.setValues(mapData.mapTemps.heat);
      map.setScale(['#ffeded', '#ff0000']);
    } else {
      map.setValues(mapData.mapTemps.cool);
      map.setScale(['#0000ff', '#ededff']);
    }
  }

	// Clears form data
  mapCtrl.clear = () => {
    mapCtrl.zip = mapCtrl.error = '';
    mapCtrl.heat = mapCtrl.cool = 60;
    mapCtrl.noheat = mapCtrl.nocool = null;
    $('.error-block').collapse('hide');
  }

	// Submits form data for new temperature to the database
  mapCtrl.send = () => {
    $http.post('/api', {
      zip: mapCtrl.zip,
      heat: mapCtrl.heat,
      cool: mapCtrl.cool,
      noheat: mapCtrl.noheat,
      nocool: mapCtrl.nocool
    })
    .then(succResp => {
      const failMessages = [
        'Blank lookup (you must provide a ZIP Code and/or City/State combination).',
        'Invalid ZIP Code.'
      ];
      if (failMessages.includes(succResp.data.message)) {
        $('.error-block').collapse('show');
        mapCtrl.error = 'Please provide a valid ZIP Code.';
        mapCtrl.zip = '';
      } else {
        retrieveData().then(temps => {
          mapData.mapTemps = temps;
          mapCtrl.swap();
        });
        mapCtrl.clear();
        $('#input-modal').modal('hide');
      }
    }, failResp => {
      console.log('Post failure:', failResp); // eslint-disable-line no-console
    });
  };
});
<|endoftext|>


<commit_before>var debug = require('debug')('keystone:core:routes');

/**
 * Adds bindings for the keystone routes
 *
 * ####Example:
 *
 *     var app = express();
 *     app.use(...); // middleware, routes, etc. should come before keystone is initialised
 *     keystone.routes(app);
 *
 * @param {Express()} app
 * @api public
 */
function routes(app) {
	this.app = app;
	var keystone = this;

	// ensure keystone nav has been initialised
	if (!this.nav) {
		debug('setting up nav');
		this.nav = this.initNav();
	}

	// Cache compiled view templates if we are in Production mode
	this.set('view cache', this.get('env') === 'production');

	// Bind auth middleware (generic or custom) to /keystone* routes, allowing
	// access to the generic signin page if generic auth is used

	if (this.get('auth') === true) {
		debug('setting up auth');

		if (!this.get('signout url')) {
			this.set('signout url', '/keystone/signout');
		}
		if (!this.get('signin url')) {
			this.set('signin url', '/keystone/signin');
		}

		if (!this.nativeApp || !this.get('session')) {
			app.all('/keystone*', this.session.persist);
		}

		app.all('/keystone/signin', require('../../admin/routes/views/signin'));
		app.all('/keystone/signout', require('../../admin/routes/views/signout'));
		app.all('/keystone*', this.session.keystoneAuth);

	} else if ('function' === typeof this.get('auth')) {
		debug('setting up auth');
		app.all('/keystone*', this.get('auth'));
	}

	function initList(respectHiddenOption) {
		return function(req, res, next) {
			req.list = keystone.list(req.params.list);

			if (!req.list || (respectHiddenOption && req.list.get('hidden'))) {
				debug('could not find list ', req.params.list);
				req.flash('error', 'List ' + req.params.list + ' could not be found.');
				return res.redirect('/keystone');
			}

			debug('getting list ', req.params.list);
			next();
		};
	}

	debug('setting keystone Admin Route');
	app.all('/keystone', require('../../admin/routes/views/home'));

	// Email test routes
	if (this.get('email tests')) {
		debug('setting email test routes');
		this.bindEmailTestRoutes(app, this.get('email tests'));
	}

	// Cloudinary API for selecting an existing image / upload a new image
	if (keystone.get('cloudinary config')) {
		debug('setting cloudinary api');
		app.get('/keystone/api/cloudinary/get', require('../../admin/api/cloudinary').get);
		app.get('/keystone/api/cloudinary/autocomplete', require('../../admin/api/cloudinary').autocomplete);
		app.post('/keystone/api/cloudinary/upload', require('../../admin/api/cloudinary').upload);
	}

	// Init API request helpers
	app.use('/keystone/api', function(req, res, next) {
		res.apiError = function(err, key) {
			var statusCode = 500;
			if (err === 404) {
				statusCode = 404;
				err = null;
				key = 'not found';
			}
			if (typeof err === 'object' && err.message) {
				err = err.message;
			}
			if (!err) {
				err = 'API Error';
			}
			if (!key) {
				key = 'unknown error';
			}
			res.status(statusCode);
			res.json({ err: err, key: key });
		};
		next();
	});

	// Generic Lists API
	debug('setting generic list api');
	app.all('/keystone/api/:list/:action(autocomplete|get|order|create|delete|fetch)', initList(), require('../../admin/api/list'));
	app.get('/keystone/api/:list/:id', initList(), require('../../admin/api/item/get'));
	app.post('/keystone/api/:list/:id/delete', initList(), require('../../admin/api/item/delete'));

	debug('setting generic Lists download route');
	app.all('/keystone/download/:list', initList(), require('../../admin/api/download'));

	// Admin-UI API
	debug('setting list and item details admin routes');
	app.all('/keystone/:list/:page([0-9]{1,5})?', initList(true), require('../../admin/routes/views/list'));
	app.all('/keystone/:list/:item', initList(true), require('../../admin/routes/views/item'));

	return this;
}

module.exports = routes;
<commit_msg>Fixing api error handling middleware<commit_after>var debug = require('debug')('keystone:core:routes');

/**
 * Adds bindings for the keystone routes
 *
 * ####Example:
 *
 *     var app = express();
 *     app.use(...); // middleware, routes, etc. should come before keystone is initialised
 *     keystone.routes(app);
 *
 * @param {Express()} app
 * @api public
 */
function routes(app) {
	this.app = app;
	var keystone = this;

	// ensure keystone nav has been initialised
	if (!this.nav) {
		debug('setting up nav');
		this.nav = this.initNav();
	}

	// Cache compiled view templates if we are in Production mode
	this.set('view cache', this.get('env') === 'production');

	// Bind auth middleware (generic or custom) to /keystone* routes, allowing
	// access to the generic signin page if generic auth is used

	if (this.get('auth') === true) {
		debug('setting up auth');

		if (!this.get('signout url')) {
			this.set('signout url', '/keystone/signout');
		}
		if (!this.get('signin url')) {
			this.set('signin url', '/keystone/signin');
		}

		if (!this.nativeApp || !this.get('session')) {
			app.all('/keystone*', this.session.persist);
		}

		app.all('/keystone/signin', require('../../admin/routes/views/signin'));
		app.all('/keystone/signout', require('../../admin/routes/views/signout'));
		app.all('/keystone*', this.session.keystoneAuth);

	} else if ('function' === typeof this.get('auth')) {
		debug('setting up auth');
		app.all('/keystone*', this.get('auth'));
	}

	function initList(respectHiddenOption) {
		return function(req, res, next) {
			req.list = keystone.list(req.params.list);

			if (!req.list || (respectHiddenOption && req.list.get('hidden'))) {
				debug('could not find list ', req.params.list);
				req.flash('error', 'List ' + req.params.list + ' could not be found.');
				return res.redirect('/keystone');
			}

			debug('getting list ', req.params.list);
			next();
		};
	}

	debug('setting keystone Admin Route');
	app.all('/keystone', require('../../admin/routes/views/home'));

	// Email test routes
	if (this.get('email tests')) {
		debug('setting email test routes');
		this.bindEmailTestRoutes(app, this.get('email tests'));
	}

	// Cloudinary API for selecting an existing image / upload a new image
	if (keystone.get('cloudinary config')) {
		debug('setting cloudinary api');
		app.get('/keystone/api/cloudinary/get', require('../../admin/api/cloudinary').get);
		app.get('/keystone/api/cloudinary/autocomplete', require('../../admin/api/cloudinary').autocomplete);
		app.post('/keystone/api/cloudinary/upload', require('../../admin/api/cloudinary').upload);
	}

	// Init API request helpers
	app.use('/keystone/api', function(req, res, next) {
		res.apiError = function(key, err) {
			var statusCode = 500;
			if (key === 404) {
				statusCode = 404;
				key = null;
				key = 'not found';
			}
			if (!key) {
				key = 'unknown error';
			}
			if (!err) {
				err = 'API Error';
			}
			if (typeof err === 'object' && err.message) {
				err = err.message;
			}
			res.status(statusCode);
			res.json({ err: err, key: key });
		};
		next();
	});

	// Generic Lists API
	debug('setting generic list api');
	app.all('/keystone/api/:list/:action(autocomplete|get|order|create|delete|fetch)', initList(), require('../../admin/api/list'));
	app.get('/keystone/api/:list/:id', initList(), require('../../admin/api/item/get'));
	app.post('/keystone/api/:list/:id/delete', initList(), require('../../admin/api/item/delete'));

	debug('setting generic Lists download route');
	app.all('/keystone/download/:list', initList(), require('../../admin/api/download'));

	// Admin-UI API
	debug('setting list and item details admin routes');
	app.all('/keystone/:list/:page([0-9]{1,5})?', initList(true), require('../../admin/routes/views/list'));
	app.all('/keystone/:list/:item', initList(true), require('../../admin/routes/views/item'));

	return this;
}

module.exports = routes;
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var util = require('util')
	, crypto = require('crypto')
	, _ = require('lodash');

// Make _.defaults recursive
_.defaults = require('merge-defaults');

/**
 * This `before` function is run before generating targets.
 * Validate, configure defaults, get extra dependencies, etc.
 *
 * @param  {Object} scope
 * @param  {Function} cb    [callback]
 */

module.exports = function(scope, cb) {

	//
	// Validate custom scope variables which
	// are required by this generator.
	//
	//
	if ( !scope.rootPath ) {
		return cb(new Error(
			'Missing scope variable: `rootPath`\n' +
			'Please make sure it is specified and try again.'
		));
	}

	//
	// Determine default values based on the
	// available scope.
	//
	_.defaults(scope, {
		currentTime: new Date(),
		viewEngine: 'ejs'
	});

	// Determine which views generator to use
	if (scope.viewEngine && scope.viewEngine !== 'ejs') {
		scope.modules['views'] = 'sails-generate-views-'+scope.viewEngine;

		// enable partials and layout for handlebars
		if (scope.viewEngine === 'handlebars') {
			scope.layout = 'layouts/layout';
			scope.partials = 'partials';
		}
	}

	// Only .ejs gets layout
	else {
		scope.layout = 'layout';
	}

	// Create a default session secret
	scope.secret = generateSecret();

	cb();
};

/**
 * Generate session secret
 * @return {[type]} [description]
 */
function generateSecret () {

	// Combine random and case-specific factors into a base string
	var factors = {
		creationDate: (new Date()).getTime(),
		random: Math.random() * (Math.random() * 1000),
		nodeVersion: process.version
	};
	var basestring = '';
	_.each(factors, function (val) { basestring += val; });

	// Build hash
	var hash =	crypto.
				createHash('md5').
				update(basestring).
				digest('hex');

	return hash;
};
<commit_msg>Update before.js<commit_after>/**
 * Module dependencies
 */

var util = require('util');
var crypto = require('crypto');
var _ = require('lodash');
var mergeDefaults = require('merge-defaults');

/**
 * This `before` function is run before generating targets.
 * Validate, configure defaults, get extra dependencies, etc.
 *
 * @param  {Object} scope
 * @param  {Function} cb    [callback]
 */

module.exports = function(scope, cb) {

	//
	// Validate custom scope variables which
	// are required by this generator.
	//
	//
	if ( !scope.rootPath ) {
		return cb(new Error(
			'Missing scope variable: `rootPath`\n' +
			'Please make sure it is specified and try again.'
		));
	}

	//
	// Determine default values based on the
	// available scope.
	//
	mergeDefaults(scope, {
		currentTime: new Date(),
		viewEngine: 'ejs'
	});

	// Determine which views generator to use
	if (scope.viewEngine && scope.viewEngine !== 'ejs') {
		scope.modules['views'] = 'sails-generate-views-'+scope.viewEngine;

		// enable partials and layout for handlebars
		if (scope.viewEngine === 'handlebars') {
			scope.layout = 'layouts/layout';
			scope.partials = 'partials';
		}
	}

	// Only .ejs gets layout
	else {
		scope.layout = 'layout';
	}

	// Create a default session secret
	scope.secret = generateSecret();

	cb();
};

/**
 * Generate session secret
 * @return {[type]} [description]
 */
function generateSecret () {

	// Combine random and case-specific factors into a base string
	var factors = {
		creationDate: (new Date()).getTime(),
		random: Math.random() * (Math.random() * 1000),
		nodeVersion: process.version
	};
	var basestring = '';
	_.each(factors, function (val) { basestring += val; });

	// Build hash
	var hash =	crypto.
				createHash('md5').
				update(basestring).
				digest('hex');

	return hash;
};
<|endoftext|>


<commit_before>// this could be used with some modifications
//https://github.com/leszekr/bezier-spline-js/blob/master/bezier-spline.js
var t = {}
var _ = require('lodash')
t.linestring = require('./linestring')

module.exports = function(line, resolution, done){
  var lineOut = t.linestring([])
  lineOut.properties = line.properties
  pts = []
  _.each(line.geometry.coordinates, function(pt){
    pts.push({x: pt[0], y: pt[1]})
  })

  var spline = new Spline({
    points: pts,
    duration: 15000,
    //sharpness: how_curvy,
    //stepLength: distance_between_points_to_cache
  });
  for(var i=0; i<spline.duration; i+=10){
    var pos = spline.pos(i); //bezier(i/max,p1, c1, c2, p2);
    if(Math.floor(i/100)%2==0) lineOut.geometry.coordinates.push([pos.x, pos.y]);
    //else ctx.moveTo(pos.x, pos.y);
  }
  done(null, lineOut)
}

 /**
   * BezierSpline
   * http://leszekr.github.com/
   *
   * @copyright
   * Copyright (C) 2012 Leszek Rybicki.
   *
   * @license
   * This file is part of BezierSpline
   *
   * BezierSpline is free software: you can redistribute it and/or modify
   * it under the terms of the GNU Lesser General Public License as published by
   * the Free Software Foundation, either version 3 of the License, or
   * (at your option) any later version.
   *
   * BezierSpline is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with BezierSpline.  If not, see <http://www.gnu.org/copyleft/lesser.html>.
   */

  /*
  Usage:

    var spline = new Spline({
      points: array_of_control_points,
      duration: time_in_miliseconds,
      sharpness: how_curvy,
      stepLength: distance_between_points_to_cache
    });

  */
  Spline = function(options){
    this.points = options.points || [];
    this.duration = options.duration || 10000;
    this.sharpness = options.sharpness || 0.85;
    this.centers = [];
    this.controls = [];
    this.stepLength = options.stepLength || 60;
    this.length = this.points.length;
    this.delay = 0;
    // this is to ensure compatibility with the 2d version
    for(var i=0; i<this.length; i++) this.points[i].z = this.points[i].z || 0;
    for(var i=0; i<this.length-1; i++){
      var p1 = this.points[i];
      var p2 = this.points[i+1];
      this.centers.push({x:(p1.x+p2.x)/2, y:(p1.y+p2.y)/2, z:(p1.z+p2.z)/2});
    }
    this.controls.push([this.points[0],this.points[0]]);
    for(var i=0; i<this.centers.length-1; i++){
      var p1 = this.centers[i];
      var p2 = this.centers[i+1];
      var dx = this.points[i+1].x-(this.centers[i].x+this.centers[i+1].x)/2;
      var dy = this.points[i+1].y-(this.centers[i].y+this.centers[i+1].y)/2;
      var dz = this.points[i+1].z-(this.centers[i].y+this.centers[i+1].z)/2;
      this.controls.push([{
        x:(1.0-this.sharpness)*this.points[i+1].x+this.sharpness*(this.centers[i].x+dx),
        y:(1.0-this.sharpness)*this.points[i+1].y+this.sharpness*(this.centers[i].y+dy),
        z:(1.0-this.sharpness)*this.points[i+1].z+this.sharpness*(this.centers[i].z+dz)},
      {
        x:(1.0-this.sharpness)*this.points[i+1].x+this.sharpness*(this.centers[i+1].x+dx),
        y:(1.0-this.sharpness)*this.points[i+1].y+this.sharpness*(this.centers[i+1].y+dy),
        z:(1.0-this.sharpness)*this.points[i+1].z+this.sharpness*(this.centers[i+1].z+dz)}]);
    }
    this.controls.push([this.points[this.length-1],this.points[this.length-1]]);
    this.steps = this.cacheSteps(this.stepLength);
    return this;
  }

  /*
    Caches an array of equidistant (more or less) points on the curve.
  */
  Spline.prototype.cacheSteps = function(mindist){
    var steps = [];
    var laststep = this.pos(0);
    steps.push(0);
    for(var t=0; t<this.duration; t+=10){
      var step = this.pos(t);
      var dist = Math.sqrt((step.x-laststep.x)*(step.x-laststep.x)+(step.y-laststep.y)*(step.y-laststep.y)+(step.z-laststep.z)*(step.z-laststep.z));
      if(dist>mindist){
        steps.push(t);
        laststep = step;
      }
    }
    return steps;
  }

  /*
    returns angle and speed in the given point in the curve
  */
  Spline.prototype.vector = function(t){
    var p1 = this.pos(t+10);
    var p2 = this.pos(t-10);
    return {
      angle:180*Math.atan2(p1.y-p2.y, p1.x-p2.x)/3.14,
      speed:Math.sqrt((p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y)+(p2.z-p1.z)*(p2.z-p1.z))
    }
  }

  /*
    Draws the control points
  */
  Spline.prototype.drawControlPoints = function(ctx, color){
    ctx.fillStyle = color||"#f60";
    ctx.strokeStyle = "#fff";
    ctx.lineWidth = 2;
    for(var i=0; i<this.length; i++){
      var p = this.points[i];
      var c1 = this.controls[i][0];
      var c2 = this.controls[i][1];

      ctx.beginPath();
      ctx.moveTo(c1.x,c1.y);
      ctx.lineTo(p.x,p.y);
      ctx.lineTo(c2.x,c2.y);
      ctx.stroke();

      ctx.beginPath();
      ctx.arc(c1.x, c1.y, 3, 0, 2 * Math.PI, false);
      ctx.fill();
      ctx.stroke();

      /*ctx.beginPath();
      ctx.arc(this.centers[i].x, this.centers[i].y, 5, 0, 2 * Math.PI, false);
      ctx.fill();
      ctx.stroke();*/

      ctx.beginPath();
      ctx.arc(c2.x, c2.y, 3, 0, 2 * Math.PI, false);
      ctx.fill();
      ctx.stroke();

      ctx.beginPath();
      ctx.arc(p.x, p.y, 7, 0, 2 * Math.PI, false);
      ctx.fill();
      ctx.stroke();
    }
    return this;
  }

  /*
    Gets the position of the point, given time.

    WARNING: The speed is not constant. The time it takes between control points is constant.

    For constant speed, use Spline.steps[i];
  */
  Spline.prototype.pos = function(time){

    function bezier(t, p1, c1, c2, p2){
      var B = function(t) {
        var t2=t*t, t3=t2*t;
        return [(t3),(3*t2*(1-t)),(3*t*(1-t)*(1-t)),((1-t)*(1-t)*(1-t))]
      }
      var b = B(t)
      var pos = {
        x : p2.x * b[0] + c2.x * b[1] +c1.x * b[2] + p1.x * b[3],
        y : p2.y * b[0] + c2.y * b[1] +c1.y * b[2] + p1.y * b[3],
        z : p2.z * b[0] + c2.z * b[1] +c1.z * b[2] + p1.z * b[3]
      }
      return pos;
    }
    var t = time-this.delay;
    if(t<0) t=0;
    if(t>this.duration) t=this.duration-1;
    //t = t-this.delay;
    var t2 = (t)/this.duration;
    if(t2>=1) return this.points[this.length-1];

    var n = Math.floor((this.points.length-1)*t2);
    var t1 = (this.length-1)*t2-n;
    return bezier(t1,this.points[n],this.controls[n][1],this.controls[n+1][0],this.points[n+1]);
  }

  /*
    Draws the line
  */
  Spline.prototype.draw = function(ctx,color){
    ctx.strokeStyle = color || "#7e5e38"; // line color
    ctx.lineWidth = 14;
    ctx.beginPath();
    var pos;
    for(var i=0; i<this.duration; i+=10){
      pos = this.pos(i); //bezier(i/max,p1, c1, c2, p2);
      if(Math.floor(i/100)%2==0) ctx.lineTo(pos.x, pos.y);
      else ctx.moveTo(pos.x, pos.y);
    }
    ctx.stroke();
    return this;
  }<commit_msg>added intensity option<commit_after>// code modded from here:
//https://github.com/leszekr/bezier-spline-js/blob/master/bezier-spline.js
var t = {}
var _ = require('lodash')
t.linestring = require('./linestring')

module.exports = function(line, resolution, intensity, done){
  var lineOut = t.linestring([])
  lineOut.properties = line.properties
  pts = []
  _.each(line.geometry.coordinates, function(pt){
    pts.push({x: pt[0], y: pt[1]})
  })

  var spline = new Spline({
    points: pts,
    duration: resolution,
    sharpness: intensity,
    //stepLength: distance_between_points_to_cache
  });
  for(var i=0; i<spline.duration; i+=10){
    var pos = spline.pos(i); //bezier(i/max,p1, c1, c2, p2);
    if(Math.floor(i/100)%2==0) lineOut.geometry.coordinates.push([pos.x, pos.y]);
    //else ctx.moveTo(pos.x, pos.y);
  }
  done(null, lineOut)
}

 /**
   * BezierSpline
   * http://leszekr.github.com/
   *
   * @copyright
   * Copyright (C) 2012 Leszek Rybicki.
   *
   * @license
   * This file is part of BezierSpline
   *
   * BezierSpline is free software: you can redistribute it and/or modify
   * it under the terms of the GNU Lesser General Public License as published by
   * the Free Software Foundation, either version 3 of the License, or
   * (at your option) any later version.
   *
   * BezierSpline is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with BezierSpline.  If not, see <http://www.gnu.org/copyleft/lesser.html>.
   */

  /*
  Usage:

    var spline = new Spline({
      points: array_of_control_points,
      duration: time_in_miliseconds,
      sharpness: how_curvy,
      stepLength: distance_between_points_to_cache
    });

  */
  Spline = function(options){
    this.points = options.points || [];
    this.duration = options.duration || 10000;
    this.sharpness = options.sharpness || 0.85;
    this.centers = [];
    this.controls = [];
    this.stepLength = options.stepLength || 60;
    this.length = this.points.length;
    this.delay = 0;
    // this is to ensure compatibility with the 2d version
    for(var i=0; i<this.length; i++) this.points[i].z = this.points[i].z || 0;
    for(var i=0; i<this.length-1; i++){
      var p1 = this.points[i];
      var p2 = this.points[i+1];
      this.centers.push({x:(p1.x+p2.x)/2, y:(p1.y+p2.y)/2, z:(p1.z+p2.z)/2});
    }
    this.controls.push([this.points[0],this.points[0]]);
    for(var i=0; i<this.centers.length-1; i++){
      var p1 = this.centers[i];
      var p2 = this.centers[i+1];
      var dx = this.points[i+1].x-(this.centers[i].x+this.centers[i+1].x)/2;
      var dy = this.points[i+1].y-(this.centers[i].y+this.centers[i+1].y)/2;
      var dz = this.points[i+1].z-(this.centers[i].y+this.centers[i+1].z)/2;
      this.controls.push([{
        x:(1.0-this.sharpness)*this.points[i+1].x+this.sharpness*(this.centers[i].x+dx),
        y:(1.0-this.sharpness)*this.points[i+1].y+this.sharpness*(this.centers[i].y+dy),
        z:(1.0-this.sharpness)*this.points[i+1].z+this.sharpness*(this.centers[i].z+dz)},
      {
        x:(1.0-this.sharpness)*this.points[i+1].x+this.sharpness*(this.centers[i+1].x+dx),
        y:(1.0-this.sharpness)*this.points[i+1].y+this.sharpness*(this.centers[i+1].y+dy),
        z:(1.0-this.sharpness)*this.points[i+1].z+this.sharpness*(this.centers[i+1].z+dz)}]);
    }
    this.controls.push([this.points[this.length-1],this.points[this.length-1]]);
    this.steps = this.cacheSteps(this.stepLength);
    return this;
  }

  /*
    Caches an array of equidistant (more or less) points on the curve.
  */
  Spline.prototype.cacheSteps = function(mindist){
    var steps = [];
    var laststep = this.pos(0);
    steps.push(0);
    for(var t=0; t<this.duration; t+=10){
      var step = this.pos(t);
      var dist = Math.sqrt((step.x-laststep.x)*(step.x-laststep.x)+(step.y-laststep.y)*(step.y-laststep.y)+(step.z-laststep.z)*(step.z-laststep.z));
      if(dist>mindist){
        steps.push(t);
        laststep = step;
      }
    }
    return steps;
  }

  /*
    returns angle and speed in the given point in the curve
  */
  Spline.prototype.vector = function(t){
    var p1 = this.pos(t+10);
    var p2 = this.pos(t-10);
    return {
      angle:180*Math.atan2(p1.y-p2.y, p1.x-p2.x)/3.14,
      speed:Math.sqrt((p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y)+(p2.z-p1.z)*(p2.z-p1.z))
    }
  }

  /*
    Draws the control points
  */
  Spline.prototype.drawControlPoints = function(ctx, color){
    ctx.fillStyle = color||"#f60";
    ctx.strokeStyle = "#fff";
    ctx.lineWidth = 2;
    for(var i=0; i<this.length; i++){
      var p = this.points[i];
      var c1 = this.controls[i][0];
      var c2 = this.controls[i][1];

      ctx.beginPath();
      ctx.moveTo(c1.x,c1.y);
      ctx.lineTo(p.x,p.y);
      ctx.lineTo(c2.x,c2.y);
      ctx.stroke();

      ctx.beginPath();
      ctx.arc(c1.x, c1.y, 3, 0, 2 * Math.PI, false);
      ctx.fill();
      ctx.stroke();

      /*ctx.beginPath();
      ctx.arc(this.centers[i].x, this.centers[i].y, 5, 0, 2 * Math.PI, false);
      ctx.fill();
      ctx.stroke();*/

      ctx.beginPath();
      ctx.arc(c2.x, c2.y, 3, 0, 2 * Math.PI, false);
      ctx.fill();
      ctx.stroke();

      ctx.beginPath();
      ctx.arc(p.x, p.y, 7, 0, 2 * Math.PI, false);
      ctx.fill();
      ctx.stroke();
    }
    return this;
  }

  /*
    Gets the position of the point, given time.

    WARNING: The speed is not constant. The time it takes between control points is constant.

    For constant speed, use Spline.steps[i];
  */
  Spline.prototype.pos = function(time){

    function bezier(t, p1, c1, c2, p2){
      var B = function(t) {
        var t2=t*t, t3=t2*t;
        return [(t3),(3*t2*(1-t)),(3*t*(1-t)*(1-t)),((1-t)*(1-t)*(1-t))]
      }
      var b = B(t)
      var pos = {
        x : p2.x * b[0] + c2.x * b[1] +c1.x * b[2] + p1.x * b[3],
        y : p2.y * b[0] + c2.y * b[1] +c1.y * b[2] + p1.y * b[3],
        z : p2.z * b[0] + c2.z * b[1] +c1.z * b[2] + p1.z * b[3]
      }
      return pos;
    }
    var t = time-this.delay;
    if(t<0) t=0;
    if(t>this.duration) t=this.duration-1;
    //t = t-this.delay;
    var t2 = (t)/this.duration;
    if(t2>=1) return this.points[this.length-1];

    var n = Math.floor((this.points.length-1)*t2);
    var t1 = (this.length-1)*t2-n;
    return bezier(t1,this.points[n],this.controls[n][1],this.controls[n+1][0],this.points[n+1]);
  }

  /*
    Draws the line
  */
  Spline.prototype.draw = function(ctx,color){
    ctx.strokeStyle = color || "#7e5e38"; // line color
    ctx.lineWidth = 14;
    ctx.beginPath();
    var pos;
    for(var i=0; i<this.duration; i+=10){
      pos = this.pos(i); //bezier(i/max,p1, c1, c2, p2);
      if(Math.floor(i/100)%2==0) ctx.lineTo(pos.x, pos.y);
      else ctx.moveTo(pos.x, pos.y);
    }
    ctx.stroke();
    return this;
  }<|endoftext|>


<commit_before>const https = require('https')
const BN = require('../../../bn')
const E = require('../../../error')

const axios = require('axios').create({
  // TODO: get rejectUnauthorized true to work
  baseURL: 'https://localhost:5555/api/',
  httpsAgent: new https.Agent({
    rejectUnauthorized: false
  })
})

const SUPPORTED_COINS = ['BTC']

function checkCryptoCode (cryptoCode) {
  if (!SUPPORTED_COINS.includes(cryptoCode)) {
    return Promise.reject(new Error('Unsupported crypto: ' + cryptoCode))
  }

  return Promise.resolve()
}

function balance (account, cryptoCode, settings, operatorId) {
  return axios.post('/balance', {
    account,
    cryptoCode,
    settings,
    operatorId
  }).catch(console.error)
}

function sendCoins (account, tx, settings, operatorId) {
  const { cryptoCode } = tx
  try {
    return checkCryptoCode(cryptoCode).then(() => {
      return axios.post('/sendCoins', {
        account,
        tx,
        settings,
        operatorId
      }).then(({ data }) => {
        if (data.error && data.error.message === 'insufficient funds') throw new E.InsufficientFundsError()
        else if (data.error) throw new Error({ error: data.error, message: data.error.message })
        const fee = BN(data.fee).round()
        const txid = data.txid
        return { txid, fee }
      })
    })
  } catch (e) {
    throw e
  }
}

function newAddress (account, info, tx, settings, operatorId) {
  return axios.post('/newAddress', {
    account,
    info,
    tx,
    settings,
    operatorId
  }).catch(console.error)
}

function newFunding (account, cryptoCode, settings, operatorId) {
  return axios.post('/newFunding', {
    account,
    cryptoCode,
    settings,
    operatorId
  }).catch(console.error)
}

function getStatus (account, tx, requested, settings, operatorId) {
  return axios.post('/getStatus', {
    account,
    tx,
    requested,
    settings,
    operatorId
  }).catch(console.error)
}

function sweep (account, cryptoCode, hdIndex, settings, operatorId) {
  return axios.post('/sweep', {
    account,
    cryptoCode,
    hdIndex,
    settings,
    operatorId
  }).catch(console.error)
}

function cryptoNetwork (account, cryptoCode, settings, operatorId) {
  return axios.post('/cryptoNetwork', {
    account,
    cryptoCode,
    settings,
    operatorId
  }).catch(console.error)
}

function isStrictAddress (cryptoCode, toAddress, settings, operatorId) {
  return axios.post('/isStrictAddress', {
    cryptoCode,
    toAddress,
    settings,
    operatorId
  }).catch(console.error)
}

module.exports = {
  balance,
  sendCoins,
  newAddress,
  newFunding,
  getStatus,
  sweep,
  supportsHd: true,
  cryptoNetwork,
  isStrictAddress
}
<commit_msg>Fix: error handling<commit_after>const https = require('https')
const BN = require('../../../bn')
const E = require('../../../error')

const axios = require('axios').create({
  // TODO: get rejectUnauthorized true to work
  baseURL: 'https://localhost:5555/api/',
  httpsAgent: new https.Agent({
    rejectUnauthorized: false
  })
})

const SUPPORTED_COINS = ['BTC', 'ZEC', 'LTC', 'BCH', 'DASH', 'ETH']

function checkCryptoCode (cryptoCode) {
  if (!SUPPORTED_COINS.includes(cryptoCode)) {
    return Promise.reject(new Error('Unsupported crypto: ' + cryptoCode))
  }

  return Promise.resolve()
}

function balance (account, cryptoCode, settings, operatorId) {
  return checkCryptoCode(cryptoCode).then(() => {
    return axios.post('/balance', {
      account,
      cryptoCode,
      settings,
      operatorId
    }).then(({ data }) => {
      if (data.error) throw new Error(JSON.stringify({ errorCode: data.error.errorCode, message: data.error.message }))
      return BN(data.balance)
    })
  })
}

function sendCoins (account, tx, settings, operatorId) {
  const { cryptoCode } = tx
  return checkCryptoCode(cryptoCode).then(() => {
    return axios.post('/sendCoins', {
      account,
      tx,
      settings,
      operatorId
    }).then(({ data }) => {
      if (data.error && data.error.errorCode === 'sc-001') throw new E.InsufficientFundsError()
      else if (data.error) throw new Error(JSON.stringify({ errorCode: data.error.errorCode, message: data.error.message }))
      const fee = BN(data.fee).round()
      const txid = data.txid
      return { txid, fee }
    })
  })
}

function newAddress (account, info, tx, settings, operatorId) {
  return axios.post('/newAddress', {
    account,
    info,
    tx,
    settings,
    operatorId
  }).catch(console.error)
}

function newFunding (account, cryptoCode, settings, operatorId) {
  return axios.post('/newFunding', {
    account,
    cryptoCode,
    settings,
    operatorId
  }).catch(console.error)
}

function getStatus (account, tx, requested, settings, operatorId) {
  return axios.post('/getStatus', {
    account,
    tx,
    requested,
    settings,
    operatorId
  }).catch(console.error)
}

function sweep (account, cryptoCode, hdIndex, settings, operatorId) {
  return axios.post('/sweep', {
    account,
    cryptoCode,
    hdIndex,
    settings,
    operatorId
  }).catch(console.error)
}

function cryptoNetwork (account, cryptoCode, settings, operatorId) {
  return checkCryptoCode(cryptoCode)
    .then(() => axios.post('/cryptoNetwork', {
      account,
      cryptoCode,
      settings,
      operatorId
    }))
    .then(({ data }) => {
      if (data.error && data.error.errorCode === 'cn-001') return false
      else if (data.error) throw new Error(JSON.stringify({ error: data.error, message: data.error.message }))
      return data.cryptoNetwork
    })
}

function isStrictAddress (cryptoCode, toAddress, settings, operatorId) {
  return axios.post('/isStrictAddress', {
    cryptoCode,
    toAddress,
    settings,
    operatorId
  }).catch(console.error)
}

module.exports = {
  balance,
  sendCoins,
  newAddress,
  newFunding,
  getStatus,
  sweep,
  supportsHd: true,
  cryptoNetwork,
  isStrictAddress
}
<|endoftext|>