<commit_before>var _ = require('underscore');

var Player = require('./character/player');
var Overworld = require('./world/overworld');

window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

(function() {
  'use strict';

  var canvas = document.getElementById('game');
  var ctx = canvas.getContext('2d');

  canvas.tabIndex = 1;

  var game = {
    initialize : function() {
      this.run = this.run.bind(this);
      this.tick = this.tick.bind(this);
      this.render = this.render.bind(this);
      this.calculateLayout = this.calculateLayout.bind(this);

      this.calculateLayout();

      this.overworld = new Overworld();
      this.character = new Player('Hero');

      this.listenForUserInput();
      this.listenForWindowResize();

      // TODO: Remove (testing)
      this.listenForPlayerChange();
      this.listenForMouseMovement();
    },

    listenForWindowResize : function() {
      // Limit amount of redraws during window resize
      var lazyLayout = _.debounce(this.calculateLayout, 300);
      window.addEventListener('resize', lazyLayout);
    },

    toggleSettings : function() {
      var settingsContainer = document.getElementById('settings');

      if (settingsContainer.style.display === 'none') {
        settingsContainer.style.display = 'block';
      } else {
        settingsContainer.style.display = 'none';
      }
    },

    showSettings : function() {
      document.getElementById('settings').style.display = 'block';
    },

    hideSettings : function() {
      document.getElementById('settings').style.display = 'none';
    },

    calculateLayout : function() {
      this.scale = window.innerWidth / 15 / 16 / 2;

      ctx.clearRect ( 0 , 0 , ctx.canvas.width, ctx.canvas.height );

      ctx.canvas.width = 15*16*this.scale;
      ctx.canvas.height = 15*16*this.scale;
    },

    listenForMouseMovement : function() {
      var self = this,
          timeout = null;

      window.addEventListener('mousemove', function(e) {
        clearTimeout(timeout);

        self.showSettings();
        timeout = setTimeout(self.hideSettings, 3000);
      });
    },

    listenForPlayerChange : function() {
      var playerSelect = document.getElementById('playerSelection');
      var self = this;

      playerSelect.addEventListener('change', function(e) {
        self.character = new Player(e.target.value);
      });

    },

    listenForUserInput : function() {
      window.addEventListener('keydown', function(e) {
        var direction = '';

        switch(e.keyCode) {
          case 38: // up
            e.preventDefault();
            direction = 'north';
            break;
          case 40: // down
            e.preventDefault();
            direction = 'south';
            break;
          case 39: // right
            e.preventDefault();
            direction = 'east';
            break;
          case 37: // left
            e.preventDefault();
            direction = 'west';
            break;
        }

        if (direction !== '') {
          var canMove = this.overworld.canMove(
            this.character.state.position,
            direction,
            this.character.type
          );

          this.character.move(direction, canMove);
        }

      }.bind(this), false);
    },

    run : function() {
      requestAnimFrame(this.run);

      this.tick();
      this.render();
    },

    tick : function() {
      this.overworld.tick(this.character.state.position);
      this.character.tick();
    },

    render : function() {
      this.overworld.render(ctx, this.scale);
      this.character.render(ctx, this.scale);
    }
  };

  game.initialize();
  game.run();

}());<commit_msg>Give the canvas focus after changing the player<commit_after>var _ = require('underscore');

var Player = require('./character/player');
var Overworld = require('./world/overworld');

window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

(function() {
  'use strict';

  var canvas = document.getElementById('game');
  var ctx = canvas.getContext('2d');

  canvas.tabIndex = 1;

  var game = {
    initialize : function() {
      this.run = this.run.bind(this);
      this.tick = this.tick.bind(this);
      this.render = this.render.bind(this);
      this.calculateLayout = this.calculateLayout.bind(this);

      this.calculateLayout();

      this.overworld = new Overworld();
      this.character = new Player('Hero');

      this.listenForUserInput();
      this.listenForWindowResize();

      // TODO: Remove (testing)
      this.listenForPlayerChange();
      this.listenForMouseMovement();
    },

    listenForWindowResize : function() {
      // Limit amount of redraws during window resize
      var lazyLayout = _.debounce(this.calculateLayout, 300);
      window.addEventListener('resize', lazyLayout);
    },

    toggleSettings : function() {
      var settingsContainer = document.getElementById('settings');

      if (settingsContainer.style.display === 'none') {
        settingsContainer.style.display = 'block';
      } else {
        settingsContainer.style.display = 'none';
      }
    },

    showSettings : function() {
      document.getElementById('settings').style.display = 'block';
    },

    hideSettings : function() {
      document.getElementById('settings').style.display = 'none';
    },

    calculateLayout : function() {
      this.scale = window.innerWidth / 15 / 16 / 2;

      ctx.clearRect ( 0 , 0 , ctx.canvas.width, ctx.canvas.height );

      ctx.canvas.width = 15*16*this.scale;
      ctx.canvas.height = 15*16*this.scale;
    },

    listenForMouseMovement : function() {
      var self = this,
          timeout = null;

      window.addEventListener('mousemove', function(e) {
        clearTimeout(timeout);

        self.showSettings();
        timeout = setTimeout(self.hideSettings, 3000);
      });
    },

    listenForPlayerChange : function() {
      var playerSelect = document.getElementById('playerSelection');
      var self = this;

      playerSelect.addEventListener('change', function(e) {
        self.character = new Player(e.target.value);

        canvas.tabIndex = 1;
      });

    },

    listenForUserInput : function() {
      window.addEventListener('keydown', function(e) {
        var direction = '';

        switch(e.keyCode) {
          case 38: // up
            e.preventDefault();
            direction = 'north';
            break;
          case 40: // down
            e.preventDefault();
            direction = 'south';
            break;
          case 39: // right
            e.preventDefault();
            direction = 'east';
            break;
          case 37: // left
            e.preventDefault();
            direction = 'west';
            break;
        }

        if (direction !== '') {
          var canMove = this.overworld.canMove(
            this.character.state.position,
            direction,
            this.character.type
          );

          this.character.move(direction, canMove);
        }

      }.bind(this), false);
    },

    run : function() {
      requestAnimFrame(this.run);

      this.tick();
      this.render();
    },

    tick : function() {
      this.overworld.tick(this.character.state.position);
      this.character.tick();
    },

    render : function() {
      this.overworld.render(ctx, this.scale);
      this.character.render(ctx, this.scale);
    }
  };

  game.initialize();
  game.run();

}());<|endoftext|>


<commit_before>// This module is modified from dojox/mobile/_ScrollableMixin and dojox/mobile/ScrollableView
define([
	"dojo/_base/declare",
	"dojo/_base/lang",
	"dojo/dom-class",
	"dojo/dom-construct",
	"./scrollable"],
	function(declare, lang, domClass, domConstruct, Scrollable){
	// module:
	//		dojox/mobile/_ScrollableMixin
	// summary:
	//		Mixin for widgets to have a touch scrolling capability.

	var cls = declare("dojox.app.widgets._ScrollableMixin", null, {
		// summary:
		//		Mixin for widgets to have a touch scrolling capability.
		// description:
		//		Actual implementation is in scrollable.js.
		//		scrollable.js is not a dojo class, but just a collection
		//		of functions. This module makes scrollable.js a dojo class.

		// remove fixedHeader and fixedFooter, let dojox/app layout container to do header and footer layout
		// fixedHeader: String
		//		Id of the fixed header.
		//fixedHeader: "",

		// fixedFooter: String
		//		Id of the fixed footer.
		//fixedFooter: "",

		// scrollableParams: Object
		//		Parameters for dojox/mobile/scrollable.init().
		scrollableParams: null,

		// allowNestedScrolls: Boolean
		//		e.g. Allow ScrollableView in a SwapView.
		allowNestedScrolls: true,

		// remove appBars, let dojox/app layout container to do appBars layout
		//appBars: true, // search for application-level bars

		constructor: function(){
			this.scrollableParams = {};
		},

		destroy: function(){
			this.cleanup();
			this.inherited(arguments);
		},

		startup: function(){
			if(this._started){ return; }
			var params = this.scrollableParams;
			this.init(params);
			this.inherited(arguments);
			this.reparent();
			//remove fixedHeader and fixedFooter
		},

		// build scrollable container domNode. This method from dojox/mobile/ScrollableView
		buildRendering: function(){
			this.inherited(arguments);
			domClass.add(this.domNode, "mblScrollableView");
			this.domNode.style.overflow = "hidden";
			this.domNode.style.top = "0px";
			this.containerNode = domConstruct.create("div",	{className:"mblScrollableViewContainer"}, this.domNode);
			this.containerNode.style.position = "absolute";
			this.containerNode.style.top = "0px"; // view bar is relative
			if(this.scrollDir === "v"){
				this.containerNode.style.width = "100%";
			}
		},

		// This method from dojox/mobile/ScrollableView
		reparent: function(){
			// summary:
			//		Moves all the children to containerNode.
			var i, idx, len, c;
			for(i = 0, idx = 0, len = this.domNode.childNodes.length; i < len; i++){
				c = this.domNode.childNodes[idx];
				// search for view-specific header or footer
				if(c === this.containerNode){
					idx++;
					continue;
				}
				this.containerNode.appendChild(this.domNode.removeChild(c));
			}
		},

		// This method from dojox/mobile/ScrollableView
		resize: function(){
			// summary:
			//		Calls resize() of each child widget.
			this.inherited(arguments); // scrollable#resize() will be called
			array.forEach(this.getChildren(), function(child){
				if(child.resize){ child.resize(); }
			});
		}
	});
	lang.extend(cls, new Scrollable());
	return cls;
});
<commit_msg>remove commented out props so they don't appear in api doc<commit_after>// This module is modified from dojox/mobile/_ScrollableMixin and dojox/mobile/ScrollableView
define([
	"dojo/_base/declare",
	"dojo/_base/lang",
	"dojo/dom-class",
	"dojo/dom-construct",
	"./scrollable"],
	function(declare, lang, domClass, domConstruct, Scrollable){
	// module:
	//		dojox/mobile/_ScrollableMixin
	// summary:
	//		Mixin for widgets to have a touch scrolling capability.

	var cls = declare("dojox.app.widgets._ScrollableMixin", null, {
		// summary:
		//		Mixin for widgets to have a touch scrolling capability.
		// description:
		//		Actual implementation is in scrollable.js.
		//		scrollable.js is not a dojo class, but just a collection
		//		of functions. This module makes scrollable.js a dojo class.

		// scrollableParams: Object
		//		Parameters for dojox/mobile/scrollable.init().
		scrollableParams: null,

		// allowNestedScrolls: Boolean
		//		e.g. Allow ScrollableView in a SwapView.
		allowNestedScrolls: true,

		constructor: function(){
			this.scrollableParams = {};
		},

		destroy: function(){
			this.cleanup();
			this.inherited(arguments);
		},

		startup: function(){
			if(this._started){ return; }
			var params = this.scrollableParams;
			this.init(params);
			this.inherited(arguments);
			this.reparent();
		},

		// build scrollable container domNode. This method from dojox/mobile/ScrollableView
		buildRendering: function(){
			this.inherited(arguments);
			domClass.add(this.domNode, "mblScrollableView");
			this.domNode.style.overflow = "hidden";
			this.domNode.style.top = "0px";
			this.containerNode = domConstruct.create("div",	{className:"mblScrollableViewContainer"}, this.domNode);
			this.containerNode.style.position = "absolute";
			this.containerNode.style.top = "0px"; // view bar is relative
			if(this.scrollDir === "v"){
				this.containerNode.style.width = "100%";
			}
		},

		// This method from dojox/mobile/ScrollableView
		reparent: function(){
			// summary:
			//		Moves all the children to containerNode.
			var i, idx, len, c;
			for(i = 0, idx = 0, len = this.domNode.childNodes.length; i < len; i++){
				c = this.domNode.childNodes[idx];
				// search for view-specific header or footer
				if(c === this.containerNode){
					idx++;
					continue;
				}
				this.containerNode.appendChild(this.domNode.removeChild(c));
			}
		},

		// This method from dojox/mobile/ScrollableView
		resize: function(){
			// summary:
			//		Calls resize() of each child widget.
			this.inherited(arguments); // scrollable#resize() will be called
			array.forEach(this.getChildren(), function(child){
				if(child.resize){ child.resize(); }
			});
		}
	});
	lang.extend(cls, new Scrollable());
	return cls;
});
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// for license information please see license.txt

