<commit_before>"use strict"

module.exports = convertCFGtoJS

function value(v) {
  if(v.type === "VariableId" || v.type === "Variable") {
    if(v.id === "~global") {
      return "this"
    } else if(v.id.charAt(0) === "~") {
      return "TMP_" + v.id.substr(1)
    } else {
      return "VAR_" + v.id
    }
  } else if(v.type === "Literal") {
    if(typeof v.value === "string") {
      return "'" + v.value.replace(/\\/g, "\\\\").replace(/\'/g, "\\'") + "'"
    } else if(typeof v.value === "undefined") {
      return "void 0"
    } else if(v.value === null) {
      return "null"
    } else {
      return v.value
    }
  }
}

function convertClosure(closure) {

  var code = ["function ", closure.name, "(", closure.arguments.join(), "){"]
  code.push("var ", closure.variables.map(value).join(), ";VAR_this=this;")

  for(var i=0; i<closure.closures; ++i) {
    var cl = closure.closures[i]
    code.push(cl.id, "=", convertClosure(cl.closure), ";")
  }

  function term() {
    code.push("try{")
    code.push.apply(code, Array.prototype.slice.apply(arguments))
    code.push("}catch(", value(b.terminator.exception,
        "){return BLOCK", b.catch,
        "()}return BLOCK", b.next, "()"))
  }

  for(var i=0; i<closure.blocks.length; ++i) {
    var b = closure.blocks[i]
    code.push("function BLOCK", i, "(){")
    for(var j=0; j<b.body.length; ++j) {
      var op = b.body[j]
      if(op.type === "UnaryOperator") {
        code.push(value(op.destination), "=", op.operator, value(op.argument), ";")
      } else if(op.type === "BinaryOperator") {
        code.push(value(op.destination), "=", value(op.left), op.operator, value(op.right), ";")
      } else {
        throw new Error("Invalid operator: " + op.type)
      }
    }
    switch(b.terminator.type) {
      case "JumpTerminator":
        code.push("return BLOCK", b.terminator.next, "()")
      break

      case "IfTerminator":
        code.push("if(", value(b.terminator.predicate),
                  "){return BLOCK", b.terminator.consequent,
                  "()}return BLOCK", b.terminator.alternate, "()")
      break

      case "NewTerminator":
        term(value(b.terminator.result),
            "=new ", value(b.terminator.constructor),
            "(", b.terminator.arguments.map(value).join(), ")")
      break

      case "SetTerminator":
        term(value(b.terminator.result), "=",
            value(b.terminator.object), "[", value(b.terminator.property), "]=",
            value(b.terminator.value))
      break

      case "GetTerminator":
        term(value(b.terminator.result), "=",
            value(b.terminator.object), "[", value(b.terminator.property), "]")
      break

      case "DeleteTerminator":
        term(value(b.terminator.result), "=delete ",
            value(b.terminator.object), "[", value(b.terminator.property), "]")
      break

      case "HasTerminator":
        term(value(b.terminator.result), "=",
            value(b.terminator.property), " in ", value(b.terminator.object))
      break

      case "CallTerminator":
        term(value(b.terminator.result), "=",
            value(b.terminator.callee), ".call(",
              value(b.terminator.object),
              b.terminator.arguments.map(value).join(), ")")
      break

      case "ReturnTerminator":
        code.push("return ", value(b.terminator.result))
      break

      case "ThrowTerminator":
        code.push("throw ", value(b.terminator.exception))
      break

      default:
        throw new Error("Unrecognized terminator")
    }
    code.push("};")
  }

  code.push("return BLOCK", closure.entry, "();}")

  return code.join("")
}

function convertCFGtoJS(root) {
  return ";(" + convertClosure(root) + ")();"
}<commit_msg>improving support for globals<commit_after>"use strict"

module.exports = convertCFGtoJS

function value(v) {
  if(v.type === "VariableId" || v.type === "Variable") {
    if(v.id.charAt(0) === "~") {
      return "TMP_" + v.id.substr(1)
    } else {
      return "VAR_" + v.id
    }
  } else if(v.type === "Literal") {
    if(typeof v.value === "string") {
      return "'" + v.value.replace(/\\/g, "\\\\").replace(/\'/g, "\\'") + "'"
    } else if(typeof v.value === "undefined") {
      return "void 0"
    } else if(v.value === null) {
      return "null"
    } else {
      return v.value
    }
  }
}

function convertClosure(closure) {

  var code = ["function ", closure.name, "(", closure.arguments.join(), "){"]
  code.push("var ", closure.variables.map(value).join(), ";VAR_this=this;")

  for(var i=0; i<closure.closures; ++i) {
    var cl = closure.closures[i]
    code.push(cl.id, "=", convertClosure(cl.closure), ";")
  }

  function term() {
    code.push("try{")
    code.push.apply(code, Array.prototype.slice.apply(arguments))
    code.push("}catch(", value(b.terminator.exception,
        "){return BLOCK", b.catch,
        "()}return BLOCK", b.next, "()"))
  }

  for(var i=0; i<closure.blocks.length; ++i) {
    var b = closure.blocks[i]
    code.push("function BLOCK", i, "(){")
    for(var j=0; j<b.body.length; ++j) {
      var op = b.body[j]
      if(op.type === "UnaryOperator") {
        code.push(value(op.destination), "=", op.operator, value(op.argument), ";")
      } else if(op.type === "BinaryOperator") {
        code.push(value(op.destination), "=", value(op.left), op.operator, value(op.right), ";")
      } else {
        throw new Error("Invalid operator: " + op.type)
      }
    }
    switch(b.terminator.type) {
      case "JumpTerminator":
        code.push("return BLOCK", b.terminator.next, "()")
      break

      case "IfTerminator":
        code.push("if(", value(b.terminator.predicate),
                  "){return BLOCK", b.terminator.consequent,
                  "()}return BLOCK", b.terminator.alternate, "()")
      break

      case "NewTerminator":
        term(value(b.terminator.result),
            "=new ", value(b.terminator.constructor),
            "(", b.terminator.arguments.map(value).join(), ")")
      break

      case "SetTerminator":
        term(value(b.terminator.result), "=",
            value(b.terminator.object), "[", value(b.terminator.property), "]=",
            value(b.terminator.value))
      break

      case "GetTerminator":
        term(value(b.terminator.result), "=",
            value(b.terminator.object), "[", value(b.terminator.property), "]")
      break

      case "DeleteTerminator":
        term(value(b.terminator.result), "=delete ",
            value(b.terminator.object), "[", value(b.terminator.property), "]")
      break

      case "HasTerminator":
        term(value(b.terminator.result), "=",
            value(b.terminator.property), " in ", value(b.terminator.object))
      break

      case "CallTerminator":
        term(value(b.terminator.result), "=",
            value(b.terminator.callee), ".call(",
              value(b.terminator.object),
              b.terminator.arguments.map(value).join(), ")")
      break

      case "ReturnTerminator":
        code.push("return ", value(b.terminator.result))
      break

      case "ThrowTerminator":
        code.push("throw ", value(b.terminator.exception))
      break

      default:
        throw new Error("Unrecognized terminator")
    }
    code.push("};")
  }

  code.push("return BLOCK", closure.entry, "();}")

  return code.join("")
}

function convertCFGtoJS(root) {
  return ";(" + convertClosure(root) + ")();"
}<|endoftext|>


<commit_before>var FS = require('fs'),
    PATH = require('path'),
    FREEZE = require('./freeze'),
    INHERIT = require('inherit'),
    U = require('./util');

var VOW = require('vow');

function _inherit(d, s) {
    return INHERIT(this, d, s);
}

exports.Tech = INHERIT({

        __constructor: function(opts) {
            this.opts = opts;

            /**
             * Hash of processed files to remove duplicates.
             * @type {Object}
             */
            this.processedFiles = {};
        },

        createFile: function(path, type, parent) {
            var file = new this.File(this, path, type, parent);
            if (type == 'include') file.read();
            return file;
        },

        process: function() {
            var res;
            var path = this.opts.input;
            if (path) {
                res = this.createFile(path, 'include').process(path);
            } else {
                var fakeFile = PATH.join(this.opts.basePath, 'borschik.fakefile');
                var file = new this.File(this, fakeFile, 'include');
                file.content = file.parse(this.opts.inputString);
                //TODO: i call ctor with path and then call method with same path. WTF?
                res = file.process(fakeFile);
            }
            // NOTE: Passing path of source file into process(). This could lead to
            // incorrect paths in the resulting file if it will be stored in another
            // directory then source file.

            var out = this.opts.output;
            if (this.opts.minimize) {
                try {
                    res = this.minimize(res);

                } catch(e) {
                    if (this.opts.inputString && !out.path) {
                        return VOW.reject(e);
                    }

                    var errorMessage = e.toString();

                    // if output is the path
                    if (out.path) {
                        // close current output stream
                        out.end();

                        if (path != out.path) {
                            // remove empty output file if input != ouput
                            FS.unlinkSync(out.path);
                        }
                    }

                    // open new stream for error result
                    var errorFilename;
                    if (out.path) {
                        errorFilename = out.path + '.borschik-error';
                    } else {
                        errorFilename = PATH.resolve(process.cwd(), 'borschik-error');
                    }

                    out = FS.createWriteStream(errorFilename, {
                        encoding: 'utf8'
                    });

                    errorMessage += '\nError result in ' + errorFilename;

                    return this.write(out, res).then(function() {
                        throw errorMessage;
                    });

                }
            }

            if (this.opts.inputString && !this.opts.output.path) {
                return VOW.fulfill(res);
            } else {
                return this.write(out, res);
            }
        },

        write: U.writeFile,

        minimize: function(content) {
            return content;
        },

        File: exports.File = INHERIT({

            __constructor: function(tech, path, type, parent) {
                this.tech = tech;
                // realpathSync processes path with "follow_symlinks" directive
                this.path = PATH.resolve(PATH.dirname(path), FREEZE.realpathSync(path));
                this.childType = type || 'include';
                this.parent = parent;
                this.children = {};
            },

            read: function() {
                this.content = this.parse(FS.readFileSync(this.processPath(this.path)));
                return this;
            },

            processPath: function(path) {
                return path;
            },

            parse: function(content) {
                return this.childType == 'include'?
                    this.parseInclude(content) : this.parseLink(content);
            },

            parseInclude: function(content) {
                return content;
            },

            parseLink: function(content) {
                return this.path;
            },

            process: function(path) {
                return this.childType == 'include'?
                    this.processInclude(path) : this.processLink(path);
            },

            processInclude: function(path) {
                return this.content;
            },

            processLink: function(path) {
                return this.pathFrom(path);
            },

            child: function(type, path) {
                var children = this.children,
                    key = type + '|' + path;
                return children[key] || (children[key] = this.tech.createFile(this.pathTo(path), type, this));
            },

            /**
             * Returns absolute path to resource relative to current file.
             * @param {string} resourcePath Path to resource relative to current file.
             * @returns {string}
             * @example
             * // current file (this.path) /home/user/site/css/page.css
             * this.pathTo(img/bg.png); // /home/user/site/css/img/bg.png
             */
            pathTo: function(resourcePath) {
                return U.pathToUnix(PATH.resolve(PATH.dirname(this.path), resourcePath));
            },

            pathFrom: function(path) {
                return U.pathToUnix(PATH.relative(PATH.dirname(path), this.path));
            }

        }, {
            inherit: _inherit
        })

    }, {
        inherit: _inherit
    });
<commit_msg>Borschik should support to process strings as input or ouput #29<commit_after>var FS = require('fs'),
    PATH = require('path'),
    FREEZE = require('./freeze'),
    INHERIT = require('inherit'),
    U = require('./util'),
    VOW = require('vow');

function _inherit(d, s) {
    return INHERIT(this, d, s);
}

exports.Tech = INHERIT({

        __constructor: function(opts) {
            this.opts = opts;

            /**
             * Hash of processed files to remove duplicates.
             * @type {Object}
             */
            this.processedFiles = {};
        },

        createFile: function(path, type, parent) {
            var file = new this.File(this, path, type, parent);
            if (type == 'include') file.read();
            return file;
        },

        process: function() {
            var res;
            var path = this.opts.input;
            if (path) {
                res = this.createFile(path, 'include').process(path);
            } else {
                var fakeFile = PATH.join(this.opts.basePath, 'borschik.fakefile');
                var file = new this.File(this, fakeFile, 'include');
                file.content = file.parse(this.opts.inputString);
                //TODO: i call ctor with path and then call method with same path. WTF?
                res = file.process(fakeFile);
            }
            // NOTE: Passing path of source file into process(). This could lead to
            // incorrect paths in the resulting file if it will be stored in another
            // directory then source file.

            var out = this.opts.output;
            if (this.opts.minimize) {
                try {
                    res = this.minimize(res);

                } catch(e) {
                    if (this.opts.inputString && !out.path) {
                        return VOW.reject(e);
                    }

                    var errorMessage = e.toString();

                    // if output is the path
                    if (out.path) {
                        // close current output stream
                        out.end();

                        if (path != out.path) {
                            // remove empty output file if input != ouput
                            FS.unlinkSync(out.path);
                        }
                    }

                    // open new stream for error result
                    var errorFilename;
                    if (out.path) {
                        errorFilename = out.path + '.borschik-error';
                    } else {
                        errorFilename = PATH.resolve(process.cwd(), 'borschik-error');
                    }

                    out = FS.createWriteStream(errorFilename, {
                        encoding: 'utf8'
                    });

                    errorMessage += '\nError result in ' + errorFilename;

                    return this.write(out, res).then(function() {
                        throw errorMessage;
                    });

                }
            }

            if (this.opts.inputString && !this.opts.output.path) {
                return VOW.fulfill(res);
            } else {
                return this.write(out, res);
            }
        },

        write: U.writeFile,

        minimize: function(content) {
            return content;
        },

        File: exports.File = INHERIT({

            __constructor: function(tech, path, type, parent) {
                this.tech = tech;
                // realpathSync processes path with "follow_symlinks" directive
                this.path = PATH.resolve(PATH.dirname(path), FREEZE.realpathSync(path));
                this.childType = type || 'include';
                this.parent = parent;
                this.children = {};
            },

            read: function() {
                this.content = this.parse(FS.readFileSync(this.processPath(this.path)));
                return this;
            },

            processPath: function(path) {
                return path;
            },

            parse: function(content) {
                return this.childType == 'include'?
                    this.parseInclude(content) : this.parseLink(content);
            },

            parseInclude: function(content) {
                return content;
            },

            parseLink: function(content) {
                return this.path;
            },

            process: function(path) {
                return this.childType == 'include'?
                    this.processInclude(path) : this.processLink(path);
            },

            processInclude: function(path) {
                return this.content;
            },

            processLink: function(path) {
                return this.pathFrom(path);
            },

            child: function(type, path) {
                var children = this.children,
                    key = type + '|' + path;
                return children[key] || (children[key] = this.tech.createFile(this.pathTo(path), type, this));
            },

            /**
             * Returns absolute path to resource relative to current file.
             * @param {string} resourcePath Path to resource relative to current file.
             * @returns {string}
             * @example
             * // current file (this.path) /home/user/site/css/page.css
             * this.pathTo(img/bg.png); // /home/user/site/css/img/bg.png
             */
            pathTo: function(resourcePath) {
                return U.pathToUnix(PATH.resolve(PATH.dirname(this.path), resourcePath));
            },

            pathFrom: function(path) {
                return U.pathToUnix(PATH.relative(PATH.dirname(path), this.path));
            }

        }, {
            inherit: _inherit
        })

    }, {
        inherit: _inherit
    });
<|endoftext|>


<commit_before>// Automatic Generation of Random Names.

var vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
// Most common letters, digraphs, trigraphs and doubles.
var graphs = ["e","t","a","o","i","n","s","r","th","he","an","in","er","on","re","ed","nd","ha","at","en","es","of","nt","ea","ti","to","io","le","is","ou","ar","as","de","rt","ve","the","and","tha","ent","ion","tio","for","nde","has","nce","tis","oft","men","ss","ee","tt","ll","mm","oo"];
var startWithVowel = graphs.filter(function(e) {
  if (vowels.indexOf(e[0]) >= 0) return e; });
var startWithConsonant = graphs.filter(function(e) {
  if (vowels.indexOf(e[0]) < 0) return e; });

function pick(l) {
  return l[(Math.random() * l.length)|0];
}

function genName() {
  var len = (Math.random() * 4)|0 + 2;
  var name = '';
  var vowel = true;
  for (var i = 0; i < len; i++) {
    var picked = vowel? pick(startWithVowel): pick(startWithConsonant);
    name += picked;
    vowel = vowels.indexOf(picked[picked.length-1]) < 0;
  }
  if (Math.random() > 0.5) { name = name.slice(1); }
  name = String.fromCharCode(name.charCodeAt(0) - 32)
       + name.slice(1);
  return name;
}

module.exports = genName;
<commit_msg>Better name generation.<commit_after>// Automatic Generation of Random Names.

var vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
// Most common letters, digraphs, trigraphs and doubles.
var graphs = ["e","t","a","o","i","n","s","r","th","he","an","in","er","on","re","ed","nd","ha","at","en","es","of","nt","ea","ti","to","io","le","is","ou","ar","as","de","rt","ve","the","and","tha","ent","ion","tio","for","nde","has","nce","tis","oft","men","ss","ee","tt","ll","mm","oo"];
var startWithVowel = graphs.filter(function(e) {
  if (vowels.indexOf(e[0]) >= 0) return e; });
var startWithConsonant = graphs.filter(function(e) {
  if (vowels.indexOf(e[0]) < 0) return e; });

function pick(l) {
  return l[(Math.random() * l.length)|0];
}

function letterBasedName() {
  var len = (Math.random() * 4)|0 + 2;
  var name = '';
  var vowel = true;
  for (var i = 0; i < len; i++) {
    var picked = vowel? pick(startWithVowel): pick(startWithConsonant);
    name += picked;
    vowel = vowels.indexOf(picked[picked.length-1]) < 0;
  }
  if (Math.random() > 0.5) { name = name.slice(1); }
  name = String.fromCharCode(name.charCodeAt(0) - 32)
       + name.slice(1);
  return name;
}

// Approach using combination of words.

var words = ['back', 'bag', 'baker', 'bad', 'bar', 'bat', 'bath', 'beau', 'bec', 'bel', 'ben', 'bin', 'bir', 'black', 'boro', 'bos', 'brad', 'bridge', 'berg', 'burg', 'burn', 'camp', 'carol', 'casa', 'castle', 'cent', 'cester', 'char', 'cław', 'dam', 'dart', 'day', 'fast', 'field', 'ford', 'for', 'fré', 'gate', 'gham', 'grad', 'ham', 'hart', 'head', 'hiro', 'ita', 'jala', 'jiao', 'kan', 'king', 'land', 'las', 'lei', 'lings', 'long', 'mara', 'may', 'milli', 'mont', 'more', 'mouth', 'naga', 'new', 'novo', 'nurem', 'pan', 'pez', 'pit', 'pool', 'port', 'ports', 'pur', 'qing', 'que', 'rack', 'rest', 'richt', 'roch', 'salem', 'san', 'son', 'shiro', 'shima', 'shore', 'smith', 'sor', 'stock', 'tai', 'tela', 'tiago', 'tla', 'to', 'ton', 'vais', 'val', 'viva', 'water', 'wood', 'wor', 'win', 'wind', 'xia', 'yi', 'yoko', 'zaki', 'zao', 'zen'];

function wordBasedName() {
  var name = pick(words) + pick(words);
  name = String.fromCharCode(name.charCodeAt(0) - 32)
       + name.slice(1);
  return name;
}

function genName() {
  return wordBasedName();
}

module.exports = genName;
<|endoftext|>


<commit_before>AsciiWait = function(element, options){

  this.element = element;
  this.currentFrame = 0;
  this.timer = false;

  this.options = $.extend({
    // more cool frames here: http://stackoverflow.com/questions/2685435/cooler-ascii-spinners
    // frames : ['●○○','○●○','○○●','○○○'],
    frames : '. o O @ *'.split(' '),
    timeout : 120
  },options);

  this.txt = function(label){
    // todo: make this work properly without arguments
    // instead of repeating this line twice
    if(typeof label == 'undefined'){
      return this.element[this.element.is('input') ? 'val' : 'text']();
    }else{
      return this.element[this.element.is('input') ? 'val' : 'text'](label);
    }
  }

  // this is kinda dirty, maybe a better way
  this.originalText = this.txt();

  this.step = function(){
    // todo: make private
    thisFrame = this.options.frames[(this.currentFrame++) % this.options.frames.length];
    this.txt(thisFrame);
  };

  this.isWaiting = function(){
    return !!this.timer;
  };

  this.wait = function(){
    if(!this.timer){
      this.step(); // this makes it start instantly
      this.timer = setInterval($.proxy(this.step,this),this.options.timeout);
      return true;
    }else{
      return false;
    }
  };

  this.stopWaiting = function(){
    if(!this.timer){
      return false;
    }else{
      this.currentFrame = 0;
      clearTimeout(this.timer);
      this.timer = false;
      this.txt(this.originalText);
      return true;
    }
  };

  return this;

};
<commit_msg>removing old asciiwait file<commit_after><|endoftext|>


<commit_before>/**
 * execute a callback at random intervals within a range
 * @function
 * @category Algorithmic
 * @memberof cracked
 * @name cracked#random_interval
 * @public
 * @param {Function} callback to be invoked at every interval
 * @param {Number} minTime minimum value for the random interval
 * @param {Number} maxTime maximum value for the random interval
 */
cracked.random_interval = function(callback, minTime, maxTime) {

    function set_timeout(callback, minTime, maxTime,ran) {
        var nextRan = cracked.random(minTime, maxTime);
        setTimeout(function(){
            callback(nextRan);
            set_timeout(callback, minTime, maxTime,nextRan);
        },ran);
    }

    if(typeof callback === "function" && __.isNum(minTime) && __.isNum(maxTime)) {
        set_timeout(callback, minTime, maxTime,cracked.random(minTime, maxTime));
    }

};

/**
 * create a adsr envelope with random values scaled to a length
 * @function
 * @category Algorithmic
 * @memberof cracked
 * @name cracked#random_envelope
 * @public
 * @param {Number} length in sec
 * @returns {Array}
 */
cracked.random_envelope = function(length) {

    var result = [];

    if(__.isNum(length)) {

        var tmp = __.fill_array(4,function(){
            return __.random(0,100);
        });

        var sum = tmp.reduce(function(a, b) {
            return a + b;
        });

        var factor = (length/sum);

        result = tmp.map(function(element,index){
            return element*factor;
        });
    }

    return result;
};

/**
 * fill an array with some values
 * @function
 * @category Algorithmic
 * @memberof cracked
 * @name cracked#fill_array
 * @public
 * @param {Number} size of the array to be filled
 * @param {Function} fn to provide the value, if absent then array is filled with 0's.
 * @returns {Array}
 */
cracked.fill_array = function(size,fn) {
    var tmp = [];
    if(__.isNum(size)) {
        var fun = __.isFun(fn) ? fn : function(){return 0;};
        for(var i=0;i<size;i++) {
            tmp.push(fun.apply(this,[i]));
        }
    }
    return tmp;
};

/**
 * advance thru array one step at a time.
 * start over when arriving at the end
 * @param {Array} arr to loop over
 * @param {Number} offset added to index
 * @param {Number} limit upper bound to iteration
 * @param {Function} callback invoked when the count resets
 * @function
 * @category Algorithmic
 * @memberof cracked
 * @name cracked#array_next
 * @public
 */

cracked.array_next = function(arr,offset,limit,callback) {
    offset = offset || 0;
    limit = limit || arr.length;
    var adjusted_limit = Math.min(limit,arr.length);
    var adjusted_offset = Math.min(offset,adjusted_limit-1);
    var old_index = arr.current_index = __.ifUndef(arr.current_index,-1);
    arr.current_index = (arr.current_index+1+adjusted_offset) >= adjusted_limit ? 0 : arr.current_index+1;
    if((old_index > arr.current_index) && (typeof callback === "function")) {
        callback();
    }
    return arr[arr.current_index + adjusted_offset];
};

/**
 * Returns a boolean based on percentage.
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#chance
 * @public
 * @param {Number} percentage
 * @returns {boolean}
 */
cracked.chance = function(percentage) {
    return percentage > __.random(0,100);
};

/**
 * Returns a musical scale/mode based on type
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#scales
 * @public
 * @param {String} type scale type
 */
cracked.scales = function (type) {
    return {
        "major": [0, 2, 4, 5, 7, 9, 11],
        "minor": [0, 2, 3, 5, 7, 8, 10],
        "wholetone": [0, 2, 4, 6, 8, 10],
        "overtone": [0, 2, 4, 6, 7, 9, 10],
        "lydian": [0, 2, 4, 6, 7, 9, 11],
        "mixolydian": [0, 2, 4, 5, 7, 9, 10],
        "ionian": [0, 2, 4, 5, 7, 9, 11]
    }[type];
};

/**
 * Returns a musical scale/mode based on type
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#chords
 * @public
 * @param {String} type scale type
 */
cracked.chords = function (type) {
    return {
        "major": [0, 4, 7],
        "minor": [0, 3, 7],
        "seventh": [0, 4, 7, 10],
        "ninth": [0, 4, 7, 10, 14],
        "major_seventh": [0, 4, 7, 11],
        "minor_seventh": [0, 3, 7, 10],
        "suspended": [0, 5, 7],
        "diminished": [0, 3, 6],
        "eleventh": [0, 4, 7, 10, 14, 17],
        "thirteenth": [0, 4, 7, 10, 14, 17, 21]
    }[type];
};

/**
 * Return a random series of frequencies from randomly selected octaves from a given scale
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#random_scale
 * @public
 * @param {String} scale
 * @param {Number} octave_lower
 * @param {Number} octave_upper
 */
cracked.random_scale = function (scale,octave_lower,octave_upper) {
    var lower = __.ifUndef(octave_lower,3);
    var upper = __.ifUndef(octave_upper,7);
    return __.pitch2freq(__.scales(scale)[__.random(0,__.scales(scale).length-1)] + __.random(lower,upper) * 12);
};

/**
 * Return a random series of frequencies from a randomly selected octave from a given chord
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#random_arpeggio
 * @public
 * @param {String} chord
 * @param {Number} octave_lower
 * @param {Number} octave_upper
 */
cracked.random_arpeggio = function (chord,octave_lower,octave_upper) {
    var lower = __.ifUndef(octave_lower,3);
    var upper = __.ifUndef(octave_upper,7);
    return __.pitch2freq(__.chords(chord)[__.random(0,__.chords(chord).length-1)] + __.random(lower,upper) * 12);
};

/**
 * Takes a reference to an array, shuffles it
 * and returns it
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#shuffle
 * @public
 * @param {Array} arr
 */
cracked.shuffle = function (arr) {
    var counter = arr.length, temp, index;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        temp = arr[counter];
        arr[counter] = arr[index];
        arr[index] = temp;
    }

    return arr;
};

/**
 * Returns a random number between min & max
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#random
 * @public
 * @param {Number} min
 * @param {Number} max
 */
cracked.random = function (min, max) {
    return Math.round(min + Math.random() * (max - min));
};

/**
 * Factory to create a throttling function that returns true when called every nth times
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#throttle_factory
 * @public
 * @param {Number} num
 */
cracked.throttle_factory = function  (num) {
    var index = 0;
    var number = num;
    return function() {
        index++;
        return index % number===0;
    };
};

/**
 * Factory to create a sequencing function that returns true when called every nth times
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#sequence_factory
 * @public
 * @param {Array} arr
 * @param {Function} fn
 */
cracked.sequence_factory = function  (arr,fn) {
    var count = 0;
    var current_index = 0;
    var arr_copy = arr.slice();
    var current_value = arr_copy[current_index];
    var transition = true;
    var first_run = true;
    return function() {
        if(count===current_value) {
            if(current_index===arr_copy.length-1) {
                current_index = 0;
            } else {
                current_index++;
            }
            count = 1;
            transition=true;
            current_value = arr_copy[current_index];
        } else {
            count++;
            transition=first_run||false;
        }
        fn(transition,current_index);
        first_run=false;
    };
};

//Sequence

/*
 __.sequence("foo")
 .step(function(){console.log("this step got called at minute 1")},1)
 .step(function(){console.log("this step got called at minute 2")},2);

 __.sequence("foo").start();
 */

//this should be private
cracked.__sequence_storage = {};

/**
 * Sequence - create a series of steps that take a function to execute and a time in minutes for when to execute it
 *
 * [See more sampler examples](examples/sequence.html)
 *
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#sequence
 * @public
 * @param {String} name name of sequence
 */
cracked.sequence = function(name) {

    if(!cracked.__sequence_storage[name]) {
        cracked.__sequence_storage[name]={
            steps:{}
        };
    }

    return (function(name){
        return {
            step:function(func,time){
                cracked.__sequence_storage[name].steps[time.toString()]=func;
                return this;
            },
            start:function(){
                cracked.__sequence_storage[name].startTime = Date.now();
                cracked.__sequence_storage[name].clearInterval=setInterval(function(){
                    var time_elapsed = Date.now() - cracked.__sequence_storage[name].startTime;
                    var steps = Object.keys(cracked.__sequence_storage[name].steps);
                    if(steps.length) {
                        steps.map(function(x){
                            if(Math.floor(time_elapsed/60000) >= x) {
                                cracked.__sequence_storage[name].steps[x]();
                                delete cracked.__sequence_storage[name].steps[x];
                            }
                        });
                    } else {
                        clearInterval(cracked.__sequence_storage[name].clearInterval);
                    }
                },1000);
            },
            stop:function(){
                clearInterval(cracked.__sequence_storage[name].clearInterval);
            }
        };
    })(name);
};<commit_msg>add an urn<commit_after>/**
 * execute a callback at random intervals within a range
 * @function
 * @category Algorithmic
 * @memberof cracked
 * @name cracked#random_interval
 * @public
 * @param {Function} callback to be invoked at every interval
 * @param {Number} minTime minimum value for the random interval
 * @param {Number} maxTime maximum value for the random interval
 */
cracked.random_interval = function(callback, minTime, maxTime) {

    function set_timeout(callback, minTime, maxTime,ran) {
        var nextRan = cracked.random(minTime, maxTime);
        setTimeout(function(){
            callback(nextRan);
            set_timeout(callback, minTime, maxTime,nextRan);
        },ran);
    }

    if(typeof callback === "function" && __.isNum(minTime) && __.isNum(maxTime)) {
        set_timeout(callback, minTime, maxTime,cracked.random(minTime, maxTime));
    }

};

/**
 * create a adsr envelope with random values scaled to a length
 * @function
 * @category Algorithmic
 * @memberof cracked
 * @name cracked#random_envelope
 * @public
 * @param {Number} length in sec
 * @returns {Array}
 */
cracked.random_envelope = function(length) {

    var result = [];

    if(__.isNum(length)) {

        var tmp = __.fill_array(4,function(){
            return __.random(0,100);
        });

        var sum = tmp.reduce(function(a, b) {
            return a + b;
        });

        var factor = (length/sum);

        result = tmp.map(function(element,index){
            return element*factor;
        });
    }

    return result;
};

/**
 * fill an array with some values
 * @function
 * @category Algorithmic
 * @memberof cracked
 * @name cracked#fill_array
 * @public
 * @param {Number} size of the array to be filled
 * @param {Function} fn to provide the value, if absent then array is filled with 0's.
 * @returns {Array}
 */
cracked.fill_array = function(size,fn) {
    var tmp = [];
    if(__.isNum(size)) {
        var fun = __.isFun(fn) ? fn : function(){return 0;};
        for(var i=0;i<size;i++) {
            tmp.push(fun.apply(this,[i]));
        }
    }
    return tmp;
};

/**
 * advance thru array one step at a time.
 * start over when arriving at the end
 * @param {Array} arr to loop over
 * @param {Number} offset added to index
 * @param {Number} limit upper bound to iteration
 * @param {Function} callback invoked when the count resets
 * @function
 * @category Algorithmic
 * @memberof cracked
 * @name cracked#array_next
 * @public
 */

cracked.array_next = function(arr,offset,limit,callback) {
    offset = offset || 0;
    limit = limit || arr.length;
    var adjusted_limit = Math.min(limit,arr.length);
    var adjusted_offset = Math.min(offset,adjusted_limit-1);
    var old_index = arr.current_index = __.ifUndef(arr.current_index,-1);
    arr.current_index = (arr.current_index+1+adjusted_offset) >= adjusted_limit ? 0 : arr.current_index+1;
    if((old_index > arr.current_index) && (typeof callback === "function")) {
        callback();
    }
    return arr[arr.current_index + adjusted_offset];
};

/**
 * Returns a boolean based on percentage.
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#chance
 * @public
 * @param {Number} percentage
 * @returns {boolean}
 */
cracked.chance = function(percentage) {
    return percentage > __.random(0,100);
};

/**
 * Returns a musical scale/mode based on type
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#scales
 * @public
 * @param {String} type scale type
 */
cracked.scales = function (type) {
    return {
        "major": [0, 2, 4, 5, 7, 9, 11],
        "minor": [0, 2, 3, 5, 7, 8, 10],
        "wholetone": [0, 2, 4, 6, 8, 10],
        "overtone": [0, 2, 4, 6, 7, 9, 10],
        "lydian": [0, 2, 4, 6, 7, 9, 11],
        "mixolydian": [0, 2, 4, 5, 7, 9, 10],
        "ionian": [0, 2, 4, 5, 7, 9, 11]
    }[type];
};

/**
 * Returns a musical scale/mode based on type
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#chords
 * @public
 * @param {String} type scale type
 */
cracked.chords = function (type) {
    return {
        "major": [0, 4, 7],
        "minor": [0, 3, 7],
        "seventh": [0, 4, 7, 10],
        "ninth": [0, 4, 7, 10, 14],
        "major_seventh": [0, 4, 7, 11],
        "minor_seventh": [0, 3, 7, 10],
        "suspended": [0, 5, 7],
        "diminished": [0, 3, 6],
        "eleventh": [0, 4, 7, 10, 14, 17],
        "thirteenth": [0, 4, 7, 10, 14, 17, 21]
    }[type];
};

/**
 * Return a random series of frequencies from randomly selected octaves from a given scale
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#random_scale
 * @public
 * @param {String} scale
 * @param {Number} octave_lower
 * @param {Number} octave_upper
 */
cracked.random_scale = function (scale,octave_lower,octave_upper) {
    var lower = __.ifUndef(octave_lower,3);
    var upper = __.ifUndef(octave_upper,7);
    return __.pitch2freq(__.scales(scale)[__.random(0,__.scales(scale).length-1)] + __.random(lower,upper) * 12);
};

/**
 * Return a random series of frequencies from a randomly selected octave from a given chord
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#random_arpeggio
 * @public
 * @param {String} chord
 * @param {Number} octave_lower
 * @param {Number} octave_upper
 */
cracked.random_arpeggio = function (chord,octave_lower,octave_upper) {
    var lower = __.ifUndef(octave_lower,3);
    var upper = __.ifUndef(octave_upper,7);
    return __.pitch2freq(__.chords(chord)[__.random(0,__.chords(chord).length-1)] + __.random(lower,upper) * 12);
};

/**
 * Takes a reference to an array, shuffles it
 * and returns it
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#shuffle
 * @public
 * @param {Array} arr
 */
cracked.shuffle = function (arr) {
    var counter = arr.length, temp, index;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        temp = arr[counter];
        arr[counter] = arr[index];
        arr[index] = temp;
    }

    return arr;
};

