<commit_before>/*jshint bitwise: true, camelcase: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, regexp: true, undef: true, unused: true, strict: true*/
/*global define*/
define(function () {

    "use strict";

    function error(msg, form) {
        // TODO: add line/char details to forms for better errors
        throw new Error(msg);
    }

    function expandComment() {
        return null;
    }

    var expanders = {
        "comment": expandComment
    };

    function expand(form) {
        if (form.type === "list") {
            var car = form.value[0];
            if (car.type === "symbol") {
                var expander = expanders[car.value];
                if (expander) {
                    return expander(form);
                }
            }
            form.value = expandAll(form.value);
        }
        return form;
    }

    function expandAll(seq) {
        var result = [];
        for (var i = 0, l = seq.length; i < l; i++) {
            var form = expand(seq[i]);
            if (form !== null) {
                result.push(form);
            }
        }
        return result;
    }

    return { expand: expandAll };

});<commit_msg>Don't error on empty list<commit_after>/*jshint bitwise: true, camelcase: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, regexp: true, undef: true, unused: true, strict: true*/
/*global define*/
define(function () {

    "use strict";

    function error(msg, form) {
        // TODO: add line/char details to forms for better errors
        throw new Error(msg);
    }

    function expandComment() {
        return null;
    }

    var expanders = {
        "comment": expandComment
    };

    function expand(form) {
        if (form.type === "list" && form.value.length > 0) {
            var car = form.value[0];
            if (car.type === "symbol") {
                var expander = expanders[car.value];
                if (expander) {
                    return expander(form);
                }
            }
            form.value = expandAll(form.value);
        }
        return form;
    }

    function expandAll(seq) {
        var result = [];
        for (var i = 0, l = seq.length; i < l; i++) {
            var form = expand(seq[i]);
            if (form !== null) {
                result.push(form);
            }
        }
        return result;
    }

    return { expand: expandAll };

});<|endoftext|>


<commit_before>define([], function () {

    var Validate = function (ractive, rules, errorSuffix) {

        var self = this;

        self.ractive = ractive;

        self.rules = rules;

        /**
         * If set, if there is a validation error with a given keypath, then the
         * error text will be set at the keypath with the errorSuffix appended.
         */
        self.errorSuffix = errorSuffix || 'ErrorMsg';

        self.patterns = {
            alpha: /[a-z A-Z ]+/,
            alpha_numeric: /[a-zA-Z0-9]+/,
			digits: /-?\d+/,
            required: function (value) {
                return !_.isNull(value) && !_.isEqual(value, '') && !_.isUndefined(value);
            },
			minlength: function (value, param) {
				return !_.isNull(value) && !_.isUndefined(value) && !_.isBoolean(value) &&
						String(value).length >= parseInt(param, 10);
			},
			maxlength: function (value, param) {
				return !_.isNull(value) && !_.isUndefined(value) && !_.isBoolean(value) &&
						String(value).length <= parseInt(param, 10);
			}
        };
    };

    Validate.prototype = {

        validate: function () {
            var self = this;

			var validateValue = function (params, rule) {
				var self = this,
					passed = false,
					message = params.message || params,
					param = params.param || null;

				if (_.isFunction(self.patterns[rule])) {
					passed = self.patterns[rule](self.value, param);
				}
				if (_.isRegExp(self.patterns[rule])) {
					passed = self.patterns[rule].test(self.value);
				}

				return {
					rule: rule,
					passed: passed,
					message: passed ? '' : message
				};
			};

            var invalidCount = _.filter(self.rules, function (rules, keypath) {
				var invalid = _(rules)
					.map(validateValue, {
						patterns: self.patterns,
						value: self.ractive.get(keypath)
					})
					.filter(function (result) {
						return !result.passed;
					});

                self.ractive.set(keypath + self.errorSuffix, invalid[0] || null);

                return invalid.length > 0;
            }).length;

			return {
				valid: invalidCount === 0
			};
        }

    };

    return Validate;
});
<commit_msg>Lodash as a dependency, changing tabs to spaces<commit_after>define([lodash], function (_) {

    var Validate = function (ractive, rules, errorSuffix) {

        var self = this;

        self.ractive = ractive;

        self.rules = rules;

        /**
         * If set, if there is a validation error with a given keypath, then the
         * error text will be set at the keypath with the errorSuffix appended.
         */
        self.errorSuffix = errorSuffix || 'ErrorMsg';

        self.patterns = {
            alpha: /[a-z A-Z ]+/,
            alpha_numeric: /[a-zA-Z0-9]+/,
            digits: /-?\d+/,
            required: function (value) {
                return !_.isNull(value) && !_.isEqual(value, '') && !_.isUndefined(value);
            },
            minlength: function (value, param) {
                return !_.isNull(value) && !_.isUndefined(value) && !_.isBoolean(value) &&
                        String(value).length >= parseInt(param, 10);
            },
            maxlength: function (value, param) {
                return !_.isNull(value) && !_.isUndefined(value) && !_.isBoolean(value) &&
                        String(value).length <= parseInt(param, 10);
            }
        };
    };

    Validate.prototype = {

        validate: function () {
            var self = this;

            var validateValue = function (params, rule) {
                var self = this,
                    passed = false,
                    message = params.message || params,
                    param = params.param || null;

                if (_.isFunction(self.patterns[rule])) {
                    passed = self.patterns[rule](self.value, param);
                }
                if (_.isRegExp(self.patterns[rule])) {
                    passed = self.patterns[rule].test(self.value);
                }

                return {
                    rule: rule,
                    passed: passed,
                    message: passed ? '' : message
                };
            };

            var invalidCount = _.filter(self.rules, function (rules, keypath) {
                var invalid = _(rules)
                    .map(validateValue, {
                        patterns: self.patterns,
                        value: self.ractive.get(keypath)
                    })
                    .filter(function (result) {
                        return !result.passed;
                    });

                self.ractive.set(keypath + self.errorSuffix, invalid[0] || null);

                return invalid.length > 0;
            }).length;

            return {
                valid: invalidCount === 0
            };
        }

    };

    return Validate;
});
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   S3UploadWidget
// Website:   http://github.com/jgwhite/s3_upload_widget
// Authors:   Jamie White <jamie@jgwhite.co.uk>
// License:   Licensed under MIT license
// Copyright: © 2010 Jamie White
// ==========================================================================

S3UploadWidget = function() {};
S3UploadWidget.instances = [];
S3UploadWidget.DEFAULTS = {};
S3UploadWidget.REQUIRED_OPTIONS = [ "aws_access_key_id", "bucket", "policy", "signature" ];
S3UploadWidget.generate_id = function() {
  if (S3UploadWidget.__id === undefined) S3UploadWidget.__id = 0;
  return S3UploadWidget.__id++;
}
S3UploadWidget.create = function(options) {
  var instance = new S3UploadWidget();
  instance.initialize(options);
  return instance;
}
S3UploadWidget.prototype.initialize = function(options) {
  this._options = {};

  for (var key in S3UploadWidget.DEFAULTS)
    this._options[key] = S3UploadWidget.DEFAULTS[key];

  for (var key in options)
    this._options[key] = options[key];

  var missing_options = [];

  for (var i in S3UploadWidget.REQUIRED_OPTIONS) {
    var required_key = S3UploadWidget.REQUIRED_OPTIONS[i];
    if (this._options[required_key] === undefined
     || this._options[required_key] === null
     || this._options[required_key] === "") {
      missing_options.push(required_key);
    }
  }

  if (missing_options.length > 0) {
    throw("The following options are required: " + missing_options.join(", "));
  }

  S3UploadWidget.instances.push(this);

  if (this.options()["target"]) {
    this.insert(this.options()["target"]);
  }

  return this;
}
S3UploadWidget.prototype.id = function() {
  return this._id = this._id || ("s3_upload_widget_" + S3UploadWidget.generate_id());
}
S3UploadWidget.prototype.options = function() {
  return this._options;
}
S3UploadWidget.prototype.element = function() {
  if (!this._element) {
    this._element = document.createElement("div");
    this._element.className = "S3UploadWidget";
    this._element.id = this.id();

    this._element.appendChild(this.form());
  }
  return this._element;
}
S3UploadWidget.prototype.form = function() {
  if (!this._form) {
    this._form = document.createElement("form");
    this._form.id = this.id() + "_form";
    this._form.action = "http://" + this.options()["bucket"] + ".s3.amazonaws.com/";
    this._form.method = "post";
    this._form.enctype = "multipart/form-data";

    var fieldset;

    fieldset = document.createElement("fieldset");
    this._form.appendChild(fieldset);
    fieldset.appendChild(this.file_input());

    fieldset = document.createElement("fieldset");
    this._form.appendChild(fieldset);
    fieldset.appendChild(this.submit_button());
  }
  return this._form;
}
S3UploadWidget.prototype.file_input = function() {
  if (!this._file_input) {
    this._file_input = document.createElement("input");
    this._file_input.type = "file";
    this._file_input.name = "file";
    this._file_input.id = this.id() + "_file_input";
  }
  return this._file_input;
}
S3UploadWidget.prototype.submit_button = function() {
  if (!this._submit_button) {
    this._submit_button = document.createElement("input");
    this._submit_button.type = "submit";
    this._submit_button.value = "Upload";
    this._submit_button.disabled = "disabled";
    this._submit_button.id = this.id() + "_submit_button";
  }
  return this._submit_button;
}
S3UploadWidget.prototype.insert = function(target) {
  if (typeof(target) == "string") target = document.getElementById(target);

  if (target == undefined) throw("Target argument must be id or element");

  target.appendChild(this.element());
}
S3UploadWidget.prototype.remove = function() {
  this.unregister();
  this.remove_elements();
  this.dealloc();
  delete this;
}
S3UploadWidget.prototype.remove_elements = function() {
  if (this._element && this._element.parentNode)
    this._element.parentNode.removeChild(this._element);
}
S3UploadWidget.prototype.unregister = function () {
  var indexOf_this = S3UploadWidget.instances.indexOf(this);
  if (indexOf_this !== -1) S3UploadWidget.instances.splice(indexOf_this, 1);
}
S3UploadWidget.prototype.dealloc = function() {
  for (var prop in this) if (prop.indexOf("_") === 0) delete this[prop];
}

