<commit_before>var INDENTATION_PREFIX = '  ';

// A BlockExpression compiles an array of expressions down to a JavaScript
// function which returns the value of the last expression.
function BlockExpression(expressions) {
  this.expressions = expressions;
}

BlockExpression.prototype.compile = function() {
  var lines = [];
  for (var i = 0, len = this.expressions.length; i < len; ++i) {
    var expressionCode = this.expressions[i].compile() + ';';
    if (i === this.expressions.length - 1) {
      expressionCode = 'return ' + expressionCode;
    }
    lines.push(indentCode(expressionCode));
  }
  return '(function() {\n' + lines.join('\n') + '\n})()';
};

// A CommandExpression compiles a command down to a JavaScript function call.
function CommandExpression(tokens, lineNumber) {
  if (tokens.length === 0) {
    throw new CompileError('empty command cannot be compiled');
  }
  this.lineNumber = lineNumber;
  this.name = tokens[0];
  this.arguments = tokens.slice(1);
}

CommandExpression.prototype.compile = function() {
  var res = 'runtime.commands[' + this.name.compile() + '](' +
    this.lineNumber;
  for (var i = 0, len = this.arguments.length; i < len; ++i) {
    res += ', ' + this.arguments[i].compile();
  }
  return res + ')';
};

// A CompileError is triggered when compilation fails.
function CompileError(message, line) {
  this.message = message;
  this.line = line || -1;
}

CompileError.prototype.toString = function() {
  return 'line ' + this.line + ': ' + this.message;
};

// A ConditionExpression is a statement which compiles to a boolean expression.
function ConditionExpression(tokens) {
  if (tokens[0] === 'not') {
    tokens = tokens.slice(1);
    this.not = true;
  } else {
    this.not = false;
  }

  this.statements = [];
  for (var i = 0, len = tokens.length; i < len; ++i) {
    this.statements[i] = tokenToExpression(tokens[i]);
  }
}

ConditionExpression.prototype.compile = function() {
  if (this.statements.length === 0) {
    return this.not ? 'false' : 'true';
  } else if (this.statements.length === 1) {
    // The runtime.isEmpty function will check if a value is empty.
    return (this.not ? '' : '!') + 'runtime.isEmpty(' +
      this.statements[0].compile() + ')';
  } else {
    var res = (this.not ? '!' : '') + 'runtime.areAllEqual(';
    for (var i = 0, len = this.statements.length; i < len; ++i) {
      if (i !== 0) {
        res += ', ';
      }
      res += this.statements[i].compile();
    }
    return res + ')';
  }
};

// A ForExpression compiles a for loop down to a JavaScript expression.
function ForExpression(lineNumber, expression, body, variable, index) {
  this.lineNumber = lineNumber;
  this.expression = expression;
  this.body = body;
  this.variable = variable;
  this.index = index;
}

ForExpression.prototype.compile = function() {
  // var list = runtime.elements(...);
  // var result = "";
  var codeBeginning = 'var list = runtime.elements(' +
    this.expression.compile() + ');\nvar result = "";';

  var loopBeginning = 'for (var i = 0, len = list.length; i < len; ++i) {\n';

  var loopBody = [];
  if (this.index) {
    // runtime.commands.set(line#, ..., i);
    loopBody.push('runtime.commands.set(' + this.lineNumber + ', ' +
      this.index.compile() + ', i)');
  }
  if (this.variable) {
    // runtime.command.set(line#, ..., list[i]);
    loopBody.push('runtime.commands.set(' + this.lineNumber + ', ' +
      this.variable.compile(), ', list[i])');
  }
  loopBody.push('result = ' + this.body.compile() + ';');

  var loopCode = indentCode(loopBody.join('\n'));
  var functionBody = codeBeginning + loopBeginning + loopCode +
    '\n}\nreturn result;';

  return '(function() {\n' + indentCode(functionBody) + '\n})()';
};

// An IfExpression compiles to a JavaScript if statement wrapped in a function.
function IfExpression(conditions, branches) {
  this.conditions = conditions;
  this.branches = branches;
}

IfExpression.prototype.compile = function() {
  var res = '(function() {';
  for (var i = 0, len = this.conditions.length; i < len; ++i) {
    var condition = this.conditions[i];
    var branch = this.branches[i];
    var branchCode;
    if (i === 0) {
      branchCode = 'if (' + condition.compile() + ') {\n';
    } else {
      branchCode = '} else if (' + condition.compile() + ') {\n';
    }
    branchCode += indentCode('return ' + branch.compile());
    res += indentCode(branchCode) + '\n'
  }
  return res + indentCode('}') + '})()';
};

// A StringExpression compiles to a JavaScript string.
function StringExpression(str) {
  this.string = str;
}

StringExpression.prototype.compile = function() {
  return JSON.stringify(this.string);
};

// indentCode adds a level of indentation to a block of code.
function indentCode(code) {
  var lines = code.split('\n');
  for (var i = 0, len = lines.length; i < len; ++i) {
    lines[i] = INDENTATION_PREFIX + lines[i];
  }
  return lines.join('\n');
}

// tokenToExpression generates a StringExpression or CommandExpression from a
// token (which must be a string or array).
function tokenToExpression(token, lineNumber) {
  // The token is either a string or an array.
  if ('string' === typeof token) {
    return new StringExpression(token);
  } else {
    return new CommandExpression(token, lineNumber);
  }
}
<commit_msg>drafted WhileExpression<commit_after>var INDENTATION_PREFIX = '  ';

// A BlockExpression compiles an array of expressions down to a JavaScript
// function which returns the value of the last expression.
function BlockExpression(expressions) {
  this.expressions = expressions;
}

BlockExpression.prototype.compile = function() {
  var lines = [];
  for (var i = 0, len = this.expressions.length; i < len; ++i) {
    var expressionCode = this.expressions[i].compile() + ';';
    if (i === this.expressions.length - 1) {
      expressionCode = 'return ' + expressionCode;
    }
    lines.push(indentCode(expressionCode));
  }
  return '(function() {\n' + lines.join('\n') + '\n})()';
};

// A CommandExpression compiles a command down to a JavaScript function call.
function CommandExpression(tokens, lineNumber) {
  if (tokens.length === 0) {
    throw new CompileError('empty command cannot be compiled');
  }
  this.lineNumber = lineNumber;
  this.name = tokens[0];
  this.arguments = tokens.slice(1);
}

CommandExpression.prototype.compile = function() {
  var res = 'runtime.commands[' + this.name.compile() + '](' +
    this.lineNumber;
  for (var i = 0, len = this.arguments.length; i < len; ++i) {
    res += ', ' + this.arguments[i].compile();
  }
  return res + ')';
};

// A CompileError is triggered when compilation fails.
function CompileError(message, line) {
  this.message = message;
  this.line = line || -1;
}

CompileError.prototype.toString = function() {
  return 'line ' + this.line + ': ' + this.message;
};

// A ConditionExpression is a statement which compiles to a boolean expression.
function ConditionExpression(tokens) {
  if (tokens[0] === 'not') {
    tokens = tokens.slice(1);
    this.not = true;
  } else {
    this.not = false;
  }

  this.statements = [];
  for (var i = 0, len = tokens.length; i < len; ++i) {
    this.statements[i] = tokenToExpression(tokens[i]);
  }
}

ConditionExpression.prototype.compile = function() {
  if (this.statements.length === 0) {
    return this.not ? 'false' : 'true';
  } else if (this.statements.length === 1) {
    // The runtime.isEmpty function will check if a value is empty.
    return (this.not ? '' : '!') + 'runtime.isEmpty(' +
      this.statements[0].compile() + ')';
  } else {
    var res = (this.not ? '!' : '') + 'runtime.areAllEqual(';
    for (var i = 0, len = this.statements.length; i < len; ++i) {
      if (i !== 0) {
        res += ', ';
      }
      res += this.statements[i].compile();
    }
    return res + ')';
  }
};

// A ForExpression compiles a for loop down to a JavaScript expression.
function ForExpression(lineNumber, expression, body, variable, index) {
  this.lineNumber = lineNumber;
  this.expression = expression;
  this.body = body;
  this.variable = variable;
  this.index = index;
}

ForExpression.prototype.compile = function() {
  // var list = runtime.elements(...);
  // var result = "";
  var codeBeginning = 'var list = runtime.elements(' +
    this.expression.compile() + ');\nvar result = "";';

  var loopBeginning = 'for (var i = 0, len = list.length; i < len; ++i) {\n';

  var loopBody = [];
  if (this.index) {
    // runtime.commands.set(line#, ..., i);
    loopBody.push('runtime.commands.set(' + this.lineNumber + ', ' +
      this.index.compile() + ', i)');
  }
  if (this.variable) {
    // runtime.command.set(line#, ..., list[i]);
    loopBody.push('runtime.commands.set(' + this.lineNumber + ', ' +
      this.variable.compile(), ', list[i])');
  }
  loopBody.push('result = ' + this.body.compile() + ';');

  var loopCode = indentCode(loopBody.join('\n'));
  var functionBody = codeBeginning + loopBeginning + loopCode +
    '\n}\nreturn result;';

  return '(function() {\n' + indentCode(functionBody) + '\n})()';
};

// An IfExpression compiles to a JavaScript if statement wrapped in a function.
function IfExpression(conditions, branches) {
  this.conditions = conditions;
  this.branches = branches;
}

IfExpression.prototype.compile = function() {
  var res = '(function() {';
  for (var i = 0, len = this.conditions.length; i < len; ++i) {
    var condition = this.conditions[i];
    var branch = this.branches[i];
    var branchCode;
    if (i === 0) {
      branchCode = 'if (' + condition.compile() + ') {\n';
    } else {
      branchCode = '} else if (' + condition.compile() + ') {\n';
    }
    branchCode += indentCode('return ' + branch.compile());
    res += indentCode(branchCode) + '\n'
  }
  return res + indentCode('}') + '})()';
};

// A StringExpression compiles to a JavaScript string.
function StringExpression(str) {
  this.string = str;
}

StringExpression.prototype.compile = function() {
  return JSON.stringify(this.string);
};

// A WhileExpression compiles to a JavaScript while loop.
function WhileExpression(condition, body) {
  this.condition = condition;
  this.body = body;
}

