<commit_before>$(document).ready(function() {

	// Adicionar Elementos na Tabela
	$("#add").submit(function(event) {
			var assunto = $("#aprender").val();

        	if(assunto.trim() != "") {

        		var radio = $('input[name=assuntos]');
        		var checkedValue = radio.filter(':checked').val();
        		var index = $("#list tr").length + 1;

        		if(checkedValue == "sim") {
                    $("#list").append(
                    		"
" +
                    		"<input type=checkbox name=chk>	" +
                    		"" + index + "	" +
                    		""+ assunto + "	" +
                    		"J\u00e1 Aprendi	" +
                    	    "
");
        		}else{
        			$("#list").append(
                    		"
" +
                    		"<input type=checkbox name=chk>	" +
                    		"" + index + "	" +
                    		""+ assunto + "	" +
                    		"Gostaria de Aprender	" +
                    	    "
");
        		}
        	}
        	event.preventDefault();
        });

	$("#dl-btn").on("click", function(event) {
		var ch = $(document).find("input[name='chk']");
		var sel = false;
		var c = confirm("Continue delete?");

		if(c) {
			ch.each(function() {
				var $this = $(this);
				if($this.is(":checked")) {
					sel = true;
					$this.parents("tr").fadeOut(function() {
						$this.remove();
					});
				}
			});
			if(!sel) {
				alert("Nenhuma linha selecionada");
			}
		}
	});
});<commit_msg>pequeno ajuste do script<commit_after>$(document).ready(function() {
	var index = 1;

	// Adicionar Elementos na Tabela
	$("#add").submit(function(event) {
			var assunto = $("#aprender").val();

        	if(assunto.trim() != "") {

        		var radio = $('input[name=assuntos]');
        		var checkedValue = radio.filter(':checked').val();

        		if(checkedValue == "sim") {
                    $("#list").append(
                    		"
" +
                    		"<input type=checkbox name=chk>	" +
                    		"" + index + "	" +
                    		""+ assunto + "	" +
                    		"J\u00e1 Aprendi	" +
                    	    "
");
        		}else{
        			$("#list").append(
                    		"
" +
                    		"<input type=checkbox name=chk>	" +
                    		"" + index + "	" +
                    		""+ assunto + "	" +
                    		"Gostaria de Aprender	" +
                    	    "
");
        		}
        	}
        	index++;
        	event.preventDefault();
        });

	// Remove N itens da lista de assuntos
	$("#dl-btn").on("click", function(event) {
		var ch = $("input[name='chk']");
		var sel = false;
		var c = confirm("Continue delete?");

		if(c) {
			ch.each(function() {
				var $this = $(this);
				if($this.is(":checked")) {
					sel = true;
					$this.parents("tr").fadeOut(function() {
						$this.remove();
						index = index - $this.length;
					});
				}
			});
			if(!sel) {
				alert("Nenhuma linha selecionada");
			}
		}
	});
});<|endoftext|>


<commit_before>//     Proto.js v1.0.3

//     (c) 2015-2016 Adrian C. Miranda
//     Proto may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://ambox.github.io
(function(global, name, version, factory){
  'use strict';

  /* globals define:false, module:false */
  if(typeof module === 'object' && typeof module.exports === 'object'){

    // Set up for Node.js or CommonJS.
    global[name] = module.exports = factory(global, exports, name, version);

  }else if(typeof define === 'function' && define.amd){

    // Next for module appropriately for the environment. Start with AMD.
    define(['exports'], function(exports){
      return factory(global, exports, name, version);
    });

  }else{

    // Finally, as a browser global.
    global[name] = factory(global, {}, name, version);

  }

}(typeof window !== 'undefined'? window : this, 'Proto', '1.0.3', function(global, exports, name, version){
  'use strict';

  // Helpers
  // -------

  function ape(fn){
    return function(){
      return Function.call.apply(fn, arguments);
    };
  }

  var slice = ape(Array.prototype.slice);

  var isArray = Array.isArray;

  var toStr = ape(Object.prototype.toString);

  var reSuper = /\bsuper\b/;

  var reFnDeclaration = /^.*function\s([^\s]*|[^\(]*)\([^\x00]+$/;

  var reObjectWrapper = /^(\[object(\s|\uFEFF|\xA0))|(\])$/g;

  var numInstances = 0;

  function isLikeObject(value){
    return value === Object(value);
  }

  function isObject(value){
    return toStr(value) === '[object Object]';
  }

  function isFunction(value){
    return typeof value === 'function';
  }

  function isString(value){
    return typeof value === 'string';
  }

  function iteraction(ctx, key, value, index, getEnum, fn){
    if(getEnum || value.hasOwnProperty(key)){
      return fn.call(ctx || value[key], value[key], key, index, value);
    }
  }

  function each(value, fn, ctx, getEnum){
    var ctr, index = 0, isFn = isFunction(value);
    for(var key in value){
      ctr = isFn? key !== 'prototype' && key !== 'length' && key !== 'name' : true;
      if(ctr && iteraction(ctx, key, value, index++, getEnum, fn) === false){
        break;
      }
    }
  }

  function copy(child){
    var Clone = function(){};
    Clone.prototype = child && child.prototype || child;
    return new Clone();
  }

  function create(child, properties){
    if(child === null){return {};}
    var Child = function(){};
    Child.prototype = child;
    child = new Child();
    each(properties, function(value, property){
      child[property] = value.value;
    });
    return child;
  }

  if(!isFunction(Object.create)){
    Object.create = create;
  }

  function merge(overwrite, target){
    var args = slice(arguments, 2);
    each(args, function(parameter){
      each(parameter, function(value, key){
        if(isObject(value) && isObject(target[key])){
          merge(overwrite, target[key], value);
        }else if(overwrite || !target[key]){
          target[key] = value;
        }
      }, null, true);
    });
    return target;
  }

  function shallowMerge(target){
    var args = slice(arguments, 1);
    each(args, function(parameter){
      each(parameter, function(value, key){
        target[key] = value;
      });
    });
    return target;
  }

  function copyShallowObjectsFrom(child){
    var copy = {};
    each(child, function(value, key){
      if(isObject(value)){
        copy[key] = value;
      }
    }, null, true);
    return copy;
  }

  function keys(object, getEnum){
    var properties = [];
    each(object, function(value, key){
      properties.push(key);
    }, null, getEnum);
    return properties;
  }

  function overload(target, name, fn){
    var cache = target[name];
    target[name] = function(){
      if(fn.length === arguments.length){
        return fn.apply(this, arguments);
      }else if(isFunction(cache)){
        return cache.apply(this, arguments);
      }
    };
  }

  function flush(object){
    for(var key in object){
      if(object.hasOwnProperty(key)){
        delete object[key];
      }
    }
  }

  function bind(fn, context){
    var args = slice(arguments, 2);
    var proxy = function(){
      return fn.apply(context, args.concat(slice(arguments)));
    };
    proxy.__bind__ = proxy.__bind__ || fn;
    return proxy;
  }

  function unbind(fn){
    var cache = fn.__bind__;
    delete fn.__bind__;
    return cache;
  }

  function mapContext(fn, context, methods){
    methods = methods.length? methods : keys(context, true);
    each(methods, function(method){
      if(isFunction(context[method])){
        context[method] = fn(context[method], context);
      }
    });
    return context;
  }

  function bindAll(context, methods){
    methods = isArray(methods)? methods : slice(arguments, 1);
    return mapContext(bind, context, methods);
  }

  function unbindAll(context, methods){
    methods = isArray(methods)? methods : slice(arguments, 1);
    return mapContext(unbind, context, methods);
  }

  function createSuperMethod(action, value){
    var pointer = isFunction(value)? value : function $super(){
      return value;
    };
    return function Class(){
      this.super = pointer;
      return action.apply(this, arguments);
    };
  }

  function hasSuperCall(fn){
    return isFunction(fn) && reSuper.test(fn.toString());
  }

  function injectMethod(parent, child, fn, key){
    if(hasSuperCall(fn) && isLikeObject(parent)){
      child[key] = createSuperMethod(fn, parent[key]);
    }else{
      child[key] = fn;
    }
  }

  function enableSuperMethods(parent, child){
    each(child, bind(injectMethod, null, parent, child));
    return child;
  }

  function inherit(Proto, parent, child){
    var caste = child;
    child = createSuperMethod(child, parent);
    shallowMerge(child, caste);
    shallowMerge(child.prototype, caste.prototype);
    flush(caste);

    shallowMerge(child, parent);

    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent instanceof Proto? null : parent.prototype;
    child.prototype = Object.create(Surrogate.prototype);
    child.super = parent.prototype;
    return child;
  }

  // Proto
  // -----

  function Proto(caste){
    Proto.size = numInstances++;
    caste = createSuperMethod(caste, null);
    caste.prototype.$protoID = Proto.size;
    caste.prototype.toString = this.toString;
    caste.prototype.toString = this.toString;
    caste.prototype.flush = this.flush;
    caste.overload = this.overload;
    caste.extends = this.extends;
    caste.public = this.public;
    return caste;
  }

  Proto.size = 0;
  Proto.create = Object.create;
  Proto.each = each;
  Proto.unbindAll = unbindAll;
  Proto.bindAll = bindAll;
  Proto.unbind = unbind;
  Proto.bind = bind;
  Proto.overload = overload;
  Proto.copyShallowObjects = copyShallowObjectsFrom;
  Proto.shallowMerge = shallowMerge;
  Proto.flush = flush;
  Proto.keys = keys;
  Proto.copy = copy;
  Proto.ape = ape;
  Proto.isArray = isArray;
  Proto.isLikeObject = isLikeObject;
  Proto.isObject = isObject;
  Proto.isFunction = isFunction;
  Proto.isString = isString;
  Proto.merge = bind(merge, null, true);

  Proto.of = function(value, qualified){
    var type = toStr(value);
    if(qualified && type === '[object Object]'){
      return value.constructor.toString().replace(reFnDeclaration, '$1') || 'Object';
    }
    return type.replace(reObjectWrapper, '');
  };

  Proto.prototype = {

    option:function(options){
      if(isString(options) && this.options){
        return this.options[options];
      }else if(isLikeObject(options)){
        this.options = merge(true, {}, this.defaults, options);
      }
      return isLikeObject(this.options)? this.options : {};
    },

    extends:function(parent){
      return inherit(Proto, parent, this);
    },

    public:function(name, definition){
      if(isString(name)){
        injectMethod(this.super, this.prototype, definition, name);
      }else if(isLikeObject(name)){
        each(name, function(value, key){
          this.public(key, value);
        }, this, true);
      }
      return this;
    },

    overload:function(name, fn){
      overload(this.prototype, name, fn);
      return this;
    },

    unbindAll:function(){
      return unbindAll(this, slice(arguments));
    },

    bindAll:function(){
      return bindAll(this, slice(arguments));
    },

    unbind:function(fn){
      return unbind(fn);
    },

    bind:function(fn, context){
      return bind(fn, context || this);
    },

    flush:function(){
      flush(this);
    },

    toString:function(){
      return '[object '+ Proto.of(this, true) +']';
    }
  };

  // Externalize
  // -----------

  exports[name] = Proto;
  exports[name].VERSION = version;

  return Proto;
}));
<commit_msg>Update Proto.pilot.js<commit_after>//     Proto.js v1.0.3

//     (c) 2015-2016 Adrian C. Miranda
//     Proto may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://ambox.github.io
(function(global, name, version, factory){
  'use strict';

  /* globals define:false, module:false */
  if(typeof module === 'object' && typeof module.exports === 'object'){

    // Set up for Node.js or CommonJS.
    global[name] = module.exports = factory(global, exports, name, version);

  }else if(typeof define === 'function' && define.amd){

    // Next for module appropriately for the environment. Start with AMD.
    define(['exports'], function(exports){
      return factory(global, exports, name, version);
    });

  }else{

    // Finally, as a browser global.
    global[name] = factory(global, {}, name, version);

  }

}(typeof window !== 'undefined'? window : this, 'Proto', '1.0.3', function(global, exports, name, version){
  'use strict';

  // Helpers
  // -------

  function ape(fn){
    return function(){
      return Function.call.apply(fn, arguments);
    };
  }

  var slice = ape(Array.prototype.slice);

  var isArray = Array.isArray;

  var toStr = ape(Object.prototype.toString);

  var reSuper = /\bsuper\b/;

  var reFnDeclaration = /^.*function\s([^\s]*|[^\(]*)\([^\x00]+$/;

  var reObjectWrapper = /^(\[object(\s|\uFEFF|\xA0))|(\])$/g;

  var numInstances = 0;

  function isLikeObject(value){
    return value === Object(value);
  }

  function isObject(value){
    return toStr(value) === '[object Object]';
  }

  function isFunction(value){
    return typeof value === 'function';
  }

  function isString(value){
    return typeof value === 'string';
  }

  function iteraction(ctx, key, value, index, getEnum, fn){
    if(getEnum || value.hasOwnProperty(key)){
      return fn.call(ctx || value[key], value[key], key, index, value);
    }
  }

  function each(value, fn, ctx, getEnum){
    var ctr, index = 0, isFn = isFunction(value);
    for(var key in value){
      ctr = isFn? key !== 'prototype' && key !== 'length' && key !== 'name' : true;
      if(ctr && iteraction(ctx, key, value, index++, getEnum, fn) === false){
        break;
      }
    }
  }

  function copy(child){
    var Clone = function(){};
    Clone.prototype = child && child.prototype || child;
    return new Clone();
  }

  function create(child, properties){
    if(child === null){return {};}
    var Child = function(){};
    Child.prototype = child;
    child = new Child();
    each(properties, function(value, property){
      child[property] = value.value;
    });
    return child;
  }

  if(!isFunction(Object.create)){
    Object.create = create;
  }

  function merge(overwrite, target){
    var args = slice(arguments, 2);
    each(args, function(parameter){
      each(parameter, function(value, key){
        if(isObject(value) && isObject(target[key])){
          merge(overwrite, target[key], value);
        }else if(overwrite || !target[key]){
          target[key] = value;
        }
      }, null, true);
    });
    return target;
  }

  function shallowMerge(target){
    var args = slice(arguments, 1);
    each(args, function(parameter){
      each(parameter, function(value, key){
        target[key] = value;
      });
    });
    return target;
  }

  function copyShallowObjectsFrom(child){
    var copy = {};
    each(child, function(value, key){
      if(isObject(value)){
        copy[key] = value;
      }
    }, null, true);
    return copy;
  }

  function keys(object, getEnum){
    var properties = [];
    each(object, function(value, key){
      properties.push(key);
    }, null, getEnum);
    return properties;
  }

  function overload(target, name, fn){
    var cache = target[name];
    target[name] = function(){
      if(fn.length === arguments.length){
        return fn.apply(this, arguments);
      }else if(isFunction(cache)){
        return cache.apply(this, arguments);
      }
    };
  }

  function flush(object){
    for(var key in object){
      if(object.hasOwnProperty(key)){
        delete object[key];
      }
    }
  }

  function bind(fn, context){
    var args = slice(arguments, 2);
    var proxy = function(){
      return fn.apply(context, args.concat(slice(arguments)));
    };
    proxy.__bind__ = proxy.__bind__ || fn;
    return proxy;
  }

  function unbind(fn){
    var cache = fn.__bind__;
    delete fn.__bind__;
    return cache;
  }

  function mapContext(fn, context, methods){
    methods = methods.length? methods : keys(context, true);
    each(methods, function(method){
      if(isFunction(context[method])){
        context[method] = fn(context[method], context);
      }
    });
    return context;
  }

  function bindAll(context, methods){
    methods = isArray(methods)? methods : slice(arguments, 1);
    return mapContext(bind, context, methods);
  }

  function unbindAll(context, methods){
    methods = isArray(methods)? methods : slice(arguments, 1);
    return mapContext(unbind, context, methods);
  }

  function createSuperMethod(action, value){
    var pointer = isFunction(value)? value : function $super(){
      return value;
    };
    return function Class(){
      this.super = pointer;
      return action.apply(this, arguments);
    };
  }

  function hasSuperCall(fn){
    return isFunction(fn) && reSuper.test(fn.toString());
  }

  function injectMethod(parent, child, fn, key){
    if(hasSuperCall(fn) && isLikeObject(parent)){
      child[key] = createSuperMethod(fn, parent[key]);
    }else{
      child[key] = fn;
    }
  }

  function enableSuperMethods(parent, child){
    each(child, bind(injectMethod, null, parent, child));
    return child;
  }

  function inherit(Proto, parent, child){
    var caste = child;
    child = createSuperMethod(child, parent);
    shallowMerge(child, caste);
    shallowMerge(child.prototype, caste.prototype);
    flush(caste);

    shallowMerge(child, parent);

    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent instanceof Proto? null : parent.prototype;
    child.prototype = Object.create(Surrogate.prototype);
    child.super = parent.prototype;
    return child;
  }

  // Proto
  // -----

  function Proto(caste){
    Proto.size = numInstances++;
    caste = createSuperMethod(caste, null);
    caste.prototype.$protoID = Proto.size;
    caste.prototype.toString = this.toString;
    caste.prototype.toString = this.toString;
    caste.prototype.flush = this.flush;
    caste.overload = this.overload;
    caste.extends = this.extends;
    caste.public = this.public;
    return caste;
  }

  Proto.size = 0;
  Proto.create = Object.create;
  Proto.each = each;
  Proto.unbindAll = unbindAll;
  Proto.bindAll = bindAll;
  Proto.unbind = unbind;
  Proto.bind = bind;
  Proto.overload = overload;
  Proto.copyShallowObjects = copyShallowObjectsFrom;
  Proto.shallowMerge = shallowMerge;
  Proto.flush = flush;
  Proto.keys = keys;
  Proto.copy = copy;
  Proto.ape = ape;
  Proto.isArray = isArray;
  Proto.isLikeObject = isLikeObject;
  Proto.isObject = isObject;
  Proto.isFunction = isFunction;
  Proto.isString = isString;
  Proto.merge = bind(merge, null, true);

  Proto.of = function(value, qualified){
    var type = toStr(value);
    if(qualified && type === '[object Object]'){
      return value.constructor.toString().replace(reFnDeclaration, '$1') || 'Object';
    }
    return type.replace(reObjectWrapper, '');
  };

  Proto.prototype = {

    option:function(options){
      if(isString(options) && this.options){
        return this.options[options];
      }else if(isLikeObject(options)){
        this.options = merge(true, {}, this.defaults, options);
      }
      return isLikeObject(this.options)? this.options : {};
    },

    extends:function(parent){
      return inherit(Proto, parent, this);
    },

    public:function(name, definition){
      if(isString(name)){
        injectMethod(this.super, this.prototype, definition, name);
      }else if(isLikeObject(name)){
        each(name, function(value, key){
          this.public(key, value);
        }, this, true);
      }
      return this;
    },

    overload:function(name, fn){
      overload(this.prototype, name, fn);
      return this;
    },

    define:function(){
      var args = slice(arguments);
      var definitions = Object.create(null);
      if(args.length === 2 && isString(args[0])){
        definitions[args[0]] = args[1];
      }else if(args.length === 1){
        definitions = args[0];
      }
      Object.defineProperties(this.prototype, definitions);
      return this;
    },

    unbindAll:function(){
      return unbindAll(this, slice(arguments));
    },

    bindAll:function(){
      return bindAll(this, slice(arguments));
    },

    unbind:function(fn){
      return unbind(fn);
    },

    bind:function(fn, context){
      return bind(fn, context || this);
    },

    flush:function(){
      flush(this);
    },

    toString:function(){
      return '[object '+ Proto.of(this, true) +']';
    }
  };

  // Externalize
  // -----------

  exports[name] = Proto;
  exports[name].VERSION = version;

  return Proto;
}));
<|endoftext|>


<commit_before>/*!
 * Mappersmith 2.0.0-rc2
 * https://github.com/tulios/mappersmith
 */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.mappersmith=t():e.mappersmith=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var s=r[n]={i:n,l:!1,exports:{}};return e[n].call(s.exports,s,s.exports,t),s.l=!0,s.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=10)}([function(module,exports,__webpack_require__){"use strict";function toQueryString(e){return isPlainObject(e)?validKeys(e).map(function(t){return buildRecursive(t,e[t])}).join("&").replace(R20,"+"):e}function performanceNow(){return hasProcessHrtime()?(getNanoSeconds()-loadTime)/1e6:performance.now()}function parseResponseHeaders(e){var t={};if(!e)return t;for(var r=e.split("\r\n"),n=0;n<r.length;n++){var s=r[n],o=s.indexOf(": ");if(o>0){var i=s.substring(0,o).toLowerCase(),a=s.substring(o+2).trim();t[i]=a}}return t}function lowerCaseObjectKeys(e){return Object.keys(e).reduce(function(t,r){return t[r.toLowerCase()]=e[r],t},{})}function isPlainObject(e){return"[object Object]"===toString.call(e)&&Object.getPrototypeOf(e)===Object.getPrototypeOf({})}var _typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(e){return"undefined"==typeof e?"undefined":_typeof2(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":"undefined"==typeof e?"undefined":_typeof2(e)};exports.toQueryString=toQueryString,exports.performanceNow=performanceNow,exports.parseResponseHeaders=parseResponseHeaders,exports.lowerCaseObjectKeys=lowerCaseObjectKeys,exports.isPlainObject=isPlainObject,"undefined"!=typeof window&&null!==window&&(window.performance||(window.performance={}),performance.now=function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()}}());var _process=void 0,getNanoSeconds=void 0,loadTime=void 0;try{_process=eval("process")}catch(e){}var hasProcessHrtime=function(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime};hasProcessHrtime()&&(getNanoSeconds=function(){var e=_process.hrtime();return 1e9*e[0]+e[1]},loadTime=getNanoSeconds());var R20=/%20/g,validKeys=function(e){return Object.keys(e).filter(function(t){return void 0!==e[t]&&null!==e[t]})},buildRecursive=function e(t,r,n){n=n||"";var s=Array.isArray(r),o="object"===("undefined"==typeof r?"undefined":_typeof(r));return s||o?s?r.map(function(r){return e(t,r,n+"[]")}).join("&"):validKeys(r).map(function(s){return e(t,r[s],n+"["+s+"]")}).join("&"):encodeURIComponent(t+n)+"="+encodeURIComponent(r)},hasOwnProperty=Object.prototype.hasOwnProperty,assign=exports.assign=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},toString=Object.prototype.toString},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){return new i.default(e,a.gateway).build()}Object.defineProperty(t,"__esModule",{value:!0}),t.configs=void 0,t.default=s;var o=r(6),i=n(o),a=t.configs={Promise:"function"==typeof Promise?Promise:null,gateway:null,gatewayConfigs:{emulateHTTP:!1,XHR:{withCredentials:!1,configure:null}}}},function(e,t,r){"use strict";function n(e){this.host=e.host,this.path=e.path,this.method=e.method||"get",this.headers=e.headers,this.params=e.params,this.bodyAttr=e.bodyAttr||"body",this.headersAttr=e.headersAttr||"headers"}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,r){"use strict";function n(e,t,r,n){this.originalRequest=e,this.responseStatus=t,this.responseData=r,this.responseHeaders=n||{},this.timeElapsed=null}Object.defineProperty(t,"__esModule",{value:!0});var s=r(0);n.prototype={request:function(){return this.originalRequest},status:function(){return 1223===this.responseStatus?204:this.responseStatus},success:function(){var e=this.status();return e>=200&&e<400},headers:function(){return(0,s.lowerCaseObjectKeys)(this.responseHeaders)},rawData:function(){return this.responseData},data:function e(){var e=this.responseData;if(this.isContentTypeJSON())try{e=JSON.parse(this.responseData)}catch(e){}return e},isContentTypeJSON:function(){return/application\/json/.test(this.headers()["content-type"])},enhance:function(e){return new n(this.request(),e.status||this.status(),e.rawData||this.rawData(),(0,s.assign)({},this.headers(),e.headers))}},t.default=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){i.default.apply(this,arguments)}Object.defineProperty(t,"__esModule",{value:!0});var o=r(7),i=n(o),a=r(3),u=n(a),c=r(0);s.prototype=i.default.extends({get:function(){var e=new XMLHttpRequest;this.configureCallbacks(e),e.open("get",this.request.url(),!0),this.setHeaders(e,{}),e.send()},post:function(){this.performRequest("post")},put:function(){this.performRequest("put")},patch:function(){this.performRequest("patch")},delete:function(){this.performRequest("delete")},configureCallbacks:function(e){var t=this;e.addEventListener("load",function(){t.dispatchResponse(t.createResponse(e))}),e.addEventListener("error",function(){t.dispatchClientError("Network error")});var r=this.options().XHR;r.withCredentials&&(e.withCredentials=!0),r.configure&&r.configure(e)},performRequest:function(e){var t=this.shouldEmulateHTTP()?"post":e,r=new XMLHttpRequest;this.configureCallbacks(r),r.open(t,this.request.url(),!0);var n={},s=this.prepareBody(e,n);this.setHeaders(r,n);var o=[];s&&o.push(s),r.send.apply(r,o)},createResponse:function(e){var t=e.status,r=e.responseText,n=(0,c.parseResponseHeaders)(e.getAllResponseHeaders());return new u.default(this.request,t,r,n)},setHeaders:function(e,t){var r=(0,c.assign)(t,this.request.headers());Object.keys(r).forEach(function(t){e.setRequestHeader(t,r[t])})}}),t.default=s},function(e,t){},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){if(!e)throw new Error("[Mappersmith] invalid manifest ("+e+")");if(!t)throw new Error("[Mappersmith] gateway class not configured (configs.gateway)");this.manifest=new a.default(e),this.GatewayClass=t}Object.defineProperty(t,"__esModule",{value:!0});var i=r(8),a=n(i),u=r(2),c=(n(u),r(9)),f=n(c),p=r(0);o.prototype={build:function(){var e=this,t={_manifest:this.manifest};return this.manifest.eachResource(function(r,n){t[r]=e.buildResource(n)}),t},buildResource:function(e){var t=this;return e.reduce(function(e,r){return(0,p.assign)(e,s({},r.name,function(e){var n=new f.default(r.descriptor,e);return t.invokeMiddlewares(n)}))},{})},invokeMiddlewares:function(e){var t=this,r=this.manifest.createMiddlewares(),n=r.reduce(function(e,t){return t.request(e)},e),s=function(){return new t.GatewayClass(n).call()},o=r.reduce(function(e,t){return function(){return t.response(e)}},s);return o()}},t.default=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){this.request=e,this.successCallback=function(){},this.failCallback=function(){}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(0),i=r(1),a=r(3),u=n(a);s.extends=function(e){return(0,o.assign)({},s.prototype,e)},s.prototype={options:function(){return i.configs.gatewayConfigs},shouldEmulateHTTP:function(){return this.options().emulateHTTP&&/^(delete|put|patch)/i.test(this.request.method())},call:function(){var e=this,t=arguments,r=(0,o.performanceNow)();return new i.configs.Promise(function(n,s){e.successCallback=function(e){e.timeElapsed=(0,o.performanceNow)()-r,n(e)},e.failCallback=function(e){e.timeElapsed=(0,o.performanceNow)()-r,s(e)};try{e[e.request.method()].apply(e,t)}catch(t){e.dispatchClientError(t.message)}})},dispatchResponse:function(e){e.success()?this.successCallback(e):this.failCallback(e)},dispatchClientError:function(e){this.failCallback(new u.default(this.request,400,e))},prepareBody:function(e,t){var r=this.request.body();this.shouldEmulateHTTP()&&(r=r||{},(0,o.isPlainObject)(r)&&(r._method=e),t["x-http-method-override"]=e);var n=(0,o.toQueryString)(r);return n&&(0,o.isPlainObject)(r)&&(t["content-type"]="application/x-www-form-urlencoded;charset=utf-8"),n}},t.default=s},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){this.host=e.host,this.resources=e.resources||{},this.middlewares=e.middlewares||[]}Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),i=n(o),a=r(0);s.prototype={eachResource:function(e){var t=this;Object.keys(this.resources).forEach(function(r){var n=t.eachMethod(r,function(e){return{name:e,descriptor:t.createMethodDescriptor(r,e)}});e(r,n)})},eachMethod:function(e,t){return Object.keys(this.resources[e]).map(function(e){return t(e)})},createMethodDescriptor:function(e,t){var r=this.resources[e][t];if(!r||!r.path)throw new Error('[Mappersmith] path is undefined for resource "'+e+'" method "'+t+'"');return new i.default((0,a.assign)({host:this.host},r))},createMiddlewares:function(){var e=function(e){return(0,a.assign)({request:function(e){return e},response:function(e){return e()}},e())};return this.middlewares.map(function(t){return e(t)})}},t.default=s},function(e,t,r){"use strict";function n(e,t){this.methodDescriptor=e,this.requestParams=t||{}}Object.defineProperty(t,"__esModule",{value:!0});var s=r(0),o=new RegExp("{([^}]+)}");n.prototype={params:function e(){var t=this,e=(0,s.assign)({},this.methodDescriptor.params,this.requestParams),r=function(e){return e!==t.methodDescriptor.headersAttr&&e!==t.methodDescriptor.bodyAttr};return Object.keys(e).reduce(function(t,n){return r(n)&&(t[n]=e[n]),t},{})},method:function(){return this.methodDescriptor.method.toLowerCase()},host:function(){return(this.methodDescriptor.host||"").replace(/\/$/,"")},path:function e(){var e=this.methodDescriptor.path,t=this.methodDescriptor;t.headersAttr,t.bodyAttr;"/"!==this.methodDescriptor.path[0]&&(e="/"+this.methodDescriptor.path);var r=this.params();Object.keys(r).forEach(function(t){var n=r[t],s="{"+t+"}";new RegExp(s).test(e)&&(e=e.replace("{"+t+"}",n),delete r[t])});var n=e.match(o);if(n)throw new Error("[Mappersmith] required parameter missing ("+n[1]+'), "'+e+'" cannot be resolved');var i=(0,s.toQueryString)(r);return 0!==i.length&&(e+="?"+i),e},url:function(){return""+this.host()+this.path()},headers:function(){return(0,s.lowerCaseObjectKeys)((0,s.assign)({},this.methodDescriptor.headers,this.requestParams[this.methodDescriptor.headersAttr]))},body:function(){return this.requestParams[this.methodDescriptor.bodyAttr]},enhance:function(e){var t=this.methodDescriptor.headersAttr,r=this.methodDescriptor.bodyAttr,o=(0,s.assign)({},this.requestParams,e.params);return o[t]=(0,s.assign)({},this.requestParams[t],e.headers),o[r]=e.body,new n(this.methodDescriptor,o)}},t.default=n},function(module,exports,__webpack_require__){"use strict";var lib=__webpack_require__(1),_process,defaultGateway;try{_process=eval("process")}catch(e){}"undefined"!=typeof XMLHttpRequest?defaultGateway=__webpack_require__(4).default:"undefined"!=typeof _process&&(defaultGateway=__webpack_require__(5).default),lib.configs.gateway=defaultGateway,module.exports=lib}])});
//# sourceMappingURL=mappersmith.map<commit_msg>update precompiled version<commit_after>/*!
 * Mappersmith 2.0.0-rc3
 * https://github.com/tulios/mappersmith
 */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.mappersmith=t():e.mappersmith=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var s=r[n]={i:n,l:!1,exports:{}};return e[n].call(s.exports,s,s.exports,t),s.l=!0,s.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=10)}([function(module,exports,__webpack_require__){"use strict";function toQueryString(e){return isPlainObject(e)?validKeys(e).map(function(t){return buildRecursive(t,e[t])}).join("&").replace(R20,"+"):e}function performanceNow(){return hasProcessHrtime()?(getNanoSeconds()-loadTime)/1e6:performance.now()}function parseResponseHeaders(e){var t={};if(!e)return t;for(var r=e.split("\r\n"),n=0;n<r.length;n++){var s=r[n],o=s.indexOf(": ");if(o>0){var i=s.substring(0,o).toLowerCase(),a=s.substring(o+2).trim();t[i]=a}}return t}function lowerCaseObjectKeys(e){return Object.keys(e).reduce(function(t,r){return t[r.toLowerCase()]=e[r],t},{})}function isPlainObject(e){return"[object Object]"===toString.call(e)&&Object.getPrototypeOf(e)===Object.getPrototypeOf({})}var _typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(e){return"undefined"==typeof e?"undefined":_typeof2(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":"undefined"==typeof e?"undefined":_typeof2(e)};exports.toQueryString=toQueryString,exports.performanceNow=performanceNow,exports.parseResponseHeaders=parseResponseHeaders,exports.lowerCaseObjectKeys=lowerCaseObjectKeys,exports.isPlainObject=isPlainObject,"undefined"!=typeof window&&null!==window&&(window.performance||(window.performance={}),performance.now=function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()}}());var _process=void 0,getNanoSeconds=void 0,loadTime=void 0;try{_process=eval("process")}catch(e){}var hasProcessHrtime=function(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime};hasProcessHrtime()&&(getNanoSeconds=function(){var e=_process.hrtime();return 1e9*e[0]+e[1]},loadTime=getNanoSeconds());var R20=/%20/g,validKeys=function(e){return Object.keys(e).filter(function(t){return void 0!==e[t]&&null!==e[t]})},buildRecursive=function e(t,r,n){n=n||"";var s=Array.isArray(r),o="object"===("undefined"==typeof r?"undefined":_typeof(r));return s||o?s?r.map(function(r){return e(t,r,n+"[]")}).join("&"):validKeys(r).map(function(s){return e(t,r[s],n+"["+s+"]")}).join("&"):encodeURIComponent(t+n)+"="+encodeURIComponent(r)},hasOwnProperty=Object.prototype.hasOwnProperty,assign=exports.assign=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},toString=Object.prototype.toString},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){return new i.default(e,a.gateway).build()}Object.defineProperty(t,"__esModule",{value:!0}),t.configs=void 0,t.default=s;var o=r(6),i=n(o),a=t.configs={Promise:"function"==typeof Promise?Promise:null,gateway:null,gatewayConfigs:{emulateHTTP:!1,XHR:{withCredentials:!1,configure:null}}}},function(e,t,r){"use strict";function n(e){this.host=e.host,this.path=e.path,this.method=e.method||"get",this.headers=e.headers,this.params=e.params,this.bodyAttr=e.bodyAttr||"body",this.headersAttr=e.headersAttr||"headers"}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,r){"use strict";function n(e,t,r,n){this.originalRequest=e,this.responseStatus=t,this.responseData=r,this.responseHeaders=n||{},this.timeElapsed=null}Object.defineProperty(t,"__esModule",{value:!0});var s=r(0);n.prototype={request:function(){return this.originalRequest},status:function(){return 1223===this.responseStatus?204:this.responseStatus},success:function(){var e=this.status();return e>=200&&e<400},headers:function(){return(0,s.lowerCaseObjectKeys)(this.responseHeaders)},rawData:function(){return this.responseData},data:function e(){var e=this.responseData;if(this.isContentTypeJSON())try{e=JSON.parse(this.responseData)}catch(e){}return e},isContentTypeJSON:function(){return/application\/json/.test(this.headers()["content-type"])},enhance:function(e){return new n(this.request(),e.status||this.status(),e.rawData||this.rawData(),(0,s.assign)({},this.headers(),e.headers))}},t.default=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){i.default.apply(this,arguments)}Object.defineProperty(t,"__esModule",{value:!0});var o=r(7),i=n(o),a=r(3),u=n(a),c=r(0);s.prototype=i.default.extends({get:function(){var e=new XMLHttpRequest;this.configureCallbacks(e),e.open("get",this.request.url(),!0),this.setHeaders(e,{}),e.send()},post:function(){this.performRequest("post")},put:function(){this.performRequest("put")},patch:function(){this.performRequest("patch")},delete:function(){this.performRequest("delete")},configureCallbacks:function(e){var t=this;e.addEventListener("load",function(){t.dispatchResponse(t.createResponse(e))}),e.addEventListener("error",function(){t.dispatchClientError("Network error")});var r=this.options().XHR;r.withCredentials&&(e.withCredentials=!0),r.configure&&r.configure(e)},performRequest:function(e){var t=this.shouldEmulateHTTP()?"post":e,r=new XMLHttpRequest;this.configureCallbacks(r),r.open(t,this.request.url(),!0);var n={},s=this.prepareBody(e,n);this.setHeaders(r,n);var o=[];s&&o.push(s),r.send.apply(r,o)},createResponse:function(e){var t=e.status,r=e.responseText,n=(0,c.parseResponseHeaders)(e.getAllResponseHeaders());return new u.default(this.request,t,r,n)},setHeaders:function(e,t){var r=(0,c.assign)(t,this.request.headers());Object.keys(r).forEach(function(t){e.setRequestHeader(t,r[t])})}}),t.default=s},function(e,t){},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){if(!e)throw new Error("[Mappersmith] invalid manifest ("+e+")");if(!t)throw new Error("[Mappersmith] gateway class not configured (configs.gateway)");this.manifest=new a.default(e),this.GatewayClass=t}Object.defineProperty(t,"__esModule",{value:!0});var i=r(8),a=n(i),u=r(2),c=(n(u),r(9)),f=n(c),p=r(0);o.prototype={build:function(){var e=this,t={_manifest:this.manifest};return this.manifest.eachResource(function(r,n){t[r]=e.buildResource(n)}),t},buildResource:function(e){var t=this;return e.reduce(function(e,r){return(0,p.assign)(e,s({},r.name,function(e){var n=new f.default(r.descriptor,e);return t.invokeMiddlewares(n)}))},{})},invokeMiddlewares:function(e){var t=this,r=this.manifest.createMiddlewares(),n=r.reduce(function(e,t){return t.request(e)},e),s=function(){return new t.GatewayClass(n).call()},o=r.reduce(function(e,t){return function(){return t.response(e)}},s);return o()}},t.default=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){this.request=e,this.successCallback=function(){},this.failCallback=function(){}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(0),i=r(1),a=r(3),u=n(a);s.extends=function(e){return(0,o.assign)({},s.prototype,e)},s.prototype={options:function(){return i.configs.gatewayConfigs},shouldEmulateHTTP:function(){return this.options().emulateHTTP&&/^(delete|put|patch)/i.test(this.request.method())},call:function(){var e=this,t=arguments,r=(0,o.performanceNow)();return new i.configs.Promise(function(n,s){e.successCallback=function(e){e.timeElapsed=(0,o.performanceNow)()-r,n(e)},e.failCallback=function(e){e.timeElapsed=(0,o.performanceNow)()-r,s(e)};try{e[e.request.method()].apply(e,t)}catch(t){e.dispatchClientError(t.message)}})},dispatchResponse:function(e){e.success()?this.successCallback(e):this.failCallback(e)},dispatchClientError:function(e){this.failCallback(new u.default(this.request,400,e))},prepareBody:function(e,t){var r=this.request.body();this.shouldEmulateHTTP()&&(r=r||{},(0,o.isPlainObject)(r)&&(r._method=e),t["x-http-method-override"]=e);var n=(0,o.toQueryString)(r);return n&&(0,o.isPlainObject)(r)&&(t["content-type"]="application/x-www-form-urlencoded;charset=utf-8"),n}},t.default=s},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function s(e){this.host=e.host,this.resources=e.resources||{},this.middlewares=e.middlewares||[]}Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),i=n(o),a=r(0);s.prototype={eachResource:function(e){var t=this;Object.keys(this.resources).forEach(function(r){var n=t.eachMethod(r,function(e){return{name:e,descriptor:t.createMethodDescriptor(r,e)}});e(r,n)})},eachMethod:function(e,t){return Object.keys(this.resources[e]).map(function(e){return t(e)})},createMethodDescriptor:function(e,t){var r=this.resources[e][t];if(!r||!r.path)throw new Error('[Mappersmith] path is undefined for resource "'+e+'" method "'+t+'"');return new i.default((0,a.assign)({host:this.host},r))},createMiddlewares:function(){var e=function(e){return(0,a.assign)({request:function(e){return e},response:function(e){return e()}},e())};return this.middlewares.map(function(t){return e(t)})}},t.default=s},function(e,t,r){"use strict";function n(e,t){this.methodDescriptor=e,this.requestParams=t||{}}Object.defineProperty(t,"__esModule",{value:!0});var s=r(0),o=new RegExp("{([^}]+)}");n.prototype={params:function e(){var t=this,e=(0,s.assign)({},this.methodDescriptor.params,this.requestParams),r=function(e){return e!==t.methodDescriptor.headersAttr&&e!==t.methodDescriptor.bodyAttr};return Object.keys(e).reduce(function(t,n){return r(n)&&(t[n]=e[n]),t},{})},method:function(){return this.methodDescriptor.method.toLowerCase()},host:function(){return(this.methodDescriptor.host||"").replace(/\/$/,"")},path:function e(){var e=this.methodDescriptor.path,t=this.methodDescriptor;t.headersAttr,t.bodyAttr;"/"!==this.methodDescriptor.path[0]&&(e="/"+this.methodDescriptor.path);var r=this.params();Object.keys(r).forEach(function(t){var n=r[t],s="{"+t+"}";new RegExp(s).test(e)&&(e=e.replace("{"+t+"}",n),delete r[t])});var n=e.match(o);if(n)throw new Error("[Mappersmith] required parameter missing ("+n[1]+'), "'+e+'" cannot be resolved');var i=(0,s.toQueryString)(r);return 0!==i.length&&(e+="?"+i),e},url:function(){return""+this.host()+this.path()},headers:function(){return(0,s.lowerCaseObjectKeys)((0,s.assign)({},this.methodDescriptor.headers,this.requestParams[this.methodDescriptor.headersAttr]))},body:function(){return this.requestParams[this.methodDescriptor.bodyAttr]},enhance:function(e){var t=this.methodDescriptor.headersAttr,r=this.methodDescriptor.bodyAttr,o=(0,s.assign)({},this.requestParams,e.params);return o[t]=(0,s.assign)({},this.requestParams[t],e.headers),o[r]=e.body,new n(this.methodDescriptor,o)}},t.default=n},function(module,exports,__webpack_require__){"use strict";var lib=__webpack_require__(1),_process,defaultGateway;try{_process=eval("process")}catch(e){}"undefined"!=typeof XMLHttpRequest?defaultGateway=__webpack_require__(4).default:"undefined"!=typeof _process&&(defaultGateway=__webpack_require__(5).default),lib.configs.gateway=defaultGateway,module.exports=lib}])});
//# sourceMappingURL=mappersmith.map<|endoftext|>


<commit_before>(function(global) {

  if (typeof global.CustomEvent === 'function') return

  function CustomEvent(event, params) {
    params = params || {
        bubbles: false,
        cancelable: false,
        detail: undefined
    }
    var evt = document.createEvent('CustomEvent')
    evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
    return evt
  }

  CustomEvent.prototype = global.Event.prototype

  global.CustomEvent = CustomEvent
})(this)<commit_msg>Stub out a fake CustomEvent when in a web worker<commit_after>(function(global) {

  if (typeof global.CustomEvent === 'function') return

  function CustomEvent(event, params) {
    params = params || {
        bubbles: false,
        cancelable: false,
        detail: undefined
    }

    var evt
    if (typeof document !== 'undefined') {
      evt = document.createEvent('CustomEvent')
      evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
    } else {
      // This is not a proper polyfill at all. If you need a CustomEvent in a WebWorker,
      // please benefit the rest of the world and submit a pull request to your favorite
      // CustomEvent polyfil like https://github.com/kaesetoast/customevent-polyfill/issues/1
      evt = {
        type: event,
        detail: params.detail,
        bubbles: false,
        cancelable: false,
        preventDefault: function() {},
        stopPropagation: function() {}
      }
    }

    return evt
  }

  if (global.Event) {
    CustomEvent.prototype = global.Event.prototype
  }

  global.CustomEvent = CustomEvent
})(this)<|endoftext|>


<commit_before>'use strict';

import chai, { assert, expect } from 'chai';
import spies from 'chai-spies';
import Kohonen from '../src/Kohonen';
import { generateGrid } from '../src/hexagon';
import { random } from '../src/vector';

chai.use(spies);

describe('Kohonen', ()=> {

    const data = [
        [10, 20, 30],
        [-10, 17, 21],
        [7, -50, 35]
    ];

    describe('constructor', () => {

        it('should not throw an error when called properly', () => {
            assert.doesNotThrow(()=> {
                new Kohonen({data, neurons: generateGrid(10, 10)});
            }, Error);
        });

        it('should return an instance of Kohonen', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            assert.instanceOf(k, Kohonen);
        });

        it('should return an instance of Kohonen with a neurons attribute as an array', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            assert.property(k, 'neurons');
            assert.isArray(k.neurons);
        });

        it('should return an instance of Kohonen with a data attribute as an array', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            assert.property(k, 'data');
            assert.isArray(k.data);
        });

        it('should return an instance of Kohonen with properly defined neurons attributes', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            k.neurons.forEach(n => {
                assert.property(n, 'v');
                assert.isArray(n.v);
                assert.lengthOf(n.v, 3);
                assert.property(n, 'pos');
                assert.isArray(n.pos);
                assert.lengthOf(n.pos, 2);
            });
        });

        it('should return an instance of Kohonen with a step attribute as an int', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            assert.property(k, 'step');
            assert.isNumber(k.step);
        });

        it('should return an instance of Kohonen with a scaleStepLearningCoef attribute as a function', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            assert.property(k, 'scaleStepLearningCoef');
            assert.isFunction(k.scaleStepLearningCoef);
        });

        it('should return an instance of Kohonen with a scaleStepNeighborhood attribute as a function', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            assert.property(k, 'scaleStepNeighborhood');
            assert.isFunction(k.scaleStepNeighborhood);
        });

    });

    describe('findBestMatchingUnit', ()=> {

        it('should return a neuron', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            const bmu = k.findBestMatchingUnit([0, 0, 0]);
            assert.isObject(bmu);
            assert.property(bmu, 'v');
            assert.property(bmu, 'pos');
        });

    });

    describe('neighborhood', ()=> {

        it('should return a number', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            const v = [0, 0, 0];
            const bmu = k.findBestMatchingUnit(v);
            assert.isNumber(k.neighborhood({bmu, n: k.neurons[0]}));
        });

        it('should return decreasing value with time', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            const v = [0, 0, 0];
            const bmu = k.findBestMatchingUnit(v);
            let currentNeighborhood = 1;
            for (let i = 0; i < 10; i++) {
                const tempNeighborhood = k.neighborhood({bmu, n: k.neurons[0]});
                k.step += 1;
                assert.isBelow(tempNeighborhood, currentNeighborhood);
                currentNeighborhood = tempNeighborhood;
            }
        });

    });

    describe('learn', ()=> {

        it('should increase step', () => {
            const k = new Kohonen({data, neurons: generateGrid(10, 10)});
            k.learn(random(3));
            assert.equal(k.step, 1);
            k.learn(random(3));
            assert.equal(k.step, 2);
        });

        it('should update the bmu and its neighbors', () => {

        });

    });

});
<commit_msg>issue #3<commit_after><|endoftext|>


<commit_before>var InfluxNodeClient = require('./influx_node_client');
var InfluxBasicClient = require('./influx_basic_client');
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var InfluxQueryClient = module.exports = function() {
  EventEmitter.call(this);
  var self = this;
  var connected = false;
  var opts = {
    host: process.env.COREOS_PRIVATE_IPV4
  };

  if(process.env.ETCD_PEER_HOSTS) {
    opts.host = process.env.ETCD_PEER_HOSTS.split(',');
  }

  this._nodeClient = new InfluxNodeClient(opts);
  self._nodeClient.findAll(function(err, results) {
    console.log(arguments);
    if(err) {
      return console.error(err);
    }

    if(results.length) {
      var endpoint = results[0].url;
      console.log('Connecting to influx endpoint: ', endpoint);
      var endpointUrl = url.parse(endpoint);
      self._clientCredentials = {
        hostname:endpointUrl.hostname,
        port:endpointUrl.port,
        database:'deviceData'
      };
      self._createSubscription();
      self.emit('ready');
    }

    self._nodeClient.on('change', function(results) {
      if(results.length) {
        var endpoint = results[0].url;
        console.log('Connecting to influx endpoint: ', endpoint);
        var endpointUrl = url.parse(endpoint);
        if(!self._clientCredentials || (endpointUrl.hostname != self._clientCredentials.hostname)) {
          self._createSubscription();
        }
        self._clientCredentials = {
          hostname:endpointUrl.hostname,
          port:endpointUrl.port,
          database:'deviceData'
        };

      }
    });
  });
}
util.inherits(InfluxQueryClient, EventEmitter);

InfluxQueryClient.prototype.getFiveLatestEvents = function(aggregate, topic, cb) {
  var current = new Date();
  var timestamp = new Date(current.setSeconds(0));
  var topicComponents = topic.split('/');
  var type = topicComponents[0];
  var id = topicComponents[1];
  var stream = topicComponents[2];
  var series = 'devicedata.'+type+'.'+stream;

  if(aggregate == 'average') {
    series = 'aggregatedata.average';
  }
  series = '"' + series + '"';
  var creds = this._clientCredentials;
  var query = "SELECT mean as value, * FROM "+ series +" WHERE time < '" + timestamp.toISOString() + "' AND device = '" + id + "' ORDER BY time DESC LIMIT 5";
  console.log(query);
  if(aggregate == 'raw') {
    query = "SELECT * FROM "+ series +" WHERE device = '" + id + "' ORDER BY time DESC LIMIT 5";
  }
  InfluxBasicClient.query(creds.hostname, creds.port, creds.database, query, function(err, results) {
    if(err) {
      return cb(err);
    }

    return cb(null, results);
  });
};

InfluxQueryClient.prototype._createSubscription = function() {
  var query = "CREATE SUBSCRIPTION sub0 ON \"deviceData\".\"deviceDataRetention\" DESTINATIONS ALL 'udp://"+process.env.COREOS_PRIVATE_IPV4+":1337';";
  var creds = this._clientCredentials;
  InfluxBasicClient.postQuery(creds.hostname, creds.port, creds.database, query, function(err, results) {
    if(err) {
      return console.error(err);
    }
    console.log('Created UDP subscription for query stats.');
  });
}
<commit_msg>Updating port required for subscription.<commit_after>var InfluxNodeClient = require('./influx_node_client');
var InfluxBasicClient = require('./influx_basic_client');
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var InfluxQueryClient = module.exports = function() {
  EventEmitter.call(this);
  var self = this;
  var connected = false;
  var opts = {
    host: process.env.COREOS_PRIVATE_IPV4
  };

  if(process.env.ETCD_PEER_HOSTS) {
    opts.host = process.env.ETCD_PEER_HOSTS.split(',');
  }

  this._nodeClient = new InfluxNodeClient(opts);
  self._nodeClient.findAll(function(err, results) {
    console.log(arguments);
    if(err) {
      return console.error(err);
    }

    if(results.length) {
      var endpoint = results[0].url;
      console.log('Connecting to influx endpoint: ', endpoint);
      var endpointUrl = url.parse(endpoint);
      self._clientCredentials = {
        hostname:endpointUrl.hostname,
        port:endpointUrl.port,
        database:'deviceData'
      };
      self._createSubscription();
      self.emit('ready');
    }

    self._nodeClient.on('change', function(results) {
      if(results.length) {
        var endpoint = results[0].url;
        console.log('Connecting to influx endpoint: ', endpoint);
        var endpointUrl = url.parse(endpoint);
        if(!self._clientCredentials || (endpointUrl.hostname != self._clientCredentials.hostname)) {
          self._createSubscription();
        }
        self._clientCredentials = {
          hostname:endpointUrl.hostname,
          port:endpointUrl.port,
          database:'deviceData'
        };

      }
    });
  });
}
util.inherits(InfluxQueryClient, EventEmitter);

InfluxQueryClient.prototype.getFiveLatestEvents = function(aggregate, topic, cb) {
  var current = new Date();
  var timestamp = new Date(current.setSeconds(0));
  var topicComponents = topic.split('/');
  var type = topicComponents[0];
  var id = topicComponents[1];
  var stream = topicComponents[2];
  var series = 'devicedata.'+type+'.'+stream;

  if(aggregate == 'average') {
    series = 'aggregatedata.average';
  }
  series = '"' + series + '"';
  var creds = this._clientCredentials;
  var query = "SELECT mean as value, * FROM "+ series +" WHERE time < '" + timestamp.toISOString() + "' AND device = '" + id + "' ORDER BY time DESC LIMIT 5";
  console.log(query);
  if(aggregate == 'raw') {
    query = "SELECT * FROM "+ series +" WHERE device = '" + id + "' ORDER BY time DESC LIMIT 5";
  }
  InfluxBasicClient.query(creds.hostname, creds.port, creds.database, query, function(err, results) {
    if(err) {
      return cb(err);
    }

    return cb(null, results);
  });
};

InfluxQueryClient.prototype._createSubscription = function() {
  var query = "CREATE SUBSCRIPTION sub0 ON \"deviceData\".\"deviceDataRetention\" DESTINATIONS ALL 'udp://"+process.env.COREOS_PRIVATE_IPV4+":3007';";
  var creds = this._clientCredentials;
  InfluxBasicClient.postQuery(creds.hostname, creds.port, creds.database, query, function(err, results) {
    if(err) {
      return console.error(err);
    }
    console.log('Created UDP subscription for query stats.');
  });
}
<|endoftext|>


<commit_before>(function() {
  /*
     ======== A Handy Little QUnit Reference ========
http://api.qunitjs.com/

Test methods:
module(name, {[setup][ ,teardown]})
test(name, callback)
expect(numberOfAssertions)
stop(increment)
start(decrement)
Test assertions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
throws(block, [expected], [message])
*/

  test("Check Ace namespace", function() {
    ok(typeof ace !== "undefined" && ace !== null, "Ace namespace defined");
  });

  test("Check Underscore namespace", function() {
    ok(typeof _ !== "undefined" && _ !== null, "Underscore namespace defined");
  });

  test("Check Backbone namespace", function() {
    ok(typeof Backbone !== "undefined" && Backbone !== null, "Backbone namepsace defined");
  });

  test("Check Angles Namespace", function() {
    expect(1);
    ok(typeof Angles !== "undefined" && Angles !== null, "Angles namespace defined");
  });

})();
<commit_msg>remove unneeded test expectation<commit_after>(function() {
  /*
     ======== A Handy Little QUnit Reference ========
http://api.qunitjs.com/

Test methods:
module(name, {[setup][ ,teardown]})
test(name, callback)
expect(numberOfAssertions)
stop(increment)
start(decrement)
Test assertions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
throws(block, [expected], [message])
*/

  test("Check Ace namespace", function() {
    ok(typeof ace !== "undefined" && ace !== null, "Ace namespace defined");
  });

  test("Check Underscore namespace", function() {
    ok(typeof _ !== "undefined" && _ !== null, "Underscore namespace defined");
  });

  test("Check Backbone namespace", function() {
    ok(typeof Backbone !== "undefined" && Backbone !== null, "Backbone namepsace defined");
  });

  test("Check Angles Namespace", function() {
    ok(typeof Angles !== "undefined" && Angles !== null, "Angles namespace defined");
  });

})();
<|endoftext|>


<commit_before>const expect = require('chai').expect;
const mongoose = require('mongoose');
import fetch from 'node-fetch';
const request = require('superagent');
const dataMakers = require('../helpers/data');
const Game = require('../../app/models/game');

describe('api/release', () => {
  describe('GET', () => {
    it('should return the latest prod release for a game if no token is provided.', async function() {
      await dataMakers.makeGame('prod');
      let gameResponse = await request.get('http://localhost:3000/api/games');
      let gameSlug = gameResponse.body.data[0].slug;
      let releaseResponse = await request.get(
        `http://localhost:3000/api/release/${gameSlug}`
      );
      expect(releaseResponse.body.success).to.equal(true);
      expect(releaseResponse.body.data.game.slug).to.equal(gameSlug);
    });

    it('should return the dev releases for a game if a valid token is provided.', async function() {
      // make a write level access token
      let editor = await dataMakers.makeUser(2);
      let token = await dataMakers.getUserToken(editor);

      await dataMakers.makeGame('dev');
      let gameResponse = await request.get('http://localhost:3000/api/games');
      // get the game slug from the api response
      let gameSlug = gameResponse.body.data[0].slug;

      // add the editor token's group to the game's definition
      let gameObject = await Game.getBySlug(gameSlug);
      gameObject.groups.push({
        group: editor.groups[0],
        permission: 2
      });
      await gameObject.save();

      // send the request
      let releaseParams = {
        token: token,
        status: 'dev'
      };

      let releaseResponse = await request
        .get(`http://localhost:3000/api/release/${gameSlug}`)
        .query(`token=${token}`)
        .query('status=dev');

      expect(releaseResponse.body.success).to.equal(true);
      expect(releaseResponse.body.data.game.slug).to.equal(gameSlug);
    });

    it('should provide caching headers for non dev games', async function() {
      const game = await dataMakers.makeGame('prod');
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}`);
      expect(response.headers.get('Cache-Control')).to.not.equal(null);
    });

    it('should not provide caching headers for dev games', async function() {
      const game = await dataMakers.makeGame('dev');
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}?status=dev`);
      expect(response.headers.get('Cache-Control')).to.equal(null);
    });

    it('should respond with a 404 if a request is made for a slug that does not exist', async function() {
      const response = await fetch(`http://localhost:3000/api/release/dont-exists`);
      expect(response.status).to.equal(404);
    });

    it('should respond with a 404 if a request is made for a game that does not have a prod release', async function() {
      const game = await dataMakers.makeGame('dev');
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}`);
      expect(response.status).to.equal(404);
    });

    it('should respond with a 403 if a request is made for a dev release without a token', async function() {
      const game = await dataMakers.makeGame('dev');
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}?status=dev`);
      const json = await response.json();

      expect(response.status).to.equal(403);
    });

    it('should respond with a 422 if the request had invalid fields', async function() {
      const response = await fetch('http://localhost:3000/api/release/doesntmatter?status=NOPE&token=tooshort');
      expect(response.status).to.equal(422);
    });

    const getMethods = (obj) => {
      let properties = new Set()
      let currentObj = obj
      do {
        Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
      } while ((currentObj = Object.getPrototypeOf(currentObj)))
      return [...properties.keys()].filter(item => typeof obj[item] === 'function')
    }

    it('should respond with a 403 when user does not have permissions to view game', async function() {
      // create test objects
      const game = await dataMakers.makeGame('dev');
      const release = await dataMakers.makeRelease(game._id, 'dev');
      const user = await dataMakers.makeUser(0);
      const token = await dataMakers.getUserToken(user);
      // query api
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}?commitId=${release.commitId}&token=${token}&debug=true`);
      const body = JSON.parse(await response.text());

      // test status
      expect(response.status).to.equal(403);
      // test error message
      expect(body.error.toLowerCase()).to.equal('unauthorized token');
    });
  });

  describe('POST', () => {
    it('should be able to make a new release on POST if has editor+ credentials for the game in question', async function() {
      await dataMakers.makeGame('prod');
      let gameResponse = await request.get('http://localhost:3000/api/games');

      // make a write level access token
      let editor = await dataMakers.makeUser(2);
      let token = await dataMakers.getUserToken(editor);
      // get the game slug from the api response
      let gameSlug = gameResponse.body.data[0].slug;

      // add the editor token's group to the game's definition
      let gameObject = await Game.getBySlug(gameSlug);
      gameObject.groups.push({
        group: editor.groups[0],
        permission: 2
      });
      await gameObject.save();

      // make a new commit id for the new release
      let commitId = dataMakers.makeRandomString(40);
      // send the request
      let releaseParams = {
        status: 'dev',
        commitId: commitId,
        version: '1.0.0',
        token: token
      };

      let postResponse = await request
        .post(`http://localhost:3000/api/release/${gameSlug}`)
        .send(releaseParams);
      expect(postResponse.body.success).to.equal(true);
    });

    it('should not be able to make a new release on POST if no token is provided.', async function() {
      // need to uhhh make some games.
      await dataMakers.makeGame('prod');
      let gameResponse = await request.get('http://localhost:3000/api/games');
      // get the game slug from the api response
      let gameSlug = gameResponse.body.data[0].slug;
      // make a new commit id for the new release
      let commitId = dataMakers.makeRandomString(40);
      // send the request
      let releaseParams = {
        status: 'dev',
        commitId: commitId,
        version: '1.0.0'
      };

      let postResponse = await request
        .post(`http://localhost:3000/api/release/${gameSlug}`)
        .send(releaseParams);
      expect(postResponse.body.success).to.equal(false);
    });

    it('should still allow an admin user to create a game, even if they do not have privileges on that game', async function() {
      await dataMakers.makeGame('prod');
      let gameResponse = await request.get('http://localhost:3000/api/games');

      // make a admin level access token
      let editor = await dataMakers.makeUser(2);
      let token = await dataMakers.getUserToken(editor);
      // get the game slug from the api response
      let gameSlug = gameResponse.body.data[0].slug;

      // make a new commit id for the new release
      let commitId = dataMakers.makeRandomString(40);

      // send the request
      let releaseParams = {
        status: 'dev',
        commitId: commitId,
        version: '1.0.0',
        token: token
      };

      let postResponse = await request
        .post(`http://localhost:3000/api/release/${gameSlug}`)
        .send(releaseParams);
      expect(postResponse.body.success).to.equal(true);
    });
  });
});
<commit_msg>copy clean up<commit_after>const expect = require('chai').expect;
const mongoose = require('mongoose');
import fetch from 'node-fetch';
const request = require('superagent');
const dataMakers = require('../helpers/data');
const Game = require('../../app/models/game');

