<commit_before>var $ = require('jquery');
var _ = require('underscore');
var cdb = require('cartodb.js');
var TooltipView = require('../widget-tooltip-view');
var template = require('./histogram-title-template.tpl');

/**
 *  Show title + show if histogram sizes are applied or not
 *
 */

module.exports = cdb.core.View.extend({
  className: 'CDB-Widget-title CDB-Widget-contentSpaced',

  events: {
    'click .js-autoStyle': '_autoStyle',
    'click .js-cancelAutoStyle': '_cancelAutoStyle'
  },

  initialize: function (opts) {
    if (!opts.widgetModel) throw new Error('widgetModel is needed');
    if (!opts.dataviewModel) throw new Error('dataviewModel is needed');

    this.widgetModel = opts.widgetModel;
    this.dataviewModel = opts.dataviewModel;
    this._initBinds();
  },

  render: function () {
    this.clearSubViews();
    this.$el.html(
      template({
        title: this.widgetModel.get('title'),
        isAutoStyleEnabled: this._isAutoStyleButtonVisible(),
        isAutoStyle: this.widgetModel.get('autoStyle'),
        isCollapsed: this.widgetModel.get('collapsed')
      })
    );
    this._initViews();

    return this;
  },

  _initBinds: function () {
    this.widgetModel.bind('change:title change:collapsed change:autoStyle change:style', this.render, this);
    this.add_related_model(this.widgetModel);

    this.dataviewModel.layer.bind('change:visible change:cartocss', this.render, this);
    this.add_related_model(this.dataviewModel.layer);
  },

  _initViews: function () {
    var sizesTooltip = new TooltipView({
      target: this.$('.js-sizes')
    });
    $('body').append(sizesTooltip.render().el);
    this.addView(sizesTooltip);
  },

  _isAutoStyleButtonVisible: function () {
    var layerModelMeta = this.dataviewModel.layer.get('meta');
    var cartocss = this.dataviewModel.layer.get('cartocss') || (layerModelMeta && layerModelMeta.cartocss);
    var hasColorsAutoStyle = cartocss && this.widgetModel.hasColorsAutoStyle();

    return this.widgetModel.isAutoStyleEnabled() &&
      this.dataviewModel.layer.get('visible') &&
      hasColorsAutoStyle;
  },

  _autoStyle: function () {
    this.widgetModel.autoStyle();
  },

  _cancelAutoStyle: function () {
    this.widgetModel.cancelAutoStyle();
  }

});
<commit_msg>Remove unneeded underscore require<commit_after>var $ = require('jquery');
var cdb = require('cartodb.js');
var TooltipView = require('../widget-tooltip-view');
var template = require('./histogram-title-template.tpl');

/**
 *  Show title + show if histogram sizes are applied or not
 *
 */

module.exports = cdb.core.View.extend({
  className: 'CDB-Widget-title CDB-Widget-contentSpaced',

  events: {
    'click .js-autoStyle': '_autoStyle',
    'click .js-cancelAutoStyle': '_cancelAutoStyle'
  },

  initialize: function (opts) {
    if (!opts.widgetModel) throw new Error('widgetModel is needed');
    if (!opts.dataviewModel) throw new Error('dataviewModel is needed');

    this.widgetModel = opts.widgetModel;
    this.dataviewModel = opts.dataviewModel;
    this._initBinds();
  },

  render: function () {
    this.clearSubViews();
    this.$el.html(
      template({
        title: this.widgetModel.get('title'),
        isAutoStyleEnabled: this._isAutoStyleButtonVisible(),
        isAutoStyle: this.widgetModel.get('autoStyle'),
        isCollapsed: this.widgetModel.get('collapsed')
      })
    );
    this._initViews();

    return this;
  },

  _initBinds: function () {
    this.widgetModel.bind('change:title change:collapsed change:autoStyle change:style', this.render, this);
    this.add_related_model(this.widgetModel);

    this.dataviewModel.layer.bind('change:visible change:cartocss', this.render, this);
    this.add_related_model(this.dataviewModel.layer);
  },

  _initViews: function () {
    var sizesTooltip = new TooltipView({
      target: this.$('.js-sizes')
    });
    $('body').append(sizesTooltip.render().el);
    this.addView(sizesTooltip);
  },

  _isAutoStyleButtonVisible: function () {
    var layerModelMeta = this.dataviewModel.layer.get('meta');
    var cartocss = this.dataviewModel.layer.get('cartocss') || (layerModelMeta && layerModelMeta.cartocss);
    var hasColorsAutoStyle = cartocss && this.widgetModel.hasColorsAutoStyle();

    return this.widgetModel.isAutoStyleEnabled() &&
      this.dataviewModel.layer.get('visible') &&
      hasColorsAutoStyle;
  },

  _autoStyle: function () {
    this.widgetModel.autoStyle();
  },

  _cancelAutoStyle: function () {
    this.widgetModel.cancelAutoStyle();
  }

});
<|endoftext|>


<commit_before>"use strict";

var es = require("./errors.js");
var ERRORS = es.ERRORS;
var APICombinedError = es.APICombinedError;

// Middleware to handle errors and output an error response over the API

// flatten an error object (mongoose ValidationError, APIError, etc) into a list of APIErrors
// folds up err into errors (so call parseError(err, []) initially)
function parseError(err, errors) {
    // mongoose error with sub-errors
    if (err.name === "ValidationError") {
        var errorKeys = Object.keys(err.errors);
        for (var i = 0; i < errorKeys.length; i++) {
            // recurse ourselves on each of these errors
            errors = parseError(err.errors[errorKeys[i]], errors);
        }
        return errors;
    }

    // base mongoose error
    if (err.name === "ValidatorError" || err.name === "CastError") {
        // mongoose errors are ugly and we need to match them up to errors in ERRORS
        // idea is to use metadata to generate a key we think may be in ERRORS

        // get actual base field name (e.g., hours.monday.open => hours)
        var fullField = err.path.split(".")[0];
        // convert field name from camelCase to uppercase SNAKE_CASE
        var field = fullField.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
        var testKey = "";

        // use a couple of heuristics to try and find the appropriate error
        var ps = err.properties;
        // two kind of errors with invalid IDs:
        //      when finding a resource with ID in URL (thrown explicitly)
        //      when POSTing a child resource ID (e.g., a medication_id when creating an adherence): gives CastError
        //          or a required ValidatorError
        if ((err.name === "CastError" || err.kind === "required") && field.indexOf("_ID") >= 0) {
            // unpluralise
            field = field.replace("_IDS", "_ID");
            testKey = "INVALID_RESOURCE_" + field;
        } else if (err.kind === "regexp" || (typeof ps !== "undefined" && (ps.kind === "enum" || ps.type === "enum"))) {
            // regular expression or enum => invalid format
            testKey = "INVALID_" + field;
        } else if (err.kind === "required") {
            // required fields not present
            testKey = field + "_REQUIRED";
        } else {
            // set custom error message in models to be keys in ERRORS
            testKey = err.message;
        }

        // if an error matches
        if (testKey in ERRORS) {
            errors.push(ERRORS[testKey]);
            return errors;
        // otherwise try using the error message (it may have been custom set to an error's code)
        } else if (err.message in ERRORS) {
            errors.push(ERRORS[err.message]);
            return errors;
        }
    }

    // already an APIError
    if (err.name === "APIError") {
        errors.push(err);
        return errors;
    }

    // unknown case
    if (process.env.DEBUG) {
        console.error("Unknown error!");
        console.error(err.name);
        console.error(err);
        console.error("");
        throw err;
    } else {
        console.error("Unknown error!");
        console.error(err.name);
        console.error(err);
        console.error("");
        console.error(err.stack);
        errors.push(ERRORS.UNKNOWN_ERROR);
        return errors;
    }
}

// handle errors by returning a JSON response with appropriate resp code
function errorHandler(err, req, res, next) {
    // don't do anything unless an error was thrown
    if (!err) return next();

    if(err.name === "ValidationError" || err.name === "ValidatorError" || err.name === "CastError"){
      try {
        var mongoGeneratedError = parseError(err, []);
        if(mongoGeneratedError.length){
          err = mongoGeneratedError[0];
        }else{
          err = ERRORS.INVALID_SUBMISSION;
        }
      }
      catch(errorz) {
        err = ERRORS.INVALID_SUBMISSION;
      }
    }

    // parse err into an APICombinedError object
    var error = err; //new APICombinedError(parseError(err, []));

    // if we send a 401 response, we also need to send the error code in a
    // WWW-Authenticate header as per www spec
    if (error.responseCode === 401) res.set("WWW-Authenticate", "Bearer realm='orange'");

    // send JSON error response
    res.status(error.responseCode);
    res.send(error);
    // res.send({
    //     success: false,
    //     errors: error.slugs
    // });
}

module.exports = errorHandler;
<commit_msg>Fix Invalid status code: undefined<commit_after>"use strict";

var es = require("./errors.js");
var ERRORS = es.ERRORS;
var APICombinedError = es.APICombinedError;

// Middleware to handle errors and output an error response over the API

// flatten an error object (mongoose ValidationError, APIError, etc) into a list of APIErrors
// folds up err into errors (so call parseError(err, []) initially)
function parseError(err, errors) {
    // mongoose error with sub-errors
    if (err.name === "ValidationError") {
        var errorKeys = Object.keys(err.errors);
        for (var i = 0; i < errorKeys.length; i++) {
            // recurse ourselves on each of these errors
            errors = parseError(err.errors[errorKeys[i]], errors);
        }
        return errors;
    }

    // base mongoose error
    if (err.name === "ValidatorError" || err.name === "CastError") {
        // mongoose errors are ugly and we need to match them up to errors in ERRORS
        // idea is to use metadata to generate a key we think may be in ERRORS

        // get actual base field name (e.g., hours.monday.open => hours)
        var fullField = err.path.split(".")[0];
        // convert field name from camelCase to uppercase SNAKE_CASE
        var field = fullField.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
        var testKey = "";

        // use a couple of heuristics to try and find the appropriate error
        var ps = err.properties;
        // two kind of errors with invalid IDs:
        //      when finding a resource with ID in URL (thrown explicitly)
        //      when POSTing a child resource ID (e.g., a medication_id when creating an adherence): gives CastError
        //          or a required ValidatorError
        if ((err.name === "CastError" || err.kind === "required") && field.indexOf("_ID") >= 0) {
            // unpluralise
            field = field.replace("_IDS", "_ID");
            testKey = "INVALID_RESOURCE_" + field;
        } else if (err.kind === "regexp" || (typeof ps !== "undefined" && (ps.kind === "enum" || ps.type === "enum"))) {
            // regular expression or enum => invalid format
            testKey = "INVALID_" + field;
        } else if (err.kind === "required") {
            // required fields not present
            testKey = field + "_REQUIRED";
        } else {
            // set custom error message in models to be keys in ERRORS
            testKey = err.message;
        }

        // if an error matches
        if (testKey in ERRORS) {
            errors.push(ERRORS[testKey]);
            return errors;
        // otherwise try using the error message (it may have been custom set to an error's code)
        } else if (err.message in ERRORS) {
            errors.push(ERRORS[err.message]);
            return errors;
        }
    }

    // already an APIError
    if (err.name === "APIError") {
        errors.push(err);
        return errors;
    }

    // unknown case
    if (process.env.DEBUG) {
        console.error("Unknown error!");
        console.error(err.name);
        console.error(err);
        console.error("");
        throw err;
    } else {
        console.error("Unknown error!");
        console.error(err.name);
        console.error(err);
        console.error("");
        console.error(err.stack);
        errors.push(ERRORS.UNKNOWN_ERROR);
        return errors;
    }
}

