<commit_before>const config = require('../../../config')
const authorisedRequest = require('../../lib/authorised-request')

function getInteraction (token, interactionId) {
  return authorisedRequest(token, `${config.apiRoot}/interaction/${interactionId}/`)
}

function saveInteraction (token, interaction) {
  const options = {
    body: interaction,
  }

  if (interaction.id && interaction.id.length > 0) {
    // update
    options.url = `${config.apiRoot}/interaction/${interaction.id}/`
    options.method = 'PUT'
  } else {
    options.url = `${config.apiRoot}/interaction/`
    options.method = 'POST'
  }

  return authorisedRequest(token, options)
}

/**
 * Get all the interactions for a contact
 *
 * @param {string} token
 * @param {string} contactId
 * @param {number} page
 * @return {Array[Object]} Returns a promise that resolves to an array of API interaction objects
 */
function getInteractionsForContact (token, contactId, page = 1) {
  const limit = 10
  const offset = limit * (page - 1)
  return authorisedRequest(token, `${config.apiRoot}/v3/interaction?contact_id=${contactId}&limit=${limit}&offset=${offset}`)
}

/**
 * Get interactions for a company
 *
 * @param {string} token
 * @param {string} companyId
 * @param {number} page
 * @return {Promise<Object[]>} Returns a promise that resolves to an array of API interaction objects
 */
function getInteractionsForCompany (token, companyId, page = 1) {
  const limit = 10
  const offset = limit * (page - 1)
  return authorisedRequest(token, `${config.apiRoot}/v3/interaction?company_id=${companyId}&limit=${limit}&offset=${offset}`)
}

function getInteractionsForInvestment (token, investmentId, page) {
  const limit = 10
  const offset = limit * (page - 1)
  return authorisedRequest(token, `${config.apiRoot}/v3/interaction?investment_project_id=${investmentId}&limit=${limit}&offset=${offset}`)
}

function createInvestmentInteraction (token, body) {
  return authorisedRequest(token, {
    url: `${config.apiRoot}/interaction/`,
    method: 'POST',
    body,
  })
}

function updateInvestmentInteraction (token, interactionId, body) {
  return authorisedRequest(token, {
    url: `${config.apiRoot}/interaction/${interactionId}/`,
    method: 'PUT',
    body,
  })
}

module.exports = {
  saveInteraction,
  getInteraction,
  getInteractionsForCompany,
  getInteractionsForContact,
  getInteractionsForInvestment,
  createInvestmentInteraction,
  updateInvestmentInteraction,
}
<commit_msg>Update save interaction endpoint<commit_after>const config = require('../../../config')
const authorisedRequest = require('../../lib/authorised-request')

function getInteraction (token, interactionId) {
  return authorisedRequest(token, `${config.apiRoot}/interaction/${interactionId}/`)
}

function saveInteraction (token, interaction) {
  const options = {
    url: `${config.apiRoot}/v3/interaction`,
    method: 'POST',
    body: interaction,
  }

  if (interaction.id) {
    options.url = `${options.url}/${interaction.id}`
    options.method = 'PATCH'
  }

  return authorisedRequest(token, options)
}

/**
 * Get all the interactions for a contact
 *
 * @param {string} token
 * @param {string} contactId
 * @param {number} page
 * @return {Array[Object]} Returns a promise that resolves to an array of API interaction objects
 */
function getInteractionsForContact (token, contactId, page = 1) {
  const limit = 10
  const offset = limit * (page - 1)
  return authorisedRequest(token, `${config.apiRoot}/v3/interaction?contact_id=${contactId}&limit=${limit}&offset=${offset}`)
}

/**
 * Get interactions for a company
 *
 * @param {string} token
 * @param {string} companyId
 * @param {number} page
 * @return {Promise<Object[]>} Returns a promise that resolves to an array of API interaction objects
 */
function getInteractionsForCompany (token, companyId, page = 1) {
  const limit = 10
  const offset = limit * (page - 1)
  return authorisedRequest(token, `${config.apiRoot}/v3/interaction?company_id=${companyId}&limit=${limit}&offset=${offset}`)
}

function getInteractionsForInvestment (token, investmentId, page) {
  const limit = 10
  const offset = limit * (page - 1)
  return authorisedRequest(token, `${config.apiRoot}/v3/interaction?investment_project_id=${investmentId}&limit=${limit}&offset=${offset}`)
}

function createInvestmentInteraction (token, body) {
  return authorisedRequest(token, {
    url: `${config.apiRoot}/interaction/`,
    method: 'POST',
    body,
  })
}

function updateInvestmentInteraction (token, interactionId, body) {
  return authorisedRequest(token, {
    url: `${config.apiRoot}/interaction/${interactionId}/`,
    method: 'PUT',
    body,
  })
}

module.exports = {
  saveInteraction,
  getInteraction,
  getInteractionsForCompany,
  getInteractionsForContact,
  getInteractionsForInvestment,
  createInvestmentInteraction,
  updateInvestmentInteraction,
}
<|endoftext|>


<commit_before>var asLines = function () {
	this.redraw  = function (d, quantifier) {
		this.callbacks = {};
		var data = d.data;
		d.scale.range ([this.height, 0]); // this comes from the prequantifier and it is used by the quantifier
		var lines = data; //TODO verify if this works with a single line..
		if (data.nests == 2) {
			lines = data.items ();
		}
		var itemsMax = d3.max (lines, function (l) { return l.values.length; });
		var pointDistance = this.width / itemsMax;
		var height = this.height;

		var after = function (container, origAttrs) {
			return function (orets, a) {
				var ys = [], rs = [], origYs = [];
				var attrs = {};
				var cHeight = height;
				var rets = jQuery.extend({}, orets, true);
				for (var i in rets) {
					var origY = rets [i].y;
					rets [i].y = 0;
					rets [i].x = pointDistance * i;
					rets [i].width = pointDistance;
					rets [i].height = cHeight;
					var rect = container.insert ("rect", ":first-child")
						.on ("click", this.createCallback ("click"))
						.on ("mouseover", this.createCallback ("mouseover"));
					this.setElementAttributes (rect, {data: rets [i]["data"], width: pointDistance, height: cHeight, x: rets [i].x - (pointDistance / 2), y: 0, "class": rets [i]["class"]});
					rect.classed ("background", true);

					rets [i].y = origY;
					rets [i].cx = rets [i].x;
					rets [i].cy = rets [i].y;
					origYs.push (rets [i].y);
					if (origAttrs && origAttrs ["stepped"] == true) {
						ys.push ({y: rets [i].y, x: rets [i].x - (pointDistance / 2)});
						ys.push ({y: rets [i].y, x: rets [i].x});
						ys.push ({y: rets [i].y, x: rets [i].x + (pointDistance / 2)});
					} else {
						ys.push ({y: rets [i].y, x: rets [i].x});
					}
					rs.push (rets [i].r);

					var circle = container.insert ("circle")
						.on ("click", this.createCallback ("click"))
						.on ("mouseover", this.createCallback ("mouseover"));
					this.setElementAttributes (circle, {"class": rets [i]["class"], x: rets [i].x, y: rets [i].y});
					if (rets [i].value) {
						var text = container.append("text").text (rets [i].value);
						this.setElementAttributes (text, {"class": rets [i]["class"], x: rets [i].x, y: rets [i].y});
						text.classed ("value", true);
					}
					if (rets [i].label) {
						var text = container.append ("text").text (rets [i].label);
						this.setElementAttributes (text, {"class": rets [i]["class"], x: rets [i].x, y: cHeight});
						text.classed ("label", true);
					}
					if (rets [i].note) {
						var text = container.append ("text").text (rets [i].note);
						this.setElementAttributes (text, {"class": rets [i]["class"], x: rets [i].x, y: 10});
						text.classed ("note", true);

					}
				}
				var x = function (d, e) { return d.x; };
				var y = function (d, e) { return d.y; };
				var line = container.insert ("path");
				var svgLine = d3.svg.line ().x (x).y (y);
				line.attr ("d", function (t) { return svgLine (ys) })
					.on ("click", this.createCallback ("click"));
				this.setElementAttributes (line, origAttrs);

				//FOREGROUND
				for (var i in rets) {
					var attrs = {
						y: origYs [i] - (pointDistance / 2),
						x: (pointDistance * i) - (pointDistance / 2),
						width: pointDistance,
						height: pointDistance,
						data: rets [i].data,
						"class": rets [i]["class"]
					};
					var rect = container.append ("rect")
						.on ("click", this.createCallback ("click"))
						.on ("mouseover", this.createCallback ("mouseover"));
					this.setElementAttributes (rect, {y: attrs.y, x: attrs.x, width: attrs.width, height: attrs.height, data: attrs.data});
					rect.classed ("square", true);

					var col = container.append ("rect")
						.on ("click", this.createCallback ("click"))
						.on ("mouseover", this.createCallback ("mouseover"));
					attrs.height = cHeight - attrs.y;
					this.setElementAttributes (col, attrs);
					col.classed ("column", true);
				}

				return attrs;
			}
		}

		var quantifierCb = this.quantifierCallback, me = this;
		this.svg.selectAll ("g").remove (); //HACK lets see later how to UPDATE them the elements instead of just removing all...
		for (var i in lines) {
			var line = lines [i];
			var bar = this.svg.append ("g")
				.on ("click", this.createCallback ("mouseover"))
				.on ("mouseover", this.createCallback ("mouseover"));
			var qn = quantifierCb.apply (this, [quantifier, after (bar, line.attrs)]);
			qn.apply  (this, [bar, line.values]);
			this.setElementAttributes (bar, line.attrs);
		}
	}
	return this;
}
ant.charts.lines = function (container, conf) { this.init (container,conf); }
asChart.call (ant.charts.lines.prototype);
asLines.call (ant.charts.lines.prototype);
<commit_msg>yAxis for chart<commit_after>var asLines = function () {
	this.redraw  = function (d, quantifier) {
		if (!d || !d.scale) return;
		this.callbacks = {};
		var data = d.data;
		d.scale.range ([this.height, 0]); // this comes from the prequantifier and it is used by the quantifier

		var lines = data; //TODO verify if this works with a single line..
		if (data.nests == 2) {
			lines = data.items ();
		}
		var itemsMax = d3.max (lines, function (l) { return l.values.length; });
		var pointDistance = this.width / itemsMax;
		var height = this.height;

		var after = function (container, origAttrs) {
			return function (orets, a) {
				var ys = [], rs = [], origYs = [];
				var attrs = {};
				var cHeight = height;
				var rets = jQuery.extend({}, orets, true);
				for (var i in rets) {
					var origY = rets [i].y;
					rets [i].y = 0;
					rets [i].x = pointDistance * i;
					rets [i].width = pointDistance;
					rets [i].height = cHeight;
					var rect = container.insert ("rect", ":first-child")
						.on ("click", this.createCallback ("click"))
						.on ("mouseover", this.createCallback ("mouseover"));
					this.setElementAttributes (rect, {data: rets [i]["data"], width: pointDistance, height: cHeight, x: rets [i].x - (pointDistance / 2), y: 0, "class": rets [i]["class"]});
					rect.classed ("background", true);

					rets [i].y = origY;
					rets [i].cx = rets [i].x;
					rets [i].cy = rets [i].y;
					origYs.push (rets [i].y);
					if (origAttrs && origAttrs ["stepped"] == true) {
						ys.push ({y: rets [i].y, x: rets [i].x - (pointDistance / 2)});
						ys.push ({y: rets [i].y, x: rets [i].x});
						ys.push ({y: rets [i].y, x: rets [i].x + (pointDistance / 2)});
					} else {
						ys.push ({y: rets [i].y, x: rets [i].x});
					}
					rs.push (rets [i].r);

				}
				var x = function (d, e) { return d.x; };
				var y = function (d, e) { return d.y; };
				var line = container.insert ("path");
				var svgLine = d3.svg.line ().x (x).y (y);
				line.attr ("d", function (t) { return svgLine (ys) })
					.on ("click", this.createCallback ("click"));
				this.setElementAttributes (line, origAttrs);

				//FOREGROUND
				for (var i in rets) {
					var attrs = {
						y: origYs [i] - (pointDistance / 2),
						x: (pointDistance * i) - (pointDistance / 2),
						width: pointDistance,
						height: pointDistance,
						data: rets [i].data,
						"class": rets [i]["class"]
					};
					var rect = container.append ("rect")
						.on ("click", this.createCallback ("click"))
						.on ("mouseover", this.createCallback ("mouseover"));
					this.setElementAttributes (rect, {y: attrs.y, x: attrs.x, width: attrs.width, height: attrs.height, data: attrs.data});
					rect.classed ("square", true);

					var col = container.append ("rect")
						.on ("click", this.createCallback ("click"))
						.on ("mouseover", this.createCallback ("mouseover"));
					attrs.height = cHeight - attrs.y;
					this.setElementAttributes (col, attrs);
					col.classed ("column", true);

					var circle = container.insert ("circle")
						.on ("click", this.createCallback ("click"))
						.on ("mouseover", this.createCallback ("mouseover"));
					this.setElementAttributes (circle, {"class": rets [i]["class"], cx: rets [i].x, cy: rets [i].y, r: rets [i].r});
					if (rets [i].value) {
						var text = container.append("text").text (rets [i].value);
						this.setElementAttributes (text, {"class": rets [i]["class"], x: rets [i].x, y: rets [i].y});
						text.classed ("value", true);
					}
					if (rets [i].label) {
						var text = container.append ("text").text (rets [i].label);
						this.setElementAttributes (text, {"class": rets [i]["class"], x: rets [i].x, y: cHeight, "transform": "rotate(-90,"+ rets [i].x +","+ cHeight +")"});
						text.classed ("label", true);
					}
					if (rets [i].note) {
						var text = container.append ("text").text (rets [i].note);
						this.setElementAttributes (text, {"class": rets [i]["class"], x: rets [i].x, y: 10, "transform": "rotate(90,"+ rets [i].x+","+10+")"});
						text.classed ("note", true);

					}
				}

				return attrs;
			}
		}

		var quantifierCb = this.quantifierCallback, me = this;
		this.svg.selectAll ("g").remove (); //HACK lets see later how to UPDATE them the elements instead of just removing all...

		var yAxis = d3.svg.axis().scale (d.scale).tickSize (this.width).orient ("right");
		this.svg.append ("g").attr("class", "axis").attr ("transform", "translate(0,0)").call (yAxis);

		for (var i in lines) {
			var line = lines [i];
			var bar = this.svg.append ("g")
				.on ("click", this.createCallback ("mouseover"))
				.on ("mouseover", this.createCallback ("mouseover"));
			var qn = quantifierCb.apply (this, [quantifier, after (bar, line.attrs)]);
			qn.apply  (this, [bar, line.values]);
			this.setElementAttributes (bar, line.attrs);
		}
	}
	return this;
}
ant.charts.lines = function (container, conf) { this.init (container,conf); }
asChart.call (ant.charts.lines.prototype);
asLines.call (ant.charts.lines.prototype);
<|endoftext|>