S3UploadWidget.Field = function() {};
S3UploadWidget.Field.DEFAULTS = { "type": "text" };
S3UploadWidget.Field.generate_id = function() {
  if (S3UploadWidget.Field.__id === undefined) S3UploadWidget.Field.__id = 0;
  return S3UploadWidget.Field.__id++;
}
S3UploadWidget.Field.prototype.id = function() {
  return this._id = this._id || ("s3_upload_widget_field_" + S3UploadWidget.Field.generate_id());
}
S3UploadWidget.Field.prototype.element = function() {
  if (!this._element) {
    this._element = document.createElement("fieldset");
    this._element.appendChild(this.input());
  }
  return this._element
}
S3UploadWidget.Field.prototype.make_input = function(type) {
  if (this._input) {
    var name = this._input.name;
    var value = this._input.value;

    if (this._input.parentNode) this._input.parentNode.removeChild(this._input);
    delete this._input;
  }

  type = type || S3UploadWidget.Field.DEFAULTS;

  switch (type) {
  case "textarea":
    this._input = document.createElement("textarea");
    break;
  default:
    this._input = document.createElement("input");
    break;
  }

  this._input.type = type;
  this._input.id = this.id() + "_input";
  this._input.name = name;
  this._input.value = value;
}
S3UploadWidget.Field.prototype.input = function() {
  if (!this._input) this.make_input();
  return this._input;
}
S3UploadWidget.Field.prototype.label = function() {
  return this._label;
}
S3UploadWidget.Field.prototype.set_type = function(new_type) {
  this.make_input(new_type);
}
S3UploadWidget.Field.prototype.set_name = function(new_name) {
  this.input().name = new_name;
}
S3UploadWidget.Field.prototype.set_value = function(new_value) {
  this.input().value = new_value;
}
S3UploadWidget.Field.prototype.set_label = function(new_label) {
  if (new_label != undefined && new_label.length > 0) {
    if (!this._label) {
      this._label = document.createElement("label");
      this.element().appendChild(this._label);
    }
    this._label.innerHTML = new_label;
  } else {
    if (this._label && this._label.parentNode) this._label.parentNode.removeChild(this._label);
    delete this.label;
  }
}
S3UploadWidget.Field.prototype.value = function() {
  return this.input().value;
}
S3UploadWidget.Field.prototype.initialize = function(new_options) {
  var options = {};
  for (var key in S3UploadWidget.Field.DEFAULTS)
    options[key] = S3UploadWidget.Field.DEFAULTS[key];
  for (var key in new_options)
    options[key] = new_options[key];

  for (var key in options) {
    var setter = this["set_" + key];
    if (setter === undefined) continue; // TODO: throw error for unknown setter
    setter.apply(this, [options[key]]);
  }
}
<commit_msg>Array extensions<commit_after>// ==========================================================================
// Project:   S3UploadWidget
// Website:   http://github.com/jgwhite/s3_upload_widget
// Authors:   Jamie White <jamie@jgwhite.co.uk>
// License:   Licensed under MIT license
// Copyright: © 2010 Jamie White
// ==========================================================================

Array.prototype.remove = function(obj) {
  for (var i = 0; i < this.length; i++)
    if (this[i] === obj) { this.splice(i, 1); return obj; }
  return null;
}
Array.prototype.indexOf = function(obj) {
  for (var i = 0; i < this.length; i++)
    if (this[i] === obj) { return i; }
  return -1;
}

S3UploadWidget = function() {};
S3UploadWidget.instances = [];
S3UploadWidget.DEFAULTS = {};
S3UploadWidget.REQUIRED_OPTIONS = [ "aws_access_key_id", "bucket", "policy", "signature" ];
S3UploadWidget.generate_id = function() {
  if (S3UploadWidget.__id === undefined) S3UploadWidget.__id = 0;
  return S3UploadWidget.__id++;
}
S3UploadWidget.create = function(options) {
  var instance = new S3UploadWidget();
  instance.initialize(options);
  return instance;
}
S3UploadWidget.prototype.initialize = function(options) {
  this._options = {};

  for (var key in S3UploadWidget.DEFAULTS)
    this._options[key] = S3UploadWidget.DEFAULTS[key];

  for (var key in options)
    this._options[key] = options[key];

  var missing_options = [];

  for (var i = 0; i < S3UploadWidget.REQUIRED_OPTIONS.length; i++) {
    var required_key = S3UploadWidget.REQUIRED_OPTIONS[i];
    if (this._options[required_key] === undefined
     || this._options[required_key] === null
     || this._options[required_key] === "") {
      missing_options.push(required_key);
    }
  }

  if (missing_options.length > 0) {
    throw("The following options are required: " + missing_options.join(", "));
  }

  S3UploadWidget.instances.push(this);

  if (this.options()["target"]) {
    this.insert(this.options()["target"]);
  }

  return this;
}
S3UploadWidget.prototype.id = function() {
  return this._id = this._id || ("s3_upload_widget_" + S3UploadWidget.generate_id());
}
S3UploadWidget.prototype.options = function() {
  return this._options;
}
S3UploadWidget.prototype.element = function() {
  if (!this._element) {
    this._element = document.createElement("div");
    this._element.className = "S3UploadWidget";
    this._element.id = this.id();

    this._element.appendChild(this.form());
  }
  return this._element;
}
S3UploadWidget.prototype.form = function() {
  if (!this._form) {
    this._form = document.createElement("form");
    this._form.id = this.id() + "_form";
    this._form.action = "http://" + this.options()["bucket"] + ".s3.amazonaws.com/";
    this._form.method = "post";
    this._form.enctype = "multipart/form-data";

    var fieldset;

    fieldset = document.createElement("fieldset");
    this._form.appendChild(fieldset);
    fieldset.appendChild(this.file_input());

    fieldset = document.createElement("fieldset");
    this._form.appendChild(fieldset);
    fieldset.appendChild(this.submit_button());
  }
  return this._form;
}
S3UploadWidget.prototype.file_input = function() {
  if (!this._file_input) {
    this._file_input = document.createElement("input");
    this._file_input.setAttribute("type", "file");
    this._file_input.name = "file";
    this._file_input.id = this.id() + "_file_input";
  }
  return this._file_input;
}
S3UploadWidget.prototype.submit_button = function() {
  if (!this._submit_button) {
    this._submit_button = document.createElement("input");
    this._submit_button.type = "submit";
    this._submit_button.value = "Upload";
    this._submit_button.disabled = "disabled";
    this._submit_button.id = this.id() + "_submit_button";
  }
  return this._submit_button;
}
S3UploadWidget.prototype.insert = function(target) {
  if (typeof(target) == "string") target = document.getElementById(target);

  if (target == undefined) throw("Target argument must be id or element");

  target.appendChild(this.element());
}
S3UploadWidget.prototype.remove = function() {
  this.unregister();
  this.remove_elements();
  this.dealloc();
}
S3UploadWidget.prototype.remove_elements = function() {
  if (this._element && this._element.parentNode)
    this._element.parentNode.removeChild(this._element);
}
S3UploadWidget.prototype.unregister = function () {
  var indexOf_this = S3UploadWidget.instances.remove(this);
}
S3UploadWidget.prototype.dealloc = function() {
  for (var prop in this) if (prop.indexOf("_") === 0) delete this[prop];
}

S3UploadWidget.Field = function() {};
S3UploadWidget.Field.DEFAULTS = { "type": "text" };
S3UploadWidget.Field.generate_id = function() {
  if (S3UploadWidget.Field.__id === undefined) S3UploadWidget.Field.__id = 0;
  return S3UploadWidget.Field.__id++;
}
S3UploadWidget.Field.prototype.id = function() {
  return this._id = this._id || ("s3_upload_widget_field_" + S3UploadWidget.Field.generate_id());
}
S3UploadWidget.Field.prototype.element = function() {
  if (!this._element) {
    this._element = document.createElement("fieldset");
    this._element.appendChild(this.input());
  }
  return this._element
}
S3UploadWidget.Field.prototype.make_input = function(type) {
  if (this._input) {
    var name = this._input.name;
    var value = this._input.value;

    if (this._input.parentNode) this._input.parentNode.removeChild(this._input);
    delete this._input;
  }

  type = type || S3UploadWidget.Field.DEFAULTS;

  switch (type) {
  case "textarea":
    this._input = document.createElement("textarea");
    break;
  default:
    this._input = document.createElement("input");
    this._input.setAttribute("type", type);
    break;
  }

  this._input.id = this.id() + "_input";
  this._input.name = name;
  this._input.value = value;
}
S3UploadWidget.Field.prototype.input = function() {
  if (!this._input) this.make_input();
  return this._input;
}
S3UploadWidget.Field.prototype.label = function() {
  return this._label;
}
S3UploadWidget.Field.prototype.set_type = function(new_type) {
  this.make_input(new_type);
}
S3UploadWidget.Field.prototype.set_name = function(new_name) {
  this.input().name = new_name;
}
S3UploadWidget.Field.prototype.set_value = function(new_value) {
  this.input().value = new_value;
}
S3UploadWidget.Field.prototype.set_label = function(new_label) {
  if (new_label != undefined && new_label.length > 0) {
    if (!this._label) {
      this._label = document.createElement("label");
      this.element().appendChild(this._label);
    }
    this._label.innerHTML = new_label;
  } else {
    if (this._label && this._label.parentNode) this._label.parentNode.removeChild(this._label);
    delete this.label;
  }
}
S3UploadWidget.Field.prototype.value = function() {
  return this.input().value;
}
S3UploadWidget.Field.prototype.initialize = function(new_options) {
  var options = {};
  for (var key in S3UploadWidget.Field.DEFAULTS)
    options[key] = S3UploadWidget.Field.DEFAULTS[key];
  for (var key in new_options)
    options[key] = new_options[key];

  for (var key in options) {
    var setter = this["set_" + key];
    if (setter === undefined) continue; // TODO: throw error for unknown setter
    setter.apply(this, [options[key]]);
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Globo.com (https://github.com/globocom)
 *
 * License: MIT
 */

export default {
  "entityMap": {
    "0": {
      "type": "LINK",
      "mutability": "MUTABLE",
      "data": {
        "url": "http://globocom.github.io/megadraft/#/docs/overview"
      }
    },
    "1": {
      "type": "LINK",
      "mutability": "MUTABLE",
      "data": {
        "url": "https://raw.githubusercontent.com/globocom/megadraft/master/LICENSE"
      }
    }
  },
  "blocks": [
    {
      "key": "ag6qs",
      "text": "Megadraft",
      "type": "header-two",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "59kd9",
      "text": "Megadraft is a ReactJS Rich Text editor built on top of Facebook's draft.js featuring:",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "bqjdr",
      "text": "Good usability",
      "type": "ordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "1pdm1",
      "text": "A nice default base of plugins",
      "type": "ordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "1sd0p",
      "text": "Extensibility.",
      "type": "ordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "c4sc5",
      "text": "It is easy to customize the sidebar, disabling or including new itens, and the media blocks are rendered with a beautiful component:",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "43m8u",
      "text": "Docs",
      "type": "header-two",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "cc4j7",
      "text": "You can find the docs here.",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": [
        {
          "offset": 22,
          "length": 4,
          "key": 0
        }
      ]
    },
    {
      "key": "gcc6",
      "text": "License",
      "type": "header-two",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "kst0",
      "text": "Megadraft is MIT licensed.",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": [
        {
          "offset": 13,
          "length": 3,
          "key": 1
        }
      ]
    }
  ]
};
<commit_msg>Fixed typo 'itens'<commit_after>/*
 * Copyright (c) 2016, Globo.com (https://github.com/globocom)
 *
 * License: MIT
 */

export default {
  "entityMap": {
    "0": {
      "type": "LINK",
      "mutability": "MUTABLE",
      "data": {
        "url": "http://globocom.github.io/megadraft/#/docs/overview"
      }
    },
    "1": {
      "type": "LINK",
      "mutability": "MUTABLE",
      "data": {
        "url": "https://raw.githubusercontent.com/globocom/megadraft/master/LICENSE"
      }
    }
  },
  "blocks": [
    {
      "key": "ag6qs",
      "text": "Megadraft",
      "type": "header-two",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "59kd9",
      "text": "Megadraft is a ReactJS Rich Text editor built on top of Facebook's draft.js featuring:",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "bqjdr",
      "text": "Good usability",
      "type": "ordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "1pdm1",
      "text": "A nice default base of plugins",
      "type": "ordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "1sd0p",
      "text": "Extensibility.",
      "type": "ordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "c4sc5",
      "text": "It is easy to customize the sidebar, disabling or including new items, and the media blocks are rendered with a beautiful component:",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "43m8u",
      "text": "Docs",
      "type": "header-two",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "cc4j7",
      "text": "You can find the docs here.",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": [
        {
          "offset": 22,
          "length": 4,
          "key": 0
        }
      ]
    },
    {
      "key": "gcc6",
      "text": "License",
      "type": "header-two",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": []
    },
    {
      "key": "kst0",
      "text": "Megadraft is MIT licensed.",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": [
        {
          "offset": 13,
          "length": 3,
          "key": 1
        }
      ]
    }
  ]
};
<|endoftext|>


