<commit_before>// Dependencies
var Fs = require("fs")
  , ReadUtf8 = require("read-utf8")
  , Mustache = require("mustache")
  , Phantom = require("phantom-render-stream")
  , SameTime = require("same-time")
  , OneByOne = require("one-by-one")
  , IterateObject = require("iterate-object")
  , Events = require("events")
  , EventEmitter = Events.EventEmitter
  , Ul = require("ul")
  ;

/**
 * Invoice
 * This is the constructor that creates a new instance containing the needed
 * methods.
 *
 * @name Invoice
 * @function
 * @param {Object} options The options for creating the new invoice:
 *
 *  - `config` (Object):
 *    - `template` (String): The HTML root template.
 *    - `tableRowBlock` (String): The row block HTML template.
 *  - `data` (Object):
 *    - `currencyBalance` (Object):
 *      - `main` (Number): The main balance.
 *      - `secondary` (Number): The converted main balance.
 *      - `tasks` (Array): An array with the tasks (description of the services you did).
 *      - `invoice` (Object): Information about invoice.
 *  - `seller` (Object): Information about seller.
 *  - `buyer` (Object): Information about buyer.
 */
function NodeIce(options) {
    this.options = options;
    this.templates = {};
}

/**
 * initTemplates
 * Inits the HTML templates.
 *
 * @name initTemplates
 * @function
 * @param {Function} callback The callback function.
 */
NodeIce.prototype.initTemplates = function (callback) {
    var self = this;
    if (self.templates.root === undefined || self.templates.tableRowBlock === undefined) {
        SameTime([
            ReadUtf8.bind(this, self.options.config.template)
          , ReadUtf8.bind(this, self.options.config.tableRowBlock)
        ], function (err, data) {
            if (err) { return callback(err); }
            self.templates.root = data[0];
            self.templates.tableRowBlock = data[1];
            callback(null, self.templates);
        });
    } else {
        return callback(null, self.templates);
    }
};

/**
 * renderHtml
 * Renders the invoice in HTML format.
 *
 * @name renderAsHtml
 * @function
 * @param {Object} ops An object containing the required field output - that
 * should be a string representing the path to the output that will store
 * the HTML code.
 * @param {Function} callback The callback function
 * @return {Invoice} The Invoice instance
 */
NodeIce.prototype.toHtml = function (ops, callback) {

    if (typeof ops === "function") {
        callback = ops;
        ops = {};
    }

    if (typeof ops === "string") {
        ops = {
            output: ops
        };
    }

    var self = this
      , options = self.options
      , tasks = options.data.tasks
      , invoiceHtml = ""
      , invoiceData = {
            seller: options.seller
          , buyer: options.buyer
          , invoice: options.data.invoice
          , description_rows: ""
          , total: {
                main: 0
              , secondary: 0
            }
        }
      ;

    IterateObject(tasks, function (cTask, i) {
        // Set the additional fields and compute data
        cTask.nrCrt = i + 1;
        if (typeof cTask.unitPrice === "number") {
            cTask.unitPrice = {
                main: cTask.unitPrice
              , secondary: self.convertToSecondary(
                    cTask.unitPrice
                )
            };
        }

        if (typeof cTask.unitPrice.main === "number") {
            // Set the unit price of this row
            cTask.unitPrice.main = cTask.unitPrice.main.toFixed(2);
            cTask.unitPrice.secondary = cTask.unitPrice.secondary.toFixed(2);
        }

        // Build amount object
        cTask.amount = {
            main: cTask.unitPrice.main * cTask.quantity
          , secondary: cTask.unitPrice.secondary * cTask.quantity
        };

        // Sum the amount to the total
        invoiceData.total.main += cTask.amount.main;
        invoiceData.total.secondary += cTask.amount.secondary;

        // Set the amount of this row
        cTask.amount.main = cTask.amount.main.toFixed(2);
        cTask.amount.secondary = cTask.amount.secondary.toFixed(2);
    });

    self.initTemplates(function (err, templates) {
        if (err) { return callback(err); }

        // Render HTML for the current row
        invoiceData.description_rows += Mustache.render(
            templates.rowBlockContent, cTask
        );

        // Set the total
        invoiceData.total.main  = invoiceData.total.main.toFixed(2);
        invoiceData.total.secondary = invoiceData.total.secondary.toFixed(2);

        // Render the invoice HTML fields
        invoiceHtml = Mustache.render(templates.templateContent, invoiceData);

        // Output file
        if (typeof ops.output === "string") {
            Fs.writeFile(ops.output, invoiceHtml, function (err, data) {
                callback(err, invoiceHtml);
            });
            return;
        }

        // Callback the data
        callback(null, invoiceHtml);
    });

    return self;
};

/**
 * convertToSecondary
 * Converts a currency into another currency according to the currency
 * balance provided in the options
 *
 * @name convertToSecondary
 * @function
 * @param {Number} input The number that should be converted
 * @return {Number} The converted input
 */
NodeIce.prototype.convertToSecondary = function (input) {
    return input * this.options.data.currencyBalance.secondary / this.options.data.currencyBalance.main;
};

/**
 * renderAsPdf
 * Renders invoice as pdf
 *
 * @name renderAsPdf
 * @function
 * @param {Object} options An object containing the `output` field
 * represeting the path to the pdf file that will be created.
 * @param {Function} callback The callback function
 * @return {Invoice} The Invoice instance
 */
NodeIce.prototype.toPdf = function (ops, callback) {
    var self = this
      , ev = new EventEmitter()
      ;

    if (typeof ops === "function") {
        callback = ops;
        ops = {};
    }

    ops = Ul.merge(ops, {
        phantom: {}
    });

    OneByOne([
        self.toHtml.bind(self)
      , function (next, html) {
  // TODO
        //    var render = Phantom(ops.phantom);
        //    if (typeof ops.output === "string") {
        //    }
        //    Phantom.create(function (ph) {
        //        ph.createPage(function (page) {
        //            page.set("viewportSize", { width: 2480, height: 3508 });
        //            page.open(tmpFileName, function(status) {
        //                page.render(options.output, function() {
        //                    Fs.unlink(tmpFileName);
        //                    ph.exit();
        //                    callback.call(this, arguments);
        //                });
        //            });
        //        });
        //    });
            next();
        }
    ], callback);
};

module.exports = NodeIce;
<commit_msg>Fixed the toHtml method<commit_after>// Dependencies
var Fs = require("fs")
  , ReadUtf8 = require("read-utf8")
  , Mustache = require("mustache")
  , Phantom = require("phantom-render-stream")
  , SameTime = require("same-time")
  , OneByOne = require("one-by-one")
  , IterateObject = require("iterate-object")
  , Events = require("events")
  , EventEmitter = Events.EventEmitter
  , Ul = require("ul")
  ;

/**
 * Invoice
 * This is the constructor that creates a new instance containing the needed
 * methods.
 *
 * @name Invoice
 * @function
 * @param {Object} options The options for creating the new invoice:
 *
 *  - `config` (Object):
 *    - `template` (String): The HTML root template.
 *    - `tableRowBlock` (String): The row block HTML template.
 *  - `data` (Object):
 *    - `currencyBalance` (Object):
 *      - `main` (Number): The main balance.
 *      - `secondary` (Number): The converted main balance.
 *      - `tasks` (Array): An array with the tasks (description of the services you did).
 *      - `invoice` (Object): Information about invoice.
 *  - `seller` (Object): Information about seller.
 *  - `buyer` (Object): Information about buyer.
 */
function NodeIce(options) {
    this.options = options;
    this.templates = {};
}

/**
 * initTemplates
 * Inits the HTML templates.
 *
 * @name initTemplates
 * @function
 * @param {Function} callback The callback function.
 */
NodeIce.prototype.initTemplates = function (callback) {
    var self = this;
    if (self.templates.root === undefined || self.templates.tableRowBlock === undefined) {
        SameTime([
            ReadUtf8.bind(this, self.options.config.template)
          , ReadUtf8.bind(this, self.options.config.tableRowBlock)
        ], function (err, data) {
            if (err) { return callback(err); }
            self.templates.root = data[0];
            self.templates.tableRowBlock = data[1];
            callback(null, self.templates);
        });
    } else {
        return callback(null, self.templates);
    }
};

/**
 * renderHtml
 * Renders the invoice in HTML format.
 *
 * @name renderAsHtml
 * @function
 * @param {Object} ops An object containing the required field output - that
 * should be a string representing the path to the output that will store
 * the HTML code.
 * @param {Function} callback The callback function
 * @return {Invoice} The Invoice instance
 */
NodeIce.prototype.toHtml = function (ops, callback) {

    if (typeof ops === "function") {
        callback = ops;
        ops = {};
    }

    if (typeof ops === "string") {
        ops = {
            output: ops
        };
    }

    var self = this
      , options = self.options
      , tasks = options.data.tasks
      , invoiceHtml = ""
      , invoiceData = {
            seller: options.seller
          , buyer: options.buyer
          , invoice: options.data.invoice
          , description_rows: ""
          , total: {
                main: 0
              , secondary: 0
            }
        }
      ;

    self.initTemplates(function (err, templates) {
        if (err) { return callback(err); }

        IterateObject(tasks, function (cTask, i) {
            // Set the additional fields and compute data
            cTask.nrCrt = i + 1;
            if (typeof cTask.unitPrice === "number") {
                cTask.unitPrice = {
                    main: cTask.unitPrice
                  , secondary: self.convertToSecondary(
                        cTask.unitPrice
                    )
                };
            }

            if (typeof cTask.unitPrice.main === "number") {
                // Set the unit price of this row
                cTask.unitPrice.main = cTask.unitPrice.main.toFixed(2);
                cTask.unitPrice.secondary = cTask.unitPrice.secondary.toFixed(2);
            }

            // Build amount object
            cTask.amount = {
                main: cTask.unitPrice.main * cTask.quantity
              , secondary: cTask.unitPrice.secondary * cTask.quantity
            };

            // Sum the amount to the total
            invoiceData.total.main += cTask.amount.main;
            invoiceData.total.secondary += cTask.amount.secondary;

            // Set the amount of this row
            cTask.amount.main = cTask.amount.main.toFixed(2);
            cTask.amount.secondary = cTask.amount.secondary.toFixed(2);

            // Render HTML for the current row
            invoiceData.description_rows += Mustache.render(
                templates.rowBlockContent, cTask
            );
        });

        // Set the total
        invoiceData.total.main  = invoiceData.total.main.toFixed(2);
        invoiceData.total.secondary = invoiceData.total.secondary.toFixed(2);

        // Render the invoice HTML fields
        invoiceHtml = Mustache.render(templates.root, invoiceData);

        // Output file
        if (typeof ops.output === "string") {
            Fs.writeFile(ops.output, invoiceHtml, function (err, data) {
                callback(err, invoiceHtml);
            });
            return;
        }

        // Callback the data
        callback(null, invoiceHtml);
    });

    return self;
};