WhileExpression.prototype.compile = function() {
  var loopHeader = 'var result = "";\nwhile (' + this.condition.compile() +
    ') {';
  var loopCode = 'result = ' + this.body.compile() + ';';
  var functionBody = loopHeader + '\n' + indentCode(loopCode) + '\n}\n' +
    'return result;';
  return '(function() {\n' + indentCode(functionBody) + '\n})()';
};

// indentCode adds a level of indentation to a block of code.
function indentCode(code) {
  var lines = code.split('\n');
  for (var i = 0, len = lines.length; i < len; ++i) {
    lines[i] = INDENTATION_PREFIX + lines[i];
  }
  return lines.join('\n');
}

// tokenToExpression generates a StringExpression or CommandExpression from a
// token (which must be a string or array).
function tokenToExpression(token, lineNumber) {
  // The token is either a string or an array.
  if ('string' === typeof token) {
    return new StringExpression(token);
  } else {
    return new CommandExpression(token, lineNumber);
  }
}
<|endoftext|>


<commit_before><commit_msg>allow multiple plugins to provide global options<commit_after><|endoftext|>


<commit_before>(function (Q, $, window, document, undefined) {

/**
 * Places Tools
 * @module Places-tools
 */

var Users = Q.Users;
var Streams = Q.Streams;
var Places = Q.Places;

/**
 * Allows the logged-in user to add his own locations and select among these locations
 * @class Places location
 * @constructor
 * @param {Object} [options] used to pass options
 * @param {String} [options.publisherId=Q.Users.loggedInUserId()] Override the publisherId
 *  for saving new locations.
 * @param {Object} [options.geocode] Default google location object, if available
 * @param {Places.Coordinates} [options.location] Provide a location to start off with.
 *  Can be anything that is accepted by Places.Coordinates constructor.
 * @param {Boolean} [options.showCurrent=true] Whether to allow user to select current location
 * @param {Boolean} [options.showLocations=true] Whether to allow user to select their saved locations
 * @param {Boolean} [options.showAddress=true] Whether to allow user to enter a custom address
 * @param {Q.Event} [options.onChoose] this event occurs when user selected some valid location
 */
Q.Tool.define("Places/location", function (options) {
	var tool = this;
	var state = this.state;
	var $te = $(tool.element);

	Q.addStylesheet('Q/plugins/Places/css/location.css');

	// change location event
	$te.on(Q.Pointer.click, "[data-location], .Places_location_preview_tool", function () {
		var $this = $(this);

		if ($this.hasClass('Q_selected')) {
			return false;
		}

		// set onChoose status to null
		Q.handle(state.onChoose, tool, [null]);

		// toggle Q_selected class
		$te.find(".Q_selected").removeClass("Q_selected");
		$this.addClass('Q_selected');

		var $olt = $this.find(tool.addressTool.element);
		if ($olt.length) {
			$olt.plugin('Q/placeholders', function () {
				tool.addressTool.filter.setText('');
				tool.addressTool.filter.$input.plugin('Q/clickfocus');
			});
		}

		var selector = $this.attr("data-location");
		if (selector == 'current') {
			tool.getCurrentPosition(function (pos) {
				var crd = pos.coords;
				if (!crd) {
					Q.alert("Places/location tool: could not obtain location", pos);
					return false;
				}
				Places.Coordinates.from({
					latitude: crd.latitude,
					longitude: crd.longitude
				}).geocode(function (err, results) {
					var loc = Q.getObject([0, 'geometry', 'location'], results);
					Q.handle(state.onChoose, tool, [loc, this]);
				});
			}, function (err) {
				Q.alert("Places/location tool: ERROR(" + err.code + "): " + err.message);
				return false;
			});

			return;
		} else if (selector == 'address') {
			// if address selected just repeat onChoose event of places/address tool
			Q.handle(
				tool.addressTool.state.onChoose,
				tool.addressTool,
				[tool.addressTool.place]
			);
			return;
		}

		// related location selected
		var locationPreviewTool = Q.Tool.from($this, "Streams/preview");
		var ls = locationPreviewTool.state;
		Streams.get(ls.publisherId, ls.streamName, function () {
			Places.Coordinates.from(this).geocode(function (err, results) {
				var loc = Q.getObject([0, 'geometry', 'location'], results);
				Q.handle(state.onChoose, tool, [loc, this]);
			});
		});
	});

	tool.refresh();
},

{ // default options here
	geocode: null,
	onChoose: new Q.Event(function (geocode) {
		this.state.location = geocode;
	}, 'Places/location'),
	location: null, // currently selected location
	showCurrent: true,
	showLocations: true,
	showAddress: true
},

{ // methods go here
	/**
	 * Refresh the display
	 * @method refresh
	 */
	refresh: function () {
		var tool = this;
		var state = tool.state;
		var $te = $(tool.element);

		// location empty - render standard location select template
		if (Q.isEmpty(state.location)) {
			tool.selectLocation();
			return;
		}

		// location already set in state - just type it
		Places.Coordinates.from(state.location).geocode(function (err, results) {
			var fem = Q.firstErrorMessage(err);
			if (fem) {
				// if something wrong with location
				// render standard location select template
				tool.selectLocation();

				return console.warn(fem);
			}

			var result = results[0];
			var address = result.formatted_address || result.address;
			$te.html(address).addClass("Q_selected");
			Q.handle(state.onChoose, tool, [result.geometry.location]);
		});
	},
	/**
	 * Render template with locations, so user can select one of them
	 * @method selectLocation
	 */
	selectLocation: function(){
		var tool = this;
		var state = tool.state;
		var $te = $(tool.element);
		var userId = Users.loggedInUserId();

		Q.Text.get('Places/content', function (err, text) {
			Q.Template.render('Places/location/select', Q.extend({
				text: text
			}, state), function (err, html) {
				$te.html(html).activate(function () {

					// set address tool
					tool.$(".Places_location_address")
					.tool('Places/address', {
						onChoose: _onChoose
					}, 'Places_address', tool.prefix)
					.activate(function () {
						tool.addressTool = this;
					});

					// set showLocations state.
					if (state.showLocations && userId) {
						tool.$(".Places_location_related")
							.tool('Streams/related', {
								publisherId: userId,
								streamName: 'Places/user/locations',
								relationType: 'Places/locations',
								isCategory: true
							}, tool.prefix + 'relatedLocations')
							.activate(function () {
								tool.relatedTool = this;
							});
					}

					function _onChoose(place) {
						if (!place || !place.id) {
							return Q.handle(state.onChoose, tool, [null]);
						}
						Places.Coordinates.from({
							placeId: place.id
						}).geocode(function (err, results) {
							var result = results[0];
							if (!result || !userId) {
								return;
							}
							var c = text.location.confirm;
							Q.confirm(c.message, function (shouldSave) {
								if (!shouldSave) {
									return;
								}
								var a = text.location.add;
								Q.prompt(a.prompt, function (title) {
									if (!title) {
										return;
									}
									Streams.create({
										publisherId: state.publisherId || userId,
										type: 'Places/location',
										title: title,
										attributes: {
											types: result.types,
											latitude: result.geometry.location.lat(),
											longitude: result.geometry.location.lng(),
											locationType: result.geometry.type
										},
										readLevel: 0,
										writeLevel: 0,
										adminLevel: 0
									}, function (err) {
										if (!err) {
											tool.relatedTool.refresh();
										}
									}, {
										publisherId: userId,
										streamName: 'Places/user/locations',
										type: 'Places/locations'
									});
								}, {
									title: a.title,
									placeholder: a.placeholder,
									ok: a.ok
								});
							}, {
								title: c.title,
								ok: c.ok,
								cancel: c.cancel
							});
							Q.handle(state.onChoose, tool, [result.geometry.location, this]);
						});
					}
				});
			}, {tool: tool});
		});
	},
	/**
	 * Get current geolocation
	 * @method getCurrentPosition
	 * @param {function} [success] Callback for success
	 * @param {function} [fail] Callback for fail
	 */
	getCurrentPosition: function (success, fail) {
		var tool = this;

		navigator.geolocation.getCurrentPosition(function (pos) {
			Q.handle(success, tool, [pos]);
		}, function (err) {
			Q.handle(fail, tool, [err]);
			console.warn("Places.location.getCurrentPosition: ERROR(" + err.code + "): " + err.message);
		}, {
			enableHighAccuracy: true, // need to set true to make it work consistently, it doesn't seem to make it any more accurate
			timeout: 5000,
			maximumAge: 0
		});
	}
});

Q.Template.set('Places/location/select',
	'{{#if showCurrent}}' +
		'
{{text.myCurrentLocation}}
' +
	'{{/if}}' +
	'{{#if showLocations}}' +
		'

' +
	'{{/if}}' +
	'{{#if showAddress}}' +
		'
' +
			'{{text.enterAddress}}' +
			'

' +
		'
' +
	'{{/if}}'
);

Q.Template.set("Places/location/new",
	'
' +
	'
<input placeholder="{{text.nameYourLocation}}" name="title">
' +
	'

' +
	'
<button class="Q_button" name="submit">{{text.action}}</button>
' +
	'
'
);

})(Q, jQuery, window, document);<commit_msg>Fixed bugs with wrong texts at Places/location tool. Also removed useless template "Places/location/new".<commit_after>(function (Q, $, window, document, undefined) {

/**
 * Places Tools
 * @module Places-tools
 */

var Users = Q.Users;
var Streams = Q.Streams;
var Places = Q.Places;

/**
 * Allows the logged-in user to add his own locations and select among these locations
 * @class Places location
 * @constructor
 * @param {Object} [options] used to pass options
 * @param {String} [options.publisherId=Q.Users.loggedInUserId()] Override the publisherId
 *  for saving new locations.
 * @param {Object} [options.geocode] Default google location object, if available
 * @param {Places.Coordinates} [options.location] Provide a location to start off with.
 *  Can be anything that is accepted by Places.Coordinates constructor.
 * @param {Boolean} [options.showCurrent=true] Whether to allow user to select current location
 * @param {Boolean} [options.showLocations=true] Whether to allow user to select their saved locations
 * @param {Boolean} [options.showAddress=true] Whether to allow user to enter a custom address
 * @param {Q.Event} [options.onChoose] this event occurs when user selected some valid location
 */
Q.Tool.define("Places/location", function (options) {
	var tool = this;
	var state = this.state;
	var $te = $(tool.element);

	Q.addStylesheet('Q/plugins/Places/css/location.css');

	// change location event
	$te.on(Q.Pointer.click, "[data-location], .Places_location_preview_tool", function () {
		var $this = $(this);

		if ($this.hasClass('Q_selected')) {
			return false;
		}

		// set onChoose status to null
		Q.handle(state.onChoose, tool, [null]);

		// toggle Q_selected class
		$te.find(".Q_selected").removeClass("Q_selected");
		$this.addClass('Q_selected');

		var $olt = $this.find(tool.addressTool.element);
		if ($olt.length) {
			$olt.plugin('Q/placeholders', function () {
				tool.addressTool.filter.setText('');
				tool.addressTool.filter.$input.plugin('Q/clickfocus');
			});
		}

		var selector = $this.attr("data-location");
		if (selector === 'current') {
			tool.getCurrentPosition(function (pos) {
				var crd = pos.coords;
				if (!crd) {
					Q.alert("Places/location tool: could not obtain location", pos);
					return false;
				}
				Places.Coordinates.from({
					latitude: crd.latitude,
					longitude: crd.longitude
				}).geocode(function (err, results) {
					var loc = Q.getObject([0, 'geometry', 'location'], results);
					Q.handle(state.onChoose, tool, [loc, this]);
				});
			}, function (err) {
				Q.alert("Places/location tool: ERROR(" + err.code + "): " + err.message);
				return false;
			});

			return;
		} else if (selector === 'address') {
			// if address selected just repeat onChoose event of places/address tool
			Q.handle(
				tool.addressTool.state.onChoose,
				tool.addressTool,
				[tool.addressTool.place]
			);
			return;
		}

		// related location selected
		var locationPreviewTool = Q.Tool.from($this, "Streams/preview");
		var ls = locationPreviewTool.state;
		Streams.get(ls.publisherId, ls.streamName, function () {
			Places.Coordinates.from(this).geocode(function (err, results) {
				var loc = Q.getObject([0, 'geometry', 'location'], results);
				Q.handle(state.onChoose, tool, [loc, this]);
			});
		});
	});

	tool.refresh();
},

{ // default options here
	geocode: null,
	onChoose: new Q.Event(function (geocode) {
		this.state.location = geocode;
	}, 'Places/location'),
	location: null, // currently selected location
	showCurrent: true,
	showLocations: true,
	showAddress: true
},

{ // methods go here
	/**
	 * Refresh the display
	 * @method refresh
	 */
	refresh: function () {
		var tool = this;
		var state = tool.state;
		var $te = $(tool.element);

		// location empty - render standard location select template
		if (Q.isEmpty(state.location)) {
			tool.selectLocation();
			return;
		}

		// location already set in state - just type it
		Places.Coordinates.from(state.location).geocode(function (err, results) {
			var fem = Q.firstErrorMessage(err);
			if (fem) {
				// if something wrong with location
				// render standard location select template
				tool.selectLocation();

				return console.warn(fem);
			}

			var result = results[0];
			var address = result.formatted_address || result.address;
			$te.html(address).addClass("Q_selected");
			Q.handle(state.onChoose, tool, [result.geometry.location]);
		});
	},
	/**
	 * Render template with locations, so user can select one of them
	 * @method selectLocation
	 */
	selectLocation: function(){
		var tool = this;
		var state = tool.state;
		var $te = $(tool.element);
		var userId = Users.loggedInUserId();

		Q.Text.get('Places/content', function (err, text) {
			Q.Template.render('Places/location/select', Q.extend({
				text: text
			}, state), function (err, html) {
				$te.html(html).activate(function () {

					// set address tool
					tool.$(".Places_location_address")
					.tool('Places/address', {
						onChoose: _onChoose
					}, 'Places_address', tool.prefix)
					.activate(function () {
						tool.addressTool = this;
					});

					// set showLocations state.
					if (state.showLocations && userId) {
						tool.$(".Places_location_related")
							.tool('Streams/related', {
								publisherId: userId,
								streamName: 'Places/user/locations',
								relationType: 'Places/locations',
								isCategory: true
							}, tool.prefix + 'relatedLocations')
							.activate(function () {
								tool.relatedTool = this;
							});
					}

					function _onChoose(place) {
						if (!place || !place.id) {
							return Q.handle(state.onChoose, tool, [null]);
						}
						Places.Coordinates.from({
							placeId: place.id
						}).geocode(function (err, results) {
							var result = results[0];
							if (!result || !userId) {
								return;
							}
							var textConfirm = text.location.confirm;
							Q.confirm(textConfirm.message, function (shouldSave) {
								if (!shouldSave) {
									return;
								}
								var textAdd = text.location.add;
								Q.prompt(textAdd.title, function (title) {
									if (!title) {
										return;
									}
									Streams.create({
										publisherId: state.publisherId || userId,
										type: 'Places/location',
										title: title,
										attributes: {
											types: result.types,
											latitude: result.geometry.location.lat(),
											longitude: result.geometry.location.lng(),
											locationType: result.geometry.type
										},
										readLevel: 0,
										writeLevel: 0,
										adminLevel: 0
									}, function (err) {
										if (!err) {
											tool.relatedTool.refresh();
										}
									}, {
										publisherId: userId,
										streamName: 'Places/user/locations',
										type: 'Places/locations'
									});
								}, {
									title: textAdd.title,
									placeholder: textAdd.placeholder,
									ok: textAdd.ok
								});
							}, {
								title: textConfirm.title,
								ok: textConfirm.ok,
								cancel: textConfirm.cancel
							});
							Q.handle(state.onChoose, tool, [result.geometry.location, this]);
						});
					}
				});
			}, {tool: tool});
		});
	},
	/**
	 * Get current geolocation
	 * @method getCurrentPosition
	 * @param {function} [success] Callback for success
	 * @param {function} [fail] Callback for fail
	 */
	getCurrentPosition: function (success, fail) {
		var tool = this;

		navigator.geolocation.getCurrentPosition(function (pos) {
			Q.handle(success, tool, [pos]);
		}, function (err) {
			Q.handle(fail, tool, [err]);
			console.warn("Places.location.getCurrentPosition: ERROR(" + err.code + "): " + err.message);
		}, {
			enableHighAccuracy: true, // need to set true to make it work consistently, it doesn't seem to make it any more accurate
			timeout: 5000,
			maximumAge: 0
		});
	}
});

Q.Template.set('Places/location/select',
	'{{#if showCurrent}}' +
		'
{{text.location.myCurrentLocation}}
' +
	'{{/if}}' +
	'{{#if showLocations}}' +
		'

' +
	'{{/if}}' +
	'{{#if showAddress}}' +
		'
' +
			'{{text.location.enterAddress}}' +
			'

' +
		'
' +
	'{{/if}}'
);
})(Q, jQuery, window, document);<|endoftext|>