// handle errors by returning a JSON response with appropriate resp code
function errorHandler(err, req, res, next) {
    // don't do anything unless an error was thrown
    if (!err) return next();

    if(err.name === "ValidationError" || err.name === "ValidatorError" || err.name === "CastError"){
      try {
        var mongoGeneratedError = parseError(err, []);
        if(mongoGeneratedError.length){
          err = mongoGeneratedError[0];
        }else{
          err = ERRORS.INVALID_SUBMISSION;
        }
      }
      catch(errorz) {
        err = ERRORS.INVALID_SUBMISSION;
      }
    }

    // parse err into an APICombinedError object
    var error = err; //new APICombinedError(parseError(err, []));

    // if we send a 401 response, we also need to send the error code in a
    // WWW-Authenticate header as per www spec
    if (error.responseCode === 401) res.set("WWW-Authenticate", "Bearer realm='orange'");

    // send JSON error response
    res.status(error.responseCode || 500);
    res.send(error);
    // res.send({
    //     success: false,
    //     errors: error.slugs
    // });
}

module.exports = errorHandler;
<|endoftext|>


<commit_before>dojo.provide("dojox.grid.cells.dijit");

dojo.require("dojox.grid.cells");

// TODO: shouldn't it be the test file's job to require these modules,
// if it is using them?  Most of these modules aren't referenced by this file.

dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.form.TimeTextBox");
dojo.require("dijit.form.ComboBox");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.NumberSpinner");
dojo.require("dijit.form.NumberTextBox");
dojo.require("dijit.form.CurrencyTextBox");
dojo.require("dijit.form.HorizontalSlider");
dojo.require("dijit.Editor");

(function(){
	var dgc = dojox.grid.cells;
	dojo.declare("dojox.grid.cells._Widget", dgc._Base, {
		widgetClass: dijit.form.TextBox,
		constructor: function(inCell){
			this.widget = null;
			if(typeof this.widgetClass == "string"){
				dojo.deprecated("Passing a string to widgetClass is deprecated", "pass the widget class object instead", "2.0");
				this.widgetClass = dojo.getObject(this.widgetClass);
			}
		},
		formatEditing: function(inDatum, inRowIndex){
			this.needFormatNode(inDatum, inRowIndex);
			return "

";
		},
		getValue: function(inRowIndex){
			return this.widget.attr('value');
		},
		setValue: function(inRowIndex, inValue){
			if(this.widget&&this.widget.attr){
				//Look for lazy-loading editor and handle it via its deferred.
				if(this.widget.onLoadDeferred){
					var self = this;
					this.widget.onLoadDeferred.addCallback(function(){
						self.widget.attr("value",inValue===null?"":inValue);
					});
				}else{
					this.widget.attr("value", inValue);
				}
			}else{
				this.inherited(arguments);
			}
		},
		getWidgetProps: function(inDatum){
			return dojo.mixin({}, this.widgetProps||{}, {
				constraints: dojo.mixin({}, this.constraint) || {}, //TODO: really just for ValidationTextBoxes
				value: inDatum
			});
		},
		createWidget: function(inNode, inDatum, inRowIndex){
			return new this.widgetClass(this.getWidgetProps(inDatum), inNode);
		},
		attachWidget: function(inNode, inDatum, inRowIndex){
			inNode.appendChild(this.widget.domNode);
			this.setValue(inRowIndex, inDatum);
		},
		formatNode: function(inNode, inDatum, inRowIndex){
			if(!this.widgetClass){
				return inDatum;
			}
			if(!this.widget){
				this.widget = this.createWidget.apply(this, arguments);
			}else{
				this.attachWidget.apply(this, arguments);
			}
			this.sizeWidget.apply(this, arguments);
			this.grid.rowHeightChanged(inRowIndex);
			this.focus();
			return undefined;
		},
		sizeWidget: function(inNode, inDatum, inRowIndex){
			var
				p = this.getNode(inRowIndex),
				box = dojo.contentBox(p);
			dojo.marginBox(this.widget.domNode, {w: box.w});
		},
		focus: function(inRowIndex, inNode){
			if(this.widget){
				setTimeout(dojo.hitch(this.widget, function(){
					dojox.grid.util.fire(this, "focus");
				}), 0);
			}
		},
		_finish: function(inRowIndex){
			this.inherited(arguments);
			dojox.grid.util.removeNode(this.widget.domNode);
		}
	});
	dgc._Widget.markupFactory = function(node, cell){
		dgc._Base.markupFactory(node, cell);
		var d = dojo;
		var widgetProps = d.trim(d.attr(node, "widgetProps")||"");
		var constraint = d.trim(d.attr(node, "constraint")||"");
		var widgetClass = d.trim(d.attr(node, "widgetClass")||"");
		if(widgetProps){
			cell.widgetProps = d.fromJson(widgetProps);
		}
		if(constraint){
			cell.constraint = d.fromJson(constraint);
		}
		if(widgetClass){
			cell.widgetClass = d.getObject(widgetClass);
		}
	};

	dojo.declare("dojox.grid.cells.ComboBox", dgc._Widget, {
		widgetClass: dijit.form.ComboBox,
		getWidgetProps: function(inDatum){
			var items=[];
			dojo.forEach(this.options, function(o){
				items.push({name: o, value: o});
			});
			var store = new dojo.data.ItemFileReadStore({data: {identifier:"name", items: items}});
			return dojo.mixin({}, this.widgetProps||{}, {
				value: inDatum,
				store: store
			});
		},
		getValue: function(){
			var e = this.widget;
			// make sure to apply the displayed value
			e.attr('displayedValue', e.attr('displayedValue'));
			return e.attr('value');
		}
	});
	dgc.ComboBox.markupFactory = function(node, cell){
		dgc._Widget.markupFactory(node, cell);
		var d=dojo;
		var options = d.trim(d.attr(node, "options")||"");
		if(options){
			var o = options.split(',');
			if(o[0] != options){
				cell.options = o;
			}
		}
	};

	dojo.declare("dojox.grid.cells.DateTextBox", dgc._Widget, {
		widgetClass: dijit.form.DateTextBox,
		setValue: function(inRowIndex, inValue){
			if(this.widget){
				this.widget.attr('value', new Date(inValue));
			}else{
				this.inherited(arguments);
			}
		},
		getWidgetProps: function(inDatum){
			return dojo.mixin(this.inherited(arguments), {
				value: new Date(inDatum)
			});
		}
	});
	dgc.DateTextBox.markupFactory = function(node, cell){
		dgc._Widget.markupFactory(node, cell);
	};

	dojo.declare("dojox.grid.cells.CheckBox", dgc._Widget, {
		widgetClass: dijit.form.CheckBox,
		getValue: function(){
			return this.widget.checked;
		},
		setValue: function(inRowIndex, inValue){
			if(this.widget&&this.widget.attributeMap.checked){
				this.widget.attr("checked", inValue);
			}else{
				this.inherited(arguments);
			}
		},
		sizeWidget: function(inNode, inDatum, inRowIndex){
			return;
		}
	});
	dgc.CheckBox.markupFactory = function(node, cell){
		dgc._Widget.markupFactory(node, cell);
	};

	dojo.declare("dojox.grid.cells.Editor", dgc._Widget, {
		widgetClass: dijit.Editor,
		getWidgetProps: function(inDatum){
			return dojo.mixin({}, this.widgetProps||{}, {
				height: this.widgetHeight || "100px"
			});
		},
		createWidget: function(inNode, inDatum, inRowIndex){
			// widget needs its value set after creation
			var widget = new this.widgetClass(this.getWidgetProps(inDatum), inNode);
			dojo.connect(widget, 'onLoad', dojo.hitch(this, 'populateEditor'));
			return widget;
		},
		formatNode: function(inNode, inDatum, inRowIndex){
			this.content = inDatum;
			this.inherited(arguments);
			if(dojo.isMoz){
				// FIXME: seem to need to reopen the editor and display the toolbar
				var e = this.widget;
				e.open();
				if(this.widgetToolbar){
					dojo.place(e.toolbar.domNode, e.editingArea, "before");
				}
			}
		},
		populateEditor: function(){
			this.widget.attr('value', this.content);
			this.widget.placeCursorAtEnd();
		}
	});
	dgc.Editor.markupFactory = function(node, cell){
		dgc._Widget.markupFactory(node, cell);
		var d = dojo;
		var h = dojo.trim(dojo.attr(node, "widgetHeight")||"");
		if(h){
			if((h != "auto")&&(h.substr(-2) != "em")){
				h = parseInt(h, 10)+"px";
			}
			cell.widgetHeight = h;
		}
	};
})();
<commit_msg>When grid creates an editor based on a _Widget, pass in dir/lang settings of grid itself.   Refs #10880 !strict.<commit_after>dojo.provide("dojox.grid.cells.dijit");

dojo.require("dojox.grid.cells");

// TODO: shouldn't it be the test file's job to require these modules,
// if it is using them?  Most of these modules aren't referenced by this file.

dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.form.TimeTextBox");
dojo.require("dijit.form.ComboBox");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.NumberSpinner");
dojo.require("dijit.form.NumberTextBox");
dojo.require("dijit.form.CurrencyTextBox");
dojo.require("dijit.form.HorizontalSlider");
dojo.require("dijit.Editor");