/**
 * convertToSecondary
 * Converts a currency into another currency according to the currency
 * balance provided in the options
 *
 * @name convertToSecondary
 * @function
 * @param {Number} input The number that should be converted
 * @return {Number} The converted input
 */
NodeIce.prototype.convertToSecondary = function (input) {
    return input * this.options.data.currencyBalance.secondary / this.options.data.currencyBalance.main;
};

/**
 * renderAsPdf
 * Renders invoice as pdf
 *
 * @name renderAsPdf
 * @function
 * @param {Object} options An object containing the `output` field
 * represeting the path to the pdf file that will be created.
 * @param {Function} callback The callback function
 * @return {Invoice} The Invoice instance
 */
NodeIce.prototype.toPdf = function (ops, callback) {
    var self = this
      , ev = new EventEmitter()
      ;

    if (typeof ops === "function") {
        callback = ops;
        ops = {};
    }

    ops = Ul.merge(ops, {
        phantom: {}
    });

    OneByOne([
        self.toHtml.bind(self)
      , function (next, html) {
  // TODO
        //    var render = Phantom(ops.phantom);
        //    if (typeof ops.output === "string") {
        //    }
        //    Phantom.create(function (ph) {
        //        ph.createPage(function (page) {
        //            page.set("viewportSize", { width: 2480, height: 3508 });
        //            page.open(tmpFileName, function(status) {
        //                page.render(options.output, function() {
        //                    Fs.unlink(tmpFileName);
        //                    ph.exit();
        //                    callback.call(this, arguments);
        //                });
        //            });
        //        });
        //    });
            next();
        }
    ], callback);
};

module.exports = NodeIce;
<|endoftext|>


<commit_before>/**
 * Emma: functional toolkit
 *
 * Emma may be freely distributed under the MIT license.
 * https://github.com/bcarrell/emma
 * Copyright (c) Brandon Carrell
 *
 */

// FIXME
/*jshint unused: false */

/**
 * Internal utilities
 */

var ArrProto = Array.prototype;
var ObjProto = Object.prototype;

var util = {
  isFunction: function(x) {
    return typeof x === 'function';
  },
  isObject: function(x) {
    return typeof x === 'object' && x !== null;
  },
  isString: function(x) {
    return typeof x === 'string';
  },
  isArray: Array.isArray || function(x) {
    return Object.prototype.toString.call(x) === '[object Array]';
  },
  isNumber: function(x) {
    return typeof x === 'number';
  }
};

function addOp(context, f) {
  context.ops.push(f);
}

/**
 * External utilities
 */

// terminates chain
function realize() {
  var _this = this,
      len = this.ops.length;

  for (var i = 0; i < len; i++) {
    // realizing all previously accumulated ops
    this.ops[i]();
  }

  this.ops = [];

  return this;

}

/**
 * Sequence functions
 */

function conj() {
  var _this = this,
      args = arguments;

  addOp(this, function() {
    ArrProto.push.apply(_this.coll, args);
  });

  return this;
}

function cons() {
  var _this = this,
      args = arguments;

  addOp(this, function() {
    ArrProto.unshift.apply(_this.coll, args);
  });

  return this;
}

function _takeWhile(context, f) {
  var _g = context.g,
      xs = [],
      coll = ArrProto.slice.call(context.coll),
      len = coll.length,
      next,
      i;

  for (i = 0; i < len; i++) {
    next = coll[i];
    if (f(next, i)) {
      xs.push(next);
    }
  }

  return xs;
}

function takeWhile(f) {
  var _this = this;

  addOp(this, function() {
    var xs = _takeWhile(_this, f);

    _this.coll = xs;
  });

  return this;

}

function take(x) {
  return takeWhile.call(this, function(_, i) {
    return x >= (i + 1);
  });
}

function dropWhile(f) {
  var _this = this;

  addOp(this, function() {
    var xs = _takeWhile(_this, f),
        coll = ArrProto.slice.call(_this.coll, xs.length);

    _this.coll = coll;
  });

  return this;

}

function drop(x) {
  return dropWhile.call(this, function(_, i) {
    return x >= (i + 1);
  });
}

function distinct() {
  var _this = this;

  addOp(this, function() {
    _this.coll = ArrProto.filter.call(_this.coll, function(el, pos, self) {
      return ArrProto.indexOf.call(self, el) === pos;
    });
  });

  return this;
}

function filter(f) {
  var _this = this;

  addOp(this, function() {
    _this.coll = ArrProto.filter.call(_this.coll, function(el, pos, self) {
      return f(el);
    });
  });

  return this;
}

function rest() {
  var _this = this;

  addOp(this, function() {
    ArrProto.shift.call(_this.coll);
  });

  return this;
}

function interleave(xs) {
  var _this = this;

  addOp(this, function() {
    var i,
        coll = _this.coll,
        len = xs.length,
        ys = [];

    for (i = 0; i < len; i++) {
      ys.push(coll[i]);
      ys.push(xs[i]);
    }

    _this.coll = ys;
  });

  return this;
}

function interpose(x) {
  var _this = this;

  addOp(this, function() {
    var coll = _this.coll,
        len = coll.length,
        xs = [],
        i;

    for (i = 0; i < len; i++) {
      xs.push(coll[i]);
      xs.push(x);
    }

    xs.pop();

    _this.coll = xs;

  });

  return this;
}

var Emma = {
  create: function(xs, g) {
    var newEmma = Object.create(Emma.prototype),
        isArr = util.isArray;

    newEmma.coll = xs;
    newEmma.g = g;
    newEmma.ops = [];

    if (!isArr(xs)) {
      newEmma.coll = [xs];
    }

    return newEmma;
  },
  prototype: { // public API
    conj: conj,
    cons: cons,
    realize: realize,
    r: realize,
    take: take,
    takeWhile: takeWhile,
    distinct: distinct,
    filter: filter,
    rest: rest,
    interleave: interleave,
    interpose: interpose,
    drop: drop,
    dropWhile: dropWhile
  }
};

/**
 * Main constructor/api for Emma to manage collections with, happily accepts
 * two function signatures:
 *
 *    (xs)
 *      - xs should be an array
 *    (xs, f)
 *      - xs can be an array, number, or string.  If xs is an array, f will
 *        use the last element of the array to `infinitely` grow the collection
 *        if it is necessary.  fn should be a function which accepts a single
 *        argument used to grow the collection.
 *
 * Usage example:
 *
 *   Array:
 *       var e = require('emma');
 *       var coll = e([1, 2, 3, 4]);
 *
 *   Function:
 *       var e = require('emma');
 *       var coll = e(0, function(x) {
 *          return x + 1;
 *       });
 *
 *     --
 *
 *       var e = require('emma');
 *       var coll = e([1, 2, 3], function(x) { // will generate starting at 4
 *          return x + 1;
 *       });
 */
module.exports = function(xs, g) {
  var isFn = util.isFunction,
      isArr = util.isArray,
      isStr = util.isString,
      isNum = util.isNumber;

  if (isFn(g) && (isArr(xs) || isStr(xs) || isNum(xs))) {
    return Emma.create(xs, g);
  } else if (isArr(xs) && g === undefined) {
    return Emma.create(xs);
  } else {
    throw new Error('Invalid function signature.');
  }
};
<commit_msg>remove arrproto reference<commit_after>/**
 * Emma: functional toolkit
 *
 * Emma may be freely distributed under the MIT license.
 * https://github.com/bcarrell/emma
 * Copyright (c) Brandon Carrell
 *
 */

// FIXME
/*jshint unused: false */

/**
 * Internal utilities
 */

var ArrProto = Array.prototype;
var ObjProto = Object.prototype;

var util = {
  isFunction: function(x) {
    return typeof x === 'function';
  },
  isObject: function(x) {
    return typeof x === 'object' && x !== null;
  },
  isString: function(x) {
    return typeof x === 'string';
  },
  isArray: Array.isArray || function(x) {
    return Object.prototype.toString.call(x) === '[object Array]';
  },
  isNumber: function(x) {
    return typeof x === 'number';
  }
};

function addOp(context, f) {
  context.ops.push(f);
}

/**
 * External utilities
 */

// terminates chain
function realize() {
  var _this = this,
      len = this.ops.length;

  for (var i = 0; i < len; i++) {
    // realizing all previously accumulated ops
    this.ops[i]();
  }

  this.ops = [];

  return this;

}

/**
 * Sequence functions
 */

function conj() {
  var _this = this,
      args = arguments;

  addOp(this, function() {
    _this.coll.push.apply(_this.coll, args);
  });

  return this;
}

function cons() {
  var _this = this,
      args = arguments;

  addOp(this, function() {
    _this.coll.unshift.apply(_this.coll, args);
  });

  return this;
}

function _takeWhile(context, f) {
  var _g = context.g,
      xs = [],
      coll = ArrProto.slice.call(context.coll),
      len = coll.length,
      next,
      i;

  for (i = 0; i < len; i++) {
    next = coll[i];
    if (f(next, i)) {
      xs.push(next);
    }
  }

  return xs;
}

function takeWhile(f) {
  var _this = this;

  addOp(this, function() {
    var xs = _takeWhile(_this, f);

    _this.coll = xs;
  });

  return this;

}

function take(x) {
  return takeWhile.call(this, function(_, i) {
    return x >= (i + 1);
  });
}

function dropWhile(f) {
  var _this = this;

  addOp(this, function() {
    var xs = _takeWhile(_this, f),
        coll = ArrProto.slice.call(_this.coll, xs.length);

    _this.coll = coll;
  });

  return this;

}

function drop(x) {
  return dropWhile.call(this, function(_, i) {
    return x >= (i + 1);
  });
}

function distinct() {
  var _this = this;

  addOp(this, function() {
    _this.coll = ArrProto.filter.call(_this.coll, function(el, pos, self) {
      return ArrProto.indexOf.call(self, el) === pos;
    });
  });

  return this;
}

function filter(f) {
  var _this = this;

  addOp(this, function() {
    _this.coll = ArrProto.filter.call(_this.coll, function(el, pos, self) {
      return f(el);
    });
  });

  return this;
}

function rest() {
  var _this = this;

  addOp(this, function() {
    ArrProto.shift.call(_this.coll);
  });

  return this;
}

function interleave(xs) {
  var _this = this;

  addOp(this, function() {
    var i,
        coll = _this.coll,
        len = xs.length,
        ys = [];

    for (i = 0; i < len; i++) {
      ys.push(coll[i]);
      ys.push(xs[i]);
    }

    _this.coll = ys;
  });

  return this;
}

function interpose(x) {
  var _this = this;

  addOp(this, function() {
    var coll = _this.coll,
        len = coll.length,
        xs = [],
        i;

    for (i = 0; i < len; i++) {
      xs.push(coll[i]);
      xs.push(x);
    }

    xs.pop();

    _this.coll = xs;

  });

  return this;
}