<commit_before>/**
 * Example for creating and working with the Slack RTM API.
 */

/* eslint no-console:0 */

/*******************************************************************************
 * Globals
 */
const RtmClient = require('@slack/client').RtmClient;
const RTM_EVENTS = require('@slack/client').RTM_EVENTS;
const AWS = require('./AWS_API.js');
var rtm;

const token = process.env.SLACK_API_TOKEN || '';
const DEBUG = process.env.DEBUG || false;
AWS.DEBUG = DEBUG;

/*******************************************************************************
 * Functions
 */

var handleRtmMessage = function(message) {
    if (DEBUG) { console.log('Message:', message) }

    var text = message.text;

    if (keyMessage(text, 'aws ')) {
        text = text.substring('aws '.length, text.length);
        if (keyMessage(text, 'describe ec2 ')) {
            text = text.substring('describe ec2 '.length, text.length);
            if (keyMessage(text, 'instance ')) {
                AWS.checkEC2Instance(text.substring('instance '.length, text.length)).then(function (resp) {
                    rtm.sendMessage(resp, message.channel);
                }, function (err) {
                    rtm.sendMessage('Looks like there was a problem processing your request', message.channel);
                    console.log(err);
                });
            } else {
                AWS.checkEC2().then(function (resp) {
                    rtm.sendMessage(resp, message.channel);
                }, function (err) {
                    rtm.sendMessage('Looks like there was a problem processing your request', message.channel);
                    console.log(err);
                });
            }
        } else if (keyMessage(text, 'check number of instances ')) {
            AWS.checkNumInstances().then(function (resp) {
                rtm.sendMessage(resp, message.channel);
            }, function (err) {
                rtm.sendMessage('Looks like there was a problem processing your request', message.channel);
                console.log(err);
            });
        } else {
            rtm.sendMessage("I'm sorry, this isn't an AWS command I'm familiar with.", message.channel);
        }
    } else {
        rtm.sendMessage("I'm sorry, this isn't a command I'm familiar with.", message.channel);
    }
}

/*******************************************************************************
 * Helper functions
 */

function keyMessage(text, key) {
    var temptext = text + ' ';
    if (temptext.length >= key.length && temptext.substring(0, key.length).toLowerCase() === key) {
        return true;
    }
    return false;
}

/*******************************************************************************
 * Test stuff
 */
/*
Sample inputs:
aws describe ec2 instance i-0a681657adec3b3ee
aws describe ec2
 */
var mockRTM = function() {
    var readline = require('readline');
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    process.stdout.write("Please input your test message text: ");
    rl.on('line', function (line) {
        var message = {
            'text': line,
            'channel': 3
        };

        // mocking rtm
        rtm = {};
        rtm.sendMessage = function(message, channel) {
            console.log('----------Response message----------');
            console.log('Text: ' + message);
            console.log('Channel: ' + channel);
        }

        // run the test
        handleRtmMessage(message);
    });
}

/*******************************************************************************
 * main()
 */

var main = function() {
    rtm = new RtmClient(token);
    rtm.start();

    rtm.on(RTM_EVENTS.MESSAGE, handleRtmMessage);

    rtm.on(RTM_EVENTS.REACTION_ADDED, function handleRtmReactionAdded(reaction) {
        console.log('Reaction added:', reaction);
    });

    rtm.on(RTM_EVENTS.REACTION_REMOVED, function handleRtmReactionRemoved(reaction) {
        console.log('Reaction removed:', reaction);
    });
}

if (DEBUG) {
    mockRTM();
} else {
    main();
}<commit_msg>61 Create function to handle message promise<commit_after>/**
 * Example for creating and working with the Slack RTM API.
 */

/* eslint no-console:0 */