(function(){
	var dgc = dojox.grid.cells;
	dojo.declare("dojox.grid.cells._Widget", dgc._Base, {
		widgetClass: dijit.form.TextBox,
		constructor: function(inCell){
			this.widget = null;
			if(typeof this.widgetClass == "string"){
				dojo.deprecated("Passing a string to widgetClass is deprecated", "pass the widget class object instead", "2.0");
				this.widgetClass = dojo.getObject(this.widgetClass);
			}
		},
		formatEditing: function(inDatum, inRowIndex){
			this.needFormatNode(inDatum, inRowIndex);
			return "

";
		},
		getValue: function(inRowIndex){
			return this.widget.attr('value');
		},
		setValue: function(inRowIndex, inValue){
			if(this.widget&&this.widget.attr){
				//Look for lazy-loading editor and handle it via its deferred.
				if(this.widget.onLoadDeferred){
					var self = this;
					this.widget.onLoadDeferred.addCallback(function(){
						self.widget.attr("value",inValue===null?"":inValue);
					});
				}else{
					this.widget.attr("value", inValue);
				}
			}else{
				this.inherited(arguments);
			}
		},
		getWidgetProps: function(inDatum){
			return dojo.mixin(
				{
					dir: this.dir,
					lang: this.lang
				},
				this.widgetProps||{},
				{
					constraints: dojo.mixin({}, this.constraint) || {}, //TODO: really just for ValidationTextBoxes
					value: inDatum
				}
			);
		},
		createWidget: function(inNode, inDatum, inRowIndex){
			return new this.widgetClass(this.getWidgetProps(inDatum), inNode);
		},
		attachWidget: function(inNode, inDatum, inRowIndex){
			inNode.appendChild(this.widget.domNode);
			this.setValue(inRowIndex, inDatum);
		},
		formatNode: function(inNode, inDatum, inRowIndex){
			if(!this.widgetClass){
				return inDatum;
			}
			if(!this.widget){
				this.widget = this.createWidget.apply(this, arguments);
			}else{
				this.attachWidget.apply(this, arguments);
			}
			this.sizeWidget.apply(this, arguments);
			this.grid.rowHeightChanged(inRowIndex);
			this.focus();
			return undefined;
		},
		sizeWidget: function(inNode, inDatum, inRowIndex){
			var
				p = this.getNode(inRowIndex),
				box = dojo.contentBox(p);
			dojo.marginBox(this.widget.domNode, {w: box.w});
		},
		focus: function(inRowIndex, inNode){
			if(this.widget){
				setTimeout(dojo.hitch(this.widget, function(){
					dojox.grid.util.fire(this, "focus");
				}), 0);
			}
		},
		_finish: function(inRowIndex){
			this.inherited(arguments);
			dojox.grid.util.removeNode(this.widget.domNode);
		}
	});
	dgc._Widget.markupFactory = function(node, cell){
		dgc._Base.markupFactory(node, cell);
		var d = dojo;
		var widgetProps = d.trim(d.attr(node, "widgetProps")||"");
		var constraint = d.trim(d.attr(node, "constraint")||"");
		var widgetClass = d.trim(d.attr(node, "widgetClass")||"");
		if(widgetProps){
			cell.widgetProps = d.fromJson(widgetProps);
		}
		if(constraint){
			cell.constraint = d.fromJson(constraint);
		}
		if(widgetClass){
			cell.widgetClass = d.getObject(widgetClass);
		}
	};

	dojo.declare("dojox.grid.cells.ComboBox", dgc._Widget, {
		widgetClass: dijit.form.ComboBox,
		getWidgetProps: function(inDatum){
			var items=[];
			dojo.forEach(this.options, function(o){
				items.push({name: o, value: o});
			});
			var store = new dojo.data.ItemFileReadStore({data: {identifier:"name", items: items}});
			return dojo.mixin({}, this.widgetProps||{}, {
				value: inDatum,
				store: store
			});
		},
		getValue: function(){
			var e = this.widget;
			// make sure to apply the displayed value
			e.attr('displayedValue', e.attr('displayedValue'));
			return e.attr('value');
		}
	});
	dgc.ComboBox.markupFactory = function(node, cell){
		dgc._Widget.markupFactory(node, cell);
		var d=dojo;
		var options = d.trim(d.attr(node, "options")||"");
		if(options){
			var o = options.split(',');
			if(o[0] != options){
				cell.options = o;
			}
		}
	};

	dojo.declare("dojox.grid.cells.DateTextBox", dgc._Widget, {
		widgetClass: dijit.form.DateTextBox,
		setValue: function(inRowIndex, inValue){
			if(this.widget){
				this.widget.attr('value', new Date(inValue));
			}else{
				this.inherited(arguments);
			}
		},
		getWidgetProps: function(inDatum){
			return dojo.mixin(this.inherited(arguments), {
				value: new Date(inDatum)
			});
		}
	});
	dgc.DateTextBox.markupFactory = function(node, cell){
		dgc._Widget.markupFactory(node, cell);
	};

	dojo.declare("dojox.grid.cells.CheckBox", dgc._Widget, {
		widgetClass: dijit.form.CheckBox,
		getValue: function(){
			return this.widget.checked;
		},
		setValue: function(inRowIndex, inValue){
			if(this.widget&&this.widget.attributeMap.checked){
				this.widget.attr("checked", inValue);
			}else{
				this.inherited(arguments);
			}
		},
		sizeWidget: function(inNode, inDatum, inRowIndex){
			return;
		}
	});
	dgc.CheckBox.markupFactory = function(node, cell){
		dgc._Widget.markupFactory(node, cell);
	};

	dojo.declare("dojox.grid.cells.Editor", dgc._Widget, {
		widgetClass: dijit.Editor,
		getWidgetProps: function(inDatum){
			return dojo.mixin({}, this.widgetProps||{}, {
				height: this.widgetHeight || "100px"
			});
		},
		createWidget: function(inNode, inDatum, inRowIndex){
			// widget needs its value set after creation
			var widget = new this.widgetClass(this.getWidgetProps(inDatum), inNode);
			dojo.connect(widget, 'onLoad', dojo.hitch(this, 'populateEditor'));
			return widget;
		},
		formatNode: function(inNode, inDatum, inRowIndex){
			this.content = inDatum;
			this.inherited(arguments);
			if(dojo.isMoz){
				// FIXME: seem to need to reopen the editor and display the toolbar
				var e = this.widget;
				e.open();
				if(this.widgetToolbar){
					dojo.place(e.toolbar.domNode, e.editingArea, "before");
				}
			}
		},
		populateEditor: function(){
			this.widget.attr('value', this.content);
			this.widget.placeCursorAtEnd();
		}
	});
	dgc.Editor.markupFactory = function(node, cell){
		dgc._Widget.markupFactory(node, cell);
		var d = dojo;
		var h = dojo.trim(dojo.attr(node, "widgetHeight")||"");
		if(h){
			if((h != "auto")&&(h.substr(-2) != "em")){
				h = parseInt(h, 10)+"px";
			}
			cell.widgetHeight = h;
		}
	};
})();
<|endoftext|>