var Emma = {
  create: function(xs, g) {
    var newEmma = Object.create(Emma.prototype),
      isArr = util.isArray;

    newEmma.coll = xs;
    newEmma.g = g;
    newEmma.ops = [];

    if (!isArr(xs)) {
      newEmma.coll = [xs];
    }

    return newEmma;
  },
  prototype: { // public API
    conj: conj,
    cons: cons,
    realize: realize,
    r: realize,
    take: take,
    takeWhile: takeWhile,
    distinct: distinct,
    filter: filter,
    rest: rest,
    interleave: interleave,
    interpose: interpose,
    drop: drop,
    dropWhile: dropWhile
  }
};

/**
 * Main constructor/api for Emma to manage collections with, happily accepts
 * two function signatures:
 *
 *    (xs)
 *      - xs should be an array
 *    (xs, f)
 *      - xs can be an array, number, or string.  If xs is an array, f will
 *        use the last element of the array to `infinitely` grow the collection
 *        if it is necessary.  fn should be a function which accepts a single
 *        argument used to grow the collection.
 *
 * Usage example:
 *
 *   Array:
 *       var e = require('emma');
 *       var coll = e([1, 2, 3, 4]);
 *
 *   Function:
 *       var e = require('emma');
 *       var coll = e(0, function(x) {
 *          return x + 1;
 *       });
 *
 *     --
 *
 *       var e = require('emma');
 *       var coll = e([1, 2, 3], function(x) { // will generate starting at 4
 *          return x + 1;
 *       });
 */
module.exports = function(xs, g) {
  var isFn = util.isFunction,
    isArr = util.isArray,
    isStr = util.isString,
    isNum = util.isNumber;

  if (isFn(g) && (isArr(xs) || isStr(xs) || isNum(xs))) {
    return Emma.create(xs, g);
  } else if (isArr(xs) && g === undefined) {
    return Emma.create(xs);
  } else {
    throw new Error('Invalid function signature.');
  }
};
<|endoftext|>


<commit_before>'use babel'

/* @flow */

import Path from 'path'
import { CompositeDisposable } from 'atom'
import { exec, findCachedAsync } from 'atom-linter'
import { shouldTriggerAutocomplete } from 'atom-autocomplete'
import { INIT_MESSAGE, shouldRunAutocomplete, toLinterMessages, injectPosition, toAutocompleteSuggestions } from './helpers'

module.exports = {
  executablePath: 'flow',
  onlyIfAppropriate: true,

  config: {
    onlyIfAppropriate: {
      title: "Only activate when .flowconfig exists",
      type: 'boolean',
      default: true
    },
    executablePath: {
      type: 'string',
      description: 'Path to `flow` executable',
      default: ''
    }
  },

  activate() {
    require('atom-package-deps').install()

    this.subscriptions = new CompositeDisposable()
    this.subscriptions.add(atom.config.observe('flow-ide.executablePath', executablePath => {
      this.executablePath = executablePath
    }))
    this.subscriptions.add(atom.config.observe('flow-ide.onlyIfAppropriate', onlyIfAppropriate => {
      this.onlyIfAppropriate = onlyIfAppropriate
    }))
  },

  deactivate() {
    this.subscriptions.dispose()
  },

  provideLinter(): Object {
    const linter = {
      name: 'Flow IDE',
      grammarScopes: ['source.js', 'source.js.jsx'],
      scope: 'project',
      lintOnFly: false,
      lint: async (textEditor) => {
        const filePath = textEditor.getPath()
        const fileDirectory = Path.dirname(filePath)

        if (this.onlyIfAppropriate) {
          const configFile = await findCachedAsync(fileDirectory, '.flowconfig')
          if (!configFile) {
            return []
          }
        }

        const executable = (
          await findCachedAsync(fileDirectory, 'node_modules/.bin/flow') ||
          this.executablePath ||
          'flow'
        )

        let result
        try {
          result = await exec(executable, ['status', '--json'], {cwd: fileDirectory})
        } catch (error) {
          if (error.message.indexOf(INIT_MESSAGE) !== -1) {
            return await linter.lint(textEditor)
          } else if (err.code === 'ENOENT') {
            throw new Error('Unable to find `flow` executable.')
          } else {
            throw error
          }
        }

        return toLinterMessages(result)
      }
    }
    return linter
  },

  provideAutocomplete(): Object {
    const provider = {
      selector: '.source.js, .source.js.jsx',
      disableForSelector: '.comment',
      inclusionPriority: 100,
      getSuggestions: async ({editor, bufferPosition, prefix, activatedManually}) => {
        const filePath = editor.getPath()
        const fileDirectory = Path.dirname(filePath)
        const fileContents = injectPosition(editor.getText(), editor, bufferPosition)

        if (this.onlyIfAppropriate) {
          const configFile = await findCachedAsync(fileDirectory, '.flowconfig')
          if (!configFile) {
            return []
          }
        }
        if (!shouldTriggerAutocomplete({ activatedManually, bufferPosition, editor })) {
          return []
        }

        let result
        try {
          result = await exec(this.executablePath, ['autocomplete', '--json', filePath], {cwd: fileDirectory, stdin: fileContents})
        } catch (_) {
          if (_.message.indexOf(INIT_MESSAGE) !== -1) {
            return await provider.getSuggestions(editor)
          } else throw _
        }

        return toAutocompleteSuggestions(result, prefix)
      }
    }
    return provider
  }
}
<commit_msg>fix reference to error variable<commit_after>'use babel'

/* @flow */

import Path from 'path'
import { CompositeDisposable } from 'atom'
import { exec, findCachedAsync } from 'atom-linter'
import { shouldTriggerAutocomplete } from 'atom-autocomplete'
import { INIT_MESSAGE, shouldRunAutocomplete, toLinterMessages, injectPosition, toAutocompleteSuggestions } from './helpers'

module.exports = {
  executablePath: 'flow',
  onlyIfAppropriate: true,

  config: {
    onlyIfAppropriate: {
      title: "Only activate when .flowconfig exists",
      type: 'boolean',
      default: true
    },
    executablePath: {
      type: 'string',
      description: 'Path to `flow` executable',
      default: ''
    }
  },

  activate() {
    require('atom-package-deps').install()

    this.subscriptions = new CompositeDisposable()
    this.subscriptions.add(atom.config.observe('flow-ide.executablePath', executablePath => {
      this.executablePath = executablePath
    }))
    this.subscriptions.add(atom.config.observe('flow-ide.onlyIfAppropriate', onlyIfAppropriate => {
      this.onlyIfAppropriate = onlyIfAppropriate
    }))
  },

  deactivate() {
    this.subscriptions.dispose()
  },

  provideLinter(): Object {
    const linter = {
      name: 'Flow IDE',
      grammarScopes: ['source.js', 'source.js.jsx'],
      scope: 'project',
      lintOnFly: false,
      lint: async (textEditor) => {
        const filePath = textEditor.getPath()
        const fileDirectory = Path.dirname(filePath)

        if (this.onlyIfAppropriate) {
          const configFile = await findCachedAsync(fileDirectory, '.flowconfig')
          if (!configFile) {
            return []
          }
        }

        const executable = (
          await findCachedAsync(fileDirectory, 'node_modules/.bin/flow') ||
          this.executablePath ||
          'flow'
        )

        let result
        try {
          result = await exec(executable, ['status', '--json'], {cwd: fileDirectory})
        } catch (error) {
          if (error.message.indexOf(INIT_MESSAGE) !== -1) {
            return await linter.lint(textEditor)
          } else if (error.code === 'ENOENT') {
            throw new Error('Unable to find `flow` executable.')
          } else {
            throw error
          }
        }

        return toLinterMessages(result)
      }
    }
    return linter
  },

  provideAutocomplete(): Object {
    const provider = {
      selector: '.source.js, .source.js.jsx',
      disableForSelector: '.comment',
      inclusionPriority: 100,
      getSuggestions: async ({editor, bufferPosition, prefix, activatedManually}) => {
        const filePath = editor.getPath()
        const fileDirectory = Path.dirname(filePath)
        const fileContents = injectPosition(editor.getText(), editor, bufferPosition)

        if (this.onlyIfAppropriate) {
          const configFile = await findCachedAsync(fileDirectory, '.flowconfig')
          if (!configFile) {
            return []
          }
        }
        if (!shouldTriggerAutocomplete({ activatedManually, bufferPosition, editor })) {
          return []
        }

        let result
        try {
          result = await exec(this.executablePath, ['autocomplete', '--json', filePath], {cwd: fileDirectory, stdin: fileContents})
        } catch (_) {
          if (_.message.indexOf(INIT_MESSAGE) !== -1) {
            return await provider.getSuggestions(editor)
          } else throw _
        }

        return toAutocompleteSuggestions(result, prefix)
      }
    }
    return provider
  }
}
<|endoftext|>


<commit_before>var Generation = require('./generation');
var Individual = require('./individual');
var Breeder = require('./breeder');
var Mutator = require('./mutator');
var Problem = require('./problem');
var defaults = require('./defaults');
var _ = require('lodash');
var async = require('async');

function Evolve(options) {
    options = options || {};
    this.generations = options.generations || defaults.generations;
    this.populationSize = options.populationSize || defaults.populationSize;
    this.elites = options.elites || defaults.elites;

    this.breeder = new Breeder(options.breeding);

    //Allows for mutation to be toggled
    if(options.mutation) {
        this.mutator = new Mutator(options.mutation);
    }

    this.individualSchema = options.individual;
    this.problem = new Problem(options.problem);
    this.generation = new Generation(this.initPopulation(), this.breeder, this.mutator, this.problem, this.elites);

}

Evolve.prototype = Object.create(Object.prototype);

Evolve.constructor = Evolve;

Evolve.prototype.initPopulation = function () {
    return _.times(this.populationSize, function () {
        return new Individual(this.individualSchema);
    }, this);
};

Evolve.prototype.validatePreconditions = function() {
    return this.individualSchema && this.problem && this.generation;
};

Evolve.prototype.run = function (callback) {
    var index = 0;
    if(!this.validatePreconditions()) {
        console.error('Invalid config', this);
        return callback('Cant start, preconditions not met');
    }
    async.whilst(() => { return index < this.generations; },
        (callback) => {
            index++;
            console.log('Generation: ', index);
            this.generation.run((err, newGeneration) => {
                if (err) {
                    return callback(err);
                }
                this.generation = newGeneration;
                return callback();
            });
        },
        (err) => {
            if (err) {
                return callback(err);
            }
            this.generation.calculateFitness();
            var bestIndividual = this.generation.selectBestIndividual();
            return callback(null, bestIndividual.chromosone);
        });
};