<commit_before>
var app = angular.module('cloudStorm.log', [])

app.factory('csLog', [

  function(){

    var csLog = {

      //Initially the log is disabled
      set : function(scope, componentName, enabled){

          scope.logEnabled = false || enable
          scope.log = function(msg){
            if(scope.logEnabled){
              console.log(componentName, msg)
            }
          }
      },

      enable : function(scope){
        scope.logEnabled = true
      }

      disable : function(scope){
        scope.logEnabled = false
      }

    }
    return csLog
  }
])
<commit_msg>bug fixed<commit_after>
var app = angular.module('cloudStorm.log', [])

app.factory('csLog', [

  function(){

    var csLog = {

      //Initially the log is disabled
      set : function(scope, componentName, enabled){

          scope.logEnabled = false || enabled
          scope.log = function(msg){
            if(scope.logEnabled){
              console.log(componentName, msg)
            }
          }
      },

      enable : function(scope){
        scope.logEnabled = true
      },

      disable : function(scope){
        scope.logEnabled = false
      }

    }
    return csLog
  }
])
<|endoftext|>


<commit_before>if (!window.maxkir) maxkir = {};
maxkir.FF = /Firefox/i.test(navigator.userAgent);

// Unify access to computed styles (for IE)
if (typeof document.defaultView == 'undefined') {
  document.defaultView = {};
  document.defaultView.getComputedStyle = function(element){
    return element.currentStyle;
  }
}

// This class allows to obtain position of cursor in the text area
// The position can be calculated as cursorX/cursorY or
// pointX/pointY
// See getCursorCoordinates and getPixelCoordinates
maxkir.CursorPosition = function(element, padding) {
  this.element = element;
  this.padding = padding;

  var that = this;

  var get_sel_range = function() {
    // thanks to http://the-stickman.com/web-development/javascript/finding-selection-cursor-position-in-a-textarea-in-internet-explorer/
    if( (typeof element.selectionStart == 'undefined') && document.selection ){
      // The current selection
      var range = document.selection.createRange();
      // We'll use this as a 'dummy'
      var stored_range = range.duplicate();
      // Select all text
      if (element.type == 'text') {
        stored_range.moveStart('character', -element.value.length);
        stored_range.moveEnd('character', element.value.length);
      } else { // textarea
        stored_range.moveToElementText( element );
      }
      // Now move 'dummy' end point to end point of original range
      stored_range.setEndPoint( 'EndToEnd', range );
      // Now we can calculate start and end points
      var selectionStart = stored_range.text.length - range.text.length;
      var selectionEnd = selectionStart + range.text.length;
      return [selectionStart, selectionEnd];
    }
    return [element.selectionStart, element.selectionEnd];
  };

  this.get_selection_range = function() {
    try {
      return get_sel_range();
    }
    catch(e) {
      return [0,0]
    }
  };

  var clone_css_style = function(target, styleName) {
    var val = element.style[styleName];
    if (!val) {
      var css = document.defaultView.getComputedStyle(element, null);
      val = css ? css[styleName] : null;
    }
    if (val) {
      target.style[styleName] = val;
    }
  };

  this.get_string_metrics = function(s) {
    var widthElementId = "__widther";
    var div = document.getElementById(widthElementId);
    if (!div) {
      div = document.createElement("div");
      div.id = widthElementId;
      document.body.appendChild(div);

      div.style.position = 'absolute';
      div.style.left = '-10000px';
    }

    clone_css_style(div, 'fontSize');
    clone_css_style(div, 'fontFamily');
    clone_css_style(div, 'fontWeight');
    clone_css_style(div, 'fontVariant');
    clone_css_style(div, 'fontStyle');
    clone_css_style(div, 'textTransform');
    clone_css_style(div, 'lineHeight');

    div.style.width = '0';
    div.style.paddingLeft = that.padding + "px";

    div.innerHTML = s.replace(' ', " ");
    div.style.width = 'auto';
    return [div.offsetWidth, div.offsetHeight];
  };

  var splitter = new maxkir.StringSplitter(function(s) {
    var metrics = that.get_string_metrics(s);
    //maxkir.info(s + " |||" + metrics)
    return metrics[0];
  });

  this.split_to_lines = function() {
    var innerAreaWidth = element.scrollWidth;
    if (maxkir.FF) {  // FF has some implicit additional padding
      innerAreaWidth -= 4;
    }

    var pos = that.get_selection_range()[0];
    return splitter.splitString(element.value.substr(0, pos), innerAreaWidth);
  };

};

maxkir.CursorPosition.prototype.getCursorCoordinates = function() {
  var lines = this.split_to_lines();
  return [lines[lines.length - 1].length, lines.length];
};

maxkir.CursorPosition.prototype.getPixelCoordinates = function() {
  var lines = this.split_to_lines();
  var m = this.get_string_metrics(lines[lines.length - 1]);
  var w = m[0];
  var h = m[1] * lines.length - this.element.scrollTop + this.padding;
  return [w, h];
};
<commit_msg>Extract separate maxkir.CursorPosition.getTextMetrics method<commit_after>if (!window.maxkir) maxkir = {};
maxkir.FF = /Firefox/i.test(navigator.userAgent);

// Unify access to computed styles (for IE)
if (typeof document.defaultView == 'undefined') {
  document.defaultView = {};
  document.defaultView.getComputedStyle = function(element){
    return element.currentStyle;
  }
}

// This class allows to obtain position of cursor in the text area
// The position can be calculated as cursorX/cursorY or
// pointX/pointY
// See getCursorCoordinates and getPixelCoordinates
maxkir.CursorPosition = function(element, padding) {
  this.element = element;
  this.padding = padding;

  var that = this;

  var get_sel_range = function() {
    // thanks to http://the-stickman.com/web-development/javascript/finding-selection-cursor-position-in-a-textarea-in-internet-explorer/
    if( (typeof element.selectionStart == 'undefined') && document.selection ){
      // The current selection
      var range = document.selection.createRange();
      // We'll use this as a 'dummy'
      var stored_range = range.duplicate();
      // Select all text
      if (element.type == 'text') {
        stored_range.moveStart('character', -element.value.length);
        stored_range.moveEnd('character', element.value.length);
      } else { // textarea
        stored_range.moveToElementText( element );
      }
      // Now move 'dummy' end point to end point of original range
      stored_range.setEndPoint( 'EndToEnd', range );
      // Now we can calculate start and end points
      var selectionStart = stored_range.text.length - range.text.length;
      var selectionEnd = selectionStart + range.text.length;
      return [selectionStart, selectionEnd];
    }
    return [element.selectionStart, element.selectionEnd];
  };

  this.get_selection_range = function() {
    try {
      return get_sel_range();
    }
    catch(e) {
      return [0,0]
    }
  };

  this.get_string_metrics = function(s) {
    return maxkir.CursorPosition.getTextMetrics(element, s, padding);
  };

  var splitter = new maxkir.StringSplitter(function(s) {
    var metrics = that.get_string_metrics(s);
    //maxkir.info(s + " |||" + metrics)
    return metrics[0];
  });

  this.split_to_lines = function() {
    var innerAreaWidth = element.scrollWidth;
    if (maxkir.FF) {  // FF has some implicit additional padding
      innerAreaWidth -= 4;
    }

    var pos = that.get_selection_range()[0];
    return splitter.splitString(element.value.substr(0, pos), innerAreaWidth);
  };

};