/*******************************************************************************
 * Globals
 */
const RtmClient = require('@slack/client').RtmClient;
const RTM_EVENTS = require('@slack/client').RTM_EVENTS;
const AWS = require('./AWS_API.js');
const token = process.env.SLACK_API_TOKEN || '';
const DEBUG = process.env.DEBUG || false;
AWS.DEBUG = DEBUG;

var rtm;
var problemMessage = 'Looks like there was a problem processing your request.';

/*******************************************************************************
 * Functions
 */

var handleRtmMessage = function(message) {
    if (DEBUG) { console.log('Message:', message) }

    var text = message.text;

    if (keyMessage(text, 'aws ')) {
        text = text.substring('aws '.length, text.length);
        if (keyMessage(text, 'check ec2 ')) {
            text = text.substring('check ec2 '.length, text.length);
            if (keyMessage(text, 'instance ')) {
                handleMessagePromise(AWS.checkEC2Instance(text.substring('instance '.length, text.length)), message);
            } else {
                handleMessagePromise(AWS.checkEC2(), message);
            }
        } else if (keyMessage(text, 'check number of instances ')) {
            handleMessagePromise(AWS.checkNumInstances(), message);
        } else {
            rtm.sendMessage("I'm sorry, this isn't an AWS command I'm familiar with.", message.channel);
        }
    } else {
        rtm.sendMessage("I'm sorry, this isn't a command I'm familiar with.", message.channel);
    }
}

/*******************************************************************************
 * Helper functions
 */

function keyMessage(text, key) {
    var temptext = text + ' ';
    if (temptext.length >= key.length && temptext.substring(0, key.length).toLowerCase() === key) {
        return true;
    }
    return false;
}

function handleMessagePromise(promise, message) {
    promise.then(function (resp) {
        rtm.sendMessage(resp, message.channel);
    }, function (err) {
        rtm.sendMessage(problemMessage, message.channel);
        console.log(err);
    });
}

/*******************************************************************************
 * Test stuff
 */
/*
Sample inputs:
aws describe ec2 instance i-0a681657adec3b3ee
aws describe ec2
 */
var mockRTM = function() {
    var readline = require('readline');
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    process.stdout.write("Please input your test message text: ");
    rl.on('line', function (line) {
        var message = {
            'text': line,
            'channel': 3
        };

        // mocking rtm
        rtm = {};
        rtm.sendMessage = function(message, channel) {
            console.log('----------Response message----------');
            console.log('Text: ' + message);
            console.log('Channel: ' + channel);
        }

        // run the test
        handleRtmMessage(message);
    });
}

/*******************************************************************************
 * main()
 */

var main = function() {
    rtm = new RtmClient(token);
    rtm.start();

    rtm.on(RTM_EVENTS.MESSAGE, handleRtmMessage);

    rtm.on(RTM_EVENTS.REACTION_ADDED, function handleRtmReactionAdded(reaction) {
        console.log('Reaction added:', reaction);
    });

    rtm.on(RTM_EVENTS.REACTION_REMOVED, function handleRtmReactionRemoved(reaction) {
        console.log('Reaction removed:', reaction);
    });
}

if (DEBUG) {
    mockRTM();
} else {
    main();
}<|endoftext|>


<commit_before>import path from 'path';
import resolve from 'resolve';
import { toLocalPath, toPosixPath, replaceExtension } from './utils';
import mapToRelative from './mapToRelative';

function findPathInRoots(sourcePath, rootDirs, cwd, extensions) {
  // Search the source path inside every custom root directory
  let resolvedSourceFile;
  rootDirs.some((dir) => {
    try {
      // check if the file exists (will throw if not)
      resolvedSourceFile = resolve.sync(`./${sourcePath}`, {
        basedir: path.resolve(cwd, dir),
        extensions,
      });
      return true;
    } catch (e) {
      return false;
    }
  });

  return resolvedSourceFile;
}

function getRealPathFromRootConfig(sourcePath, absCurrentFile, rootDirs, cwd, extensions) {
  const absFileInRoot = findPathInRoots(sourcePath, rootDirs, cwd, extensions);

  if (absFileInRoot) {
    const realSourceFileExtension = path.extname(absFileInRoot);
    const sourceFileExtension = path.extname(sourcePath);

    // map the source and keep its extension if the import/require had one
    const ext = realSourceFileExtension === sourceFileExtension ? realSourceFileExtension : '';
    return toLocalPath(toPosixPath(replaceExtension(
      mapToRelative(cwd, absCurrentFile, absFileInRoot),
      ext,
    )));
  }

  return null;
}

function getRealPathFromAliasConfig(sourcePath, absCurrentFile, alias, cwd) {
  const moduleSplit = sourcePath.split('/');

  let aliasPath;
  while (moduleSplit.length) {
    const m = moduleSplit.join('/');
    if ({}.hasOwnProperty.call(alias, m)) {
      aliasPath = alias[m];
      break;
    }
    moduleSplit.pop();
  }

  // no alias mapping found
  if (!aliasPath) {
    return null;
  }

  // remove legacy "npm:" prefix for npm packages
  aliasPath = aliasPath.replace(/^(npm:)/, '');
  const newPath = sourcePath.replace(moduleSplit.join('/'), aliasPath);

  // alias to npm module don't need relative mapping
  if (aliasPath[0] !== '.') {
    return newPath;
  }

  return toLocalPath(toPosixPath(mapToRelative(cwd, absCurrentFile, newPath)));
}

function getRealPathFromRegExpConfig(sourcePath, regExps) {
  let aliasedSourceFile;

  regExps.find(([regExp, substitute]) => {
    const execResult = regExp.exec(sourcePath);

    if (execResult === null) {
      return false;
    }

    aliasedSourceFile = substitute(execResult);
    return true;
  });

  return aliasedSourceFile;
}

export default function getRealPath(sourcePath, currentFile, opts) {
  if (sourcePath[0] === '.') {
    return sourcePath;
  }

  // file param is a relative path from the environment current working directory
  // (not from cwd param)
  const absCurrentFile = path.resolve(currentFile);

  const { cwd, extensions, pluginOpts } = opts;
  const rootDirs = pluginOpts.root || [];
  const regExps = pluginOpts.regExps;
  const alias = pluginOpts.alias || {};

  const sourceFileFromRoot = getRealPathFromRootConfig(
    sourcePath, absCurrentFile, rootDirs, cwd, extensions,
  );
  if (sourceFileFromRoot) {
    return sourceFileFromRoot;
  }

  const sourceFileFromAlias = getRealPathFromAliasConfig(
    sourcePath, absCurrentFile, alias, cwd,
  );
  if (sourceFileFromAlias) {
    return sourceFileFromAlias;
  }

  const sourceFileFromRegExp = getRealPathFromRegExpConfig(
    sourcePath, regExps,
  );
  if (sourceFileFromRegExp) {
    return sourceFileFromRegExp;
  }

  return sourcePath;
}
<commit_msg>fix: Fix `regExps.find` undefined error<commit_after>import path from 'path';
import resolve from 'resolve';
import { toLocalPath, toPosixPath, replaceExtension } from './utils';
import mapToRelative from './mapToRelative';

function findPathInRoots(sourcePath, rootDirs, cwd, extensions) {
  // Search the source path inside every custom root directory
  let resolvedSourceFile;
  rootDirs.some((dir) => {
    try {
      // check if the file exists (will throw if not)
      resolvedSourceFile = resolve.sync(`./${sourcePath}`, {
        basedir: path.resolve(cwd, dir),
        extensions,
      });
      return true;
    } catch (e) {
      return false;
    }
  });

  return resolvedSourceFile;
}

function getRealPathFromRootConfig(sourcePath, absCurrentFile, rootDirs, cwd, extensions) {
  const absFileInRoot = findPathInRoots(sourcePath, rootDirs, cwd, extensions);

  if (absFileInRoot) {
    const realSourceFileExtension = path.extname(absFileInRoot);
    const sourceFileExtension = path.extname(sourcePath);

    // map the source and keep its extension if the import/require had one
    const ext = realSourceFileExtension === sourceFileExtension ? realSourceFileExtension : '';
    return toLocalPath(toPosixPath(replaceExtension(
      mapToRelative(cwd, absCurrentFile, absFileInRoot),
      ext,
    )));
  }

  return null;
}

function getRealPathFromAliasConfig(sourcePath, absCurrentFile, alias, cwd) {
  const moduleSplit = sourcePath.split('/');

  let aliasPath;
  while (moduleSplit.length) {
    const m = moduleSplit.join('/');
    if ({}.hasOwnProperty.call(alias, m)) {
      aliasPath = alias[m];
      break;
    }
    moduleSplit.pop();
  }

  // no alias mapping found
  if (!aliasPath) {
    return null;
  }

  // remove legacy "npm:" prefix for npm packages
  aliasPath = aliasPath.replace(/^(npm:)/, '');
  const newPath = sourcePath.replace(moduleSplit.join('/'), aliasPath);

  // alias to npm module don't need relative mapping
  if (aliasPath[0] !== '.') {
    return newPath;
  }

  return toLocalPath(toPosixPath(mapToRelative(cwd, absCurrentFile, newPath)));
}

function getRealPathFromRegExpConfig(sourcePath, regExps) {
  let aliasedSourceFile;

  regExps.find(([regExp, substitute]) => {
    const execResult = regExp.exec(sourcePath);

    if (execResult === null) {
      return false;
    }

    aliasedSourceFile = substitute(execResult);
    return true;
  });

  return aliasedSourceFile;
}

export default function getRealPath(sourcePath, currentFile, opts) {
  if (sourcePath[0] === '.') {
    return sourcePath;
  }

  // file param is a relative path from the environment current working directory
  // (not from cwd param)
  const absCurrentFile = path.resolve(currentFile);

  const { cwd, extensions, pluginOpts } = opts;
  const rootDirs = pluginOpts.root || [];
  const regExps = pluginOpts.regExps || [];
  const alias = pluginOpts.alias || {};

  const sourceFileFromRoot = getRealPathFromRootConfig(
    sourcePath, absCurrentFile, rootDirs, cwd, extensions,
  );
  if (sourceFileFromRoot) {
    return sourceFileFromRoot;
  }

  const sourceFileFromAlias = getRealPathFromAliasConfig(
    sourcePath, absCurrentFile, alias, cwd,
  );
  if (sourceFileFromAlias) {
    return sourceFileFromAlias;
  }

  const sourceFileFromRegExp = getRealPathFromRegExpConfig(
    sourcePath, regExps,
  );
  if (sourceFileFromRegExp) {
    return sourceFileFromRegExp;
  }

  return sourcePath;
}
<|endoftext|>