/**
 * Returns a function that generates a unique random number between 0 & max.
 * If max is exceeded, then repeat the sequence of random numbers.
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#urnFactory
 * @public
 * @param {Number} max
 */
cracked.urnFactory = function (max) {

    var arr = [];
    while(arr.length < max){
        var r = Math.floor(Math.random() * max);
        if(arr.indexOf(r) === -1) arr.push(r);
    }

    return function() {
        return cracked.array_next(arr);
    };

};

/**
 * Returns a random number between min & max
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#random
 * @public
 * @param {Number} min
 * @param {Number} max
 */
cracked.random = function (min, max) {
    return Math.round(min + Math.random() * (max - min));
};

/**
 * Factory to create a throttling function that returns true when called every nth times
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#throttle_factory
 * @public
 * @param {Number} num
 */
cracked.throttle_factory = function  (num) {
    var index = 0;
    var number = num;
    return function() {
        index++;
        return index % number===0;
    };
};

/**
 * Factory to create a sequencing function that returns true when called every nth times
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#sequence_factory
 * @public
 * @param {Array} arr
 * @param {Function} fn
 */
cracked.sequence_factory = function  (arr,fn) {
    var count = 0;
    var current_index = 0;
    var arr_copy = arr.slice();
    var current_value = arr_copy[current_index];
    var transition = true;
    var first_run = true;
    return function() {
        if(count===current_value) {
            if(current_index===arr_copy.length-1) {
                current_index = 0;
            } else {
                current_index++;
            }
            count = 1;
            transition=true;
            current_value = arr_copy[current_index];
        } else {
            count++;
            transition=first_run||false;
        }
        fn(transition,current_index);
        first_run=false;
    };
};