describe('api/release', () => {
  describe('GET', () => {
    it('should return the latest prod release for a game if no token is provided.', async function() {
      await dataMakers.makeGame('prod');
      let gameResponse = await request.get('http://localhost:3000/api/games');
      let gameSlug = gameResponse.body.data[0].slug;
      let releaseResponse = await request.get(
        `http://localhost:3000/api/release/${gameSlug}`
      );
      expect(releaseResponse.body.success).to.equal(true);
      expect(releaseResponse.body.data.game.slug).to.equal(gameSlug);
    });

    it('should return the dev releases for a game if a valid token is provided.', async function() {
      // make a write level access token
      let editor = await dataMakers.makeUser(2);
      let token = await dataMakers.getUserToken(editor);

      await dataMakers.makeGame('dev');
      let gameResponse = await request.get('http://localhost:3000/api/games');
      // get the game slug from the api response
      let gameSlug = gameResponse.body.data[0].slug;

      // add the editor token's group to the game's definition
      let gameObject = await Game.getBySlug(gameSlug);
      gameObject.groups.push({
        group: editor.groups[0],
        permission: 2
      });
      await gameObject.save();

      // send the request
      let releaseParams = {
        token: token,
        status: 'dev'
      };

      let releaseResponse = await request
        .get(`http://localhost:3000/api/release/${gameSlug}`)
        .query(`token=${token}`)
        .query('status=dev');

      expect(releaseResponse.body.success).to.equal(true);
      expect(releaseResponse.body.data.game.slug).to.equal(gameSlug);
    });

    it('should provide caching headers for non dev games', async function() {
      const game = await dataMakers.makeGame('prod');
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}`);
      expect(response.headers.get('Cache-Control')).to.not.equal(null);
    });

    it('should not provide caching headers for dev games', async function() {
      const game = await dataMakers.makeGame('dev');
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}?status=dev`);
      expect(response.headers.get('Cache-Control')).to.equal(null);
    });

    it('should respond with a 404 if a request is made for a slug that does not exist', async function() {
      const response = await fetch(`http://localhost:3000/api/release/dont-exists`);
      expect(response.status).to.equal(404);
    });

    it('should respond with a 404 if a request is made for a game that does not have a prod release', async function() {
      const game = await dataMakers.makeGame('dev');
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}`);
      expect(response.status).to.equal(404);
    });

    it('should respond with a 403 if a request is made for a dev release without a token', async function() {
      const game = await dataMakers.makeGame('dev');
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}?status=dev`);
      const json = await response.json();

      expect(response.status).to.equal(403);
    });

    it('should respond with a 422 if the request had invalid fields', async function() {
      const response = await fetch('http://localhost:3000/api/release/doesntmatter?status=NOPE&token=tooshort');
      expect(response.status).to.equal(422);
    });

    const getMethods = (obj) => {
      let properties = new Set()
      let currentObj = obj
      do {
        Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
      } while ((currentObj = Object.getPrototypeOf(currentObj)))
      return [...properties.keys()].filter(item => typeof obj[item] === 'function')
    }

    it('should respond with a 403 when user does not have permission to view the game', async function() {
      // create test objects
      const game = await dataMakers.makeGame('dev');
      const release = await dataMakers.makeRelease(game._id, 'dev');
      const user = await dataMakers.makeUser(0);
      const token = await dataMakers.getUserToken(user);
      // query api
      const response = await fetch(`http://localhost:3000/api/release/${game.slug}?commitId=${release.commitId}&token=${token}&debug=true`);
      const body = JSON.parse(await response.text());

      // test status
      expect(response.status).to.equal(403);
      // test error message
      expect(body.error.toLowerCase()).to.equal('unauthorized token');
    });
  });

  describe('POST', () => {
    it('should be able to make a new release on POST if has editor+ credentials for the game in question', async function() {
      await dataMakers.makeGame('prod');
      let gameResponse = await request.get('http://localhost:3000/api/games');

      // make a write level access token
      let editor = await dataMakers.makeUser(2);
      let token = await dataMakers.getUserToken(editor);
      // get the game slug from the api response
      let gameSlug = gameResponse.body.data[0].slug;

      // add the editor token's group to the game's definition
      let gameObject = await Game.getBySlug(gameSlug);
      gameObject.groups.push({
        group: editor.groups[0],
        permission: 2
      });
      await gameObject.save();

      // make a new commit id for the new release
      let commitId = dataMakers.makeRandomString(40);
      // send the request
      let releaseParams = {
        status: 'dev',
        commitId: commitId,
        version: '1.0.0',
        token: token
      };

      let postResponse = await request
        .post(`http://localhost:3000/api/release/${gameSlug}`)
        .send(releaseParams);
      expect(postResponse.body.success).to.equal(true);
    });

    it('should not be able to make a new release on POST if no token is provided.', async function() {
      // need to uhhh make some games.
      await dataMakers.makeGame('prod');
      let gameResponse = await request.get('http://localhost:3000/api/games');
      // get the game slug from the api response
      let gameSlug = gameResponse.body.data[0].slug;
      // make a new commit id for the new release
      let commitId = dataMakers.makeRandomString(40);
      // send the request
      let releaseParams = {
        status: 'dev',
        commitId: commitId,
        version: '1.0.0'
      };

      let postResponse = await request
        .post(`http://localhost:3000/api/release/${gameSlug}`)
        .send(releaseParams);
      expect(postResponse.body.success).to.equal(false);
    });

    it('should still allow an admin user to create a game, even if they do not have privileges on that game', async function() {
      await dataMakers.makeGame('prod');
      let gameResponse = await request.get('http://localhost:3000/api/games');

      // make a admin level access token
      let editor = await dataMakers.makeUser(2);
      let token = await dataMakers.getUserToken(editor);
      // get the game slug from the api response
      let gameSlug = gameResponse.body.data[0].slug;

      // make a new commit id for the new release
      let commitId = dataMakers.makeRandomString(40);

      // send the request
      let releaseParams = {
        status: 'dev',
        commitId: commitId,
        version: '1.0.0',
        token: token
      };

      let postResponse = await request
        .post(`http://localhost:3000/api/release/${gameSlug}`)
        .send(releaseParams);
      expect(postResponse.body.success).to.equal(true);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs')
  , mongojs = require('mongojs')
  , config = require('../config')
  , db = mongojs(config.DB)
  , municipality = db.collection('municipality')
  ;

function getData(callback){
  fs.readFile('data/municipalities.json', function(err, data){
    if(err){
      return callback(err, null);
    } else {
      return callback(null, JSON.parse(data.toString()));
    }
  })
}

function addMunicipality(post){
  municipality.save(post, function (err, success) {
    if(err){
      console.error(err);
    } else {
      console.log(success);
    }
  });
}

// First we drop the collection
municipality.drop();

// Get the init data
getData(function(err, data){
  if(err){
    console.error(err)
  } else {
    data.forEach(function(municipality){
      addMunicipality(municipality);
    });
  }
});<commit_msg>Initial commit<commit_after>'use strict';

var fs = require('fs')
  , mongojs = require('mongojs')
  , config = require('../config')
  , db = mongojs(config.DB)
  , municipality = db.collection('municipality')
  ;

function getData(callback){
  fs.readFile('data/municipalities.json', function(err, data){
    if(err){
      return callback(err, null);
    } else {
      return callback(null, JSON.parse(data.toString()));
    }
  })
}

function addMunicipality(post){
  municipality.save(post, function (err, success) {
    if(err){
      console.error(err);
    } else {
      console.log(success);
    }
  });
}

function addMunicipalities(err, data){
  if(err){
    console.error(err)
  } else {
    data.forEach(function(municipality){
      addMunicipality(municipality);
    });
  }
}

// First we drop the collection
municipality.drop();

// Get the init data, add them to the collection
getData(addMunicipalities);<|endoftext|>


<commit_before>'use strict';

const mocha = require('mocha');
const config = require('../lib/config');
const { expect } = require('chai');
const google = require('../lib/google');
const factory = require('../lib/factory');
const authConfig = config.google.auth;

describe('Google', ()=> {
   describe('OAuth', ()=> {
      it('creates client', ()=> {
         expect(google.auth.client).to.exist;
      });

      it('genenerates authorization URL', ()=> {
         const url = google.auth.url();
         expect(url).to.exist;
         expect(url).to.include(authConfig.clientID);
         expect(url).to.include(config.domain);
      });

      it('tests for expired access token', ()=> {
         expect(google.auth.expired()).is.true;
         authConfig.token.accessExpiration = new Date() + 1;
         expect(google.auth.expired()).is.false;
      });

      it('refreshes access token', ()=> {
         authConfig.token.accessExpiration = null;
         return google.auth.verify().then(() => {
            expect(authConfig.token.accessExpiration).to.exist;
            expect(authConfig.token.accessExpiration).is.instanceOf(Date);
         });
      });
   });

   describe('Drive', ()=> {
      let post = null;

      before(() => factory.buildLibrary().then(library => {
         post = library.postWithKey('owyhee-snow-and-sand/lowlands');
         return true;
      }));

      it('retrieve GPX file content', ()=> {
         return google.drive.loadGPX(post).then(gpxText => {
            expect(gpxText).to.exist;
         })
      });
   });
});<commit_msg>increase google drive test timeout to 10 seconds<commit_after>'use strict';

const mocha = require('mocha');
const config = require('../lib/config');
const { expect } = require('chai');
const google = require('../lib/google');
const factory = require('../lib/factory');
const authConfig = config.google.auth;

describe('Google', ()=> {
   describe('OAuth', ()=> {
      it('creates client', ()=> {
         expect(google.auth.client).to.exist;
      });

      it('genenerates authorization URL', ()=> {
         const url = google.auth.url();
         expect(url).to.exist;
         expect(url).to.include(authConfig.clientID);
         expect(url).to.include(config.domain);
      });

      it('tests for expired access token', ()=> {
         expect(google.auth.expired()).is.true;
         authConfig.token.accessExpiration = new Date() + 1;
         expect(google.auth.expired()).is.false;
      });

      it('refreshes access token', ()=> {
         authConfig.token.accessExpiration = null;
         return google.auth.verify().then(() => {
            expect(authConfig.token.accessExpiration).to.exist;
            expect(authConfig.token.accessExpiration).is.instanceOf(Date);
         });
      });
   });

   describe('Drive', ()=> {
      let post = null;

      before(() => factory.buildLibrary().then(library => {
         post = library.postWithKey('owyhee-snow-and-sand/lowlands');
         return true;
      }));

      it('retrieve GPX file content', function() {
         this.timeout = 10000;
         return google.drive.loadGPX(post).then(gpxText => {
            expect(gpxText).to.exist;
         })
      });
   });
});<|endoftext|>


<commit_before>/**
 * Copyright 2016 Jean Desravines <hi@jeandesravines.com>
 */

'use strict';

const {afterEach, beforeEach, describe, it} = require('mocha');
const {expect, should} = require('chai');
const fs = require('fs');
const promisify = require('@jdes/promisify');
const rimraf = require('rimraf');
const Gpio = require('../../lib/helper/gpio');
const UnknownChannelError = require('../../lib/error/unknown-channel-error');
const UnknownEdgeError = require('../../lib/error/unknown-edge-error');
const UnknownDirectionError = require('../../lib/error/unknown-direction-error');

describe('Gpio', () => {
	/**
	 * @type {Gpio}
	 */
	let gpio;

	/**
	 * @readonly
	 * @type {string}
	 */
	const path = '.gpio.tmp';

	/**
	 * @readonly
	 * @type {Object.<string, *>}
	 */
	let config = {
		path: Gpio.path
	};

	/* Hooks */

	beforeEach(() => {
		Gpio.path = path;
	});

	beforeEach('Instantiate and open 7th channel to out', () => {
		return promisify(rimraf)(path, {})
			.then(() => promisify(fs.mkdir)(path))
			.then(() => Promise.all(Object.keys(Gpio.mapping).map((channel) => {
				return promisify(fs.mkdir)(path + '/' + Gpio.mapping[channel])
			})))
			.then(() => gpio = new Gpio())
			.then(() => gpio.open(7, Gpio.direction.out));
	});

	afterEach('Close', () => {
		return gpio.close(7)
			.then(() => promisify(rimraf)(path, {}));
	});

	afterEach(() => {
		Gpio.path = config.path;
	});

	/* Tests */

	describe('FileSystem', () => {
		describe('read', () => {
			it('should reject on read with a wrong path', () => {
				return Gpio.readFile('directory/unknown')
					.then(() => Promise.reject())
					.catch(() => Promise.resolve());
			});
		});

		describe('write', () => {
			it('should reject on write with a wrong path', () => {
				return Gpio.writeFile('directory/unknown', '')
					.then(() => Promise.reject())
					.catch(() => Promise.resolve());
			});
		});

		describe('exists', () => {
			it('should exists', () => {
				expect(Gpio.exists('.')).to.be.equal(true);
			});

			it('should not exists', () => {
				expect(Gpio.exists('.unknown')).to.be.equal(false);
			});
		})
	});

	describe('Config', () => {
		describe('Pin Mapping', () => {
			it('should throw an error if get a pin on a unknown channel', () => {
				expect(() => Gpio.pins[30]).to.throw(UnknownChannelError);
			});

			it('should return 4', () => {
				expect(Gpio.pins[7]).to.be.equal(4);
			});
		});

		describe('Open', () => {
			it('should open a channel', () => {
				return gpio.open(7, Gpio.direction.out);
			});

			it('should be open on channel 7', () => {
				return gpio.getValue(7)
					.then((value) => {
						expect(value).to.satisfy(Number.isInteger);
					});
			});
		});
	});

	describe('Edit', () => {
		describe('Direction', () => {
			it('should throw an error', () => {
				gpio.setDirection(7, 'unknown')
					.then(() => Promise.reject())
					.catch((error) => {
						expect(error).to.be.a(UnknownDirectionError)
					});
			});

			Object.keys(Gpio.direction).forEach((i) => {
				const value = Gpio.direction[i];

				it(`should set to ${value}`, () => {
					return gpio.setDirection(7, value)
						.then(() => gpio.getDirection(7))
						.then((value) => {
							expect(value).to.be.equal(value);
						});
				});
			});
		});

		describe('Edge', () => {
			it('should throw an error', () => {
				gpio.setEdge(7, 'unknown')
					.then(() => Promise.reject())
					.catch((error) => {
						expect(error).to.be.a(UnknownEdgeError)
					});
			});

			Object.keys(Gpio.edge).forEach((i) => {
				const value = Gpio.edge[i];

				it(`should set to ${value}`, () => {
					return gpio.setEdge(7, value)
						.then(() => gpio.getEdge(7))
						.then((value) => {
							expect(value).to.be.equal(value);
						});
				});
			});
		});

		describe('Path', () => {
			expect(Gpio.paths.v1).to.be.equal('/sys/devices/virtual/gpio');
			expect(Gpio.paths.v2).to.be.equal('/sys/class/gpio');
		});
	});

	describe('IO', () => {
		describe('Digital', () => {
			it('should set to high', () => {
				return gpio.setValue(7, -1)
					.then(() => gpio.getValue(7))
					.then((value) => {
						expect(value).to.be.equal(Gpio.signal.high);
					});
			});

			Object.keys(Gpio.direction).forEach((i) => {
				const direction = Gpio.direction[i];

				Object.keys(Gpio.signal).forEach((j) => {
					const signal = Gpio.signal[j];

					it(`should set to ${signal} to an ${direction} channel`, () => {
						return gpio.setDirection(7, direction)
							.then(() => gpio.setValue(7, signal))
							.then(() => gpio.getValue(7))
							.then((value) => {
								expect(value).to.be.equal(signal);
							});
					});
				});
			});
		});

		describe('Analog', () => {
			it('set value to low signal', () => {
				return gpio.setAnalogValue(7, Gpio.signal.low, 100);
			});

			it('set value to high signal', () => {
				return gpio.setAnalogValue(7, Gpio.signal.high, 100);
			});

			it('set value to ~0.5', () => {
				return gpio.setAnalogValue(7, 0.5, 100)
					.then(() => gpio.getAnalogValue(7, 200))
					.then((value) => {
						expect(value).to.be.closeTo(0.5, 0.05);
					});
			});
		});
	});
});<commit_msg>const<commit_after>/**
 * Copyright 2016 Jean Desravines <hi@jeandesravines.com>
 */

'use strict';

const {afterEach, beforeEach, describe, it} = require('mocha');
const {expect, should} = require('chai');
const fs = require('fs');
const promisify = require('@jdes/promisify');
const rimraf = require('rimraf');
const Gpio = require('../../lib/helper/gpio');
const UnknownChannelError = require('../../lib/error/unknown-channel-error');
const UnknownEdgeError = require('../../lib/error/unknown-edge-error');
const UnknownDirectionError = require('../../lib/error/unknown-direction-error');

describe('Gpio', () => {
	/**
	 * @type {Gpio}
	 */
	let gpio;

	/**
	 * @readonly
	 * @type {string}
	 */
	const path = '.gpio.tmp';

	/**
	 * @readonly
	 * @type {Object.<string, *>}
	 */
	let config = {
		path: Gpio.path
	};

	/* Hooks */

	beforeEach(() => {
		Gpio.path = path;
	});

	beforeEach('Instantiate and open 7th channel to out', () => {
		return promisify(rimraf)(path, {})
			.then(() => promisify(fs.mkdir)(path))
			.then(() => Promise.all(Object.keys(Gpio.mapping).map((channel) => {
				return promisify(fs.mkdir)(path + '/' + Gpio.mapping[channel])
			})))
			.then(() => gpio = new Gpio())
			.then(() => gpio.open(7, Gpio.direction.out));
	});

	afterEach('Close', () => {
		return gpio.close(7)
			.then(() => promisify(rimraf)(path, {}));
	});

	afterEach(() => {
		Gpio.path = config.path;
	});

	/* Tests */

	describe('FileSystem', () => {
		describe('read', () => {
			it('should reject on read with a wrong path', () => {
				return Gpio.readFile('directory/unknown')
					.then(() => Promise.reject())
					.catch(() => Promise.resolve());
			});
		});

		describe('write', () => {
			it('should reject on write with a wrong path', () => {
				return Gpio.writeFile('directory/unknown', '')
					.then(() => Promise.reject())
					.catch(() => Promise.resolve());
			});
		});

		describe('exists', () => {
			it('should exists', () => {
				expect(Gpio.exists('.')).to.be.equal(true);
			});

			it('should not exists', () => {
				expect(Gpio.exists('.unknown')).to.be.equal(false);
			});
		})
	});

	describe('Config', () => {
		describe('Pin Mapping', () => {
			it('should throw an error if get a pin on a unknown channel', () => {
				expect(() => Gpio.pins[30]).to.throw(UnknownChannelError);
			});

			it('should return 4', () => {
				expect(Gpio.pins[7]).to.be.equal(4);
			});
		});

		describe('Open', () => {
			it('should open a channel', () => {
				return gpio.open(7, Gpio.direction.out);
			});

			it('should be open on channel 7', () => {
				return gpio.getValue(7)
					.then((value) => {
						expect(value).to.satisfy(Number.isInteger);
					});
			});
		});
	});

	describe('Edit', () => {
		describe('Direction', () => {
			it('should throw an error', () => {
				gpio.setDirection(7, 'unknown')
					.then(() => Promise.reject())
					.catch((error) => {
						expect(error).to.be.a(UnknownDirectionError)
					});
			});

			Object.keys(Gpio.direction).forEach((i) => {
				const value = Gpio.direction[i];

				it(`should set to ${value}`, () => {
					return gpio.setDirection(7, value)
						.then(() => gpio.getDirection(7))
						.then((value) => {
							expect(value).to.be.equal(value);
						});
				});
			});
		});

		describe('Edge', () => {
			it('should throw an error', () => {
				gpio.setEdge(7, 'unknown')
					.then(() => Promise.reject())
					.catch((error) => {
						expect(error).to.be.a(UnknownEdgeError)
					});
			});

			Object.keys(Gpio.edge).forEach((i) => {
				const value = Gpio.edge[i];

				it(`should set to ${value}`, () => {
					return gpio.setEdge(7, value)
						.then(() => gpio.getEdge(7))
						.then((value) => {
							expect(value).to.be.equal(value);
						});
				});
			});
		});

		describe('Path', () => {
			expect(Gpio.paths.v1).to.be.equal('/sys/devices/virtual/gpio');
			expect(Gpio.paths.v2).to.be.equal('/sys/class/gpio');
		});
	});

	describe('IO', () => {
		describe('Digital', () => {
			it('should set to high', () => {
				return gpio.setValue(7, -1)
					.then(() => gpio.getValue(7))
					.then((value) => {
						expect(value).to.be.equal(Gpio.signal.high);
					});
			});

			Object.keys(Gpio.direction).forEach((i) => {
				Object.keys(Gpio.signal).forEach((j) => {
					const direction = Gpio.direction[i];
					const signal = Gpio.signal[j];

					it(`should set to ${signal} to an ${direction} channel`, () => {
						return gpio.setDirection(7, direction)
							.then(() => gpio.setValue(7, signal))
							.then(() => gpio.getValue(7))
							.then((value) => {
								expect(value).to.be.equal(signal);
							});
					});
				});
			});
		});

		describe('Analog', () => {
			it('set value to low signal', () => {
				return gpio.setAnalogValue(7, Gpio.signal.low, 100);
			});

			it('set value to high signal', () => {
				return gpio.setAnalogValue(7, Gpio.signal.high, 100);
			});

			it('set value to ~0.5', () => {
				return gpio.setAnalogValue(7, 0.5, 100)
					.then(() => gpio.getAnalogValue(7, 200))
					.then((value) => {
						expect(value).to.be.closeTo(0.5, 0.05);
					});
			});
		});
	});
});<|endoftext|>


<commit_before>describe('issues', function() {
  it('formats `2011-09-29 14:50:49`', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/19
    expect($.format.date('2011-09-29 14:50:49', 'MMM dd, yyyy')).toEqual('Sep 29, 2011');
  });

  it('formats `2011-04-25T09:04:14.7270000`', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/17
    expect($.format.date('2011-04-25T09:04:14.7270000', 'yyyy-MM-dd HH:mm')).toEqual('2011-04-25 09:04');
  });

  it('formats `Wed Jan 09 06:23:38 PST 2012`', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/24
    expect($.format.date('Wed Jan 09 06:23:38 PST 2012', '-')).toEqual('-');
    expect($.format.date('Wed Jan 09 06:23:38 PST 2012', 'd-')).toEqual('9-');
    expect($.format.date('Wed Jan 09 06:23:38 PST 2012', 'd/')).toEqual('9/');
  });

  it('formats `2012-02-07CET00:00:00`', function() {
    // https://github.com/phstc/jquery-dateFormat/pull/22
    expect($.format.date('2012-02-07CET00:00:00', 'dd/MM/yyyy')).toEqual('07/02/2012');
    expect($.format.date('2012-02-07CET00:00:00', 'MMM/yyyy')).toEqual('Feb/2012');
    expect($.format.date('2012-02-07CET00:00:00', 'MM')).toEqual('02');
    expect($.format.date('2012-02-07CET00:00:00', 'dd')).toEqual('07');
    expect($.format.date('2012-02-07CET00:00:00', 'yyyy')).toEqual('2012');
  });

  it('formats `946782123000`', function() {
    // https://github.com/phstc/jquery-dateFormat/pull/22
    var testDate = new Date('Jan 2, 2000 01:02:03');
    expect($.format.date(testDate.getTime(), 'MM')).toEqual('01');
    expect($.format.date(testDate.getTime(), 'd')).toEqual('2');
    expect($.format.date(testDate.getTime(), 'yyyy')).toEqual('2000');
    expect($.format.date(testDate.getTime(), 'HH')).toEqual('01');
    expect($.format.date(testDate.getTime(), 'mm')).toEqual('02');
    expect($.format.date(testDate.getTime(), 'ss')).toEqual('03');
  });

  it('formats `2009-04-19T16:11:05-02:00`', function() {
    // http://pablocantero.com/blog/2010/09/04/jquery-plugin-javascript-for-java-util-date-tostring-format/#comment-259520318
    expect($.format.date('2009-04-19T16:11:05-02:00', 'dd/MM/yyyy')).toEqual('19/04/2009');
    expect($.format.date('2009-04-19T16:11:05-02:00', 'MMM/yyyy')).toEqual('Apr/2009');
  });

  it('formats `Mon Mar 28 2011 17:45:00 GMT-0400 (Eastern Daylight Time)`', function() {
    // http://pablocantero.com/blog/2010/09/04/jquery-plugin-javascript-for-java-util-date-tostring-format/#comment-178490699
    expect($.format.date('Mon Mar 28 2011 17:45:00 GMT-0400 (Eastern Daylight Time)', 'hh:mma')).toEqual('05:45PM');
    expect($.format.date('Mon Mar 28 2011 17:45:00 GMT-0400 (Eastern Daylight Time)', 'hh:mmp')).toEqual('05:45p.m.');
  });

  it('formats `h:mm` `2012-02-07CET00:00:00`', function() {
    var testDate = new Date('Jan 2, 2000 00:00:00');
    expect($.format.date(testDate, 'h:mm')).toEqual('12:00');
  });

  it('formats `dd/MM/yyyy HH:mm` `Mon Apr 28 2014 05:30:00 GMT-0300`', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/64
    // Mon Mar 28 2011 17:45:00 GMT-0400 (Eastern Daylight Time)
    expect($.format.date('Mon Apr 28 2014 05:30:00 GMT-0300', 'dd/MM/yyyy HH:mm')).toEqual('28/04/2014 05:30');
  });

  it('parseDate `yyyy-MM-dd HH:mm:ss` `2015-01-16 12:55:54` missing time ?', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/75
    // missing time when parsing ??
    expect($.format.parseDate('2015-01-16 12:55:54', 'yyyy-MM-dd HH:mm:ss').date.getMinutes()).toEqual(55);
  });
});
<commit_msg>Add test for issue #77: Leading 0 for 'SSS' (milliseconds) is missing<commit_after>describe('issues', function() {
  it('formats `2011-09-29 14:50:49`', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/19
    expect($.format.date('2011-09-29 14:50:49', 'MMM dd, yyyy')).toEqual('Sep 29, 2011');
  });

  it('formats `2011-04-25T09:04:14.7270000`', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/17
    expect($.format.date('2011-04-25T09:04:14.7270000', 'yyyy-MM-dd HH:mm')).toEqual('2011-04-25 09:04');
  });

  it('formats `Wed Jan 09 06:23:38 PST 2012`', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/24
    expect($.format.date('Wed Jan 09 06:23:38 PST 2012', '-')).toEqual('-');
    expect($.format.date('Wed Jan 09 06:23:38 PST 2012', 'd-')).toEqual('9-');
    expect($.format.date('Wed Jan 09 06:23:38 PST 2012', 'd/')).toEqual('9/');
  });

  it('formats `2012-02-07CET00:00:00`', function() {
    // https://github.com/phstc/jquery-dateFormat/pull/22
    expect($.format.date('2012-02-07CET00:00:00', 'dd/MM/yyyy')).toEqual('07/02/2012');
    expect($.format.date('2012-02-07CET00:00:00', 'MMM/yyyy')).toEqual('Feb/2012');
    expect($.format.date('2012-02-07CET00:00:00', 'MM')).toEqual('02');
    expect($.format.date('2012-02-07CET00:00:00', 'dd')).toEqual('07');
    expect($.format.date('2012-02-07CET00:00:00', 'yyyy')).toEqual('2012');
  });

  it('formats `946782123000`', function() {
    // https://github.com/phstc/jquery-dateFormat/pull/22
    var testDate = new Date('Jan 2, 2000 01:02:03');
    expect($.format.date(testDate.getTime(), 'MM')).toEqual('01');
    expect($.format.date(testDate.getTime(), 'd')).toEqual('2');
    expect($.format.date(testDate.getTime(), 'yyyy')).toEqual('2000');
    expect($.format.date(testDate.getTime(), 'HH')).toEqual('01');
    expect($.format.date(testDate.getTime(), 'mm')).toEqual('02');
    expect($.format.date(testDate.getTime(), 'ss')).toEqual('03');
  });

  it('formats `2009-04-19T16:11:05-02:00`', function() {
    // http://pablocantero.com/blog/2010/09/04/jquery-plugin-javascript-for-java-util-date-tostring-format/#comment-259520318
    expect($.format.date('2009-04-19T16:11:05-02:00', 'dd/MM/yyyy')).toEqual('19/04/2009');
    expect($.format.date('2009-04-19T16:11:05-02:00', 'MMM/yyyy')).toEqual('Apr/2009');
  });

  it('formats `Mon Mar 28 2011 17:45:00 GMT-0400 (Eastern Daylight Time)`', function() {
    // http://pablocantero.com/blog/2010/09/04/jquery-plugin-javascript-for-java-util-date-tostring-format/#comment-178490699
    expect($.format.date('Mon Mar 28 2011 17:45:00 GMT-0400 (Eastern Daylight Time)', 'hh:mma')).toEqual('05:45PM');
    expect($.format.date('Mon Mar 28 2011 17:45:00 GMT-0400 (Eastern Daylight Time)', 'hh:mmp')).toEqual('05:45p.m.');
  });

  it('formats `h:mm` `2012-02-07CET00:00:00`', function() {
    var testDate = new Date('Jan 2, 2000 00:00:00');
    expect($.format.date(testDate, 'h:mm')).toEqual('12:00');
  });

  it('formats `dd/MM/yyyy HH:mm` `Mon Apr 28 2014 05:30:00 GMT-0300`', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/64
    // Mon Mar 28 2011 17:45:00 GMT-0400 (Eastern Daylight Time)
    expect($.format.date('Mon Apr 28 2014 05:30:00 GMT-0300', 'dd/MM/yyyy HH:mm')).toEqual('28/04/2014 05:30');
  });

  it('parseDate `yyyy-MM-dd HH:mm:ss` `2015-01-16 12:55:54` missing time ?', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/75
    // missing time when parsing ??
    expect($.format.parseDate('2015-01-16 12:55:54', 'yyyy-MM-dd HH:mm:ss').date.getMinutes()).toEqual(55);
  });

  it('formats `dd/MM/yyyy HH:mm` `Mon Apr 28 2014 05:30:00 GMT-0300`', function() {
    // https://github.com/phstc/jquery-dateFormat/issues/77
    // Leading 0 for "SSS"(milliseconds) is missing
    expect($.format.date(new Date(2015, 4, 6, 15, 32, 12, 34), 'MM/dd/yyyy HH:mm:ss.SSS')).toEqual('05/06/2015 15:32:12.034');
  });
});
<|endoftext|>