module.exports = Evolve;<commit_msg>removed console log<commit_after>var Generation = require('./generation');
var Individual = require('./individual');
var Breeder = require('./breeder');
var Mutator = require('./mutator');
var Problem = require('./problem');
var defaults = require('./defaults');
var _ = require('lodash');
var async = require('async');

function Evolve(options) {
    options = options || {};
    this.generations = options.generations || defaults.generations;
    this.populationSize = options.populationSize || defaults.populationSize;
    this.elites = options.elites || defaults.elites;

    this.breeder = new Breeder(options.breeding);

    //Allows for mutation to be toggled
    if(options.mutation) {
        this.mutator = new Mutator(options.mutation);
    }

    this.individualSchema = options.individual;
    this.problem = new Problem(options.problem);
    this.generation = new Generation(this.initPopulation(), this.breeder, this.mutator, this.problem, this.elites);

}

Evolve.prototype = Object.create(Object.prototype);

Evolve.constructor = Evolve;

Evolve.prototype.initPopulation = function () {
    return _.times(this.populationSize, function () {
        return new Individual(this.individualSchema);
    }, this);
};

Evolve.prototype.validatePreconditions = function() {
    return this.individualSchema && this.problem && this.generation;
};

Evolve.prototype.run = function (callback) {
    var index = 0;
    if(!this.validatePreconditions()) {
        console.error('Invalid config', this);
        return callback('Cant start, preconditions not met');
    }
    async.whilst(() => { return index < this.generations; },
        (callback) => {
            index++;
            this.generation.run((err, newGeneration) => {
                if (err) {
                    return callback(err);
                }
                this.generation = newGeneration;
                return callback();
            });
        },
        (err) => {
            if (err) {
                return callback(err);
            }
            this.generation.calculateFitness();
            var bestIndividual = this.generation.selectBestIndividual();
            return callback(null, bestIndividual.chromosone);
        });
};

module.exports = Evolve;<|endoftext|>


<commit_before>var express = require('express');
var url = require('url');
var net = require('net');
var path = require('path');
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var exnted = require('util')._extend;
var util = require('./util');
var rules = require('./rules');
var dispatch = require('./https');
var httpsUtil = require('./https/util');
var rulesUtil = require('./rules/util');
var initDataServer = require('./util/data-server');
var initLogServer = require('./util/log-server');
var config = require('../package.json');
var LOCALHOST = '127.0.0.1';

function tunnelProxy(server, proxy) {
	process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
	server.on('connect', function(req, reqSocket, head) {//ws, wss, https proxy
		var tunnelUrl = req.url = util.setProtocol(req.url, true);
		var options = parseUrl();
		var resSocket, proxySocket, responsed;

		if (!options.hostname) {
			tunnelUrl = req.url = util.setProtocol(req.headers.host, true);
			options = parseUrl();
		}
		var hostname = options.hostname;
		abortIfUnavailable(reqSocket);
		var _rules = req.rules = rules.resolveRules(tunnelUrl);
		var filter = rules.resolveFilter(tunnelUrl);

		if (/local\.whistlejs\.com$/.test(hostname) || filter.https) {
			sendEstablished();
			dispatch(reqSocket, hostname, proxy);
			return;
		}

		var reqEmitter = new EventEmitter();
		var headers = req.headers;
		var reqData = {
				ip: util.getClientIp(req) || LOCALHOST,
				method: util.toUpperCase(req.method) || 'CONNECT',
				httpVersion: req.httpVersion || '1.1',
	            headers: headers
			};
		var resData = {headers: {}};
		var data = reqEmitter.data = {
				url: options.host,
				startTime: Date.now(),
				rules: _rules,
				req: reqData,
				res: resData,
				isHttps: true
		};

		var proxyUrl = util.rule.getProxy(_rules.rule);
		if (proxyUrl) {
			var isSocks = /^socks:\/\//.test(proxyUrl);
			data.realUrl = proxyUrl;
			var _url = 'https:' + util.removeProtocol(proxyUrl);
			data.proxy = true;
			resolveHost(_url, function(ip) {
				if (options.port == config.port && util.isLocalAddress(ip)) {
					options = parseUrl();
					return tunnel();
				}
				options = parseUrl(_url, isSocks ? 1080 : 8888);
				var opts = url.parse(tunnelUrl);
				headers.host = opts.hostname + ':' + (opts.port || 443);
				util.connect({
					isSocks: isSocks,
					host: ip,
					port: options.port,
					auth: options.auth,
					url: 'http://' + headers.host,
					headers: headers
				}, function(err, _proxySocket) {
					if (err) {
						return emitError(err);
					}
					proxySocket = _proxySocket;
					abortIfUnavailable(proxySocket);
					sendEstablished().pipe(proxySocket).pipe(reqSocket);
				});
			});
		} else {
			if (_rules.rule) {
				var _url = util.setProtocol(util.rule.getMatcher(_rules.rule), true);
				if (/^https:/i.test(_url)) {
					options = parseUrl(_url);
					data.realUrl = _url;
				} else {
					var protocol = util.getProtocol(_url);
					protocol = protocol.substring(0, protocol.length - 1);
					var localProtocol = protocol + 'sslport';
					var port = config[localProtocol];
					if (port) {
						data.realUrl = _url;
						proxy.emit(localProtocol, {
							rule: _url,
							url: tunnelUrl,
							type: protocol,
							callback: function (err, data) {
								if (err) {
									return emitError(err);
								}
								if (data && data.port > 0) {
									port = data.port;
								}
								options = parseUrl(_url);
								options.protocol = 'https:';
								options.hostname = LOCALHOST;
								options.host = options.hostname + ':' + port;
								options.port = port;
								tunnel('https://' + hostname + ':' + port, options.hostname);
							}
						});
						return;
					} else {
						_url = null;//如果规则无法处理，则直接访问
					}
				}
			}

			tunnel(_url);
		}

		function tunnel(url, ip) {
			resolveHost(url || tunnelUrl, function(ip) {
				resSocket = net.connect(options.port, ip, function() {
		            resSocket.pipe(reqSocket).pipe(resSocket);
		            sendEstablished();
		        });
				abortIfUnavailable(resSocket);
			}, ip);
		}

		function parseUrl(_url, port) {
			_url = _url || tunnelUrl;
			options = req.options = url.parse(_url);
			options.port = options.port || port || 443;
			return options;
		}

		function resolveHost(url, callback, ip) {
			!filter.hide && proxy.emit('request', reqEmitter);
			rules.resolveHost(ip || url, function(err, ip) {
				data.requestTime = data.dnsTime = Date.now();
				resData.ip = ip || LOCALHOST;
				reqEmitter.emit('send', data);
				err ? emitError(err) : callback(ip);
			}, filter.host);
		}

		function abortIfUnavailable(socket) {
			socket.on('error', emitError).on('close', emitError);
		}

		function sendEstablished() {
			reqSocket.write('HTTP/1.1 200 Connection Established\r\nProxy-Agent: ' + config.name + '\r\n\r\n');
			responsed = true;
			if (!reqEmitter) {
				return;
			}
			data.responseTime = data.endTime = Date.now();
            resData.statusCode = 200;
			reqEmitter.emit('response', data);
			reqEmitter.emit('end', data);
			return reqSocket;
		}

		function emitError(err) {
			if (responsed) {
				return;
			}
			responsed = true;
			resSocket && resSocket.destroy();
			proxySocket && proxySocket.destroy();
			reqSocket.destroy();
			data.responseTime = data.endTime = Date.now();

			if (!resData.ip) {
				resData.ip = LOCALHOST;
			}

			if (err) {
				err = new Error('aborted');
				data.reqError = true;
				resData.statusCode ='aborted';
				reqData.body = util.getErrorStack(err);
				reqEmitter.emit('abort', data);
			} else {
				data.resError = true;
				resData.statusCode = resData.statusCode || 502;
				resData.body = util.getErrorStack(err);
				util.emitError(reqEmitter, data);
			}
		}
    });

	return server;
}

function proxy(conf) {
	if (conf) {
		['port', 'sockets', 'timeout',
		 'username', 'password', 'uipath', 'rules', 'debug']
			.forEach(function(name) {
				if (conf[name]) {
					config[name] = conf[name];
				}
			});

		if (Array.isArray(conf.ports)) {
			config.ports = config.ports.concat(conf.ports);
		}
	}

	if (!conf || typeof conf.middlewares != 'string') {
		if (!Array.isArray(conf.middlewares)) {
			config.middlewares = [];
		}
	} else {
		config.middlewares = conf.middlewares.trim().split(/\s*,\s*/g);
	}

	config.middlewares.map(util.resolvePath);

	var port = config.port;
	config.ports.forEach(function(name) {
		if (!/port$/.test(name) || name == 'port') {
			throw new Error('port name "' + name + '" must be end of "port", but not equals "port", like: ' + name + 'port');
		}
		config[name] = ++port;
	});

	var agentConfig = {
				maxSockets: config.sockets,
				keepAlive: config.keepAlive,
				keepAliveMsecs: config.keepAliveMsecs
			};
	config.httpAgent = config.debug ? false : util.createAgent(agentConfig);
	config.httpsAgent = config.debug ? false : util.createAgent(agentConfig, true);
	config.WEINRE_HOST = 'weinre.' + config.localUIHost;

	var app = express();
	var server = app.listen(config.port);
	var proxyEvents = new EventEmitter();
	var middlewares = ['./init',
	               '../biz']
				   .concat(require('./inspectors'))
				   .concat(config.middlewares)
	               .concat(require('./handlers'));

	proxyEvents.config = config;
	middlewares.forEach(function(mw) {
		mw && app.use((typeof mw == 'string' ? require(mw) : mw).bind(proxyEvents));
	});

	parseHosts(config);
	exportInterfaces(proxyEvents);
	tunnelProxy(server, proxyEvents);
	initDataServer(proxyEvents);
	initLogServer(proxyEvents);
	require('../biz/init')(proxyEvents);

	return proxyEvents;
}

function exportInterfaces(obj) {
	obj.rules = rules;
	obj.util = util;
	obj.rulesUtil = rulesUtil;
	obj.httpsUtil = httpsUtil;
	return obj;
}

function parseHosts(config) {
	var rulesPath = config.rules;
	if (rulesPath) {
		try {
			rulesUtil.setPublicHosts(fs.readFileSync(path.resolve(rulesPath), {encoding: 'utf8'}));
			rulesUtil.enablePublicHosts();
		} catch(e) {}
	}

	rulesUtil.loadHosts(config);
}

process.on('uncaughtException', function(err){
	var stack = util.getErrorStack(err);
	fs.writeFileSync(path.join(process.cwd(), config.name + '.log'), '\r\n' + util.formatDate()  + '\r\n' +  stack + '\r\n', {flag: 'a'});
	console.error(stack);
	process.exit(1);
});