//Sequence

/*
 __.sequence("foo")
 .step(function(){console.log("this step got called at minute 1")},1)
 .step(function(){console.log("this step got called at minute 2")},2);

 __.sequence("foo").start();
 */

//this should be private
cracked.__sequence_storage = {};

/**
 * Sequence - create a series of steps that take a function to execute and a time in minutes for when to execute it
 *
 * [See more sampler examples](examples/sequence.html)
 *
 * @plugin
 * @category Algorithmic
 * @function
 * @memberof cracked
 * @name cracked#sequence
 * @public
 * @param {String} name name of sequence
 */
cracked.sequence = function(name) {

    if(!cracked.__sequence_storage[name]) {
        cracked.__sequence_storage[name]={
            steps:{}
        };
    }

    return (function(name){
        return {
            step:function(func,time){
                cracked.__sequence_storage[name].steps[time.toString()]=func;
                return this;
            },
            start:function(){
                cracked.__sequence_storage[name].startTime = Date.now();
                cracked.__sequence_storage[name].clearInterval=setInterval(function(){
                    var time_elapsed = Date.now() - cracked.__sequence_storage[name].startTime;
                    var steps = Object.keys(cracked.__sequence_storage[name].steps);
                    if(steps.length) {
                        steps.map(function(x){
                            if(Math.floor(time_elapsed/60000) >= x) {
                                cracked.__sequence_storage[name].steps[x]();
                                delete cracked.__sequence_storage[name].steps[x];
                            }
                        });
                    } else {
                        clearInterval(cracked.__sequence_storage[name].clearInterval);
                    }
                },1000);
            },
            stop:function(){
                clearInterval(cracked.__sequence_storage[name].clearInterval);
            }
        };
    })(name);
};<|endoftext|>


