<commit_before>/** section: Language
 * class Function
 *
 *  Extensions to the built-in `Function` object.
**/
Object.extend(Function.prototype, (function() {
  var slice = Array.prototype.slice;

  function update(array, args) {
    var arrayLength = array.length, length = args.length;
    while (length--) array[arrayLength + length] = args[length];
    return array;
  }

  function merge(array, args) {
    array = slice.call(array, 0);
    return update(array, args);
  }

  /**
   *  Function#argumentNames() -> Array
   *
   *  Reads the argument names as stated in the function definition and returns
   *  the values as an array of strings (or an empty array if the function is
   *  defined without parameters).
   *
   *  ### Examples
   *
   *      function fn(foo, bar) {
   *        return foo + bar;
   *      }
   *      fn.argumentNames();
   *      //-> ['foo', 'bar']
   *
   *      Prototype.emptyFunction.argumentNames();
   *      //-> []
  **/
  function argumentNames() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
      .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
      .replace(/\s+/g, '').split(',');
    return names.length == 1 && !names[0] ? [] : names;
  }

  /** related to: Function#bindAsEventListener
   *  Function#bind(context[, args...]) -> Function
   *  - context (Object): The object to bind to.
   *  - args (?): Optional additional arguments to curry for the function.
   *
   *  Binds this function to the given `context` by wrapping it in another
   *  function and returning the wrapper. Whenever the resulting "bound"
   *  function is called, it will call the original ensuring that `this` is set
   *  to `context`. Also optionally curries arguments for the function.
   *
   *  ### Examples
   *
   *  A typical use of `Function#bind` is to ensure that a callback (event
   *  handler, etc.) that is an object method gets called with the correct
   *  object as its context (`this` value):
   *
   *      var AlertOnClick = Class.create({
   *        initialize: function(msg) {
   *          this.msg = msg;
   *        },
   *        handleClick: function(event) {
   *          event.stop();
   *          alert(this.msg);
   *        }
   *      });
   *      var myalert = new AlertOnClick("Clicked!");
   *      $('foo').observe('click', myalert.handleClick); // <= WRONG
   *      // -> If 'foo' is clicked, the alert will be blank; "this" is wrong
   *      $('bar').observe('click', myalert.handleClick.bind(myalert)); // <= RIGHT
   *      // -> If 'bar' is clicked, the alert will be "Clicked!"
   *
   *  `bind` can also *curry* (burn in) arguments for the function if you
   *  provide them after the `context` argument:
   *
   *      var Averager = Class.create({
   *        initialize: function() {
   *          this.count = 0;
   *          this.total = 0;
   *        },
   *        add: function(addend) {
   *          ++this.count;
   *          this.total += addend;
   *        },
   *        getAverage: function() {
   *          return this.count == 0 ? NaN : this.total / this.count;
   *        }
   *      });
   *      var a = new Averager();
   *      var b = new Averager();
   *      var aAdd5 = a.add.bind(a, 5);   // Bind to a, curry 5
   *      var aAdd10 = a.add.bind(a, 10); // Bind to a, curry 10
   *      var bAdd20 = b.add.bind(b, 20); // Bind to b, curry 20
   *      aAdd5();
   *      aAdd10();
   *      bAdd20();
   *      bAdd20();
   *      alert(a.getAverage());
   *      // -> Alerts "7.5" (average of [5, 10])
   *      alert(b.getAverage());
   *      // -> Alerts "20" (average of [20, 20])
   *
   *  (To curry without binding, see [[Function#curry]].)
  **/
  function bind(context) {
    if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
    var __method = this, args = slice.call(arguments, 1);
    return function() {
      var a = merge(args, arguments);
      return __method.apply(context, a);
    }
  }

  /** related to: Function#bind
   *  Function#bindAsEventListener(context[, args...]) -> Function
   *  - context (Object): The object to bind to.
   *  - args (?): Optional arguments to curry after the event argument.
   *
   *  An event-specific variant of [[Function#bind]] which ensures the function
   *  will recieve the current event object as the first argument when
   *  executing.
   *
   *  It is not necessary to use `bindAsEventListener` for all bound event
   *  handlers; [[Function#bind]] works well for the vast majority of cases.
   *  `bindAsEventListener` is only needed when:
   *
   *  - Using old-style DOM0 handlers rather than handlers hooked up via
   *    [[Event.observe]], because `bindAsEventListener` gets the event object
   *    from the right place (even on MSIE). (If you're using `Event.observe`,
   *    that's already handled.)
   *  - You want to bind an event handler and curry additional arguments but
   *    have those arguments appear after, rather than before, the event object.
   *    This mostly happens if the number of arguments will vary, and so you
   *    want to know the event object is the first argument.
   *
   *  ### Example
   *
   *      var ContentUpdater = Class.create({
   *        initialize: function(initialData) {
   *          this.data = Object.extend({}, initialData);
   *        },
   *        // On an event, update the content in the elements whose
   *        // IDs are passed as arguments from our data
   *        updateTheseHandler: function(event) {
   *          var argIndex, id, element;
   *          event.stop();
   *          for (argIndex = 1; argIndex < arguments.length; ++argIndex) {
   *            id = arguments[argIndex];
   *            element = $(id);
   *            if (element) {
   *              element.update(String(this.data[id]).escapeHTML());
   *            }
   *          }
   *        }
   *      });
   *      var cu = new ContentUpdater({
   *        dispName: 'Joe Bloggs',
   *        dispTitle: 'Manager <provisional>',
   *        dispAge: 47
   *      });
   *      // Using bindAsEventListener because of the variable arg lists:
   *      $('btnUpdateName').observe('click',
   *        cu.updateTheseHandler.bindAsEventListener(cu, 'dispName')
   *      );
   *      $('btnUpdateAll').observe('click',
   *        cu.updateTheseHandler.bindAsEventListener(cu, 'dispName', 'dispTitle', 'dispAge')
   *      );
  **/
  function bindAsEventListener(context) {
    var __method = this, args = slice.call(arguments, 1);
    return function(event) {
      var a = update([event || window.event], args);
      return __method.apply(context, a);
    }
  }

  /**
   *  Function#curry(args...) -> Function
   *  - args (?): The arguments to curry.
   *
   *  *Curries* (burns in) arguments to a function, returning a new function
   *  that when called with call the original passing in the curried arguments
   *  (along with any new ones):
   *
   *      function showArguments() {
   *        alert($A(arguments).join(', '));
   *      }
   *      showArguments(1, 2,, 3);
   *      // -> alerts "1, 2, 3"
   *
   *      var f = showArguments.curry(1, 2, 3);
   *      f('a', 'b');
   *      // -> alerts "1, 2, 3, a, b"
   *
   *  `Function#curry` works just like [[Function#bind]] without the initial
   *  context argument. Use `bind` if you need to curry arguments _and_ set
   *  context at the same time.
   *
   *  The name "curry" comes from [mathematics](http://en.wikipedia.org/wiki/Currying).
  **/
  function curry() {
    if (!arguments.length) return this;
    var __method = this, args = slice.call(arguments, 0);
    return function() {
      var a = merge(args, arguments);
      return __method.apply(this, a);
    }
  }

  /**
   *  Function#delay(seconds[, args...]) -> Number
   *  - seconds (Number): How long to wait before calling the function.
   *
   *  Schedules the function to run after the specified amount of time, passing
   *  any arguments given.
   *
   *  Behaves much like `window.setTimeout`. Returns an integer ID that can be
   *  used to clear the timeout with `window.clearTimeout` before it runs.
   *
   *  To schedule a function to run as soon as the interpreter is idle, use
   *  [[Function#defer]].
  **/
  function delay(timeout) {
    var __method = this, args = slice.call(arguments, 1);
    timeout = timeout * 1000
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  }

  /**
   *  Function#defer(args...) -> Number
   *  - args (?): Optional arguments to pass into the function.
   *
   *  Schedules the function to run as soon as the interpreter is idle.
   *
   *  A "deferred" function will not run immediately; rather, it will run as soon
   *  as the interpreter's call stack is empty.
   *
   *  Behaves much like `window.setTimeout` with a delay set to `0`. Returns an
   *  ID that can be used to clear the timeout with `window.clearTimeout` before
   *  it runs.
   *
   *  ### Example
   *
   *      function showMsg(msg) {
   *        alert(msg);
   *      }
   *
   *      showMsg("One");
   *      showMsg.defer("Two");
   *      showMsg("Three");
   *      // Alerts "One", then "Three", then (after a brief pause) "Two"
   *      // Note that "Three" happens before "Two"
  **/
  function defer() {
    var args = update([0.01], arguments);
    return this.delay.apply(this, args);
  }

  /**
   *  Function#wrap(wrapperFunction) -> Function
   *  - wrapperFunction (Function): The function to act as a wrapper.
   *
   *  Returns a function "wrapped" around the original function.
   *
   *  `Function#wrap` distills the essence of aspect-oriented programming into
   *  a single method, letting you easily build on existing functions by
   *  specifying before and after behavior, transforming the return value, or
   *  even preventing the original function from being called.
  **/
  function wrap(wrapper) {
    var __method = this;
    return function() {
      var a = update([__method.bind(this)], arguments);
      return wrapper.apply(this, a);
    }
  }

  /**
   *  Function#methodize() -> Function
   *  Wraps the function inside another function that, at call time, pushes
   *  `this` to the original function as the first argument.
   *
   *  Used to define both a generic method and an instance method.
  **/
  function methodize() {
    if (this._methodized) return this._methodized;
    var __method = this;
    return this._methodized = function() {
      var a = update([this], arguments);
      return __method.apply(null, a);
    };
  }

  return {
    argumentNames:       argumentNames,
    bind:                bind,
    bindAsEventListener: bindAsEventListener,
    curry:               curry,
    delay:               delay,
    defer:               defer,
    wrap:                wrap,
    methodize:           methodize
  }
})());

<commit_msg>doc: Fleshed out docs on Function#delay.<commit_after>/** section: Language
 * class Function
 *
 *  Extensions to the built-in `Function` object.