maxkir.CursorPosition.prototype.getCursorCoordinates = function() {
  var lines = this.split_to_lines();
  return [lines[lines.length - 1].length, lines.length];
};

maxkir.CursorPosition.prototype.getPixelCoordinates = function() {
  var lines = this.split_to_lines();
  var m = this.get_string_metrics(lines[lines.length - 1]);
  var w = m[0];
  var h = m[1] * lines.length - this.element.scrollTop + this.padding;
  return [w, h];
};

/** Return preferred [width, height] of the text as if it was written inside styledElement (textarea)
 * @param styledElement element to copy styles from
 * @s text for metrics calculation
 * @padding - explicit additional padding
 * */
maxkir.CursorPosition.getTextMetrics = function(styledElement, s, padding) {

  var element = styledElement;
  var clone_css_style = function(target, styleName) {
    var val = element.style[styleName];
    if (!val) {
      var css = document.defaultView.getComputedStyle(element, null);
      val = css ? css[styleName] : null;
    }
    if (val) {
      target.style[styleName] = val;
    }
  };

  var widthElementId = "__widther";
  var div = document.getElementById(widthElementId);
  if (!div) {
    div = document.createElement("div");
    document.body.appendChild(div)
    div.id = widthElementId;

    div.style.position = 'absolute';
    div.style.left = '-10000px';
  }

  clone_css_style(div, 'fontSize');
  clone_css_style(div, 'fontFamily');
  clone_css_style(div, 'fontWeight');
  clone_css_style(div, 'fontVariant');
  clone_css_style(div, 'fontStyle');
  clone_css_style(div, 'textTransform');
  clone_css_style(div, 'lineHeight');

  div.style.width = '0';
  div.style.paddingLeft = padding + "px";

  div.innerHTML = s.replace(' ', " ");
  div.style.width = 'auto';
  return [div.offsetWidth, div.offsetHeight];

};<|endoftext|>


<commit_before>import inquirerAsync from 'inquirer-async';

import {
  Api,
  Exp,
} from 'xdl';

import _ from 'lodash';
import log from '../log';

async function action(projectDir, options) {
  let validatedOptions = {};
  let templateType;
  let questions = [];

  if (options.projectName) {
    validatedOptions.name = options.projectName;
  } else {
    questions.push({
      type: 'input',
      name: 'name',
      message: 'Project name',
      validate(val) {
        // TODO: Validate
        return val.length > 0;
      },
    });
  }

  if (options.projectType) {
    templateType = options.projectType;
  } else {
    let versions = await Api.versionsAsync();
    let templateIds = _.map(versions.templates, (template) => `"${template.id}"`);

    questions.push({
      type: 'input',
      name: 'type',
      message: `Project type. Options are: ${templateIds.join(', ')}`,
      validate(val) {
        for (let i = 0; i < versions.templates.length; i++) {
          if (versions.templates[i].id === val) {
            return true;
          }
        }

        return false;
      },
    });
  }

  if (questions.length > 0) {
    var answers = await inquirerAsync.promptAsync(questions);
    if (answers.name) {
      validatedOptions.name = answers.name;
    }
    if (answers.type) {
      templateType = answers.type;
    }
  }

  let root = await Exp.createNewExpAsync(templateType, projectDir, {}, validatedOptions);
  log(`Your project is ready at ${root}. Use "exp start ${root}" to get started.`);
}

export default (program) => {
  program
    .command('init [project-dir]')
    .alias('i')
    .description('Initializes a directory with an example project')
    .option('-n, --projectName [name]', 'Specify a name for the new project')
    .option('-t, --projectType [type]', 'Specify what type of template to use. Run without this options to see all choices.')
    .asyncActionProjectDir(action, true); // pass true to skip validation
};
<commit_msg>Update exp init help entry<commit_after>import inquirerAsync from 'inquirer-async';

import {
  Api,
  Exp,
} from 'xdl';

import _ from 'lodash';
import log from '../log';

async function action(projectDir, options) {
  let validatedOptions = {};
  let templateType;
  let questions = [];

  if (options.projectName) {
    validatedOptions.name = options.projectName;
  } else {
    questions.push({
      type: 'input',
      name: 'name',
      message: 'Project name',
      validate(val) {
        // TODO: Validate
        return val.length > 0;
      },
    });
  }

  if (options.projectType) {
    templateType = options.projectType;
  } else {
    let versions = await Api.versionsAsync();
    let templateIds = _.map(versions.templates, (template) => `"${template.id}"`);

    questions.push({
      type: 'input',
      name: 'type',
      message: `Project type. Options are: ${templateIds.join(', ')}`,
      validate(val) {
        for (let i = 0; i < versions.templates.length; i++) {
          if (versions.templates[i].id === val) {
            return true;
          }
        }

        return false;
      },
    });
  }

  if (questions.length > 0) {
    var answers = await inquirerAsync.promptAsync(questions);
    if (answers.name) {
      validatedOptions.name = answers.name;
    }
    if (answers.type) {
      templateType = answers.type;
    }
  }

  let root = await Exp.createNewExpAsync(templateType, projectDir, {}, validatedOptions);
  log(`Your project is ready at ${root}. Use "exp start ${root}" to get started.`);
}

export default (program) => {
  program
    .command('init [project-dir]')
    .alias('i')
    .description('Initializes a directory with an example project. Run it without any options and you will be prompted for the name and type.')
    .option('-n, --projectName [name]', 'Specify a name for the new project')
    .option('-t, --projectType [type]', 'Specify what type of template to use. Run without this option to see all choices.')
    .asyncActionProjectDir(action, true); // pass true to skip validation
};
<|endoftext|>


<commit_before>import {
  RPL_LISTSTART,
  RPL_LIST,
  RPL_LISTEND
} from '../replies'

export default function list ({ user, server, parameters: [ channels ] }) {
  const mask = server.mask()

  channels = channels ? channels.split(',') : Object.keys(server.channels)

  user.send(mask, RPL_LISTSTART, [ user.nickname, 'Channel', 'Users  Name' ])

  channels
    .map(server.findChannel, server)
    .forEach((chan) => {
      user.send(mask, RPL_LIST,
                [ user.nickname, chan.name, chan.users.length, chan.topic || '' ])
    })

  user.send(mask, RPL_LISTEND, [ user.nickname, 'End of /LIST' ])
}
<commit_msg>/LIST: hide private and secret channels<commit_after>import {
  RPL_LISTSTART,
  RPL_LIST,
  RPL_LISTEND
} from '../replies'

export default function list ({ user, server, parameters: [ channels ] }) {
  const mask = server.mask()

  channels = channels ? channels.split(',') : Object.keys(server.channels)

  user.send(mask, RPL_LISTSTART, [ user.nickname, 'Channel', 'Users  Name' ])

  channels
    .map(server.findChannel, server)
    .filter((chan) => !chan.isSecret() || chan.hasUser(user))
    .forEach((chan) => {
      let response = [ user.nickname, chan.name, chan.users.length, chan.topic || '' ]
      if (chan.isPrivate() && !chan.hasUser(user)) {
        response = [ user.nickname, 'Prv', chan.users.length, '' ]
      }
      user.send(mask, RPL_LIST, response)
    })

  user.send(mask, RPL_LISTEND, [ user.nickname, 'End of /LIST' ])
}
<|endoftext|>


<commit_before>import React from 'react';
import classSet from 'classnames';
import Const from './Const';
import Util from './util';

class TableHeaderColumn extends React.Component{

  handleColumnClick(e){
    if(!this.props.dataSort)return;
    let order = this.props.sort == Const.SORT_DESC?Const.SORT_ASC:Const.SORT_DESC;
    this.props.onSort(order, this.props.dataField);
  }

  componentDidMount(){
    this.refs.innerDiv.setAttribute("data-field", this.props.dataField);
  }

  render(){
    var width = this.props.width!==null?parseInt(this.props.width):null;
    var thStyle = {
      textAlign: this.props.dataAlign,
      display: this.props.hidden?"none":null,
      width: width,
      maxWidth: width
    };

    const sortCaret = this.props.sort ? Util.renderReactSortCaret(this.props.sort) : null;

    var classes = this.props.className+" "+(this.props.dataSort?"sort-column":"");
    return(

          {this.props.children}{sortCaret}

    )
  }
}
TableHeaderColumn.propTypes = {
  dataField: React.PropTypes.string,
  dataAlign: React.PropTypes.string,
  dataSort: React.PropTypes.bool,
  onSort: React.PropTypes.func,
  dataFormat: React.PropTypes.func,
  isKey: React.PropTypes.bool,
  editable: React.PropTypes.any,
  hidden: React.PropTypes.bool,
  className:React.PropTypes.string,
  width: React.PropTypes.string,
  sortFunc: React.PropTypes.func,
  columnClassName: React.PropTypes.any,
  filterFormatted: React.PropTypes.bool,
  sort: React.PropTypes.string,
  formatExtraData: React.PropTypes.any
};

TableHeaderColumn.defaultProps = {
  dataAlign: "left",
  dataSort: false,
  dataFormat: undefined,
  isKey: false,
  editable: true,
  onSort: undefined,
  hidden: false,
  className: "",
  width: null,
  sortFunc: undefined,
  columnClassName: '',
  filterFormatted: false,
  sort: undefined,
  formatExtraData: undefined
};

export default TableHeaderColumn;
<commit_msg>Show default caret to tell user which column is sortable<commit_after>import React from 'react';
import classSet from 'classnames';
import Const from './Const';
import Util from './util';

class TableHeaderColumn extends React.Component{

  handleColumnClick(e){
    if(!this.props.dataSort)return;
    let order = this.props.sort == Const.SORT_DESC?Const.SORT_ASC:Const.SORT_DESC;
    this.props.onSort(order, this.props.dataField);
  }

  componentDidMount(){
    this.refs.innerDiv.setAttribute("data-field", this.props.dataField);
  }

  render(){
    var width = this.props.width!==null?parseInt(this.props.width):null;
    var thStyle = {
      textAlign: this.props.dataAlign,
      display: this.props.hidden?"none":null,
      width: width,
      maxWidth: width
    };

    const defaultCaret = (!this.props.dataSort) ? null : (

    );
    const sortCaret = this.props.sort ? Util.renderReactSortCaret(this.props.sort) : defaultCaret;

    var classes = this.props.className+" "+(this.props.dataSort?"sort-column":"");
    return(

          {this.props.children}{sortCaret}

    )
  }
}
TableHeaderColumn.propTypes = {
  dataField: React.PropTypes.string,
  dataAlign: React.PropTypes.string,
  dataSort: React.PropTypes.bool,
  onSort: React.PropTypes.func,
  dataFormat: React.PropTypes.func,
  isKey: React.PropTypes.bool,
  editable: React.PropTypes.any,
  hidden: React.PropTypes.bool,
  className:React.PropTypes.string,
  width: React.PropTypes.string,
  sortFunc: React.PropTypes.func,
  columnClassName: React.PropTypes.any,
  filterFormatted: React.PropTypes.bool,
  sort: React.PropTypes.string
};