<commit_before>var cookieParser    = require('cookie-parser');
var cookieSession   = require('cookie-session');
var _               = require('lodash');
var Promise         = require('promise');
var debug           = require('debug')("auth:persona");
var assert          = require('assert');
var moment          = require('moment');
var marked          = require('marked');
var passport        = require('passport');
var PassportPersona = require('passport-persona');
var express         = require('express')
var bodyParser      = require('body-parser');
var querystring     = require('querystring');
var taskcluster     = require('taskcluster-client');
var url             = require('url');

/** Index page (the only page we have) */
var renderIndex = async function(authFailed, req, res) {

  let credentials = {
    clientId:     '',
    accessToken:  '',
    certificate:  'Internal server error'
  };
  try {
    // Load client so we can sign
    let client = await req.app.globals.Client.load({
      clientId: req.app.globals.clientIdForTempCreds
    });
    credentials = taskcluster.createTemporaryCredentials({
      start:        new Date(),
      // good for three days
      expiry:       new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000),
      // use the client's role without expanding them, so that the temporary
      // credentials track changes to roles
      scopes:       ['assume:client-id:' + client.clientId],
      credentials:  {
        clientId:     client.clientId,
        accessToken:  client.accessToken
      }
    });
  } catch (err) {
    debug("Error loading client: %s, as JSON: %j", err, err, err.stack);
  }

  if (typeof(credentials.certificate) !== 'string') {
    credentials.certificate = JSON.stringify(credentials.certificate);
  }

  // Add temporary credentials to target URL
  var target = undefined;
  if (req.query.target) {
    target = url.parse(req.query.target);
    delete target.search;
    if (!target.query) {
      target.query = {};
    }
    target.query.clientId     = credentials.clientId;
    target.query.accessToken  = credentials.accessToken;
    target.query.certificate  = credentials.certificate;
  }

  // Render login page
  res.render('login', {
    query:        req.query,
    target:       url.format(target),
    credentials:  credentials,
    querystring:  querystring.stringify(req.query),
    authFailed:   authFailed
  });
};