**/
Object.extend(Function.prototype, (function() {
  var slice = Array.prototype.slice;

  function update(array, args) {
    var arrayLength = array.length, length = args.length;
    while (length--) array[arrayLength + length] = args[length];
    return array;
  }

  function merge(array, args) {
    array = slice.call(array, 0);
    return update(array, args);
  }

  /**
   *  Function#argumentNames() -> Array
   *
   *  Reads the argument names as stated in the function definition and returns
   *  the values as an array of strings (or an empty array if the function is
   *  defined without parameters).
   *
   *  ### Examples
   *
   *      function fn(foo, bar) {
   *        return foo + bar;
   *      }
   *      fn.argumentNames();
   *      //-> ['foo', 'bar']
   *
   *      Prototype.emptyFunction.argumentNames();
   *      //-> []
  **/
  function argumentNames() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
      .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
      .replace(/\s+/g, '').split(',');
    return names.length == 1 && !names[0] ? [] : names;
  }

  /** related to: Function#bindAsEventListener
   *  Function#bind(context[, args...]) -> Function
   *  - context (Object): The object to bind to.
   *  - args (?): Optional additional arguments to curry for the function.
   *
   *  Binds this function to the given `context` by wrapping it in another
   *  function and returning the wrapper. Whenever the resulting "bound"
   *  function is called, it will call the original ensuring that `this` is set
   *  to `context`. Also optionally curries arguments for the function.
   *
   *  ### Examples
   *
   *  A typical use of `Function#bind` is to ensure that a callback (event
   *  handler, etc.) that is an object method gets called with the correct
   *  object as its context (`this` value):
   *
   *      var AlertOnClick = Class.create({
   *        initialize: function(msg) {
   *          this.msg = msg;
   *        },
   *        handleClick: function(event) {
   *          event.stop();
   *          alert(this.msg);
   *        }
   *      });
   *      var myalert = new AlertOnClick("Clicked!");
   *      $('foo').observe('click', myalert.handleClick); // <= WRONG
   *      // -> If 'foo' is clicked, the alert will be blank; "this" is wrong
   *      $('bar').observe('click', myalert.handleClick.bind(myalert)); // <= RIGHT
   *      // -> If 'bar' is clicked, the alert will be "Clicked!"
   *
   *  `bind` can also *curry* (burn in) arguments for the function if you
   *  provide them after the `context` argument:
   *
   *      var Averager = Class.create({
   *        initialize: function() {
   *          this.count = 0;
   *          this.total = 0;
   *        },
   *        add: function(addend) {
   *          ++this.count;
   *          this.total += addend;
   *        },
   *        getAverage: function() {
   *          return this.count == 0 ? NaN : this.total / this.count;
   *        }
   *      });
   *      var a = new Averager();
   *      var b = new Averager();
   *      var aAdd5 = a.add.bind(a, 5);   // Bind to a, curry 5
   *      var aAdd10 = a.add.bind(a, 10); // Bind to a, curry 10
   *      var bAdd20 = b.add.bind(b, 20); // Bind to b, curry 20
   *      aAdd5();
   *      aAdd10();
   *      bAdd20();
   *      bAdd20();
   *      alert(a.getAverage());
   *      // -> Alerts "7.5" (average of [5, 10])
   *      alert(b.getAverage());
   *      // -> Alerts "20" (average of [20, 20])
   *
   *  (To curry without binding, see [[Function#curry]].)
  **/
  function bind(context) {
    if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
    var __method = this, args = slice.call(arguments, 1);
    return function() {
      var a = merge(args, arguments);
      return __method.apply(context, a);
    }
  }

  /** related to: Function#bind
   *  Function#bindAsEventListener(context[, args...]) -> Function
   *  - context (Object): The object to bind to.
   *  - args (?): Optional arguments to curry after the event argument.
   *
   *  An event-specific variant of [[Function#bind]] which ensures the function
   *  will recieve the current event object as the first argument when
   *  executing.
   *
   *  It is not necessary to use `bindAsEventListener` for all bound event
   *  handlers; [[Function#bind]] works well for the vast majority of cases.
   *  `bindAsEventListener` is only needed when:
   *
   *  - Using old-style DOM0 handlers rather than handlers hooked up via
   *    [[Event.observe]], because `bindAsEventListener` gets the event object
   *    from the right place (even on MSIE). (If you're using `Event.observe`,
   *    that's already handled.)
   *  - You want to bind an event handler and curry additional arguments but
   *    have those arguments appear after, rather than before, the event object.
   *    This mostly happens if the number of arguments will vary, and so you
   *    want to know the event object is the first argument.
   *
   *  ### Example
   *
   *      var ContentUpdater = Class.create({
   *        initialize: function(initialData) {
   *          this.data = Object.extend({}, initialData);
   *        },
   *        // On an event, update the content in the elements whose
   *        // IDs are passed as arguments from our data
   *        updateTheseHandler: function(event) {
   *          var argIndex, id, element;
   *          event.stop();
   *          for (argIndex = 1; argIndex < arguments.length; ++argIndex) {
   *            id = arguments[argIndex];
   *            element = $(id);
   *            if (element) {
   *              element.update(String(this.data[id]).escapeHTML());
   *            }
   *          }
   *        }
   *      });
   *      var cu = new ContentUpdater({
   *        dispName: 'Joe Bloggs',
   *        dispTitle: 'Manager <provisional>',
   *        dispAge: 47
   *      });
   *      // Using bindAsEventListener because of the variable arg lists:
   *      $('btnUpdateName').observe('click',
   *        cu.updateTheseHandler.bindAsEventListener(cu, 'dispName')
   *      );
   *      $('btnUpdateAll').observe('click',
   *        cu.updateTheseHandler.bindAsEventListener(cu, 'dispName', 'dispTitle', 'dispAge')
   *      );
  **/
  function bindAsEventListener(context) {
    var __method = this, args = slice.call(arguments, 1);
    return function(event) {
      var a = update([event || window.event], args);
      return __method.apply(context, a);
    }
  }

  /**
   *  Function#curry(args...) -> Function
   *  - args (?): The arguments to curry.
   *
   *  *Curries* (burns in) arguments to a function, returning a new function
   *  that when called with call the original passing in the curried arguments
   *  (along with any new ones):
   *
   *      function showArguments() {
   *        alert($A(arguments).join(', '));
   *      }
   *      showArguments(1, 2,, 3);
   *      // -> alerts "1, 2, 3"
   *
   *      var f = showArguments.curry(1, 2, 3);
   *      f('a', 'b');
   *      // -> alerts "1, 2, 3, a, b"
   *
   *  `Function#curry` works just like [[Function#bind]] without the initial
   *  context argument. Use `bind` if you need to curry arguments _and_ set
   *  context at the same time.
   *
   *  The name "curry" comes from [mathematics](http://en.wikipedia.org/wiki/Currying).
  **/
  function curry() {
    if (!arguments.length) return this;
    var __method = this, args = slice.call(arguments, 0);
    return function() {
      var a = merge(args, arguments);
      return __method.apply(this, a);
    }
  }

  /**
   *  Function#delay(timeout[, args...]) -> Number
   *  - timeout (Number): The time, in seconds, to wait before calling the
   *    function.
   *  - args (?): Optional arguments to pass to the function when calling it.
   *
   *  Schedules the function to run after the specified amount of time, passing
   *  any arguments given.
   *
   *  Behaves much like `window.setTimeout`, but the timeout is in seconds
   *  rather than milliseconds. Returns an integer ID that can be used to
   *  clear the timeout with `window.clearTimeout` before it runs.
   *
   *  To schedule a function to run as soon as the interpreter is idle, use
   *  [[Function#defer]].
   *
   *  ### Example
   *
   *      function showMsg(msg) {
   *        alert(msg);
   *      }
   *      showMsg.delay(0.1, "Hi there!");
   *      // -> Waits a 10th of a second, then alerts "Hi there!"
  **/
  function delay(timeout) {
    var __method = this, args = slice.call(arguments, 1);
    timeout = timeout * 1000
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  }

  /**
   *  Function#defer(args...) -> Number
   *  - args (?): Optional arguments to pass into the function.
   *
   *  Schedules the function to run as soon as the interpreter is idle.
   *
   *  A "deferred" function will not run immediately; rather, it will run as soon
   *  as the interpreter's call stack is empty.
   *
   *  Behaves much like `window.setTimeout` with a delay set to `0`. Returns an
   *  ID that can be used to clear the timeout with `window.clearTimeout` before
   *  it runs.
   *
   *  ### Example
   *
   *      function showMsg(msg) {
   *        alert(msg);
   *      }
   *
   *      showMsg("One");
   *      showMsg.defer("Two");
   *      showMsg("Three");
   *      // Alerts "One", then "Three", then (after a brief pause) "Two"
   *      // Note that "Three" happens before "Two"
  **/
  function defer() {
    var args = update([0.01], arguments);
    return this.delay.apply(this, args);
  }

  /**
   *  Function#wrap(wrapperFunction) -> Function
   *  - wrapperFunction (Function): The function to act as a wrapper.
   *
   *  Returns a function "wrapped" around the original function.
   *
   *  `Function#wrap` distills the essence of aspect-oriented programming into
   *  a single method, letting you easily build on existing functions by
   *  specifying before and after behavior, transforming the return value, or
   *  even preventing the original function from being called.
  **/
  function wrap(wrapper) {
    var __method = this;
    return function() {
      var a = update([__method.bind(this)], arguments);
      return wrapper.apply(this, a);
    }
  }

  /**
   *  Function#methodize() -> Function
   *  Wraps the function inside another function that, at call time, pushes
   *  `this` to the original function as the first argument.
   *
   *  Used to define both a generic method and an instance method.
  **/
  function methodize() {
    if (this._methodized) return this._methodized;
    var __method = this;
    return this._methodized = function() {
      var a = update([this], arguments);
      return __method.apply(null, a);
    };
  }

  return {
    argumentNames:       argumentNames,
    bind:                bind,
    bindAsEventListener: bindAsEventListener,
    curry:               curry,
    delay:               delay,
    defer:               defer,
    wrap:                wrap,
    methodize:           methodize
  }
})());

<|endoftext|>


<commit_before>var redis = require('redis');
var async = require('async');

var stats = require('./stats.js');