<commit_before>/* eslint react/prefer-stateless-function:0 */
import 'react-native-gesture-handler'; // https://github.com/kmagiera/react-native-gesture-handler/issues/320
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { useScreens } from 'react-native-screens';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import App from './App';
import { LocalizationProvider } from '../../components/Localization';
import Loader from '../../components/Loader';
import i18n from '../../common/helpers/i18n';
import configureStore from '../../common/store/configureStore';
// GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest;

const { store, persistor } = configureStore();

useScreens();

if (process.env.NODE_ENV === 'production') {
  // eslint-disable-line no-undef
  [
    'assert',
    'clear',
    'count',
    'debug',
    'dir',
    'dirxml',
    'error',
    'exception',
    'group',
    'groupCollapsed',
    'groupEnd',
    'info',
    'log',
    'profile',
    'profileEnd',
    'table',
    'time',
    'timeEnd',
    'timeStamp',
    'trace',
    'warn',
  ].forEach(methodName => {
    // eslint-disable-next-line no-console
    console[methodName] = () => {};
  });
}

console.disableYellowBox = true;

class Root extends Component {
  render() {
    return (
      <Provider store={store}>
        <LocalizationProvider i18n={i18n}>
          <PersistGate loading={<Loader />} persistor={persistor}>
            <App />
          </PersistGate>
        </LocalizationProvider>
      </Provider>
    );
  }
}

AppRegistry.registerComponent('PxView', () => Root);
<commit_msg>Enable yellow box<commit_after>/* eslint react/prefer-stateless-function:0 */
import 'react-native-gesture-handler'; // https://github.com/kmagiera/react-native-gesture-handler/issues/320
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { useScreens } from 'react-native-screens';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import App from './App';
import { LocalizationProvider } from '../../components/Localization';
import Loader from '../../components/Loader';
import i18n from '../../common/helpers/i18n';
import configureStore from '../../common/store/configureStore';
// GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest;

const { store, persistor } = configureStore();

useScreens();

if (process.env.NODE_ENV === 'production') {
  // eslint-disable-line no-undef
  [
    'assert',
    'clear',
    'count',
    'debug',
    'dir',
    'dirxml',
    'error',
    'exception',
    'group',
    'groupCollapsed',
    'groupEnd',
    'info',
    'log',
    'profile',
    'profileEnd',
    'table',
    'time',
    'timeEnd',
    'timeStamp',
    'trace',
    'warn',
  ].forEach(methodName => {
    // eslint-disable-next-line no-console
    console[methodName] = () => {};
  });
}

// console.disableYellowBox = true;

class Root extends Component {
  render() {
    return (
      <Provider store={store}>
        <LocalizationProvider i18n={i18n}>
          <PersistGate loading={<Loader />} persistor={persistor}>
            <App />
          </PersistGate>
        </LocalizationProvider>
      </Provider>
    );
  }
}

AppRegistry.registerComponent('PxView', () => Root);
<|endoftext|>


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

var minimatch = require('minimatch');

var config = require('./config');
var validators = require('./validators');

var fileTypes = {
	'eslint': '*.js',
	'jscs': '*.js',
	'jshint': '*.js'
};

function Linter(options, cb) {
	this.options = options;
	this.cb = cb;

	this.validating = 0;
	this.ended = false;

	this.err = [];
	this.lints = [];

	for (var key in options.lintConfig) {
		if (validators[key] && minimatch(options.path, fileTypes[key], { matchBase: true })) {
			this.validating++;
			validators[key].validate({
				path: options.path,
				content: options.content,
				config: options.lintConfig[key]
			}, this.onValidate.bind(this));
		}
	}
	this.ended = true;
	this.end();
}

Linter.prototype.onValidate = function(err, lints) {
	if (err) this.err = this.err.concat(err);
	this.lints = this.lints.concat(lints);

	this.validating--;
	this.end();
};

Linter.prototype.end = function() {
	if (this.ended && this.validating === 0) {
		var err = this.err.length ? this.err : null;
		var lint = this.lints.length ? { file: this.options.path, lines: this.options.lines, errors: this.lints } : null;
		this.cb(err, lint);
	}
};

/**
 * Lint a file
 * @param {Object} options
 * @param {string} options.path - path of the file to lint
 * @param {string} [options.content] - Content of the file to lint. If no content is provided `options.path` is used to
 *                                     read the content
 * @param {Object} [options.lintConfig] - Config for the lint. If not provided, it is read in parents folders of
 *                                        `options.path`
 * @param {Function} cb
 */
exports.lint = function lint(options, cb) {
	if (!options.lintConfig) {
		var folder = path.dirname(options.path);
		config.load(folder, function(err, conf) {
			if (err) return cb([err], []);
			options.lintConfig = conf;
			lint(options, cb);
		});
		return;
	}
	if (typeof options.content !== 'string') {
		fs.readFile(options.path, {encoding: 'UTF-8'}, function(err, content) {
			if (err) return cb([err], []);
			options.content = content;
			options.lines = content.split(/\r?\n/);
			lint(options, cb);
		});
		return;
	}
	new Linter(options, cb);
};
<commit_msg>Perf: do not read file with no validators<commit_after>var fs = require('fs');
var path = require('path');

var minimatch = require('minimatch');

var config = require('./config');
var validators = require('./validators');

var fileTypes = {
	'eslint': '*.js',
	'jscs': '*.js',
	'jshint': '*.js'
};

function Linter(options, cb) {
	this.options = options;
	this.cb = cb;

	this.validators = [];
	this.validated = 0;

	this.err = [];
	this.lints = [];

	for (var key in options.lintConfig) {
		if (validators[key] && minimatch(options.path, fileTypes[key], { matchBase: true })) {
			this.validators.push({
				validator: validators[key],
				config: options.lintConfig[key]
			});
		}
	}

	if (!this.validators.length) return cb();

	fs.readFile(options.path, {encoding: 'UTF-8'}, function(err, content) {
		if (err) return cb([err]);
		this.options.content = content;
		this.options.lines = content.split(/\r?\n/);
		this.lint();
	}.bind(this));
}

Linter.prototype.lint = function() {
	this.validators.forEach(function(validator) {
		validator.validator.validate({
			path: this.options.path,
			content: this.options.content,
			config: validator.config
		}, this.onValidate.bind(this));
	}.bind(this));
};

Linter.prototype.onValidate = function(err, lints) {
	if (err) this.err = this.err.concat(err);
	this.lints = this.lints.concat(lints);

	this.validated++;
	this.end();
};

Linter.prototype.end = function() {
	if (this.validated === this.validators.length) {
		var err = this.err.length ? this.err : null;
		var lint = this.lints.length ? { file: this.options.path, lines: this.options.lines, errors: this.lints } : null;
		this.cb(err, lint);
	}
};

/**
 * Lint a file
 * @param {Object} options
 * @param {string} options.path - path of the file to lint
 * @param {Object} [options.lintConfig] - Config for the lint. If not provided, it is read in parents folders of
 *                                        `options.path`
 * @param {Function} cb
 */
exports.lint = function lint(options, cb) {
	if (!options.lintConfig) {
		var folder = path.dirname(options.path);
		config.load(folder, function(err, conf) {
			if (err) return cb([err], []);
			options.lintConfig = conf;
			lint(options, cb);
		});
		return;
	}
	new Linter(options, cb);
};
<|endoftext|>


<commit_before>import ExpandableMolecule from './ExpandableMolecule';
import Nmr1dManager from './Nmr1dManager';
import MF from './MF';
import Datas from 'src/main/datas';
import API from 'src/util/api';
import UI from 'src/util/ui';
import {createVar, getData} from './jpaths';
import {elnPlugin} from './libs';
import Roc from '../rest-on-couch/Roc';

const DataObject = Datas.DataObject;

var defaultOptions = {
    varName: 'sample',
    track: true
};

class Sample {
    constructor(couchDB, uuid, options) {
        this.options = Object.assign({}, defaultOptions, options);

        var roc = API.cache('roc');
        if (!roc) {
            roc = new Roc({
                url: couchDB.url,
                database: couchDB.database,
                processor: elnPlugin,
                kind: couchDB.kind
            });
            API.cache('roc', roc);
        }
        this.roc = roc;

        this.uuid = uuid;
        if (!this.uuid) {
            UI.showNotification('Cannot create an editable sample without an uuid', 'error');
            return;
        }
        this._loadInstanceInVisualizer();
    }

    async _loadInstanceInVisualizer() {
        this.sample = await this.roc.document(this.uuid, this.options);
        var sampleVar = API.getVar(this.options.varName);

        createVar(sampleVar, 'sampleCode');
        createVar(sampleVar, 'batchCode');
        createVar(sampleVar, 'creationDate');
        createVar(sampleVar, 'modificationDate');
        createVar(sampleVar, 'content');
        createVar(sampleVar, 'general');
        createVar(sampleVar, 'molfile');
        createVar(sampleVar, 'mf');
        createVar(sampleVar, 'mw');
        createVar(sampleVar, 'em');
        createVar(sampleVar, 'title');
        createVar(sampleVar, 'description');
        createVar(sampleVar, 'name');
        createVar(sampleVar, 'physical');
        createVar(sampleVar, 'bp');
        createVar(sampleVar, 'nd');
        createVar(sampleVar, 'mp');
        createVar(sampleVar, 'density');
        createVar(sampleVar, 'ir');
        createVar(sampleVar, 'mass');
        createVar(sampleVar, 'xray');
        createVar(sampleVar, 'chromatogram');
        createVar(sampleVar, 'image');
        createVar(sampleVar, 'sampleCode');
        createVar(sampleVar, 'attachments');

        this.expandableMolecule = new ExpandableMolecule(this.sample, this.options);
        this.nmr1dManager = new Nmr1dManager(this.sample);
        this.nmr1dManager.initializeNMRAssignment();
        createVar(sampleVar, 'nmr');
        this.mf = new MF(this.sample);
        this.mf.fromMF();

        this.onChange = (event) => {
            if (this.options.track && typeof IframeBridge !== 'undefined') {
                self.IframeBridge.postMessage('tab.status', {
                    saved: false
                });
            }

            var jpathStr = event.jpath.join('.');

            if (jpathStr.replace(/\.\d+\..*/, '') === '$content.spectra.nmr') {
                // execute peak picking
                var currentNmr = this.sample.getChildSync(jpathStr.replace(/(\.\d+)\..*/, '$1').split('.'));
                this.nmr1dManager.executePeakPicking(currentNmr);
            }

            switch (event.jpath.join('.')) {
                case '':
                    this.nmr1dManager.initializeNMRAssignment(getData(this.sample, 'nmr'));
                    createVar(sampleVar, 'nmr');
                    break;
                case '$content.general.molfile':
                    this.mf.fromMolfile();
                    break;
                case '$content.general.mf':
                    try {
                        this.mf.fromMF();
                        this.nmr1dManager.updateIntegral({mf: true});
                    } catch (e) {
                        // ignore
                    }
                    break;
                default:
                    break; // ignore
            }
        };

        this.bindChange();
    }