TableHeaderColumn.defaultProps = {
  dataAlign: "left",
  dataSort: false,
  dataFormat: undefined,
  isKey: false,
  editable: true,
  onSort: undefined,
  hidden: false,
  className: "",
  width: null,
  sortFunc: undefined,
  columnClassName: '',
  filterFormatted: false,
  sort: undefined
};

export default TableHeaderColumn;
<|endoftext|>


<commit_before>'use strict';

var TypedError = require('error/typed');

var Errors = {};

Errors.MissingFieldInConstr = TypedError({
    type: 'jsig.verify.missing-field-in-constructor',
    message: '@{line}: Expected the field: {fieldName} to be defined ' +
        'in constructor {funcName} but instead found: {otherField}.',
    fieldName: null,
    otherField: null,
    funcName: null,
    loc: null,
    line: null
});

Errors.UnknownIdentifier = TypedError({
    type: 'jsig.verify.unknown-identifier',
    message: '@{line}: Could not find identifier {tokenName}.',
    tokenName: null,
    loc: null,
    line: null
});

Errors.UnknownModuleExports = TypedError({
    type: 'jsig.verify.unknown-module-exports',
    message: '@{line}: Cannot export untyped function {funcName}.',
    funcName: null,
    loc: null,
    line: null
});

Errors.UnTypedIdentifier = TypedError({
    type: 'jsig.verify.untyped-identifier',
    message: '@{line}: Identifier {tokenName} does not have a type.',
    name: null,
    loc: null,
    line: null
});

Errors.TooManyArgsInFunc = TypedError({
    type: 'jsig.verify.too-many-function-args',
    message: '@{line}: Expected the function {funcName} to have exactly ' +
        '{expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooFewArgsInFunc = TypedError({
    type: 'jsig.verify.too-few-function-args',
    message: '@{line}: Expected the function {funcName} to have exactly ' +
        '{expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooManyArgsInNewExpression = TypedError({
    type: 'jsig.verify.too-many-args-in-new-expression',
    message: '@{line}: Expected the new call on constructor {funcName} to ' +
        'have exactly {expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooFewArgsInNewExpression = TypedError({
    type: 'jsig.verify.too-few-args-in-new-expression',
    message: '@{line}: Expected the new call on constructor {funcName} to ' +
        'have exactly {expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooManyArgsInCall = TypedError({
    type: 'jsig.verify.too-many-args-in-call',
    message: '@{line}: Expected invocation of {funcName} to have exactly ' +
        '{expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooFewArgsInCall = TypedError({
    type: 'jsig.verify.too-few-args-in-call',
    message: '@{line}: Expected invocation of {funcName} to have exactly ' +
        '{expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.NonExistantField = TypedError({
    type: 'jsig.verify.non-existant-field',
    message: '@{line}: Object {objName} does not have field {fieldName}.',
    fieldName: null,
    objName: null,
    loc: null,
    line: null
});

Errors.NonVoidReturnType = TypedError({
    type: 'jsig.verify.non-void-return-type',
    message: '@{line}: Expected function {funcName} to return ' +
        'void but found: {actual}.',
    expected: null,
    actual: null,
    funcName: null,
    loc: null,
    line: null
});

Errors.MissingReturnStatement = TypedError({
    type: 'jsig.verify.missing-return-statement',
    message: '@{line}: Expected function {funcName} to return ' +
        '{expected} but found no return statement.',
    expected: null,
    actual: null,
    funcName: null,
    loc: null,
    line: null
});

Errors.UnTypedFunctionFound = TypedError({
    type: 'jsig.verify.untyped-function-found',
    message: '@{line}: Expected the function {funcName} to have ' +
        'type but could not find one.',
    funcName: null,
    loc: null,
    line: null
});

Errors.UnTypedFunctionCall = TypedError({
    type: 'jsig.verify.untyped-function-call',
    message: '@{line}: Expected to know type of function: {funcName}. ' +
        'Instead found callsite of untyped function: {callExpression}.',
    funcName: null,
    callExpression: null,
    loc: null,
    line: null
});

Errors.CallingNewOnPlainFunction = TypedError({
    type: 'jsig.verify.calling-new-on-plain-function',
    message: '@{line}: Cannot call `new` on plain function {funcName}. ' +
        'The function type {funcType} is not a constructor.',
    funcName: null,
    funcType: null,
    loc: null,
    line: null
});

Errors.ConstructorMustBePascalCase = TypedError({
    type: 'jsig.verify.constructor-must-be-pascal-case',
    message: '@{line}: Constructor function {funcName} must be pascal case. ' +
        'Cannot call `new` on function type {funcType}.',
    funcName: null,
    funcType: null,
    loc: null,
    line: null
});

Errors.ConstructorThisTypeMustBeObject = TypedError({
    type: 'jsig.verify.constructor-this-type-must-be-object',
    message: '@{line}: Constructor {funcName} must have non-empty thisType. ' +
        'Cannot have non-object or empty object this ({thisType}).',
    funcName: null,
    thisType: null,
    loc: null,
    line: null
});

Errors.ConstructorMustReturnVoid = TypedError({
    type: 'jsig.verify.constructor-must-return-void',
    message: '@{line}: Constructor {funcName} must return void. ' +
        'Cannot return type: {returnType}.',
    funcName: null,
    returnType: null,
    loc: null,
    line: null
});

Errors.ReturnStatementInConstructor = TypedError({
    type: 'jsig.verify.return-statement-in-constructor',
    message: '@{line}: Constructor {funcName} has unexpected ' +
        'return statement. ' +
        'Expected no return but found type: {returnType}.',
    funcName: null,
    returnType: null,
    loc: null,
    line: null
});

Errors.UnionFieldAccess = TypedError({
    type: 'jsig.verify.accessing-field-on-union',
    message: '@{line}: Cannot read field {fieldName} of union. ' +
        'Expected an object type but found {unionType}.',
    fieldName: null,
    unionType: null,
    loc: null,
    line: null
});

Errors.NonObjectFieldAccess = TypedError({
    type: 'jsig.verify.accessing-field-on-non-object',
    message: '@{line}: Cannot read field {fieldName} of non-object. ' +
        'Expected an object type but found {nonObjectType}.',
    fieldName: null,
    nonObjectType: null,
    loc: null,
    line: null
});

Errors.NonExistantThis = TypedError({
    type: 'jsig.verify.non-existant-this',
    message: '@{line}: Cannot access `this` inside function {funcName}. ' +
        'Function type: {funcType} does not have thisType.',
    funcName: null,
    funcType: null,
    loc: null,
    line: null
});

Errors.MissingDefinition = TypedError({
    type: 'jsig.verify.missing-definition',
    message: '@{line}: Cannot find external definition for ' +
        'module: {moduleName}.',
    moduleName: null,
    loc: null,
    line: null
});

Errors.TypeClassMismatch = TypedError({
    type: 'jsig.sub-type.type-class-mismatch',
    message: '@{line}: Got unexpected type class. ' +
        'Expected {expected} but got {actual}',
    expected: null,
    actual: null,
    loc: null,
    line: null
});

Errors.UnionTypeClassMismatch = TypedError({
    type: 'jsig.sub-type.union-type-class-mismatch',
    message: '@{line}: Got unexpected type for union. ' +
        'Expected {expected} but got {actual}',
    expected: null,
    actual: null,
    loc: null,
    line: null
});

Errors.IntersectionOperatorCallMismatch = TypedError({
    type: 'jsig.sub-type.intersection-operator-call-mismatch',
    message: '@{line}: Cannot call any of operators: {operator} types.',
    expected: null,
    actual: null,
    operator: null,
    loc: null,
    line: null
});

Errors.IncorrectFieldCount = TypedError({
    type: 'jsig.sub-type.unexpected-field-count',
    message: '@{line}: Got unexpected number of fields. ' +
        'Expected {expectedFields} fields but found {actualFields} fields.',
    actual: null,
    expected: null,
    actualFields: null,
    expectedFields: null,
    loc: null,
    line: null
});

Errors.NonGenericPropertyLookup = TypedError({
    type: 'jsig.verify.non-generic-property-lookup',
    message: '@{line}: Cannot lookup field in non-generic value. ' +
        'Expected {expected} type but got {actual} type.',
    actual: null,
    expected: null,
    loc: null,
    line: null
});

Errors.InvalidThrowStatement = TypedError({
    type: 'jsig.verify.invalid-throw-statement',
    message: '@{line}: A throw statement must throw an actual error. ' +
        'Expected {expected} tyoe but got {actual} type.',
    actual: null,
    expected: null,
    loc: null,
    line: null
});

module.exports = Errors;
<commit_msg>add error defn<commit_after>'use strict';

var TypedError = require('error/typed');

var Errors = {};

Errors.MissingFieldInConstr = TypedError({
    type: 'jsig.verify.missing-field-in-constructor',
    message: '@{line}: Expected the field: {fieldName} to be defined ' +
        'in constructor {funcName} but instead found: {otherField}.',
    fieldName: null,
    otherField: null,
    funcName: null,
    loc: null,
    line: null
});

Errors.UnknownIdentifier = TypedError({
    type: 'jsig.verify.unknown-identifier',
    message: '@{line}: Could not find identifier {tokenName}.',
    tokenName: null,
    loc: null,
    line: null
});

Errors.UnknownModuleExports = TypedError({
    type: 'jsig.verify.unknown-module-exports',
    message: '@{line}: Cannot export untyped function {funcName}.',
    funcName: null,
    loc: null,
    line: null
});

Errors.UnTypedIdentifier = TypedError({
    type: 'jsig.verify.untyped-identifier',
    message: '@{line}: Identifier {tokenName} does not have a type.',
    name: null,
    loc: null,
    line: null
});

Errors.TooManyArgsInFunc = TypedError({
    type: 'jsig.verify.too-many-function-args',
    message: '@{line}: Expected the function {funcName} to have exactly ' +
        '{expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooFewArgsInFunc = TypedError({
    type: 'jsig.verify.too-few-function-args',
    message: '@{line}: Expected the function {funcName} to have exactly ' +
        '{expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooManyArgsInNewExpression = TypedError({
    type: 'jsig.verify.too-many-args-in-new-expression',
    message: '@{line}: Expected the new call on constructor {funcName} to ' +
        'have exactly {expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooFewArgsInNewExpression = TypedError({
    type: 'jsig.verify.too-few-args-in-new-expression',
    message: '@{line}: Expected the new call on constructor {funcName} to ' +
        'have exactly {expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooManyArgsInCall = TypedError({
    type: 'jsig.verify.too-many-args-in-call',
    message: '@{line}: Expected invocation of {funcName} to have exactly ' +
        '{expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.TooFewArgsInCall = TypedError({
    type: 'jsig.verify.too-few-args-in-call',
    message: '@{line}: Expected invocation of {funcName} to have exactly ' +
        '{expectedArgs} arguments but instead has {actualArgs}.',
    funcName: null,
    actualArgs: null,
    expectedArgs: null,
    loc: null,
    line: null
});