/** Setup the application for hosting the index page */
var setup = function(app, options) {
  assert(options.cookieSecret,    "cookieSecret is required");
  assert(options.viewFolder,      "viewFolder is required");
  assert(options.assetFolder,     "assetFolder is required");

  app.set('views', options.viewFolder);
  app.set('view engine', 'jade');
  app.locals.moment = moment;
  app.locals.marked = marked;

  app.use(bodyParser.urlencoded({extended: false}));
  app.use(cookieParser(options.cookieSecret));
  app.use(cookieSession({secret: options.cookieSecret}));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(function(req, res, next) {
    // Expose user to all templates, if logged in
    res.locals.user = req.user;
    next();
  });
  app.use('/assets', express.static(options.assetFolder));

  // Warn if no secret was used in production
  if ('production' == app.get('env')) {
    var secret = options.cookieSecret;
    if (secret == "Warn, if no secret is used on production") {
      console.log("Warning: Customized cookie secret should be used in " +
                  "production");
    }
  }

  // Passport configuration
  passport.use(new PassportPersona.Strategy({
      audience:   options.publicUrl
    }, function(email, done) {
    debug("Signed in with:" + email);
    if (/@(mozilla|qanalydocs|mgsei)\.com$/.test(email)) {
      done(null, {email: email});
    } else {
      done(null, null);
    }
  }));

  // Serialize user to signed cookie
  passport.serializeUser(function(user, done) {
    done(null, user.email);
  });

  // Deserialize user from signed cookie
  passport.deserializeUser(function(email, done) {
    done(null, {email: email});
  });

  // Facilitate persona login
  app.post('/', function(req, res, next) {
    passport.authenticate('persona', function(err, user, info) {
      if (user) {
        // Make sure we preserve the querystring
        req.logIn(user, function() {
          res.redirect('/?' + querystring.stringify(req.query));
        });
      } else {
        renderIndex(true, req, res);
      }
    })(req, res, next);
  });

  // Provide end-point to log out the user
  app.get('/logout', function(req, res){
    req.logout();
    // Make sure we preserve the querystring
    res.redirect('/?' + querystring.stringify(req.query));
  });

  // render index page
  app.get('/', function(req, res) {
    renderIndex(false, req, res);
  });
};