<commit_before>module.exports = (function() {
    'use strict';

    // Module dependencies
    var crypto  = require('crypto'),
        request = require('request'),
        nonce   = require('nonce')();

    // Constants
    var version         = '0.0.8',
        PUBLIC_API_URL  = 'https://poloniex.com/public',
        PRIVATE_API_URL = 'https://poloniex.com/tradingApi',
        USER_AGENT      = 'poloniex.js ' + version;
        //USER_AGENT    = 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0'

    // Helper methods
    function joinCurrencies(currencyA, currencyB) {
        // If only one arg, then return the first
        if (typeof currencyB !== 'string') {
            return currencyA;
        }

        return currencyA + '_' + currencyB;
    }

    // Constructor
    function Poloniex(key, secret) {
        // Generate headers signed by this user's key and secret.
        // The secret is encapsulated and never exposed
        this._getPrivateHeaders = function(parameters) {
            var paramString, signature;

            if (!key || !secret) {
                throw 'Poloniex: Error. API key and secret required';
            }

            // Convert to `arg1=foo&arg2=bar`
            paramString = Object.keys(parameters).map(function(param) {
                return encodeURIComponent(param) + '=' + encodeURIComponent(parameters[param]);
            }).join('&');

            signature = crypto.createHmac('sha512', secret).update(paramString).digest('hex');

            return {
                Key: key,
                Sign: signature
            };
        };
    }

    // Currently, this fails with `Error: CERT_UNTRUSTED`
    // Poloniex.STRICT_SSL can be set to `false` to avoid this. Use with caution.
    // Will be removed in future, once this is resolved.
    Poloniex.STRICT_SSL = true;

    // Customisable user agent string
    Poloniex.USER_AGENT = USER_AGENT;

    // Prototype
    Poloniex.prototype = {
        constructor: Poloniex,

        // Make an API request
        _request: function(options, callback) {
            if (!('headers' in options)) {
                options.headers = {};
            }

            options.json = true;
            options.headers['User-Agent'] = Poloniex.USER_AGENT;
            options.strictSSL = Poloniex.STRICT_SSL;
            options.timeout = 10 * 1000;

            request(options, function(err, response, body) {
            // Empty response
            if (!err && (typeof body === 'undefined' || body === null)){
            err = 'Empty response';
            }

            callback(err, body);
        });

            return this;
        },

        // Make a public API request
        _public: function(command, parameters, callback) {
            var options;

            if (typeof parameters === 'function') {
                callback = parameters;
                parameters = {};
            }

            parameters || (parameters = {});
            parameters.command = command;
            options = {
                method: 'GET',
                url: PUBLIC_API_URL,
                qs: parameters
            };

            options.qs.command = command;
            return this._request(options, callback);
        },

        // Make a private API request
        _private: function(command, parameters, callback) {
            var options;

            if (typeof parameters === 'function') {
                callback = parameters;
                parameters = {};
            }

            parameters || (parameters = {});
            parameters.command = command;
            parameters.nonce = nonce();

            options = {
                method: 'POST',
                url: PRIVATE_API_URL,
                form: parameters,
                headers: this._getPrivateHeaders(parameters)
            };

            return this._request(options, callback);
        },

        /////
        // PUBLIC METHODS

        returnTicker: function(callback) {
            return this._public('returnTicker', callback);
        },

        return24hVolume: function(callback) {
            return this._public('return24hVolume', callback);
        },

        returnOrderBook: function(currencyA, currencyB, callback) {
            var parameters = {
        currencyPair: joinCurrencies(currencyA, currencyB)
        };

            return this._public('returnOrderBook', parameters, callback);
        },

        returnChartData: function(currencyA, currencyB, period, start, end, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
        period: period,
        start: start,
        end: end
            };

            return this._public('returnChartData', parameters, callback);
        },

        returnCurrencies: function(callback) {
            return this._public('returnCurrencies', callback);
        },

        returnLoanOrders: function(currency, callback) {
            return this._public('returnLoanOrders', {currency: currency}, callback);
        },

        /////
        // PRIVATE METHODS

        returnBalances: function(callback) {
            return this._private('returnBalances', {}, callback);
        },

    returnCompleteBalances: function(callback) {
            return this._private('returnCompleteBalances', {}, callback);
        },

        returnDepositAddresses: function(callback) {
            return this._private('returnDepositAddresses', {}, callback);
        },

        generateNewAddress: function(currency, callback) {
            return this._private('returnDepositsWithdrawals', {currency: currency}, callback);
        },

        returnDepositsWithdrawals: function(start, end, callback) {
            return this._private('returnDepositsWithdrawals', {start: start, end: end}, callback);
        },

        returnOpenOrders: function(currencyA, currencyB, callback) {
            var parameters = {
              currencyPair: joinCurrencies(currencyA, currencyB)
            };

            return this._private('returnOpenOrders', parameters, callback);
        },

        returnTradeHistory: function(currencyA, currencyB, start, end, callback) {
            if(arguments.length < 5){
                callback = start;
                start = Date.now() / 1000 - 60 * 60;
                end = Date.now() / 1000 + 60 * 60; // Some buffer in case of client/server time out of sync.
            }

            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                start: start,
                end: end
            };

            return this._private('returnTradeHistory', parameters, callback);
        },

        returnOrderTrades: function(orderNumber, callback) {
            var parameters = {
                orderNumber: orderNumber
            };

            return this._private('returnOrderTrades', parameters, callback);
        },

        buy: function(currencyA, currencyB, rate, amount, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                rate: rate,
                amount: amount
            };

            return this._private('buy', parameters, callback);
        },

        sell: function(currencyA, currencyB, rate, amount, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                rate: rate,
                amount: amount
            };

            return this._private('sell', parameters, callback);
        },

        cancelOrder: function(currencyA, currencyB, orderNumber, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                orderNumber: orderNumber
            };

            return this._private('cancelOrder', parameters, callback);
        },

        moveOrder: function(orderNumber, rate, amount, callback) {
            var parameters = {
                orderNumber: orderNumber,
                rate: rate,
                amount: amount ? amount : null
            };

            return this._private('moveOrder', parameters, callback);
        },

        withdraw: function(currency, amount, address, callback) {
            var parameters = {
                currency: currency,
                amount: amount,
                address: address
            };

            return this._private('withdraw', parameters, callback);
        },

        returnFeeInfo: function(callback) {
            return this._private('returnFeeInfo', {}, callback);
        },

        returnAvailableAccountBalances: function(account, callback) {
            var options = {};
            if (account) {
              options.account = account;
            }
            return this._private('returnAvailableAccountBalances', options, callback);
        },

        returnTradableBalances: function(callback) {
            return this._private('returnTradableBalances', {}, callback);
        },

        transferBalance: function(currency, amount, fromAccount, toAccount, callback) {
            var parameters = {
                currency: currency,
                amount: amount,
                fromAccount: fromAccount,
                toAccount: toAccount
            };

            return this._private('transferBalance', parameters, callback);
        },

        returnMarginAccountSummary: function(callback) {
            return this._private('returnMarginAccountSummary', {}, callback);
        },

        marginBuy: function(currencyA, currencyB, rate, amount, lendingRate, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                rate: rate,
                amount: amount,
                lendingRate: lendingRate ? lendingRate : null
            };

            return this._private('marginBuy', parameters, callback);
        },

        marginSell: function(currencyA, currencyB, rate, amount, lendingRate, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                rate: rate,
                amount: amount,
                lendingRate: lendingRate ? lendingRate : null
            };

            return this._private('marginSell', parameters, callback);
        },

        getMarginPosition: function(currencyA, currencyB, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB)
            };

            return this._private('getMarginPosition', parameters, callback);
        },

        closeMarginPosition: function(currencyA, currencyB, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB)
            };

            return this._private('closeMarginPosition', parameters, callback);
        },

        createLoanOffer: function(currency, amount, duration, autoRenew, lendingRate, callback) {
            var parameters = {
                currency: currency,
                amount: amount,
                duration: duration,
                autoRenew: autoRenew,
                lendingRate: lendingRate
            };

            return this._private('createLoanOffer', parameters, callback);
        },

        cancelLoanOffer: function(orderNumber, callback) {
            var parameters = {
                orderNumber: orderNumber
            };

            return this._private('cancelLoanOffer', parameters, callback);
        },

        returnOpenLoanOffers: function(callback) {
            return this._private('returnOpenLoanOffers', {}, callback);
        },

    returnActiveLoans: function(callback) {
            return this._private('returnActiveLoans', {}, callback);
        },

        returnLendingHistory: function(start, end, limit, callback) {
            var parameters = {
                start: start,
                end: end,
                limit: limit
            };

            return this._private('returnLendingHistory', parameters, callback);
        },

    toggleAutoRenew: function(orderNumber, callback) {
            return this._private('toggleAutoRenew', {orderNumber: orderNumber}, callback);
        }

    };

    // Backwards Compatibility
    Poloniex.prototype.getTicker = Poloniex.prototype.returnTicker;
    Poloniex.prototype.get24hVolume = Poloniex.prototype.return24hVolume;
    Poloniex.prototype.getOrderBook = Poloniex.prototype.returnOrderBook;
    Poloniex.prototype.getTradeHistory = Poloniex.prototype.returnChartData;
    Poloniex.prototype.myBalances = Poloniex.prototype.returnBalances;
    Poloniex.prototype.myOpenOrders = Poloniex.prototype.returnOpenOrders;
    Poloniex.prototype.myTradeHistory = Poloniex.prototype.returnTradeHistory;

    return Poloniex;
})();
<commit_msg>Fix generateNewAddress call, closes #28<commit_after>module.exports = (function() {
    'use strict';

    // Module dependencies
    var crypto  = require('crypto'),
        request = require('request'),
        nonce   = require('nonce')();

    // Constants
    var version         = '0.0.8',
        PUBLIC_API_URL  = 'https://poloniex.com/public',
        PRIVATE_API_URL = 'https://poloniex.com/tradingApi',
        USER_AGENT      = 'poloniex.js ' + version;
        //USER_AGENT    = 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0'

    // Helper methods
    function joinCurrencies(currencyA, currencyB) {
        // If only one arg, then return the first
        if (typeof currencyB !== 'string') {
            return currencyA;
        }

        return currencyA + '_' + currencyB;
    }

    // Constructor
    function Poloniex(key, secret) {
        // Generate headers signed by this user's key and secret.
        // The secret is encapsulated and never exposed
        this._getPrivateHeaders = function(parameters) {
            var paramString, signature;

            if (!key || !secret) {
                throw 'Poloniex: Error. API key and secret required';
            }

            // Convert to `arg1=foo&arg2=bar`
            paramString = Object.keys(parameters).map(function(param) {
                return encodeURIComponent(param) + '=' + encodeURIComponent(parameters[param]);
            }).join('&');

            signature = crypto.createHmac('sha512', secret).update(paramString).digest('hex');

            return {
                Key: key,
                Sign: signature
            };
        };
    }

    // Currently, this fails with `Error: CERT_UNTRUSTED`
    // Poloniex.STRICT_SSL can be set to `false` to avoid this. Use with caution.
    // Will be removed in future, once this is resolved.
    Poloniex.STRICT_SSL = true;

    // Customisable user agent string
    Poloniex.USER_AGENT = USER_AGENT;

    // Prototype
    Poloniex.prototype = {
        constructor: Poloniex,

        // Make an API request
        _request: function(options, callback) {
            if (!('headers' in options)) {
                options.headers = {};
            }

            options.json = true;
            options.headers['User-Agent'] = Poloniex.USER_AGENT;
            options.strictSSL = Poloniex.STRICT_SSL;
            options.timeout = 10 * 1000;

            request(options, function(err, response, body) {
            // Empty response
            if (!err && (typeof body === 'undefined' || body === null)){
            err = 'Empty response';
            }

            callback(err, body);
        });

            return this;
        },

        // Make a public API request
        _public: function(command, parameters, callback) {
            var options;

            if (typeof parameters === 'function') {
                callback = parameters;
                parameters = {};
            }

            parameters || (parameters = {});
            parameters.command = command;
            options = {
                method: 'GET',
                url: PUBLIC_API_URL,
                qs: parameters
            };

            options.qs.command = command;
            return this._request(options, callback);
        },

        // Make a private API request
        _private: function(command, parameters, callback) {
            var options;

            if (typeof parameters === 'function') {
                callback = parameters;
                parameters = {};
            }

            parameters || (parameters = {});
            parameters.command = command;
            parameters.nonce = nonce();

            options = {
                method: 'POST',
                url: PRIVATE_API_URL,
                form: parameters,
                headers: this._getPrivateHeaders(parameters)
            };

            return this._request(options, callback);
        },

        /////
        // PUBLIC METHODS

        returnTicker: function(callback) {
            return this._public('returnTicker', callback);
        },

        return24hVolume: function(callback) {
            return this._public('return24hVolume', callback);
        },

        returnOrderBook: function(currencyA, currencyB, callback) {
            var parameters = {
        currencyPair: joinCurrencies(currencyA, currencyB)
        };

            return this._public('returnOrderBook', parameters, callback);
        },

        returnChartData: function(currencyA, currencyB, period, start, end, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
        period: period,
        start: start,
        end: end
            };

            return this._public('returnChartData', parameters, callback);
        },

        returnCurrencies: function(callback) {
            return this._public('returnCurrencies', callback);
        },

        returnLoanOrders: function(currency, callback) {
            return this._public('returnLoanOrders', {currency: currency}, callback);
        },

        /////
        // PRIVATE METHODS

        returnBalances: function(callback) {
            return this._private('returnBalances', {}, callback);
        },

    returnCompleteBalances: function(callback) {
            return this._private('returnCompleteBalances', {}, callback);
        },

        returnDepositAddresses: function(callback) {
            return this._private('returnDepositAddresses', {}, callback);
        },

        generateNewAddress: function(currency, callback) {
            return this._private('generateNewAddress', {currency: currency}, callback);
        },

        returnDepositsWithdrawals: function(start, end, callback) {
            return this._private('returnDepositsWithdrawals', {start: start, end: end}, callback);
        },

        returnOpenOrders: function(currencyA, currencyB, callback) {
            var parameters = {
              currencyPair: joinCurrencies(currencyA, currencyB)
            };

            return this._private('returnOpenOrders', parameters, callback);
        },

        returnTradeHistory: function(currencyA, currencyB, start, end, callback) {
            if(arguments.length < 5){
                callback = start;
                start = Date.now() / 1000 - 60 * 60;
                end = Date.now() / 1000 + 60 * 60; // Some buffer in case of client/server time out of sync.
            }

            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                start: start,
                end: end
            };

            return this._private('returnTradeHistory', parameters, callback);
        },

        returnOrderTrades: function(orderNumber, callback) {
            var parameters = {
                orderNumber: orderNumber
            };

            return this._private('returnOrderTrades', parameters, callback);
        },

        buy: function(currencyA, currencyB, rate, amount, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                rate: rate,
                amount: amount
            };

            return this._private('buy', parameters, callback);
        },

        sell: function(currencyA, currencyB, rate, amount, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                rate: rate,
                amount: amount
            };

            return this._private('sell', parameters, callback);
        },

        cancelOrder: function(currencyA, currencyB, orderNumber, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                orderNumber: orderNumber
            };

            return this._private('cancelOrder', parameters, callback);
        },

        moveOrder: function(orderNumber, rate, amount, callback) {
            var parameters = {
                orderNumber: orderNumber,
                rate: rate,
                amount: amount ? amount : null
            };

            return this._private('moveOrder', parameters, callback);
        },

        withdraw: function(currency, amount, address, callback) {
            var parameters = {
                currency: currency,
                amount: amount,
                address: address
            };

            return this._private('withdraw', parameters, callback);
        },

        returnFeeInfo: function(callback) {
            return this._private('returnFeeInfo', {}, callback);
        },

        returnAvailableAccountBalances: function(account, callback) {
            var options = {};
            if (account) {
              options.account = account;
            }
            return this._private('returnAvailableAccountBalances', options, callback);
        },

        returnTradableBalances: function(callback) {
            return this._private('returnTradableBalances', {}, callback);
        },

        transferBalance: function(currency, amount, fromAccount, toAccount, callback) {
            var parameters = {
                currency: currency,
                amount: amount,
                fromAccount: fromAccount,
                toAccount: toAccount
            };

            return this._private('transferBalance', parameters, callback);
        },

        returnMarginAccountSummary: function(callback) {
            return this._private('returnMarginAccountSummary', {}, callback);
        },

        marginBuy: function(currencyA, currencyB, rate, amount, lendingRate, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                rate: rate,
                amount: amount,
                lendingRate: lendingRate ? lendingRate : null
            };

            return this._private('marginBuy', parameters, callback);
        },

        marginSell: function(currencyA, currencyB, rate, amount, lendingRate, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB),
                rate: rate,
                amount: amount,
                lendingRate: lendingRate ? lendingRate : null
            };

            return this._private('marginSell', parameters, callback);
        },

        getMarginPosition: function(currencyA, currencyB, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB)
            };

            return this._private('getMarginPosition', parameters, callback);
        },

        closeMarginPosition: function(currencyA, currencyB, callback) {
            var parameters = {
                currencyPair: joinCurrencies(currencyA, currencyB)
            };

            return this._private('closeMarginPosition', parameters, callback);
        },

        createLoanOffer: function(currency, amount, duration, autoRenew, lendingRate, callback) {
            var parameters = {
                currency: currency,
                amount: amount,
                duration: duration,
                autoRenew: autoRenew,
                lendingRate: lendingRate
            };

            return this._private('createLoanOffer', parameters, callback);
        },

        cancelLoanOffer: function(orderNumber, callback) {
            var parameters = {
                orderNumber: orderNumber
            };

            return this._private('cancelLoanOffer', parameters, callback);
        },

        returnOpenLoanOffers: function(callback) {
            return this._private('returnOpenLoanOffers', {}, callback);
        },

    returnActiveLoans: function(callback) {
            return this._private('returnActiveLoans', {}, callback);
        },

        returnLendingHistory: function(start, end, limit, callback) {
            var parameters = {
                start: start,
                end: end,
                limit: limit
            };

            return this._private('returnLendingHistory', parameters, callback);
        },

    toggleAutoRenew: function(orderNumber, callback) {
            return this._private('toggleAutoRenew', {orderNumber: orderNumber}, callback);
        }

    };

    // Backwards Compatibility
    Poloniex.prototype.getTicker = Poloniex.prototype.returnTicker;
    Poloniex.prototype.get24hVolume = Poloniex.prototype.return24hVolume;
    Poloniex.prototype.getOrderBook = Poloniex.prototype.returnOrderBook;
    Poloniex.prototype.getTradeHistory = Poloniex.prototype.returnChartData;
    Poloniex.prototype.myBalances = Poloniex.prototype.returnBalances;
    Poloniex.prototype.myOpenOrders = Poloniex.prototype.returnOpenOrders;
    Poloniex.prototype.myTradeHistory = Poloniex.prototype.returnTradeHistory;

    return Poloniex;
})();
<|endoftext|>