Errors.NonExistantField = TypedError({
    type: 'jsig.verify.non-existant-field',
    message: '@{line}: Object {objName} does not have field {fieldName}.',
    fieldName: null,
    objName: null,
    loc: null,
    line: null
});

Errors.NonVoidReturnType = TypedError({
    type: 'jsig.verify.non-void-return-type',
    message: '@{line}: Expected function {funcName} to return ' +
        'void but found: {actual}.',
    expected: null,
    actual: null,
    funcName: null,
    loc: null,
    line: null
});

Errors.MissingReturnStatement = TypedError({
    type: 'jsig.verify.missing-return-statement',
    message: '@{line}: Expected function {funcName} to return ' +
        '{expected} but found no return statement.',
    expected: null,
    actual: null,
    funcName: null,
    loc: null,
    line: null
});

Errors.UnTypedFunctionFound = TypedError({
    type: 'jsig.verify.untyped-function-found',
    message: '@{line}: Expected the function {funcName} to have ' +
        'type but could not find one.',
    funcName: null,
    loc: null,
    line: null
});

Errors.UnTypedFunctionCall = TypedError({
    type: 'jsig.verify.untyped-function-call',
    message: '@{line}: Expected to know type of function: {funcName}. ' +
        'Instead found callsite of untyped function: {callExpression}.',
    funcName: null,
    callExpression: null,
    loc: null,
    line: null
});

Errors.CallingNewOnPlainFunction = TypedError({
    type: 'jsig.verify.calling-new-on-plain-function',
    message: '@{line}: Cannot call `new` on plain function {funcName}. ' +
        'The function type {funcType} is not a constructor.',
    funcName: null,
    funcType: null,
    loc: null,
    line: null
});

Errors.CallingNonFunctionObject = TypedError({
    type: 'jsig.verify.calling-non-function-object',
    message: '@{line}: Cannot call non-function object. ' +
        'The call expr {callExpression} does not work for type: {objType}.',
    objType: null,
    callExpression: null,
    loc: null,
    line: null
});

Errors.ConstructorMustBePascalCase = TypedError({
    type: 'jsig.verify.constructor-must-be-pascal-case',
    message: '@{line}: Constructor function {funcName} must be pascal case. ' +
        'Cannot call `new` on function type {funcType}.',
    funcName: null,
    funcType: null,
    loc: null,
    line: null
});

Errors.ConstructorThisTypeMustBeObject = TypedError({
    type: 'jsig.verify.constructor-this-type-must-be-object',
    message: '@{line}: Constructor {funcName} must have non-empty thisType. ' +
        'Cannot have non-object or empty object this ({thisType}).',
    funcName: null,
    thisType: null,
    loc: null,
    line: null
});

Errors.ConstructorMustReturnVoid = TypedError({
    type: 'jsig.verify.constructor-must-return-void',
    message: '@{line}: Constructor {funcName} must return void. ' +
        'Cannot return type: {returnType}.',
    funcName: null,
    returnType: null,
    loc: null,
    line: null
});

Errors.ReturnStatementInConstructor = TypedError({
    type: 'jsig.verify.return-statement-in-constructor',
    message: '@{line}: Constructor {funcName} has unexpected ' +
        'return statement. ' +
        'Expected no return but found type: {returnType}.',
    funcName: null,
    returnType: null,
    loc: null,
    line: null
});

Errors.UnionFieldAccess = TypedError({
    type: 'jsig.verify.accessing-field-on-union',
    message: '@{line}: Cannot read field {fieldName} of union. ' +
        'Expected an object type but found {unionType}.',
    fieldName: null,
    unionType: null,
    loc: null,
    line: null
});

Errors.NonObjectFieldAccess = TypedError({
    type: 'jsig.verify.accessing-field-on-non-object',
    message: '@{line}: Cannot read field {fieldName} of non-object. ' +
        'Expected an object type but found {nonObjectType}.',
    fieldName: null,
    nonObjectType: null,
    loc: null,
    line: null
});

Errors.NonExistantThis = TypedError({
    type: 'jsig.verify.non-existant-this',
    message: '@{line}: Cannot access `this` inside function {funcName}. ' +
        'Function type: {funcType} does not have thisType.',
    funcName: null,
    funcType: null,
    loc: null,
    line: null
});

Errors.MissingDefinition = TypedError({
    type: 'jsig.verify.missing-definition',
    message: '@{line}: Cannot find external definition for ' +
        'module: {moduleName}.',
    moduleName: null,
    loc: null,
    line: null
});

Errors.TypeClassMismatch = TypedError({
    type: 'jsig.sub-type.type-class-mismatch',
    message: '@{line}: Got unexpected type class. ' +
        'Expected {expected} but got {actual}',
    expected: null,
    actual: null,
    loc: null,
    line: null
});

Errors.UnionTypeClassMismatch = TypedError({
    type: 'jsig.sub-type.union-type-class-mismatch',
    message: '@{line}: Got unexpected type for union. ' +
        'Expected {expected} but got {actual}',
    expected: null,
    actual: null,
    loc: null,
    line: null
});

Errors.IntersectionOperatorCallMismatch = TypedError({
    type: 'jsig.sub-type.intersection-operator-call-mismatch',
    message: '@{line}: Cannot call any of operators: {operator} types.',
    expected: null,
    actual: null,
    operator: null,
    loc: null,
    line: null
});

Errors.IncorrectFieldCount = TypedError({
    type: 'jsig.sub-type.unexpected-field-count',
    message: '@{line}: Got unexpected number of fields. ' +
        'Expected {expectedFields} fields but found {actualFields} fields.',
    actual: null,
    expected: null,
    actualFields: null,
    expectedFields: null,
    loc: null,
    line: null
});

Errors.NonGenericPropertyLookup = TypedError({
    type: 'jsig.verify.non-generic-property-lookup',
    message: '@{line}: Cannot lookup field in non-generic value. ' +
        'Expected {expected} type but got {actual} type.',
    actual: null,
    expected: null,
    loc: null,
    line: null
});

Errors.InvalidThrowStatement = TypedError({
    type: 'jsig.verify.invalid-throw-statement',
    message: '@{line}: A throw statement must throw an actual error. ' +
        'Expected {expected} tyoe but got {actual} type.',
    actual: null,
    expected: null,
    loc: null,
    line: null
});

module.exports = Errors;
<|endoftext|>


<commit_before>export default {
  TechSkills: [
    {
      title: "PHP",
      desc: "server-side programming langauge",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "NodeJS",
      desc: "javaScript server-side runtime back-end",
      prod: true,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "Git",
      desc: "source code versioning",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Laravel PHP",
      desc: "modern PHP framework",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Gulp",
      desc: "automation toolkit (task runner)",
      prod: true,
      actual: false,
      hobby: true
    },
    {
      title: "Grunt",
      desc: "javascript Task Runner",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Webpack",
      desc: "javascript Module bundler",
      prod: true,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "TypeScript",
      desc: "typed superset of Javascript",
      prod: true,
      hobby: false,
      actual: false
    },
    {
      title: "AngularJS",
      desc: "front-end JavaScript library framework",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Angular",
      desc: "monolithic JavaScript framework",
      prod: true,
      hobby: false,
      actual: false
    },
    {
      title: "React",
      desc: "javaScript library for building user interfaces",
      prod: true,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "MySQL",
      desc: "relational database system",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "SCSS",
      desc: "style sheet language",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Nginx",
      desc: "modern server",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Python",
      desc: "server-side programming language",
      prod: false,
      hobby: true,
      actual: true
    },
    {
      title: "Scrum",
      desc: "agile framework for completing complex projects",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "React Native",
      desc: "build native mobile apps using JavaScript and React",
      prod: false,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "Google Cloud Platform",
      desc: "cloud-based scalable infrastructure",
      prod: true,
      hobby: false,
      actual: true
    },
    {
      title: "Heroku",
      desc: "cloud-based application hosting",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Digital Ocean",
      desc: "cloud computing platform",
      prod: true,
      hobby: true
    },
    {
      title: "Google Analytics",
      desc: "web analytics service",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Adobe Analytics (Omniture)",
      desc: "web analytics service",
      prod: true,
      hobby: false,
      actual: true
    },
    {
      title: "CoffeeScript",
      desc: "javaScript subset language",
      prod: true,
      hobby: true,
      legacy: true,
      actual: false
    },
    {
      title: "Sketch",
      desc: "design toolkit",
      prod: true,
      hobby: true
    },
    {
      title: "Amazon Alexa",
      desc: "voice service framework",
      prod: true,
      hobby: true
    },
    {
      title: "Wit.AI",
      desc: "natural language API",
      prod: true,
      hobby: true
    },
    {
      title: "Visual Studio Code",
      desc: "text editor",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Zeit's Now",
      desc: "realtime global deployments",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Go Language",
      desc: "programming language",
      prod: false,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "Apache Cordova",
      desc: "mobile development framework",
      prod: true,
      hobby: true,
      actual: false,
      learning: false
    },
    {
      title: "Lumen PHP",
      desc: "minimal PHP framework",
      prod: true,
      hobby: false,
      actual: false
    },
    {
      title: "ES6",
      desc: "javaScript language update",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "ES7",
      desc: "javaScript language update",
      prod: true,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "Sublime Text 2/3",
      desc: "text editor",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "JavaScript",
      desc: "glorious programming language",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "VIM",
      desc: "terminal text editor",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Mailgun",
      desc: "transactional email API",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "SendGrid",
      desc: "transactional email API",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Terminal & CLIs",
      desc: "command-line interfaces",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "WordPress",
      desc: "PHP website & CMS software",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Vagrant",
      desc: "development environments",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Docker",
      desc: "containerization platform",
      prod: false,
      hobby: false,
      learning: true,
      actual: false
    },
    {
      title: "Microsoft Bot Framework",
      desc: "framework for building chatbots",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Facebook Graph & Marketing APIs",
      desc: "Facebook integrations SDKs",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "PostgreSQL",
      desc: "database system",
      prod: true,
      hobby: false,
      actual: false
    },
    {
      title: "Let's Encrypt",
      desc: "certificate authority",
      prod: true,
      hobby: false,
      actual: true
    },
    {
      title: "Firebase",
      desc: "mobile and web application development platform",
      prod: true,
      hobby: true,
      actual: true
    }
  ]
};
<commit_msg>this is fun<commit_after>export default {
  TechSkills: [
    {
      title: "PHP",
      desc: "server-side programming langauge",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "NodeJS",
      desc: "javaScript server-side runtime back-end",
      prod: true,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "Git",
      desc: "source code versioning",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Laravel PHP",
      desc: "modern PHP framework",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Gulp",
      desc: "automation toolkit (task runner)",
      prod: true,
      actual: false,
      hobby: true
    },
    {
      title: "Grunt",
      desc: "javascript Task Runner",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Webpack",
      desc: "javascript Module bundler",
      prod: true,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "TypeScript",
      desc: "typed superset of Javascript",
      prod: true,
      hobby: false,
      actual: false
    },
    {
      title: "AngularJS",
      desc: "front-end JavaScript library framework",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Angular",
      desc: "monolithic JavaScript framework",
      prod: true,
      hobby: false,
      actual: false
    },
    {
      title: "React",
      desc: "javaScript library for building user interfaces",
      prod: true,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "MySQL",
      desc: "relational database system",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "SCSS",
      desc: "style sheet language",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Nginx",
      desc: "modern server",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Python",
      desc: "server-side programming language",
      prod: false,
      hobby: true,
      actual: true
    },
    {
      title: "Scrum",
      desc: "agile framework for completing complex projects",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "React Native",
      desc: "build native mobile apps using JavaScript and React",
      prod: false,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "Google Cloud Platform",
      desc: "cloud-based scalable infrastructure",
      prod: true,
      hobby: false,
      actual: true
    },
    {
      title: "Heroku",
      desc: "cloud-based application hosting",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Digital Ocean",
      desc: "cloud computing platform",
      prod: true,
      hobby: true
    },
    {
      title: "Google Analytics",
      desc: "web analytics service",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Adobe Analytics (Omniture)",
      desc: "web analytics service",
      prod: true,
      hobby: false,
      actual: true
    },
    {
      title: "CoffeeScript",
      desc: "javaScript subset language",
      prod: true,
      hobby: true,
      legacy: true,
      actual: false
    },
    {
      title: "Sketch",
      desc: "design toolkit",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Amazon Alexa",
      desc: "voice service framework",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Wit.AI",
      desc: "natural language API",
      prod: true,
      hobby: true
    },
    {
      title: "Visual Studio Code",
      desc: "text editor",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Zeit's Now",
      desc: "realtime global deployments",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Go Language",
      desc: "programming language",
      prod: false,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "Apache Cordova",
      desc: "mobile development framework",
      prod: true,
      hobby: true,
      actual: false,
      learning: false
    },
    {
      title: "C++",
      desc: "programming language",
      prod: false,
      hobby: true,
      actual: false,
      learning: false
    },
    {
      title: "Swift",
      desc: "programming language",
      prod: false,
      hobby: true,
      actual: false,
      learning: false
    },
    {
      title: "Lumen PHP",
      desc: "minimal PHP framework",
      prod: true,
      hobby: false,
      actual: false
    },
    {
      title: "ES6",
      desc: "javaScript language update",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "ES7",
      desc: "javaScript language update",
      prod: true,
      hobby: true,
      actual: true,
      learning: true
    },
    {
      title: "Sublime Text 2/3",
      desc: "text editor",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "JavaScript",
      desc: "glorious programming language",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "VIM",
      desc: "terminal text editor",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "Mailgun",
      desc: "transactional email API",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "SendGrid",
      desc: "transactional email API",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Terminal & CLIs",
      desc: "command-line interfaces",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "WordPress",
      desc: "PHP website & CMS software",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Vagrant",
      desc: "development environments",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Docker",
      desc: "containerization platform",
      prod: false,
      hobby: false,
      learning: true,
      actual: false
    },
    {
      title: "Microsoft Bot Framework",
      desc: "framework for building chatbots",
      prod: true,
      hobby: true,
      actual: false
    },
    {
      title: "Facebook Graph & Marketing APIs",
      desc: "Facebook integrations SDKs",
      prod: true,
      hobby: true,
      actual: true
    },
    {
      title: "PostgreSQL",
      desc: "database system",
      prod: true,
      hobby: false,
      actual: false
    },
    {
      title: "Let's Encrypt",
      desc: "certificate authority",
      prod: true,
      hobby: false,
      actual: true
    },
    {
      title: "Firebase",
      desc: "mobile and web application development platform",
      prod: true,
      hobby: true,
      actual: true
    }
  ]
};
<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
"use strict";
/*exported _gpfArraySlice*/
/*#endif*/