module.exports = exportInterfaces(proxy);<commit_msg>fix: https://github.com/joyent/node/issues/9272<commit_after>var express = require('express');
var url = require('url');
var net = require('net');
var path = require('path');
var tls = require('tls');
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var exnted = require('util')._extend;
var util = require('./util');
var rules = require('./rules');
var dispatch = require('./https');
var httpsUtil = require('./https/util');
var rulesUtil = require('./rules/util');
var initDataServer = require('./util/data-server');
var initLogServer = require('./util/log-server');
var config = require('../package.json');
var LOCALHOST = '127.0.0.1';

if (typeof tls.checkServerIdentity == 'function') {
	var checkServerIdentity = tls.checkServerIdentity;
	tls.checkServerIdentity = function() {
		try {
			return checkServerIdentity.apply(this, arguments);
		} catch(err) {
			return err;
		}
	};
}

function tunnelProxy(server, proxy) {
	process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
	server.on('connect', function(req, reqSocket, head) {//ws, wss, https proxy
		var tunnelUrl = req.url = util.setProtocol(req.url, true);
		var options = parseUrl();
		var resSocket, proxySocket, responsed;

		if (!options.hostname) {
			tunnelUrl = req.url = util.setProtocol(req.headers.host, true);
			options = parseUrl();
		}
		var hostname = options.hostname;
		abortIfUnavailable(reqSocket);
		var _rules = req.rules = rules.resolveRules(tunnelUrl);
		var filter = rules.resolveFilter(tunnelUrl);

		if (/local\.whistlejs\.com$/.test(hostname) || filter.https) {
			sendEstablished();
			dispatch(reqSocket, hostname, proxy);
			return;
		}

		var reqEmitter = new EventEmitter();
		var headers = req.headers;
		var reqData = {
				ip: util.getClientIp(req) || LOCALHOST,
				method: util.toUpperCase(req.method) || 'CONNECT',
				httpVersion: req.httpVersion || '1.1',
	            headers: headers
			};
		var resData = {headers: {}};
		var data = reqEmitter.data = {
				url: options.host,
				startTime: Date.now(),
				rules: _rules,
				req: reqData,
				res: resData,
				isHttps: true
		};

		var proxyUrl = util.rule.getProxy(_rules.rule);
		if (proxyUrl) {
			var isSocks = /^socks:\/\//.test(proxyUrl);
			data.realUrl = proxyUrl;
			var _url = 'https:' + util.removeProtocol(proxyUrl);
			data.proxy = true;
			resolveHost(_url, function(ip) {
				if (options.port == config.port && util.isLocalAddress(ip)) {
					options = parseUrl();
					return tunnel();
				}
				options = parseUrl(_url, isSocks ? 1080 : 8888);
				var opts = url.parse(tunnelUrl);
				headers.host = opts.hostname + ':' + (opts.port || 443);
				util.connect({
					isSocks: isSocks,
					host: ip,
					port: options.port,
					auth: options.auth,
					url: 'http://' + headers.host,
					headers: headers
				}, function(err, _proxySocket) {
					if (err) {
						return emitError(err);
					}
					proxySocket = _proxySocket;
					abortIfUnavailable(proxySocket);
					sendEstablished().pipe(proxySocket).pipe(reqSocket);
				});
			});
		} else {
			if (_rules.rule) {
				var _url = util.setProtocol(util.rule.getMatcher(_rules.rule), true);
				if (/^https:/i.test(_url)) {
					options = parseUrl(_url);
					data.realUrl = _url;
				} else {
					var protocol = util.getProtocol(_url);
					protocol = protocol.substring(0, protocol.length - 1);
					var localProtocol = protocol + 'sslport';
					var port = config[localProtocol];
					if (port) {
						data.realUrl = _url;
						proxy.emit(localProtocol, {
							rule: _url,
							url: tunnelUrl,
							type: protocol,
							callback: function (err, data) {
								if (err) {
									return emitError(err);
								}
								if (data && data.port > 0) {
									port = data.port;
								}
								options = parseUrl(_url);
								options.protocol = 'https:';
								options.hostname = LOCALHOST;
								options.host = options.hostname + ':' + port;
								options.port = port;
								tunnel('https://' + hostname + ':' + port, options.hostname);
							}
						});
						return;
					} else {
						_url = null;//如果规则无法处理，则直接访问
					}
				}
			}

			tunnel(_url);
		}

		function tunnel(url, ip) {
			resolveHost(url || tunnelUrl, function(ip) {
				resSocket = net.connect(options.port, ip, function() {
		            resSocket.pipe(reqSocket).pipe(resSocket);
		            sendEstablished();
		        });
				abortIfUnavailable(resSocket);
			}, ip);
		}

		function parseUrl(_url, port) {
			_url = _url || tunnelUrl;
			options = req.options = url.parse(_url);
			options.port = options.port || port || 443;
			return options;
		}

		function resolveHost(url, callback, ip) {
			!filter.hide && proxy.emit('request', reqEmitter);
			rules.resolveHost(ip || url, function(err, ip) {
				data.requestTime = data.dnsTime = Date.now();
				resData.ip = ip || LOCALHOST;
				reqEmitter.emit('send', data);
				err ? emitError(err) : callback(ip);
			}, filter.host);
		}

		function abortIfUnavailable(socket) {
			socket.on('error', emitError).on('close', emitError);
		}

		function sendEstablished() {
			reqSocket.write('HTTP/1.1 200 Connection Established\r\nProxy-Agent: ' + config.name + '\r\n\r\n');
			responsed = true;
			if (!reqEmitter) {
				return;
			}
			data.responseTime = data.endTime = Date.now();
            resData.statusCode = 200;
			reqEmitter.emit('response', data);
			reqEmitter.emit('end', data);
			return reqSocket;
		}

		function emitError(err) {
			if (responsed) {
				return;
			}
			responsed = true;
			resSocket && resSocket.destroy();
			proxySocket && proxySocket.destroy();
			reqSocket.destroy();
			data.responseTime = data.endTime = Date.now();

			if (!resData.ip) {
				resData.ip = LOCALHOST;
			}

			if (err) {
				err = new Error('aborted');
				data.reqError = true;
				resData.statusCode ='aborted';
				reqData.body = util.getErrorStack(err);
				reqEmitter.emit('abort', data);
			} else {
				data.resError = true;
				resData.statusCode = resData.statusCode || 502;
				resData.body = util.getErrorStack(err);
				util.emitError(reqEmitter, data);
			}
		}
    });

	return server;
}

function proxy(conf) {
	if (conf) {
		['port', 'sockets', 'timeout',
		 'username', 'password', 'uipath', 'rules', 'debug']
			.forEach(function(name) {
				if (conf[name]) {
					config[name] = conf[name];
				}
			});

		if (Array.isArray(conf.ports)) {
			config.ports = config.ports.concat(conf.ports);
		}
	}

	if (!conf || typeof conf.middlewares != 'string') {
		if (!Array.isArray(conf.middlewares)) {
			config.middlewares = [];
		}
	} else {
		config.middlewares = conf.middlewares.trim().split(/\s*,\s*/g);
	}

	config.middlewares.map(util.resolvePath);

	var port = config.port;
	config.ports.forEach(function(name) {
		if (!/port$/.test(name) || name == 'port') {
			throw new Error('port name "' + name + '" must be end of "port", but not equals "port", like: ' + name + 'port');
		}
		config[name] = ++port;
	});

	var agentConfig = {
				maxSockets: config.sockets,
				keepAlive: config.keepAlive,
				keepAliveMsecs: config.keepAliveMsecs
			};
	config.httpAgent = config.debug ? false : util.createAgent(agentConfig);
	config.httpsAgent = config.debug ? false : util.createAgent(agentConfig, true);
	config.WEINRE_HOST = 'weinre.' + config.localUIHost;

	var app = express();
	var server = app.listen(config.port);
	var proxyEvents = new EventEmitter();
	var middlewares = ['./init',
	               '../biz']
				   .concat(require('./inspectors'))
				   .concat(config.middlewares)
	               .concat(require('./handlers'));

	proxyEvents.config = config;
	middlewares.forEach(function(mw) {
		mw && app.use((typeof mw == 'string' ? require(mw) : mw).bind(proxyEvents));
	});

	parseHosts(config);
	exportInterfaces(proxyEvents);
	tunnelProxy(server, proxyEvents);
	initDataServer(proxyEvents);
	initLogServer(proxyEvents);
	require('../biz/init')(proxyEvents);

	return proxyEvents;
}

function exportInterfaces(obj) {
	obj.rules = rules;
	obj.util = util;
	obj.rulesUtil = rulesUtil;
	obj.httpsUtil = httpsUtil;
	return obj;
}

function parseHosts(config) {
	var rulesPath = config.rules;
	if (rulesPath) {
		try {
			rulesUtil.setPublicHosts(fs.readFileSync(path.resolve(rulesPath), {encoding: 'utf8'}));
			rulesUtil.enablePublicHosts();
		} catch(e) {}
	}

	rulesUtil.loadHosts(config);
}

process.on('uncaughtException', function(err){
	var stack = util.getErrorStack(err);
	fs.writeFileSync(path.join(process.cwd(), config.name + '.log'), '\r\n' + util.formatDate()  + '\r\n' +  stack + '\r\n', {flag: 'a'});
	console.error(stack);
	process.exit(1);
});

module.exports = exportInterfaces(proxy);<|endoftext|>


<commit_before>var ps = {}

ps.name = {
  pretty: 'PolicyStat LLC'
}

ps.copyrightNotice = 'Copyright © ' + new Date().getFullYear() + ' ' + ps.name.pretty

ps.openSource = {
  license: {
    pretty: 'BSD 3–Clause',
    spdx: 'BSD-3-Clause'
  }
}

module.exports = ps
<commit_msg>Export testing.browsers.zuul<commit_after>var ps = {}

ps.name = {
  pretty: 'PolicyStat LLC'
}

ps.copyrightNotice = 'Copyright © ' + new Date().getFullYear() + ' ' + ps.name.pretty

ps.openSource = {
  license: {
    pretty: 'BSD 3–Clause',
    spdx: 'BSD-3-Clause'
  }
}

ps.testing = {}
ps.testing.browsers = {}
ps.testing.browsers.zuul = [
  {name: 'ie', version: '8..latest'},
  {name: 'chrome', version: 'latest'},
  {name: 'firefox', version: 'latest'},
  {name: 'safari', version: '6..latest'},
  {name: 'android', version: '4.4..latest'},
  {name: 'iphone', version: 'latest'},
  {name: 'ipad', version: 'latest'}
]

module.exports = ps
<|endoftext|>


<commit_before>'use strict';

var multimatch = require('multimatch'),
    findup = require('findup-sync'),
    path = require('path');

/**
 * AutoPlug Class
 *
 * @param {mixed} options  custom options object or options.prefix string
 */