<commit_before>/* Controllers */

function MyCtrl1() {}
MyCtrl1.$inject = [];

function DashboardController() {
	$scope.hypothesis_submit = function(){
      $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
      $http.defaults.headers.common['Content-Type'] = 'application/json'
      $http.defaults.headers.common['Accept'] = 'application/json'

      $http.post(
        '/api/v1/hypotheses',

        JSON.stringify({ $scope., company: $scope.company, password: $scope.password, password_confirm: $scope.password_confirm})
        ).success(
        function(data){
          // if success
          if (data['response']['user']){
                 $location.path("/onboarding/stick");
          }

          else{
            // TODO: brevity
            var errors = data['response']['errors'];
           }
          }
     	).error(
        function(data){
          console.log('registration error')
          alert(data)
          $scope.errorMsg = data.reason;
        }
      );
    };
  }

	$scope.new_hypothesis = function(){
	{
}

function CarouselController($scope, $location, $anchorScroll){
  $scope.scroll_to = function(id) {
    alert(id)
      $location.hash(id);
      $anchorScroll();
   }
}

function ErrorPageController(){
}

function OnboardingController(){
}

function StickController($scope, $http, GoogleAnalytics){
  var GAQuery = GoogleAnalytics.get();
  console.log(GAQuery);
  if (GAQuery.length > 0){
    $scope.GA = true;
  }
  $scope.has_GA = function(){
    if ($scope.GA){
      return true;
    }
  }
  $scope.GA_auth = function(){
    $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
    $http.post(
        '/connect/google-analytics'
        ).success(
        function(data){
          var status = data['status'];
          if (status == 100){
            var redirect_url = data['redirect_url'];
            window.location(redirect_url);
          }
        }
      )
    }
}

function ViralityController($scope, $http, Facebook, Twitter){
  $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
  var FBQuery = Facebook.get();
  var TwitterQuery = Twitter.get();

  if (FBQuery.length > 0){
    $scope.FB = true;
  }

  $scope.has_FB = function(){
    if ($scope.FB){
      return true;
    }
  }

  $scope.fb_auth = function(){
    $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
    $http.post(
        '/connect/facebook'
    ).success(
    	function(data){
			var redirect_url = data['redirect_url'];
			if (redirect_url != null){
				open(redirect_url);
			}
        }
    ).error(
        function(data){
          	console.log('error')
          	$scope.FB_error = "Facebook authentication failed."
        })
	}

  if (TwitterQuery['twitter_handle']){
    $scope.Twitter = true;
  }

  $scope.has_Twitter = function(){
    if ($scope.Twitter){
      return true;
    }
  }

  $scope.twitter_auth = function(){
    $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
    $http.post(
        '/connect/twitter'
        ).success(
        function(data){
          var status = data['status'];
          if (status == 100){
            var redirect_url = data['redirect_url'];
            open(redirect_url);
          }
        }
      ).error(
        function(data){
          $scope.twitter_error = "Twitter authentication failed."
        }
      )
    }

}

function PayController($scope){

}

var LWBApp = angular.module('LWBApp', ['ngRoute','http-auth-interceptor', 'LWBServices'],
  function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
}).controller({
  RegistrationController: function($scope, $http, authService, $location){
    $scope.submit = function(){
      $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
	  console.log(csrf_token);
      $http.defaults.headers.common['Content-Type'] = 'application/json'
      $http.defaults.headers.common['Accept'] = 'application/json'

      $http.post(
        '/registration',

        JSON.stringify({email: $scope.email, company: $scope.company, password: $scope.password, password_confirm: $scope.password_confirm})
        ).success(
        function(data){
          // if success
          if (data['response']['user']){
                 $location.path("/onboarding/stick");
          }

          else{
            // TODO: brevity
            var errors = data['response']['errors'];
            if (errors.hasOwnProperty('email')){
              $scope.email_error = errors['email'][0];
            }
            if (errors.hasOwnProperty('company')){
              $scope.company_error = errors['company'][0];
            }
            if (errors.hasOwnProperty('password')){
              $scope.password_error = errors['password'][0];
            }
            if (errors.hasOwnProperty('password_confirm')){
              $scope.password_confirm_error = errors['password_confirm'][0];
            }
          }
        }
      ).error(
        function(data){
          console.log('registration error')
          alert(data)
          $scope.errorMsg = data.reason;
        }
      );
    };
  }

}).controller({
  LoginController: function ($scope, $http, authService, $location) {
    $scope.submit = function() {
      console.log('in logincontroller')
      $http.defaults.headers.post['X-CSRFToken'] = csrf_token;
      $http.defaults.headers.common['Content-Type'] = 'application/json'
      $http.defaults.headers.common['Accept'] = 'application/json'

      //debugger;
      $http.post(
        '/login',
          JSON.stringify({ email: $scope.email, password: $scope.password })
      ).success(
        function(data) {
          if (data.meta){
            var status_code = data.meta.code;
          }
          else{
            var status_code = data.status;
          }
          if (status_code == 200 || status_code == 302 || status_code == 301){
            $.cookie('email', $scope.email, { expires: 7 });
            $.cookie('auth_token', data.authentication_token, { expires: 7 });
            $http.defaults.headers.common['Authentication-Token'] = data.authentication_token;
            authService.loginConfirmed();
            $location.path("/dashboard");
          }
          else{
            var errors = data['response']['errors'];
            if (errors.hasOwnProperty('email')){
              $scope.email_error = errors['email'][0];
            }
            if (errors.hasOwnProperty('password')){
              $scope.password_error = errors['password'][0];
            }
          }
        }
        ).error(
        function(data) {
          alert('LoginController submit error');
          $scope.errorMsg = data.reason;
          //debugger;
        }
      );
    };
  }

})
.controller({
  NavController: function ($scope, $http, authService, $location) {
      $scope.click_login = function(){
        alert('inside click login')
        var main = $('#content');
        var login = $('#login-holder');
          login.slideDown('slow', function() {
          main.hide();
        });
      }

     $scope.click_logout = function() {
      $http.defaults.headers.post['X-CSRFToken'] = csrf_token;

      $http.get('/logout').success(function() {
        $scope.restrictedContent = [];
        $.cookie('auth_token', null);
        $.cookie('email', null);
        $http.defaults.headers.common['Authorization'] = null;
        $http.defaults.headers.common['Authentication-Token'] = null;

      }).error(function() {
        // This should happen after the .post call either way.
        $.cookie('auth_token', null);
        $http.defaults.headers.common['Authorization'] = null;
          $location.path("/");
      });
    };

    $scope.logged_in = function(){
      if ($.cookie('auth_token')){
        return True;
      }

      else{
        return False;
      }
    }

  }

})

.controller({
  ContentController: function ($scope, $http) {

    $scope.publicContent = [];
    $scope.restrictedContent = [];

    $scope.publicAction = function() {

      $http.post(
        '/api/myproperty/paymenttype/',
        JSON.stringify({ name: $scope.publicData })
      ).success(
        function(response) {
          $scope.publicContent.push(response);
        }
      ).error(
        function(response) {
          alert('error 99');
        }
      );
    };

    $scope.restrictedAction = function() {
      alert('restrictedAction');

      $http.post(
        'http://localhost:8001/api/myproperty/paymenttype/',
        JSON.stringify({ name: $scope.restrictedData }), {
          //transformResponse: function(data),
          timeout: 5000
        }
      ).success(
        function(response) {
          alert('restrictedAction inside');
          // this piece of code will not be executed until user is authenticated
          $scope.restrictedContent.push(response);
        }
      );
    };
  }
})
.controller({
  HypothesesListController: function ($scope, $http, Hypotheses) {
    var hypothesesQuery = Hypotheses.get({}, function(hypotheses) {
      $scope.hypotheses = hypotheses.objects;
    });
  }
})
.directive('authApplication', function() {
    return {
      restrict: 'C',

      link: function(scope, elem, attrs) {
        //once Angular is started, remove class:
        elem.removeClass('waiting-for-angular');

        var login = elem.find('#login-holder');
        var main = elem.find('#content');

        login.hide();

        scope.$on('event:auth-loginRequired', function() {
          login.slideDown('slow', function() {
            alert('auth login required')
            main.hide();
          });
        });
        scope.$on('event:auth-loginConfirmed', function() {
          alert('auth login confirmed!')
          main.show();
          login.slideUp();
        });
      }
    };
  })
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider
    .when('/', {templateUrl: 'static/partials/public.html', controller: MyCtrl1})
    .when('/dashboard', {templateUrl: 'static/partials/dashboard.html', controller: DashboardController})
    .when('/onboarding/stick', {templateUrl: '/static/partials/onboarding/stick.html', controller: StickController})
    .when('/onboarding/virality', {templateUrl: '/static/partials/onboarding/virality.html', controller: ViralityController})
    .when('/onboarding/pay', {templateUrl: '/static/partials/onboarding/pay.html', controller: PayController})
    // enable push state
    $locationProvider.html5Mode(true);
}])
<commit_msg>fixed error in controllers.js<commit_after>/* Controllers */

function MyCtrl1() {}
MyCtrl1.$inject = [];

function DashboardController() {
	$scope.hypothesis_submit = function(){
      $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
      $http.defaults.headers.common['Content-Type'] = 'application/json'
      $http.defaults.headers.common['Accept'] = 'application/json'

      $http.post(
        '/api/v1/hypotheses',
        JSON.stringify({name: $scope.name, twitter: $scope.twitter})
        ).success(
        function(data){
          // if success
          if (data['response']['user']){
                 $location.path("/onboarding/stick");
          }

          else{
            // TODO: brevity
            var errors = data['response']['errors'];
           }
          }
     	).error(
        function(data){
          console.log('registration error')
          alert(data)
          $scope.errorMsg = data.reason;
        }
      );
    }

	$scope.new_hypothesis = function(){

	}
}

function CarouselController($scope, $location, $anchorScroll){
  $scope.scroll_to = function(id) {
    alert(id)
      $location.hash(id);
      $anchorScroll();
   }
}

function ErrorPageController(){
}