var _gpfArrayPrototypeSlice = Array.prototype.slice;

/**
 * Slice an array-like object
 *
 * @param {Object} array array-like parameter (arguments, Array)
 * @param {Number} from
 * @param {Number} [to=undefined] to
 * @return {Array}
 */
function _gpfArraySlice (array, from, to) {
    return _gpfArrayPrototypeSlice.apply(array, [from || 0, to || array.length + 1]);
}

if (undefined === Array.prototype.every) {

    // Introduced with JavaScript 1.6
    Array.prototype.every = function (callback, thisArg) {
        var len = this.length,
            idx;
        for (idx = 0; idx < len; ++idx) {
            if (!callback.apply(thisArg, [this[idx], idx, this])) {
                return false;
            }
        }
        return true;
    };
}

if (undefined === Array.prototype.filter) {

    // Introduced with JavaScript 1.6
    Array.prototype.filter = function (callback, thisArg) {
        var result = [],
            len = this.length,
            idx,
            item;
        for (idx = 0; idx < len; ++idx) {
            item = this[idx];
            if (callback.apply(thisArg, [this[idx], idx, this])) {
                result.push(item);
            }
        }
        return result;
    };
}

if (undefined === Array.prototype.forEach) {

    // Introduced with JavaScript 1.6
    Array.prototype.forEach = function (callback, thisArg) {
        var len = this.length,
            idx;
        for (idx = 0; idx < len; ++idx) {
            callback.apply(thisArg, [this[idx], idx, this]);
        }
    };
}

if (undefined === Array.prototype.indexOf) {

    // Introduced with JavaScript 1.5
    Array.prototype.indexOf = function (searchElement, fromIndex) {
        var index = fromIndex || 0,
            thisLength = this.length;
        while (index < thisLength) {
            if (this[index] === searchElement) {
                return index;
            }
            ++index;
        }
        return -1;
    };

}

if (undefined === Array.prototype.map) {

    // Introduced with JavaScript 1.6
    Array.prototype.map = function (callback, thisArg) {
        var thisLength = this.length,
            result = new Array(thisLength),
            index;
        for (index = 0; index < thisLength; ++index) {
            result[index] = callback.apply(thisArg, [this[index], index, this]);
        }
        return result;
    };

}

if (undefined === Array.prototype.reduce) {

    // Introduced with JavaScript 1.8
    Array.prototype.reduce = function (callback, initialValue) {
        var thisLength = this.length,
            index = 0,
            value;
        if (undefined === initialValue) {
            value = this[index++];
        } else {
            value = initialValue;
        }
        for (; index < thisLength; ++index) {
            value = callback(value, this[index], index, this);
        }
        return value;
    };

}

if (undefined === Function.prototype.bind) {

    // Introduced with JavaScript 1.8.5
    Function.prototype.bind = function (thisArg) {
        var thisFunction = this,
            prependArgs = _gpfArraySlice(arguments, 1);
        return function() {
            var args = _gpfArraySlice(arguments, 0);
            thisFunction.apply(thisArg, prependArgs.concat(args));
        };
    };

}

// Handling function name properly
if ((function () {
    function functionName() {}
    return functionName.name !== "functionName";
})()) {

    (function () {

        var comments = new RegExp("//.*$|/\\*.*\\*/", "g");

        Function.prototype.compatibleName = function () {
            // Use simple parsing as a first step
            // TODO leverage JS parser to implement this properly
            var functionSource = Function.prototype.toString.apply(this),
                functionKeywordPos = functionSource.indexOf("function"),
                parameterListStartPos = functionSource.indexOf("(", functionKeywordPos);
            return functionSource
                    .substr(functionKeywordPos + 9, parameterListStartPos - functionKeywordPos - 9)
                    .replace(comments, "") // remove comments
                    .trim();
        };

    }());

} else {

    /**
     * Return function name
     *
     * @return {String}
     */
    Function.prototype.compatibleName = function () {
        return this.name;
    };

}

/*eslint-disable no-proto*/ // Used for compatibility reasons

if (undefined === Object.create) {

    /*jshint -W103*/
    Object.create = (function() {
        function Temp() {}
        return function (O) {
            Temp.prototype = O;
            var obj = new Temp();
            Temp.prototype = null;
            if (!obj.__proto__) {
                obj.__proto__ = O;
            }
            return obj;
        };
    }());

}

if (undefined === Object.getPrototypeOf) {

    Object.getPrototypeOf = function (object){
        // May break if the constructor has been tampered with
        return object.__proto__ || object.constructor.prototype;
    };
    /*jshint +W103*/

}

if (undefined === String.prototype.trim) {

    // Introduced with JavaScript 1.8.1
    (function () {
        var rtrim = new RegExp("^[\\s\uFEFF\xA0]+|[\\s\uFEFF\xA0]+$", "g");
        String.prototype.trim = function() {
            return this.replace(rtrim, "");
        };
    }());

}
<commit_msg>ESLint fixes<commit_after>/*#ifndef(UMD)*/
"use strict";
/*exported _gpfArraySlice*/
/*#endif*/

var _gpfArrayPrototypeSlice = Array.prototype.slice;

/**
 * Slice an array-like object
 *
 * @param {Object} array array-like parameter (arguments, Array)
 * @param {Number} from
 * @param {Number} [to=undefined] to
 * @return {Array}
 */
function _gpfArraySlice (array, from, to) {
    return _gpfArrayPrototypeSlice.apply(array, [from || 0, to || array.length + 1]);
}

if (undefined === Array.prototype.every) {

    // Introduced with JavaScript 1.6
    Array.prototype.every = function (callback, thisArg) {
        var len = this.length,
            idx;
        for (idx = 0; idx < len; ++idx) {
            if (!callback.apply(thisArg, [this[idx], idx, this])) {
                return false;
            }
        }
        return true;
    };
}

if (undefined === Array.prototype.filter) {

    // Introduced with JavaScript 1.6
    Array.prototype.filter = function (callback, thisArg) {
        var result = [],
            len = this.length,
            idx,
            item;
        for (idx = 0; idx < len; ++idx) {
            item = this[idx];
            if (callback.apply(thisArg, [this[idx], idx, this])) {
                result.push(item);
            }
        }
        return result;
    };
}

if (undefined === Array.prototype.forEach) {

    // Introduced with JavaScript 1.6
    Array.prototype.forEach = function (callback, thisArg) {
        var len = this.length,
            idx;
        for (idx = 0; idx < len; ++idx) {
            callback.apply(thisArg, [this[idx], idx, this]);
        }
    };
}

if (undefined === Array.prototype.indexOf) {

    // Introduced with JavaScript 1.5
    Array.prototype.indexOf = function (searchElement, fromIndex) {
        var index = fromIndex || 0,
            thisLength = this.length;
        while (index < thisLength) {
            if (this[index] === searchElement) {
                return index;
            }
            ++index;
        }
        return -1;
    };

}

if (undefined === Array.prototype.map) {

    // Introduced with JavaScript 1.6
    Array.prototype.map = function (callback, thisArg) {
        var thisLength = this.length,
            result = new Array(thisLength),
            index;
        for (index = 0; index < thisLength; ++index) {
            result[index] = callback.apply(thisArg, [this[index], index, this]);
        }
        return result;
    };

}

if (undefined === Array.prototype.reduce) {

    // Introduced with JavaScript 1.8
    Array.prototype.reduce = function (callback, initialValue) {
        var thisLength = this.length,
            index = 0,
            value;
        if (undefined === initialValue) {
            value = this[index++];
        } else {
            value = initialValue;
        }
        for (; index < thisLength; ++index) {
            value = callback(value, this[index], index, this);
        }
        return value;
    };

}