module.exports = function(logger, portalConfig, poolConfigs){

    var _this = this;

    var portalStats = this.stats = new stats(logger, portalConfig, poolConfigs);

    this.liveStatConnections = {};

    this.handleApiRequest = function(req, res, next){

        switch(req.params.method){
            case 'stats':
                res.header('Content-Type', 'application/json');
                res.end(portalStats.statsString);
                return;
            case 'pool_stats':
                res.header('Content-Type', 'application/json');
                res.end(JSON.stringify(portalStats.statPoolHistory));
                return;
            case 'blocks':
            case 'getblocksstats':
                portalStats.getBlocks(function(data){
                    res.header('Content-Type', 'application/json');
                    res.end(JSON.stringify(data));
                });
                break;
            case 'payments':
                var poolBlocks = [];
                for(var pool in portalStats.stats.pools) {
                    poolBlocks.push({name: pool, pending: portalStats.stats.pools[pool].pending, payments: portalStats.stats.pools[pool].payments});
                }
                res.header('Content-Type', 'application/json');
                res.end(JSON.stringify(poolBlocks));
                return;
			case 'worker_stats':
				res.header('Content-Type', 'application/json');
				if (req.url.indexOf("?")>0) {
				var url_parms = req.url.split("?");
				if (url_parms.length > 0) {
					var history = {};
					var workers = {};
					var address = url_parms[1] || null;
					//res.end(portalStats.getWorkerStats(address));
					if (address != null && address.length > 0) {
						// make sure it is just the miners address
						address = address.split(".")[0];
						// get miners balance along with worker balances
						portalStats.getBalanceByAddress(address, function(balances) {
							// get current round share total
							portalStats.getTotalSharesByAddress(address, function(shares) {
								var totalHash = parseFloat(0.0);
								var totalShares = shares;
								var networkSols = 0;
								for (var h in portalStats.statHistory) {
									for(var pool in portalStats.statHistory[h].pools) {
										for(var w in portalStats.statHistory[h].pools[pool].workers){
											if (w.startsWith(address)) {
												if (history[w] == null) {
													history[w] = [];
												}
												if (portalStats.statHistory[h].pools[pool].workers[w].hashrate) {
													history[w].push({time: portalStats.statHistory[h].time, hashrate:portalStats.statHistory[h].pools[pool].workers[w].hashrate});
												}
											}
										}
										// order check...
										//console.log(portalStats.statHistory[h].time);
									}
								}
								for(var pool in portalStats.stats.pools) {
								  for(var w in portalStats.stats.pools[pool].workers){
									  if (w.startsWith(address)) {
										workers[w] = portalStats.stats.pools[pool].workers[w];
										for (var b in balances.balances) {
											if (w == balances.balances[b].worker) {
                                                workers[w].paid = balances.balances[b].paid;
                                                workers[w].balance = balances.balances[b].balance;
											}
										}
										workers[w].balance = (workers[w].balance || 0);
										workers[w].paid = (workers[w].paid || 0);
										totalHash += portalStats.stats.pools[pool].workers[w].hashrate;
										networkSols = portalStats.stats.pools[pool].poolStats.networkSols;
									  }
								  }
								}
								res.end(JSON.stringify({miner: address, totalHash: totalHash, totalShares: totalShares, networkSols: networkSols, immature: balances.totalImmature, balance: balances.totalHeld, paid: balances.totalPaid, workers: workers, history: history}));
							});
						});
					} else {
						res.end(JSON.stringify({result: "error"}));
					}
				} else {
					res.end(JSON.stringify({result: "error"}));
				}
				} else {
					res.end(JSON.stringify({result: "error"}));
				}
                return;
            case 'live_stats':
                res.writeHead(200, {
                    'Content-Type': 'text/event-stream',
                    'Cache-Control': 'no-cache',
                    'Connection': 'keep-alive'
                });
                res.write('\n');
                var uid = Math.random().toString();
			req.on("close", function() {
                _this.liveStatConnections[uid] = res;
			res.flush();
                req.on("close", function() {
                    delete _this.liveStatConnections[uid];
                });
                return;
            default:
                next();
        }
    };

    this.handleAdminApiRequest = function(req, res, next){
        switch(req.params.method){
            case 'pools': {
                res.end(JSON.stringify({result: poolConfigs}));
                return;
            }
            default:
                next();
        }
    };

};
<commit_msg>Update api.js<commit_after>var redis = require('redis');
var async = require('async');

var stats = require('./stats.js');

module.exports = function(logger, portalConfig, poolConfigs){

    var _this = this;

    var portalStats = this.stats = new stats(logger, portalConfig, poolConfigs);

    this.liveStatConnections = {};

    this.handleApiRequest = function(req, res, next){

        switch(req.params.method){
            case 'stats':
                res.header('Content-Type', 'application/json');
                res.end(portalStats.statsString);
                return;
            case 'pool_stats':
                res.header('Content-Type', 'application/json');
                res.end(JSON.stringify(portalStats.statPoolHistory));
                return;
            case 'blocks':
            case 'getblocksstats':
                portalStats.getBlocks(function(data){
                    res.header('Content-Type', 'application/json');
                    res.end(JSON.stringify(data));
                });
                break;
            case 'payments':
                var poolBlocks = [];
                for(var pool in portalStats.stats.pools) {
                    poolBlocks.push({name: pool, pending: portalStats.stats.pools[pool].pending, payments: portalStats.stats.pools[pool].payments});
                }
                res.header('Content-Type', 'application/json');
                res.end(JSON.stringify(poolBlocks));
                return;
			case 'worker_stats':
				res.header('Content-Type', 'application/json');
				if (req.url.indexOf("?")>0) {
				var url_parms = req.url.split("?");
				if (url_parms.length > 0) {
					var history = {};
					var workers = {};
					var address = url_parms[1] || null;
					//res.end(portalStats.getWorkerStats(address));
					if (address != null && address.length > 0) {
						// make sure it is just the miners address
						address = address.split(".")[0];
						// get miners balance along with worker balances
						portalStats.getBalanceByAddress(address, function(balances) {
							// get current round share total
							portalStats.getTotalSharesByAddress(address, function(shares) {
								var totalHash = parseFloat(0.0);
								var totalShares = shares;
								var networkSols = 0;
								for (var h in portalStats.statHistory) {
									for(var pool in portalStats.statHistory[h].pools) {
										for(var w in portalStats.statHistory[h].pools[pool].workers){
											if (w.startsWith(address)) {
												if (history[w] == null) {
													history[w] = [];
												}
												if (portalStats.statHistory[h].pools[pool].workers[w].hashrate) {
													history[w].push({time: portalStats.statHistory[h].time, hashrate:portalStats.statHistory[h].pools[pool].workers[w].hashrate});
												}
											}
										}
										// order check...
										//console.log(portalStats.statHistory[h].time);
									}
								}
								for(var pool in portalStats.stats.pools) {
								  for(var w in portalStats.stats.pools[pool].workers){
									  if (w.startsWith(address)) {
										workers[w] = portalStats.stats.pools[pool].workers[w];
										for (var b in balances.balances) {
											if (w == balances.balances[b].worker) {
                                                workers[w].paid = balances.balances[b].paid;
                                                workers[w].balance = balances.balances[b].balance;
											}
										}
										workers[w].balance = (workers[w].balance || 0);
										workers[w].paid = (workers[w].paid || 0);
										totalHash += portalStats.stats.pools[pool].workers[w].hashrate;
										networkSols = portalStats.stats.pools[pool].poolStats.networkSols;
									  }
								  }
								}
								res.end(JSON.stringify({miner: address, totalHash: totalHash, totalShares: totalShares, networkSols: networkSols, immature: balances.totalImmature, balance: balances.totalHeld, paid: balances.totalPaid, workers: workers, history: history}));
							});
						});
					} else {
						res.end(JSON.stringify({result: "error"}));
					}
				} else {
					res.end(JSON.stringify({result: "error"}));
				}
				} else {
					res.end(JSON.stringify({result: "error"}));
				}
                return;
            case 'live_stats':
                res.writeHead(200, {
                    'Content-Type': 'text/event-stream',
                    'Cache-Control': 'no-cache',
                    'Connection': 'keep-alive'
                });
                res.write('\n');
                var uid = Math.random().toString();
                _this.liveStatConnections[uid] = res;
			res.flush();
                req.on("close", function() {
                    delete _this.liveStatConnections[uid];
                });
                return;
            default:
                next();
        }
    };

    this.handleAdminApiRequest = function(req, res, next){
        switch(req.params.method){
            case 'pools': {
                res.end(JSON.stringify({result: poolConfigs}));
                return;
            }
            default:
                next();
        }
    };

};
<|endoftext|>


<commit_before>function DBManager(server)
{
	this.registerPlugin(server);
};

DBManager.prototype.registerPlugin = function (server)
{
	server.register(
		{
			register: require('hapi-sequelize'),
			options : {
				database : 'music_election',
				user     : 'root',
				pass     : 'mysqlsifresi',
				dialect  : 'sqlite', //yada mysql
				models   : 'src/models/**/*.js',
				sequelize: {
					define : {underscoredAll: true},
					storage: 'app/data/database.sqlite'
				}
			}
		},
		err =>
		{
			if (err)
			{
				throw err;
			}

			this.registerMethods(server);
		}
	);
};

DBManager.prototype.registerMethods = function (server)
{
	var db = server.plugins['hapi-sequelize'].db;

	server.method('getDB', () => db);
	server.method(
		'getModel',
		(modelName) =>
		{
			if (modelName)
			{
				return db.sequelize.models[modelName];
			}
			else {
				return db.sequelize.models;
			}
		}
	);

	this.bootstrapDB(server);
};

DBManager.prototype.registerExtension = function (server)
{
	server.ext(
		'onPreHandler',
		(modelCollections =>
		{
			return (request, reply) =>
			{
				request.models = modelCollections;
				reply.continue();
			}
		})(server.plugins['hapi-sequelize'].db.sequelize.models)
	);
};

DBManager.prototype.bootstrapDB = function (server)
{

	var db    = server.methods.getDB();
	var music = server.methods.getModel('music');

	db.sequelize
		.sync({force: false})
		.then(() =>
			  {
				  console.log('models synced');

				  return music.count();
			  })
		.then(result =>
			  {
				  if (result > 0)
				  {
					  return true;
				  }

				  return music.bulkCreate(
					  [
						  {name: 'Tarkan - Kuzu Kuzu'},
						  {name: 'Mark Ronson feat. Bruno Mars - Uptown Funk!'},
						  {name: 'Ed Sheeran - Thinking Out Lout'},
						  {name: 'Wiz Khalifa feat. Charlie Puth - See You Again'},
						  {name: 'Maroon 5 - Sugar'},
						  {name: 'Ellie Goulding - Love Me Like You Do'},
						  {name: 'Walk The Moon - Shut Up And Dance'},
						  {name: 'The Weeknd - Earned It'},
						  {name: 'Hozier - Take Me To Church'},
						  {name: 'Rihanna Kanye West Paul McCartney - Fourfiveseconds'},
						  {name: 'Fetty Wap - Trap Queen'}
					  ]
				  );
			  })
		.catch(err=> { throw new Error(err); })
		.then(() => this.registerExtension(server));
};

module.exports = DBManager;
<commit_msg>Konfigurasyon değişikligi<commit_after>function DBManager(server)
{
	this.registerPlugin(server);
};

;
DBManager.prototype.registerPlugin = function (server)
{
	server.register(
		{
			register: require('hapi-sequelize'),
			options : {
				database : 'music_election',
				user     : process.env.MYSQL_USER,
				pass     : process.env.MYSQL_PASS,
				dialect  : 'mysql',
				models   : 'src/models/**/*.js',
				sequelize: {
					define : {underscoredAll: true},
					storage: 'app/data/database.sqlite'
				}
			}
		},
		err =>
		{
			if (err)
			{
				throw err;
			}

			this.registerMethods(server);
		}
	);
};

DBManager.prototype.registerMethods = function (server)
{
	var db = server.plugins['hapi-sequelize'].db;

	server.method('getDB', () => db);
	server.method(
		'getModel',
		(modelName) =>
		{
			if (modelName)
			{
				return db.sequelize.models[modelName];
			}
			else {
				return db.sequelize.models;
			}
		}
	);

	this.bootstrapDB(server);
};

DBManager.prototype.registerExtension = function (server)
{
	server.ext(
		'onPreHandler',
		(modelCollections =>
		{
			return (request, reply) =>
			{
				request.models = modelCollections;
				reply.continue();
			}
		})(server.plugins['hapi-sequelize'].db.sequelize.models)
	);
};

DBManager.prototype.bootstrapDB = function (server)
{

	var db    = server.methods.getDB();
	var music = server.methods.getModel('music');

	db.sequelize
		.sync({force: false})
		.then(() =>
			  {
				  console.log('models synced');

				  return music.count();
			  })
		.then(result =>
			  {
				  if (result > 0)
				  {
					  return true;
				  }

				  return music.bulkCreate(
					  [
						  {name: 'Tarkan - Kuzu Kuzu'},
						  {name: 'Mark Ronson feat. Bruno Mars - Uptown Funk!'},
						  {name: 'Ed Sheeran - Thinking Out Lout'},
						  {name: 'Wiz Khalifa feat. Charlie Puth - See You Again'},
						  {name: 'Maroon 5 - Sugar'},
						  {name: 'Ellie Goulding - Love Me Like You Do'},
						  {name: 'Walk The Moon - Shut Up And Dance'},
						  {name: 'The Weeknd - Earned It'},
						  {name: 'Hozier - Take Me To Church'},
						  {name: 'Rihanna Kanye West Paul McCartney - Fourfiveseconds'},
						  {name: 'Fetty Wap - Trap Queen'}
					  ]
				  );
			  })
		.catch(err=> { throw new Error(err); })
		.then(() => this.registerExtension(server));
};

module.exports = DBManager;
<|endoftext|>


<commit_before>import colors from 'colors/safe';

export default class Log {

  constructor(env) {
    this.env = env;
  }

  info(message) {
    console.info('[INFO]', message); // eslint-disable-line no-console
  }

  error(message) {
    console.error('[ERROR]', colors.red(message)); // eslint-disable-line no-console
  }

  warn(message) {
    console.log('[WARN]', colors.yellow(message)); // eslint-disable-line no-console
  }

  // Environnement de dev uniquement

  verbose(message) {
    if (this.env) return;
    console.log('[VERBOSE]', colors.grey(message)); // eslint-disable-line no-console
  }

  debug(message) {
    if (this.env) return;
    console.log('[DEBUG]', colors.grey(message)); // eslint-disable-line no-console
  }

}

// log.error({
//   message: `balbablabalba ${truc}`,
// });
<commit_msg>Ajouté la possibilité d'envoyer plusieurs lignes de texte<commit_after>import colors from 'colors/safe';

export default class Log {

  constructor(env) {
    this.env = env;
  }

  info(...messages) {
    messages.forEach((message) => {
      console.error('[INFO]', message); // eslint-disable-line no-console
    });
  }

  error(...messages) {
    messages.forEach((message) => {
      console.error('[ERROR]', colors.red(message)); // eslint-disable-line no-console
    });
  }

  warn(...messages) {
    messages.forEach((message) => {
      console.error('[WARNING]', colors.yellow(message)); // eslint-disable-line no-console
    });
  }

  // Environnement de dev uniquement

  verbose(...messages) {
    if (this.env) return;
    messages.forEach((message) => {
      console.error('[VERBOSE]', colors.grey(message)); // eslint-disable-line no-console
    });
  }

  debug(...messages) {
    if (this.env) return;
    messages.forEach((message) => {
      console.error('[DEBUG]', colors.grey(message)); // eslint-disable-line no-console
    });
  }

}
<|endoftext|>


<commit_before>let fs = require('../core/fs.js');
let async = require('async');
//var Plugins = require('../core/plugins.js');
var utils = require('../utils/utils.js');
//var Npm = require('../pipeline/npm.js');
//let currentWeb3Version = require('../../package.json').dependencies.web3.replace("^","");
const webpack = require("webpack");

require("babel-preset-react");
require("babel-preset-es2015");
require("babel-preset-es2016");
require("babel-preset-es2017");

class Pipeline {

  constructor(options) {
    this.buildDir = options.buildDir;
    this.contractsFiles = options.contractsFiles;
    this.assetFiles = options.assetFiles;
    this.events = options.events;
    this.logger = options.logger;
    this.plugins = options.plugins;
  }

  build(abi, contractsJSON, path, callback) {
    let self = this;

    this.buildContracts(contractsJSON);

    self.buildWeb3JS(function() {

    // limit:1 due to issues when downloading required files such as web3.js
    async.eachOfLimit(self.assetFiles, 1, function (files, targetFile, cb) {
      // limit:1 due to issues when downloading required files such as web3.js
      async.mapLimit(files, 1,
        function(file, fileCb) {
          self.logger.trace("reading " + file.filename);

          if (file.filename.indexOf('.js') >= 0) {
              let importsList = {};

              //importsList["Embark/EmbarkJS"] = fs.embarkPath("js/embark.js");

              importsList["Embark/EmbarkJS"] = utils.joinPath(fs.dappPath(), ".embark", 'embark.js');
              importsList["Embark/web3"] = utils.joinPath(fs.dappPath(), ".embark", 'web3_instance.js');
              importsList["Embark/contracts/SimpleStorage"] = utils.joinPath(fs.dappPath(), ".embark", 'SimpleStorage.js');

              self.plugins.getPluginsProperty('imports', 'imports').forEach(function (importObject) {
                let [importName, importLocation] = importObject;
                importsList[importName] = importLocation;
              });

              for (let contractName in contractsJSON) {
                let contractCode = self.buildContractJS(contractName);
                let filePath = utils.joinPath(fs.dappPath(), ".embark", contractName + '.js');
                fs.writeFileSync(filePath, contractCode);
                importsList["Embark/contracts/" + contractName] = filePath;
              }

              let realCwd;

              async.waterfall([

                function findImports(next) {
                  self.webpackRun(file.filename, {}, false, importsList, false, next);
                },

                function changeCwd(next) {
                  realCwd = process.env.PWD;
                  process.chdir(fs.embarkPath(''));
                  next();
                },

                //function findImportsPhase2(next) {
                //  console.log("====> findImports_2");
                //  self.webpackRun(file.filename, {
                //    externals: function(context, request, callback) {
                //      if (request === utils.joinPath(fs.dappPath(), file.filename)) {
                //        callback();
                //      } else {
                //        //if (request.indexOf('Embark/contracts/') === 0) {
                //        //  let contractName = request.split('/')[2];
                //        //  let contractCode = self.buildContractJS(contractName);
                //        //  let filePath = utils.joinPath(fs.dappPath(), ".embark", contractName + '.js');
                //        //  fs.writeFileSync(filePath, contractCode);
                //        //  importsList[request] = filePath;
                //        //}
                //        callback(null, "amd " + Math.random());
                //      }
                //    }
                //  }, true, importsList, next);
                //},

                function runWebpack(next) {
                  self.webpackRun(file.filename, {}, true, importsList, true, next);
                },

                function changeCwdBack(next) {
                  process.chdir(realCwd);
                  next();
                }

              ], function(err, _result) {
                if (err) {
                  process.chdir(realCwd);
                  self.logger.error(err);
                  return fileCb(err);
                }
                if (!fs.existsSync('./.embark/' + file.filename)) {
                  self.logger.error("couldn't find file: " + file.filename);
                  return fileCb("couldn't find file: " + file.filename);
                }
                let fileContent = fs.readFileSync('./.embark/' + file.filename).toString();

                let pipelinePlugins = self.plugins.getPluginsFor('pipeline');

                if (pipelinePlugins.length > 0) {
                  async.eachSeries(pipelinePlugins, function(plugin, pluginCB) {
                    if (file.options && file.options.skipPipeline) {
                      return pluginCB();
                    }

                    fileContent = plugin.runPipeline({targetFile: file.filename, source: fileContent});
                    file.modified = true;
                    pluginCB();
                  },
                    function (err) {
                      if (err) {
                        self.logger.error(err.message);
                      }
                      return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, basedir: file.basedir, modified: true});
                    });
                } else {
                  return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, basedir: file.basedir, modified: true});
                }
              });

          } else {

            let pipelinePlugins = self.plugins.getPluginsFor('pipeline');
            if (pipelinePlugins.length > 0) {
              file.content(function(fileContent) {
                async.eachSeries(pipelinePlugins, function(plugin, pluginCB) {
                  if (file.options && file.options.skipPipeline) {
                    return pluginCB();
                  }

                  fileContent = plugin.runPipeline({targetFile: file.filename, source: fileContent});
                  file.modified = true;
                  pluginCB();
                },
                function (err) {
                  if (err) {
                    self.logger.error(err.message);
                  }
                  return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, basedir: file.basedir, modified: true});
                });
              });
            } else {
              file.content(function(fileContent) {
                return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, basedir: file.basedir, modified: true});
              });
            }

          }

        },
        function (err, contentFiles) {
          if (err) {
            self.logger.warn('errors found while generating ' + targetFile);
          }
          let dir = targetFile.split('/').slice(0, -1).join('/');
          self.logger.trace("creating dir " + self.buildDir + dir);
          fs.mkdirpSync(self.buildDir + dir);

          // if it's a directory
          if (targetFile.slice(-1) === '/' || targetFile.indexOf('.') === -1) {
            let targetDir = targetFile;

            if (targetDir.slice(-1) !== '/') {
              targetDir = targetDir + '/';
            }

            contentFiles.map(function (file) {
              let filename = file.filename.replace(file.basedir + '/', '');
              self.logger.info("writing file " + (self.buildDir + targetDir + filename).bold.dim);

              fs.copySync(file.path, self.buildDir + targetDir + filename, {overwrite: true});
            });
          } else {
            let content = contentFiles.map(function (file) {
              if (file === undefined) {
                return "";
              }
              return file.content;
            }).join("\n");

            self.logger.info("writing file " + (self.buildDir + targetFile).bold.dim);
            fs.writeFileSync(self.buildDir + targetFile, content);
          }
          cb();
        }
      );
    },
    function (_err, _results) {
      callback();
    });
  });
  }

  webpackRun(filename, options, includeModules, importsList, detectErrors, callback) {
    let defaultOptions = {
      entry: utils.joinPath(fs.dappPath(), filename),
      output: {
        libraryTarget: 'umd',
        path: utils.joinPath(fs.dappPath(), '.embark'),
        filename: filename
      },
      resolve: {
        alias: importsList,
        modules: [
          fs.embarkPath('node_modules'),
          utils.joinPath(fs.dappPath(), 'node_modules')
        ]
      },
      externals: function(context, request, callback) {
        callback();
      }
    };

    let webpackOptions =  utils.recursiveMerge(defaultOptions, options);

    if (includeModules) {
      webpackOptions.module = {
        rules: [
          {
            test: /\.css$/,
            use: [{loader: "style-loader"}, {loader: "css-loader"}]
          },
          {
            test: /\.scss$/,
            use: [{loader: "style-loader"}, {loader: "css-loader"}]
          },
          {
            test: /\.(png|woff|woff2|eot|ttf|svg)$/,
            loader: 'url-loader?limit=100000'
          },
          {
            test: /\.js$/,
            loader: "babel-loader",
            exclude: /(node_modules|bower_components)/,
            options: {
              presets: ['babel-preset-es2016', 'babel-preset-es2017', 'babel-preset-react'].map(require.resolve),
              plugins: ["babel-plugin-webpack-aliases"].map(require.resolve),
              compact: false
            }
          }
        ]
      };
    }

    webpack(webpackOptions).run((_err, _stats) => {
      if (!detectErrors) {
        return callback();
      }

      if (_stats.hasErrors()) {
        return callback(_stats.toJson().errors.join("\n"));
      }
      callback();
    });
  }

  buildContracts(contractsJSON) {
    fs.mkdirpSync(utils.joinPath(fs.dappPath(), this.buildDir, 'contracts'));

    for (let className in contractsJSON) {
      let contract = contractsJSON[className];
      fs.writeJSONSync(utils.joinPath(fs.dappPath(), this.buildDir, 'contracts', className + ".json"), contract, {spaces: 2});
    }
  }

  buildContractJS(contractName) {
    let contractJSON = fs.readFileSync(utils.joinPath(fs.dappPath(), this.buildDir, 'contracts', contractName + '.json')).toString();

    let contractCode = "";
    contractCode += "import web3 from 'Embark/web3';\n";
    contractCode += "import EmbarkJS from 'Embark/EmbarkJS';\n";
    contractCode += "let " + contractName + "JSONConfig = " + contractJSON + ";\n";
    contractCode += "let " + contractName + " = new EmbarkJS.Contract(" + contractName + "JSONConfig);\n";

    contractCode += "\n__embarkContext.execWhenReady(function() {\n";
    contractCode += "\n" + contractName + ".setProvider(web3.currentProvider);\n";
    contractCode += "\n});\n";

    contractCode += "export default " + contractName + ";\n";

    return contractCode;
  }

  buildWeb3JS(cb) {
    const self = this;
    let code = "";

    async.waterfall([
      function getWeb3Location(next) {
        self.events.request("version:get:web3", function(web3Version) {
          if (web3Version === "1.0.0-beta") {
            return next(null, utils.joinPath(fs.embarkPath("js/web3-1.0.min.js")));
          } else {
            self.events.request("version:getPackageLocation", "web3", web3Version, function(err, location) {
              return next(null, utils.joinPath(process.env.PWD, location));
            });
          }
        });
      },
      function getImports(web3Location, next) {
        code += "\nimport Web3 from '" + web3Location + "';\n";

        code += "\n if (typeof web3 !== 'undefined') {";
        code += "\n } else {";
        code += "\n var web3 = new Web3();\n";
        code += "\n }";

        self.events.request('provider-code', function(providerCode)  {
          code += providerCode;
          code += "\nglobal.__embarkContext = __mainContext.__loadManagerInstance;\n";
          code += "\nwindow.web3 = web3;\n";
          code += "\nexport default web3;\n";
          next();
        });
      },
      function writeFile(next) {
        let filePath = utils.joinPath(fs.dappPath(), ".embark", 'web3_instance.js');
        fs.mkdirpSync(utils.joinPath(fs.dappPath(), ".embark"));
        fs.writeFileSync(filePath, code);
        next();
      }
    ], function(_err, _result) {
      cb();
    });
  }

}