    bindChange() {
        this.sample.unbindChange(this.onChange);
        this.sample.onChange(this.onChange);
    }

    unbindChange() {
        this.sample.unbindChange(this.onChange);
    }

    async handleDrop(name, askType) {
        var type;
        if (!name) {
            throw new Error('handleDrop expects a variable name');
        }
        name = String(name);
        if (!askType) {
            // maps name of variable to type of data
            var types = {
                'droppedNmr': 'nmr',
                'droppedIR': 'ir',
                'droppedMS': 'mass'
            };
            if (!types[name]) {
                throw new Error('Unexpected variable name');
            }
            type = types[name];
        } else {
            type = await UI.choose({
                nmr: 'NMR (jcamp, pdf)',
                mass: 'Mass (jcamp, pdf, netcdf, xml)',
                ir: 'Infra-red (jcamp, pdf)',
                chromatogram: 'GCMS (jcamp, pdf, netcdf, xml)',
                xray: 'Xray (cif, pdb)',
                image: 'Images (jpg, png or tiff)',
                other: 'Other'
            }, {
                noConfirmation: true,
                columns: [
                    {
                        id: 'description',
                        name: 'description',
                        field: 'description'
                    }
                ]
            });
            if (!type) return;
        }

        // Dropped data can be an array
        // Expecting format as from drag and drop module
        var droppedDatas = API.getData(name);
        droppedDatas = droppedDatas.file || droppedDatas.str;

        if (type === 'other') {
            await this.roc.addAttachment(this.sample, droppedDatas);
        } else {
            for (let i = 0; i < droppedDatas.length; i++) {
                var data = DataObject.resurrect(droppedDatas[i]);
                await this.roc.attach(type, this.sample, data);
            }
        }

    }

    async handleAction(action) {
        if (!action) return;

        if (this.expandableMolecule && this.expandableMolecule.handleAction(action)) return;
        if (this.nmr1dManager && this.nmr1dManager.handleAction(action)) return;

        switch (action.name) {
            case 'save':
                await this.roc.update(this.sample);
                if (typeof IframeBridge !== 'undefined') {
                    self.IframeBridge.postMessage('tab.status', {
                        saved: true
                    });
                }
                break;
            case 'createOptions':
                var advancedOptions1H = API.cache('nmr1hAdvancedOptions');
                if (advancedOptions1H) {
                    API.createData('nmr1hOndeTemplate', API.getData('nmr1hOndeTemplates').full);
                } else {
                    API.createData('nmr1hOndeTemplate', API.getData('nmr1hOndeTemplates').short);
                }
                break;
            case 'deleteAttachment':
                var attachment = action.value.name;
                await this.roc.deleteAttachment(this.sample, attachment);
                break;
            case 'deleteNmr': // Deprecated. Use unattach. Leave this for backward compatibility
            case 'unattach':
                await this.roc.unattach(this.sample, action.value);
                break;
            case 'attachNMR':
            case 'attachIR':
            case 'attachMass': {
                var type = action.name.replace('attach', '').toLowerCase();
                var droppedDatas = action.value;
                droppedDatas = droppedDatas.file || droppedDatas.str;
                for (let i = 0; i < droppedDatas.length; i++) {
                    const data = DataObject.resurrect(droppedDatas[i]);
                    await this.roc.attach(type, this.sample, data);
                }
                break;
            }
            case 'refresh': {
                const ok = await UI.confirm('Are you sure you want to refresh? This will discard your local modifications.');
                if (!ok) return;
                this.unbindChange();
                await this.roc.discardLocal(this.sample);
                this.nmr1dManager.initializeNMRAssignment(API.getData('currentNmr'));
                this.expandableMolecule.unbindChange();
                this.expandableMolecule = new ExpandableMolecule(this.sample, this.options);
                this.mf = new MF(this.sample);
                this.mf.fromMF();
                this.bindChange();
                self.IframeBridge.postMessage('tab.status', {
                    saved: true
                });
                break;
            }
            default:
                break;
        }
    }
}

module.exports = Sample;
<commit_msg>Add title if missing<commit_after>import ExpandableMolecule from './ExpandableMolecule';
import Nmr1dManager from './Nmr1dManager';
import MF from './MF';
import Datas from 'src/main/datas';
import API from 'src/util/api';
import UI from 'src/util/ui';
import {createVar, getData} from './jpaths';
import {elnPlugin} from './libs';
import Roc from '../rest-on-couch/Roc';

const DataObject = Datas.DataObject;

var defaultOptions = {
    varName: 'sample',
    track: true
};

class Sample {
    constructor(couchDB, uuid, options) {
        this.options = Object.assign({}, defaultOptions, options);

        var roc = API.cache('roc');
        if (!roc) {
            roc = new Roc({
                url: couchDB.url,
                database: couchDB.database,
                processor: elnPlugin,
                kind: couchDB.kind
            });
            API.cache('roc', roc);
        }
        this.roc = roc;

        this.uuid = uuid;
        if (!this.uuid) {
            UI.showNotification('Cannot create an editable sample without an uuid', 'error');
            return;
        }
        this._loadInstanceInVisualizer();
    }

    async _loadInstanceInVisualizer() {
        this.sample = await this.roc.document(this.uuid, this.options);

        if (! this.sample.$content.general) {
            this.sample.$content.general={};
        }
        // TODO improve to add the missing properties from eln-plugin / types / sample / general.js
        Object.assign(this.sample.$content.general, {title:''});

        var sampleVar = API.getVar(this.options.varName);

        createVar(sampleVar, 'sampleCode');
        createVar(sampleVar, 'batchCode');
        createVar(sampleVar, 'creationDate');
        createVar(sqampleVar, 'modificationDate');
        createVar(sampleVar, 'content');
        createVar(sampleVar, 'general');
        createVar(sampleVar, 'molfile');
        createVar(sampleVar, 'mf');
        createVar(sampleVar, 'mw');
        createVar(sampleVar, 'em');
        createVar(sampleVar, 'title');
        createVar(sampleVar, 'description');
        createVar(sampleVar, 'name');
        createVar(sampleVar, 'physical');
        createVar(sampleVar, 'bp');
        createVar(sampleVar, 'nd');
        createVar(sampleVar, 'mp');
        createVar(sampleVar, 'density');
        createVar(sampleVar, 'ir');
        createVar(sampleVar, 'mass');
        createVar(sampleVar, 'xray');
        createVar(sampleVar, 'chromatogram');
        createVar(sampleVar, 'image');
        createVar(sampleVar, 'sampleCode');
        createVar(sampleVar, 'attachments');

        this.expandableMolecule = new ExpandableMolecule(this.sample, this.options);
        this.nmr1dManager = new Nmr1dManager(this.sample);
        this.nmr1dManager.initializeNMRAssignment();
        createVar(sampleVar, 'nmr');
        this.mf = new MF(this.sample);
        this.mf.fromMF();

        this.onChange = (event) => {
            if (this.options.track && typeof IframeBridge !== 'undefined') {
                self.IframeBridge.postMessage('tab.status', {
                    saved: false
                });
            }

            var jpathStr = event.jpath.join('.');

            if (jpathStr.replace(/\.\d+\..*/, '') === '$content.spectra.nmr') {
                // execute peak picking
                var currentNmr = this.sample.getChildSync(jpathStr.replace(/(\.\d+)\..*/, '$1').split('.'));
                this.nmr1dManager.executePeakPicking(currentNmr);
            }

            switch (event.jpath.join('.')) {
                case '':
                    this.nmr1dManager.initializeNMRAssignment(getData(this.sample, 'nmr'));
                    createVar(sampleVar, 'nmr');
                    break;
                case '$content.general.molfile':
                    this.mf.fromMolfile();
                    break;
                case '$content.general.mf':
                    try {
                        this.mf.fromMF();
                        this.nmr1dManager.updateIntegral({mf: true});
                    } catch (e) {
                        // ignore
                    }
                    break;
                default:
                    break; // ignore
            }
        };

        this.bindChange();
    }

    bindChange() {
        this.sample.unbindChange(this.onChange);
        this.sample.onChange(this.onChange);
    }

    unbindChange() {
        this.sample.unbindChange(this.onChange);
    }

    async handleDrop(name, askType) {
        var type;
        if (!name) {
            throw new Error('handleDrop expects a variable name');
        }
        name = String(name);
        if (!askType) {
            // maps name of variable to type of data
            var types = {
                'droppedNmr': 'nmr',
                'droppedIR': 'ir',
                'droppedMS': 'mass'
            };
            if (!types[name]) {
                throw new Error('Unexpected variable name');
            }
            type = types[name];
        } else {
            type = await UI.choose({
                nmr: 'NMR (jcamp, pdf)',
                mass: 'Mass (jcamp, pdf, netcdf, xml)',
                ir: 'Infra-red (jcamp, pdf)',
                chromatogram: 'GCMS (jcamp, pdf, netcdf, xml)',
                xray: 'Xray (cif, pdb)',
                image: 'Images (jpg, png or tiff)',
                other: 'Other'
            }, {
                noConfirmation: true,
                columns: [
                    {
                        id: 'description',
                        name: 'description',
                        field: 'description'
                    }
                ]
            });
            if (!type) return;
        }

        // Dropped data can be an array
        // Expecting format as from drag and drop module
        var droppedDatas = API.getData(name);
        droppedDatas = droppedDatas.file || droppedDatas.str;

        if (type === 'other') {
            await this.roc.addAttachment(this.sample, droppedDatas);
        } else {
            for (let i = 0; i < droppedDatas.length; i++) {
                var data = DataObject.resurrect(droppedDatas[i]);
                await this.roc.attach(type, this.sample, data);
            }
        }

    }