<commit_before>// TODO:
// - Enable check for empty namespaces with RegExp instead of Array.indexOf()
// - Update *removeListener* to support namespaced events
// - Update *listener* to support namespaced events

;!function(root) {

  var EventEmitter2 = root.EventEmitter2 = function EventEmitter2(conf) {
    this.initializeEvents(conf);
  };

  EventEmitter2.prototype.initializeEvents = function(conf) {
    conf = conf || {};
    this.setEventDelimiter(conf.delimiter);
    this._eventCaseSensitive = conf.eventCaseSensitive || false;
    this._eventDelimiter = conf.eventDelimiter || '.';
    this._maxListeners = conf.maxListeners === 0 ? 0 : conf.maxListeners || 10;
    this._listeners = {};
    return this;
  }

  EventEmitter2.prototype.addListener = function(event, listener) {

    // If the listener is not a function throw an error. A listener that is not
    // a function can not be called when an event is emitted and therefor is
    // not allowed to be added.
    if ('function' !== typeof listener) {
      throw new Error('addListener only accepts instances of Function');
    }

    // If *_listeners* is undefined invoke *initializeEvents* to set the
    // default properties.
    if (!this._listeners) this.initializeEvents();

    // Set variables.
    var delimiter = this._eventDelimiter,
        caseSensative = this._eventCaseSensitive,
        listeners = this._listeners,
        maxListeners = this._maxListeners,
        event = caseSensative ? event.toLowerCase() : event,
        ns, exploreNs = listeners,
        listenToEvent, eventListeners;

    // If an event starts or ends with a delimiter character throw an error.
    // Starting or ending an event with a delimiter character creates empty
    // namespaces which don't work and therefor are not allowed.
    if (event[event.length-1] === delimiter || event[0] === delimiter) {
      this.eventNameError('addListener');
      return false;
    }

    // If the event is namespaced loop through the namespaces, set seperate
    // events for each namespace and set *listenToEvent* to the last
    // namespace to attach the listener function to this event after the loop.
    if (~event.indexOf(delimiter)) {

      // Split the event into a namespace array for looping.
      ns = event.split(delimiter);

      // If an event contains an empty namespace throw an error. Using two or
      // more delimiters like for example ".." is incorrect and therefor not
      // allowed.
      // if (~ns.indexOf('')) {
      //   this.eventNameError('addListener');
      //   return false;
      // }

      // Loop through the namespaces.
      for (var i = 0, l = ns.length; i < l; i++) {

        // If the event is undefined in *exploreNs* it means it doesn't exist
        // in *listeners* so a new event should be created.
        if (!exploreNs[ns[i]]) {
          exploreNs[ns[i]] = {
              _name: ns[i],
              _fn: [],
              _ns: {}
            };
        }

        // If the loop is at the end set *listenToEvent* to the current
        // namespace - which is the last one - to attach the listener to this
        // event. If the loop is not at the end rebase *exploreNs* to loop the
        // current event's namespaces.
        if (i === ns.length - 1) {
          listenToEvent = exploreNs[ns[i]];
        } else {
          exploreNs = exploreNs[ns[i]]._ns;
        }
      }
    }

    // If the event is not namespaced set the single event and set
    // *listenToEvent* to this event to attach the listener to.
    else {

      // If the event is undefined in *listeners* it means it doesn't exist
      // so a new event should be created.
      if (!listeners[event]) {
        listeners[event] = {
          _name: event,
          _fn: [],
          _ns: {}
        };
      }

      // Set *listenToEvent* to the current event to attach the listener to.
      listenToEvent = listeners[event];
    }

    eventListeners = listenToEvent._fn;

    // Signal that a new listener is being added.
    this.emit('newListener', event, listener);

    // If the max amount of listeners has been reached signal and return to
    // cancel the addition of this new event.
    if (eventListeners.length >= maxListeners) {
      this.emit('maxListeners', event);
      return this;
    }

    // Add the listener to the event.
    eventListeners.push(listener);
    return this;
  };

  EventEmitter2.prototype.on = EventEmitter2.prototype.addListener;

  EventEmitter2.prototype.once = function(event, listener) {
    this.many(event, 1, listener);
    return this;
  };

  EventEmitter2.prototype.many = function(event, ttl, listener) {
    var self = this;

    this.addListener(event, function() {
      if(ttl-- == 0) {
        self.removeListener(event, listener);
      } else {
        listener.apply(null, arguments);
      }
    });

    return this;
  };

  EventEmitter2.prototype.emit = function(event) {
    var self = this,
        args = arguments,
        i = 0,
        delimiter = this._eventDelimiter,
        caseSensitive = this._eventCaseSensitive,
        listeners = this._listeners,
        ns, exploreNs = [listeners], collectedListeners = [],
        invoked = false;

    // If no listeners are defined the emit will not be able to invoke a
    // function. Therefore return *invoked* to exit.
    if (!listeners) return invoked;

    // If an event starts or ends with a delimiter character throw an error.
    // Starting or ending an event with a delimiter character creates empty
    // namespaces which don't work and therefor are not allowed.
    if (event[event.length-1] === delimiter || event[0] === delimiter) {
      this.eventNameError('emit');
      return false;
    }

    // If the event is namespaced loop through the namespaces, find all the
    // listeners for the namespaces and wildcards and add them to the
    // *collectedListeners* array for listener invocation after the loop.
    if (~event.indexOf(delimiter) || event === '*') {

      // Split the event into a namespace array for looping.
      ns = event.split(delimiter);

      // If an event contains an empty namespace throw an error. Using two or
      // more delimiters like for example ".." is incorrect and therefor not
      // allowed.
      // if (~ns.indexOf('')) {
      //   this.eventNameError('addListener');
      //   return false;
      // }

      // Loop through the namespaces.
      for (i = 0; i < ns.length; i++) {

        // While looping through the namespace array loop through *exploreNs*
        // with *i* as well. This is basicaly the same as looping through the
        // the different levels of *events*. *collectedNs* is used to collect
        // all the namespaces that are going to be explored for the next level
        // of *events*.
        var currentNs = ns[i],
            currentExploreNs = exploreNs[i],
            collectedNs = [];

        // Loop through the current level of *events*.
        for (var key1 in currentExploreNs) {

          // Set the current namespace in *events* that is being explored.
          var exploredNs = currentExploreNs[key1],
              name = caseSensitive ? exploredNs._name.toLowerCase() : exploredNs._name;

          // If there is a match for the namespace or a wildcard collect the
          // next level of namespaces or collect the listeners of this
          // particular namespace.
          if (currentNs === '*' || (name === currentNs || name === '*')) {

            // If the loop is at the end collect the listeners for this
            // particular event and add them to the *collectedListeners* array
            // for listener invocation after the loop. If the loop is not at
            // the end collect the next level of namespaces.
            if (i === ns.length - 1) {
              var listeners = exploredNs._fn;
              if (listeners.length > 0) {
                collectedListeners = collectedListeners.concat(listeners);
              }
            } else {
              for (var key2 in exploredNs._ns) {
                collectedNs.push(exploredNs._ns[key2]);
              }
            }
          }
        }

        exploreNs.push(collectedNs);
      }
    }

    // If the event is not namespaced collect all the listeners for this
    // particular event and from the wildcard event and add them to
    // the *collectedListeners* array for listener invocation.
    else if (event !== '*' && event !== 'all' && listeners[event] && listeners[event]._fn.length > 0) {
      if (listeners['*'] && listeners['*']._fn.length > 0) {
        collectedListeners = collectedListeners.concat(listeners['*']._fn);
      }
      collectedListeners = collectedListeners.concat(listeners[event]._fn);
    }

    // If the event is "all" fire all events?
    if (event === 'all') {}

    // Loop through the collected listeners and invoke them.
    for (i = 0, l = collectedListeners.length; i < l; i++) {
      collectedListeners[i].apply(this, args);
      invoked = true;
    }

    // If a listener "all" is defined in *events* invoke its functions.
    if (listeners['all'] && listeners['all']._fn.length > 0){
      for (i = 0, l = listeners['all']._fn.length; i < l; i++) {
        listeners['all']._fn[i].apply(this, args);
        invoked = true;
      }
    }

    return invoked;
  };

  EventEmitter2.prototype.removeListener = function(event, listener) {
    if(listener && this._listeners[event] && this._listeners[event]._fn) {
      var listeners = this._listeners[event]._fn;

      for(var i = 0, l = listeners.length; i < l; i++) {
        if(listener === listeners[i]) {
          // Break out and return the removed listener.
          return listeners.splice(i, 1);
        }
      }
    } else {
      this._listeners[event] = {};
    }
    return this;
  };

  EventEmitter2.prototype.un = EventEmitter2.prototype.removeListener;

  EventEmitter2.prototype.removeAllListeners = function() {
    this._listeners = {};
    return this;
  };

  EventEmitter2.prototype.setEventDelimiter = function(delimiter) {
    if (delimiter === '*' && delimiter.length === 1) {
      throw new Error('setEventDelimiter doesn\'t accept a "*" (wild-card) character');
    } else {
      this._eventDelimiter = delimiter;
    }
    return this;
  };

  EventEmitter2.prototype.setEventCaseSensitive = function(caseSensative) {
    this._eventCaseSensitive = caseSensative;
    return this;
  };

  EventEmitter2.prototype.setMaxListeners = function(n) {
    this._maxListeners = n;
    return this;
  };

  EventEmitter2.prototype.listeners = function(event) {
    if(this._listeners[event]) {
      return this._listeners[event]._fn;
    } else {
      return false;
    }
  };

  EventEmitter2.prototype.eventNameError = function(fn) {
    throw new Error(fn + ' doesn\'t accept empty namespaces or events starting or ending with a "' + this._eventDelimiter + '" (delimiter) character ');
  };

}(typeof exports === 'undefined' ? window : exports);
<commit_msg>me becomes self<commit_after>// TODO:
// - Enable check for empty namespaces with RegExp instead of Array.indexOf()
// - Update *removeListener* to support namespaced events
// - Update *listener* to support namespaced events