module.exports = Pipeline;
<commit_msg>refactor: join duplicated code<commit_after>let fs = require('../core/fs.js');
let async = require('async');
//var Plugins = require('../core/plugins.js');
var utils = require('../utils/utils.js');
//var Npm = require('../pipeline/npm.js');
//let currentWeb3Version = require('../../package.json').dependencies.web3.replace("^","");
const webpack = require("webpack");

require("babel-preset-react");
require("babel-preset-es2015");
require("babel-preset-es2016");
require("babel-preset-es2017");

class Pipeline {

  constructor(options) {
    this.buildDir = options.buildDir;
    this.contractsFiles = options.contractsFiles;
    this.assetFiles = options.assetFiles;
    this.events = options.events;
    this.logger = options.logger;
    this.plugins = options.plugins;
  }

  build(abi, contractsJSON, path, callback) {
    let self = this;

    this.buildContracts(contractsJSON);

    self.buildWeb3JS(function() {

    // limit:1 due to issues when downloading required files such as web3.js
    async.eachOfLimit(self.assetFiles, 1, function (files, targetFile, cb) {
      // limit:1 due to issues when downloading required files such as web3.js
      async.mapLimit(files, 1,
        function(file, fileCb) {
          self.logger.trace("reading " + file.filename);

          if (file.filename.indexOf('.js') >= 0) {
              let importsList = {};

              //importsList["Embark/EmbarkJS"] = fs.embarkPath("js/embark.js");

              importsList["Embark/EmbarkJS"] = utils.joinPath(fs.dappPath(), ".embark", 'embark.js');
              importsList["Embark/web3"] = utils.joinPath(fs.dappPath(), ".embark", 'web3_instance.js');
              importsList["Embark/contracts/SimpleStorage"] = utils.joinPath(fs.dappPath(), ".embark", 'SimpleStorage.js');

              self.plugins.getPluginsProperty('imports', 'imports').forEach(function (importObject) {
                let [importName, importLocation] = importObject;
                importsList[importName] = importLocation;
              });

              for (let contractName in contractsJSON) {
                let contractCode = self.buildContractJS(contractName);
                let filePath = utils.joinPath(fs.dappPath(), ".embark", contractName + '.js');
                fs.writeFileSync(filePath, contractCode);
                importsList["Embark/contracts/" + contractName] = filePath;
              }

              let realCwd;

              async.waterfall([

                function findImports(next) {
                  self.webpackRun(file.filename, {}, false, importsList, false, next);
                },

                function changeCwd(next) {
                  realCwd = process.env.PWD;
                  process.chdir(fs.embarkPath(''));
                  next();
                },

                //function findImportsPhase2(next) {
                //  console.log("====> findImports_2");
                //  self.webpackRun(file.filename, {
                //    externals: function(context, request, callback) {
                //      if (request === utils.joinPath(fs.dappPath(), file.filename)) {
                //        callback();
                //      } else {
                //        //if (request.indexOf('Embark/contracts/') === 0) {
                //        //  let contractName = request.split('/')[2];
                //        //  let contractCode = self.buildContractJS(contractName);
                //        //  let filePath = utils.joinPath(fs.dappPath(), ".embark", contractName + '.js');
                //        //  fs.writeFileSync(filePath, contractCode);
                //        //  importsList[request] = filePath;
                //        //}
                //        callback(null, "amd " + Math.random());
                //      }
                //    }
                //  }, true, importsList, next);
                //},

                function runWebpack(next) {
                  self.webpackRun(file.filename, {}, true, importsList, true, next);
                },

                function changeCwdBack(next) {
                  process.chdir(realCwd);
                  next();
                }

              ], function(err, _result) {
                if (err) {
                  process.chdir(realCwd);
                  self.logger.error(err);
                  return fileCb(err);
                }
                if (!fs.existsSync('./.embark/' + file.filename)) {
                  self.logger.error("couldn't find file: " + file.filename);
                  return fileCb("couldn't find file: " + file.filename);
                }
                let fileContent = fs.readFileSync('./.embark/' + file.filename).toString();
                self.runPlugins(file, fileContent, fileCb);
              });
          } else {
            file.content(function(fileContent) {
              self.runPlugins(file, fileContent, fileCb);
            });
          }
        },
        function (err, contentFiles) {
          if (err) {
            self.logger.warn('errors found while generating ' + targetFile);
          }
          let dir = targetFile.split('/').slice(0, -1).join('/');
          self.logger.trace("creating dir " + self.buildDir + dir);
          fs.mkdirpSync(self.buildDir + dir);

          // if it's a directory
          if (targetFile.slice(-1) === '/' || targetFile.indexOf('.') === -1) {
            let targetDir = targetFile;

            if (targetDir.slice(-1) !== '/') {
              targetDir = targetDir + '/';
            }

            contentFiles.map(function (file) {
              let filename = file.filename.replace(file.basedir + '/', '');
              self.logger.info("writing file " + (self.buildDir + targetDir + filename).bold.dim);

              fs.copySync(file.path, self.buildDir + targetDir + filename, {overwrite: true});
            });
          } else {
            let content = contentFiles.map(function (file) {
              if (file === undefined) {
                return "";
              }
              return file.content;
            }).join("\n");

            self.logger.info("writing file " + (self.buildDir + targetFile).bold.dim);
            fs.writeFileSync(self.buildDir + targetFile, content);
          }
          cb();
        }
      );
    },
    function (_err, _results) {
      callback();
    });
  });
  }