    async handleAction(action) {
        if (!action) return;

        if (this.expandableMolecule && this.expandableMolecule.handleAction(action)) return;
        if (this.nmr1dManager && this.nmr1dManager.handleAction(action)) return;

        switch (action.name) {
            case 'save':
                await this.roc.update(this.sample);
                if (typeof IframeBridge !== 'undefined') {
                    self.IframeBridge.postMessage('tab.status', {
                        saved: true
                    });
                }
                break;
            case 'createOptions':
                var advancedOptions1H = API.cache('nmr1hAdvancedOptions');
                if (advancedOptions1H) {
                    API.createData('nmr1hOndeTemplate', API.getData('nmr1hOndeTemplates').full);
                } else {
                    API.createData('nmr1hOndeTemplate', API.getData('nmr1hOndeTemplates').short);
                }
                break;
            case 'deleteAttachment':
                var attachment = action.value.name;
                await this.roc.deleteAttachment(this.sample, attachment);
                break;
            case 'deleteNmr': // Deprecated. Use unattach. Leave this for backward compatibility
            case 'unattach':
                await this.roc.unattach(this.sample, action.value);
                break;
            case 'attachNMR':
            case 'attachIR':
            case 'attachMass': {
                var type = action.name.replace('attach', '').toLowerCase();
                var droppedDatas = action.value;
                droppedDatas = droppedDatas.file || droppedDatas.str;
                for (let i = 0; i < droppedDatas.length; i++) {
                    const data = DataObject.resurrect(droppedDatas[i]);
                    await this.roc.attach(type, this.sample, data);
                }
                break;
            }
            case 'refresh': {
                const ok = await UI.confirm('Are you sure you want to refresh? This will discard your local modifications.');
                if (!ok) return;
                this.unbindChange();
                await this.roc.discardLocal(this.sample);
                this.nmr1dManager.initializeNMRAssignment(API.getData('currentNmr'));
                this.expandableMolecule.unbindChange();
                this.expandableMolecule = new ExpandableMolecule(this.sample, this.options);
                this.mf = new MF(this.sample);
                this.mf.fromMF();
                this.bindChange();
                self.IframeBridge.postMessage('tab.status', {
                    saved: true
                });
                break;
            }
            default:
                break;
        }
    }
}

module.exports = Sample;
<|endoftext|>


<commit_before>/*
  messages so far:

  - "active-tab" a runtime was selected array msg.activeTab
  - "show-view" a view was created id msg.view
  - "hide-view" a view was removed id msg.view
  - "setting-changed" a setting has changed msg.id view_id, msg.key key
  - "host-state" msg.state = 'disconnected' | 'ready' | waiting';
  - "element-selected" msg.obj_id, msg.rt_id

*/

var messages = new function()
{
  var __listeners = {};
  this.addListener = function(key, cb)
  {
    if( __listeners[ key ] )
    {
      __listeners[ key ].push( cb );
    }
    else
    {
      __listeners[ key ] = [ cb ];
    }
  }
  this.removeListener = function(key)
  {

  }
  this.post = function( key, msg )
  {
    var listeners = __listeners[ key ], cb = null, i = 0;
    msg.type = key;
    if( listeners )
    {
      for( ; cb = listeners[i]; i++)
      {
        cb(msg);
      }
    }
  }
}<commit_msg>commented two new messages<commit_after>/*
  messages so far:

  - "active-tab" a runtime was selected array msg.activeTab
  - "show-view" a view was created id msg.view
  - "hide-view" a view was removed id msg.view
  - "setting-changed" a setting has changed msg.id view_id, msg.key key
  - "host-state" msg.state = 'disconnected' | 'ready' | waiting';
  - "element-selected" msg.obj_id, msg.rt_id
  - "view-created" msg.id, msg.container
  - "view-destroyed" msg.id

*/

var messages = new function()
{
  var __listeners = {};
  this.addListener = function(key, cb)
  {
    if( __listeners[ key ] )
    {
      __listeners[ key ].push( cb );
    }
    else
    {
      __listeners[ key ] = [ cb ];
    }
  }
  this.removeListener = function(key)
  {

  }
  this.post = function( key, msg )
  {
    var listeners = __listeners[ key ], cb = null, i = 0;
    msg.type = key;
    if( listeners )
    {
      for( ; cb = listeners[i]; i++)
      {
        cb(msg);
      }
    }
  }
}<|endoftext|>


<commit_before>var FACEBOOK_PAGE_HTML = '';
var SOURCE_URL = 'http://github.com/jyro2080/TabSense'
var BUGS_URL = 'http://github.com/jyro2080/TabSense/issues'

function processTabs(realtabs) {
    var tl = realtabs.length;
    var wid;
    for(var j=0; j < tl; j++) {
        var rtab = realtabs[j];
        wid = rtab.windowId;

        tabMap[rtab.id] = rtab;

        mtab = new Tab(rtab);

        windowMap[wid].addTab(mtab);
    }

    windowMap[wid].refreshStyle();

    doneWindows++;

    if(doneWindows == windowList.length) {
        layout_windows();
    }
}

var tabOnMove = null;

function getColumnHeight(colNum) {
    var h = CEILING;
    if(!winColumns[colNum]) winColumns[colNum] = [];
    for(var i=0; i < winColumns[colNum].length; i++) {
        var wi = winColumns[colNum][i];
        var w = windowList[wi];
        var height = w.elem.height() + VMARGIN;
        h += height;
    }
    return h;
}

function layout_windows() {
    windowList.sort(function(a,b) { return (b.numTabs-a.numTabs); });

    var colDir = 1;
    function columnNumber(counter) {
        var r = parseInt(counter / NUMCOL);
        var c = counter % NUMCOL;
        return ( ((r % 2) == 0) ? c : (NUMCOL-1-c) );
    }

    var colCount = 0;
    for(var i=0; i < windowList.length; i++) {

        colCount = columnNumber(i);

        var wh = windowList[i].elem.height();

        if(!winColumns[colCount]) winColumns[colCount] = [];

        windowList[i].setLocation(
            getColumnHeight(colCount),
            (colCount*windowList[i].elem.width()+(colCount+0.5) * HMARGIN));

        winColumns[colCount].push(i);
    }
}

function get_column(x) {
    return parseInt((x - 0.5*HMARGIN)/windowList[0].elem.width());
}
function relayout_column(colnum) {
    var column = winColumns[colnum]
    var wl = column.splice(0); // copy array and empty it
    for(var i=0; i < wl.length; i++) {
        var win = windowList[wl[i]];
        win.setLocation(
            getColumnHeight(colnum),
            colnum * win.elem.width() + (colnum+0.5) * HMARGIN);
        column.push(wl[i]);
    }

}

var winColumns = new Array(NUMCOL);
var tabMap = [];
var windowMap = [];
var windowList = [];
var doneWindows = 0;
var dw, dh, winw;
var HMARGIN = 30;
var VMARGIN = 20;
var NUMCOL = 3;
var CEILING = 50;