if (undefined === Function.prototype.bind) {

    // Introduced with JavaScript 1.8.5
    Function.prototype.bind = function (thisArg) {
        var me = this,
            prependArgs = _gpfArraySlice(arguments, 1);
        return function() {
            var args = _gpfArraySlice(arguments, 0);
            me.apply(thisArg, prependArgs.concat(args));
        };
    };

}

// Handling function name properly
if ((function () {
    function functionName() {}
    return functionName.name !== "functionName";
})()) {

    (function () {

        var comments = new RegExp("//.*$|/\\*.*\\*/", "g");

        Function.prototype.compatibleName = function () {
            // Use simple parsing as a first step
            // TODO leverage JS parser to implement this properly
            var functionSource = Function.prototype.toString.apply(this),
                functionKeywordPos = functionSource.indexOf("function"),
                parameterListStartPos = functionSource.indexOf("(", functionKeywordPos);
            return functionSource
                    .substr(functionKeywordPos + 9, parameterListStartPos - functionKeywordPos - 9)
                    .replace(comments, "") // remove comments
                    .trim();
        };

    }());

} else {

    /**
     * Return function name
     *
     * @return {String}
     */
    Function.prototype.compatibleName = function () {
        return this.name;
    };

}

/*eslint-disable no-proto*/ // Used for compatibility reasons

if (undefined === Object.create) {

    /*jshint -W103*/
    Object.create = (function() {
        function Temp() {}
        return function (O) {
            Temp.prototype = O;
            var obj = new Temp();
            Temp.prototype = null;
            if (!obj.__proto__) {
                obj.__proto__ = O;
            }
            return obj;
        };
    }());

}

if (undefined === Object.getPrototypeOf) {

    Object.getPrototypeOf = function (object){
        // May break if the constructor has been tampered with
        return object.__proto__ || object.constructor.prototype;
    };
    /*jshint +W103*/

}

if (undefined === String.prototype.trim) {

    // Introduced with JavaScript 1.8.1
    (function () {
        var rtrim = new RegExp("^[\\s\uFEFF\xA0]+|[\\s\uFEFF\xA0]+$", "g");
        String.prototype.trim = function() {
            return this.replace(rtrim, "");
        };
    }());

}
<|endoftext|>


<commit_before>/*
 * typeahead.js
 * https://github.com/twitter/typeahead
 * Copyright 2013 Twitter, Inc. and other contributors; Licensed MIT
 */

var Dataset = (function() {
  var keys;

  keys = { data: 'data', protocol: 'protocol', thumbprint: 'thumbprint' };

  // constructor
  // -----------

  function Dataset(o) {
    if (!o || (!o.local && !o.prefetch && !o.remote)) {
      $.error('one of local, prefetch, or remote is required');
    }

    this.name = o.name || _.getUniqueId();
    this.limit = o.limit || 5;
    this.valueKey = o.valueKey || 'value';
    this.dupChecker = getDupChecker(o.dupChecker);
    this.sorter = getSorter(o.sorter);

    this.local = getLocal(o);
    this.prefetch = getPrefetch(o);
    this.remote = getRemote(o);

    // the backing data structure used for fast pattern matching
    this.index = new SearchIndex();

    // only initialize storage if there's a name otherwise
    // loading from storage on subsequent page loads is impossible
    this.storage = o.name ? new PersistentStorage(o.name) : null;
  }

  // instance methods
  // ----------------

  _.mixin(Dataset.prototype, {

    // ### private

    _loadPrefetch: function loadPrefetch(o) {
      var that = this, serialized, deferred;

      if (serialized = this._readFromStorage(o.thumbprint)) {
        this.index.bootstrap(serialized);
        deferred = $.Deferred().resolve();
      }

      else {
        deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse);
      }

      return deferred;

      function handlePrefetchResponse(resp) {
        var filtered, normalized;

        filtered = o.filter ? o.filter(resp) : resp;
        that.add(filtered);

        that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl);
      }
    },

    _getFromRemote: function getFromRemote(query, cb) {
      var that = this, url, uriEncodedQuery;

      query = query || '';

      uriEncodedQuery = encodeURIComponent(query);

      url = this.remote.replace ?
        this.remote.replace(this.remote.url, query) :
        this.remote.url.replace(this.remote.wildcard, uriEncodedQuery);

      return this.transport.get(url, this.remote.ajax, handleRemoteResponse);

      function handleRemoteResponse(resp) {
        var filtered = that.remote.filter ? that.remote.filter(resp) : resp;

        cb(that._normalize(filtered));
      }
    },

    _normalize: function normalize(data) {
      var that = this;

      return _.map(data, normalizeRawDatum);

      function normalizeRawDatum(raw) {
        var value, datum;

        value = _.isString(raw) ? raw : raw[that.valueKey];
        datum = { value: value };

        _.isString(raw) ?
          (datum.raw = {})[that.valueKey] = raw :
          datum.raw = raw;

        return datum;
      }
    },

    _saveToStorage: function saveToStorage(data, thumbprint, ttl) {
      if (this.storage) {
        this.storage.set(keys.data, data, ttl);
        this.storage.set(keys.protocol, location.protocol, ttl);
        this.storage.set(keys.thumbprint, thumbprint, ttl);
      }
    },

    _readFromStorage: function readFromStorage(thumbprint) {
      var stored = {};

      if (this.storage) {
        stored.data = this.storage.get(keys.data);
        stored.protocol = this.storage.get(keys.protocol);
        stored.thumbprint = this.storage.get(keys.thumbprint);
      }
      // the stored data is considered expired if the thumbprints
      // don't match or if the protocol it was originally stored under
      // has changed
      isExpired = stored.thumbprint !== thumbprint ||
        stored.protocol !== location.protocol;

      return stored.data && !isExpired ? stored.data : null;
    },

    // ### public

    // the contents of this function are broken out of the constructor
    // to help improve the testability of datasets
    initialize: function initialize() {
      var that = this, deferred;

      deferred = this.prefetch ?
        this._loadPrefetch(this.prefetch) : $.Deferred().resolve();

      // make sure local is added to the index after prefetch
      this.local && deferred.done(addLocalToIndex);

      this.transport = this.remote ? new Transport(this.remote) : null;
      this.initialize = function initialize() { return deferred; };

      return deferred;

      function addLocalToIndex() { that.add(that.local); }
    },

    add: function add(data) {
      var normalized;

      data = _.isArray(data) ? data : [data];
      normalized = this._normalize(data);

      this.index.add(normalized);
    },

    get: function get(query, cb) {
      var that = this, matches, cacheHit = false;

      matches = this.index.get(query).sort(this.sorter).slice(0, this.limit);

      if (matches.length < this.limit && this.transport) {
        cacheHit = this._getFromRemote(query, returnRemoteMatches);
      }

      // if a cache hit occurred, skip rendering local matches
      // because the rendering of local/remote matches is already
      // in the event loop
      !cacheHit && cb && cb(matches);

      function returnRemoteMatches(remoteMatches) {
        var matchesWithBackfill = matches.slice(0);

        _.each(remoteMatches, function(remoteMatch) {
          var isDuplicate;

          // checks for duplicates
          isDuplicate = _.some(matchesWithBackfill, function(match) {
            return that.dupChecker(remoteMatch, match);
          });

          !isDuplicate && matchesWithBackfill.push(remoteMatch);

          // if we're at the limit, we no longer need to process
          // the remote results and can break out of the each loop
          return matchesWithBackfill.length < that.limit;
        });

        cb && cb(matchesWithBackfill.sort(this.sorter));
      }
    }
  });

  return Dataset;

  // helper functions
  // ----------------

  function getSorter(sorter) {
    return sorter || defaultSorter;

    function defaultSorter() { return 0; }
  }

  function getDupChecker(dupChecker) {
    if (!_.isFunction(dupChecker)) {
      dupChecker = dupChecker === false ? ignoreDups : standardDupChecker;
    }

    return dupChecker;

    function ignoreDups() { return false; }
    function standardDupChecker(a, b) { return a.value === b.value; }
  }

  function getLocal(o) {
    return o.local || null;
  }

  function getPrefetch(o) {
    var prefetch, defaults;

    defaults = {
      url: null,
      thumbprint: '',
      ttl: 24 * 60 * 60 * 1000, // 1 day
      filter: null,
      ajax: {}
    };

    if (prefetch = o.prefetch || null) {
      // support basic (url) and advanced configuration
      prefetch = _.isString(prefetch) ? { url: prefetch } : prefetch;

      prefetch = _.mixin(defaults, prefetch);
      prefetch.thumbprint = VERSION + prefetch.thumbprint;

      prefetch.ajax.method = prefetch.ajax.method || 'get';
      prefetch.ajax.dataType = prefetch.ajax.dataType || 'json';
    }

    return prefetch;
  }

  function getRemote(o) {
    var remote, defaults;

    defaults = {
      url: null,
      wildcard: '%QUERY',
      replace: null,
      rateLimitBy: 'debounce',
      rateLimitWait: 300,
      send: null,
      filter: null,
      ajax: {}
    };

    if (remote = o.remote || null) {
      // support basic (url) and advanced configuration
      remote = _.isString(remote) ? { url: remote } : remote;

      remote = _.mixin(defaults, remote);
      remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ?
        byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait);

      remote.ajax.method = remote.ajax.method || 'get';
      remote.ajax.dataType = remote.ajax.dataType || 'json';

      delete remote.rateLimitBy;
      delete remote.rateLimitWait;
    }

    return remote;

    function byDebounce(wait) {
      return function(fn) { return _.debounce(fn, wait); };
    }

    function byThrottle(wait) {
      return function(fn) { return _.throttle(fn, wait); };
    }
  }
})();
<commit_msg>Expose Dataset globally.<commit_after>/*
 * typeahead.js
 * https://github.com/twitter/typeahead
 * Copyright 2013 Twitter, Inc. and other contributors; Licensed MIT
 */