function OnboardingController(){
}

function StickController($scope, $http, GoogleAnalytics){
  var GAQuery = GoogleAnalytics.get();
  console.log(GAQuery);
  if (GAQuery.length > 0){
    $scope.GA = true;
  }
  $scope.has_GA = function(){
    if ($scope.GA){
      return true;
    }
  }
  $scope.GA_auth = function(){
    $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
    $http.post(
        '/connect/google-analytics'
        ).success(
        function(data){
          var status = data['status'];
          if (status == 100){
            var redirect_url = data['redirect_url'];
            window.location(redirect_url);
          }
        }
      )
    }
}

function ViralityController($scope, $http, Facebook, Twitter){
  $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
  var FBQuery = Facebook.get();
  var TwitterQuery = Twitter.get();

  if (FBQuery.length > 0){
    $scope.FB = true;
  }

  $scope.has_FB = function(){
    if ($scope.FB){
      return true;
    }
  }

  $scope.fb_auth = function(){
    $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
    $http.post(
        '/connect/facebook'
    ).success(
    	function(data){
			var redirect_url = data['redirect_url'];
			if (redirect_url != null){
				open(redirect_url);
			}
        }
    ).error(
        function(data){
          	console.log('error')
          	$scope.FB_error = "Facebook authentication failed."
        })
	}

  if (TwitterQuery['twitter_handle']){
    $scope.Twitter = true;
  }

  $scope.has_Twitter = function(){
    if ($scope.Twitter){
      return true;
    }
  }

  $scope.twitter_auth = function(){
    $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
    $http.post(
        '/connect/twitter'
        ).success(
        function(data){
          var status = data['status'];
          if (status == 100){
            var redirect_url = data['redirect_url'];
            open(redirect_url);
          }
        }
      ).error(
        function(data){
          $scope.twitter_error = "Twitter authentication failed."
        }
      )
    }

}

function PayController($scope){

}

var LWBApp = angular.module('LWBApp', ['ngRoute','http-auth-interceptor', 'LWBServices'],
  function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
}).controller({
  RegistrationController: function($scope, $http, authService, $location){
    $scope.submit = function(){
      $http.defaults.headers.common['X-CSRFToken'] = csrf_token;
	  console.log(csrf_token);
      $http.defaults.headers.common['Content-Type'] = 'application/json'
      $http.defaults.headers.common['Accept'] = 'application/json'

      $http.post(
        '/registration',

        JSON.stringify({email: $scope.email, company: $scope.company, password: $scope.password, password_confirm: $scope.password_confirm})
        ).success(
        function(data){
          // if success
          if (data['response']['user']){
                 $location.path("/onboarding/stick");
          }

          else{
            // TODO: brevity
            var errors = data['response']['errors'];
            if (errors.hasOwnProperty('email')){
              $scope.email_error = errors['email'][0];
            }
            if (errors.hasOwnProperty('company')){
              $scope.company_error = errors['company'][0];
            }
            if (errors.hasOwnProperty('password')){
              $scope.password_error = errors['password'][0];
            }
            if (errors.hasOwnProperty('password_confirm')){
              $scope.password_confirm_error = errors['password_confirm'][0];
            }
          }
        }
      ).error(
        function(data){
          console.log('registration error')
          alert(data)
          $scope.errorMsg = data.reason;
        }
      );
    };
  }

}).controller({
  LoginController: function ($scope, $http, authService, $location) {
    $scope.submit = function() {
      console.log('in logincontroller')
      $http.defaults.headers.post['X-CSRFToken'] = csrf_token;
      $http.defaults.headers.common['Content-Type'] = 'application/json'
      $http.defaults.headers.common['Accept'] = 'application/json'

      //debugger;
      $http.post(
        '/login',
          JSON.stringify({ email: $scope.email, password: $scope.password })
      ).success(
        function(data) {
          if (data.meta){
            var status_code = data.meta.code;
          }
          else{
            var status_code = data.status;
          }
          if (status_code == 200 || status_code == 302 || status_code == 301){
            $.cookie('email', $scope.email, { expires: 7 });
            $.cookie('auth_token', data.authentication_token, { expires: 7 });
            $http.defaults.headers.common['Authentication-Token'] = data.authentication_token;
            authService.loginConfirmed();
            $location.path("/dashboard");
          }
          else{
            var errors = data['response']['errors'];
            if (errors.hasOwnProperty('email')){
              $scope.email_error = errors['email'][0];
            }
            if (errors.hasOwnProperty('password')){
              $scope.password_error = errors['password'][0];
            }
          }
        }
        ).error(
        function(data) {
          alert('LoginController submit error');
          $scope.errorMsg = data.reason;
          //debugger;
        }
      );
    };
  }

})
.controller({
  NavController: function ($scope, $http, authService, $location) {
      $scope.click_login = function(){
        alert('inside click login')
        var main = $('#content');
        var login = $('#login-holder');
          login.slideDown('slow', function() {
          main.hide();
        });
      }

     $scope.click_logout = function() {
      $http.defaults.headers.post['X-CSRFToken'] = csrf_token;

      $http.get('/logout').success(function() {
        $scope.restrictedContent = [];
        $.cookie('auth_token', null);
        $.cookie('email', null);
        $http.defaults.headers.common['Authorization'] = null;
        $http.defaults.headers.common['Authentication-Token'] = null;

      }).error(function() {
        // This should happen after the .post call either way.
        $.cookie('auth_token', null);
        $http.defaults.headers.common['Authorization'] = null;
          $location.path("/");
      });
    };

    $scope.logged_in = function(){
      if ($.cookie('auth_token')){
        return True;
      }

      else{
        return False;
      }
    }

  }

})

.controller({
  ContentController: function ($scope, $http) {

    $scope.publicContent = [];
    $scope.restrictedContent = [];

    $scope.publicAction = function() {

      $http.post(
        '/api/myproperty/paymenttype/',
        JSON.stringify({ name: $scope.publicData })
      ).success(
        function(response) {
          $scope.publicContent.push(response);
        }
      ).error(
        function(response) {
          alert('error 99');
        }
      );
    };

    $scope.restrictedAction = function() {
      alert('restrictedAction');

      $http.post(
        'http://localhost:8001/api/myproperty/paymenttype/',
        JSON.stringify({ name: $scope.restrictedData }), {
          //transformResponse: function(data),
          timeout: 5000
        }
      ).success(
        function(response) {
          alert('restrictedAction inside');
          // this piece of code will not be executed until user is authenticated
          $scope.restrictedContent.push(response);
        }
      );
    };
  }
})
.controller({
  HypothesesListController: function ($scope, $http, Hypotheses) {
    var hypothesesQuery = Hypotheses.get({}, function(hypotheses) {
      $scope.hypotheses = hypotheses.objects;
    });
  }
})
.directive('authApplication', function() {
    return {
      restrict: 'C',

      link: function(scope, elem, attrs) {
        //once Angular is started, remove class:
        elem.removeClass('waiting-for-angular');

        var login = elem.find('#login-holder');
        var main = elem.find('#content');

        login.hide();

        scope.$on('event:auth-loginRequired', function() {
          login.slideDown('slow', function() {
            alert('auth login required')
            main.hide();
          });
        });
        scope.$on('event:auth-loginConfirmed', function() {
          alert('auth login confirmed!')
          main.show();
          login.slideUp();
        });
      }
    };
  })
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider
    .when('/', {templateUrl: 'static/partials/public.html', controller: MyCtrl1})
    .when('/dashboard', {templateUrl: 'static/partials/dashboard.html', controller: DashboardController})
    .when('/onboarding/stick', {templateUrl: '/static/partials/onboarding/stick.html', controller: StickController})
    .when('/onboarding/virality', {templateUrl: '/static/partials/onboarding/virality.html', controller: ViralityController})
    .when('/onboarding/pay', {templateUrl: '/static/partials/onboarding/pay.html', controller: PayController})
    // enable push state
    $locationProvider.html5Mode(true);
}])
<|endoftext|>


<commit_before>THREE.MeshLine = function() {

	this.positions = [];

	this.previous = [];
	this.next = [];
	this.side = [];
	this.width = [];
	this.indices_array = [];
	this.uvs = [];

	this.geometry = new THREE.BufferGeometry();

	this.widthCallback = null;

}

THREE.MeshLine.prototype.setGeometry = function( g, c ) {

	this.widthCallback = c;

	this.positions = [];

	if( g instanceof THREE.Geometry ) {
		for( var j = 0; j < g.vertices.length; j++ ) {
			var v = g.vertices[ j ];
			this.positions.push( v.x, v.y, v.z );
			this.positions.push( v.x, v.y, v.z );
		}
	}

	if( g instanceof THREE.BufferGeometry ) {
		// read attribute positions ?
	}

	if( g instanceof Float32Array ) {
		for( var j = 0; j < g.length; j += 3 ) {
			this.positions.push( g[ j ], g[ j + 1 ], g[ j + 2 ] );
			this.positions.push( g[ j ], g[ j + 1 ], g[ j + 2 ] );
		}
	}

	this.process();

}

THREE.MeshLine.prototype.compareV3 = function( a, b ) {

	var aa = a * 6;
	var ab = b * 6;
	return ( this.positions[ aa ] === this.positions[ ab ] ) && ( this.positions[ aa + 1 ] === this.positions[ ab + 1 ] ) && ( this.positions[ aa + 2 ] === this.positions[ ab + 2 ] );

}

THREE.MeshLine.prototype.copyV3 = function( a ) {

	var aa = a * 6;
	return [ this.positions[ aa ], this.positions[ aa + 1 ], this.positions[ aa + 2 ] ];

}