// Export setup
exports.setup = setup;
<commit_msg>Remove persona...<commit_after><|endoftext|>


<commit_before>// TODO: handle clear log menu
// TODO: handle clear queue menu
// TODO: handle clear ack menu

/**
 * The controller for the control panel.
 */
app.controller('controlPanelCtrl', function($scope, hotkeys, settingsService, machineService) {
  $scope.emergencyStop = machineService.emergencyStop;
  $scope.settings = settingsService.settings;
  $scope.machineService = machineService;

  $scope.stepSize = 1;

  hotkeys.bindTo($scope)
    .add({
      combo: ['up', 'i'],
      description: 'move the Y axis in the + direction',
      callback: function() {$scope.relativeMove("Y")}
    })
    .add({
      combo: ['down' ,'k'],
      description: 'move the Y axis in the - direction',
      callback: function() {$scope.relativeMove("Y-")}
    })
    .add({
      combo: ['left', 'j'],
      description: 'move the X axis in the - direction',
      callback: function() {$scope.relativeMove("X")}
    })
    .add({
      combo: ['right', 'l'],
      description: 'move the X axis in the + direction',
      callback: function() {$scope.relativeMove("X")}
    })
    .add({
      combo: ['a'],
      description: 'move the Z axis in the + direction',
      callback: function() {$scope.relativeMove("Z")}
    })
    .add({
      combo: ['z'],
      description: 'move the Z axis in the - direction',
      callback: function() {$scope.relativeMove("Z-")}
    })
    .add({
      combo: '-',
      description: 'decrement the step size',
      callback: function() {$scope.incrementStepSize(-1)}
    })
    .add({
      combo: '=',
      description: 'increment the step size',
      callback: function() {$scope.incrementStepSize(1)}
    })
    .add({
      combo: '/',
      description: 'focus the manual command entry',
      callback: function() {
        // Let the event finish propagating.
        setTimeout(function() {
          $("#input-control-cmd").focus();
        }, 1);
      }
    });

  // The manual input field has to be configured manually.
  // The history of manual commands that the user has entered.
  var manualInputHistory = [];
  var manualInputPosition = 0;

  $scope.manualCommand = "";
  $scope.sendManualCommand = function(command) {
    manualInputHistory.push(command);
    manualInputPosition = manualInputHistory.length;
    machineService.enqueueCommands([command]);
    $scope.manualCommand = "";
  }

  $("#input-control-cmd").keydown(function(e) {
    e.stopPropagation();

    if (e.keyCode == 27) { // escape; blur the manual command input.
      // the delay is to allow the current event propagation to finish.
      setTimeout(function() {
        $("#input-control-cmd").blur();
      }, 1);

    } else if (e.keyCode == 38) { // up arrow; show previous history position.
      manualInputPosition = Math.max(manualInputPosition - 1, 0);
      var prevCommand = ((manualInputPosition < manualInputHistory.length) ?
          manualInputHistory[manualInputPosition] : "");
      $scope.manualCommand = prevCommand;
      setTimeout(function() {
        $("#input-control-cmd")[0].setSelectionRange(prevCommand.length, prevCommand.length);
      }, 1);
    } else if (e.keyCode == 40) { // down arrow; show next history position.
      manualInputPosition = Math.min(manualInputPosition + 1, manualInputHistory.length);
      var nextCommand = ((manualInputPosition < manualInputHistory.length) ?
          manualInputHistory[manualInputPosition] : "");
      $scope.manualCommand = nextCommand;
      setTimeout(function() {
        $("#input-control-cmd")[0].setSelectionRange(nextCommand.length, nextCommand.length);
      }, 1);
    }
  });

  var shouldSendCommands = function() {
    return machineService.isConnected && machineService.commandQueue.length == 0;
  }

  $scope.getStepSize = function() {
    return Math.pow(10, $scope.stepSize);
  }

  $scope.incrementStepSize = function(amt) {
    $scope.stepSize = Math.max(-1, Math.min(2, $scope.stepSize + amt));
  }

  /**
   * Enqueue a command to perform a relative move. The global step size
   * will be used.
   *
   * @param {string} axis The axis to move about (eg. 'X-')
   */
  $scope.relativeMove = function(axis) {
    if (!shouldSendCommands()) {
      return;
    }

    var commands = [];
    if (!machineService.isRelativeMode) {
      commands.push("G91");
    }
    if (!machineService.isMm) {
      commands.push("G21");
    }

    var feedrate = settingsService.settings.workspace_jog_feedrate;
    var mv = "G1";
    if (settingsService.settings.workspace_jog_rapid) {
      mv = "G0"
    } else if (feedrate != NaN && feedrate > 0) {
      mv += " F" + feedrate;
    }
    mv += " " + axis + $scope.getStepSize();
    commands.push(mv);

    machineService.enqueueCommands(commands);
  };

  $scope.sendCommands = function(cmds) {
    if (!shouldSendCommands()) {
      return;
    }
    machineService.enqueueCommands(cmds);
  }
});
<commit_msg>fix direction of left arrow<commit_after>// TODO: handle clear log menu
// TODO: handle clear queue menu
// TODO: handle clear ack menu

/**
 * The controller for the control panel.
 */