var Dataset = window.Dataset = (function() {
  var keys;

  keys = { data: 'data', protocol: 'protocol', thumbprint: 'thumbprint' };

  // constructor
  // -----------

  function Dataset(o) {
    if (!o || (!o.local && !o.prefetch && !o.remote)) {
      $.error('one of local, prefetch, or remote is required');
    }

    this.name = o.name || _.getUniqueId();
    this.limit = o.limit || 5;
    this.valueKey = o.valueKey || 'value';
    this.dupChecker = getDupChecker(o.dupChecker);
    this.sorter = getSorter(o.sorter);

    this.local = getLocal(o);
    this.prefetch = getPrefetch(o);
    this.remote = getRemote(o);

    // the backing data structure used for fast pattern matching
    this.index = new SearchIndex();

    // only initialize storage if there's a name otherwise
    // loading from storage on subsequent page loads is impossible
    this.storage = o.name ? new PersistentStorage(o.name) : null;
  }

  // instance methods
  // ----------------

  _.mixin(Dataset.prototype, {

    // ### private

    _loadPrefetch: function loadPrefetch(o) {
      var that = this, serialized, deferred;

      if (serialized = this._readFromStorage(o.thumbprint)) {
        this.index.bootstrap(serialized);
        deferred = $.Deferred().resolve();
      }

      else {
        deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse);
      }

      return deferred;

      function handlePrefetchResponse(resp) {
        var filtered, normalized;

        filtered = o.filter ? o.filter(resp) : resp;
        that.add(filtered);

        that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl);
      }
    },

    _getFromRemote: function getFromRemote(query, cb) {
      var that = this, url, uriEncodedQuery;

      query = query || '';

      uriEncodedQuery = encodeURIComponent(query);

      url = this.remote.replace ?
        this.remote.replace(this.remote.url, query) :
        this.remote.url.replace(this.remote.wildcard, uriEncodedQuery);

      return this.transport.get(url, this.remote.ajax, handleRemoteResponse);

      function handleRemoteResponse(resp) {
        var filtered = that.remote.filter ? that.remote.filter(resp) : resp;

        cb(that._normalize(filtered));
      }
    },

    _normalize: function normalize(data) {
      var that = this;

      return _.map(data, normalizeRawDatum);

      function normalizeRawDatum(raw) {
        var value, datum;

        value = _.isString(raw) ? raw : raw[that.valueKey];
        datum = { value: value };

        _.isString(raw) ?
          (datum.raw = {})[that.valueKey] = raw :
          datum.raw = raw;

        return datum;
      }
    },

    _saveToStorage: function saveToStorage(data, thumbprint, ttl) {
      if (this.storage) {
        this.storage.set(keys.data, data, ttl);
        this.storage.set(keys.protocol, location.protocol, ttl);
        this.storage.set(keys.thumbprint, thumbprint, ttl);
      }
    },

    _readFromStorage: function readFromStorage(thumbprint) {
      var stored = {};

      if (this.storage) {
        stored.data = this.storage.get(keys.data);
        stored.protocol = this.storage.get(keys.protocol);
        stored.thumbprint = this.storage.get(keys.thumbprint);
      }
      // the stored data is considered expired if the thumbprints
      // don't match or if the protocol it was originally stored under
      // has changed
      isExpired = stored.thumbprint !== thumbprint ||
        stored.protocol !== location.protocol;

      return stored.data && !isExpired ? stored.data : null;
    },

    // ### public

    // the contents of this function are broken out of the constructor
    // to help improve the testability of datasets
    initialize: function initialize() {
      var that = this, deferred;

      deferred = this.prefetch ?
        this._loadPrefetch(this.prefetch) : $.Deferred().resolve();

      // make sure local is added to the index after prefetch
      this.local && deferred.done(addLocalToIndex);

      this.transport = this.remote ? new Transport(this.remote) : null;
      this.initialize = function initialize() { return deferred; };

      return deferred;

      function addLocalToIndex() { that.add(that.local); }
    },

    add: function add(data) {
      var normalized;

      data = _.isArray(data) ? data : [data];
      normalized = this._normalize(data);

      this.index.add(normalized);
    },

    get: function get(query, cb) {
      var that = this, matches, cacheHit = false;

      matches = this.index.get(query).sort(this.sorter).slice(0, this.limit);

      if (matches.length < this.limit && this.transport) {
        cacheHit = this._getFromRemote(query, returnRemoteMatches);
      }

      // if a cache hit occurred, skip rendering local matches
      // because the rendering of local/remote matches is already
      // in the event loop
      !cacheHit && cb && cb(matches);

      function returnRemoteMatches(remoteMatches) {
        var matchesWithBackfill = matches.slice(0);

        _.each(remoteMatches, function(remoteMatch) {
          var isDuplicate;

          // checks for duplicates
          isDuplicate = _.some(matchesWithBackfill, function(match) {
            return that.dupChecker(remoteMatch, match);
          });

          !isDuplicate && matchesWithBackfill.push(remoteMatch);

          // if we're at the limit, we no longer need to process
          // the remote results and can break out of the each loop
          return matchesWithBackfill.length < that.limit;
        });

        cb && cb(matchesWithBackfill.sort(this.sorter));
      }
    }
  });

  return Dataset;

  // helper functions
  // ----------------

  function getSorter(sorter) {
    return sorter || defaultSorter;

    function defaultSorter() { return 0; }
  }

  function getDupChecker(dupChecker) {
    if (!_.isFunction(dupChecker)) {
      dupChecker = dupChecker === false ? ignoreDups : standardDupChecker;
    }

    return dupChecker;

    function ignoreDups() { return false; }
    function standardDupChecker(a, b) { return a.value === b.value; }
  }

  function getLocal(o) {
    return o.local || null;
  }

  function getPrefetch(o) {
    var prefetch, defaults;

    defaults = {
      url: null,
      thumbprint: '',
      ttl: 24 * 60 * 60 * 1000, // 1 day
      filter: null,
      ajax: {}
    };

    if (prefetch = o.prefetch || null) {
      // support basic (url) and advanced configuration
      prefetch = _.isString(prefetch) ? { url: prefetch } : prefetch;

      prefetch = _.mixin(defaults, prefetch);
      prefetch.thumbprint = VERSION + prefetch.thumbprint;

      prefetch.ajax.method = prefetch.ajax.method || 'get';
      prefetch.ajax.dataType = prefetch.ajax.dataType || 'json';
    }

    return prefetch;
  }

  function getRemote(o) {
    var remote, defaults;

    defaults = {
      url: null,
      wildcard: '%QUERY',
      replace: null,
      rateLimitBy: 'debounce',
      rateLimitWait: 300,
      send: null,
      filter: null,
      ajax: {}
    };

    if (remote = o.remote || null) {
      // support basic (url) and advanced configuration
      remote = _.isString(remote) ? { url: remote } : remote;

      remote = _.mixin(defaults, remote);
      remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ?
        byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait);

      remote.ajax.method = remote.ajax.method || 'get';
      remote.ajax.dataType = remote.ajax.dataType || 'json';

      delete remote.rateLimitBy;
      delete remote.rateLimitWait;
    }

    return remote;

    function byDebounce(wait) {
      return function(fn) { return _.debounce(fn, wait); };
    }

    function byThrottle(wait) {
      return function(fn) { return _.throttle(fn, wait); };
    }
  }
})();
<|endoftext|>


<commit_before>var chokidar = require("chokidar");
var _ = require("lodash");
var qfs = require("q-io/fs");
var Q = require("q");
var deep = require("q-deep");

function notify() {
    console.log("Generated", arguments);
}

function isDirectory(file) {
    return qfs.isDirectory(file);
}

function watch(files, callback, chokOptions) {
    var watcher = chokidar.watch(files, _.merge({
        ignoreInitial: true
    }), chokOptions);
    console.log("Watching ", files, chokOptions);
    var fn = function () {
        callback().catch(console.log).done(notify);
    };
    fn = _.throttle(fn, 1000);
    watcher.on("ready", function () {
        console.log("Watchers for ", files, " ready");
    });
    watcher.on("change", fn);
    watcher.on("add", fn);
    watcher.on("delete", fn);
}

/**
 *
 * @param files
 * @param callback
 * @param chokOptions addition options for chokidar
 */
function watchFilesOrDirs(files, callback, chokOptions) {
    console.log("file",files);
    // Divide files into "real" files and directories
    var groupsP = files.reduce(function(subresult, file) {
        return Q.all([subresult, qfs.isDirectory(file)]).spread(function(subresult, isDirectory) {

            if (isDirectory) {
                subresult.dirs.push(file)
            } else {
                subresult.files.push(file);
            }
            return subresult;
        });

    },Q({ files: [], dirs: []}));

    deep(groupsP).done(function(groups) {
        // Files must be watched with polling in order to solve problems with "atomic writes"
        watch(groups.files, callback, _.merge({
            usePolling: true
        },chokOptions));

        // Directories work well, even with "atomic writes"
        watch(groups.files, callback, chokOptions);

    });

}

module.exports = function (bootprint, swaggerFile, targetDir) {
    var options = bootprint.options;

    // Watch partial templates and swagger file
    var htmlDependencies = _.union(
        _.flatten(_.values(options.partials)),
        [swaggerFile]
    );
    console.log("swaggerfile",htmlDependencies);
    watchFilesOrDirs(htmlDependencies, function () {
        // swaggerFile must be read every time, since it is also on the watch-list
        return qfs.read(swaggerFile).catch(console.log).then(function (swaggerJson) {
            return bootprint.generateHtml(JSON.parse(swaggerJson), targetDir);
        });
    });

    // Watch less files and include paths
    var lessFiles = _.flatten([
        options.less.main_files,
        options.less.paths
    ]);
    watchFilesOrDirs(lessFiles,function() {
        return bootprint.generateCss();
    });

};<commit_msg>Fix watching directories<commit_after>var chokidar = require("chokidar");
var _ = require("lodash");
var qfs = require("q-io/fs");
var Q = require("q");
var deep = require("q-deep");

function notify() {
    console.log("Generated", arguments);
}

function isDirectory(file) {
    return qfs.isDirectory(file);
}

function watch(files, callback, chokOptions) {
    var watcher = chokidar.watch(files, _.merge({
        ignoreInitial: true
    }), chokOptions);
    console.log("Watching ", files, chokOptions);
    var fn = function () {
        callback().catch(console.log).done(notify);
    };
    fn = _.throttle(fn, 1000);
    watcher.on("ready", function () {
        console.log("Watchers for ", files, " ready");
    });
    watcher.on("change", fn);
    watcher.on("add", fn);
    watcher.on("delete", fn);
}

/**
 *
 * @param files
 * @param callback
 * @param chokOptions addition options for chokidar
 */
function watchFilesOrDirs(files, callback, chokOptions) {
    console.log("file",files);
    // Divide files into "real" files and directories
    var groupsP = files.reduce(function(subresult, file) {
        return Q.all([subresult, qfs.isDirectory(file)]).spread(function(subresult, isDirectory) {

            if (isDirectory) {
                subresult.dirs.push(file)
            } else {
                subresult.files.push(file);
            }
            return subresult;
        });

    },Q({ files: [], dirs: []}));

    deep(groupsP).done(function(groups) {
        // Files must be watched with polling in order to solve problems with "atomic writes"
        watch(groups.files, callback, _.merge({
            usePolling: true
        },chokOptions));

        // Directories work well, even with "atomic writes"
        watch(groups.dirs, callback, chokOptions);

    });

}

module.exports = function (bootprint, swaggerFile, targetDir) {
    var options = bootprint.options;

    // Watch partial templates and swagger file
    var htmlDependencies = _.union(
        _.flatten(_.values(options.partials)),
        [swaggerFile]
    );
    console.log("swaggerfile",htmlDependencies);
    watchFilesOrDirs(htmlDependencies, function () {
        // swaggerFile must be read every time, since it is also on the watch-list
        return qfs.read(swaggerFile).catch(console.log).then(function (swaggerJson) {
            return bootprint.generateHtml(JSON.parse(swaggerJson), targetDir);
        });
    });

    // Watch less files and include paths
    var lessFiles = _.flatten([
        options.less.main_files,
        options.less.paths
    ]);
    watchFilesOrDirs(lessFiles,function() {
        return bootprint.generateCss();
    });

};<|endoftext|>