function AutoPlug(options) {
    this.validateOptions(isType('String', options) ? {prefix: options} : options)
        .plug();
}

/**
 * properties of AutoPlug options for validation
 * @type {Object}
 */
AutoPlug.prototype.optionsProperties = {
    prefix: {
        default: '',
        type: 'String'
    },
    scope: {
        default: ['dependencies', 'devDependencies'],
        type: 'String',
        arrayify: true
    },
    module: {
        default: module.parent,
        type: 'Object'
    },
    requireFn: {
        getDefault: function() {
            return this.options.module.require.bind(this.options.module);
        },
        type: 'Function'
    },
    camelize: {
        default: true,
        type: 'Boolean'
    },
    lazy: {
        default: true,
        type: 'Boolean'
    },
    rename: {
        default: {},
        type: 'Object'
    },
    pattern: {
        type: 'String',
        arrayify: true,
        getDefault: function() {
            return [this.options.prefix + '-*', this.options.prefix + '.*'];
        },
        after: function() {
            this.options.pattern.push('!auto-plug');
        }
    },
    replaceExp: {
        type: 'RegExp',
        getDefault: function() {
            return new RegExp('^' + this.options.prefix + '(-|\\.)');
        }
    },
    config: {
        type: ['String', 'Object'],
        getDefault: function() {
            return findup(
                'package.json',
                {cwd: path.dirname(this.options.module.filename)}
            );
        },
        after: function() {
            this.retrieveAndValidateConfigData();
        }
    }
};

/**
 * sets the container object with requires
 *
 * @return {AutoPlug} this
 */
AutoPlug.prototype.plug = function() {
    this.container = {};
    this.setPackagesToRequire();
    this.pkgNames.forEach(this.addPackageToContainer.bind(this));
    return this;
};

/**
 * sets packages to require according to config, scope and pattern
 *
 * @return {AutoPlug} this
 */
AutoPlug.prototype.setPackagesToRequire = function() {
    this.pkgNames = multimatch(this.options.scope.reduce(function(result, prop) {
        return result.concat(Object.keys(this.options.config[prop] || {}));
    }.bind(this), []), this.options.pattern);
    return this;
};

/**
 * adds a package to the container object
 *
 * @param {String} pkgName  package name to require
 */
AutoPlug.prototype.addPackageToContainer = function(pkgName) {
    var requireName = this.getRequireNameForPackage(pkgName);
    if (this.options.lazy) {
        Object.defineProperty(this.container, requireName, {
            enumerable: true,
            get: function() {
                return this.options.requireFn(pkgName);
            }.bind(this)
        });
    } else {
        this.container[requireName] = this.options.requireFn(pkgName);
    }
};

/**
 * returns container object with requires
 *
 * @return {Object}
 */
AutoPlug.prototype.getContainer = function() {
    return this.container;
};

/**
 * returns a filtered name for a require container property
 *
 * @param  {String} pkgName  original package name
 * @return {String}          filtered name
 */
AutoPlug.prototype.getRequireNameForPackage = function(pkgName) {
    if (this.options.rename[pkgName]) {
        return this.options.rename[pkgName];
    }
    var requireName = pkgName.replace(this.options.replaceExp, '');
    return this.options.camelize ? camelize(requireName) : requireName;
};

/**
 * validate custom options according to option properties
 *
 * @param  {Object}   options  custom options
 * @return {AutoPlug}          this
 */
AutoPlug.prototype.validateOptions = function(options) {
    this.options = (isType('Object', options) ? options : {});
    this.testOptions();
    Object.keys(this.optionsProperties).forEach(function(propertyName) {
        var properties = this.optionsProperties[propertyName],
            validType = arrayify(properties.type).filter(function(type) {
                return isType(type, this.options[propertyName], properties.arrayify ? true : false);
            }.bind(this)).length === 1;
        if (!validType) {
            this.options[propertyName] = properties.hasOwnProperty('getDefault') ?
                properties.getDefault.bind(this)() : properties.default;
        }
        if (properties.arrayify) {
            this.options[propertyName] = arrayify(this.options[propertyName]);
        }
        if (properties.hasOwnProperty('after')) {
            properties.after.bind(this)();
        }
    }.bind(this));
    return this;
};

/**
 * test if given options are valid
 *
 * @return {AutoPlug} this
 */
AutoPlug.prototype.testOptions = function() {
    if (
        (this.options.hasOwnProperty('prefix') && (this.options.prefix === '' || !isType('String', this.options.prefix))) ||
        (!this.options.hasOwnProperty('prefix') &&
            (!this.options.hasOwnProperty('replaceExp') || !this.options.hasOwnProperty('pattern') ||
            !(isType('RegExp', this.options.replaceExp) && isType('String', this.options.pattern, true)))
        )
    ) {
        throw new Error('Neither a prefix option is set, nor replaceExp or pattern options are valid.');
    }
    return this;
};

/**
 * retrieve config data from given path or die
 *
 * @return {AutoPlug} this
 */
AutoPlug.prototype.retrieveAndValidateConfigData = function() {
    if (isType('String', this.options.config)) {
        try {
            this.options.config = require(this.options.config);
        }
        catch (err) {
            throw new Error('Could not require given config file: \'' + this.options.config + '\'');
        }
    }
    if (!isType('Object', this.options.config)) {
        throw new Error('Could not find dependencies. Do you have a package.json file in your project?');
    }
    return this;
};

/**
 * if item is no array, put it in an array
 *
 * @param  {mixed} item
 * @return {Array}
 */
function arrayify(item) {
    return isType('Array', item) ? item : [item];
}

/**
 * transform string to camelcase
 *
 * @param  {String} str
 * @return {String}
 */
function camelize(str) {
    return str.replace(/-(\w)/g, function(m, p1) {
        return p1.toUpperCase();
    });
}

/**
 * test if an item is an object of given type or an array of same type (if allowArrayOfType is true)
 *
 * @param  {String}  type
 * @param  {mixed}   item
 * @param  {Boolean} allowArrayOfType
 * @return {Boolean}                   result
 */
function isType(type, item, allowArrayOfType) {
    var testType = function(obj) {
        return Object.prototype.toString.call(obj) === '[object ' + type + ']';
    };
    if (allowArrayOfType && Object.prototype.toString.call(item) === '[object Array]') {
        return item.every(testType);
    }
    return testType(item);
}

/**
 * export main function
 *
 * @param  {mixed}  options  custom options object or options.prefix string
 * @return {Object}          object containing requires
 */
module.exports = function(options) {
    var autoPlug = new AutoPlug(options);
    return autoPlug.getContainer();
};

// necessary to get the current `module.parent` and resolve paths correctly.
delete require.cache[__filename];
<commit_msg>remove some whitespace<commit_after>'use strict';

var multimatch = require('multimatch'),
    findup = require('findup-sync'),
    path = require('path');

/**
 * AutoPlug Class
 *
 * @param {mixed} options  custom options object or options.prefix string
 */
function AutoPlug(options) {
    this.validateOptions(isType('String', options) ? {prefix: options} : options)
        .plug();
}

/**
 * properties of AutoPlug options for validation
 * @type {Object}
 */
AutoPlug.prototype.optionsProperties = {
    prefix: {
        default: '',
        type: 'String'
    },
    scope: {
        default: ['dependencies', 'devDependencies'],
        type: 'String',
        arrayify: true
    },
    module: {
        default: module.parent,
        type: 'Object'
    },
    requireFn: {
        getDefault: function() {
            return this.options.module.require.bind(this.options.module);
        },
        type: 'Function'
    },
    camelize: {
        default: true,
        type: 'Boolean'
    },
    lazy: {
        default: true,
        type: 'Boolean'
    },
    rename: {
        default: {},
        type: 'Object'
    },
    pattern: {
        type: 'String',
        arrayify: true,
        getDefault: function() {
            return [this.options.prefix + '-*', this.options.prefix + '.*'];
        },
        after: function() {
            this.options.pattern.push('!auto-plug');
        }
    },
    replaceExp: {
        type: 'RegExp',
        getDefault: function() {
            return new RegExp('^' + this.options.prefix + '(-|\\.)');
        }
    },
    config: {
        type: ['String', 'Object'],
        getDefault: function() {
            return findup(
                'package.json',
                {cwd: path.dirname(this.options.module.filename)}
            );
        },
        after: function() {
            this.retrieveAndValidateConfigData();
        }
    }
};

/**
 * sets the container object with requires
 *
 * @return {AutoPlug} this
 */
AutoPlug.prototype.plug = function() {
    this.container = {};
    this.setPackagesToRequire();
    this.pkgNames.forEach(this.addPackageToContainer.bind(this));
    return this;
};

/**
 * sets packages to require according to config, scope and pattern
 *
 * @return {AutoPlug} this
 */
AutoPlug.prototype.setPackagesToRequire = function() {
    this.pkgNames = multimatch(this.options.scope.reduce(function(result, prop) {
        return result.concat(Object.keys(this.options.config[prop] || {}));
    }.bind(this), []), this.options.pattern);
    return this;
};

/**
 * adds a package to the container object
 *
 * @param {String} pkgName  package name to require
 */
AutoPlug.prototype.addPackageToContainer = function(pkgName) {
    var requireName = this.getRequireNameForPackage(pkgName);
    if (this.options.lazy) {
        Object.defineProperty(this.container, requireName, {
            enumerable: true,
            get: function() {
                return this.options.requireFn(pkgName);
            }.bind(this)
        });
    } else {
        this.container[requireName] = this.options.requireFn(pkgName);
    }
};

/**
 * returns container object with requires
 *
 * @return {Object}
 */
AutoPlug.prototype.getContainer = function() {
    return this.container;
};

/**
 * returns a filtered name for a require container property
 *
 * @param  {String} pkgName  original package name
 * @return {String}          filtered name
 */
AutoPlug.prototype.getRequireNameForPackage = function(pkgName) {
    if (this.options.rename[pkgName]) {
        return this.options.rename[pkgName];
    }
    var requireName = pkgName.replace(this.options.replaceExp, '');
    return this.options.camelize ? camelize(requireName) : requireName;
};

/**
 * validate custom options according to option properties
 *
 * @param  {Object}   options  custom options
 * @return {AutoPlug}          this
 */
AutoPlug.prototype.validateOptions = function(options) {
    this.options = (isType('Object', options) ? options : {});
    this.testOptions();
    Object.keys(this.optionsProperties).forEach(function(propertyName) {
        var properties = this.optionsProperties[propertyName],
            validType = arrayify(properties.type).filter(function(type) {
                return isType(type, this.options[propertyName], properties.arrayify ? true : false);
            }.bind(this)).length === 1;
        if (!validType) {
            this.options[propertyName] = properties.hasOwnProperty('getDefault') ?
                properties.getDefault.bind(this)() : properties.default;
        }
        if (properties.arrayify) {
            this.options[propertyName] = arrayify(this.options[propertyName]);
        }
        if (properties.hasOwnProperty('after')) {
            properties.after.bind(this)();
        }
    }.bind(this));
    return this;
};