  runPlugins(file, fileContent, fileCb) {
    const self = this;
    let pipelinePlugins = self.plugins.getPluginsFor('pipeline');
    if (pipelinePlugins.length <= 0) {
      return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, basedir: file.basedir, modified: true});
    }
    async.eachSeries(pipelinePlugins,
      function(plugin, pluginCB) {
        if (file.options && file.options.skipPipeline) {
          return pluginCB();
        }

        fileContent = plugin.runPipeline({targetFile: file.filename, source: fileContent});
        file.modified = true;
        pluginCB();
      },
      function (err) {
        if (err) {
          self.logger.error(err.message);
        }
        return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, basedir: file.basedir, modified: true});
      }
    );
  }

  webpackRun(filename, options, includeModules, importsList, detectErrors, callback) {
    let defaultOptions = {
      entry: utils.joinPath(fs.dappPath(), filename),
      output: {
        libraryTarget: 'umd',
        path: utils.joinPath(fs.dappPath(), '.embark'),
        filename: filename
      },
      resolve: {
        alias: importsList,
        modules: [
          fs.embarkPath('node_modules'),
          utils.joinPath(fs.dappPath(), 'node_modules')
        ]
      },
      externals: function(context, request, callback) {
        callback();
      }
    };

    let webpackOptions =  utils.recursiveMerge(defaultOptions, options);

    if (includeModules) {
      webpackOptions.module = {
        rules: [
          {
            test: /\.css$/,
            use: [{loader: "style-loader"}, {loader: "css-loader"}]
          },
          {
            test: /\.scss$/,
            use: [{loader: "style-loader"}, {loader: "css-loader"}]
          },
          {
            test: /\.(png|woff|woff2|eot|ttf|svg)$/,
            loader: 'url-loader?limit=100000'
          },
          {
            test: /\.js$/,
            loader: "babel-loader",
            exclude: /(node_modules|bower_components)/,
            options: {
              presets: ['babel-preset-es2016', 'babel-preset-es2017', 'babel-preset-react'].map(require.resolve),
              plugins: ["babel-plugin-webpack-aliases"].map(require.resolve),
              compact: false
            }
          }
        ]
      };
    }

    webpack(webpackOptions).run((_err, _stats) => {
      if (!detectErrors) {
        return callback();
      }

      if (_stats.hasErrors()) {
        return callback(_stats.toJson().errors.join("\n"));
      }
      callback();
    });
  }

  buildContracts(contractsJSON) {
    fs.mkdirpSync(utils.joinPath(fs.dappPath(), this.buildDir, 'contracts'));

    for (let className in contractsJSON) {
      let contract = contractsJSON[className];
      fs.writeJSONSync(utils.joinPath(fs.dappPath(), this.buildDir, 'contracts', className + ".json"), contract, {spaces: 2});
    }
  }

  buildContractJS(contractName) {
    let contractJSON = fs.readFileSync(utils.joinPath(fs.dappPath(), this.buildDir, 'contracts', contractName + '.json')).toString();

    let contractCode = "";
    contractCode += "import web3 from 'Embark/web3';\n";
    contractCode += "import EmbarkJS from 'Embark/EmbarkJS';\n";
    contractCode += "let " + contractName + "JSONConfig = " + contractJSON + ";\n";
    contractCode += "let " + contractName + " = new EmbarkJS.Contract(" + contractName + "JSONConfig);\n";

    contractCode += "\n__embarkContext.execWhenReady(function() {\n";
    contractCode += "\n" + contractName + ".setProvider(web3.currentProvider);\n";
    contractCode += "\n});\n";

    contractCode += "export default " + contractName + ";\n";

    return contractCode;
  }

  buildWeb3JS(cb) {
    const self = this;
    let code = "";

    async.waterfall([
      function getWeb3Location(next) {
        self.events.request("version:get:web3", function(web3Version) {
          if (web3Version === "1.0.0-beta") {
            return next(null, utils.joinPath(fs.embarkPath("js/web3-1.0.min.js")));
          } else {
            self.events.request("version:getPackageLocation", "web3", web3Version, function(err, location) {
              return next(null, utils.joinPath(process.env.PWD, location));
            });
          }
        });
      },
      function getImports(web3Location, next) {
        code += "\nimport Web3 from '" + web3Location + "';\n";

        code += "\n if (typeof web3 !== 'undefined') {";
        code += "\n } else {";
        code += "\n var web3 = new Web3();\n";
        code += "\n }";

        self.events.request('provider-code', function(providerCode)  {
          code += providerCode;
          code += "\nglobal.__embarkContext = __mainContext.__loadManagerInstance;\n";
          code += "\nwindow.web3 = web3;\n";
          code += "\nexport default web3;\n";
          next();
        });
      },
      function writeFile(next) {
        let filePath = utils.joinPath(fs.dappPath(), ".embark", 'web3_instance.js');
        fs.mkdirpSync(utils.joinPath(fs.dappPath(), ".embark"));
        fs.writeFileSync(filePath, code);
        next();
      }
    ], function(_err, _result) {
      cb();
    });
  }

}