;!function(root) {

  var EventEmitter2 = root.EventEmitter2 = function EventEmitter2(conf) {
    this.initializeEvents(conf);
  };

  EventEmitter2.prototype.initializeEvents = function(conf) {
    conf = conf || {};
    var self = this;
    self.setEventDelimiter(conf.delimiter);
    self._eventCaseSensitive = conf.eventCaseSensitive || false;
    self._eventDelimiter = conf.eventDelimiter || '.';
    self._maxListeners = conf.maxListeners === 0 ? 0 : conf.maxListeners || 10;
    self._listeners = {};
    return self;
  }

  EventEmitter2.prototype.addListener = function(event, listener) {
    var self = this;

    // If the listener is not a function throw an error. A listener that is not
    // a function can not be called when an event is emitted and therefor is
    // not allowed to be added.
    if ('function' !== typeof listener) {
      throw new Error('addListener only accepts instances of Function');
    }

    // If *_listeners* is undefined invoke *initializeEvents* to set the
    // default properties.
    if (!self._listeners) self.initializeEvents();

    // Set variables.
    var delimiter = self._eventDelimiter,
        caseSensative = self._eventCaseSensitive,
        listeners = self._listeners,
        maxListeners = self._maxListeners,
        event = caseSensative ? event.toLowerCase() : event,
        ns, exploreNs = listeners,
        listenToEvent, eventListeners;

    // If an event starts or ends with a delimiter character throw an error.
    // Starting or ending an event with a delimiter character creates empty
    // namespaces which don't work and therefor are not allowed.
    if (event[event.length-1] === delimiter || event[0] === delimiter) {
      self.eventNameError('addListener');
      return false;
    }

    // If the event is namespaced loop through the namespaces, set seperate
    // events for each namespace and set *listenToEvent* to the last
    // namespace to attach the listener function to this event after the loop.
    if (~event.indexOf(delimiter)) {

      // Split the event into a namespace array for looping.
      ns = event.split(delimiter);

      // If an event contains an empty namespace throw an error. Using two or
      // more delimiters like for example ".." is incorrect and therefor not
      // allowed.
      // if (~ns.indexOf('')) {
      //   self.eventNameError('addListener');
      //   return false;
      // }

      // Loop through the namespaces.
      for (var i = 0, l = ns.length; i < l; i++) {

        // If the event is undefined in *exploreNs* it means it doesn't exist
        // in *listeners* so a new event should be created.
        if (!exploreNs[ns[i]]) {
          exploreNs[ns[i]] = {
              _name: ns[i],
              _fn: [],
              _ns: {}
            };
        }

        // If the loop is at the end set *listenToEvent* to the current
        // namespace - which is the last one - to attach the listener to this
        // event. If the loop is not at the end rebase *exploreNs* to loop the
        // current event's namespaces.
        if (i === ns.length - 1) {
          listenToEvent = exploreNs[ns[i]];
        } else {
          exploreNs = exploreNs[ns[i]]._ns;
        }
      }
    }

    // If the event is not namespaced set the single event and set
    // *listenToEvent* to this event to attach the listener to.
    else {

      // If the event is undefined in *listeners* it means it doesn't exist
      // so a new event should be created.
      if (!listeners[event]) {
        listeners[event] = {
          _name: event,
          _fn: [],
          _ns: {}
        };
      }

      // Set *listenToEvent* to the current event to attach the listener to.
      listenToEvent = listeners[event];
    }

    eventListeners = listenToEvent._fn;

    // Signal that a new listener is being added.
    self.emit('newListener', event, listener);

    // If the max amount of listeners has been reached signal and return to
    // cancel the addition of this new event.
    if (eventListeners.length >= maxListeners) {
      self.emit('maxListeners', event);
      return self;
    }

    // Add the listener to the event.
    eventListeners.push(listener);
    return self;
  };

  EventEmitter2.prototype.on = EventEmitter2.prototype.addListener;

  EventEmitter2.prototype.once = function(event, listener) {
    this.many(event, 1, listener);
    return this;
  };

  EventEmitter2.prototype.many = function(event, ttl, listener) {
    var self = this;

    self.addListener(event, function() {
      if(ttl-- == 0) {
        self.removeListener(event, listener);
      } else {
        listener.apply(null, arguments);
      }
    });

    return self;
  };

  EventEmitter2.prototype.emit = function(event) {
    var self = this,
        args = arguments,
        i = 0,
        delimiter = self._eventDelimiter,
        caseSensitive = self._eventCaseSensitive,
        listeners = self._listeners,
        ns, exploreNs = [listeners], collectedListeners = [],
        invoked = false;

    // If no listeners are defined the emit will not be able to invoke a
    // function. Therefore return *invoked* to exit.
    if (!listeners) return invoked;

    // If an event starts or ends with a delimiter character throw an error.
    // Starting or ending an event with a delimiter character creates empty
    // namespaces which don't work and therefor are not allowed.
    if (event[event.length-1] === delimiter || event[0] === delimiter) {
      self.eventNameError('emit');
      return false;
    }

    // If the event is namespaced loop through the namespaces, find all the
    // listeners for the namespaces and wildcards and add them to the
    // *collectedListeners* array for listener invocation after the loop.
    if (~event.indexOf(delimiter) || event === '*') {

      // Split the event into a namespace array for looping.
      ns = event.split(delimiter);

      // If an event contains an empty namespace throw an error. Using two or
      // more delimiters like for example ".." is incorrect and therefor not
      // allowed.
      // if (~ns.indexOf('')) {
      //   self.eventNameError('addListener');
      //   return false;
      // }

      // Loop through the namespaces.
      for (i = 0; i < ns.length; i++) {

        // While looping through the namespace array loop through *exploreNs*
        // with *i* as well. This is basicaly the same as looping through the
        // the different levels of *events*. *collectedNs* is used to collect
        // all the namespaces that are going to be explored for the next level
        // of *events*.
        var currentNs = ns[i],
            currentExploreNs = exploreNs[i],
            collectedNs = [];

        // Loop through the current level of *events*.
        for (var key1 in currentExploreNs) {

          // Set the current namespace in *events* that is being explored.
          var exploredNs = currentExploreNs[key1],
              name = caseSensitive ? exploredNs._naself.toLowerCase() : exploredNs._name;

          // If there is a match for the namespace or a wildcard collect the
          // next level of namespaces or collect the listeners of this
          // particular namespace.
          if (currentNs === '*' || (name === currentNs || name === '*')) {

            // If the loop is at the end collect the listeners for this
            // particular event and add them to the *collectedListeners* array
            // for listener invocation after the loop. If the loop is not at
            // the end collect the next level of namespaces.
            if (i === ns.length - 1) {
              var listeners = exploredNs._fn;
              if (listeners.length > 0) {
                collectedListeners = collectedListeners.concat(listeners);
              }
            } else {
              for (var key2 in exploredNs._ns) {
                collectedNs.push(exploredNs._ns[key2]);
              }
            }
          }
        }

        exploreNs.push(collectedNs);
      }
    }

    // If the event is not namespaced collect all the listeners for this
    // particular event and from the wildcard event and add them to
    // the *collectedListeners* array for listener invocation.
    else if (event !== '*' && event !== 'all' && listeners[event] && listeners[event]._fn.length > 0) {
      if (listeners['*'] && listeners['*']._fn.length > 0) {
        collectedListeners = collectedListeners.concat(listeners['*']._fn);
      }
      collectedListeners = collectedListeners.concat(listeners[event]._fn);
    }

    // If the event is "all" fire all events?
    if (event === 'all') {}

    // Loop through the collected listeners and invoke them.
    for (i = 0, l = collectedListeners.length; i < l; i++) {
      collectedListeners[i].apply(self, args);
      invoked = true;
    }

    // If a listener "all" is defined in *events* invoke its functions.
    if (listeners['all'] && listeners['all']._fn.length > 0){
      for (i = 0, l = listeners['all']._fn.length; i < l; i++) {
        listeners['all']._fn[i].apply(self, args);
        invoked = true;
      }
    }

    return invoked;
  };

  EventEmitter2.prototype.removeListener = function(event, listener) {
    var self = this;

    if(listener && self._listeners[event] && self._listeners[event]._fn) {
      var listeners = self._listeners[event]._fn;

      for(var i = 0, l = listeners.length; i < l; i++) {
        if(listener === listeners[i]) {
          // Break out and return the removed listener.
          return listeners.splice(i, 1);
        }
      }
    } else {
      self._listeners[event] = {};
    }
    return self;
  };

  EventEmitter2.prototype.un = EventEmitter2.prototype.removeListener;

  EventEmitter2.prototype.removeAllListeners = function() {
    this._listeners = {};
    return this;
  };

  EventEmitter2.prototype.setEventDelimiter = function(delimiter) {
    if (delimiter === '*' && delimiter.length === 1) {
      throw new Error('setEventDelimiter doesn\'t accept a "*" (wild-card) character');
    } else {
      this._eventDelimiter = delimiter;
    }
    return this;
  };

  EventEmitter2.prototype.setEventCaseSensitive = function(caseSensative) {
    this._eventCaseSensitive = caseSensative;
    return this;
  };

  EventEmitter2.prototype.setMaxListeners = function(n) {
    this._maxListeners = n;
    return this;
  };

  EventEmitter2.prototype.listeners = function(event) {
    if(this._listeners[event]) {
      return this._listeners[event]._fn;
    } else {
      return false;
    }
  };

  EventEmitter2.prototype.eventNameError = function(fn) {
    throw new Error(fn + ' doesn\'t accept empty namespaces or events starting or ending with a "' + this._eventDelimiter + '" (delimiter) character ');
  };

}(typeof exports === 'undefined' ? window : exports);
<|endoftext|>


<commit_before>"use strict";

var testTasks = [
    "exec:testWscript",
    "exec:testRhino"
];
configuration.selenium.forEach(function (browser) {
    testTasks.push("exec:test" + browser.charAt(0).toUpperCase() + browser.substr(1));
});