frappe.provide("frappe.form.formatters");

frappe.form.formatters = {
	_right: function(value, options) {
		if(options && options.inline) {
			return value;
		} else {
			return "
" + value + "
";
		}
	},
	Data: function(value) {
		return value==null ? "" : value;
	},
	Select: function(value) {
		return __(frappe.form.formatters["Data"](value));
	},
	Float: function(value, docfield, options, doc) {
		// don't allow 0 precision for Floats, hence or'ing with null
		var precision = docfield.precision || cint(frappe.boot.sysdefaults.float_precision) || null;
		if (docfield.options && docfield.options.trim()) {
			// options points to a currency field, but expects precision of float!
			docfield.precision = precision;
			return frappe.form.formatters.Currency(value, docfield, options, doc);

		} else {
			// show 1.000000 as 1
			if (!(options || {}).always_show_decimals && !is_null(value)) {
				var temp = cstr(value).split(".");
				if (temp[1]==undefined || cint(temp[1])===0) {
					precision = 0;
				}
			}

			return frappe.form.formatters._right(
				((value==null || value==="")
					? ""
					: format_number(value, null, precision)), options);
		}
	},
	Int: function(value, docfield, options) {
		return frappe.form.formatters._right(value==null ? "" : cint(value), options)
	},
	Percent: function(value, docfield, options) {
		return frappe.form.formatters._right(flt(value, 2) + "%", options)
	},
	Currency: function(value, docfield, options, doc) {
		var currency = frappe.meta.get_field_currency(docfield, doc);
		return frappe.form.formatters._right((value==null || value==="")
			? "" : format_currency(value, currency, docfield.precision || null), options);
	},
	Check: function(value) {
		if(value) {
			return '';
		} else {
			return '';
		}
	},
	Link: function(value, docfield, options) {
		var doctype = docfield._options || docfield.options;
		if(value && value.match(/^['"].*['"]$/)) {
			return value.replace(/^.(.*).$/, "$1");
		}
		if(options && options.for_print) {
			return value;
		}
		if(!value) {
			return "";
		}
		if(docfield && docfield.link_onclick) {
			return repl('%(value)s',
				{onclick: docfield.link_onclick.replace(/"/g, '"'), value:value});
		} else if(docfield && doctype) {
			return repl('%(label)s', {
				doctype: encodeURIComponent(doctype),
				name: encodeURIComponent(value),
				label: __(options && options.label || value)
			});
		} else {
			return value;
		}
	},
	Date: function(value) {
		return value ? dateutil.str_to_user(value) : "";
	},
	Datetime: function(value) {
		return value ? dateutil.str_to_user(dateutil.convert_to_user_tz(value)) : "";
	},
	Text: function(value) {
		if(value) {
			var tags = ["<p", "<div", "<br", "<table"];
			var match = false;

			for(var i=0; i<tags.length; i++) {
				if(value.match(tags[i])) {
					match = true;
					break;
				}
			}

			if(!match) {
				value = replace_newlines(value);
			}
		}

		return frappe.form.formatters.Data(value);
	},
	StarredBy: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= '';
		});
		return html;
	},
	Tag: function(value) {
		var html = "";
		$.each((value || "").split(","), function(i, v) {
			if(v) html+= ''+v +'';
		});
		return html;
	},
	Comment: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v.comment+'';
		});
		return html;
	},
	Assign: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v+'';
		});
		return html;
	},
	SmallText: function(value) {
		return frappe.form.formatters.Text(value);
	},
	TextEditor: function(value) {
		return frappe.form.formatters.Text(value);
	},
	Code: function(value) {
		return "
" + (value==null ? "" : $("
").text(value).html()) + "
"
	},
	WorkflowState: function(value) {
		workflow_state = frappe.get_doc("Workflow State", value);
		if(workflow_state) {
			return repl("\
				 %(value)s", {
					value: value,
					style: workflow_state.style.toLowerCase(),
					icon: workflow_state.icon
				});
		} else {
			return "" + value + "";
		}
	},
	Email: function(value) {
		return $("

").text(value).html();
	}
}

frappe.form.get_formatter = function(fieldtype) {
	if(!fieldtype)
		fieldtype = "Data";
	return frappe.form.formatters[fieldtype.replace(/ /g, "")] || frappe.form.formatters.Data;
}

frappe.format = function(value, df, options, doc) {
	if(!df) df = {"fieldtype":"Data"};
	var fieldtype = df.fieldtype || "Data";

	// format Dynamic Link as a Link
	if(fieldtype==="Dynamic Link") {
		fieldtype = "Link";
		df._options = doc ? doc[df.options] : null;
	}

	formatter = df.formatter || frappe.form.get_formatter(fieldtype);

	var formatted = formatter(value, df, options, doc);

	if (typeof formatted == "string")
		formatted = frappe.utils.remove_script_and_style(formatted);

	return formatted;
}

frappe.get_format_helper = function(doc) {
	var helper = {
		get_formatted: function(fieldname) {
			var df = frappe.meta.get_docfield(doc.doctype, fieldname);
			if(!df) { console.log("fieldname not found: " + fieldname); };
			return frappe.format(doc[fieldname], df, {inline:1}, doc);
		}
	};
	$.extend(helper, doc);
	return helper;
}
<commit_msg>[fix] handle invalid date in formatter. Fixes frappe/erpnext#4468<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// for license information please see license.txt

frappe.provide("frappe.form.formatters");

frappe.form.formatters = {
	_right: function(value, options) {
		if(options && options.inline) {
			return value;
		} else {
			return "
" + value + "
";
		}
	},
	Data: function(value) {
		return value==null ? "" : value;
	},
	Select: function(value) {
		return __(frappe.form.formatters["Data"](value));
	},
	Float: function(value, docfield, options, doc) {
		// don't allow 0 precision for Floats, hence or'ing with null
		var precision = docfield.precision || cint(frappe.boot.sysdefaults.float_precision) || null;
		if (docfield.options && docfield.options.trim()) {
			// options points to a currency field, but expects precision of float!
			docfield.precision = precision;
			return frappe.form.formatters.Currency(value, docfield, options, doc);

		} else {
			// show 1.000000 as 1
			if (!(options || {}).always_show_decimals && !is_null(value)) {
				var temp = cstr(value).split(".");
				if (temp[1]==undefined || cint(temp[1])===0) {
					precision = 0;
				}
			}

			return frappe.form.formatters._right(
				((value==null || value==="")
					? ""
					: format_number(value, null, precision)), options);
		}
	},
	Int: function(value, docfield, options) {
		return frappe.form.formatters._right(value==null ? "" : cint(value), options)
	},
	Percent: function(value, docfield, options) {
		return frappe.form.formatters._right(flt(value, 2) + "%", options)
	},
	Currency: function(value, docfield, options, doc) {
		var currency = frappe.meta.get_field_currency(docfield, doc);
		return frappe.form.formatters._right((value==null || value==="")
			? "" : format_currency(value, currency, docfield.precision || null), options);
	},
	Check: function(value) {
		if(value) {
			return '';
		} else {
			return '';
		}
	},
	Link: function(value, docfield, options) {
		var doctype = docfield._options || docfield.options;
		if(value && value.match(/^['"].*['"]$/)) {
			return value.replace(/^.(.*).$/, "$1");
		}
		if(options && options.for_print) {
			return value;
		}
		if(!value) {
			return "";
		}
		if(docfield && docfield.link_onclick) {
			return repl('%(value)s',
				{onclick: docfield.link_onclick.replace(/"/g, '"'), value:value});
		} else if(docfield && doctype) {
			return repl('%(label)s', {
				doctype: encodeURIComponent(doctype),
				name: encodeURIComponent(value),
				label: __(options && options.label || value)
			});
		} else {
			return value;
		}
	},
	Date: function(value) {
		if (value) {
			value = dateutil.str_to_user(value);
			// handle invalid date
			if (value==="Invalid date") {
				value = null;
			}
		}

		return value || "";
	},
	Datetime: function(value) {
		return value ? dateutil.str_to_user(dateutil.convert_to_user_tz(value)) : "";
	},
	Text: function(value) {
		if(value) {
			var tags = ["<p", "<div", "<br", "<table"];
			var match = false;

			for(var i=0; i<tags.length; i++) {
				if(value.match(tags[i])) {
					match = true;
					break;
				}
			}

			if(!match) {
				value = replace_newlines(value);
			}
		}

		return frappe.form.formatters.Data(value);
	},
	StarredBy: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= '';
		});
		return html;
	},
	Tag: function(value) {
		var html = "";
		$.each((value || "").split(","), function(i, v) {
			if(v) html+= ''+v +'';
		});
		return html;
	},
	Comment: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v.comment+'';
		});
		return html;
	},
	Assign: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v+'';
		});
		return html;
	},
	SmallText: function(value) {
		return frappe.form.formatters.Text(value);
	},
	TextEditor: function(value) {
		return frappe.form.formatters.Text(value);
	},
	Code: function(value) {
		return "
" + (value==null ? "" : $("
").text(value).html()) + "
"
	},
	WorkflowState: function(value) {
		workflow_state = frappe.get_doc("Workflow State", value);
		if(workflow_state) {
			return repl("\
				 %(value)s", {
					value: value,
					style: workflow_state.style.toLowerCase(),
					icon: workflow_state.icon
				});
		} else {
			return "" + value + "";
		}
	},
	Email: function(value) {
		return $("

").text(value).html();
	}
}