module.exports = Pipeline;
<|endoftext|>


<commit_before>'use strict';

const flatten = function(arr, result = []) {
  for (const i in arr) {
    const value = arr[i];
    if (Array.isArray(value)) {
      flatten(value, result);
    } else {
      result.push(value);
    }
  }
  return result;
};

function jsHelper(...args) {
  let result = '\n';
  let items = args;

  if (!Array.isArray(args)) {
    items = [args];
  }

  items = flatten(items);

  items.forEach(item => {
    // Old syntax
    if (typeof item === 'string' || item instanceof String) {
      let path = item;
      if (!path.endsWith('.js')) {
        path += '.js';
      }
      result += `<script src="${this.url_for(path)}"></script>\n`;
    } else {
      // New syntax
      let tmpResult = '<script';
      for (const attribute in item) {
        if (attribute === 'src') {
          item[attribute] = this.url_for(item[attribute]);
          if (!item[attribute].endsWith('.js')) item[attribute] += '.js';
        }

        if (item[attribute] === true) tmpResult += ' ' + attribute;
        else tmpResult += ` ${attribute}="${item[attribute]}"`;
      }
      tmpResult += '></script>\n';
      result += tmpResult;
    }
  });
  return result;
}

module.exports = jsHelper;
<commit_msg>refactor(js_helper): forEach()<commit_after>'use strict';

const flatten = function(arr, result = []) {
  for (const i in arr) {
    const value = arr[i];
    if (Array.isArray(value)) {
      flatten(value, result);
    } else {
      result.push(value);
    }
  }
  return result;
};

function jsHelper(...args) {
  let result = '\n';
  let items = args;

  if (!Array.isArray(args)) {
    items = [args];
  }

  items = flatten(items);

  items.forEach(item => {
    // Old syntax
    if (typeof item === 'string' || item instanceof String) {
      let path = item;
      if (!path.endsWith('.js')) {
        path += '.js';
      }
      result += `<script src="${this.url_for(path)}"></script>\n`;
    } else {
      // New syntax
      let tmpResult = '<script';
      Object.keys(item).forEach(attribute => {
        if (attribute === 'src') {
          item[attribute] = this.url_for(item[attribute]);
          if (!item[attribute].endsWith('.js')) item[attribute] += '.js';
        }

        if (item[attribute] === true) tmpResult += ' ' + attribute;
        else tmpResult += ` ${attribute}="${item[attribute]}"`;
      });
      tmpResult += '></script>\n';
      result += tmpResult;
    }
  });
  return result;
}

module.exports = jsHelper;
<|endoftext|>


<commit_before>'use strict';

var BPromise = require('bluebird');

function checkConnection(client, timeout) {
    return new BPromise(function (resolve, reject) {
        if (client.sm.started) {
            client.once('stream:management:ack', resolve);
            client.sm.request();
        } else {
            client.ping().then(resolve).catch(function (err) {
                if (err.error && err.error.condition !== 'timeout') {
                    resolve();
                } else {
                    reject();
                }
            });
        }
    }).timeout(timeout * 1000 || 15000);
}

module.exports = function (client) {
    client.enableKeepAlive = function (opts) {
        opts = opts || {};

        // Ping every 5 minutes
        opts.interval = opts.interval || 300;

        // Disconnect if no response in 15 seconds
        opts.timeout = opts.timeout || 15;

        function keepalive() {
            if (client.sessionStarted) {
                checkConnection(client, opts.timeout).catch(function () {
                    // Kill the apparently dead connection without closing
                    // the stream itself so we can reconnect and potentially
                    // resume the session.
                    client.hasStream = false;
                    client.emit('stream:error', {
                        condition: 'connection-timeout',
                        text: 'Server did not respond in ' + opts.timeout + ' seconds'
                    });
                    client.transport.disconnect();
                });
            }
        }

        client._keepAliveInterval = setInterval(keepalive, opts.interval * 1000);
    };

    client.disableKeepAlive = function () {
        if (client._keepAliveInterval) {
            clearInterval(client._keepAliveInterval);
            delete client._keepAliveInterval;
        }
    };

    client.on('disconnected', function () {
        client.disableKeepAlive();
    });
};
<commit_msg>Fix setting hasStream on transport, not client<commit_after>'use strict';

var BPromise = require('bluebird');

function checkConnection(client, timeout) {
    return new BPromise(function (resolve, reject) {
        if (client.sm.started) {
            client.once('stream:management:ack', resolve);
            client.sm.request();
        } else {
            client.ping().then(resolve).catch(function (err) {
                if (err.error && err.error.condition !== 'timeout') {
                    resolve();
                } else {
                    reject();
                }
            });
        }
    }).timeout(timeout * 1000 || 15000);
}

module.exports = function (client) {
    client.enableKeepAlive = function (opts) {
        opts = opts || {};

        // Ping every 5 minutes
        opts.interval = opts.interval || 300;

        // Disconnect if no response in 15 seconds
        opts.timeout = opts.timeout || 15;

        function keepalive() {
            if (client.sessionStarted) {
                checkConnection(client, opts.timeout).catch(function () {
                    // Kill the apparently dead connection without closing
                    // the stream itself so we can reconnect and potentially
                    // resume the session.
                    client.emit('stream:error', {
                        condition: 'connection-timeout',
                        text: 'Server did not respond in ' + opts.timeout + ' seconds'
                    });
                    client.transport.hasStream = false;
                    client.transport.disconnect();
                });
            }
        }

        client._keepAliveInterval = setInterval(keepalive, opts.interval * 1000);
    };

    client.disableKeepAlive = function () {
        if (client._keepAliveInterval) {
            clearInterval(client._keepAliveInterval);
            delete client._keepAliveInterval;
        }
    };

    client.on('disconnected', function () {
        client.disableKeepAlive();
    });
};
<|endoftext|>


<commit_before>var O = { O: true, B: true, '': true };
var E = { E: true, B: true, '': true };

module.exports = function(feature, address) {
    // features without address data at all, on either side of the street
    if (feature._rangetype !== 'tiger' ||
        !feature._geometry ||
        (feature._geometry.type !== 'LineString' &&
        feature._geometry.type !== 'MultiLineString')) return;

    var lines = feature._geometry.type === 'MultiLineString' ?
        feature._geometry.coordinates :
        [feature._geometry.coordinates];
    var lf = Array.isArray(feature._lfromhn) ? feature._lfromhn : feature._lfromhn ? [feature._lfromhn] : [];
    var lt = Array.isArray(feature._ltohn)   ? feature._ltohn : feature._ltohn ? [feature._ltohn] : [];
    var rf = Array.isArray(feature._rfromhn) ? feature._rfromhn : feature._rfromhn ? [feature._rfromhn] : [];
    var rt = Array.isArray(feature._rtohn)   ? feature._rtohn : feature._rtohn ? [feature._rtohn] : [];
    var lp = Array.isArray(feature._parityl) ? feature._parityl : feature._parityl ? [feature._parityl] : [];
    var rp = Array.isArray(feature._parityr) ? feature._parityr : feature._parityr ? [feature._parityr] : [];

    // Store the nearest endpoint during iteration over lines.
    // The nearest endpoint is used for any addresses that do
    // not have strict or loose range matches and fall within
    // a given threshold (e.g. within 400 housnums of the address).
    var nearest = {hn:Infinity,pt:null};

    for (var i = 0; i < lines.length; i++) {
        var lfromhn = parseSemiNumber(lf[i]),
            rfromhn = parseSemiNumber(rf[i]),
            ltohn = parseSemiNumber(lt[i]),
            rtohn = parseSemiNumber(rt[i]),
            parityl = lp[i] || '',
            parityr = rp[i] || '';

        // no usable data at all
        if ([lfromhn, rfromhn, ltohn, rtohn].every(falsy)) continue;

        var paritymask = (address % 2) === 0 ? E : O;

        // strict L match
        if (typeof lfromhn === 'number' &&
            address >= Math.min(lfromhn,ltohn) &&
            address <= Math.max(lfromhn,ltohn) &&
            paritymask[parityl]) {
            return setPoint(address, lfromhn, ltohn, lines[i].slice(0));
        // strict R match
        } else if (typeof rfromhn === 'number' &&
            address >= Math.min(rfromhn,rtohn) &&
            address <= Math.max(rfromhn,rtohn) &&
            paritymask[parityr]) {
            return setPoint(address, rfromhn, rtohn, lines[i].slice(0));
        // loose L match (no parity check)
        } else if (typeof lfromhn === 'number' &&
            address >= Math.min(lfromhn,ltohn) &&
            address <= Math.max(lfromhn,ltohn)) {
            return setPoint(address, lfromhn, ltohn, lines[i].slice(0), true);
        // loose R match (no parity check)
        } else if (typeof rfromhn === 'number' &&
            address >= Math.min(rfromhn,rtohn) &&
            address <= Math.max(rfromhn,rtohn)) {
            return setPoint(address, rfromhn, rtohn, lines[i].slice(0), true);
        // no range match, store line endpoint if closest so far
        } else {
            var hns = [lfromhn, ltohn, rfromhn, rtohn];
            for (var j = 0; j < 4; j++) {
                if (typeof hns[j] !== 'number') continue;
                if (Math.abs(address - nearest.hn) < Math.abs(address - hns[j])) continue;
                nearest.hn = hns[j];
                nearest.pt = j % 2 === 0 ? lines[i][0] : lines[i][1];
            }
            continue;
        }
    }

    // If the nearest line endpoint falls within our
    // threshold use it as a fallback.
    if (Math.abs(address - nearest.hn) <= 400) {
        return setPoint(address, nearest.hn, nearest.hn, [nearest.pt.slice(0), nearest.pt.slice(0)], true);
    }
};