THREE.MeshLine.prototype.process = function() {

	var l = this.positions.length / 6;

	this.previous = [];
	this.next = [];
	this.side = [];
	this.width = [];
	this.indices_array = [];
	this.uvs = [];

	for( var j = 0; j < l; j++ ) {
		this.side.push( 1 );
		this.side.push( -1 );
	}

	var w;
	for( var j = 0; j < l; j++ ) {
		if( this.widthCallback ) w = this.widthCallback( j / ( l -1 ) );
		else w = 1;
		this.width.push( w );
		this.width.push( w );
	}

	for( var j = 0; j < l; j++ ) {
		this.uvs.push( j / ( l - 1 ), 0 );
		this.uvs.push( j / ( l - 1 ), 1 );
	}

	var v;

	if( this.compareV3( 0, l - 1 ) ){
		v = this.copyV3( l - 2 );
	} else {
		v = this.copyV3( 0 );
	}
	this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	for( var j = 0; j < l - 1; j++ ) {
		v = this.copyV3( j );
		this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] );
		this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	}

	for( var j = 1; j < l; j++ ) {
		v = this.copyV3( j );
		this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] );
		this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	}

	if( this.compareV3( l - 1, 0 ) ){
		v = this.copyV3( 1 );
	} else {
		v = this.copyV3( l - 1 );
	}
	this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] );

	for( var j = 0; j < l - 1; j++ ) {
		var n = j * 2;
		this.indices_array.push( n, n + 1, n + 2 );
		this.indices_array.push( n + 2, n + 1, n + 3 );
	}

	this.attributes = {
		position: new THREE.BufferAttribute( new Float32Array( this.positions ), 3 ),
		previous: new THREE.BufferAttribute( new Float32Array( this.previous ), 3 ),
		next: new THREE.BufferAttribute( new Float32Array( this.next ), 3 ),
		side: new THREE.BufferAttribute( new Float32Array( this.side ), 1 ),
		width: new THREE.BufferAttribute( new Float32Array( this.width ), 1 ),
		uv: new THREE.BufferAttribute( new Float32Array( this.uvs ), 2 ),
		index: new THREE.BufferAttribute( new Uint16Array( this.indices_array ), 1 )
	}

	this.geometry.addAttribute( 'position', this.attributes.position );
	this.geometry.addAttribute( 'previous', this.attributes.previous );
	this.geometry.addAttribute( 'next', this.attributes.next );
	this.geometry.addAttribute( 'side', this.attributes.side );
	this.geometry.addAttribute( 'width', this.attributes.width );
	this.geometry.addAttribute( 'uv', this.attributes.uv );

	this.geometry.setIndex( this.attributes.index );

}

THREE.MeshLineMaterial = function() {

	this.material = new THREE.RawShaderMaterial( {
		uniforms:{
			lineWidth: { type: 'f', value: 1 },
			map: { type: 't', value: strokeTexture },
			useMap: { type: 'f', value: 0 },
			color: { type: 'c', value: new THREE.Color( colors[ ~~Maf.randomInRange( 0, colors.length ) ] ) },
			resolution: { type: 'v2', value: resolution },
			sizeAttenuation: { type: 'f', value: 1 },
			near: { type: 'f', value: camera.near },
			far: { type: 'f', value: camera.far }
		},
		vertexShader: document.getElementById( 'vs-line' ).textContent,
		fragmentShader: document.getElementById( 'fs-line' ).textContent,
		/*side: THREE.DoubleSide,
		transparent: true,
		depthTest: false,
		blending: THREE.AdditiveAlphaBlending*/
	});

}

THREE.MeshLineMaterial = function ( parameters ) {

	var vertexShaderSource = [
'precision highp float;',
'',
'attribute vec3 position;',
'attribute vec3 previous;',
'attribute vec3 next;',
'attribute float side;',
'attribute float width;',
'attribute vec2 uv;',
'',
'uniform mat4 projectionMatrix;',
'uniform mat4 modelViewMatrix;',
'uniform vec2 resolution;',
'uniform float lineWidth;',
'uniform vec3 color;',
'uniform float opacity;',
'uniform float near;',
'uniform float far;',
'uniform float sizeAttenuation;',
'',
'varying vec2 vUV;',
'varying vec4 vColor;',
'',
'vec2 fix( vec4 i, float aspect ) {',
'',
'    vec2 res = i.xy / i.w;',
'    res.x *= aspect;',
'    return res;',
'',
'}',
'',
'void main() {',
'',
'    float aspect = resolution.x / resolution.y;',
'',
'    vColor = vec4( color, opacity );',
'    vUV = uv;',
'',
'    mat4 m = projectionMatrix * modelViewMatrix;',
'    vec4 finalPosition = m * vec4( position, 1.0 );',
'    vec4 prevPos = m * vec4( previous, 1.0 );',
'    vec4 nextPos = m * vec4( next, 1.0 );',
'',
'    vec2 currentP = fix( finalPosition, aspect );',
'    vec2 prevP = fix( prevPos, aspect );',
'    vec2 nextP = fix( nextPos, aspect );',
'',
'    float w = 1.8 * lineWidth * width;',
'',
'    vec2 dir;',
'    if( nextP == currentP ) dir = normalize( currentP - prevP );',
'    else if( prevP == currentP ) dir = normalize( nextP - currentP );',
'    else {',
'        vec2 dir1 = normalize( currentP - prevP );',
'        vec2 dir2 = normalize( nextP - currentP );',
'        dir = normalize( dir1 + dir2 );',
'',
'        /*{',
'            vec2 perp = vec2( -dir1.y, dir1.x );',
'            vec2 miter = vec2( -dir.y, dir.x );',
'            float f = dot( miter, perp );',
'            w /= f;',
'        }*/',
'',
'    }',
'',
'    //vec2 normal = ( cross( vec3( dir, 0. ), vec3( 0., 0., 1. ) ) ).xy;',
'    vec2 normal = vec2( -dir.y, dir.x );',
'    normal.x /= aspect;',
'    normal *= .5 * w;',
'',
'    if( sizeAttenuation == 0. ) {',
'        float depth = ( finalPosition.z - near ) / ( far - near );',
'        normal *= depth;',
'    }',
'',
'    vec4 offset = vec4( normal * side, 0.0, 1.0 );',
'    finalPosition.xy += offset.xy;',
'',
'    gl_Position = finalPosition;',
'',
'}' ];

	var fragmentShaderSource = [
'precision mediump float;',
'',
'uniform sampler2D map;',
'uniform float useMap;',
'uniform float useDash;',
'uniform vec2 dashArray;',
'',
'varying vec2 vUV;',
'varying vec4 vColor;',
'',
'void main() {',
'',
'    vec4 c = vColor;',
'    if( useMap == 1. ) c *= texture2D( map, vUV );',
'	 if( useDash == 1. ){',
'	 	 ',
'	 }',
'    gl_FragColor = c;',
'',
'}' ];

	function check( v, d ) {
		if( v === undefined ) return d;
		return v;
	}

	THREE.Material.call( this );

	this.lineWidth = check( parameters.lineWidth, 1 );
	this.map = check( parameters.map, null );
	this.useMap = check( parameters.useMap, 0 );
	this.color = check( parameters.color, new THREE.Color( 0xffffff ) );
	this.opacity = check( parameters.opacity, 1 );
	this.resolution = check( parameters.resolution, new THREE.Vector2( 1, 1 ) );
	this.sizeAttenuation = check( parameters.sizeAttenuation, 1 );
	this.near = check( parameters.near, 1 );
	this.far = check( parameters.far, 1 );
	this.dashArray = check( parameters.dashArray, [] );
	this.useDash = ( this.dashArray !== [] ) ? 1 : 0;

	var material = new THREE.RawShaderMaterial( {
		uniforms:{
			lineWidth: { type: 'f', value: this.lineWidth },
			map: { type: 't', value: this.map },
			useMap: { type: 'f', value: this.useMap },
			color: { type: 'c', value: this.color },
			opacity: { type: 'f', value: this.opacity },
			resolution: { type: 'v2', value: this.resolution },
			sizeAttenuation: { type: 'f', value: this.sizeAttenuation },
			near: { type: 'f', value: this.near },
			far: { type: 'f', value: this.far },
			dashArray: { type: 'v2', value: new THREE.Vector2( this.dashArray[ 0 ], this.dashArray[ 1 ] ) },
			useDash: { type: 'f', value: this.useDash }
		},
		vertexShader: vertexShaderSource.join( '\r\n' ),
		fragmentShader: fragmentShaderSource.join( '\r\n' )
	});

	delete parameters.lineWidth;
	delete parameters.map;
	delete parameters.useMap;
	delete parameters.color;
	delete parameters.opacity;
	delete parameters.resolution;
	delete parameters.sizeAttenuation;
	delete parameters.near;
	delete parameters.far;
	delete parameters.dashArray;

	material.type = 'MeshLineMaterial';

	material.setValues( parameters );

	return material;

};

THREE.MeshLineMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshLineMaterial.prototype.constructor = THREE.MeshLineMaterial;

THREE.MeshLineMaterial.prototype.copy = function ( source ) {

	THREE.Material.prototype.copy.call( this, source );

	this.lineWidth = source.lineWidth;
	this.map = source.map;
	this.useMap = source.useMap;
	this.color.copy( source.color );
	this.opacity = source.opacity;
	this.resolution.copy( source.resolution );
	this.sizeAttenuation = source.sizeAttenuation;
	this.near = source.near;
	this.far = source.far;

	return this;

};<commit_msg>support for more arrays as source<commit_after>THREE.MeshLine = function() {

	this.positions = [];

	this.previous = [];
	this.next = [];
	this.side = [];
	this.width = [];
	this.indices_array = [];
	this.uvs = [];

	this.geometry = new THREE.BufferGeometry();

	this.widthCallback = null;

}

THREE.MeshLine.prototype.setGeometry = function( g, c ) {

	this.widthCallback = c;

	this.positions = [];

	if( g instanceof THREE.Geometry ) {
		for( var j = 0; j < g.vertices.length; j++ ) {
			var v = g.vertices[ j ];
			this.positions.push( v.x, v.y, v.z );
			this.positions.push( v.x, v.y, v.z );
		}
	}

	if( g instanceof THREE.BufferGeometry ) {
		// read attribute positions ?
	}

	if( g instanceof Float32Array || g instanceof Array ) {
		for( var j = 0; j < g.length; j += 3 ) {
			this.positions.push( g[ j ], g[ j + 1 ], g[ j + 2 ] );
			this.positions.push( g[ j ], g[ j + 1 ], g[ j + 2 ] );
		}
	}

	this.process();

}

THREE.MeshLine.prototype.compareV3 = function( a, b ) {

	var aa = a * 6;
	var ab = b * 6;
	return ( this.positions[ aa ] === this.positions[ ab ] ) && ( this.positions[ aa + 1 ] === this.positions[ ab + 1 ] ) && ( this.positions[ aa + 2 ] === this.positions[ ab + 2 ] );

}