/**
 * test if given options are valid
 *
 * @return {AutoPlug} this
 */
AutoPlug.prototype.testOptions = function() {
    if (
        (this.options.hasOwnProperty('prefix') && (this.options.prefix === '' || !isType('String', this.options.prefix))) ||
        (!this.options.hasOwnProperty('prefix') &&
            (!this.options.hasOwnProperty('replaceExp') || !this.options.hasOwnProperty('pattern') ||
            !(isType('RegExp', this.options.replaceExp) && isType('String', this.options.pattern, true)))
        )
    ) {
        throw new Error('Neither a prefix option is set, nor replaceExp or pattern options are valid.');
    }
    return this;
};

/**
 * retrieve config data from given path or die
 *
 * @return {AutoPlug} this
 */
AutoPlug.prototype.retrieveAndValidateConfigData = function() {
    if (isType('String', this.options.config)) {
        try {
            this.options.config = require(this.options.config);
        }
        catch (err) {
            throw new Error('Could not require given config file: \'' + this.options.config + '\'');
        }
    }
    if (!isType('Object', this.options.config)) {
        throw new Error('Could not find dependencies. Do you have a package.json file in your project?');
    }
    return this;
};

/**
 * if item is no array, put it in an array
 *
 * @param  {mixed} item
 * @return {Array}
 */
function arrayify(item) {
    return isType('Array', item) ? item : [item];
}

/**
 * transform string to camelcase
 *
 * @param  {String} str
 * @return {String}
 */
function camelize(str) {
    return str.replace(/-(\w)/g, function(m, p1) {
        return p1.toUpperCase();
    });
}

/**
 * test if an item is an object of given type or an array of same type (if allowArrayOfType is true)
 *
 * @param  {String}  type
 * @param  {mixed}   item
 * @param  {Boolean} allowArrayOfType
 * @return {Boolean}                   result
 */
function isType(type, item, allowArrayOfType) {
    var testType = function(obj) {
        return Object.prototype.toString.call(obj) === '[object ' + type + ']';
    };
    if (allowArrayOfType && Object.prototype.toString.call(item) === '[object Array]') {
        return item.every(testType);
    }
    return testType(item);
}

/**
 * export main function
 *
 * @param  {mixed}  options  custom options object or options.prefix string
 * @return {Object}          object containing requires
 */
module.exports = function(options) {
    var autoPlug = new AutoPlug(options);
    return autoPlug.getContainer();
};

// necessary to get the current `module.parent` and resolve paths correctly.
delete require.cache[__filename];
<|endoftext|>


<commit_before>// Dependencies
var Http = require("http")
  , Ul = require("ul")
  , Url = require("url")
  , QueryString = require("querystring")
  ;

/**
 * JsonRequest
 * Creates an HTTP request using the options passed in the first parameter.
 * Then the callback function is called (with `error` and `data` parameters).
 *
 * @name JsonRequest
 * @function
 * @param {String|Object} options A string being the request url or an object containing the following fields:
 *
 *  - `url` (String): The request url.
 *  - `method` (String): The request method.
 *  - `data` (Object): The request POST data.
 *
 * @param {Function} callback The callback function.
 * @return {Object} The request object.
 */
var JsonRequest = module.exports = function (options, callback) {

    // Handle options as string
    if (typeof options === "string") {
        options = {
            url: options
        };
    }

    var parsed = Url.parse(options.url)
      , defaults = Ul.clone(parsed)
      , request = null
      , _done = false
      , body = ""
      ;

    defaults.method = "GET";
    defaults.headers = { "Content-Type": "application/json" };

    // Merge options
    options = Ul.merge(defaults, options);

    // Unique callback
    function opt_callback(err, data) {
        if (_done) { return; }
        _done = true;
        callback(err, data);
    }

    // Handle post data
    if (options.data) {
        options.data = QueryString.stringify(options.data);
        options.headers["Content-Length"] = options.data.length;
    }

    // Create the request
    request = Http.request(options, function(res) {
        res.setEncoding("utf8");
        body = ""
        res.on("data", function (data) {
            body += data.toString();
        }).on("error", function (e) {
            opt_callback(e, null);
        }).on("end", function () {
            try {
                body = JSON.parse(body);
            } catch (e) {}
            opt_callback(null, body);
        });
    }).on("error", function (e) {
        opt_callback(e, null);
    });

    // Handle post data
    if (options.data) {
        request.write(options.data);
    }

    request.end();
    return request;
};
<commit_msg>Https support<commit_after>// Dependencies
var Http = require("http")
  , Https = require("https")
  , Ul = require("ul")
  , Url = require("url")
  , QueryString = require("querystring")
  ;

/**
 * JsonRequest
 * Creates an HTTP request using the options passed in the first parameter.
 * Then the callback function is called (with `error` and `data` parameters).
 *
 * @name JsonRequest
 * @function
 * @param {String|Object} options A string being the request url or an object containing the following fields:
 *
 *  - `url` (String): The request url.
 *  - `method` (String): The request method.
 *  - `data` (Object): The request POST data.
 *
 * @param {Function} callback The callback function.
 * @return {Object} The request object.
 */
var JsonRequest = module.exports = function (options, callback) {

    // Handle options as string
    if (typeof options === "string") {
        options = {
            url: options
        };
    }

    var parsed = Url.parse(options.url)
      , defaults = Ul.clone(parsed)
      , request = null
      , _done = false
      , body = ""
      ;

    defaults.method = "GET";
    defaults.headers = { "Content-Type": "application/json" };

    // Merge options
    options = Ul.merge(options, defaults);

    // Unique callback
    function opt_callback(err, data) {
        if (_done) { return; }
        _done = true;
        callback(err, data);
    }

    // Handle post data
    if (options.data) {
        options.data = QueryString.stringify(options.data);
        options.headers["Content-Length"] = options.data.length;
    }

    // Create the request
    request = (options.protocol === "http:" ? Http : Https).request(options, function(res) {
        res.setEncoding("utf8");
        body = ""
        res.on("data", function (data) {
            body += data.toString();
        }).on("error", function (e) {
            opt_callback(e, null);
        }).on("end", function () {
            try {
                body = JSON.parse(body);
            } catch (e) {}
            opt_callback(null, body);
        });
    }).on("error", function (e) {
        opt_callback(e, null);
    });

    // Handle post data
    if (options.data) {
        request.write(options.data);
    }

    request.end();
    return request;
};
<|endoftext|>


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

var unexpected = Unexpected.create();
var styles = require('./styles');
var types = require('./types');
var assertions = require('./assertions');

styles(unexpected);
types(unexpected);
assertions(unexpected);

// Add an inspect method to all the promises we return that will make the REPL, console.log, and util.inspect render it nicely in node.js:
require('bluebird').prototype.inspect = function () {
    return unexpected.createOutput(require('magicpen').defaultFormat).appendInspected(this).toString();
};

module.exports = unexpected;
<commit_msg>index.js: Take advantage of being able to install regular functions as plugins.<commit_after>module.exports = require('./Unexpected').create()
    .use(require('./styles'))
    .use(require('./types'))
    .use(require('./assertions'));

// Add an inspect method to all the promises we return that will make the REPL, console.log, and util.inspect render it nicely in node.js:
require('bluebird').prototype.inspect = function () {
    return module.exports.createOutput(require('magicpen').defaultFormat).appendInspected(this).toString();
};
<|endoftext|>


<commit_before>var readline = require("readline");
var fs = require("fs");

var CronJob = require("cron").CronJob;

var parseCrontabRe = new RegExp(/^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)/);

function parseCrontab(line){
    var matched = parseCrontabRe.exec(line);
    if (!matched) {
        throw Error("Failed to parse crontab line: " + line);
    }
    return {
        cronTime: [
            matched[1], matched[2], matched[3],
            matched[4], matched[5], matched[6]
        ].join(" "),
        command: matched[7]
    }
}

exports.start = function(crontab, opts){
    var rl = readline.createInterface({
        input: fs.createReadStream(crontab)
    });

    rl.on("line", function(line){
        var parsed = parseCrontab(line);
        console.dir(parsed);
    });
};
<commit_msg>Implement CronJob<commit_after>var readline = require("readline");
var fs = require("fs");
var childProcess = require("child_process");

var CronJob = require("cron").CronJob;

var parseCrontabRe = new RegExp(/^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/);

function parseCrontab(line){
    var matched = parseCrontabRe.exec(line);
    if (!matched) {
        throw Error("Failed to parse crontab line: " + line);
    }
    return {
        cronTime: [
            matched[1], matched[2], matched[3],
            matched[4], matched[5], matched[6]
        ].join(" "),
        command: matched[7]
    }
}

exports.start = function(crontab, opts){
    var rl = readline.createInterface({
        input: fs.createReadStream(crontab)
    });

    rl.on("line", function(line){
        var parsed = parseCrontab(line);
        var job = new CronJob({
            cronTime: parsed.cronTime,
            onTick: function(){
                var proc = childProcess.spawn(parsed.command, {
                    shell: true,
                    stdio: ["ignore", "pipe", "pipe"]
                });

                proc.stdout.on('data', function(data){
                    console.log(parsed.command + " | stdout: " + data.toString().trim());
                });
                proc.stderr.on('data', function(data){
                    console.log(parsed.command + " | stderr: " + data.toString().trim());
                });
                proc.on('close', function(code){
                    console.log(parsed.command + " | exited with code " +
                                code.toString());
                });
            },
            start: true
        });
        console.dir(parsed);
    });
};
<|endoftext|>


<commit_before>/**
 * sails-generate-auth
 *
 * Usage:
 * `sails generate auth`
 *
 * @type {Object}
 */
module.exports = {

  templatesDirectory: require('path').resolve(__dirname,'../templates'),

  before: require('./before'),

  targets: {
    './': {
      exec: function (scope, cb) {
        console.log('Running generator (sails-generate-auth) @ `'+scope.rootPath+'`...');
        cb();
      }
    },

    // Authentication controller
    './api/controllers/AuthController.js': { template: 'api/controllers/AuthController.js' },

    // User model
    './api/models/User.js': { template: 'api/models/User.js' },

    // Passport model
    './api/models/Passport.js': { template: 'api/models/Passport.js' },

    // Passport middleware
    './api/policies/passport.js': { template: 'api/policies/passport.js' },

    // Passport wrapper
    './api/services/passport.js': { template: 'api/services/passport.js' },

    // Authentication protocols
    './api/services/protocols': { folder: {} },
    './api/services/protocols/index.js': { template: 'api/services/protocols/index.js' },
    './api/services/protocols/local.js': { template: 'api/services/protocols/local.js' },
    './api/services/protocols/oauth.js': { template: 'api/services/protocols/oauth.js' },
    './api/services/protocols/oauth2.js': { template: 'api/services/protocols/oauth2.js' },
    './api/services/protocols/openid.js': { template: 'api/services/protocols/openid.js' },

    // Passport configuration
    './config/passport.js': { template: 'config/passport.js' },

    // Authentication views
    './views/auth/login.ejs': { copy: 'views/auth/login.ejs' },
    './views/auth/register.ejs': { copy: 'views/auth/register.ejs' }
  }
};
<commit_msg>Add bearer.js and bearerAuth.js to lib/index.js<commit_after>/**
 * sails-generate-auth
 *
 * Usage:
 * `sails generate auth`
 *
 * @type {Object}
 */