function setPoint(address, start, end, coords, omitted) {
        var reverse = false;
        if (start > end) {
            reverse = true;
            // swap start and end
            var _;
            _ = end;
            end = start;
            start = _;
        }

        // a normalized number between 0 and 1
        var part = (address - start) / (end - start);

        if (reverse) coords.reverse();

        var distance = calculateDistance(coords);
        var unnorm = part * distance;

        for (var stop = 1; stop < coords.length - 1; stop++) {
            if (coords[stop][2] > unnorm) break;
        }

        var range = coords[stop][2] - coords[stop - 1][2];
        var interp = range ? (unnorm - coords[stop - 1][2]) / range : 1;

        var geom = {
            type:'Point',
            coordinates: [
                coords[stop][0] * interp + coords[stop - 1][0] * (1 - interp),
                coords[stop][1] * interp + coords[stop - 1][1] * (1 - interp)
            ].map(function(v) {
                return Math.round(v*1e6) / 1e6;
            })
        };
        if (omitted) geom.omitted = true;
        return geom;
}

module.exports.setPoint = setPoint;
module.exports.parseSemiNumber = parseSemiNumber;
module.exports.calculateDistance = calculateDistance;

function calculateDistance(coords) {
    var a, b, distance = 0;
    coords[0].push(distance);
    for (var j = 1; j < coords.length; j++) {
        a = coords[j - 1];
        b = coords[j];
        distance += Math.sqrt(
            ((a[0] - b[0]) * (a[0] - b[0])) +
            ((a[1] - b[1]) * (a[1] - b[1])));
        coords[j].push(distance);
    }
    return distance;
}

function parseSemiNumber(_) {
    _ = parseInt((_ || '').replace(/[^\d]/g,''),10);
    return isNaN(_) ? null : _;
}

function falsy(_) { return !_; }
<commit_msg>De-indent.<commit_after>var O = { O: true, B: true, '': true };
var E = { E: true, B: true, '': true };

module.exports = function(feature, address) {
    // features without address data at all, on either side of the street
    if (feature._rangetype !== 'tiger' ||
        !feature._geometry ||
        (feature._geometry.type !== 'LineString' &&
        feature._geometry.type !== 'MultiLineString')) return;

    var lines = feature._geometry.type === 'MultiLineString' ?
        feature._geometry.coordinates :
        [feature._geometry.coordinates];
    var lf = Array.isArray(feature._lfromhn) ? feature._lfromhn : feature._lfromhn ? [feature._lfromhn] : [];
    var lt = Array.isArray(feature._ltohn)   ? feature._ltohn : feature._ltohn ? [feature._ltohn] : [];
    var rf = Array.isArray(feature._rfromhn) ? feature._rfromhn : feature._rfromhn ? [feature._rfromhn] : [];
    var rt = Array.isArray(feature._rtohn)   ? feature._rtohn : feature._rtohn ? [feature._rtohn] : [];
    var lp = Array.isArray(feature._parityl) ? feature._parityl : feature._parityl ? [feature._parityl] : [];
    var rp = Array.isArray(feature._parityr) ? feature._parityr : feature._parityr ? [feature._parityr] : [];

    // Store the nearest endpoint during iteration over lines.
    // The nearest endpoint is used for any addresses that do
    // not have strict or loose range matches and fall within
    // a given threshold (e.g. within 400 housnums of the address).
    var nearest = {hn:Infinity,pt:null};

    for (var i = 0; i < lines.length; i++) {
        var lfromhn = parseSemiNumber(lf[i]),
            rfromhn = parseSemiNumber(rf[i]),
            ltohn = parseSemiNumber(lt[i]),
            rtohn = parseSemiNumber(rt[i]),
            parityl = lp[i] || '',
            parityr = rp[i] || '';

        // no usable data at all
        if ([lfromhn, rfromhn, ltohn, rtohn].every(falsy)) continue;

        var paritymask = (address % 2) === 0 ? E : O;

        // strict L match
        if (typeof lfromhn === 'number' &&
            address >= Math.min(lfromhn,ltohn) &&
            address <= Math.max(lfromhn,ltohn) &&
            paritymask[parityl]) {
            return setPoint(address, lfromhn, ltohn, lines[i].slice(0));
        // strict R match
        } else if (typeof rfromhn === 'number' &&
            address >= Math.min(rfromhn,rtohn) &&
            address <= Math.max(rfromhn,rtohn) &&
            paritymask[parityr]) {
            return setPoint(address, rfromhn, rtohn, lines[i].slice(0));
        // loose L match (no parity check)
        } else if (typeof lfromhn === 'number' &&
            address >= Math.min(lfromhn,ltohn) &&
            address <= Math.max(lfromhn,ltohn)) {
            return setPoint(address, lfromhn, ltohn, lines[i].slice(0), true);
        // loose R match (no parity check)
        } else if (typeof rfromhn === 'number' &&
            address >= Math.min(rfromhn,rtohn) &&
            address <= Math.max(rfromhn,rtohn)) {
            return setPoint(address, rfromhn, rtohn, lines[i].slice(0), true);
        // no range match, store line endpoint if closest so far
        } else {
            var hns = [lfromhn, ltohn, rfromhn, rtohn];
            for (var j = 0; j < 4; j++) {
                if (typeof hns[j] !== 'number') continue;
                if (Math.abs(address - nearest.hn) < Math.abs(address - hns[j])) continue;
                nearest.hn = hns[j];
                nearest.pt = j % 2 === 0 ? lines[i][0] : lines[i][1];
            }
            continue;
        }
    }

    // If the nearest line endpoint falls within our
    // threshold use it as a fallback.
    if (Math.abs(address - nearest.hn) <= 400) {
        return setPoint(address, nearest.hn, nearest.hn, [nearest.pt.slice(0), nearest.pt.slice(0)], true);
    }
};

function setPoint(address, start, end, coords, omitted) {
    var reverse = false;
    if (start > end) {
        reverse = true;
        // swap start and end
        var _;
        _ = end;
        end = start;
        start = _;
    }

    // a normalized number between 0 and 1
    var part = (address - start) / (end - start);

    if (reverse) coords.reverse();

    var distance = calculateDistance(coords);
    var unnorm = part * distance;

    for (var stop = 1; stop < coords.length - 1; stop++) {
        if (coords[stop][2] > unnorm) break;
    }

    var range = coords[stop][2] - coords[stop - 1][2];
    var interp = range ? (unnorm - coords[stop - 1][2]) / range : 1;

    var geom = {
        type:'Point',
        coordinates: [
            coords[stop][0] * interp + coords[stop - 1][0] * (1 - interp),
            coords[stop][1] * interp + coords[stop - 1][1] * (1 - interp)
        ].map(function(v) {
            return Math.round(v*1e6) / 1e6;
        })
    };
    if (omitted) geom.omitted = true;
    return geom;
}

module.exports.setPoint = setPoint;
module.exports.parseSemiNumber = parseSemiNumber;
module.exports.calculateDistance = calculateDistance;

function calculateDistance(coords) {
    var a, b, distance = 0;
    coords[0].push(distance);
    for (var j = 1; j < coords.length; j++) {
        a = coords[j - 1];
        b = coords[j];
        distance += Math.sqrt(
            ((a[0] - b[0]) * (a[0] - b[0])) +
            ((a[1] - b[1]) * (a[1] - b[1])));
        coords[j].push(distance);
    }
    return distance;
}

function parseSemiNumber(_) {
    _ = parseInt((_ || '').replace(/[^\d]/g,''),10);
    return isNaN(_) ? null : _;
}

function falsy(_) { return !_; }
<|endoftext|>


<commit_before>app.config(function($stateProvider, $urlRouterProvider) {
  // Redirect 404 to homepage
  $urlRouterProvider.otherwise('/');

  // Routing
  $stateProvider
    .state('login', {
      url: '/login',
      templateUrl: 'partials/login.html',
      controller: 'LoginController',
    })
    .state('dashboard', {
      url: '/',
      menu: 'dashboard',
      templateUrl: 'partials/dashboard.html',
      controller: 'DashboardController',
      resolve: {
        projects: function(ProjectService) {
          return ProjectService.getProjects();
        },
      }
    })
    .state('profile', {
      url: '/profile',
      templateUrl: 'partials/profile.html',
      controller: 'ProfileController',
      resolve: {
        user: function(AuthenticationService) {
          return AuthenticationService.getCurrentUser();
        }
      }
    })
    .state('project', {
      url: '/project/{slug:[a-zA-Z0-9\-\.\_]+}',
      menu: 'translate',
      templateUrl: 'partials/project.html',
      controller: 'ProjectController',
      resolve: {
        project: function($stateParams, ProjectService) {
          return ProjectService.getProject($stateParams.slug);
        },
        languages: function($stateParams, LanguageService) {
          return LanguageService.getLanguages($stateParams.slug);
        },
        resources: function($stateParams, ResourceService) {
          return ResourceService.getResources($stateParams.slug);
        },
      }
    })
    .state('translate', {
      url: '/project/:slug/translate',
      menu: 'translate',
      templateUrl: 'partials/translate.html',
      controller: 'EditorController',
      resolve: {
        project: function($stateParams, ProjectService) {
          return ProjectService.getProject($stateParams.slug);
        },
        languages: function($stateParams, LanguageService) {
          return LanguageService.getLanguages($stateParams.slug);
        },
        resources: function($stateParams, ResourceService) {
          return ResourceService.getResources($stateParams.slug);
        },
      }
    })
    .state('translate.source', {
      url: '/{source:[a-zA-Z\-_]+}',
      menu: 'translate',
      controller: 'EditorSourceController',
      // Setting the source locale doesn't change the UI so let's put an empty template
      template: '<ui-view/>'
    })
    .state('translate.source.target', {
      url: '/{target:[a-zA-Z\-_]+}',
      menu: 'translate',
      controller: 'EditorTargetController',
      template: '<ui-view/>'
    })
    .state('translate.source.target.phrase', {
      url: '/{id:[0-9]+}',
      menu: 'translate',
      templateUrl: 'partials/translate-phrase.html',
      controller: 'EditorPhraseController',
    })
    .state('glossary', {
      url: '/glossary',
      menu: 'glossary',
      templateUrl: 'partials/glossary.html',
      controller: 'GlossaryController',
    })
});