app.controller('controlPanelCtrl', function($scope, hotkeys, settingsService, machineService) {
  $scope.emergencyStop = machineService.emergencyStop;
  $scope.settings = settingsService.settings;
  $scope.machineService = machineService;

  $scope.stepSize = 1;

  hotkeys.bindTo($scope)
    .add({
      combo: ['up', 'i'],
      description: 'move the Y axis in the + direction',
      callback: function() {$scope.relativeMove("Y")}
    })
    .add({
      combo: ['down' ,'k'],
      description: 'move the Y axis in the - direction',
      callback: function() {$scope.relativeMove("Y-")}
    })
    .add({
      combo: ['left', 'j'],
      description: 'move the X axis in the - direction',
      callback: function() {$scope.relativeMove("X-")}
    })
    .add({
      combo: ['right', 'l'],
      description: 'move the X axis in the + direction',
      callback: function() {$scope.relativeMove("X")}
    })
    .add({
      combo: ['a'],
      description: 'move the Z axis in the + direction',
      callback: function() {$scope.relativeMove("Z")}
    })
    .add({
      combo: ['z'],
      description: 'move the Z axis in the - direction',
      callback: function() {$scope.relativeMove("Z-")}
    })
    .add({
      combo: '-',
      description: 'decrement the step size',
      callback: function() {$scope.incrementStepSize(-1)}
    })
    .add({
      combo: '=',
      description: 'increment the step size',
      callback: function() {$scope.incrementStepSize(1)}
    })
    .add({
      combo: '/',
      description: 'focus the manual command entry',
      callback: function() {
        // Let the event finish propagating.
        setTimeout(function() {
          $("#input-control-cmd").focus();
        }, 1);
      }
    });

  // The manual input field has to be configured manually.
  // The history of manual commands that the user has entered.
  var manualInputHistory = [];
  var manualInputPosition = 0;

  $scope.manualCommand = "";
  $scope.sendManualCommand = function(command) {
    manualInputHistory.push(command);
    manualInputPosition = manualInputHistory.length;
    machineService.enqueueCommands([command]);
    $scope.manualCommand = "";
  }

  $("#input-control-cmd").keydown(function(e) {
    e.stopPropagation();

    if (e.keyCode == 27) { // escape; blur the manual command input.
      // the delay is to allow the current event propagation to finish.
      setTimeout(function() {
        $("#input-control-cmd").blur();
      }, 1);

    } else if (e.keyCode == 38) { // up arrow; show previous history position.
      manualInputPosition = Math.max(manualInputPosition - 1, 0);
      var prevCommand = ((manualInputPosition < manualInputHistory.length) ?
          manualInputHistory[manualInputPosition] : "");
      $scope.manualCommand = prevCommand;
      setTimeout(function() {
        $("#input-control-cmd")[0].setSelectionRange(prevCommand.length, prevCommand.length);
      }, 1);
    } else if (e.keyCode == 40) { // down arrow; show next history position.
      manualInputPosition = Math.min(manualInputPosition + 1, manualInputHistory.length);
      var nextCommand = ((manualInputPosition < manualInputHistory.length) ?
          manualInputHistory[manualInputPosition] : "");
      $scope.manualCommand = nextCommand;
      setTimeout(function() {
        $("#input-control-cmd")[0].setSelectionRange(nextCommand.length, nextCommand.length);
      }, 1);
    }
  });

  var shouldSendCommands = function() {
    return machineService.isConnected && machineService.commandQueue.length == 0;
  }

  $scope.getStepSize = function() {
    return Math.pow(10, $scope.stepSize);
  }

  $scope.incrementStepSize = function(amt) {
    $scope.stepSize = Math.max(-1, Math.min(2, $scope.stepSize + amt));
  }

  /**
   * Enqueue a command to perform a relative move. The global step size
   * will be used.
   *
   * @param {string} axis The axis to move about (eg. 'X-')
   */
  $scope.relativeMove = function(axis) {
    if (!shouldSendCommands()) {
      return;
    }

    var commands = [];
    if (!machineService.isRelativeMode) {
      commands.push("G91");
    }
    if (!machineService.isMm) {
      commands.push("G21");
    }

    var feedrate = settingsService.settings.workspace_jog_feedrate;
    var mv = "G1";
    if (settingsService.settings.workspace_jog_rapid) {
      mv = "G0"
    } else if (feedrate != NaN && feedrate > 0) {
      mv += " F" + feedrate;
    }
    mv += " " + axis + $scope.getStepSize();
    commands.push(mv);

    machineService.enqueueCommands(commands);
  };

  $scope.sendCommands = function(cmds) {
    if (!shouldSendCommands()) {
      return;
    }
    machineService.enqueueCommands(cmds);
  }
});
<|endoftext|>


<commit_before>'use strict';

var browserSync = require('browser-sync');

var $    = require('gulp-load-plugins')();
var _    = require('lodash');
var cjsx = require('gulp-cjsx');

function buildScripts (params) {
  var params        = params         || {};
  var options       = params.buildOptions || {};
  var gulp          = require(options.modulesData['gulp'].uses);
  var dest          = params.dest    || options.tmp + '/serve/app';
  var src           = params.src     || options.src;

  var coffeeFilter  = $.filter('**/*.coffee');
  var jsFilter      =  $.filter(['**/*.js', '!**/*.env.js']);

  return gulp.src(src)
    .pipe(coffeeFilter)
    .pipe($.sourcemaps.init())
    .pipe($.coffeelint())
    .pipe($.coffeelint.reporter())
    .pipe($.coffee()).on('error', options.errorHandler('CoffeeScript'))
    .pipe($.sourcemaps.write())
    .pipe(coffeeFilter.restore())
    .pipe(jsFilter)
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe(browserSync.reload({ stream: true }))
    .pipe($.size())
    .pipe(jsFilter.restore())
    .pipe(gulp.dest(dest))
    .pipe(browserSync.reload({ stream: true }))
    .pipe($.size());

}

function buildCJSX (params) {
  var params  = params              || {};
  var options = params.buildOptions || {};
  var gulp    = require(options.modulesData['gulp'].uses);
  var dest    = params.dest    || options.tmp + '/serve/app';
  var src     = params.src     || options.src + '/app/**/*.cjsx';

  return gulp.src(src)
    .pipe(cjsx({bare: true}).on('error', options.errorHandler('CoffeeScriptX')))
    .pipe(gulp.dest(dest))
    .pipe(browserSync.reload({ stream: true }))
    .pipe($.size());
}

var Scripts = function(buildOptions) {

  var gulp    = require(buildOptions.modulesData['gulp'].uses);

  gulp.task('scripts', function(){
    return buildScripts({buildOptions: buildOptions});
  });

  gulp.task('cjsx', function() {
    return buildCJSX({buildOptions: buildOptions})
  });

  var exports = {
    buildScripts: buildScripts,
    buildCJSX   : buildCJSX
  };

  return exports;
};

module.exports = Scripts;
<commit_msg>removed duplicated pipes and adjustments filter js<commit_after>'use strict';

var browserSync = require('browser-sync');

var $    = require('gulp-load-plugins')();
var _    = require('lodash');
var cjsx = require('gulp-cjsx');

function buildScripts (params) {
  var params        = params         || {};
  var options       = params.buildOptions || {};
  var gulp          = require(options.modulesData['gulp'].uses);
  var dest          = params.dest    || options.tmp + '/serve/app';
  var src           = params.src     || options.src;

  var coffeeFilter  = $.filter('**/*.coffee');
  var jsFilter      =  $.filter(['**/*.js']);

  return gulp.src(src)
    .pipe(coffeeFilter)
    .pipe($.sourcemaps.init())
    .pipe($.coffeelint())
    .pipe($.coffeelint.reporter())
    .pipe($.coffee()).on('error', options.errorHandler('CoffeeScript'))
    .pipe($.sourcemaps.write())
    .pipe(coffeeFilter.restore())
    .pipe(jsFilter)
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe(browserSync.reload({ stream: true }))
    .pipe($.size())
    .pipe(jsFilter.restore())
    .pipe(gulp.dest(dest))
    .pipe(browserSync.reload({ stream: true }))
    .pipe($.size());

}

function buildCJSX (params) {
  var params  = params              || {};
  var options = params.buildOptions || {};
  var gulp    = require(options.modulesData['gulp'].uses);
  var dest    = params.dest    || options.tmp + '/serve/app';
  var src     = params.src     || options.src + '/app/**/*.cjsx';

  return gulp.src(src)
    .pipe(cjsx({bare: true}).on('error', options.errorHandler('CoffeeScriptX')))
    .pipe(gulp.dest(dest))
    .pipe(browserSync.reload({ stream: true }))
    .pipe($.size());
}

var Scripts = function(buildOptions) {

  var gulp    = require(buildOptions.modulesData['gulp'].uses);

  gulp.task('scripts', function(){
    return buildScripts({buildOptions: buildOptions});
  });

  gulp.task('cjsx', function() {
    return buildCJSX({buildOptions: buildOptions})
  });

  var exports = {
    buildScripts: buildScripts,
    buildCJSX   : buildCJSX
  };

  return exports;
};

module.exports = Scripts;
<|endoftext|>