module.exports = {

  templatesDirectory: require('path').resolve(__dirname,'../templates'),

  before: require('./before'),

  targets: {
    './': {
      exec: function (scope, cb) {
        console.log('Running generator (sails-generate-auth) @ `'+scope.rootPath+'`...');
        cb();
      }
    },

    // Authentication controller
    './api/controllers/AuthController.js': { template: 'api/controllers/AuthController.js' },

    // User model
    './api/models/User.js': { template: 'api/models/User.js' },

    // Passport model
    './api/models/Passport.js': { template: 'api/models/Passport.js' },

    // Passport middleware
    './api/policies/passport.js': { template: 'api/policies/passport.js' },

    // Bearer Authentication Policy
    './api/policies/bearerAuth.js': { template: 'api/policies/bearerAuth.js' },

    // Passport wrapper
    './api/services/passport.js': { template: 'api/services/passport.js' },

    // Authentication protocols
    './api/services/protocols': { folder: {} },
    './api/services/protocols/index.js': { template: 'api/services/protocols/index.js' },
    './api/services/protocols/local.js': { template: 'api/services/protocols/local.js' },
    './api/services/protocols/oauth.js': { template: 'api/services/protocols/oauth.js' },
    './api/services/protocols/oauth2.js': { template: 'api/services/protocols/oauth2.js' },
    './api/services/protocols/openid.js': { template: 'api/services/protocols/openid.js' },
    './api/services/protocols/bearer.js': { template: 'api/services/protocols/bearer.js' },

    // Passport configuration
    './config/passport.js': { template: 'config/passport.js' },

    // Authentication views
    './views/auth/login.ejs': { copy: 'views/auth/login.ejs' },
    './views/auth/register.ejs': { copy: 'views/auth/register.ejs' }
  }
};
<|endoftext|>


<commit_before>'use strict';

const restify = require('restify');
const ws281x = require('rpi-ws281x-native');
const count = require('./count');
const theme = require('./theme');
const pkg = require('../package.json');

function init () {
  var server = restify.createServer();

  count.init();
  theme.init(ws281x);

  server.get('/theme', (req, res, next) => {
    res.send({
      theme: theme.getLastThemeName()
    });
  });

  server.put('/theme/:name', (req, res, next) => {
    theme.setTheme(req.params.name, count.getCount());
    res.status(200);
  });

  server.get('/count', (req, res, next) => {
    res.send({
      count: count.getCount()
    });
  });

  server.put('/count/:num', (req, res, next) => {
    count.setCount(req.params.num);
    res.status(200);
  });

  server.put('/stop', (req, res, next) => {
    res.status(200);
    theme.stop();
    //ws281x.reset();
  });

  server.get('/status', (req, res, next) => {
    res.send({
      theme: theme.getLastThemeName(),
      isRunning: true
    })
  });

  server.get('/version', (req, res, next) => {
    res.send({
      version: pkg.version
    });
  });

  server.listen(8080);
}

module.exports = {
  init: init
};
<commit_msg>add log<commit_after>'use strict';

const restify = require('restify');
const ws281x = require('rpi-ws281x-native');
const count = require('./count');
const theme = require('./theme');
const pkg = require('../package.json');

function init () {
  var server = restify.createServer();

  count.init();
  theme.init(ws281x);

  server.get('/theme', (req, res, next) => {
    console.log('get', '/theme');
    res.send({
      theme: theme.getLastThemeName()
    });
  });

  server.put('/theme/:name', (req, res, next) => {
    console.log('put', '/theme/:name', req.params.name);
    theme.setTheme(req.params.name, count.getCount());
    res.status(200);
  });

  server.get('/count', (req, res, next) => {
    console.log('get', '/count');
    res.send({
      count: count.getCount()
    });
  });

  server.put('/count/:num', (req, res, next) => {
    console.log('put', '/count/:num', req.params.num);
    count.setCount(req.params.num);
    res.status(200);
  });

  server.put('/stop', (req, res, next) => {
    console.log('put', '/stop');
    res.status(200);
    theme.stop();
    //ws281x.reset();
  });

  server.get('/status', (req, res, next) => {
    console.log('get', '/status');
    res.send({
      theme: theme.getLastThemeName(),
      isRunning: true
    })
  });

  server.get('/version', (req, res, next) => {
    console.log('get', '/version');
    res.send({
      version: pkg.version
    });
  });

  server.listen(8080);
}

module.exports = {
  init: init
};
<|endoftext|>


<commit_before>
var createRevisionStore = require('./revision-store')
var createBranchStore = require('./branch-store')
var types = require('./types')
var graphDiff = require('graph-difference')
var streams = require('simple-stream')
var _ = require('underscore')
var uuid = require('node-uuid')
var findCommonAncestor = require('ancestor')

module.exports = {
  createDB: createDB,
  createLocalSource: require('./local-source'),
  createLocalTarget: require('./local-target'),
  createSynchronizer: require('./synchronizer')
}

function createDB(opts) {
  var revisionStore = createRevisionStore(opts.revisionStore)
  var branchStore = createBranchStore(opts.branchStore)
  var head = null
  var name = opts.name || uuid.v4()

  return {
    name: name,
    head: readHead,
    setHead: setHead,
    remoteHead: readRemoteHead,
    setRemoteHead: setRemoteHead,
    put: put,
    get: get,
    refDifference: refDifference,
    createStream: createStream,
    writeStream: writeStream,
    ancestors: readRefAncestors,
    commonAncestor: commonAncestor
  }

  function readHead(cb) {
    return branchStore.readHead('local', cb)
  }

  function setHead(hash, cb) {
    branchStore.setHead('local', hash, function(err) {
      head = hash
      cb(null, {head: head})
    })
  }

  function readRemoteHead(name, cb) {
    branchStore.readHead(name, cb)
  }

  function setRemoteHead(name, hash, cb) {
    branchStore.setHead(name, hash, cb)
  }

  function put(data, ancestorRefs, cb) {
    if (!cb) {
      cb = ancestorRefs
      ancestorRefs = head ? [head] : []
    }
    var rev = types.createRevision({data: data, ancestors: ancestorRefs})
    revisionStore.put(rev, function(err, hash) {
      setHead(hash, cb)
    })
  }

  function get(ref, cb) {
    if (!cb) {
      cb = ref
      ref = head
    }
    revisionStore.read(ref, function(err, rev) {
      cb(null, rev.data)
    })
  }

  function readRefAncestors(ref, cb) {
    revisionStore.read(ref, function(err, revObj) {
      if (err) return cb(err)
      cb(null, revObj.ancestors)
    })
  }

  function refDifference(ref1, ref2, cb) {
    graphDiff(ref1, ref2, readRefAncestors, cb)
  }

  function createStream(refs) {
    return streams.mapAsync(streams.fromArray(refs), function(rev, cb) {
      revisionStore.read(rev, cb)
    })
  }

  function writeStream(revStream, cb) {
    revStream.read(function(err, rev) {
      if (rev === undefined) return cb()
      revisionStore.put(rev, function(err, hash) {
        writeStream(revStream, cb)
      })
    })
  }

  function commonAncestor(ref1, ref2, cb) {
    if (!cb) {
      cb = ref2
      ref2 = head
    }
    findCommonAncestor([ref1, ref2], readRefAncestors, cb)
  }
}
<commit_msg>improve var naming<commit_after>
var createRevisionStore = require('./revision-store')
var createBranchStore = require('./branch-store')
var types = require('./types')
var graphDiff = require('graph-difference')
var streams = require('simple-stream')
var _ = require('underscore')
var uuid = require('node-uuid')
var findCommonAncestor = require('ancestor')

module.exports = {
  createDB: createDB,
  createLocalSource: require('./local-source'),
  createLocalTarget: require('./local-target'),
  createSynchronizer: require('./synchronizer')
}

function createDB(opts) {
  var revisionStore = createRevisionStore(opts.revisionStore)
  var branchStore = createBranchStore(opts.branchStore)
  var head = null
  var name = opts.name || uuid.v4()

  return {
    name: name,
    head: readHead,
    setHead: setHead,
    remoteHead: readRemoteHead,
    setRemoteHead: setRemoteHead,
    put: put,
    get: get,
    refDifference: refDifference,
    createStream: createStream,
    writeStream: writeStream,
    ancestors: readRefAncestors,
    commonAncestor: commonAncestor
  }

  function readHead(cb) {
    return branchStore.readHead('local', cb)
  }

  function setHead(ref, cb) {
    branchStore.setHead('local', ref, function(err) {
      head = ref
      cb(null, {head: head})
    })
  }

  function readRemoteHead(name, cb) {
    branchStore.readHead(name, cb)
  }

  function setRemoteHead(name, ref, cb) {
    branchStore.setHead(name, ref, cb)
  }

  function put(data, ancestorRefs, cb) {
    if (!cb) {
      cb = ancestorRefs
      ancestorRefs = head ? [head] : []
    }
    var rev = types.createRevision({data: data, ancestors: ancestorRefs})
    revisionStore.put(rev, function(err, ref) {
      setHead(ref, cb)
    })
  }

  function get(ref, cb) {
    if (!cb) {
      cb = ref
      ref = head
    }
    revisionStore.read(ref, function(err, rev) {
      cb(null, rev.data)
    })
  }

  function readRefAncestors(ref, cb) {
    revisionStore.read(ref, function(err, revObj) {
      if (err) return cb(err)
      cb(null, revObj.ancestors)
    })
  }

  function refDifference(ref1, ref2, cb) {
    graphDiff(ref1, ref2, readRefAncestors, cb)
  }

  function createStream(refs) {
    return streams.mapAsync(streams.fromArray(refs), function(rev, cb) {
      revisionStore.read(rev, cb)
    })
  }

  function writeStream(revStream, cb) {
    revStream.read(function(err, rev) {
      if (rev === undefined) return cb()
      revisionStore.put(rev, function(err, ref) {
        writeStream(revStream, cb)
      })
    })
  }

  function commonAncestor(ref1, ref2, cb) {
    if (!cb) {
      cb = ref2
      ref2 = head
    }
    findCommonAncestor([ref1, ref2], readRefAncestors, cb)
  }
}
<|endoftext|>