app.run(function($rootScope) {
  $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
    console.log(event);
  })
})
<commit_msg>Fix projects url<commit_after>app.config(function($stateProvider, $urlRouterProvider) {
  // Redirect 404 to homepage
  $urlRouterProvider.otherwise('/');

  // Routing
  $stateProvider
    .state('login', {
      url: '/login',
      templateUrl: 'partials/login.html',
      controller: 'LoginController',
    })
    .state('dashboard', {
      url: '/',
      menu: 'dashboard',
      templateUrl: 'partials/dashboard.html',
      controller: 'DashboardController',
      resolve: {
        projects: function(ProjectService) {
          return ProjectService.getProjects();
        },
      }
    })
    .state('profile', {
      url: '/profile',
      templateUrl: 'partials/profile.html',
      controller: 'ProfileController',
      resolve: {
        user: function(AuthenticationService) {
          return AuthenticationService.getCurrentUser();
        }
      }
    })
    .state('project', {
      url: '/projects/{slug:[a-zA-Z0-9\-\.\_]+}',
      menu: 'translate',
      templateUrl: 'partials/project.html',
      controller: 'ProjectController',
      resolve: {
        project: function($stateParams, ProjectService) {
          return ProjectService.getProject($stateParams.slug);
        },
        languages: function($stateParams, LanguageService) {
          return LanguageService.getLanguages($stateParams.slug);
        },
        resources: function($stateParams, ResourceService) {
          return ResourceService.getResources($stateParams.slug);
        },
      }
    })
    .state('translate', {
      url: '/projects/:slug/translate',
      menu: 'translate',
      templateUrl: 'partials/translate.html',
      controller: 'EditorController',
      resolve: {
        project: function($stateParams, ProjectService) {
          return ProjectService.getProject($stateParams.slug);
        },
        languages: function($stateParams, LanguageService) {
          return LanguageService.getLanguages($stateParams.slug);
        },
        resources: function($stateParams, ResourceService) {
          return ResourceService.getResources($stateParams.slug);
        },
      }
    })
    .state('translate.source', {
      url: '/{source:[a-zA-Z\-_]+}',
      menu: 'translate',
      controller: 'EditorSourceController',
      // Setting the source locale doesn't change the UI so let's put an empty template
      template: '<ui-view/>'
    })
    .state('translate.source.target', {
      url: '/{target:[a-zA-Z\-_]+}',
      menu: 'translate',
      controller: 'EditorTargetController',
      template: '<ui-view/>'
    })
    .state('translate.source.target.phrase', {
      url: '/{id:[0-9]+}',
      menu: 'translate',
      templateUrl: 'partials/translate-phrase.html',
      controller: 'EditorPhraseController',
    })
    .state('glossary', {
      url: '/glossary',
      menu: 'glossary',
      templateUrl: 'partials/glossary.html',
      controller: 'GlossaryController',
    })
});

app.run(function($rootScope) {
  $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
    console.log(event);
  })
})
<|endoftext|>


<commit_before>var instance = false

module.exports = {
	newISOdate: function(d) {
		function pad(n) {return n<10 ? '0'+n : n}
    	return d.getUTCFullYear()+'-'
        + pad(d.getUTCMonth()+1)+'-'
        + pad(d.getUTCDate())+'T'
        + pad(d.getUTCHours())+':'
        + pad(d.getUTCMinutes())+':'
        + pad(d.getUTCSeconds())+'Z'
	},
	getISOdate: function() {
		var d = new Date()
		function pad(n) {return n<10 ? '0'+n : n}
    	return d.getUTCFullYear()+'-'
        + pad(d.getUTCMonth()+1)+'-'
        + pad(d.getUTCDate())+'T'
        + pad(d.getUTCHours())+':'
        + pad(d.getUTCMinutes())+':'
        + pad(d.getUTCSeconds())+'Z'
	},
	getPrettyDate: function(date) {
    if( ! (date instanceof Date) ) {
      date = new Date(date)
    }

		var yyyy = date.getUTCFullYear().toString()
		var mm = (date.getUTCMonth()()+1).toString()
		var dd  = date.getUTCDate().toString()
		return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0])
	},
  getPrettyDateTime: function(date) {
    if( ! (date instanceof Date) ) {
      date = new Date(date)
    }

    year = "" + date.getUTCFullYear();
    month = "" + (date.getUTCMonth() + 1); if (month.length == 1) { month = "0" + month; }
    day = "" + date.getUTCDate(); if (day.length == 1) { day = "0" + day; }
    hour = "" + date.getHours(); if (hour.length == 1) { hour = "0" + hour; }
    minute = "" + date.getUTCMinutes(); if (minute.length == 1) { minute = "0" + minute; }
    second = "" + date.getUTCSeconds(); if (second.length == 1) { second = "0" + second; }
    return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
	},
  formatHtmlEntities: function (str) {
    return str.replace(/[^]/g, function(str) {
        return "&#" + str.charCodeAt(0) + ";"
    })
  },
  returnUrl: function(req) {
    var url = '/'
    previousUrl = req.headers.referer
    host = req.headers.host

    if(typeof(previousUrl) !== 'undefined') {
      if(previousUrl.indexOf(host) >= 0) {
        var page = ( previousUrl.substr(previousUrl.indexOf(host) + host.length) )
        url = page

        if ( req.session.returnTo !== 'undefined' ) {
          if( req.originalUrl.indexOf('.') === -1 ) { //Fix for not redirecting to an image or something
            url = req.originalUrl
          }
        }
      } else {
        url = req.originalUrl
      }
    } else {
      url = req.originalUrl
    }

    return url
  },
  isAuthenticated: function(req, res, next) {
    if (req.isAuthenticated()) {
      return next()
    } else {
      //Check if this was an ajax request
      if(req.xhr || req.headers.accept.indexOf('json') >= 0) {
        res.json({
          success: false,
          message: 'Access denied'
        })
      } else {
        //Redirect to login for browsers
        res.redirect('/logga-in')
      }
    }
  },
  isPrivileged: function(req, res, next) {
    var privileged = ['admin','moderator']
    if(privileged.indexOf(req.user.info.permission) >= 0 ) {
      return next() //User is privileged, continue
    } else {
      //Check if this was an ajax request
      if(req.xhr || req.headers.accept.indexOf('json') >= 0) {
        res.json({
          success: false,
          message: 'Access denied'
        })
      } else {
        //Redirect to front page for browsers
        res.redirect('/')
      }
    }
  }
}<commit_msg>Move user prvilege checking to separate functions<commit_after>module.exports = {
	newISOdate: function(d) {
		function pad(n) {return n<10 ? '0'+n : n}
    	return d.getUTCFullYear()+'-'
        + pad(d.getUTCMonth()+1)+'-'
        + pad(d.getUTCDate())+'T'
        + pad(d.getUTCHours())+':'
        + pad(d.getUTCMinutes())+':'
        + pad(d.getUTCSeconds())+'Z'
	},
	getISOdate: function() {
		var d = new Date()
		function pad(n) {return n<10 ? '0'+n : n}
    	return d.getUTCFullYear()+'-'
        + pad(d.getUTCMonth()+1)+'-'
        + pad(d.getUTCDate())+'T'
        + pad(d.getUTCHours())+':'
        + pad(d.getUTCMinutes())+':'
        + pad(d.getUTCSeconds())+'Z'
	},
	getPrettyDate: function(date) {
    if( ! (date instanceof Date) ) {
      date = new Date(date)
    }

		var yyyy = date.getUTCFullYear().toString()
		var mm = (date.getUTCMonth()()+1).toString()
		var dd  = date.getUTCDate().toString()
		return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0])
	},
  getPrettyDateTime: function(date) {
    if( ! (date instanceof Date) ) {
      date = new Date(date)
    }

    year = "" + date.getUTCFullYear();
    month = "" + (date.getUTCMonth() + 1); if (month.length == 1) { month = "0" + month; }
    day = "" + date.getUTCDate(); if (day.length == 1) { day = "0" + day; }
    hour = "" + date.getHours(); if (hour.length == 1) { hour = "0" + hour; }
    minute = "" + date.getUTCMinutes(); if (minute.length == 1) { minute = "0" + minute; }
    second = "" + date.getUTCSeconds(); if (second.length == 1) { second = "0" + second; }
    return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
	},
  formatHtmlEntities: function (str) {
    return str.replace(/[^]/g, function(str) {
        return "&#" + str.charCodeAt(0) + ";"
    })
  },
  returnUrl: function(req) {
    var url = '/'
    previousUrl = req.headers.referer
    host = req.headers.host

    if(typeof(previousUrl) !== 'undefined') {
      if(previousUrl.indexOf(host) >= 0) {
        var page = ( previousUrl.substr(previousUrl.indexOf(host) + host.length) )
        url = page

        if ( req.session.returnTo !== 'undefined' ) {
          if( req.originalUrl.indexOf('.') === -1 ) { //Fix for not redirecting to an image or something
            url = req.originalUrl
          }
        }
      } else {
        url = req.originalUrl
      }
    } else {
      url = req.originalUrl
    }

    return url
  },
  isAuthenticated: function(req, res, next) {
    if (req.isAuthenticated()) {
      return next()
    } else {
      //Check if this was an ajax request
      if(req.xhr || req.headers.accept.indexOf('json') >= 0) {
        res.json({
          success: false,
          message: 'Access denied'
        })
      } else {
        //Redirect to login for browsers
        res.redirect('/logga-in')
      }
    }
  },
  isPrivileged: function(req, res, next) {
    if(module.exports.userCheckPrivileged(req.user)) {
      return next() //User is privileged, continue
    } else {
      //Check if this was an ajax request
      if(req.xhr || req.headers.accept.indexOf('json') >= 0) {
        res.json({
          success: false,
          message: 'Access denied'
        })
      } else {
        //Redirect to front page for browsers
        res.redirect('/')
      }
    }
  },
  userCheckPrivileged: function(user) {
    var privileged = ['admin','moderator']
    return (typeof(user) !== 'undefined') ? (privileged.indexOf(user.info.permission) >= 0) : false
  },
  userCheckAdmin: function(user) {
    var admin = ['admin']
    return (typeof(user) !== 'undefined') ? (admin.indexOf(user.info.permission) >= 0) : false
  }
}<|endoftext|>


<commit_before>const Promise = require('bluebird');
const errors = require('../errors');

class Connector {
  constructor(connection) {
    this.connection = connection;

    this.dataSocket = null;
    this.dataServer = null;
    this.type = false;
  }

  get log() {
    return this.connection.log;
  }

  get socket() {
    return this.dataSocket;
  }

  get server() {
    return this.connection.server;
  }

  waitForConnection() {
    return Promise.reject(new errors.ConnectorError('No connector setup, send PASV or PORT'));
  }

  end() {
    const closeDataSocket = new Promise(resolve => {
      if (this.dataSocket) this.dataSocket.destroy();
      resolve();
    });
    const closeDataServer = new Promise(resolve => {
      if (this.dataServer) this.dataServer.close(() => resolve());
      else resolve();
    });

    return Promise.all([closeDataSocket, closeDataServer])
    .then(() => {
      this.dataSocket = null;
      this.dataServer = null;
      this.type = false;

      this.connection.connector = new Connector(this);
    });
  }
}
module.exports = Connector;
<commit_msg>fix(connector): gracefully end data socket (#116)<commit_after>const Promise = require('bluebird');
const errors = require('../errors');

class Connector {
  constructor(connection) {
    this.connection = connection;

    this.dataSocket = null;
    this.dataServer = null;
    this.type = false;
  }

  get log() {
    return this.connection.log;
  }

  get socket() {
    return this.dataSocket;
  }

  get server() {
    return this.connection.server;
  }

  waitForConnection() {
    return Promise.reject(new errors.ConnectorError('No connector setup, send PASV or PORT'));
  }

  end() {
    const closeDataSocket = new Promise(resolve => {
      if (this.dataSocket) {
        this.dataSocket.end().destroy();
      }

      resolve();
    });
    const closeDataServer = new Promise(resolve => {
      if (this.dataServer) this.dataServer.close(() => resolve());
      else resolve();
    });

    return Promise.all([closeDataSocket, closeDataServer])
    .then(() => {
      this.dataSocket = null;
      this.dataServer = null;
      this.type = false;

      this.connection.connector = new Connector(this);
    });
  }
}
module.exports = Connector;
<|endoftext|>