THREE.MeshLine.prototype.copyV3 = function( a ) {

	var aa = a * 6;
	return [ this.positions[ aa ], this.positions[ aa + 1 ], this.positions[ aa + 2 ] ];

}

THREE.MeshLine.prototype.process = function() {

	var l = this.positions.length / 6;

	this.previous = [];
	this.next = [];
	this.side = [];
	this.width = [];
	this.indices_array = [];
	this.uvs = [];

	for( var j = 0; j < l; j++ ) {
		this.side.push( 1 );
		this.side.push( -1 );
	}

	var w;
	for( var j = 0; j < l; j++ ) {
		if( this.widthCallback ) w = this.widthCallback( j / ( l -1 ) );
		else w = 1;
		this.width.push( w );
		this.width.push( w );
	}

	for( var j = 0; j < l; j++ ) {
		this.uvs.push( j / ( l - 1 ), 0 );
		this.uvs.push( j / ( l - 1 ), 1 );
	}

	var v;

	if( this.compareV3( 0, l - 1 ) ){
		v = this.copyV3( l - 2 );
	} else {
		v = this.copyV3( 0 );
	}
	this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	for( var j = 0; j < l - 1; j++ ) {
		v = this.copyV3( j );
		this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] );
		this.previous.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	}

	for( var j = 1; j < l; j++ ) {
		v = this.copyV3( j );
		this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] );
		this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	}

	if( this.compareV3( l - 1, 0 ) ){
		v = this.copyV3( 1 );
	} else {
		v = this.copyV3( l - 1 );
	}
	this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] );
	this.next.push( v[ 0 ], v[ 1 ], v[ 2 ] );

	for( var j = 0; j < l - 1; j++ ) {
		var n = j * 2;
		this.indices_array.push( n, n + 1, n + 2 );
		this.indices_array.push( n + 2, n + 1, n + 3 );
	}

	this.attributes = {
		position: new THREE.BufferAttribute( new Float32Array( this.positions ), 3 ),
		previous: new THREE.BufferAttribute( new Float32Array( this.previous ), 3 ),
		next: new THREE.BufferAttribute( new Float32Array( this.next ), 3 ),
		side: new THREE.BufferAttribute( new Float32Array( this.side ), 1 ),
		width: new THREE.BufferAttribute( new Float32Array( this.width ), 1 ),
		uv: new THREE.BufferAttribute( new Float32Array( this.uvs ), 2 ),
		index: new THREE.BufferAttribute( new Uint16Array( this.indices_array ), 1 )
	}

	this.geometry.addAttribute( 'position', this.attributes.position );
	this.geometry.addAttribute( 'previous', this.attributes.previous );
	this.geometry.addAttribute( 'next', this.attributes.next );
	this.geometry.addAttribute( 'side', this.attributes.side );
	this.geometry.addAttribute( 'width', this.attributes.width );
	this.geometry.addAttribute( 'uv', this.attributes.uv );

	this.geometry.setIndex( this.attributes.index );

}

THREE.MeshLineMaterial = function() {

	this.material = new THREE.RawShaderMaterial( {
		uniforms:{
			lineWidth: { type: 'f', value: 1 },
			map: { type: 't', value: strokeTexture },
			useMap: { type: 'f', value: 0 },
			color: { type: 'c', value: new THREE.Color( colors[ ~~Maf.randomInRange( 0, colors.length ) ] ) },
			resolution: { type: 'v2', value: resolution },
			sizeAttenuation: { type: 'f', value: 1 },
			near: { type: 'f', value: camera.near },
			far: { type: 'f', value: camera.far }
		},
		vertexShader: document.getElementById( 'vs-line' ).textContent,
		fragmentShader: document.getElementById( 'fs-line' ).textContent,
		/*side: THREE.DoubleSide,
		transparent: true,
		depthTest: false,
		blending: THREE.AdditiveAlphaBlending*/
	});

}

THREE.MeshLineMaterial = function ( parameters ) {

	var vertexShaderSource = [
'precision highp float;',
'',
'attribute vec3 position;',
'attribute vec3 previous;',
'attribute vec3 next;',
'attribute float side;',
'attribute float width;',
'attribute vec2 uv;',
'',
'uniform mat4 projectionMatrix;',
'uniform mat4 modelViewMatrix;',
'uniform vec2 resolution;',
'uniform float lineWidth;',
'uniform vec3 color;',
'uniform float opacity;',
'uniform float near;',
'uniform float far;',
'uniform float sizeAttenuation;',
'',
'varying vec2 vUV;',
'varying vec4 vColor;',
'',
'vec2 fix( vec4 i, float aspect ) {',
'',
'    vec2 res = i.xy / i.w;',
'    res.x *= aspect;',
'    return res;',
'',
'}',
'',
'void main() {',
'',
'    float aspect = resolution.x / resolution.y;',
'',
'    vColor = vec4( color, opacity );',
'    vUV = uv;',
'',
'    mat4 m = projectionMatrix * modelViewMatrix;',
'    vec4 finalPosition = m * vec4( position, 1.0 );',
'    vec4 prevPos = m * vec4( previous, 1.0 );',
'    vec4 nextPos = m * vec4( next, 1.0 );',
'',
'    vec2 currentP = fix( finalPosition, aspect );',
'    vec2 prevP = fix( prevPos, aspect );',
'    vec2 nextP = fix( nextPos, aspect );',
'',
'    float w = 1.8 * lineWidth * width;',
'',
'    vec2 dir;',
'    if( nextP == currentP ) dir = normalize( currentP - prevP );',
'    else if( prevP == currentP ) dir = normalize( nextP - currentP );',
'    else {',
'        vec2 dir1 = normalize( currentP - prevP );',
'        vec2 dir2 = normalize( nextP - currentP );',
'        dir = normalize( dir1 + dir2 );',
'',
'        /*{',
'            vec2 perp = vec2( -dir1.y, dir1.x );',
'            vec2 miter = vec2( -dir.y, dir.x );',
'            float f = dot( miter, perp );',
'            w /= f;',
'        }*/',
'',
'    }',
'',
'    //vec2 normal = ( cross( vec3( dir, 0. ), vec3( 0., 0., 1. ) ) ).xy;',
'    vec2 normal = vec2( -dir.y, dir.x );',
'    normal.x /= aspect;',
'    normal *= .5 * w;',
'',
'    if( sizeAttenuation == 0. ) {',
'        float depth = ( finalPosition.z - near ) / ( far - near );',
'        normal *= depth;',
'    }',
'',
'    vec4 offset = vec4( normal * side, 0.0, 1.0 );',
'    finalPosition.xy += offset.xy;',
'',
'    gl_Position = finalPosition;',
'',
'}' ];

	var fragmentShaderSource = [
'precision mediump float;',
'',
'uniform sampler2D map;',
'uniform float useMap;',
'uniform float useDash;',
'uniform vec2 dashArray;',
'',
'varying vec2 vUV;',
'varying vec4 vColor;',
'',
'void main() {',
'',
'    vec4 c = vColor;',
'    if( useMap == 1. ) c *= texture2D( map, vUV );',
'	 if( useDash == 1. ){',
'	 	 ',
'	 }',
'    gl_FragColor = c;',
'',
'}' ];

	function check( v, d ) {
		if( v === undefined ) return d;
		return v;
	}

	THREE.Material.call( this );

	this.lineWidth = check( parameters.lineWidth, 1 );
	this.map = check( parameters.map, null );
	this.useMap = check( parameters.useMap, 0 );
	this.color = check( parameters.color, new THREE.Color( 0xffffff ) );
	this.opacity = check( parameters.opacity, 1 );
	this.resolution = check( parameters.resolution, new THREE.Vector2( 1, 1 ) );
	this.sizeAttenuation = check( parameters.sizeAttenuation, 1 );
	this.near = check( parameters.near, 1 );
	this.far = check( parameters.far, 1 );
	this.dashArray = check( parameters.dashArray, [] );
	this.useDash = ( this.dashArray !== [] ) ? 1 : 0;

	var material = new THREE.RawShaderMaterial( {
		uniforms:{
			lineWidth: { type: 'f', value: this.lineWidth },
			map: { type: 't', value: this.map },
			useMap: { type: 'f', value: this.useMap },
			color: { type: 'c', value: this.color },
			opacity: { type: 'f', value: this.opacity },
			resolution: { type: 'v2', value: this.resolution },
			sizeAttenuation: { type: 'f', value: this.sizeAttenuation },
			near: { type: 'f', value: this.near },
			far: { type: 'f', value: this.far },
			dashArray: { type: 'v2', value: new THREE.Vector2( this.dashArray[ 0 ], this.dashArray[ 1 ] ) },
			useDash: { type: 'f', value: this.useDash }
		},
		vertexShader: vertexShaderSource.join( '\r\n' ),
		fragmentShader: fragmentShaderSource.join( '\r\n' )
	});

	delete parameters.lineWidth;
	delete parameters.map;
	delete parameters.useMap;
	delete parameters.color;
	delete parameters.opacity;
	delete parameters.resolution;
	delete parameters.sizeAttenuation;
	delete parameters.near;
	delete parameters.far;
	delete parameters.dashArray;

	material.type = 'MeshLineMaterial';

	material.setValues( parameters );

	return material;

};

THREE.MeshLineMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.MeshLineMaterial.prototype.constructor = THREE.MeshLineMaterial;

THREE.MeshLineMaterial.prototype.copy = function ( source ) {

	THREE.Material.prototype.copy.call( this, source );

	this.lineWidth = source.lineWidth;
	this.map = source.map;
	this.useMap = source.useMap;
	this.color.copy( source.color );
	this.opacity = source.opacity;
	this.resolution.copy( source.resolution );
	this.sizeAttenuation = source.sizeAttenuation;
	this.near = source.near;
	this.far = source.far;

	return this;

};<|endoftext|>


<commit_before>define(['Modernizr', 'createElement'], function( Modernizr, createElement ) {
  // testing for placeholder attribute in inputs and textareas
  Modernizr.addTest('placeholder', !!('placeholder' in createElement('input') && 'placeholder' in createElement('textarea')));
});
<commit_msg>Remove unnecessary !!<commit_after>define(['Modernizr', 'createElement'], function( Modernizr, createElement ) {
  // testing for placeholder attribute in inputs and textareas
  Modernizr.addTest('placeholder', ('placeholder' in createElement('input') && 'placeholder' in createElement('textarea')));
});
<|endoftext|>