$(document).ready(function(){

    dw = $(document).width();
    dh = $(document).height();

    winw = parseInt(dw/NUMCOL);

    chrome.windows.getAll(null,
        function(windows) {

            var wl = windows.length;
            for(var i=0; i < wl; i++) {

                var mwin = new WinFrame(windows[i]);

                windowMap[windows[i].id] = mwin;
                windowList[i] = mwin;

                $('body').append(mwin.elem);

                chrome.tabs.getAllInWindow(windows[i].id, processTabs);
            }
        }
    );
    refresh_favorites();

    $('#topbar #search').focus(function() {
        run_query('');
    });
    $('#topbar #search').blur(function() {
        blur_all_tabs(false);
    });

    $('#topbar #search').keyup(function() {
        run_query($(this).val());
    });

    $('#creator').css('top',(dh-50)+'px');
    $('#creator').css('left',(dw-140)+'px');

    $('#topbar #info').click(function(ev) {
        if($.trim($('#infopanel').html()) === '') {

            var topline = $('

').attr('id','topline')
                .append('Source'+
                    '   '+
                    'Bugs/Features'+
                    '   '+
                    'Close');

            $('#infopanel')
                .append(topline)
                .append(FACEBOOK_PAGE_HTML);
        }
        $('#infopanel').show();
    });

    $('#infopanel #close').click(function() {
        $(this).hide();
    });
    $('#infopanel').click(function() {
        $(this).hide();
    });

    position_infopanel();

});

function position_infopanel() {
    var ipw = 550;
    var iph = 600;
    var left = (dw - ipw)/2;
    var top = (dh - iph)/2;
    $('#infopanel').css({
        'left' : left+'px',
        'top' : top+'px'
    });
}

function blur_all_tabs(yes)
{
    var wl = windowList.length;
    for(var i=0; i < wl; i++) {
        var win = windowList[i];
        (yes ? win.blurTabs : win.unblurTabs)();
    }
}

function run_query(query)
{
    blur_all_tabs(true);
    if($.trim(query) != '') {
        query = query.toLowerCase();
        for (i in tabMap) {
            var tabTitle = tabMap[i].title;
            if(tabTitle && tabTitle.toLowerCase().indexOf(query) >= 0) {
                tab_selector = 'tab_'+tabMap[i].id;
                var wl = windowList.length;
                for(var j=0; j < wl; j++) {
                    $('#'+tab_selector, windowList[j].elem).css({
                        'color':'#000'
                    });
                }
            }
        }
    }

}

function refresh_favorites()
{
    // Load favorite favicons
    var favlist = Fav.list();
    var fll = favlist.length;
    var favbar = $('#topbar #favbar');
    favbar.empty();
    for(var i=0; i < fll; i++) {
        if(favlist[i].favIconUrl) {
            var img = $('').attr('src',favlist[i].favIconUrl)
                                .width('24px')
                                .height('24px');
            var link = $('').attr('href', favlist[i].url);
            link.append(img);
            favbar.append(link);
        }
    }
}
<commit_msg>unused<commit_after>var FACEBOOK_PAGE_HTML = '';
var SOURCE_URL = 'http://github.com/jyro2080/TabSense'
var BUGS_URL = 'http://github.com/jyro2080/TabSense/issues'

function processTabs(realtabs) {
    var tl = realtabs.length;
    var wid;
    for(var j=0; j < tl; j++) {
        var rtab = realtabs[j];
        wid = rtab.windowId;

        tabMap[rtab.id] = rtab;

        mtab = new Tab(rtab);

        windowMap[wid].addTab(mtab);
    }

    windowMap[wid].refreshStyle();

    doneWindows++;

    if(doneWindows == windowList.length) {
        layout_windows();
    }
}

var tabOnMove = null;

function getColumnHeight(colNum) {
    var h = CEILING;
    if(!winColumns[colNum]) winColumns[colNum] = [];
    for(var i=0; i < winColumns[colNum].length; i++) {
        var wi = winColumns[colNum][i];
        var w = windowList[wi];
        var height = w.elem.height() + VMARGIN;
        h += height;
    }
    return h;
}

function layout_windows() {
    windowList.sort(function(a,b) { return (b.numTabs-a.numTabs); });

    function columnNumber(counter) {
        var r = parseInt(counter / NUMCOL);
        var c = counter % NUMCOL;
        return ( ((r % 2) == 0) ? c : (NUMCOL-1-c) );
    }

    var colCount = 0;
    for(var i=0; i < windowList.length; i++) {

        colCount = columnNumber(i);

        var wh = windowList[i].elem.height();

        if(!winColumns[colCount]) winColumns[colCount] = [];

        windowList[i].setLocation(
            getColumnHeight(colCount),
            (colCount*windowList[i].elem.width()+(colCount+0.5) * HMARGIN));

        winColumns[colCount].push(i);
    }
}

function get_column(x) {
    return parseInt((x - 0.5*HMARGIN)/windowList[0].elem.width());
}
function relayout_column(colnum) {
    var column = winColumns[colnum]
    var wl = column.splice(0); // copy array and empty it
    for(var i=0; i < wl.length; i++) {
        var win = windowList[wl[i]];
        win.setLocation(
            getColumnHeight(colnum),
            colnum * win.elem.width() + (colnum+0.5) * HMARGIN);
        column.push(wl[i]);
    }

}

var winColumns = new Array(NUMCOL);
var tabMap = [];
var windowMap = [];
var windowList = [];
var doneWindows = 0;
var dw, dh, winw;
var HMARGIN = 30;
var VMARGIN = 20;
var NUMCOL = 3;
var CEILING = 50;

$(document).ready(function(){

    dw = $(document).width();
    dh = $(document).height();

    winw = parseInt(dw/NUMCOL);

    chrome.windows.getAll(null,
        function(windows) {

            var wl = windows.length;
            for(var i=0; i < wl; i++) {

                var mwin = new WinFrame(windows[i]);

                windowMap[windows[i].id] = mwin;
                windowList[i] = mwin;

                $('body').append(mwin.elem);

                chrome.tabs.getAllInWindow(windows[i].id, processTabs);
            }
        }
    );
    refresh_favorites();

    $('#topbar #search').focus(function() {
        run_query('');
    });
    $('#topbar #search').blur(function() {
        blur_all_tabs(false);
    });

    $('#topbar #search').keyup(function() {
        run_query($(this).val());
    });

    $('#creator').css('top',(dh-50)+'px');
    $('#creator').css('left',(dw-140)+'px');

    $('#topbar #info').click(function(ev) {
        if($.trim($('#infopanel').html()) === '') {

            var topline = $('

').attr('id','topline')
                .append('Source'+
                    '   '+
                    'Bugs/Features'+
                    '   '+
                    'Close');

            $('#infopanel')
                .append(topline)
                .append(FACEBOOK_PAGE_HTML);
        }
        $('#infopanel').show();
    });

    $('#infopanel #close').click(function() {
        $(this).hide();
    });
    $('#infopanel').click(function() {
        $(this).hide();
    });

    position_infopanel();

});

function position_infopanel() {
    var ipw = 550;
    var iph = 600;
    var left = (dw - ipw)/2;
    var top = (dh - iph)/2;
    $('#infopanel').css({
        'left' : left+'px',
        'top' : top+'px'
    });
}

function blur_all_tabs(yes)
{
    var wl = windowList.length;
    for(var i=0; i < wl; i++) {
        var win = windowList[i];
        (yes ? win.blurTabs : win.unblurTabs)();
    }
}

function run_query(query)
{
    blur_all_tabs(true);
    if($.trim(query) != '') {
        query = query.toLowerCase();
        for (i in tabMap) {
            var tabTitle = tabMap[i].title;
            if(tabTitle && tabTitle.toLowerCase().indexOf(query) >= 0) {
                tab_selector = 'tab_'+tabMap[i].id;
                var wl = windowList.length;
                for(var j=0; j < wl; j++) {
                    $('#'+tab_selector, windowList[j].elem).css({
                        'color':'#000'
                    });
                }
            }
        }
    }

}

function refresh_favorites()
{
    // Load favorite favicons
    var favlist = Fav.list();
    var fll = favlist.length;
    var favbar = $('#topbar #favbar');
    favbar.empty();
    for(var i=0; i < fll; i++) {
        if(favlist[i].favIconUrl) {
            var img = $('').attr('src',favlist[i].favIconUrl)
                                .width('24px')
                                .height('24px');
            var link = $('').attr('href', favlist[i].url);
            link.append(img);
            favbar.append(link);
        }
    }
}
<|endoftext|>


<commit_before>// DOM Manipulation Challenge

// I worked on this challenge by myself, with: Peter Leong.

// Add your JavaScript calls to this page:

// Release 0:
// Add the class "done" to the #release-0 div.

document.getElementById("release-0").className = "done";

// Release 1:
// Set the display property of the #release-1 div to none.
document.getElementById("release-1").style.display = "none";

// Release 2:
// Change the inner text of the <h1> tag to "I completed release 2."
document.getElementsByTagName('h1')[0].innerHTML = "I completed release 2";

// Release 3:
// Add the background color #955251 to the #release-3 div. #955251 was Pantone's (Links to an external site.) color of the year for 2015!
document.getElementById("release-3").style.backgroundColor = "#955251";

// Release 4:
// Select all occurrences of class .release-4 and change the text-size to 2em.
var x = document.getElementsByClassName("release-4");
for (var i=0;i<x.length; i++){
	x[i].style.fontSize = "2em";
};

// Release 5:
// Take the HTML in the template.hidden and append it to the bottom of the page. Use the Treehouse Blog Template Tag (Links to an external site.) resource for help.
var tmpl = document.getElementById('hidden');
document.body.appendChild(tmpl.content.cloneNode(true));<commit_msg>Fix text for partner, add questions for reflection<commit_after>// DOM Manipulation Challenge

// I worked on this challenge with Peter Leong.

// Add your JavaScript calls to this page:

// Release 0:
// Add the class "done" to the #release-0 div.

document.getElementById("release-0").className = "done";

// Release 1:
// Set the display property of the #release-1 div to none.
document.getElementById("release-1").style.display = "none";

// Release 2:
// Change the inner text of the <h1> tag to "I completed release 2."
document.getElementsByTagName('h1')[0].innerHTML = "I completed release 2";

// Release 3:
// Add the background color #955251 to the #release-3 div. #955251 was Pantone's (Links to an external site.) color of the year for 2015!
document.getElementById("release-3").style.backgroundColor = "#955251";

// Release 4:
// Select all occurrences of class .release-4 and change the text-size to 2em.
var x = document.getElementsByClassName("release-4");
for (var i=0;i<x.length; i++){
	x[i].style.fontSize = "2em";
};

// Release 5:
// Take the HTML in the template.hidden and append it to the bottom of the page. Use the Treehouse Blog Template Tag (Links to an external site.) resource for help.
var tmpl = document.getElementById('hidden');
document.body.appendChild(tmpl.content.cloneNode(true));<|endoftext|>


<commit_before>import Ember from 'ember';
import {
  encode
} from 'wherehows-web/utils/encode-decode-uri-component-with-space';

const {
  Service,
  getOwner,
  isBlank
} = Ember;

export default Service.extend({
  /**
   * Transition to the search route including search keyword as query parameter
   * @param {Object} args a map of query parameters to values, including keyword
   * @prop {String|*} args.keyword the string to search for
   * @returns {void|Transition|EmberStates.Transition}
   */
  showSearchResults(args) {
    let {keyword} = args;

    // Transition to search route only if value is not null or void
    if (!isBlank(keyword)) {
      // Lookup application Route on ApplicationInstance
      const applicationRoute = getOwner(this).lookup('route:application');
      keyword = encode(keyword);

      return applicationRoute.transitionTo('search', {
        queryParams: {keyword}
      });
    }
  }
});
<commit_msg>Updates code style for search service<commit_after>import Ember from 'ember';
import {
  encode
} from 'wherehows-web/utils/encode-decode-uri-component-with-space';

const {
  Service,
  getOwner,
  isBlank
} = Ember;

export default Service.extend({
  /**
   * Transition to the search route including search keyword as query parameter
   * @param {Object} args a map of query parameters to values, including keyword
   * @prop {String|*} args.keyword the string to search for
   * @returns {void|Transition|EmberStates.Transition}
   */
  showSearchResults(args) {
    let { keyword } = args;

    // Transition to search route only if value is not null or void
    if (!isBlank(keyword)) {
      // Lookup application Route on ApplicationInstance
      const applicationRoute = getOwner(this).lookup('route:application');
      keyword = encode(keyword);

      return applicationRoute.transitionTo('search', {
        queryParams: { keyword }
      });
    }
  }
});
<|endoftext|>


<commit_before>//////////////////////////////
// Server-Side Sandbox     //
/////////////////////////////

// var firmata = require('firmata');

// var board = new firmata.Board('/dev/cu.usbmodem1421', function(err){
//   if (err) {
//     throw new Error(err);
//   }

// });

//////////////////////////////
// Client-Side Sandbox     //
/////////////////////////////

console.log('quicktest');
// p5.board('/dev/cu.usbmodem1421', 'arduino');

//////////////////////
// Example Scripts //
//////////////////////

// Board setup — obviously you may need to change the port
// p5.board('/dev/cu.usbmodem1421', 'arduino');

// // Test digital write
// var p = p5.pin(9, 'DIGITAL', 'OUTPUT');
// p.write('HIGH');

// // Test PWM write
// var p = p5.pin(9, 'PWM', 'OUTPUT');
// p.write(150);

// // Test digital read -- only uncomment one p.read() at a time
// var p = p5.pin(9, 'DIGITAL', 'INPUT');
// p.read(["val", "console.log('read val', val)"]);
// p.read();
// setInterval(function() { console.log(p.val) }, 500);

// // Test analog read -- only uncomment one p.read() at a time
// var p = p5.pin(0, 'ANALOG', 'INPUT');
// p.read(["val", "console.log('read val', val)"]);
// p.read();
// setInterval(function() { console.log(p.val) }, 500);

// // Draw ellipses with a button -- these work on the same
// // setup as the pin reads

// var p;

// function setup() {

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   p = p5.pin(9, 'DIGITAL', 'INPUT');
//   p.read();

//   createCanvas(1200, 500);
//   noStroke();
// }

// function draw() {
//   if (p.val) {
//     fill(Math.random() * 255, Math.random() * 255, Math.random() * 255);
//     ellipse(Math.random() * width, Math.random() * height, 60, 60);
//   }
// }

// Click the circle to light the LED -- this works on the same
// setup as the pin writes
// var pin;

// function setup() {
//   createCanvas(400, 400);
//   noStroke();
//   fill(62, 0, 255);
//   ellipse(width/2, height/2, 100, 100);

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   pin = p5.pin(9, 'DIGITAL', 'OUTPUT');
// }

// function mousePressed() {
//   var d = dist(width/2, height/2, mouseX, mouseY);
//   if (d < 100) {
//     pin.write('HIGH');
//   }
// }

// function mouseReleased() {
//   pin.write('LOW');
// }

// // Click a button to light the LED -- this works on the same
// // setup as the pin writes & uses the p5.dom lib

// function setup() {
//   createCanvas(400, 400);

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   var pin = p5.pin(9, 'DIGITAL', 'OUTPUT');

//   var button = createButton('LIGHT THE LED!!');
//   button.position(width/2, height/2);
//   button.mousePressed(function(){
//     pin.write('HIGH');
//   });

//   button.mouseReleased(function(){
//     pin.write('LOW');
//   });
// }<commit_msg>PWM example<commit_after>//////////////////////////////
// Server-Side Sandbox     //
/////////////////////////////

// var firmata = require('firmata');

// var board = new firmata.Board('/dev/cu.usbmodem1421', function(err){
//   if (err) {
//     throw new Error(err);
//   }

// });

//////////////////////////////
// Client-Side Sandbox     //
/////////////////////////////

console.log('quicktest');
// p5.board('/dev/cu.usbmodem1421', 'arduino');

//////////////////////
// Example Scripts //
//////////////////////

// Board setup — obviously you may need to change the port
// p5.board('/dev/cu.usbmodem1421', 'arduino');

// // Test digital write
// var p = p5.pin(9, 'DIGITAL', 'OUTPUT');
// p.write('HIGH');

// // Test PWM write
// var p = p5.pin(9, 'PWM', 'OUTPUT');
// p.write(150);

// // Test digital read -- only uncomment one p.read() at a time
// var p = p5.pin(9, 'DIGITAL', 'INPUT');
// p.read(["val", "console.log('read val', val)"]);
// p.read();
// setInterval(function() { console.log(p.val) }, 500);

// // Test analog read -- only uncomment one p.read() at a time
// var p = p5.pin(0, 'ANALOG', 'INPUT');
// p.read(["val", "console.log('read val', val)"]);
// p.read();
// setInterval(function() { console.log(p.val) }, 500);

// // Draw ellipses with a button -- these work on the same
// // setup as the pin reads

// var p;

// function setup() {

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   p = p5.pin(9, 'DIGITAL', 'INPUT');
//   p.read();

//   createCanvas(1200, 500);
//   noStroke();
// }

// function draw() {
//   if (p.val) {
//     fill(Math.random() * 255, Math.random() * 255, Math.random() * 255);
//     ellipse(Math.random() * width, Math.random() * height, 60, 60);
//   }
// }

// // Click the circle to light the LED -- this works on the same
// // setup as the pin writes
// var pin;

// function setup() {
//   createCanvas(400, 400);
//   noStroke();
//   fill(62, 0, 255);
//   ellipse(width/2, height/2, 100, 100);

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   pin = p5.pin(9, 'DIGITAL', 'OUTPUT');
// }

// function mousePressed() {
//   var d = dist(width/2, height/2, mouseX, mouseY);
//   if (d < 100) {
//     pin.write('HIGH');
//   }
// }

// function mouseReleased() {
//   pin.write('LOW');
// }

// // Click a button to light the LED -- this works on the same
// // setup as the pin writes & uses the p5.dom lib

// function setup() {
//   createCanvas(400, 400);

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   var pin = p5.pin(9, 'DIGITAL', 'OUTPUT');

//   var button = createButton('LIGHT THE LED!!');
//   button.position(width/2, height/2);
//   button.mousePressed(function(){
//     pin.write('HIGH');
//   });

//   button.mouseReleased(function(){
//     pin.write('LOW');
//   });
// }

// PWM Slider -- Same setup as above

// var slider, pin;

// function setup() {
//   slider = createSlider(0, 255, 150);
//   slider.position = (10, 10);

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   pin = p5.pin(9, 'PWM', 'OUTPUT');

// }

// function draw() {
//   var val = slider.value();
//   pin.write(val);
// }<|endoftext|>


<commit_before>
"use strict";

import Model from '../classes/Model';
import Collection from '../classes/Collection';

let http = undefined;
let cache = undefined;

/**
 * Default base Manager to extend upon.
 */
export default class Manager {

    /**
     * Class constructor.
     *
     * @param object $http Injected $http service.
     * @param object $cacheFactory Injector $cacheFactory service.
     * @return void
     */
    constructor($http, $cacheFactory) {
        http = $http;
        if (cache === undefined) {
            cache = $cacheFactory('monad-managers');
        }
        /**
         * Bindable pointer for specified list filters, if any.
         */
        this.filter = {};
    }

    /**
     * Apply the currently set filter to params.
     *
     * @param object params Hash of params to augment.
     * @return object Augmented params.
     */
    applyFilter(params) {
        if (this.filter) {
            for (let p in this.filter) {
                if (this.filter[p] !== false) {
                    params[p] = this.filter[p];
                }
            }
        }
        return params;
    }

    /**
     * Virtual getter for the cache object.
     */
    get cache() {
        return cache;
    }

    /**
     * Virtual count of total current list items. Here it returns 0; your custom
     * Manager _may_ offer an actual implementation of this (it depends on the
     * API you're using).
     *
     * @return integer Number of total items in the current list.
     */
    get count() {
        return 0;
    }

    /**
     * Retrieve a list (Collection) of items.
     *
     * @param string url The API URL to query.
     * @return Collection A collection of Models found.
     */
    list(url) {
        return new this.constructor.Collection(http.get(url, cache));
    }

    /**
     * Find a single item.
     *
     * @param string url The API URL to query.
     * @return Model A Model.
     */
    find(url) {
        return new this.constructor.Model(http.get(url, cache));
    }

    /**
     * Save the specified model back to the API.
     *
     * @param object model The model to save.
     * @return mixed On success, a Promise yielding the API's return value on
     *  `success`. On failure (because e.g. model is not dirty) an empty object.
     */
    save(model) {
        if (model.$new) {
            return this.create(model).then(result => model.$load(result.data));
        } else if (model.$deleted) {
            return this['delete'](model).then(() => {
                model.$load(undefined);
            });
        } else if (model.$dirty) {
            return this.update(model).then(result => model.$load(result.data));
        }
        return {};
    }

    /**
     * API interface. This should be overridden by a custom implementation,
     * since we have no way to guesstimate how your API works. Hence, this
     * throws an error as a friendly reminder :)
     *
     * The actual implementations should return promises.
     *
     * @param object model The model to create.
     */
    create(model) {
        throw "Manager.create must use a custom implementation.";
    }

    /**
     * API interface. This should be overridden by a custom implementation,
     * since we have no way to guesstimate how your API works. Hence, this
     * throws an error as a friendly reminder :)
     *
     * The actual implementations should return promises.
     *
     * @param object model The model to update.
     */
    update(model) {
        throw "Manager.update must use a custom implementation.";
    }

    /**
     * API interface. This should be overridden by a custom implementation,
     * since we have no way to guesstimate how your API works. Hence, this
     * throws an error as a friendly reminder :)
     *
     * The actual implementations should return promises.
     *
     * @param object model The model to delete.
     */
    ['delete'](model) {
        throw "Manager.delete must use a custom implementation.";
    }

    /**
     * Virtual property to access the $http service.
     *
     * @return object Angular $http service.
     */
    get http() {
        return http;
    }

    set order(column) {
        let order = wm.get(this);
        if (order.column != column) {
            order.column = column;
            order.ascending = false;
            wm.set(this, order);
        }
    }

    get order() {
        return wm.get(this).order;
    }

    set ascending(stat) {
        let order = wm.get(this);
        order.ascending = stat;
        wm.set(this, order);
    }

    get ascending() {
        return wm.get(this).ascending;
    }

};

Manager.$inject = ['$http', '$cacheFactory'];
/**
 * The current Model class to work on. You may set this per derived
 * manager where needed. Defaults to base Monad Model.
 */
Manager.Model = Model;
/**
 * The current Collection object to work on. You may set this per
 * derived manager where needed. Defaults to base Monad Collection.
 */
Manager.Collection = Collection;

<commit_msg>cleanup<commit_after><|endoftext|>


<commit_before>var localforage = require('localforage');
var lodash = require('lodash');

var storageVersion = 3;

function fullKeyFor(key) {
  return 'workspaces/' + storageVersion + '/' + key;
}

var Storage = {
  getCurrentProjectKey: function() {
    return localforage.getItem('currentProjectKey');
  },

  setCurrentProjectKey: function(projectKey) {
    localforage.setItem('currentProjectKey', projectKey);
  },

  all: function() {
    return localforage.getItem('allKeys').then(function(keys) {
      return Promise.all(keys.map(this.load));
    }.bind(this));
  },

  load: function(projectKey) {
    return localforage.getItem(fullKeyFor(projectKey)).then(function(payload) {
      if (payload !== null) {
        return payload;
      }
    });
  },

  save: function(data) {
    var key = data.projectKey;

    localforage.getItem('allKeys').then(function(oldKeys) {
      if (oldKeys === null || oldKeys[oldKeys.length - 1] !== key) {
        var keys = lodash.without(oldKeys || [], key);
        keys.unshift(key);
        localforage.setItem('allKeys', keys);
      }
    });

    localforage.setItem(
      fullKeyFor(key),
      lodash.extend({
        storageVersion: storageVersion,
        updatedAt: new Date(),
      }, data)
    );

    return data;
  },
};

module.exports = Storage;
<commit_msg>Wait for project to finish saving before updating key list<commit_after>var localforage = require('localforage');
var lodash = require('lodash');

var storageVersion = 3;

function fullKeyFor(key) {
  return 'workspaces/' + storageVersion + '/' + key;
}

var Storage = {
  getCurrentProjectKey: function() {
    return localforage.getItem('currentProjectKey');
  },

  setCurrentProjectKey: function(projectKey) {
    localforage.setItem('currentProjectKey', projectKey);
  },

  all: function() {
    return localforage.getItem('allKeys').then(function(keys) {
      return Promise.all(keys.map(this.load));
    }.bind(this));
  },

  load: function(projectKey) {
    return localforage.getItem(fullKeyFor(projectKey)).then(function(payload) {
      if (payload !== null) {
        return payload;
      }
    });
  },

  save: function(data) {
    var key = data.projectKey;

    localforage.setItem(
      fullKeyFor(key),
      lodash.extend({
        storageVersion: storageVersion,
        updatedAt: new Date(),
      }, data)
    ).then(function() {
      localforage.getItem('allKeys').then(function(oldKeys) {
        if (oldKeys === null || oldKeys[oldKeys.length - 1] !== key) {
          var keys = lodash.without(oldKeys || [], key);
          keys.unshift(key);
          localforage.setItem('allKeys', keys);
        }
      });
    });

    return data;
  },
};

module.exports = Storage;
<|endoftext|>


<commit_before>const http = require('http');
const express = require('express');
const nunjucks = require('nunjucks');
const compress = require('compression');
const body = require('body-parser');

function create(ctl) {
  const config = ctl.config();
  const log = ctl.log('server');
  const app = express();
  const opts = config.server || {};
  app.set('x-powered-by', false);
  if (opts.staticDir && opts.static !== false) {
    app.use(opts.static, express.static(opts.staticDir));
  }
  app.use(compress());
  app.use(body.json({ limit: '25mb' }));
  app.use(log.morgan());
  app.set('view engine', 'html');
  const env = nunjucks.configure(opts.viewsDir, {
    express: app,
    noCache: (ctl.stage() !== 'production'),
  });

  app.views = {
    render: (view, overrides) => {
      const vars = Object.assign({}, locals, overrides);
      return env.render(view, vars);
    },
  };
  app.use((req, res, next) => {
    res.locals.staticUrl = opts.staticUrl;
    res.locals.baseUrl = opts.baseUrl;
    next();
  });
  return app;
}

async function start(app, ctl) {
  const config = ctl.config();
  const log = ctl.log('server');
  const { port = 8080, host } = config.server || {};
  const server = http.createServer(app);
  server.on('listening', () => {
    const addr = server.address();
    let realHost = '<unknown-host>';
    let realPort = '<unknown-port>';
    if (addr) {
      realHost = addr.address;
      realPort = addr.port;
    }
    log.info('Server started listening at http://%s:%s', realHost, realPort);
  });
  await server.listen(port, host);
}

module.exports = {
  create,
  start,
};
<commit_msg>Add staticOpts<commit_after>const http = require('http');
const express = require('express');
const nunjucks = require('nunjucks');
const compress = require('compression');
const body = require('body-parser');

function create(ctl) {
  const config = ctl.config();
  const log = ctl.log('server');
  const app = express();
  const opts = config.server || {};
  app.set('x-powered-by', false);
  if (opts.staticDir && opts.static !== false) {
    app.use(opts.static, express.static(opts.staticDir, opts.staticOpts || {}));
  }
  app.use(compress());
  app.use(body.json({ limit: '25mb' }));
  app.use(log.morgan());
  app.set('view engine', 'html');
  const env = nunjucks.configure(opts.viewsDir, {
    express: app,
    noCache: (ctl.stage() !== 'production'),
  });

  app.views = {
    render: (view, overrides) => {
      const vars = Object.assign({}, locals, overrides);
      return env.render(view, vars);
    },
  };
  app.use((req, res, next) => {
    res.locals.staticUrl = opts.staticUrl;
    res.locals.baseUrl = opts.baseUrl;
    next();
  });
  return app;
}

async function start(app, ctl) {
  const config = ctl.config();
  const log = ctl.log('server');
  const { port = 8080, host } = config.server || {};
  const server = http.createServer(app);
  server.on('listening', () => {
    const addr = server.address();
    let realHost = '<unknown-host>';
    let realPort = '<unknown-port>';
    if (addr) {
      realHost = addr.address;
      realPort = addr.port;
    }
    log.info('Server started listening at http://%s:%s', realHost, realPort);
  });
  await server.listen(port, host);
}

module.exports = {
  create,
  start,
};
<|endoftext|>


<commit_before>import { AbstractFractal } from '../abstract'

export class BifurcationFractal extends AbstractFractal {

  constructor ({
    x, // (r)
    y = 0.5, // (p)
    minX,
    minY,
    maxX,
    maxY,
    width,
    height,
    depth
  }) {
    super(...arguments)

    this.x = x
    this.y = y
    this.minX = minX
    this.minY = minY
    this.maxX = maxX
    this.maxY = maxY
    this.cursor = 0
  }

  setup () {
    this.clear()

    this.deltas = {
      x: (this.maxX - this.minX) / this.width,
      y: (this.maxY - this.minY) / this.height
    }
  }

  moveUnit (cursor) {
    const scale = this.minX + this.deltas.x * cursor

    this.y = this.y * scale * (1 - this.y)
  }

  renderUnit (cursor) {
    // waits to give the function time to converge
    if (cursor > 100) {
      const x = this.cursor
      const y = this.height - (this.y - this.minY) / this.deltas.y

      this.context.fillRect(x, y, 1, 1)
    }
  }

  iterate (axiom = this.cursor) {
    this.y = 0.5

    for (let at = 0; at < 200; at += 1) {
      this.moveUnit(this.cursor)
      this.renderUnit(at)
    }

    if (++this.cursor < this.width) {
      this.iterate(axiom)
    }
  }

}
<commit_msg>:scroll: :sparkles: Slightly improved readability of sets/bifurcation/moveUnit method<commit_after>import { AbstractFractal } from '../abstract'

export class BifurcationFractal extends AbstractFractal {

  constructor ({
    x, // (r)
    y = 0.5, // (p)
    minX,
    minY,
    maxX,
    maxY,
    width,
    height,
    depth
  }) {
    super(...arguments)

    this.x = x
    this.y = y
    this.minX = minX
    this.minY = minY
    this.maxX = maxX
    this.maxY = maxY
    this.cursor = 0
  }

  setup () {
    this.clear()

    this.deltas = {
      x: (this.maxX - this.minX) / this.width,
      y: (this.maxY - this.minY) / this.height
    }
  }

  moveUnit (cursor) {
    const scale = this.minX + this.deltas.x * cursor
    const diff = 1 - this.y

    this.y = this.y * scale * diff
  }

  renderUnit (cursor) {
    // waits to give the function time to converge
    if (cursor > 100) {
      const x = this.cursor
      const y = this.height - (this.y - this.minY) / this.deltas.y

      this.context.fillRect(x, y, 1, 1)
    }
  }

  iterate (axiom = this.cursor) {
    this.y = 0.5

    for (let at = 0; at < 200; at += 1) {
      this.moveUnit(this.cursor)
      this.renderUnit(at)
    }

    if (++this.cursor < this.width) {
      this.iterate(axiom)
    }
  }

}
<|endoftext|>


<commit_before>var _Memcached = require('memcached'),
    settings = require('./settings').sharedInstance(),
    Singleton = require('./singleton');

class Memcached {
    constructor() {
        this.instance = new _Memcached(`${settings.memcachedHost}:${settings.memcachedPort}`);
    }

    get(key) {
        return new Promise((resolve, reject) => {
            this.instance.get(key, (err, d) => {
                if(err) {
                    reject(err);
                } else {
                    resolve(d);
                }
            });
        });
    }

    set(key, value) {
        return new Promise((resolve, reject) => {
            this.instance.set(key, value, 2592000, (err) => {
                if(err) {
                    reject(err);
                } else {
                    resolve(value);
                }
            });
        });
    }

    flush() {
        return new Promise((resolve, reject) => {
            this.instance.flush((err) => {
               if(err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        })
    }

}

module.exports = new Singleton(Memcached);
<commit_msg>Add del command to memcached helper<commit_after>var _Memcached = require('memcached'),
    settings = require('./settings').sharedInstance(),
    Singleton = require('./singleton');

class Memcached {
    constructor() {
        this.instance = new _Memcached(`${settings.memcachedHost}:${settings.memcachedPort}`);
    }

    get(key) {
        return new Promise((resolve, reject) => {
            this.instance.get(key, (err, d) => {
                if(err) {
                    reject(err);
                } else {
                    resolve(d);
                }
            });
        });
    }

    set(key, value) {
        return new Promise((resolve, reject) => {
            this.instance.set(key, value, 2592000, (err) => {
                if(err) {
                    reject(err);
                } else {
                    resolve(value);
                }
            });
        });
    }

    flush() {
        return new Promise((resolve, reject) => {
            this.instance.flush((err) => {
               if(err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        })
    }

    del(key) {
        return new Promise((resolve, reject) => {
            this.instance.del(key, (err) => {
               if(err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        });
    }
}

module.exports = new Singleton(Memcached);
<|endoftext|>


<commit_before>import {isNil, mapObjIndexed, merge, type} from 'ramda';
import {Rx} from '@cycle/core';

/**
 * Returns a function that takes an object as argument. The function predicates
 * each property of the provided object with the matching properties
 * of `definitions`. If the value of a definition is a function, it will
 * be called as predicate taking the matching object property as argument.
 * If the definition value is an object, it will look for the predicate
 * function specified by `predicateKey` (defaults to `type`).
 * @param {Object} definitions Object of properties to match.
 * @param {String} predicateKey Optional name of the property specifying
 * the predicate.
 * @returns {Function} Takes the Object to predicate as argument.
 */
function predicateObject(definitions, predicateKey = `type`) {
  return (obj) => {
    const valueWithDefault = function valueWithDefault(v, k) {
      const predicate = type(v) === `Function` ? v : v[predicateKey];
      const prop = obj[k];
      try {
        return !isNil(prop) ?
          predicate(prop) :
          v.default;
      } catch (e) {
        throw new TypeError(`${k}: ${e.message}`);
      }
    };

    return merge(obj, mapObjIndexed(valueWithDefault, definitions));
  };
}

/**
 * Returns a function that takes an Observable as argument. The function maps
 * the items of the Observable and passes the item as argument
 * to `predicateFunc`
 * @param {Function} predicateFunc Function to receive items from Observable.
 * @returns {Function} Takes the Observable as argument whose items
 * to predicate.
 */
function predicateObservable(predicateFunc) {
  return (observable$) => {
    return observable$.map((item) => predicateFunc(item));
  };
}

/**
 * Returns a function that takes an Observable that emits Objects as argument.
 * @param {Object} definitions Object of properties to match.
 * @param {String} predicateKey Optional name of the property specifying
 * the predicate.
 * @returns {Function} Takes the Observable as argument whose objects
 * to predicate.
 */
function predicateObjectOfObservable(definitions, predicateKey) {
  return (observable$ = Rx.Observable.just({})) => {
    return predicateObservable(
      predicateObject(definitions, predicateKey)
    )(observable$);
  };
}

export {
  predicateObject,
  predicateObservable,
  predicateObjectOfObservable,
};
<commit_msg>refactor(shared): add default `void 0` to `predicateKey`<commit_after>import {isNil, mapObjIndexed, merge, type} from 'ramda';
import {Rx} from '@cycle/core';

/**
 * Returns a function that takes an object as argument. The function predicates
 * each property of the provided object with the matching properties
 * of `definitions`. If the value of a definition is a function, it will
 * be called as predicate taking the matching object property as argument.
 * If the definition value is an object, it will look for the predicate
 * function specified by `predicateKey` (defaults to `type`).
 * @param {Object} definitions Object of properties to match.
 * @param {String} predicateKey Optional name of the property specifying
 * the predicate.
 * @returns {Function} Takes the Object to predicate as argument.
 */
function predicateObject(definitions, predicateKey = `type`) {
  return (obj) => {
    const valueWithDefault = function valueWithDefault(v, k) {
      const predicate = type(v) === `Function` ? v : v[predicateKey];
      const prop = obj[k];
      try {
        return !isNil(prop) ?
          predicate(prop) :
          v.default;
      } catch (e) {
        throw new TypeError(`${k}: ${e.message}`);
      }
    };

    return merge(obj, mapObjIndexed(valueWithDefault, definitions));
  };
}

/**
 * Returns a function that takes an Observable as argument. The function maps
 * the items of the Observable and passes the item as argument
 * to `predicateFunc`
 * @param {Function} predicateFunc Function to receive items from Observable.
 * @returns {Function} Takes the Observable as argument whose items
 * to predicate.
 */
function predicateObservable(predicateFunc) {
  return (observable$) => {
    return observable$.map((item) => predicateFunc(item));
  };
}

/**
 * Returns a function that takes an Observable that emits Objects as argument.
 * @param {Object} definitions Object of properties to match.
 * @param {String} predicateKey Optional name of the property specifying
 * the predicate.
 * @returns {Function} Takes the Observable as argument whose objects
 * to predicate.
 */
function predicateObjectOfObservable(definitions, predicateKey = void 0) {
  return (observable$ = Rx.Observable.just({})) => {
    return predicateObservable(
      predicateObject(definitions, predicateKey)
    )(observable$);
  };
}

export {
  predicateObject,
  predicateObservable,
  predicateObjectOfObservable,
};
<|endoftext|>