frappe.form.get_formatter = function(fieldtype) {
	if(!fieldtype)
		fieldtype = "Data";
	return frappe.form.formatters[fieldtype.replace(/ /g, "")] || frappe.form.formatters.Data;
}

frappe.format = function(value, df, options, doc) {
	if(!df) df = {"fieldtype":"Data"};
	var fieldtype = df.fieldtype || "Data";

	// format Dynamic Link as a Link
	if(fieldtype==="Dynamic Link") {
		fieldtype = "Link";
		df._options = doc ? doc[df.options] : null;
	}

	formatter = df.formatter || frappe.form.get_formatter(fieldtype);

	var formatted = formatter(value, df, options, doc);

	if (typeof formatted == "string")
		formatted = frappe.utils.remove_script_and_style(formatted);

	return formatted;
}

frappe.get_format_helper = function(doc) {
	var helper = {
		get_formatted: function(fieldname) {
			var df = frappe.meta.get_docfield(doc.doctype, fieldname);
			if(!df) { console.log("fieldname not found: " + fieldname); };
			return frappe.format(doc[fieldname], df, {inline:1}, doc);
		}
	};
	$.extend(helper, doc);
	return helper;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Francisco Salavert (SGL-CIPF)
 * Copyright (c) 2014 Alejandro Alemán (SGL-CIPF)
 * Copyright (c) 2014 Ignacio Medina (EBI-EMBL)
 *
 * This file is part of JSorolla.
 *
 * JSorolla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * JSorolla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JSorolla. If not, see <http://www.gnu.org/licenses/>.
 */
function EvaVariantPopulationStatsPanel(args) {
    _.extend(this, Backbone.Events);
    this.id = Utils.genId("VariantPopulationPanel");

    this.target;
    this.title = "Stats";
    this.height = 500;
    this.autoRender = true;
    this.statsTpl = new Ext.XTemplate(
        '
' +
            '
' +
            'Minor Allele Frequency:	' +
            '{maf} ({mafAllele})	' +
            '
',
        '
' +
            'Minor Genotype Frequency:	' +
            '{mgf} ({mgfAllele})	' +
            '
',
        '
' +
            'Mendelian Errors:	' +
            '{mendelianErrors}	' +
            '
',
        '
' +
            'Missing Alleles:	' +
            '{missingAlleles}	' +
            '
',
        '
' +
            'Missing Genotypes:	' +
            '{missingGenotypes}	' +
            '
',
        '
'
    );

    _.extend(this, args);

    this.on(this.handlers);

    this.rendered = false;

    if (this.autoRender) {
        this.render();
    }
}

EvaVariantPopulationStatsPanel.prototype = {
    render: function () {
        var _this = this;

        //HTML skel
        this.div = document.createElement('div');
        this.div.setAttribute('id', this.id);

        this.panel = this._createPanel();

    },
    draw: function () {
        this.targetDiv = (this.target instanceof HTMLElement ) ? this.target : document.querySelector('#' + this.target);
        if (!this.targetDiv) {
            console.log('target not found');
            return;
        }

        this.targetDiv.appendChild(this.div);
        this.panel.render(this.div);

    },
    clear: function () {
        this.studiesContainer.removeAll(true);
    },
    load: function (data,params) {
        var _this = this;
        this.clear();

        var panels = [];

        var availableStudies = ['301','8616'];

        for (var key in data) {
            console.log(data)
            var study = data[key];
            if(params.species == 'hsapiens_grch37'){
                if(_.indexOf(availableStudies, study.studyId) > -1){
                    var studyPanel = this._createPopulationGridPanel(study,params);
                }
            }else{
                var studyPanel = this._createPopulationGridPanel(study,params);
            }

            panels.push(studyPanel);

        }

        this.studiesContainer.add(panels);
    },
    _createPanel: function () {
        this.studiesContainer = Ext.create('Ext.container.Container', {
            layout: {
                type: 'accordion',
                titleCollapse: true,
//                fill: false,
                multi: true
            }

        });

        var panel = Ext.create('Ext.container.Container', {
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            overflowY: true,
            overflowX: true,
            padding: 10,
            items: [
                {
                    xtype: 'box',
                    id:'populationStats',
                    cls: 'ocb-header-4',
                    html: '
Population Statistics
',
                    margin: '5 0 10 10'
                },
                this.studiesContainer
            ],
            height: this.height
        });
        return panel;
    },
    _createPopulationGridPanel: function (data,params) {
        var _this = this;

        var populationData = [];
        _.each(_.keys(data.cohortStats), function(key){
            console.log(this[key])
            var tempObj =  _.extend(this[key], {id:key})
            populationData.push(tempObj);

        },data.cohortStats);

        if(params.species == 'hsapiens_grch37'){
            Ext.getCmp('populationStats').update('
Population Statistics

Population frequencies from 1000 Genomes
')
        }else{
            Ext.getCmp('populationStats').update('
Population Statistics
')
        }

        //TO BE REMOVED
        var study_title;
        var projectList = '';
        EvaManager.get({
            category: 'meta/studies',
            resource: 'list',
            params:{species:params.species},
            async: false,
//            params:{species:params.species},
            success: function (response) {
                try {
                    projectList = response.response[0].result;
//                    console.log(projectList)
                } catch (e) {
                    console.log(e);
                }
            }
        });

        if(projectList){
            for (var i = 0; i < projectList.length; i++) {
                if (projectList[i].studyId === data.studyId) {
                    study_title = ''+projectList[i].studyName+' ('+ projectList[i].studyId +')';
                }
            }
        }else{
            study_title = ''+data.studyId+'';
        }

        var populationStatsColumns = {
            items:[
                {
                    text: "Population",
                    dataIndex: "id",
                    flex: 0.4
                },
                {
                    text: "Minor Allele Frequency",
                    dataIndex: "maf",
                    xtype: "templatecolumn",
//                    tpl: '<tpl if="maf == -1 || maf == 0">NA <tpl else>{maf:number( "0.000" )} </tpl>',
                    tpl: '<tpl if="maf == -1">NA <tpl else>{maf:number( "0.000" )} </tpl>',
                    flex: 0.75
                },
                {
                    text: "MAF Allele",
                    dataIndex: "mafAllele",
                    xtype: "templatecolumn",
//                    tpl: '<tpl if="mafAllele">{mafAllele} <tpl else>NA</tpl>',
                    tpl: '<tpl if="mafAllele">{mafAllele} <tpl else>-</tpl>',
                    flex: 0.5
                },
                {
                    text: "Mendelian Errors",
                    dataIndex: "mendelianErrors",
                    xtype: "templatecolumn",
                    tpl:'<tpl if="mendelianErrors == -1">NA <tpl else>{mendelianErrors}</tpl>',
                    flex: 0.5
                },
                {
                    text: "Missing Alleles",
                    dataIndex: "missingAlleles",
                    xtype: "templatecolumn",
                    tpl:'<tpl if="missingAlleles == -1">NA <tpl else>{missingAlleles}</tpl>',
                    flex: 0.6
                },
                {
                    text: "Missing Genotypes",
                    dataIndex: "missingGenotypes",
                    xtype: "templatecolumn",
                    tpl:'<tpl if="missingGenotypes == -1">NA <tpl else>{missingGenotypes}</tpl>',
                    flex: 0.7
                },
//                {
//                    text: "Genotypes Count",
//                    dataIndex: "genotypesCount",
//                    tpl:'<tpl if="missingGenotypes == -1">NA <tpl else>{missingGenotypes}</tpl>',
//                    flex: 1
//                }
            ],
            defaults: {
                align:'center' ,
                sortable : true
            }
        };

        console.log(populationData)

        var store = Ext.create("Ext.data.Store", {
            //storeId: "GenotypeStore",
            pageSize: 10,
            fields: [
                {name: "altAllele", type: "string" },
                {name: "altAlleleCount", type: "string"}
            ],
            data: populationData,
            proxy: {
                    type: 'memory'
            },
            sorters:
            {
                property: 'id',
                direction: 'ASC'
            }
        });

        var plugins =  [{
            ptype: 'rowexpander',
            rowBodyTpl : new Ext.XTemplate(),
        }];

        var grid = Ext.create('Ext.grid.Panel', {
            store: store,
            loadMask: true,
            width: 900,
            height: 600,
            cls:'genotype-grid',
            margin: 20,
            viewConfig: {
                emptyText: 'No records to display',
                enableTextSelection: true,
                deferEmptyText:false
            },
            columns: populationStatsColumns,
            plugins:plugins

        });

        grid.view.on('expandbody', function(rowNode, record, body, rowIndex){

            var genotypesCount = record.data.genotypesCount;
            var divID = 'population-stats-grid-'+record.data.id;
            if(!_.isEmpty(genotypesCount)){
                var divID = 'population-stats-grid-'+record.data.id;
                body.innerHTML = '

';
                var genotypesCountArray=[];
                _.each(_.keys(genotypesCount), function(key){
                    genotypesCountArray.push([key,  this[key]]);

                },genotypesCount);
                var genotypesCountChartData = {id:divID,title:'Genotype Count',chartData:genotypesCountArray};
                _this._drawChart(genotypesCountChartData);
            }else{
                body.innerHTML = '
No Genotypes Count available
';
            }

        });

        var studyPanel = Ext.create('Ext.panel.Panel', {
            header:{
                titlePosition:1
            },
            title: study_title,
            border: false,
            layout: {
                type: 'vbox',
                align: 'fit'
            },
            overflowX:true,
            items: [grid]
        });

        return studyPanel;
    },
    _getGenotypeCount: function (gc) {
        var res = [];
        for (var key in gc) {
            res.push({
                genotype: key,
                count: gc[key]
            })
        }
        return res;
    },
    _drawChart:function(data){
        var _this = this;
        var height = 290;
        var width = 250;
        var id = '#'+data.id;
        var render_id = document.querySelector(id);
        var dataArray  = data.chartData;
        var title = data.title;

        $(function () {
            Highcharts.setOptions({
                colors: ['#207A7A', '#2BA32B','#2E4988','#54BDBD', '#5DD15D','#6380C4', '#70BDBD', '#7CD17C','#7D92C4','#295C5C', '#377A37','#344366','#0A4F4F', '#0E6A0E','#0F2559' ],
                chart: {
                    style: {
                        fontFamily: 'sans-serif;'
                    }
                }
            });
            $(render_id).highcharts({
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    height: height,
//                    width: width,
                    marginLeft:50,
                    marginTop:50

                },
                legend: {
                    enabled: true,
//                    width: 50,
                    margin: 0,
                    labelFormatter: function() {
                        return '
' + this.name + '('+ this.y + ')
';
                    },
                    layout:'horizontal',
                    useHTML:true,
                    align:'center'

                },
                title: {
                    text: title,
                    style: {
//                                    display: 'none'
                    },
                    align: 'center'
                },
                tooltip: {
                    pointFormat: '{point.y}'
    //                                pointFormat: '{series.name}: {point.percentage:.1f}%'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [{
                    type: 'pie',
                    name: 'Studies by '+title,
                    data: dataArray
                }],
                credits: {
                    enabled: false
                }
            });

        });

    }
};

String.prototype.escapeHTML = function () {
    return(
        this.replace(/>/g,'>').
            replace(/</g,'<').
            replace(/"/g,'"')
        );
};

<commit_msg>population statistics tab updated<commit_after>/*
 * Copyright (c) 2014 Francisco Salavert (SGL-CIPF)
 * Copyright (c) 2014 Alejandro Alemán (SGL-CIPF)
 * Copyright (c) 2014 Ignacio Medina (EBI-EMBL)
 *
 * This file is part of JSorolla.
 *
 * JSorolla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * JSorolla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JSorolla. If not, see <http://www.gnu.org/licenses/>.
 */
function EvaVariantPopulationStatsPanel(args) {
    _.extend(this, Backbone.Events);
    this.id = Utils.genId("VariantPopulationPanel");

    this.target;
    this.title = "Stats";
    this.height = 500;
    this.autoRender = true;
    this.statsTpl = new Ext.XTemplate(
        '
' +
            '
' +
            'Minor Allele Frequency:	' +
            '{maf} ({mafAllele})	' +
            '
',
        '
' +
            'Minor Genotype Frequency:	' +
            '{mgf} ({mgfAllele})	' +
            '
',
        '
' +
            'Mendelian Errors:	' +
            '{mendelianErrors}	' +
            '
',
        '
' +
            'Missing Alleles:	' +
            '{missingAlleles}	' +
            '
',
        '
' +
            'Missing Genotypes:	' +
            '{missingGenotypes}	' +
            '
',
        '
'
    );

    _.extend(this, args);

    this.on(this.handlers);

    this.rendered = false;

    if (this.autoRender) {
        this.render();
    }
}

EvaVariantPopulationStatsPanel.prototype = {
    render: function () {
        var _this = this;

        //HTML skel
        this.div = document.createElement('div');
        this.div.setAttribute('id', this.id);

        this.panel = this._createPanel();

    },
    draw: function () {
        this.targetDiv = (this.target instanceof HTMLElement ) ? this.target : document.querySelector('#' + this.target);
        if (!this.targetDiv) {
            console.log('target not found');
            return;
        }

        this.targetDiv.appendChild(this.div);
        this.panel.render(this.div);

    },
    clear: function () {
        this.studiesContainer.removeAll(true);
    },
    load: function (data,params) {
        var _this = this;
        this.clear();

        var panels = [];

        var availableStudies = ['301','8616'];

        for (var key in data) {
            console.log(data)
            var study = data[key];
            if(params.species == 'hsapiens_grch37'){
                if(_.indexOf(availableStudies, study.studyId) > -1){
                    var studyPanel = this._createPopulationGridPanel(study,params);
                }
            }else{
                var studyPanel = this._createPopulationGridPanel(study,params);
            }

            panels.push(studyPanel);

        }

        this.studiesContainer.add(panels);
    },
    _createPanel: function () {
        this.studiesContainer = Ext.create('Ext.container.Container', {
            layout: {
                type: 'accordion',
                titleCollapse: true,
//                fill: false,
                multi: true
            }

        });

        var panel = Ext.create('Ext.container.Container', {
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            overflowY: true,
            overflowX: true,
            padding: 10,
            items: [
                {
                    xtype: 'box',
                    id:'populationStats',
                    cls: 'ocb-header-4',
                    html: '
Population Statistics
',
                    margin: '5 0 10 10'
                },
                this.studiesContainer
            ],
            height: this.height
        });
        return panel;
    },
    _createPopulationGridPanel: function (data,params) {
        var _this = this;

        var populationData = [];
        _.each(_.keys(data.cohortStats), function(key){
            console.log(this[key])
            var tempObj =  _.extend(this[key], {id:key})
            populationData.push(tempObj);

        },data.cohortStats);

        if(params.species == 'hsapiens_grch37'){
            Ext.getCmp('populationStats').update('
Population Statistics

Population frequencies from 1000 Genomes
')
        }else{
            Ext.getCmp('populationStats').update('
Population Statistics
')
        }

        //TO BE REMOVED
        var study_title;
        var projectList = '';
        EvaManager.get({
            category: 'meta/studies',
            resource: 'list',
            params:{species:params.species},
            async: false,
//            params:{species:params.species},
            success: function (response) {
                try {
                    projectList = response.response[0].result;
//                    console.log(projectList)
                } catch (e) {
                    console.log(e);
                }
            }
        });

        if(projectList){
            for (var i = 0; i < projectList.length; i++) {
                if (projectList[i].studyId === data.studyId) {
                    study_title = ''+projectList[i].studyName+' ('+ projectList[i].studyId +')';
                }
            }
        }else{
            study_title = ''+data.studyId+'';
        }

        var populationStatsColumns = {
            items:[
                {
                    text: "Population",
                    dataIndex: "id",
                    flex: 0.4
                },
                {
                    text: "Minor Allele Frequency",
                    dataIndex: "maf",
                    xtype: "templatecolumn",
//                    tpl: '<tpl if="maf == -1 || maf == 0">NA <tpl else>{maf:number( "0.000" )} </tpl>',
                    tpl: '<tpl if="maf == -1">NA <tpl else>{maf:number( "0.000" )} </tpl>',
                    flex: 0.75
                },
                {
                    text: "MAF Allele",
                    dataIndex: "mafAllele",
                    xtype: "templatecolumn",
//                    tpl: '<tpl if="mafAllele">{mafAllele} <tpl else>NA</tpl>',
                    tpl: '<tpl if="mafAllele">{mafAllele} <tpl else>-</tpl>',
                    flex: 0.5
                },
                {
                    text: "Mendelian Errors",
                    dataIndex: "mendelianErrors",
                    xtype: "templatecolumn",
                    tpl:'<tpl if="mendelianErrors == -1">NA <tpl else>{mendelianErrors}</tpl>',
                    flex: 0.5
                },
                {
                    text: "Missing Alleles",
                    dataIndex: "missingAlleles",
                    xtype: "templatecolumn",
                    tpl:'<tpl if="missingAlleles == -1">NA <tpl else>{missingAlleles}</tpl>',
                    flex: 0.6
                },
                {
                    text: "Missing Genotypes",
                    dataIndex: "missingGenotypes",
                    xtype: "templatecolumn",
                    tpl:'<tpl if="missingGenotypes == -1">NA <tpl else>{missingGenotypes}</tpl>',
                    flex: 0.7
                },
//                {
//                    text: "Genotypes Count",
//                    dataIndex: "genotypesCount",
//                    tpl:'<tpl if="missingGenotypes == -1">NA <tpl else>{missingGenotypes}</tpl>',
//                    flex: 1
//                }
            ],
            defaults: {
                align:'center' ,
                sortable : true
            }
        };

        console.log(populationData)

        var store = Ext.create("Ext.data.Store", {
            //storeId: "GenotypeStore",
            pageSize: 10,
            fields: [
                {name: "altAllele", type: "string" },
                {name: "altAlleleCount", type: "string"}
            ],
            data: populationData,
            proxy: {
                    type: 'memory'
            },
            sorters:
            {
                property: 'id',
                direction: 'ASC'
            }
        });

        var plugins =  [{
            ptype: 'rowexpander',
            rowBodyTpl : new Ext.XTemplate(),
        }];

        var grid = Ext.create('Ext.grid.Panel', {
            store: store,
            loadMask: true,
            width: 900,
            height: 600,
            cls:'genotype-grid',
            margin: 20,
            viewConfig: {
                emptyText: 'No records to display',
                enableTextSelection: true,
                deferEmptyText:false
            },
            columns: populationStatsColumns,
            plugins:plugins

        });

        grid.view.on('expandbody', function(rowNode, record, body, rowIndex){

            var genotypesCount = record.data.genotypesCount;
            var divID = 'population-stats-grid-'+record.data.id;
            if(!_.isEmpty(genotypesCount)){
                var divID = 'population-stats-grid-'+record.data.id;
                body.innerHTML = '

';
                var genotypesCountArray=[];
                _.each(_.keys(genotypesCount), function(key){
                    genotypesCountArray.push([key,  this[key]]);

                },genotypesCount);
                var genotypesCountChartData = {id:divID,title:'Genotype Count',chartData:genotypesCountArray};
                _this._drawChart(genotypesCountChartData);
            }else{
                body.innerHTML = '
No Genotypes Count available
';
            }

        });

        var studyPanel = Ext.create('Ext.panel.Panel', {
            header:{
                titlePosition:1
            },
            title: study_title,
            border: false,
            layout: {
                type: 'vbox',
                align: 'fit'
            },
            overflowX:true,
            items: [grid]
        });

        return studyPanel;
    },
    _getGenotypeCount: function (gc) {
        var res = [];
        for (var key in gc) {
            res.push({
                genotype: key,
                count: gc[key]
            })
        }
        return res;
    },
    _drawChart:function(data){
        var _this = this;
        var height = 290;
        var width = 250;
        var id = '#'+data.id;
        var render_id = document.querySelector(id);
        var dataArray  = data.chartData;
        var title = data.title;

        $(function () {
            Highcharts.setOptions({
                colors: ['#207A7A', '#2BA32B','#2E4988','#54BDBD', '#5DD15D','#6380C4', '#70BDBD', '#7CD17C','#7D92C4','#295C5C', '#377A37','#344366','#0A4F4F', '#0E6A0E','#0F2559' ],
                chart: {
                    style: {
                        fontFamily: 'sans-serif;'
                    }
                }
            });
            $(render_id).highcharts({
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    height: height,
//                    width: width,
                    marginLeft:50,
                    marginTop:50

                },
                legend: {
                    enabled: true,
//                    width: 50,
                    margin: 0,
                    labelFormatter: function() {
                        return '
' + this.name + '('+ this.y + ')
';
                    },
                    layout:'horizontal',
                    useHTML:true,
                    align:'center'

                },
                title: {
                    text: title,
                    style: {
//                                    display: 'none'
                    },
                    align: 'center'
                },
                tooltip: {
                    pointFormat: '{point.y}'
    //                                pointFormat: '{series.name}: {point.percentage:.1f}%'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [{
                    type: 'pie',
                    name: 'Studies by '+title,
                    data: dataArray
                }],
                credits: {
                    enabled: false
                }
            });

        });

    }
};

String.prototype.escapeHTML = function () {
    return(
        this.replace(/>/g,'>').
            replace(/</g,'<').
            replace(/"/g,'"')
        );
};

<|endoftext|>


<commit_before>
/*
# the following file aims to define the idea of a "resistor combo" calculator
# in other words, a little utility program to calculate the "resistor combos" for a specific value,
# based on a set of resistor values & some parameters on the maximum number of resistors to be used in a said-"combo"
# also, the "resistor" objets 'll hold their value in Ohms ( decimals ) as well as their value in string ( k,m, ... Ohms )
# in other words, the decimal values are deduced from values in string, adjusting themselves depending on the unit presence

# Followds, the text from my original notes ( as a sort-of-a-reminder ;p )

*/

// rought concept
var resistor = function(resistorValue){
  if( ! isNaN(resistorValue) ){
    console.log("decimal !");
    this.resValue = resistorValue;
    this.resStr = resistorValue.toString(); // we could also have added "Ω" at the end
  }
  else {
    // get string stuff until first char: if it's Ohm, strip it, else if maj/min supported char, deduce value
    console.log("string !");
    this.resValue = ".."; // do what the above comment say, & finally just use only the unit char OR add to it the "Ω" at the end
    this.resStr = resistorValue;
  }
}

// get units & value from resistor values passed as trings ( may or not contain the ending "Ohm" symbol and/or n,µ,.. )
getUnityIdx = function(valueStr){
  var valueStrArr = valueStr.split('');
  for( var i=0; i<= valueStrArr.length; i++){
    if (isNaN(parseInt(valueStrArr[i]))) {
      idx = i;
      return idx;
      break;
    }
  }
}

// get value & unity
// strip "Ω" if present at the end of the unity ( not likely, but who knows ? ^^ ), as it's implied
if (unity.substr(-1) === "Ω" ) unity = unity.substr(0, unity.length-1)

// if unity is still !== '', we have to map the char passed to the corresponding exp in the following chart & update resValue
/*
n/nΩ --> NanoOhm  ==> 10exp-9 ==> 0,000.000.001
µ/µΩ --> MicroOhm ==> 10exp-6 ==> 0,000.001
m/mΩ --> MilliOhm ==> 10exp-3 ==> 0,001
/Ω   --> Ohm      ==> 10exp0  ==> 1
k/kΩ --> KiloOhm  ==> 10exp3 ==> 1.000
M/MΩ --> MegaOhm  ==> 10exp6 ==> 1.000.000
G/GΩ --> GigaOhm  ==> 10exp9 ==> 1.000.000.000
T/TΩ --> TeraOhm  ==> 10exp12 ==> 1.000.000.000.000
*/
// array(s) to match the unity against ( & use 'Math.pow(10, arr[idx][1]) * resValue' to deduce actual value of resistor )
var exps = [
  ['n', -9 ],
  ['µ', -6 ],
  ['m', -3 ],
  ['k',  3 ],
  ['M',  6 ],
  ['G',  9 ],
  ['T', 12 ],
];

// get a number udpdated if the unity passed is present in the exps array, in other words, "supported"
applyExp = function(theValue, theUnity){
  if( theUnity !== ''){
    // loop over the exps array & try to see if unity matches one of the array's[0] items
    // if so, update the resValue using the corresponding array's[1] item
    for( var i=0; i<= exps.length; i++){
      if (exps[i][0] === theUnity) {
        return theValue * Math.pow(10, exps[i][1]);
        break;
      }
    }
  }
  return theValue;
}

// get string value ( in other words, the one passed to the function -> it's the one we'll use to display stuff ;p )
var unity = valueStr.substr( getUnityIdx(valueStr) ); // we could also add the "Ohm sign to it"

// get actual value & updating it according to exps if unity is specified
if( unity !== '') var actualValue = applyExp( Number( valueStr.substr(0, getUnityIdx(valueStr) ) ), unity);
else var actualValue = Number( valueStr.substr(0, getUnityIdx(valueStr) ) );

// array holding all the values of all the resistors I own ( mostly mainly available resistor values )
resistors = [];

// array holding all the resistor Objects gotten from the above reistor array's values
// 'll be used to deduce the possible configs when providing the tool a request ( aka, get the optimal combo for ( .. ) )
resistorsStack = [];
<commit_msg>Update resistorsCombo.js<commit_after>
/*
# the following file aims to define the idea of a "resistor combo" calculator
# in other words, a little utility program to calculate the "resistor combos" for a specific value,
# based on a set of resistor values & some parameters on the maximum number of resistors to be used in a said-"combo"
# also, the "resistor" objets 'll hold their value in Ohms ( decimals ) as well as their value in string ( k,m, ... Ohms )
# in other words, the decimal values are deduced from values in string, adjusting themselves depending on the unit presence

# Followds, the text from my original notes ( as a sort-of-a-reminder ;p )

*/

// rought concept
var resistor = function(resistorValue){
  if( ! isNaN(resistorValue) ){
    console.log("decimal !");
    this.resValue = resistorValue;
    this.resStr = resistorValue.toString(); // we could also have added "Ω" at the end
  }
  else {
    // get string stuff until first char: if it's Ohm, strip it, else if maj/min supported char, deduce value
    console.log("string !");
    this.resValue = ".."; // do what the above comment say, & finally just use only the unit char OR add to it the "Ω" at the end
    this.resStr = resistorValue;
  }
}

// get units & value from resistor values passed as trings ( may or not contain the ending "Ohm" symbol and/or n,µ,.. )
getUnityIdx = function(valueStr){
  var valueStrArr = valueStr.split('');
  for( var i=0; i<= valueStrArr.length; i++){
    if (isNaN(parseInt(valueStrArr[i]))) {
      idx = i;
      return idx;
      break;
    }
  }
}

// get value & unity
// strip "Ω" if present at the end of the unity ( not likely, but who knows ? ^^ ), as it's implied
if (unity.substr(-1) === "Ω" ) unity = unity.substr(0, unity.length-1)

// if unity is still !== '', we have to map the char passed to the corresponding exp in the following chart & update resValue
/*
n/nΩ --> NanoOhm  ==> 10exp-9 ==> 0,000.000.001
µ/µΩ --> MicroOhm ==> 10exp-6 ==> 0,000.001
m/mΩ --> MilliOhm ==> 10exp-3 ==> 0,001
/Ω   --> Ohm      ==> 10exp0  ==> 1
k/kΩ --> KiloOhm  ==> 10exp3 ==> 1.000
M/MΩ --> MegaOhm  ==> 10exp6 ==> 1.000.000
G/GΩ --> GigaOhm  ==> 10exp9 ==> 1.000.000.000
T/TΩ --> TeraOhm  ==> 10exp12 ==> 1.000.000.000.000
*/
// array(s) to match the unity against ( & use 'Math.pow(10, arr[idx][1]) * resValue' to deduce actual value of resistor )
var exps = [
  ['n', -9 ],
  ['µ', -6 ],
  ['m', -3 ],
  ['k',  3 ],
  ['M',  6 ],
  ['G',  9 ],
  ['T', 12 ],
];

// get a number udpdated if the unity passed is present in the exps array, in other words, "supported"
applyExp = function(theValue, theUnity){
  if( theUnity !== ''){
    // loop over the exps array & try to see if unity matches one of the array's[0] items
    // if so, update the resValue using the corresponding array's[1] item
    for( var i=0; i<= exps.length; i++){
      if (exps[i][0] === theUnity) {
        return theValue * Math.pow(10, exps[i][1]);
        break;
      }
    }
  }
  return theValue;
}

// get string value ( in other words, the one passed to the function -> it's the one we'll use to display stuff ;p )
var unity = valueStr.substr( getUnityIdx(valueStr) ); // we could also add the "Ohm sign to it"

// get actual value & updating it according to exps if unity is specified
if( unity !== '') var actualValue = applyExp( Number( valueStr.substr(0, getUnityIdx(valueStr) ) ), unity);
else var actualValue = Number( valueStr.substr(0, getUnityIdx(valueStr) ) );

// array holding all the values of all the resistors I own ( mostly mainly available resistor values )
resistors = [];

// array holding all the resistor Objects gotten from the above reistor array's values
// 'll be used to deduce the possible configs when providing the tool a request ( aka, get the optimal combo for ( .. ) )
resistorsStack = [];

/* == R: NOT MY CODE !!! ==
 the following is the best I could find to study a possible [ yet not exactly to my likings ..] implm
 of the knapsack-like problematic I'm facing ..
 for the record, I have 2 solutions-that-won't-be-working-I-guess on my own ^^
*/
var source = [0., 2.5, 3.5, 4.7];
function get_combinations(val)
{
    var result = [];

    while (val >= source[0])
    {
        for (var i = source.length - 1; i >= 0; i--)
        {
            if (source[i] <= val)
            {
                val = val - source[i];
                result.push(source[i]);
                break;
            }
        }
    }

    return result;
}
console.log( get_combinations(7).join(' + ') );

<|endoftext|>


<commit_before>export default ['$compile', 'config', '$rootScope', 'hs.layermanager.service', 'hs.map.service', 'hs.utils.service', '$timeout','hs.layerEditor.sublayerService', 'hs.layout.service', function ($compile, config, $rootScope, LayMan, hsMap, utils, $timeout,subLayerService, layoutService) {
    return {
        template: require('components/layermanager/partials/layerlist.html'),
        controller: ['$scope', function ($scope) {
            $scope.toggleSublayersVisibility = function (layer) {
                if (LayMan.currentLayer == null) {
                    Object.keys(subLayerService.checkedSubLayers).forEach(function (key) {
                        subLayerService.checkedSubLayers[key] = layer.visible;
                    })
                  }
                else {
                    if (subLayerService.hasSubLayers()) {
                        Object.keys(subLayerService.checkedSubLayers).forEach(function (key) {
                            subLayerService.checkedSubLayers[key] = LayMan.currentLayer.visible;
                        })
                        if (Object.keys(subLayerService.withChildren).length === 0) {
                            return
                        }
                        else {
                            Object.keys(subLayerService.withChildren).forEach(function (key) {
                                subLayerService.withChildren[key] = LayMan.currentLayer.visible;
                            })
                    }
                };
                }
        }
        }],
        compile: function compile(element) {
            var contents = element.contents().remove();
            var contentsLinker;

            return function (scope, iElement) {

                /**
                * @ngdoc property
                * @name hs.layermanager.layerlistDirective#layer_titles
                * @public
                * @type {Array}
                * @description List of layer titles for current folder structure level. List is always ordered in order which should be used in template.
                */
                scope.layer_titles = [];

                /**
                * @ngdoc property
                * @name hs.layermanager.layerlistDirective#obj
                * @public
                * @type {Object}
                * @description Container for folder object of current folder instance. Either full folders object or its subset based on hierarchy place of directive
                */
                if (scope.value == null) {
                    scope.obj = scope.data.folders;
                } else {
                    scope.obj = scope.value;
                }

                /**
                 * @ngdoc method
                 * @name hs.layermanager.layerlistDirective#filterLayers
                 * @private
                 * @description Filters layers, and returns only the ones belonging to folder hiearchy level of directive
                 */
                function filterLayers() {
                    var tmp = [];

                    angular.forEach(scope.data.layers, function (layer) {
                        if (layer.layer.get('path') == scope.obj.hsl_path || ((angular.isUndefined(layer.layer.get('path')) || layer.layer.get('path') == '') && scope.obj.hsl_path == '')) {
                            tmp.push(layer);
                        }
                    })
                    return tmp;
                }

                /**
                * @ngdoc property
                * @name hs.layermanager.layerlistDirective#filtered_layers
                * @public
                * @type {Array}
                * @description List of layers which belong to folder hierarchy level of directive instance
                */
                scope.filtered_layers = filterLayers();

                /**
                 * @ngdoc method
                 * @name hs.layermanager.layerlistDirective#filtered_layers
                 * @public
                 * @description Generate list of layer titles out of {@link hs.layermanager.layerlistDirective#filtered_layers filtered_layers}. Complex layer objects cant be used because DragDropList functionality can handle only simple structures.
                 */
                scope.generateLayerTitlesArray = function () {
                    scope.layer_titles = [];
                    for (var i = 0; i < scope.filtered_layers.length; i++) {
                        scope.layer_titles.push(scope.filtered_layers[i].title);
                    }
                }

                scope.$on('layermanager.updated', sortLayersByPosition);

                scope.order = function () {
                    return config.layer_order || '-position';
                }

                /**
                 * @ngdoc method
                 * @name hs.layermanager.layerlistDirective#sortLayersByPosition
                 * @private
                 * @description Sort layers by computed position
                 */
                function sortLayersByPosition() {
                    scope.filtered_layers = filterLayers();
                    var minus = scope.order().indexOf('-') == 0;
                    var attribute = scope.order().replaceAll('-', '');
                    scope.filtered_layers.sort(function (a, b) {
                        var a = a.layer.get(attribute);
                        var b = b.layer.get(attribute);
                        var tmp = (a < b ? -1 : (a > b ? 1 : 0)) * (minus ? -1 : 1);
                        return tmp;
                    });
                    scope.generateLayerTitlesArray();
                }

                sortLayersByPosition();

                if (angular.isUndefined(contentsLinker)) {
                    contentsLinker = $compile(contents);
                }

                contentsLinker(scope, function (clonedElement) {
                    iElement.append(clonedElement);
                });

                /**
                 * @ngdoc method
                 * @name hs.layermanager.layerlistDirective#dragged
                 * @public
                 * @description Callback for dragged event so event can be injected with correct layer titles list needed for correct recalculation.
                 */
                scope.dragged = function (event, index, item, type, external) {
                    scope.draggedCont(event, index, item, type, external, scope.layer_titles);
                }

                /**
                 * @function dragged
                 * @memberOf hs.layermanager-layerlist-directive
                 * @param {unknow} event
                 * @param {unknown} index
                 * @param {unknown} item
                 * @param {unknown} type
                 * @param {unknown} external
                 * @param {Array} layerTitles Array of layer titles of group in which layer should be moved in other position
                 * @description Callback for dnd-drop event to change layer position in layer manager structure (drag and drop action with layers in layer manager - see https://github.com/marceljuenemann/angular-drag-and-drop-lists for more info about dnd-drop).
                 * This is called from layerlistDirective
                 */
                scope.draggedCont = function (event, index, item, type, external, layerTitles) {
                    if (layerTitles.indexOf(item) < index) index--; //Must take into acount that this item will be removed and list will shift
                    var to_title = layerTitles[index];
                    var to_index = null;
                    var item_index = null;
                    var layers = hsMap.map.getLayers();
                    //Get the position where to drop the item in the map.getLayers list and which item to remove. because we could be working only within a folder so layer_titles is small
                    for (var i = 0; i < layers.getLength(); i++) {
                        if (layers.item(i).get('title') == to_title) to_index = i;
                        if (layers.item(i).get('title') == item) item_index = i;
                        if (index > layerTitles.length) to_index = i + 1; //If dragged after the last item
                    }
                    var layerPanel = layoutService.contentWrapper.querySelector('.hs-layerpanel');
                    var layerNode = document.querySelector('.hs-lm-list')
                        .querySelectorAll('.hs-lm-item');
                    layerNode = layerNode[layerNode.length - 1];
                    utils.insertAfter(layerPanel, layerNode);
                    var item_layer = layers.item(item_index);
                    hsMap.map.getLayers().removeAt(item_index);
                    hsMap.map.getLayers().insertAt(to_index, item_layer);
                    LayMan.updateLayerOrder();
                    let layerDesc = LayMan.getLayerDescriptorForOlLayer(item_layer);
                    $timeout(_ => {
                        layerNode = document.getElementById(layerDesc.idString());
                        utils.insertAfter(layerPanel, layerNode);
                        $rootScope.$broadcast('layermanager.updated'); //Rebuild the folder contents
                    }, 300)
                }
            };
        }
    };
}]<commit_msg>fix visibility toggle of sublayer with children<commit_after>export default ['$compile', 'config', '$rootScope', 'hs.layermanager.service', 'hs.map.service', 'hs.utils.service', '$timeout', 'hs.layerEditor.sublayerService', 'hs.layout.service', function ($compile, config, $rootScope, LayMan, hsMap, utils, $timeout, subLayerService, layoutService) {
  return {
    template: require('components/layermanager/partials/layerlist.html'),
    controller: ['$scope', function ($scope) {
      $scope.toggleSublayersVisibility = function (layer) {
        if (LayMan.currentLayer == null) {
          Object.keys(subLayerService.checkedSubLayers).forEach((key) => {
            subLayerService.checkedSubLayers[key] = layer.visible;
          });
          Object.keys(subLayerService.withChildren).forEach((key) => {
            subLayerService.withChildren[key] = layer.visible;
          });
        } else {
          if (subLayerService.hasSubLayers()) {
            Object.keys(subLayerService.checkedSubLayers).forEach((key) => {
              subLayerService.checkedSubLayers[key] = LayMan.currentLayer.visible;
            });
            if (Object.keys(subLayerService.withChildren).length === 0) {
              return;
            } else {
              Object.keys(subLayerService.withChildren).forEach((key) => {
                subLayerService.withChildren[key] = LayMan.currentLayer.visible;
              });
            }
          }
        }
      };
    }],
    compile: function compile(element) {
      const contents = element.contents().remove();
      let contentsLinker;

      return function (scope, iElement) {

        /**
                * @ngdoc property
                * @name hs.layermanager.layerlistDirective#layer_titles
                * @public
                * @type {Array}
                * @description List of layer titles for current folder structure level. List is always ordered in order which should be used in template.
                */
        scope.layer_titles = [];

        /**
                * @ngdoc property
                * @name hs.layermanager.layerlistDirective#obj
                * @public
                * @type {Object}
                * @description Container for folder object of current folder instance. Either full folders object or its subset based on hierarchy place of directive
                */
        if (scope.value == null) {
          scope.obj = scope.data.folders;
        } else {
          scope.obj = scope.value;
        }

        /**
                 * @ngdoc method
                 * @name hs.layermanager.layerlistDirective#filterLayers
                 * @private
                 * @description Filters layers, and returns only the ones belonging to folder hiearchy level of directive
                 */
        function filterLayers() {
          const tmp = [];

          angular.forEach(scope.data.layers, (layer) => {
            if (layer.layer.get('path') == scope.obj.hsl_path || ((angular.isUndefined(layer.layer.get('path')) || layer.layer.get('path') == '') && scope.obj.hsl_path == '')) {
              tmp.push(layer);
            }
          });
          return tmp;
        }

        /**
                * @ngdoc property
                * @name hs.layermanager.layerlistDirective#filtered_layers
                * @public
                * @type {Array}
                * @description List of layers which belong to folder hierarchy level of directive instance
                */
        scope.filtered_layers = filterLayers();

        /**
                 * @ngdoc method
                 * @name hs.layermanager.layerlistDirective#filtered_layers
                 * @public
                 * @description Generate list of layer titles out of {@link hs.layermanager.layerlistDirective#filtered_layers filtered_layers}. Complex layer objects cant be used because DragDropList functionality can handle only simple structures.
                 */
        scope.generateLayerTitlesArray = function () {
          scope.layer_titles = [];
          for (let i = 0; i < scope.filtered_layers.length; i++) {
            scope.layer_titles.push(scope.filtered_layers[i].title);
          }
        };

        scope.$on('layermanager.updated', sortLayersByPosition);

        scope.order = function () {
          return config.layer_order || '-position';
        };

        /**
                 * @ngdoc method
                 * @name hs.layermanager.layerlistDirective#sortLayersByPosition
                 * @private
                 * @description Sort layers by computed position
                 */
        function sortLayersByPosition() {
          scope.filtered_layers = filterLayers();
          const minus = scope.order().indexOf('-') == 0;
          const attribute = scope.order().replaceAll('-', '');
          scope.filtered_layers.sort((a, b) => {
            var a = a.layer.get(attribute);
            var b = b.layer.get(attribute);
            const tmp = (a < b ? -1 : (a > b ? 1 : 0)) * (minus ? -1 : 1);
            return tmp;
          });
          scope.generateLayerTitlesArray();
        }

        sortLayersByPosition();

        if (angular.isUndefined(contentsLinker)) {
          contentsLinker = $compile(contents);
        }

        contentsLinker(scope, (clonedElement) => {
          iElement.append(clonedElement);
        });

        /**
                 * @ngdoc method
                 * @name hs.layermanager.layerlistDirective#dragged
                 * @public
                 * @description Callback for dragged event so event can be injected with correct layer titles list needed for correct recalculation.
                 */
        scope.dragged = function (event, index, item, type, external) {
          scope.draggedCont(event, index, item, type, external, scope.layer_titles);
        };

        /**
                 * @function dragged
                 * @memberOf hs.layermanager-layerlist-directive
                 * @param {unknow} event
                 * @param {unknown} index
                 * @param {unknown} item
                 * @param {unknown} type
                 * @param {unknown} external
                 * @param {Array} layerTitles Array of layer titles of group in which layer should be moved in other position
                 * @description Callback for dnd-drop event to change layer position in layer manager structure (drag and drop action with layers in layer manager - see https://github.com/marceljuenemann/angular-drag-and-drop-lists for more info about dnd-drop).
                 * This is called from layerlistDirective
                 */
        scope.draggedCont = function (event, index, item, type, external, layerTitles) {
          if (layerTitles.indexOf(item) < index) {
            index--;
          } //Must take into acount that this item will be removed and list will shift
          const to_title = layerTitles[index];
          let to_index = null;
          let item_index = null;
          const layers = hsMap.map.getLayers();
          //Get the position where to drop the item in the map.getLayers list and which item to remove. because we could be working only within a folder so layer_titles is small
          for (let i = 0; i < layers.getLength(); i++) {
            if (layers.item(i).get('title') == to_title) {
              to_index = i;
            }
            if (layers.item(i).get('title') == item) {
              item_index = i;
            }
            if (index > layerTitles.length) {
              to_index = i + 1;
            } //If dragged after the last item
          }
          const layerPanel = layoutService.contentWrapper.querySelector('.hs-layerpanel');
          let layerNode = document.querySelector('.hs-lm-list')
            .querySelectorAll('.hs-lm-item');
          layerNode = layerNode[layerNode.length - 1];
          utils.insertAfter(layerPanel, layerNode);
          const item_layer = layers.item(item_index);
          hsMap.map.getLayers().removeAt(item_index);
          hsMap.map.getLayers().insertAt(to_index, item_layer);
          LayMan.updateLayerOrder();
          const layerDesc = LayMan.getLayerDescriptorForOlLayer(item_layer);
          $timeout(_ => {
            layerNode = document.getElementById(layerDesc.idString());
            utils.insertAfter(layerPanel, layerNode);
            $rootScope.$broadcast('layermanager.updated'); //Rebuild the folder contents
          }, 300);
        };
      };
    }
  };
}];
<|endoftext|>


<commit_before>module.exports = function (grunt) {
    var pkg = grunt.file.readJSON("package.json");

    grunt.initConfig({
        pkg: pkg,
        assemblyinfo: {
            options: {
                files: ['../Src/Veil.sln'],

                // Standard assembly info
                info: {
                    version: pkg.assemblyVersion,
                    fileVersion: pkg.assemblyVersion
                }
            }
        },
        msbuild: {
            core: {
                src: ['../src/Veil/Veil.csproj'],
                options: {
                    projectConfiguration: 'Release',
                    target: ['Clean', 'Rebuild'],
                    stdout: true,
                    buildParameters: {
                        documentationFile: 'Veil.xml',
                        platform: 'AnyCPU'
                    }
                }
            },
            supersimple: {
                src: ['../src/Veil.SuperSimple/Veil.SuperSimple.csproj'],
                options: {
                    projectConfiguration: 'Release',
                    target: ['Clean', 'Rebuild'],
                    stdout: true,
                    buildParameters: {
                        platform: 'AnyCPU'
                    }
                }
            },
            handlebars: {
                src: ['../src/Veil.Handlebars/Veil.Handlebars.csproj'],
                options: {
                    projectConfiguration: 'Release',
                    target: ['Clean', 'Rebuild'],
                    stdout: true,
                    buildParameters: {
                        platform: 'AnyCPU'
                    }
                }
            },
            nancy: {
                src: ['../src/Nancy.ViewEngines.Veil/Nancy.ViewEngines.Veil.csproj'],
                options: {
                    projectConfiguration: 'Release',
                    target: ['Clean', 'Rebuild'],
                    stdout: true,
                    buildParameters: {
                        platform: 'AnyCPU'
                    }
                }
            }
        },
        clean: {
            dist: {
                src: ["./dist"]
            }
        },
        copy: {
            nuspec: {
                files: [{
                    expand: true,
                    cwd: '../Src/Nuspec/',
                    src: ['*.nuspec'],
                    dest: 'dist/'
                }]
            },
            lib: {
                files: [{
                    expand: true,
                    cwd: '../src/Veil/bin/Release/',
                    src: ['Veil.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil/',
                    src: ['Veil.xml'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.SuperSimple/bin/Release/',
                    src: ['Veil.SuperSimple.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.Handlebars/bin/Release/',
                    src: ['Veil.Handlebars.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Nancy.ViewEngines.Veil/bin/Release/',
                    src: ['Nancy.ViewEngines.Veil.*'],
                    dest: 'dist/lib/net40'
                }]
            }
        },
        nugetpack: {
            core: {
                src: 'dist/Veil.nuspec',
                dest: 'dist/',
                options: {
                    version: pkg.version
                }
            },
            supersimple: {
                src: 'dist/Veil.SuperSimple.nuspec',
                dest: 'dist/',
                options: {
                    version: pkg.version
                }
            },
            handlebars: {
                src: 'dist/Veil.Handlebars.nuspec',
                dest: 'dist/',
                options: {
                    version: pkg.version
                }
            },
            nancy: {
                src: 'dist/Nancy.ViewEngines.Veil.nuspec',
                dest: 'dist/',
                options: {
                    version: pkg.version
                }
            }
        },
        nugetpush: {
            dist: {
                src: 'dist/*.nupkg'
            }
        },
        nugetrestore: {
            restore: {
                src: '../src/**/packages.config',
                dest: '../src/packages/'
            }
        }
    });
    grunt.loadNpmTasks('grunt-nuget');
    grunt.loadNpmTasks('grunt-msbuild');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-dotnet-assembly-info');
    grunt.registerTask("build", ["nugetrestore", "msbuild"])
    grunt.registerTask("default", ["clean", "assemblyinfo", "build", "copy", "nugetpack"]);
    grunt.registerTask("push", ["default", "nugetpush"]);
};<commit_msg>Build benchmark project from build.cmd<commit_after>module.exports = function (grunt) {
    var pkg = grunt.file.readJSON("package.json");

    grunt.initConfig({
        pkg: pkg,
        assemblyinfo: {
            options: {
                files: ['../Src/Veil.sln'],

                // Standard assembly info
                info: {
                    version: pkg.assemblyVersion,
                    fileVersion: pkg.assemblyVersion
                }
            }
        },
        msbuild: {
            core: {
                src: ['../src/Veil/Veil.csproj'],
                options: {
                    projectConfiguration: 'Release',
                    target: ['Clean', 'Rebuild'],
                    stdout: true,
                    buildParameters: {
                        documentationFile: 'Veil.xml',
                        platform: 'AnyCPU'
                    }
                }
            },
            supersimple: {
                src: ['../src/Veil.SuperSimple/Veil.SuperSimple.csproj'],
                options: {
                    projectConfiguration: 'Release',
                    target: ['Clean', 'Rebuild'],
                    stdout: true,
                    buildParameters: {
                        platform: 'AnyCPU'
                    }
                }
            },
            handlebars: {
                src: ['../src/Veil.Handlebars/Veil.Handlebars.csproj'],
                options: {
                    projectConfiguration: 'Release',
                    target: ['Clean', 'Rebuild'],
                    stdout: true,
                    buildParameters: {
                        platform: 'AnyCPU'
                    }
                }
            },
            nancy: {
                src: ['../src/Nancy.ViewEngines.Veil/Nancy.ViewEngines.Veil.csproj'],
                options: {
                    projectConfiguration: 'Release',
                    target: ['Clean', 'Rebuild'],
                    stdout: true,
                    buildParameters: {
                        platform: 'AnyCPU'
                    }
                }
            },
            bench: {
                src: ['../src/Veil.Benchmark/Veil.Benchmark.csproj'],
                options: {
                    projectConfiguration: 'Release',
                    target: ['Clean', 'Rebuild'],
                    stdout: true,
                    buildParameters: {
                        platform: 'AnyCPU'
                    }
                }
            }
        },
        clean: {
            dist: {
                src: ["./dist"]
            }
        },
        copy: {
            nuspec: {
                files: [{
                    expand: true,
                    cwd: '../Src/Nuspec/',
                    src: ['*.nuspec'],
                    dest: 'dist/'
                }]
            },
            lib: {
                files: [{
                    expand: true,
                    cwd: '../src/Veil/bin/Release/',
                    src: ['Veil.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil/',
                    src: ['Veil.xml'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.SuperSimple/bin/Release/',
                    src: ['Veil.SuperSimple.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.Handlebars/bin/Release/',
                    src: ['Veil.Handlebars.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Nancy.ViewEngines.Veil/bin/Release/',
                    src: ['Nancy.ViewEngines.Veil.*'],
                    dest: 'dist/lib/net40'
                }]
            }
        },
        nugetpack: {
            core: {
                src: 'dist/Veil.nuspec',
                dest: 'dist/',
                options: {
                    version: pkg.version
                }
            },
            supersimple: {
                src: 'dist/Veil.SuperSimple.nuspec',
                dest: 'dist/',
                options: {
                    version: pkg.version
                }
            },
            handlebars: {
                src: 'dist/Veil.Handlebars.nuspec',
                dest: 'dist/',
                options: {
                    version: pkg.version
                }
            },
            nancy: {
                src: 'dist/Nancy.ViewEngines.Veil.nuspec',
                dest: 'dist/',
                options: {
                    version: pkg.version
                }
            }
        },
        nugetpush: {
            dist: {
                src: 'dist/*.nupkg'
            }
        },
        nugetrestore: {
            restore: {
                src: '../src/**/packages.config',
                dest: '../src/packages/'
            }
        }
    });
    grunt.loadNpmTasks('grunt-nuget');
    grunt.loadNpmTasks('grunt-msbuild');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-dotnet-assembly-info');
    grunt.registerTask("build", ["nugetrestore", "msbuild"])
    grunt.registerTask("default", ["clean", "assemblyinfo", "build", "copy", "nugetpack"]);
    grunt.registerTask("push", ["default", "nugetpush"]);
};
<|endoftext|>


<commit_before>/*
* The HTML strategy is more involved than the API ones
* because
*/
var utils = require('utilities')
  , strategy = function (content, options) {

      // Where to redirect to on a success event
      var params = this.params
        , type
          // Check the content for an errors hash
        , isFailure = (content.errors && typeof content.errors === 'object')
        , response
        , redirect

          // Default routes to redirect to
        , successRedirects = {
            create: {id: content.id}
          , update: {id: content.id}
          , remove: {}
          }
        , failureRedirects = {
            create: {action: 'add'}
          , update: {action:'edit', id: content.id}
          , remove: {action:'edit', id: content.id}
          }

          /**
          * Select the appropriate redirect URL for the current situation
          * @return {Boolean|Object} - false if no redirect
          *   should occur, a route object if otherwise
          */
        , getRedirect = function () {
            var location = options.location
                // Select the appropriate defaults for the situation
              , redirects = isFailure ? failureRedirects : successRedirects;

            // Don't redirect if the user explicitly set location to false
            if(location === false) {
              return false;
            }
            else {
              // If the user defined a location, use that
              if(location) {
                return location;
              }
              else {
                // Otherwise look it up in the defaults
                return redirects[params.action] || false;
              }
            }
          }

          /**
          * Sets the appropriate flash message for the current situation
          */
        , doFlash = function () {
            var status
                // Default status messages
              , successStatuses = {
                  create: type + ' created'
                , update: type + ' updated'
                , remove: type + ' removed'
                };

            // User can suppress flashes with {silent: true}
            if(options.silent) {
              return;
            }

            // Find an appropriate flash message
            if(options.status) {
              // Use a user provided status if possible

              this.flash.set(isFailure ? 'error' : 'success', options.status);
            }
            else {

              if(isFailure) {
                this.flash.set('error', content.errors);
              }
              else {
                status = successStatuses[params.action.toLowerCase()];

                // Don't set a flash if no message was found
                if(status) {
                  this.flash.set('success', status);
                }
              }
            }
          };

      // Determine if `content` is a model object
      if (typeof content === 'object' && content.type && content.toObj) {

        type = utils.string.getInflection(content.type, 'property', 'singular');

        // Set the flash message
        doFlash.apply(this);

        // Determine if we need to redirect
        redirect = getRedirect.apply(this);

        if (redirect) {
          this.redirect(redirect);
        }
        else {
          // Respond in the style
          // {model: {attr: val, attr2: val...}, params: {}}
          response = {params: params};
          response[type] = content.toObj();
          response[type].id = content.id;

          console.dir(response);

          this.respond.call(this, response, options);
        }
      }
      // Determine if `content` is a collection of models
      else if (content instanceof Array) {

        if (content.length) {
          type = content[0].type;
        }
        // If collection is empty, look for something in the options
        // to tell us what this is
        else {
          type = options.type;
        }

        if (!type) {
          throw new Error(
            'Cannot determine model type from empty array, specify one in opts');
        }

        type = utils.string.getInflection(type, 'property', 'plural');

        response = {params: params};
        response[type] = [];

        for(var i=0, ii=content.length; i<ii; i++) {
          response[type][i] = content[i].toObj();
          response[type][i].id = content[i].id;
        }

        this.respond(response, options);
      }
      else if (content instanceof Error) {
        // Format error for template-rendering
        response = utils.mixin({}, content);
        if (geddy.config.detailedErrors) {
          // 'message' and 'stack' are not enumerable
          response.message = content.message || '';
          response.stack = content.stack || '';
        }
        else {
          response.message = '';
          response.stack = '';
        }
        options.statusCode = content.statusCode || 500;
        this.respond(response, options);
      }
      else {
        throw new Error(
          'respondWith expects either a model, a collection of models, or an Error object');
      }
    };

module.exports = strategy;
<commit_msg>Removed stray debug statement<commit_after>/*
* The HTML strategy is more involved than the API ones
* because
*/
var utils = require('utilities')
  , strategy = function (content, options) {

      // Where to redirect to on a success event
      var params = this.params
        , type
          // Check the content for an errors hash
        , isFailure = (content.errors && typeof content.errors === 'object')
        , response
        , redirect

          // Default routes to redirect to
        , successRedirects = {
            create: {id: content.id}
          , update: {id: content.id}
          , remove: {}
          }
        , failureRedirects = {
            create: {action: 'add'}
          , update: {action:'edit', id: content.id}
          , remove: {action:'edit', id: content.id}
          }

          /**
          * Select the appropriate redirect URL for the current situation
          * @return {Boolean|Object} - false if no redirect
          *   should occur, a route object if otherwise
          */
        , getRedirect = function () {
            var location = options.location
                // Select the appropriate defaults for the situation
              , redirects = isFailure ? failureRedirects : successRedirects;

            // Don't redirect if the user explicitly set location to false
            if(location === false) {
              return false;
            }
            else {
              // If the user defined a location, use that
              if(location) {
                return location;
              }
              else {
                // Otherwise look it up in the defaults
                return redirects[params.action] || false;
              }
            }
          }

          /**
          * Sets the appropriate flash message for the current situation
          */
        , doFlash = function () {
            var status
                // Default status messages
              , successStatuses = {
                  create: type + ' created'
                , update: type + ' updated'
                , remove: type + ' removed'
                };

            // User can suppress flashes with {silent: true}
            if(options.silent) {
              return;
            }

            // Find an appropriate flash message
            if(options.status) {
              // Use a user provided status if possible

              this.flash.set(isFailure ? 'error' : 'success', options.status);
            }
            else {

              if(isFailure) {
                this.flash.set('error', content.errors);
              }
              else {
                status = successStatuses[params.action.toLowerCase()];

                // Don't set a flash if no message was found
                if(status) {
                  this.flash.set('success', status);
                }
              }
            }
          };

      // Determine if `content` is a model object
      if (typeof content === 'object' && content.type && content.toObj) {

        type = utils.string.getInflection(content.type, 'property', 'singular');

        // Set the flash message
        doFlash.apply(this);

        // Determine if we need to redirect
        redirect = getRedirect.apply(this);

        if (redirect) {
          this.redirect(redirect);
        }
        else {
          // Respond in the style
          // {model: {attr: val, attr2: val...}, params: {}}
          response = {params: params};
          response[type] = content.toObj();
          response[type].id = content.id;

          this.respond.call(this, response, options);
        }
      }
      // Determine if `content` is a collection of models
      else if (content instanceof Array) {

        if (content.length) {
          type = content[0].type;
        }
        // If collection is empty, look for something in the options
        // to tell us what this is
        else {
          type = options.type;
        }

        if (!type) {
          throw new Error(
            'Cannot determine model type from empty array, specify one in opts');
        }

        type = utils.string.getInflection(type, 'property', 'plural');

        response = {params: params};
        response[type] = [];

        for(var i=0, ii=content.length; i<ii; i++) {
          response[type][i] = content[i].toObj();
          response[type][i].id = content[i].id;
        }

        this.respond(response, options);
      }
      else if (content instanceof Error) {
        // Format error for template-rendering
        response = utils.mixin({}, content);
        if (geddy.config.detailedErrors) {
          // 'message' and 'stack' are not enumerable
          response.message = content.message || '';
          response.stack = content.stack || '';
        }
        else {
          response.message = '';
          response.stack = '';
        }
        options.statusCode = content.statusCode || 500;
        this.respond(response, options);
      }
      else {
        throw new Error(
          'respondWith expects either a model, a collection of models, or an Error object');
      }
    };

module.exports = strategy;
<|endoftext|>