<commit_before>"use strict";
!()=>{
    let helpers = require('./helpers.js'),
        dataHelpers = require('./data-helpers.js'),
        HEAT_DETAILS_PAGE_NAME = 'heatdetails.aspx';

    function getPage(id, callback) {
        helpers.getPage(helpers.ROOT_URL, `${HEAT_DETAILS_PAGE_NAME}?HeatNo=${id}`, callback);
    }

    function parsePos(pos) {
        if(pos.indexOf('Winner') >= 0) {
            return 1;
        }
        else {
            return helpers.extractPosition(pos);
        }
    }

    function getHeatDetailsById(id, callback) {
        getPage(id, (err, $) => {
            if(err) {
                callback(err);
            }
            else {
                // Grab racer info (not laps, those come later)
                let racerIdsByName = {},
                    lapsByRacerId = {},
                    lapGroups = null,
                    racers = $('a').map((i, el) => {
                        var custId = helpers.extractCustId(el.attribs.href),
                            row1 = $(el).closest('tr'),
                            row2 = row1.next(),
                            position = '';

                        // top 3 are formatted differently so handle those separately
                        if(!row1.is('.Top3WinnersRow') && !row1.is('.Top3WinnersRowAlt')) {
                            row2 = row1;
                            position = row1.find('.Position').find('span').text();
                        }
                        else {
                            position = parsePos(row1.find('.Position').text());
                        }

                        return {
                            id: custId,
                            name: el.children[0].data,
                            position: position,
                            bestLapTime: row2.find('.BestLap').find('span').text(),
                            lapCount: row2.find('.Laps').find('span').text(),
                            gap: row2.find('.Gap').find('span').text(),
                            averageLapTime: row2.find('.AvgLap').find('span').text()
                        };
                    }).get();

                racers.forEach((r) => {
                    racerIdsByName[r.name] = r.id;
                });

                lapGroups = $('.LapTimes').map((i, el) => {
                    return {
                        racerId: racerIdsByName[$(el).find('th').text()],
                        laps: $(el).find('.LapTimesRow,.LapTimesRowAlt').map((i, iel) => {
                            let lap = helpers.extractLap(iel.children[1].children[0].data);
                            if(lap != null) {
                                return {
                                    id: iel.children[0].children[0].data,
                                    time: lap.time,
                                    position: lap.position
                                };
                            }
                            else {
                                return {
                                    id: iel.children[0].children[0].data
                                };
                            }
                        }).get()
                    };
                }).get();

                lapGroups.forEach((g) => {
                    lapsByRacerId[g.racerId] = g.laps;
                });

                callback(null, {
                    id: id,
                    desc: $('#lblRaceType').text(),
                    winByDesc: $('#lblWinnerBy').text(),
                    date: $('#lblDate').text(),
                    racers: racers.map((r) => {
                        r.laps = lapsByRacerId[r.id];
                        return r;
                    })
                });
            }
        });
    }

    function getHeatDetailsByIdAsHashes(id, callback) {
        getHeatDetailsById(id, (err, data) => {
            let _racers = {},
                _heats = {},
                _heatRacers = {},
                _heatRacerLaps = {};

            if(err) {
                callback(err);
                return;
            }

            _heats[data.id] = {
                id: data.id,
                desc: data.desc,
                winBy: data.winByDesc,
                date: data.date
            };

            data.racers.forEach((racer) => {
                let timeOrLapsGap = helpers.extractTimeOrLapGap(racer.gap)

                _racers[racer.id] = {
                    id: racer.id,
                    name: racer.name,
                    skill: null
                };

                _heatRacers[`${data.id}_${racer.id}`] = {
                    heatId: data.id,
                    racerId: racer.id,
                    position: racer.position,
                    bestLapTime: racer.bestLapTime,
                    gapTime: timeOrLapsGap.time,
                    gapLaps: timeOrLapsGap.laps,
                    lapCount: racer.lapCount,
                    averageLapTime: racer.averageLapTime,
                    skill: null,
                    skillDelta: null,
                    kartNumber: null
                };

                racer.laps.forEach((lap) => {
                    if(!lap['time'] || !lap['position']){
                        return;
                    }

                    _heatRacerLaps[`${data.id}_${racer.id}_${lap.id}`] = {
                        heatId: data.id,
                        racerId: racer.id,
                        id: lap.id,
                        time: lap.time,
                        position: lap.position
                    };
                });
            });

            callback(null, {
                racers: dataHelpers.applyToHash(_racers),
                heats: dataHelpers.applyToHash(_heats),
                heatRacers: dataHelpers.applyToHash(_heatRacers),
                heatRacerLaps: dataHelpers.applyToHash(_heatRacerLaps)
            });
        });
    }

    module.exports.getHeatDetailsById = getHeatDetailsById;
    module.exports.getHeatDetailsByIdAsHashes = getHeatDetailsByIdAsHashes;
}();
<commit_msg>Fixed quoting heat data<commit_after>"use strict";
!()=>{
    let helpers = require('./helpers.js'),
        dataHelpers = require('./data-helpers.js'),
        HEAT_DETAILS_PAGE_NAME = 'heatdetails.aspx';

    function getPage(id, callback) {
        helpers.getPage(helpers.ROOT_URL, `${HEAT_DETAILS_PAGE_NAME}?HeatNo=${id}`, callback);
    }

    function parsePos(pos) {
        if(pos.indexOf('Winner') >= 0) {
            return 1;
        }
        else {
            return helpers.extractPosition(pos);
        }
    }

    function getHeatDetailsById(id, callback) {
        getPage(id, (err, $) => {
            if(err) {
                callback(err);
            }
            else {
                // Grab racer info (not laps, those come later)
                let racerIdsByName = {},
                    lapsByRacerId = {},
                    lapGroups = null,
                    racers = $('a').map((i, el) => {
                        var custId = helpers.extractCustId(el.attribs.href),
                            row1 = $(el).closest('tr'),
                            row2 = row1.next(),
                            position = '';

                        // top 3 are formatted differently so handle those separately
                        if(!row1.is('.Top3WinnersRow') && !row1.is('.Top3WinnersRowAlt')) {
                            row2 = row1;
                            position = row1.find('.Position').find('span').text();
                        }
                        else {
                            position = parsePos(row1.find('.Position').text());
                        }

                        return {
                            id: custId,
                            name: el.children[0].data,
                            position: position,
                            bestLapTime: row2.find('.BestLap').find('span').text(),
                            lapCount: row2.find('.Laps').find('span').text(),
                            gap: row2.find('.Gap').find('span').text(),
                            averageLapTime: row2.find('.AvgLap').find('span').text()
                        };
                    }).get();

                racers.forEach((r) => {
                    racerIdsByName[r.name] = r.id;
                });

                lapGroups = $('.LapTimes').map((i, el) => {
                    return {
                        racerId: racerIdsByName[$(el).find('th').text()],
                        laps: $(el).find('.LapTimesRow,.LapTimesRowAlt').map((i, iel) => {
                            let lap = helpers.extractLap(iel.children[1].children[0].data);
                            if(lap != null) {
                                return {
                                    id: iel.children[0].children[0].data,
                                    time: lap.time,
                                    position: lap.position
                                };
                            }
                            else {
                                return {
                                    id: iel.children[0].children[0].data
                                };
                            }
                        }).get()
                    };
                }).get();

                lapGroups.forEach((g) => {
                    lapsByRacerId[g.racerId] = g.laps;
                });

                callback(null, {
                    id: id,
                    desc: $('#lblRaceType').text(),
                    winByDesc: $('#lblWinnerBy').text(),
                    date: $('#lblDate').text(),
                    racers: racers.map((r) => {
                        r.laps = lapsByRacerId[r.id];
                        return r;
                    })
                });
            }
        });
    }

    function getHeatDetailsByIdAsHashes(id, callback) {
        getHeatDetailsById(id, (err, data) => {
            let _racers = {},
                _heats = {},
                _heatRacers = {},
                _heatRacerLaps = {};

            if(err) {
                callback(err);
                return;
            }

            _heats[data.id] = {
                id: data.id,
                desc: data.desc.replace('"', "'"),
                winBy: data.winByDesc.replace('"', "'"),
                date: data.date.replace('"', "'")
            };

            data.racers.forEach((racer) => {
                let timeOrLapsGap = helpers.extractTimeOrLapGap(racer.gap.replace('"', "'"))

                _racers[racer.id] = {
                    id: racer.id,
                    name: racer.name,
                    skill: null
                };

                _heatRacers[`${data.id}_${racer.id}`] = {
                    heatId: data.id,
                    racerId: racer.id,
                    position: racer.position.replace('"', "'"),
                    bestLapTime: racer.bestLapTime.replace('"', "'"),
                    gapTime: timeOrLapsGap.time,
                    gapLaps: timeOrLapsGap.laps,
                    lapCount: racer.lapCount.replace('"', "'"),
                    averageLapTime: racer.averageLapTime.replace('"', "'"),
                    skill: null,
                    skillDelta: null,
                    kartNumber: null
                };

                racer.laps.forEach((lap) => {
                    if(!lap['time'] || !lap['position']){
                        return;
                    }

                    _heatRacerLaps[`${data.id}_${racer.id}_${lap.id}`] = {
                        heatId: data.id,
                        racerId: racer.id,
                        id: lap.id,
                        time: lap.time.replace('"', "'"),
                        position: lap.position.replace('"', "'")
                    };
                });
            });

            callback(null, {
                racers: dataHelpers.applyToHash(_racers),
                heats: dataHelpers.applyToHash(_heats),
                heatRacers: dataHelpers.applyToHash(_heatRacers),
                heatRacerLaps: dataHelpers.applyToHash(_heatRacerLaps)
            });
        });
    }

    module.exports.getHeatDetailsById = getHeatDetailsById;
    module.exports.getHeatDetailsByIdAsHashes = getHeatDetailsByIdAsHashes;
}();
<|endoftext|>