var legacyVersions = require("fs").readdirSync("test/legacy").map(function (name) {
    return name.substr(0, name.lastIndexOf("."));
});
console.log(legacyVersions);

module.exports = {

    // Linters
    linters: [
        "jshint",
        "eslint"
    ],

    // Code quality tools
    quality: [
        "istanbul",
        "plato"
    ],

    // Tests on sources
    source: [
        "mocha:source"
    ].concat(testTasks),

    // Tests on debug version
    debug: [
        "mocha:debug",
        "mochaTest:debug"
    ].concat(testTasks.map(function (name) {
        return name + "Debug";
    })),

    // Tests on release version
    release: [
        "mocha:release",
        "mochaTest:release"
    ].concat(testTasks.map(function (name) {
        return name + "Release";
    }))
};
<commit_msg>concurrent:legacy<commit_after>"use strict";

var testTasks = [
    "exec:testWscript",
    "exec:testRhino"
];
configuration.selenium.forEach(browser => {
    testTasks.push("exec:test" + browser.charAt(0).toUpperCase() + browser.substr(1));
});

var legacyTasks = [];
require("fs")
    .readdirSync("test/legacy")
    .map(name => name.substr(0, name.lastIndexOf(".")))
    .forEach(version => {
        legacyTasks = legacyTasks.concat(testTasks.map(task => `${task}Legacy:${version}`));
    });

module.exports = {

    // Linters
    linters: [
        "jshint",
        "eslint"
    ],

    // Code quality tools
    quality: [
        "istanbul",
        "plato"
    ],

    // Tests on sources
    source: [
        "mocha:source"
    ].concat(testTasks),

    // Tests on debug version
    debug: [
        "mocha:debug",
        "mochaTest:debug"
    ].concat(testTasks.map(name => name + "Debug")),

    // Tests on release version
    release: [
        "mocha:release",
        "mochaTest:release"
    ].concat(testTasks.map(name => name + "Release")),

    // Tests on legacy test cases
    legacy: legacyTasks

};
<|endoftext|>


<commit_before>var fs      = require('fs');
var path    = require('path');
var http    = require('http');

var poormansDir     = path.normalize(process.env['HOME'] + '/Dropbox/Apps/Poormans/');
var poormansConfig  = path.normalize(poormansDir + 'poormans.md');
var logLevel        = 'info';
var logger          = require('./logger').getLogger(logLevel);
var port            = 1234;

var marked = require('marked');

exports.run = function run()
{
    getVersion(function (version)
    {
        getMarkdownConfig(function(markdownConfig)
        {
            parseMarkdownConfig(markdownConfig,function(configSettings)
            {
                startServer(version, markdownConfig, configSettings);
            });
        });
    });
};

function getVersion(callback)
{
    fs.readFile('package.json', {'encoding': 'UTF-8'}, function (err, packageInfo) {
        if (err) throw err;
        callback(JSON.parse(packageInfo).version);
    });
}

function getMarkdownConfig(callback)
{
    fs.readFile(poormansConfig, {'encoding': 'UTF-8'}, function (err, data)
    {
        if (err) throw err;
        callback(data.toString());
    });
}

function parseMarkdownConfig(markdownConfig,callback)
{
    var config = {
        'Current Media' : { path:'', files:[] }
    };
    var tokens = marked.lexer(markdownConfig);
    var len = tokens.length;
    for ( var i=0; i<len; i++ )
    {
        if ( tokens[i].type == 'heading' && tokens[i].depth==4 && tokens[i+1].type == 'table' )
        {
            i++
            var table  = tokens[i];
            var ncells = table.cells.length;
            for ( var c=0; c<ncells; c++ )
            {
                var cell = table.cells[c];
                if ( !config.hasOwnProperty( cell[0] ) )
                {
                    config[ cell[0] ] = { path:cell[1], files:[] };
                } else {
                    config[ cell[0] ].path = cell[1];
                }
            }
        }
        if ( tokens[i].type == 'heading' && tokens[i].depth==2 )
        {
            var category = tokens[i].text;
            if ( !config.hasOwnProperty( category ) )
            {
                config[ category ] = { path:'', files:[] };
            }
            i++;
            if ( tokens[i].type == 'list_start' )
            {
                i++;
                while( tokens[i].type !== 'list_end' )
                {
                    if ( tokens[i].type == 'list_item_start' )
                    {
                        i++;
                        var file = '';
                        while( tokens[i].type !== 'list_item_end' )
                        {
                            if ( !file && tokens[i].type == 'text' )
                            {
                                file = tokens[i].text;
                            }
                            i++;
                        }
                        if ( file )
                        {
                            config[ category ].files.push(file);
                        }
                    }
                    i++;
                }
            }
        }
    }
    callback(config);
}

function moveFiles(configSettings)
{
    /// match local files to configSettings
    /// using directories listed in config, map all existing local files
    /// move local files to match direcotory locations listed in config
}

function startServer(version, markdownConfig, configSettings)
{

    logger.blank();
    logger.info('Initializing Poormans Media Server (PMS), Version: ' + version);
    logger.info('Listening for changes in ' + poormansDir);
    logger.info('Starting server on port ' + port);
    logger.blank();

    var prevMarkdownConfig = markdownConfig;
    var prevConfigSettings = configSettings;

    function onConfigChange(event,filename)
    {
        configWatcher.close();
        setTimeout(function()
        {
            configWatcher = fs.watch( poormansDir+'poormans.md', onConfigChange );
            logger.info('Detected changes in ' + poormansConfig + ': reloading');
            getMarkdownConfig(function(newMarkdownConfig)
            {
                parseMarkdownConfig(config,function(newConfigSettings)
                {
                    prevMarkdownConfig = markdownConfig;
                    prevConfigSettings = configSettings;

                    markdownConfig = newMarkdownConfig;
                    configSettings = newConfigSettings;
                });
            });
        },500);
    };

    var configWatcher = fs.watch( poormansDir+'poormans.md', onConfigChange );

    http.createServer(function (req, res)
    {
        logger.info(req.method+' '+req.url);
    	if ( req.url=='/favicon.ico' )
    	{
    		var favicon = new Buffer("AAABAAEAEBAAAAEACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAAABoaGgAt7e3AFhYWADr6+sA9PT0AMnJyQBqamoA/f39AHNzcwDS0tIAfHx8ALm5uQBjY2MA9vb2AP///wBTU1MAu7u7AHd3dwBVVVUAvb29APHx8QDPz88AeXl5AIKCggDh4eEAV1dXAOrq6gBgYGAA8/PzAGlpaQD8/PwApqamANra2gC4uLgAwcHBAGtrawD+/v4AdHR0AFJSUgBbW1sAw8PDAHZ2dgDe3t4AVFRUAJqamgDOzs4AeHh4AE1NTQCBgYEAtbW1AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADysmDw8PDw8PDw8PDw8PDysmDw8PDw8mDw8PDw8PDw8mKw8PFx4VDw8PDysmDysPDyYPDwoOBQ8PDysmDw8mKw8PDyYuDigPJismKyYPDyYPKyYrKQciDysmDw8PJg8PDyYPJikHMSwYHwwmDysrJg8PDw8pBwsIAQQaFg8mJg8PDw8PKQcQDw8lHCoZDw8PDw8PDykeIQ8mKy0kLisPKw8PDyYpDgEPKyYgBy4mJg8rDyYrEQ4TAiMiDgkPJisPDysPDzAeFAMNDRMADw8PDw8mDw8nHQYjIxsvDw8PJg8PDw8mDysmKw8PJhImDw8PDw8PDw8mDw8PDysmKw8PKwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",'base64');
    	    res.writeHead(200, {'Content-Type': 'data:image/x-icon;base64'});
    		res.write(favicon);
    		res.end();
    		return;
    	}
    	if ( req.url=='/html' )
        {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(marked(markdownConfig));
            res.end();
            return;
        }
    	if ( req.url=='/json' )
        {
            res.writeHead(200, {'Content-Type': 'text/javascript'});
            res.write(JSON.stringify(configSettings));
            res.end();
            return;
        }
        if ( req.url=='/md' || true ) /// default
        {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.write(markdownConfig);
            res.end();
            return;
        }
    }).listen(port);

    logger.info('Server started');
    logger.info('You can access the current configuration at ' + ('http://localhost:' + port).bold);
}

<commit_msg>typo in config reload variable name<commit_after>var fs      = require('fs');
var path    = require('path');
var http    = require('http');

var poormansDir     = path.normalize(process.env['HOME'] + '/Dropbox/Apps/Poormans/');
var poormansConfig  = path.normalize(poormansDir + 'poormans.md');
var logLevel        = 'info';
var logger          = require('./logger').getLogger(logLevel);
var port            = 1234;

var marked = require('marked');

exports.run = function run()
{
    getVersion(function (version)
    {
        getMarkdownConfig(function(markdownConfig)
        {
            parseMarkdownConfig(markdownConfig,function(configSettings)
            {
                startServer(version, markdownConfig, configSettings);
            });
        });
    });
};

function getVersion(callback)
{
    fs.readFile('package.json', {'encoding': 'UTF-8'}, function (err, packageInfo) {
        if (err) throw err;
        callback(JSON.parse(packageInfo).version);
    });
}

function getMarkdownConfig(callback)
{
    fs.readFile(poormansConfig, {'encoding': 'UTF-8'}, function (err, data)
    {
        if (err) throw err;
        callback(data.toString());
    });
}

function parseMarkdownConfig(markdownConfig,callback)
{
    var config = {
        'Current Media' : { path:'', files:[] }
    };
    var tokens = marked.lexer(markdownConfig);
    var len = tokens.length;
    for ( var i=0; i<len; i++ )
    {
        if ( tokens[i].type == 'heading' && tokens[i].depth==4 && tokens[i+1].type == 'table' )
        {
            i++
            var table  = tokens[i];
            var ncells = table.cells.length;
            for ( var c=0; c<ncells; c++ )
            {
                var cell = table.cells[c];
                if ( !config.hasOwnProperty( cell[0] ) )
                {
                    config[ cell[0] ] = { path:cell[1], files:[] };
                } else {
                    config[ cell[0] ].path = cell[1];
                }
            }
        }
        if ( tokens[i].type == 'heading' && tokens[i].depth==2 )
        {
            var category = tokens[i].text;
            if ( !config.hasOwnProperty( category ) )
            {
                config[ category ] = { path:'', files:[] };
            }
            i++;
            if ( tokens[i].type == 'list_start' )
            {
                i++;
                while( tokens[i].type !== 'list_end' )
                {
                    if ( tokens[i].type == 'list_item_start' )
                    {
                        i++;
                        var file = '';
                        while( tokens[i].type !== 'list_item_end' )
                        {
                            if ( !file && tokens[i].type == 'text' )
                            {
                                file = tokens[i].text;
                            }
                            i++;
                        }
                        if ( file )
                        {
                            config[ category ].files.push(file);
                        }
                    }
                    i++;
                }
            }
        }
    }
    callback(config);
}

function moveFiles(configSettings)
{
    /// match local files to configSettings
    /// using directories listed in config, map all existing local files
    /// move local files to match direcotory locations listed in config
}

function startServer(version, markdownConfig, configSettings)
{

    logger.blank();
    logger.info('Initializing Poormans Media Server (PMS), Version: ' + version);
    logger.info('Listening for changes in ' + poormansDir);
    logger.info('Starting server on port ' + port);
    logger.blank();

    /// don't know if we want to compare diffs or just compare straight to filesystem
    var prevMarkdownConfig = markdownConfig;
    var prevConfigSettings = configSettings;

    /// I was using vim to edit the .md file directly from the Dropbox folder. this caused
    /// two issues.
    /// 1) Node doesn't think the file exists right after a change event,
    /// so I put the fileRead on a half second delay. I haven't tested any different value.
    /// 2) Multiple change events are being fired after a save, so I turn off the listener
    /// after receiving the first event and turn it back on once the timeout is over.
    function onConfigChange(event,filename)
    {
        configWatcher.close();
        setTimeout(function()
        {
            configWatcher = fs.watch( poormansDir+'poormans.md', onConfigChange );
            logger.info('Detected changes in ' + poormansConfig + ': reloading');
            getMarkdownConfig(function(newMarkdownConfig)
            {
                parseMarkdownConfig(newMarkdownConfig,function(newConfigSettings)
                {
                    /// don't know if we want to compare diffs or just compare straight to filesystem
                    prevMarkdownConfig = markdownConfig;
                    prevConfigSettings = configSettings;

                    markdownConfig = newMarkdownConfig;
                    configSettings = newConfigSettings;
                });
            });
        },500);
    };

    var configWatcher = fs.watch( poormansDir+'poormans.md', onConfigChange );

    http.createServer(function (req, res)
    {
        logger.info(req.method+' '+req.url);
    	if ( req.url=='/favicon.ico' )
    	{
    		var favicon = new Buffer("AAABAAEAEBAAAAEACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAAABoaGgAt7e3AFhYWADr6+sA9PT0AMnJyQBqamoA/f39AHNzcwDS0tIAfHx8ALm5uQBjY2MA9vb2AP///wBTU1MAu7u7AHd3dwBVVVUAvb29APHx8QDPz88AeXl5AIKCggDh4eEAV1dXAOrq6gBgYGAA8/PzAGlpaQD8/PwApqamANra2gC4uLgAwcHBAGtrawD+/v4AdHR0AFJSUgBbW1sAw8PDAHZ2dgDe3t4AVFRUAJqamgDOzs4AeHh4AE1NTQCBgYEAtbW1AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADysmDw8PDw8PDw8PDw8PDysmDw8PDw8mDw8PDw8PDw8mKw8PFx4VDw8PDysmDysPDyYPDwoOBQ8PDysmDw8mKw8PDyYuDigPJismKyYPDyYPKyYrKQciDysmDw8PJg8PDyYPJikHMSwYHwwmDysrJg8PDw8pBwsIAQQaFg8mJg8PDw8PKQcQDw8lHCoZDw8PDw8PDykeIQ8mKy0kLisPKw8PDyYpDgEPKyYgBy4mJg8rDyYrEQ4TAiMiDgkPJisPDysPDzAeFAMNDRMADw8PDw8mDw8nHQYjIxsvDw8PJg8PDw8mDysmKw8PJhImDw8PDw8PDw8mDw8PDysmKw8PKwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",'base64');
    	    res.writeHead(200, {'Content-Type': 'data:image/x-icon;base64'});
    		res.write(favicon);
    		res.end();
    		return;
    	}
    	if ( req.url=='/json' )
        {
            res.writeHead(200, {'Content-Type': 'text/javascript'});
            res.write(JSON.stringify(configSettings));
            res.end();
            return;
        }
    	if ( req.url=='/html' )
        {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(marked(markdownConfig));
            res.end();
            return;
        }
        if ( req.url=='/md' || true ) /// default
        {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.write(markdownConfig);
            res.end();
            return;
        }
    }).listen(port);

    logger.info('Server started');
    logger.info('You can access the current configuration at ' + ('http://localhost:' + port+'/(md|html|json)').bold);
}

<|endoftext|>


<commit_before>module.exports = {
	options: {
		concurrent: 10,
		src: 'protected/modules/*/Gruntfile.js'
	},
	default: {
		src: '<%= hub.options.src %>',
		tasks: [
			'default'
		]
	},
	compile: {
		src: '<%= hub.options.src %>',
		tasks: [
			'compile'
		]
	},
	build: {
		src: '<%= hub.options.src %>',
		tasks: [
			'build'
		]
	},
	watch: {
		src: '<%= hub.options.src %>',
		tasks: [
			'watch'
		]
	}
};<commit_msg>Increased amount of hub connections<commit_after>module.exports = {
	options: {
		concurrent: 20,
		src: 'protected/modules/*/Gruntfile.js'
	},
	default: {
		src: '<%= hub.options.src %>',
		tasks: [
			'default'
		]
	},
	compile: {
		src: '<%= hub.options.src %>',
		tasks: [
			'compile'
		]
	},
	build: {
		src: '<%= hub.options.src %>',
		tasks: [
			'build'
		]
	},
	watch: {
		src: '<%= hub.options.src %>',
		tasks: [
			'watch'
		]
	}
};<|endoftext|>


<commit_before>const redis = require('redis');
const path = require('path');
const fs = require('fs');
const once = require('once');

const NodeRateLimiter = require('node-rate-limiter');

const script = fs.readFileSync(path.join(__dirname, 'script.lua'), 'utf-8');

module.exports = RedisAdaptor;

function RedisAdaptor(opts) {
	assert(this instanceof InMemoryAdaptor, 'RedisAdaptor should be created with new keyword: new RedisAdaptor(...)');

    opts = opts || {};
    opts.timeout = opts.timeout || NodeRateLimiter.defaultTimeout;
    opts.client = opts.client || redis.createClient();

    const adaptorOpts = opts;

	this.name = RedisAdaptor.name;

    this.prepare = (callback) => prepare(adaptorOpts, callback);
    this.reset = (id, callback) => reset(adaptorOpts, id, callback);
    this.get = (id, opts, callback) => get(adaptorOpts, id, opts, callback);
}

function reset(adaptorOpts, id, callback) {
    const keyClient = 'noderatelimiter.' + id;
    const keyClientTotal = keyClient + '.total';
    const keyClientLimit = keyClient + '.limit';

    const onDoneOnce = once(onDone);

    adaptorOpts.client
        .multi()
        .del(keyClientTotal)
        .del(keyClientLimit)
        .exec(onDoneOnce);

    let timerId = registerTimeout(`reset(${id})`, adaptorOpts.timeout, onDoneOnce);

    function onDone(err, res) {
        if (timerId) {
            timerId = clearTimeout(timerId);
        }

        callback(err, res);
    }
}

function get(adaptorOpts, id, opts, callback) {
    const limit = opts && opts.limit || NodeRateLimiter.defaultRateLimit;
    const expire = opts && opts.expire || NodeRateLimiter.defaultExpiration;

    const onEvalshaDoneOnce = once(onEvalshaDone);

    adaptorOpts.client.evalsha(adaptorOpts.scriptSha, 3, id, limit, expire, onEvalshaDoneOnce);
    let timerId = registerTimeout(`get(${id}, ${JSON.stringify(opts)})`, adaptorOpts.timeout, onEvalshaDoneOnce);

    function onEvalshaDone(err, res) {
        if (timerId) {
            timerId = clearTimeout(timerId);
        }

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

        const result = {
            limit: res[0],
            remaining: res[0] - res[1] + 1,
            reset: res[2]
        };
        callback(null, result);
    }
}

function prepare(adaptorOpts, callback) {
    if (adaptorOpts.scriptSha) {
        return callback(null);
    }

    adaptorOpts.client.script('load', script, onScriptLoaded);

    function onScriptLoaded(err, sha) {
        if (err) {
            return callback(err);
        }

        adaptorOpts.scriptSha = sha;
        callback(null);
    }
}

function registerTimeout(message, timeout, callback) {
    return setTimeout(() => {
        const error = new NodeRateLimiter.TimeoutError(message, {after: timeout});
        callback(error);
    }, timeout);
}<commit_msg>assert fix<commit_after>const assert = require('assert');
const redis = require('redis');
const path = require('path');
const fs = require('fs');
const once = require('once');

const NodeRateLimiter = require('node-rate-limiter');

const script = fs.readFileSync(path.join(__dirname, 'script.lua'), 'utf-8');

module.exports = RedisAdaptor;

function RedisAdaptor(opts) {
	assert(this instanceof RedisAdaptor, 'RedisAdaptor should be created with new keyword: new RedisAdaptor(...)');

    opts = opts || {};
    opts.timeout = opts.timeout || NodeRateLimiter.defaultTimeout;
    opts.client = opts.client || redis.createClient();

    const adaptorOpts = opts;

	this.name = RedisAdaptor.name;

    this.prepare = (callback) => prepare(adaptorOpts, callback);
    this.reset = (id, callback) => reset(adaptorOpts, id, callback);
    this.get = (id, opts, callback) => get(adaptorOpts, id, opts, callback);
}

function reset(adaptorOpts, id, callback) {
    const keyClient = 'noderatelimiter.' + id;
    const keyClientTotal = keyClient + '.total';
    const keyClientLimit = keyClient + '.limit';

    const onDoneOnce = once(onDone);

    adaptorOpts.client
        .multi()
        .del(keyClientTotal)
        .del(keyClientLimit)
        .exec(onDoneOnce);

    let timerId = registerTimeout(`reset(${id})`, adaptorOpts.timeout, onDoneOnce);

    function onDone(err, res) {
        if (timerId) {
            timerId = clearTimeout(timerId);
        }

        callback(err, res);
    }
}

function get(adaptorOpts, id, opts, callback) {
    const limit = opts && opts.limit || NodeRateLimiter.defaultRateLimit;
    const expire = opts && opts.expire || NodeRateLimiter.defaultExpiration;

    const onEvalshaDoneOnce = once(onEvalshaDone);

    adaptorOpts.client.evalsha(adaptorOpts.scriptSha, 3, id, limit, expire, onEvalshaDoneOnce);
    let timerId = registerTimeout(`get(${id}, ${JSON.stringify(opts)})`, adaptorOpts.timeout, onEvalshaDoneOnce);

    function onEvalshaDone(err, res) {
        if (timerId) {
            timerId = clearTimeout(timerId);
        }

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

        const result = {
            limit: res[0],
            remaining: res[0] - res[1] + 1,
            reset: res[2]
        };
        callback(null, result);
    }
}

function prepare(adaptorOpts, callback) {
    if (adaptorOpts.scriptSha) {
        return callback(null);
    }

    adaptorOpts.client.script('load', script, onScriptLoaded);

    function onScriptLoaded(err, sha) {
        if (err) {
            return callback(err);
        }

        adaptorOpts.scriptSha = sha;
        callback(null);
    }
}

function registerTimeout(message, timeout, callback) {
    return setTimeout(() => {
        const error = new NodeRateLimiter.TimeoutError(message, {after: timeout});
        callback(error);
    }, timeout);
}<|endoftext|>