<commit_before>/* -*- coding: utf-8 -*- */
/* global cforum */

cforum.mentions = function(elem) {
  $(elem).textcomplete([
    {
      id: 'mentions',
      match: /\B@([^\n]{2,})$/,
      search: function (term, callback) {
        $.get(cforum.baseUrl + 'users.json?nick=' + encodeURIComponent(term)).
          done(function(data) {
            callback($.map(data, function(element) { return element.username; }));
          });
      },
      index: 1,
      replace: function (mention) {
        return '@' + mention + ' ';
      }
    },

    {
      id: 'emoji',
      type: 'row',
      rowLength: 5,
      match: /\B:([\-+\w]*)$/,
      index: 1,
      search: function(term, callback) {
        callback($.map(Object.keys(cforum.emojis), function(emoji) {
          return emoji.indexOf(term) !== -1 ? emoji : null;
        }));
      },
      template: function(value) {
        return cforum.emojis[value];
      },
      replace: function (value) {
        return cforum.emojis[value];
      }
    },

    {
      id: 'typography',
      match: /(=>|<=|<=>|"|\.\.\.|\*|->|<-|-{1,3}|\^|\[tm\]?|=\/=?|=)$/,
      index: 1,
      search: function (term, callback) {
        var found = [];

        switch(term) {
        case '"':
          found = ['""', '„“', '‚‘'];
          break;
        case '...':
          found = ['…'];
          break;
        case '---':
          found = ['—'];
          break;
        case '--':
          found = ['–', '—'];
          break;
        case '-':
          found = ['−', '–', '—'];
          break;
        case '*':
          found = ['×'];
          break;
        case '->':
          found = ['→', '←', '↑', '↓'];
          break;
        case '<-':
          found = ['←', '→', '↑', '↓'];
          break;
        case '^':
          found = ['↑', '▲', '←', '→', '↓'];
          break;
        case '=>':
          found = ['⇒', '⇐', '⇔'];
          break;
        case '<=':
          found = ['⇐', '⇒', '⇔'];
          break;
        case '<=>':
          found = ['⇔', '⇐', '⇒'];
          break;
        case '[tm':
        case '[tm]':
          found = ['™'];
          break;
        case '=':
        case '=/':
        case '=/=':
          found = ['≠','≈'];
          break;
        }

        callback(found);
      },
      replace: function(text) {
        switch(text) {
          case '""':
            return ['"', '"'];
          case '„“':
            return ['„', '“'];
          case '‚‘':
            return ['‚', '‘'];
        }

        return text;
      }
    },

    {
      id: 'smileys',
      match: /\B(:-?\)|;-?\)|:-?D|:-?P|:-?\(|:-?O|:-?\||:-?\/|¯\_\(ツ\)_/¯)$/i,
      index: 1,
      search: function (term, callback) {
        var found = [];

        term = term.toUpperCase();

        switch(term) {
        case ':-)':
        case ':)':
          found = ['😀'];
          break;
        case ';-)':
        case ';)':
          found = ['😉'];
          break;
        case ':-D':
        case ':D':
          found = ['😂'];
          break;
        case ':-P':
        case ':P':
          found = ['😝', '😛', '😜'];
          break;
        case ':-(':
        case ':(':
          found = ['😟'];
          break;
        case ':-O':
        case ':O':
          found = ['😱', '😨'];
          break;
        case ':-|':
        case ':|':
          found = ['😐', '😑'];
          break;
        case ':-/':
        case ':/':
          found = ['😕', '😏'];
          break;
        case 'm(':
          found = ['🤦'];
        }

        callback(found);
      },
      replace: function(text) { return text; }
    }
  ], { maxCount: 750 })
    .on("textComplete:render", function(ev, menu) {
      if(menu.attr("data-strategy") == "emoji") {
        menu.css("display", "flex");
      }
      else {
        menu.css("display", "block");
      }
    });
};

/* eof */
<commit_msg>fix: typo<commit_after>/* -*- coding: utf-8 -*- */
/* global cforum */

cforum.mentions = function(elem) {
  $(elem).textcomplete([
    {
      id: 'mentions',
      match: /\B@([^\n]{2,})$/,
      search: function (term, callback) {
        $.get(cforum.baseUrl + 'users.json?nick=' + encodeURIComponent(term)).
          done(function(data) {
            callback($.map(data, function(element) { return element.username; }));
          });
      },
      index: 1,
      replace: function (mention) {
        return '@' + mention + ' ';
      }
    },

    {
      id: 'emoji',
      type: 'row',
      rowLength: 5,
      match: /\B:([\-+\w]*)$/,
      index: 1,
      search: function(term, callback) {
        callback($.map(Object.keys(cforum.emojis), function(emoji) {
          return emoji.indexOf(term) !== -1 ? emoji : null;
        }));
      },
      template: function(value) {
        return cforum.emojis[value];
      },
      replace: function (value) {
        return cforum.emojis[value];
      }
    },

    {
      id: 'typography',
      match: /(=>|<=|<=>|"|\.\.\.|\*|->|<-|-{1,3}|\^|\[tm\]?|=\/=?|=)$/,
      index: 1,
      search: function (term, callback) {
        var found = [];

        switch(term) {
        case '"':
          found = ['""', '„“', '‚‘'];
          break;
        case '...':
          found = ['…'];
          break;
        case '---':
          found = ['—'];
          break;
        case '--':
          found = ['–', '—'];
          break;
        case '-':
          found = ['−', '–', '—'];
          break;
        case '*':
          found = ['×'];
          break;
        case '->':
          found = ['→', '←', '↑', '↓'];
          break;
        case '<-':
          found = ['←', '→', '↑', '↓'];
          break;
        case '^':
          found = ['↑', '▲', '←', '→', '↓'];
          break;
        case '=>':
          found = ['⇒', '⇐', '⇔'];
          break;
        case '<=':
          found = ['⇐', '⇒', '⇔'];
          break;
        case '<=>':
          found = ['⇔', '⇐', '⇒'];
          break;
        case '[tm':
        case '[tm]':
          found = ['™'];
          break;
        case '=':
        case '=/':
        case '=/=':
          found = ['≠','≈'];
          break;
        }

        callback(found);
      },
      replace: function(text) {
        switch(text) {
          case '""':
            return ['"', '"'];
          case '„“':
            return ['„', '“'];
          case '‚‘':
            return ['‚', '‘'];
        }

        return text;
      }
    },

    {
      id: 'smileys',
      match: /\B(:-?\)|;-?\)|:-?D|:-?P|:-?\(|:-?O|:-?\||:-?\/|m\()$/i,
      index: 1,
      search: function (term, callback) {
        var found = [];

        term = term.toUpperCase();

        switch(term) {
        case ':-)':
        case ':)':
          found = ['😀'];
          break;
        case ';-)':
        case ';)':
          found = ['😉'];
          break;
        case ':-D':
        case ':D':
          found = ['😂'];
          break;
        case ':-P':
        case ':P':
          found = ['😝', '😛', '😜'];
          break;
        case ':-(':
        case ':(':
          found = ['😟'];
          break;
        case ':-O':
        case ':O':
          found = ['😱', '😨'];
          break;
        case ':-|':
        case ':|':
          found = ['😐', '😑'];
          break;
        case ':-/':
        case ':/':
          found = ['😕', '😏'];
          break;
        case 'm(':
          found = ['🤦'];
        }

        callback(found);
      },
      replace: function(text) { return text; }
    }
  ], { maxCount: 750 })
    .on("textComplete:render", function(ev, menu) {
      if(menu.attr("data-strategy") == "emoji") {
        menu.css("display", "flex");
      }
      else {
        menu.css("display", "block");
      }
    });
};

/* eof */
<|endoftext|>


<commit_before>/*!
 * Created with JetBrains WebStorm.
 * User: mschwartz
 * Date: 8/26/13
 * Time: 5:50 PM
 */

/**
 * @class support
 * @singleton
 *
 * The support namespace provides utility methods, mostly encryption.
 *
 */
/*global require, module */
/** @private */
module.exports = {
    uuid          : require('lib/uuid'),
    md5           : require('lib/md5'),
    sha1          : require('lib/sha1'),
    utf8_encode   : require('lib/utf8_encode'),
    randomString  : require('lib/randomString'),
    base64_encode : require('lib/base64_encode'),
    BCrypt        : require('lib/bcrypt').BCrypt
};
<commit_msg>Fix BCrypt<commit_after>/*!
 * Created with JetBrains WebStorm.
 * User: mschwartz
 * Date: 8/26/13
 * Time: 5:50 PM
 */

/**
 * @class support
 * @singleton
 *
 * The support namespace provides utility methods, mostly encryption.
 *
 */
/*global require, module */
/** @private */
module.exports = {
    uuid          : require('lib/uuid'),
    md5           : require('lib/md5'),
    sha1          : require('lib/sha1'),
    utf8_encode   : require('lib/utf8_encode'),
    randomString  : require('lib/randomString'),
    base64_encode : require('lib/base64_encode'),
    BCrypt        : require('lib/bcrypt')
};
<|endoftext|>


<commit_before>var FieldType = require('../Type');
var moment = require('moment');
var util = require('util');
var utils = require('keystone-utils');
var addPresenceToQuery = require('../../utils/addPresenceToQuery');

/**
 * Date FieldType Constructor
 * @extends Field
 * @api public
 */
function datearray (list, path, options) {
	this._nativeType = [Date];
	this._defaultSize = 'medium';
	this._underscoreMethods = ['format'];
	this._properties = ['formatString'];
	this.parseFormatString = options.parseFormat || 'YYYY-MM-DD';
	this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY');
	if (this.formatString && typeof this.formatString !== 'string') {
		throw new Error('FieldType.DateArray: options.format must be a string.');
	}
	this.separator = options.separator || ' | ';
	datearray.super_.call(this, list, path, options);
}
util.inherits(datearray, FieldType);

/**
 * Formats the field value
 */
datearray.prototype.format = function (item, format, separator) {
	var value = item.get(this.path);
	if (format || this.formatString) {
		value = value.map(function (d) {
			return moment(d).format(format || this._formatString);
		});
	}
	return value.join(separator || this.separator);
};

/**
 * Asynchronously confirms that the provided value is valid
 */
datearray.prototype.validateInput = function (data, callback) {
	var value = this.getValueFromData(data);
	var result = true;
	if (value !== undefined && value !== null && value !== '') {
		if (!Array.isArray(value)) {
			value = [value];
		}
		for (var i = 0; i < value.length; i++) {
			var currentValue;
			// If we pass it an epoch, parse it without the format string
			if (typeof value[i] === 'number') {
				currentValue = moment(value[i]);
			} else {
				currentValue = moment(value[i], this.parseFormatString);
			}
			// If moment does not think it's a valid date, invalidate
			if (!currentValue.isValid()) {
				result = false;
				break;
			}
		}
	}
	utils.defer(callback, result);
};

/**
 * Asynchronously confirms that the a value is present
 */
datearray.prototype.validateRequiredInput = function (item, data, callback) {
	var value = this.getValueFromData(data);
	var result = false;
	// If the field is undefined but has a value saved already, validate
	if (value === undefined) {
		if (item.get(this.path) && item.get(this.path).length) {
			result = true;
		}
	}
	if (typeof value === 'string' || typeof value === 'number') {
		if (moment(value).isValid()) {
			result = true;
		}
	// If it's an array of only dates and/or dateify-able data, validate
	} else if (Array.isArray(value)) {
		var invalidContent = false;
		for (var i = 0; i < value.length; i++) {
			var currentValue;
			// If we pass it an epoch, parse it without the format string
			if (typeof value[i] === 'number') {
				currentValue = moment(value[i]);
			} else {
				currentValue = moment(value[i], this.parseFormatString);
			}
			// If even a single item is not a valid date, invalidate
			if (!currentValue.isValid()) {
				invalidContent = true;
				break;
			}
		}
		if (invalidContent === false) {
			result = true;
		}
	}
	utils.defer(callback, result);
};

/**
 * Add filters to a query
 *
 * @param {Object} filter 			   		The data from the frontend
 * @param {String} filter.mode  	   		The filter mode, either one of "on",
 *                                     		"after", "before" or "between"
 * @param {String} [filter.presence='some'] The presence mode, either on of
 *                                          "none" and "some". Default: 'some'
 * @param {String|Object} filter.value 		The value that is filtered for
 */
datearray.prototype.addFilterToQuery = function (filter) {
	var query = {};
	if (filter.mode === 'between') {
		if (filter.after && filter.before) {
			filter.after = moment(filter.after);
			filter.before = moment(filter.before);
			if (filter.after.isValid() && filter.before.isValid()) {
				query[this.path] = {
					$gte: filter.after.startOf('day').toDate(),
					$lte: filter.before.endOf('day').toDate(),
				};
				query[this.path] = addPresenceToQuery(filter.presence, query[this.path]);
			}
		}
	} else if (filter.value) {
		var day = {
			moment: moment(filter.value),
		};
		day.start = day.moment.startOf('day').toDate();
		day.end = moment(filter.value).endOf('day').toDate();
		if (day.moment.isValid()) {
			if (filter.mode === 'after') {
				query[this.path] = { $gt: day.end };
			} else if (filter.mode === 'before') {
				query[this.path] = { $lt: day.start };
			} else {
				query[this.path] = { $gte: day.start, $lte: day.end };
			}
			query[this.path] = addPresenceToQuery(filter.presence, query[this.path]);
		}
	}
	return query;
};

/**
 * Checks that a valid array of dates has been provided in a data object
 * An empty value clears the stored value and is considered valid
 *
 * Deprecated
 */
datearray.prototype.inputIsValid = function (data, required, item) {

	var value = this.getValueFromData(data);
	var parseFormatString = this.parseFormatString;

	if (typeof value === 'string') {
		if (!moment(value, parseFormatString).isValid()) {
			return false;
		}
		value = [value];
	}

	if (required) {
		if (value === undefined && item && item.get(this.path) && item.get(this.path).length) {
			return true;
		}
		if (value === undefined || !Array.isArray(value)) {
			return false;
		}
		if (Array.isArray(value) && !value.length) {
			return false;
		}
	}

	if (Array.isArray(value)) {
		// filter out empty fields
		value = value.filter(function (date) {
			return date.trim() !== '';
		});
		// if there are no values left, and requried is true, return false
		if (required && !value.length) {
			return false;
		}
		// if any date in the array is invalid, return false
		if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) {
			return false;
		}
	}

	return (value === undefined || Array.isArray(value));

};

/**
 * Updates the value for this field in the item from a data object
 */
datearray.prototype.updateItem = function (item, data, callback) {

	var value = this.getValueFromData(data);

	if (value !== undefined) {
		if (Array.isArray(value)) {
			// Only save valid dates
			value = value.filter(function (date) {
				return moment(date).isValid();
			});
		}
		if (value === null) {
			value = [];
		}
		if (typeof value === 'string') {
			if (moment(value).isValid()) {
				value = [value];
			}
		}
		if (Array.isArray(value)) {
			item.set(this.path, value);
		}
	}

	process.nextTick(callback);
};

/* Export Field Type */
module.exports = datearray;
<commit_msg>Use DateType addFilterToQuery directly<commit_after>var FieldType = require('../Type');
var moment = require('moment');
var util = require('util');
var utils = require('keystone-utils');
var addPresenceToQuery = require('../../utils/addPresenceToQuery');
var DateType = require('../date/DateType');

/**
 * Date FieldType Constructor
 * @extends Field
 * @api public
 */
function datearray (list, path, options) {
	this._nativeType = [Date];
	this._defaultSize = 'medium';
	this._underscoreMethods = ['format'];
	this._properties = ['formatString'];
	this.parseFormatString = options.parseFormat || 'YYYY-MM-DD';
	this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY');
	if (this.formatString && typeof this.formatString !== 'string') {
		throw new Error('FieldType.DateArray: options.format must be a string.');
	}
	this.separator = options.separator || ' | ';
	datearray.super_.call(this, list, path, options);
}
util.inherits(datearray, FieldType);

/**
 * Formats the field value
 */
datearray.prototype.format = function (item, format, separator) {
	var value = item.get(this.path);
	if (format || this.formatString) {
		value = value.map(function (d) {
			return moment(d).format(format || this._formatString);
		});
	}
	return value.join(separator || this.separator);
};

/**
 * Asynchronously confirms that the provided value is valid
 */
datearray.prototype.validateInput = function (data, callback) {
	var value = this.getValueFromData(data);
	var result = true;
	if (value !== undefined && value !== null && value !== '') {
		if (!Array.isArray(value)) {
			value = [value];
		}
		for (var i = 0; i < value.length; i++) {
			var currentValue;
			// If we pass it an epoch, parse it without the format string
			if (typeof value[i] === 'number') {
				currentValue = moment(value[i]);
			} else {
				currentValue = moment(value[i], this.parseFormatString);
			}
			// If moment does not think it's a valid date, invalidate
			if (!currentValue.isValid()) {
				result = false;
				break;
			}
		}
	}
	utils.defer(callback, result);
};

/**
 * Asynchronously confirms that the a value is present
 */
datearray.prototype.validateRequiredInput = function (item, data, callback) {
	var value = this.getValueFromData(data);
	var result = false;
	// If the field is undefined but has a value saved already, validate
	if (value === undefined) {
		if (item.get(this.path) && item.get(this.path).length) {
			result = true;
		}
	}
	if (typeof value === 'string' || typeof value === 'number') {
		if (moment(value).isValid()) {
			result = true;
		}
	// If it's an array of only dates and/or dateify-able data, validate
	} else if (Array.isArray(value)) {
		var invalidContent = false;
		for (var i = 0; i < value.length; i++) {
			var currentValue;
			// If we pass it an epoch, parse it without the format string
			if (typeof value[i] === 'number') {
				currentValue = moment(value[i]);
			} else {
				currentValue = moment(value[i], this.parseFormatString);
			}
			// If even a single item is not a valid date, invalidate
			if (!currentValue.isValid()) {
				invalidContent = true;
				break;
			}
		}
		if (invalidContent === false) {
			result = true;
		}
	}
	utils.defer(callback, result);
};

/**
 * Add filters to a query
 *
 * @param {Object} filter 			   		The data from the frontend
 * @param {String} filter.mode  	   		The filter mode, either one of "on",
 *                                     		"after", "before" or "between"
 * @param {String} [filter.presence='some'] The presence mode, either on of
 *                                          "none" and "some". Default: 'some'
 * @param {String|Object} filter.value 		The value that is filtered for
 */
datearray.prototype.addFilterToQuery = function (filter) {
	var dateTypeAddFilterToQuery = DateType.prototype.addFilterToQuery.bind(this);
	var query = dateTypeAddFilterToQuery(filter);
	if (query !== {} && query[this.path]) {
		query[this.path] = addPresenceToQuery(filter.presence, query[this.path]);
	}
	return query;
};

/**
 * Checks that a valid array of dates has been provided in a data object
 * An empty value clears the stored value and is considered valid
 *
 * Deprecated
 */
datearray.prototype.inputIsValid = function (data, required, item) {

	var value = this.getValueFromData(data);
	var parseFormatString = this.parseFormatString;

	if (typeof value === 'string') {
		if (!moment(value, parseFormatString).isValid()) {
			return false;
		}
		value = [value];
	}

	if (required) {
		if (value === undefined && item && item.get(this.path) && item.get(this.path).length) {
			return true;
		}
		if (value === undefined || !Array.isArray(value)) {
			return false;
		}
		if (Array.isArray(value) && !value.length) {
			return false;
		}
	}

	if (Array.isArray(value)) {
		// filter out empty fields
		value = value.filter(function (date) {
			return date.trim() !== '';
		});
		// if there are no values left, and requried is true, return false
		if (required && !value.length) {
			return false;
		}
		// if any date in the array is invalid, return false
		if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) {
			return false;
		}
	}

	return (value === undefined || Array.isArray(value));

};

/**
 * Updates the value for this field in the item from a data object
 */
datearray.prototype.updateItem = function (item, data, callback) {

	var value = this.getValueFromData(data);

	if (value !== undefined) {
		if (Array.isArray(value)) {
			// Only save valid dates
			value = value.filter(function (date) {
				return moment(date).isValid();
			});
		}
		if (value === null) {
			value = [];
		}
		if (typeof value === 'string') {
			if (moment(value).isValid()) {
				value = [value];
			}
		}
		if (Array.isArray(value)) {
			item.set(this.path, value);
		}
	}

	process.nextTick(callback);
};

/* Export Field Type */
module.exports = datearray;
<|endoftext|>


<commit_before>var defaultValue = '0.',
 		currentValue = "",
		totalValue = "",
		previousOperator = "";

document.body.addEventListener("click", function(event) {
	var buttonContent = event.target.textContent;

	if (event.target.nodeName == 'BUTTON')
		if (Number(buttonContent) || buttonContent==="0") {
			currentValue += buttonContent;
			display(currentValue, digitalize);
		}
		else if (buttonContent == "CA") {
			currentValue = "";
			totalValue = "";
			display(defaultValue);
		}
		else if (buttonContent == "+") {
			if (!previousOperator)
				updatePreviousOperator(buttonContent);

			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				updatePreviousOperator(buttonContent);
				display(totalValue.toString(), digitalize);
			}
		}
		else if (buttonContent == "–") {
			if (!previousOperator)
				previousOperator = "-";

			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				updatePreviousOperator(buttonContent);
				display(totalValue.toString(), digitalize);
			}
		}
		else if (buttonContent == "x") {
			if (!previousOperator)
				updatePreviousOperator(buttonContent);

			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				updatePreviousOperator(buttonContent);
				display(totalValue.toString(), digitalize);
			}
		}
		else if (buttonContent == "÷") {
			if (!previousOperator)
				updatePreviousOperator(buttonContent);

			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				updatePreviousOperator(buttonContent);
				display(totalValue.toString(), digitalize);
			}
		}
		else if (buttonContent == "=") {
			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				previousOperator = "";
				display(totalValue.toString(), digitalize);
			}
		}
});

function digitalize(value) {
	if (value.length > 9)
		value = value.slice(0, 9);
	var span = '' + value.slice(value.length-1) + '.';
	var result = value.slice(0, value.length-1) + span;
	return result;
}

function display(value, callback) {
	if (callback) {
		document.getElementById('led').innerHTML = callback(value);
	} else {
		document.getElementById('led').innerHTML = value;
	}
}

function updateTotalValue(n1, n2, operator) {
	switch (previousOperator) {
		case "+":
			totalValue = n1 + n2;
			break;
		case "-":
			totalValue = n1 - n2;
			break;
		case "x":
			totalValue = n1 * n2;
			break;
		case "÷":
			totalValue = n1 / n2;
	}
}

function updatePreviousOperator(operator) {
	previousOperator = operator
}

function add(n1, n2) {
	return n1 + n2;
};

function subtract(n1, n2) {
	return n1 - n2;
};

function multiply(n1, n2) {
	return n1 * n2;
};

function divide(n1, n2) {
	return n1 / n2;
};<commit_msg>Display corrent decimal point position<commit_after>var defaultValue = '0.',
 		currentValue = "",
		totalValue = "",
		previousOperator = "";

document.body.addEventListener("click", function(event) {
	var buttonContent = event.target.textContent;

	if (event.target.nodeName == 'BUTTON')
		if (Number(buttonContent) || buttonContent==="0") {
			currentValue += buttonContent;
			display(currentValue, digitalize);
		}
		else if (buttonContent == "CA") {
			currentValue = "";
			totalValue = "";
			display(defaultValue);
		}
		else if (buttonContent == "+") {
			if (!previousOperator)
				updatePreviousOperator(buttonContent);

			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				updatePreviousOperator(buttonContent);
				display(totalValue.toString(), digitalize);
			}
		}
		else if (buttonContent == "–") {
			if (!previousOperator)
				previousOperator = "-";

			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				updatePreviousOperator(buttonContent);
				display(totalValue.toString(), digitalize);
			}
		}
		else if (buttonContent == "x") {
			if (!previousOperator)
				updatePreviousOperator(buttonContent);

			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				updatePreviousOperator(buttonContent);
				display(totalValue.toString(), digitalize);
			}
		}
		else if (buttonContent == "÷") {
			if (!previousOperator)
				updatePreviousOperator(buttonContent);

			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				updatePreviousOperator(buttonContent);
				display(totalValue.toString(), digitalize);
			}
		}
		else if (buttonContent == "=") {
			if (currentValue) {
				if (totalValue) {
					updateTotalValue(Number(totalValue), Number(currentValue), previousOperator);
				} else {
					totalValue = currentValue;
				}
				currentValue = "";
				previousOperator = "";
				display(totalValue.toString(), digitalize);
			}
		}
});

function digitalize(value) {
	if (value.length > 9)
		value = value.slice(0, 9);

	var decimalIndex = value.indexOf(".");
	if (decimalIndex !== -1) {
		var span = '' + value.substring(decimalIndex-1, decimalIndex+1) + '';
		var result = value.substring(0, decimalIndex-1) + span + value.substring(decimalIndex+1, value.length);
	} else {
		var span = '' + value[value.length-1] + '.';
		var result = value.substring(0, value.length-1) + span;
	}
  console.log(value);
  console.log(result);
	return result;
}

function display(value, callback) {
	if (callback) {
		document.getElementById('led').innerHTML = callback(value);
	} else {
		document.getElementById('led').innerHTML = value;
	}
}

function updateTotalValue(n1, n2, operator) {
	switch (previousOperator) {
		case "+":
			totalValue = n1 + n2;
			break;
		case "-":
			totalValue = n1 - n2;
			break;
		case "x":
			totalValue = n1 * n2;
			break;
		case "÷":
			totalValue = n1 / n2;
	}
}

function updatePreviousOperator(operator) {
	previousOperator = operator
}<|endoftext|>


<commit_before>//Tell jshint (atom package) to stop showing certain irrelevent warnings.
/*jshint esversion: 6 */

// Constants

/**Critical number of harvesters. We need to have at least this many
 * harvesters before building bigger creeps
 */
let CRITICAL_HARVESTER_COUNT = 2;

/**Minimum number of harvesters.*/
let HARVESTER_MINIMUM = 6;

/**Minimum number of upgraders.*/
let UPGRADER_MINIMUM = 2;

/**Minimum number of builders.*/
let BUILDER_MINIMUM = 2;

/**Minimum number of builders.*/
let REPAIRER_MINIMUM = 2;

/**Only targets with less that this much health will be repaired by towers.*/
let TOWER_REPAIR_MAX_HEALTH = 200000;

/**Minimum energy for towers to save for attacking hostile targets.*/
let TOWER_MINIMUM_ENERGY = 800;

/**filter for helping a tower find a target to repair.*/
let TOWER_REPAIR_TARGET = {
  filter: (structure) => structure.hits < structure.hitsMax &&
    //structure.structureType != STRUCTURE_WALL &&
    structure.hits < TOWER_REPAIR_MAX_HEALTH
};

/**Base Worker Body. 2W, 1C, 1M.*/
let BASE_WORKER_BODY = [WORK, WORK, WORK, CARRY, MOVE, MOVE];

// Require other modules and prototypes.

/**Harvester role.*/
let roleHarvester = require('role.harvester');

/**Upgrader role.*/
let roleUpgrader = require('role.upgrader');

/**Builder role.*/
let roleBuilder = require('role.builder');

/**Repairer role.*/
let roleRepairer = require('role.repairer');

/**Prototype for spawn objects.*/
require('prototype.spawn')();

/**Functions that are used across different modules.*/
let functions = require('functions');

//Begin main loop.
module.exports.loop = function() {

  //Cleanup memory.
  functions.clearDeadCreepMemory();

  let spawn = Game.spawns.Spawn1;

  //Count the number of each creep role.
  let upgraders = _.filter(Game.creeps, (creep) =>
    creep.memory.role == 'upgrader');
  console.log('Upgraders: ' + upgraders.length);

  let builders = _.filter(Game.creeps, (creep) =>
    creep.memory.role == 'builder');
  console.log('Builders: ' + builders.length);

  let harvesters = _.filter(Game.creeps, (creep) =>
    creep.memory.role == 'harvester');
  console.log('Harvesters: ' + harvesters.length);

  let repairers = _.filter(Game.creeps, (creep) =>
    creep.memory.role == 'repairer');
  console.log('Repairers: ' + repairers.length);

  let name;
  let energyCapacity = spawn.room.energyCapacityAvailable;

  //Autobuild creeps:
  //Prioritize maintaining the minimum number of each creep in order.
  if (harvesters.length < HARVESTER_MINIMUM) {
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'harvester');
    if (name == ERR_NOT_ENOUGH_ENERGY &&
      harvesters.length <= CRITICAL_HARVESTER_COUNT) {
      //If very few harvesters are alive, build one
      //using whatever energy is available.
      spawn.createBiggestWorkerCreep(spawn.room.energyAvailable, 'harvester');
    }
  } else if (repairers.length < REPAIRER_MINIMUM) {
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'repairer');
  } else if (builders.length < BUILDER_MINIMUM) {
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'builder');
  } else if (upgraders.length < UPGRADER_MINIMUM) {
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'upgrader');
  } else {
    //Excess creeps will be of this role.
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'builder');
  }

  //For each creep, have it act (run) according to its role.
  for (let name in Game.creeps) {
    let creep = Game.creeps[name];
    if (creep.memory.role == 'harvester') {
      roleHarvester.run(creep);
    } else if (creep.memory.role == 'upgrader') {
      roleUpgrader.run(creep);
    } else if (creep.memory.role == 'builder') {
      roleBuilder.run(creep);
    } else if (creep.memory.role == 'repairer') {
      roleRepairer.run(creep);
    }
  }

  //Tower logic

  //get towers.
  let towers = _.filter(Game.structures, (structure) =>
    structure.structureType == STRUCTURE_TOWER);
  for (let tower of towers) {

    //find closest damaged structure.
    let closestDamagedStructure = tower.pos
      .findClosestByRange(FIND_STRUCTURES, TOWER_REPAIR_TARGET);

    //find closest hostile creep.
    let closestHostile = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);

    //prioritize shooting enemy creeps over repairing structures.
    if (closestHostile) {
      tower.attack(closestHostile);
    } else if (closestDamagedStructure &&
      tower.energy > TOWER_MINIMUM_ENERGY) {
      //Only repair if enough energy is saved up (in case of attacks).
      tower.repair(closestDamagedStructure);
    }
  }
}; //End main loop.
<commit_msg>Changed critical harvester logic to be easier to understand.<commit_after>//Tell jshint (atom package) to stop showing certain irrelevent warnings.
/*jshint esversion: 6 */

// Constants

/**Critical number of harvesters. We need to have at least this many
 * harvesters before building bigger creeps
 */
let CRITICAL_HARVESTER_COUNT = 3;

/**Minimum number of harvesters.*/
let HARVESTER_MINIMUM = 6;

/**Minimum number of upgraders.*/
let UPGRADER_MINIMUM = 2;

/**Minimum number of builders.*/
let BUILDER_MINIMUM = 2;

/**Minimum number of builders.*/
let REPAIRER_MINIMUM = 2;

/**Only targets with less that this much health will be repaired by towers.*/
let TOWER_REPAIR_MAX_HEALTH = 200000;

/**Minimum energy for towers to save for attacking hostile targets.*/
let TOWER_MINIMUM_ENERGY = 800;

/**filter for helping a tower find a target to repair.*/
let TOWER_REPAIR_TARGET = {
  filter: (structure) => structure.hits < structure.hitsMax &&
    //structure.structureType != STRUCTURE_WALL &&
    structure.hits < TOWER_REPAIR_MAX_HEALTH
};

/**Base Worker Body. 2W, 1C, 1M.*/
let BASE_WORKER_BODY = [WORK, WORK, WORK, CARRY, MOVE, MOVE];

// Require other modules and prototypes.

/**Harvester role.*/
let roleHarvester = require('role.harvester');

/**Upgrader role.*/
let roleUpgrader = require('role.upgrader');

/**Builder role.*/
let roleBuilder = require('role.builder');

/**Repairer role.*/
let roleRepairer = require('role.repairer');

/**Prototype for spawn objects.*/
require('prototype.spawn')();

/**Functions that are used across different modules.*/
let functions = require('functions');

//Begin main loop.
module.exports.loop = function() {

  //Cleanup memory.
  functions.clearDeadCreepMemory();

  let spawn = Game.spawns.Spawn1;

  //Count the number of each creep role.
  let upgraders = _.filter(Game.creeps, (creep) =>
    creep.memory.role == 'upgrader');
  console.log('Upgraders: ' + upgraders.length);

  let builders = _.filter(Game.creeps, (creep) =>
    creep.memory.role == 'builder');
  console.log('Builders: ' + builders.length);

  let harvesters = _.filter(Game.creeps, (creep) =>
    creep.memory.role == 'harvester');
  console.log('Harvesters: ' + harvesters.length);

  let repairers = _.filter(Game.creeps, (creep) =>
    creep.memory.role == 'repairer');
  console.log('Repairers: ' + repairers.length);

  let name;
  let energyCapacity = spawn.room.energyCapacityAvailable;

  //Autobuild creeps:
  //Prioritize maintaining the minimum number of each creep in order.
  if (harvesters.length < HARVESTER_MINIMUM) {
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'harvester');
    if (name == ERR_NOT_ENOUGH_ENERGY &&
      harvesters.length < CRITICAL_HARVESTER_COUNT) {
      //If very few harvesters are alive, build one
      //using whatever energy is available.
      spawn.createBiggestWorkerCreep(spawn.room.energyAvailable, 'harvester');
    }
  } else if (repairers.length < REPAIRER_MINIMUM) {
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'repairer');
  } else if (builders.length < BUILDER_MINIMUM) {
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'builder');
  } else if (upgraders.length < UPGRADER_MINIMUM) {
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'upgrader');
  } else {
    //Excess creeps will be of this role.
    name = spawn.createBiggestWorkerCreep(energyCapacity, 'builder');
  }

  //For each creep, have it act (run) according to its role.
  for (let name in Game.creeps) {
    let creep = Game.creeps[name];
    if (creep.memory.role == 'harvester') {
      roleHarvester.run(creep);
    } else if (creep.memory.role == 'upgrader') {
      roleUpgrader.run(creep);
    } else if (creep.memory.role == 'builder') {
      roleBuilder.run(creep);
    } else if (creep.memory.role == 'repairer') {
      roleRepairer.run(creep);
    }
  }

  //Tower logic

  //get towers.
  let towers = _.filter(Game.structures, (structure) =>
    structure.structureType == STRUCTURE_TOWER);
  for (let tower of towers) {

    //find closest damaged structure.
    let closestDamagedStructure = tower.pos
      .findClosestByRange(FIND_STRUCTURES, TOWER_REPAIR_TARGET);

    //find closest hostile creep.
    let closestHostile = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);

    //prioritize shooting enemy creeps over repairing structures.
    if (closestHostile) {
      tower.attack(closestHostile);
    } else if (closestDamagedStructure &&
      tower.energy > TOWER_MINIMUM_ENERGY) {
      //Only repair if enough energy is saved up (in case of attacks).
      tower.repair(closestDamagedStructure);
    }
  }
}; //End main loop.
<|endoftext|>


<commit_before>/*
 * jQuery Behavior Plugin: Define rich behaviors that include both event
 * handlers and (un)transformations on DOM elements.
 *
 * Copyright (c) 2010 Florian Schäfer (florian.schaefer@gmail.com)
 * Dual licensed under the MIT (MIT_LICENSE.txt)
 * and GPL Version 2 (GPL_LICENSE.txt) licenses.
 *
 * Version: 0.9
 * Requires: jQuery 1.4.2+ and Live Query 1.1+.
 *
 */

;(function($, attr) {

    // jQuery supports getData, setData and changeData,
    // support getAttr, setAttr, changeAttr too.
    $.attr = function (elem, name, value) {
        var current = attr (elem, name), // read current value.
        retval = current;

        if (!value) {
            // we are getting a value.
            $.event.trigger ('getAttr', {
                attribute: name,
                from: current,
                to: value
            }, elem);
        } else { // writing
            // we are setting a value.
            $.event.trigger ('setAttr', {
                attribute: name,
                from: current,
                to: value
            }, elem);

            retval = attr (elem, name, value); // call original.

            // value or type changed.
            if (current !== value) {
                $.event.trigger ('changeAttr', {
                    attribute: name,
                    from: current,
                    to: value
                }, elem);
            }
        }
        return retval; // return original
    }

})(jQuery, jQuery.attr);

;(function($, undefined) {

    if (!$.fn.livequery) throw "jquery.behavior.js: jQuery Plugin: Live Query not loaded.";

    $.behavior = function (metabehaviors, context) {

        context = context || window.document;

        // Handle $.behavior (""), $.behavior (null), or $.behavior (undefined).
        if (!metabehaviors) {
            return this;
        }

        // Handle $.behavior ([{ ... }, { ... }, ... ], [context]).
        if ($.isArray (metabehaviors)) {
            return $.each (metabehaviors, function () {
                $.behavior (this, context);
            });
        }

        // Handle $.behavior ({ ... }, [context]).
        return $.each (metabehaviors, function (selector, metabehavior) {

            metabehavior = $.extend ({
                options: {},
                transform: undefined,
                untransform: undefined
            }, metabehavior);

            // Cache element.
            var $element = $(selector, context);

            // Transform DOM element.
            if ($.isFunction (metabehavior['transform'])) {
                $element.livequery (function () {
                    metabehavior['transform'].apply (this, arguments);
                }, metabehavior['untransform']);
            }

            // Bind all events.
            for (var event in metabehavior) {
                switch (event) {
                    case 'transform':
                    case 'untransform':
                    case 'methods':
                    case 'options':
                        // Don't handle these here.
                        continue;

                    default:
                        if (metabehavior.options['expire']) {
                            $element.expire (event);
                        }

                        if ($.isFunction (metabehavior[event])) {
                            $element.livequery (event, metabehavior[event]);
                        }
                        break;
                }
            }

            delete metabehavior;

        });
    };

})(jQuery);
<commit_msg>Remove 'methods' from special events.<commit_after>/*
 * jQuery Behavior Plugin: Define rich behaviors that include both event
 * handlers and (un)transformations on DOM elements.
 *
 * Copyright (c) 2010 Florian Schäfer (florian.schaefer@gmail.com)
 * Dual licensed under the MIT (MIT_LICENSE.txt)
 * and GPL Version 2 (GPL_LICENSE.txt) licenses.
 *
 * Version: 0.9
 * Requires: jQuery 1.4.2+ and Live Query 1.1+.
 *
 */

;(function($, attr) {

    // jQuery supports getData, setData and changeData,
    // support getAttr, setAttr, changeAttr too.
    $.attr = function (elem, name, value) {
        var current = attr (elem, name), // read current value.
        retval = current;

        if (!value) {
            // we are getting a value.
            $.event.trigger ('getAttr', {
                attribute: name,
                from: current,
                to: value
            }, elem);
        } else { // writing
            // we are setting a value.
            $.event.trigger ('setAttr', {
                attribute: name,
                from: current,
                to: value
            }, elem);

            retval = attr (elem, name, value); // call original.

            // value or type changed.
            if (current !== value) {
                $.event.trigger ('changeAttr', {
                    attribute: name,
                    from: current,
                    to: value
                }, elem);
            }
        }
        return retval; // return original
    }

})(jQuery, jQuery.attr);

;(function($, undefined) {

    if (!$.fn.livequery) throw "jquery.behavior.js: jQuery Plugin: Live Query not loaded.";

    $.behavior = function (metabehaviors, context) {

        context = context || window.document;

        // Handle $.behavior (""), $.behavior (null), or $.behavior (undefined).
        if (!metabehaviors) {
            return this;
        }

        // Handle $.behavior ([{ ... }, { ... }, ... ], [context]).
        if ($.isArray (metabehaviors)) {
            return $.each (metabehaviors, function () {
                $.behavior (this, context);
            });
        }

        // Handle $.behavior ({ ... }, [context]).
        return $.each (metabehaviors, function (selector, metabehavior) {

            metabehavior = $.extend ({
                options: {},
                transform: undefined,
                untransform: undefined
            }, metabehavior);

            // Cache element.
            var $element = $(selector, context);

            // Transform DOM element.
            if ($.isFunction (metabehavior['transform'])) {
                $element.livequery (function () {
                    metabehavior['transform'].apply (this, arguments);
                }, metabehavior['untransform']);
            }

            // Bind all events.
            for (var event in metabehavior) {
                switch (event) {
                    case 'transform':
                    case 'untransform':
                    case 'options':
                        // Don't handle these here.
                        continue;

                    default:
                        if (metabehavior.options['expire']) {
                            $element.expire (event);
                        }

                        if ($.isFunction (metabehavior[event])) {
                            $element.livequery (event, metabehavior[event]);
                        }
                        break;
                }
            }

            delete metabehavior;

        });
    };

})(jQuery);
<|endoftext|>


<commit_before>import { registerOption } from "pretty-text/pretty-text";

registerOption((siteSettings, opts) => {
  opts.features["spoiler-alert"] = !!siteSettings.spoiler_enabled;
});

const CONTAINS_BLOCK_REGEX = /\n|<img|!\[[^\]]*\][(\[]/;

function insertSpoiler(_, spoiler) {
  const element = CONTAINS_BLOCK_REGEX.test(spoiler) ? "div" : "span";
  return `<${element} class='spoiler'>${spoiler}</${element}>`;
}

function replaceSpoilers(text) {
  text = text || "";
  while (
    text !==
    (text = text.replace(
      /\[spoiler\]((?:(?!\[spoiler\]|\[\/spoiler\])[\S\s])*)\[\/spoiler\]/gi,
      insertSpoiler
    ))
  ) {}
  return text;
}

function setupMarkdownIt(helper) {
  helper.registerOptions((opts, siteSettings) => {
    opts.features["spoiler-alert"] = !!siteSettings.spoiler_enabled;
  });

  helper.registerPlugin((md) => {
    md.inline.bbcode.ruler.push("spoiler", {
      tag: "spoiler",
      wrap: "span.spoiler",
    });

    md.block.bbcode.ruler.push("spoiler", {
      tag: "spoiler",
      wrap: "div.spoiler",
    });
  });
}

export function setup(helper) {
  helper.allowList(["span.spoiler", "div.spoiler"]);

  if (helper.markdownIt) {
    setupMarkdownIt(helper);
  } else {
    helper.addPreProcessor(replaceSpoilers);
  }
}
<commit_msg>DEV: Remove a deprecated no-op call (#72)<commit_after>const CONTAINS_BLOCK_REGEX = /\n|<img|!\[[^\]]*\][(\[]/;

function insertSpoiler(_, spoiler) {
  const element = CONTAINS_BLOCK_REGEX.test(spoiler) ? "div" : "span";
  return `<${element} class='spoiler'>${spoiler}</${element}>`;
}

function replaceSpoilers(text) {
  text = text || "";
  while (
    text !==
    (text = text.replace(
      /\[spoiler\]((?:(?!\[spoiler\]|\[\/spoiler\])[\S\s])*)\[\/spoiler\]/gi,
      insertSpoiler
    ))
  ) {}
  return text;
}

function setupMarkdownIt(helper) {
  helper.registerOptions((opts, siteSettings) => {
    opts.features["spoiler-alert"] = !!siteSettings.spoiler_enabled;
  });

  helper.registerPlugin((md) => {
    md.inline.bbcode.ruler.push("spoiler", {
      tag: "spoiler",
      wrap: "span.spoiler",
    });

    md.block.bbcode.ruler.push("spoiler", {
      tag: "spoiler",
      wrap: "div.spoiler",
    });
  });
}

export function setup(helper) {
  helper.allowList(["span.spoiler", "div.spoiler"]);

  if (helper.markdownIt) {
    setupMarkdownIt(helper);
  } else {
    helper.addPreProcessor(replaceSpoilers);
  }
}
<|endoftext|>


<commit_before>const request = require('request');
const config = require('../config/config');
const logger = require('../config/logger');

/**
 *  Send a text message to the Messenger Platform. This simply formats the
 *  message data properly to match what is expected by the Messenger Platform.
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {Object} text: the text to be sent to the Messenger Platform.
 **/

function sendTextMessage(recipientId, text) {
    const data = {
        recipient: {
            id: recipientId
        },
        message: { text }
    };
    return sendMessageToMessenger(data);
}

/**
 *  Send a message with attachment to the Messenger Platform. This simply
 *  formats the message data properly to match what is expected by the
 *  Messenger Platform.
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {Object} attachment: a single attachment object to be sent to the
 *      Messenger Platform.
 **/

function sendAttachment(recipientId, attachment) {
    const data = {
        recipient: {
            id: recipientId
        },
        message: { attachment }
    };
    return sendMessageToMessenger(data);
}

/**
 *  Send a message following the Generic Template format described in
 *  https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template
 *  This simply formats the message data properly to match what is expected by
 *  the Messenger Platform.
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {Array} elements: array of data for configuring each bubble in the
 *      generic template message.
 **/

function sendGenericTemplate(recipientId, elements) {
    const data = {
        recipient: {
            id: recipientId
        },
        message: {
            attachment: {
                type: 'template',
                payload: {
                    template_type: 'generic',
                    elements: elements
                }
            }
        }
    };
    return sendMessageToMessenger(data);
}

/**
 *  Send a message following the Button Template format described in
 *  https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template
 *  This simply formats the message data properly to match what is expected by
 *  the Messenger Platform.
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {String} text: a text message that will appear in the main body of
 *      the message, above the buttons.
 *  @param {Array} buttons: array of button configuration objects.
 **/

function sendButtonTemplate(recipientId, text, buttons) {
    const data = {
        recipient: {
            id: recipientId
        },
        message: {
            attachment: {
                type: 'template',
                payload: {
                    template_type: 'button',
                    text: text,
                    buttons: buttons
                }
            }
        }
    };
    return sendMessageToMessenger(data);
}

/**
 *  Set the typing indicator to let users know that we are already processing
 *  their request (these are called "Sender Actions").
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {String} state: the state to set the sender action to. Possible
 *      values are: "typing_on", "typing_off", and "mark_seen".
 **/

function setSenderAction(recipientId, state) {
    const data = {
        recipient: {
            id: recipientId
        },
        sender_action: state
    };
    return sendMessageToMessenger(data);
}

/**
 *  Set the greeting text for conversations with our Facebook Page. Greeting
 *  texts are only visible on the first time the user interacts with our
 *  Facebook Page.
 *
 *  @param {String} text: the message to set the greeting text to.
 **/

function setGreetingText(text) {
    const settings = {
        setting_type: 'greeting',
        greeting: { text }
    };
    return setMessengerThreadSettings(settings);
}

/**
 *  Configure the Get Started button for conversations with our Facebook Page.
 *  The Get Started button is only visible on the first time the user interacts
 *  with our Facebook Page.
 *
 *  @param {String} payload: the payload to send back to our webhook when the
 *      Get Started button is clicked.
 **/

function setGetStartedButton(payload) {
    const settings = {
        setting_type: 'call_to_actions',
        thread_state: 'new_thread',
        call_to_actions: [ { payload } ]
    };
    return setMessengerThreadSettings(settings);
}

/**
 *  Configure the persistent menu for conversation threads with our Facebook
 *  Page. Menu items can send back a postback event to our webhook or open a
 *  web url.
 *
 *  @param {Array} actions: array of menu item objects configurations.
 **/

function setPersistentMenu(actions) {
    const settings = {
        setting_type: 'call_to_actions',
        thread_state: 'existing_thread',
        call_to_actions: actions
    };
    return setMessengerThreadSettings(settings);
}

/**
 *  Perform the actual sending of messages to the Messenger Platform by sending
 *  a POST request to the Send API endpoint, providing the message payload we
 *  want to send, as well as the access token of our Facebook Page.
 *
 *  @param {Object} data: the message payload to be sent to the Messenger
 *      Platform.
 **/

function sendMessageToMessenger(data) {
    const requestData = {
        url: 'https://graph.facebook.com/v2.6/me/messages',
        method: 'POST',
        qs: { access_token: config.get('FB_PAGE_ACCESS_TOKEN') },
        json: data
    };

    return new Promise((resolve, reject) => {
        request(requestData, (error, response, body) => {
            if (!error && response.statusCode === 200) {
                logger.info(`Message sent successfully.`);
                logger.debug(body);
                resolve(body);
            } else {
                logger.error('Failed to send message.');
                logger.debug(body);
                reject(body);
            }
        })
    });
}

/**
 *  Set Messenger conversation thread settings by sending a POST request
 *  containing the desired settings to the Messenger Platform Thread Settings
 *  API endpoint.
 *
 *  @param {Object} settings: the thread settings to send to the API endpoint.
 *      To know more about the format of this object, check out
 *      https://developers.facebook.com/docs/messenger-platform/thread-settings
 **/

function setMessengerThreadSettings(settings) {
    const requestData = {
        url: 'https://graph.facebook.com/v2.6/me/thread_settings',
        method: 'POST',
        qs: { access_token: config.get('FB_PAGE_ACCESS_TOKEN') },
        json: settings
    };

    return new Promise((resolve, reject) => {
        request(requestData, (error, response, body) => {
            if (!error && response.statusCode === 200) {
                logger.info('Thread settings successfully set.');
                logger.debug(body);
                resolve(body);
            } else {
                logger.error('Failed to set thread settings.');
                logger.debug(body);
                reject(body);
            }
        })
    });
}

exports.sendTextMessage = sendTextMessage;
exports.sendAttachment = sendAttachment;
exports.sendGenericTemplate = sendGenericTemplate;
exports.sendButtonTemplate = sendButtonTemplate;
exports.setSenderAction = setSenderAction;
exports.setGreetingText = setGreetingText;
exports.setGetStartedButton = setGetStartedButton;
exports.setPersistentMenu = setPersistentMenu;
<commit_msg>add missing semicolons for request call<commit_after>const request = require('request');
const config = require('../config/config');
const logger = require('../config/logger');

/**
 *  Send a text message to the Messenger Platform. This simply formats the
 *  message data properly to match what is expected by the Messenger Platform.
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {Object} text: the text to be sent to the Messenger Platform.
 **/

function sendTextMessage(recipientId, text) {
    const data = {
        recipient: {
            id: recipientId
        },
        message: { text }
    };
    return sendMessageToMessenger(data);
}

/**
 *  Send a message with attachment to the Messenger Platform. This simply
 *  formats the message data properly to match what is expected by the
 *  Messenger Platform.
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {Object} attachment: a single attachment object to be sent to the
 *      Messenger Platform.
 **/

function sendAttachment(recipientId, attachment) {
    const data = {
        recipient: {
            id: recipientId
        },
        message: { attachment }
    };
    return sendMessageToMessenger(data);
}

/**
 *  Send a message following the Generic Template format described in
 *  https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template
 *  This simply formats the message data properly to match what is expected by
 *  the Messenger Platform.
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {Array} elements: array of data for configuring each bubble in the
 *      generic template message.
 **/

function sendGenericTemplate(recipientId, elements) {
    const data = {
        recipient: {
            id: recipientId
        },
        message: {
            attachment: {
                type: 'template',
                payload: {
                    template_type: 'generic',
                    elements: elements
                }
            }
        }
    };
    return sendMessageToMessenger(data);
}

/**
 *  Send a message following the Button Template format described in
 *  https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template
 *  This simply formats the message data properly to match what is expected by
 *  the Messenger Platform.
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {String} text: a text message that will appear in the main body of
 *      the message, above the buttons.
 *  @param {Array} buttons: array of button configuration objects.
 **/

function sendButtonTemplate(recipientId, text, buttons) {
    const data = {
        recipient: {
            id: recipientId
        },
        message: {
            attachment: {
                type: 'template',
                payload: {
                    template_type: 'button',
                    text: text,
                    buttons: buttons
                }
            }
        }
    };
    return sendMessageToMessenger(data);
}

/**
 *  Set the typing indicator to let users know that we are already processing
 *  their request (these are called "Sender Actions").
 *
 *  @param {String} recipientId: the id of the user to send the message to.
 *  @param {String} state: the state to set the sender action to. Possible
 *      values are: "typing_on", "typing_off", and "mark_seen".
 **/

function setSenderAction(recipientId, state) {
    const data = {
        recipient: {
            id: recipientId
        },
        sender_action: state
    };
    return sendMessageToMessenger(data);
}

/**
 *  Set the greeting text for conversations with our Facebook Page. Greeting
 *  texts are only visible on the first time the user interacts with our
 *  Facebook Page.
 *
 *  @param {String} text: the message to set the greeting text to.
 **/

function setGreetingText(text) {
    const settings = {
        setting_type: 'greeting',
        greeting: { text }
    };
    return setMessengerThreadSettings(settings);
}

/**
 *  Configure the Get Started button for conversations with our Facebook Page.
 *  The Get Started button is only visible on the first time the user interacts
 *  with our Facebook Page.
 *
 *  @param {String} payload: the payload to send back to our webhook when the
 *      Get Started button is clicked.
 **/

function setGetStartedButton(payload) {
    const settings = {
        setting_type: 'call_to_actions',
        thread_state: 'new_thread',
        call_to_actions: [ { payload } ]
    };
    return setMessengerThreadSettings(settings);
}

/**
 *  Configure the persistent menu for conversation threads with our Facebook
 *  Page. Menu items can send back a postback event to our webhook or open a
 *  web url.
 *
 *  @param {Array} actions: array of menu item objects configurations.
 **/

function setPersistentMenu(actions) {
    const settings = {
        setting_type: 'call_to_actions',
        thread_state: 'existing_thread',
        call_to_actions: actions
    };
    return setMessengerThreadSettings(settings);
}

/**
 *  Perform the actual sending of messages to the Messenger Platform by sending
 *  a POST request to the Send API endpoint, providing the message payload we
 *  want to send, as well as the access token of our Facebook Page.
 *
 *  @param {Object} data: the message payload to be sent to the Messenger
 *      Platform.
 **/

function sendMessageToMessenger(data) {
    const requestData = {
        url: 'https://graph.facebook.com/v2.6/me/messages',
        method: 'POST',
        qs: { access_token: config.get('FB_PAGE_ACCESS_TOKEN') },
        json: data
    };

    return new Promise((resolve, reject) => {
        request(requestData, (error, response, body) => {
            if (!error && response.statusCode === 200) {
                logger.info(`Message sent successfully.`);
                logger.debug(body);
                resolve(body);
            } else {
                logger.error('Failed to send message.');
                logger.debug(body);
                reject(body);
            }
        });
    });
}

/**
 *  Set Messenger conversation thread settings by sending a POST request
 *  containing the desired settings to the Messenger Platform Thread Settings
 *  API endpoint.
 *
 *  @param {Object} settings: the thread settings to send to the API endpoint.
 *      To know more about the format of this object, check out
 *      https://developers.facebook.com/docs/messenger-platform/thread-settings
 **/

function setMessengerThreadSettings(settings) {
    const requestData = {
        url: 'https://graph.facebook.com/v2.6/me/thread_settings',
        method: 'POST',
        qs: { access_token: config.get('FB_PAGE_ACCESS_TOKEN') },
        json: settings
    };

    return new Promise((resolve, reject) => {
        request(requestData, (error, response, body) => {
            if (!error && response.statusCode === 200) {
                logger.info('Thread settings successfully set.');
                logger.debug(body);
                resolve(body);
            } else {
                logger.error('Failed to set thread settings.');
                logger.debug(body);
                reject(body);
            }
        });
    });
}

exports.sendTextMessage = sendTextMessage;
exports.sendAttachment = sendAttachment;
exports.sendGenericTemplate = sendGenericTemplate;
exports.sendButtonTemplate = sendButtonTemplate;
exports.setSenderAction = setSenderAction;
exports.setGreetingText = setGreetingText;
exports.setGetStartedButton = setGetStartedButton;
exports.setPersistentMenu = setPersistentMenu;
<|endoftext|>


<commit_before>'use strict';

angular.module('confRegistrationWebApp')
  .controller('FormDropAreaCtrl', function ($rootScope, $scope, $modal, uuid, GrowlService) {
    $scope.$on('dragVars', function (event, x) {
      $scope.blockId = x.blockId;
      $scope.moveType = x.moveType;
    });

    function makePositionArray() {
      var tempPositionArray = [];
      $scope.conference.registrationPages.forEach(function (page, pageIndex) {
        page.blocks.forEach(function (block, blockIndex) {
          tempPositionArray[block.id] = {page: pageIndex, block: blockIndex};
        });
      });
      return tempPositionArray;
    }

    $scope.moveBlock = function (blockId, newPage, newPosition) {
      var tempPositionArray = makePositionArray();
      var newPageIndex = _.findIndex($scope.conference.registrationPages, { id: newPage });

      var origPageIndex = tempPositionArray[blockId].page;
      var origBlock = $scope.conference.registrationPages[origPageIndex].blocks[tempPositionArray[blockId].block];
      origBlock.pageId = newPage;
      $scope.$apply(function (scope) {
        scope.deleteBlock(blockId, false);
        scope.conference.registrationPages[newPageIndex].blocks.splice(newPosition, 0, origBlock);
      });
    };

    $scope.insertBlock = function (blockType, newPage, newPosition) {
      var newPageIndex = _.findIndex($scope.conference.registrationPages, { id: newPage });

      var blockTypeFriendly = '';
      switch (blockType) {
      case 'paragraphContent':
        blockTypeFriendly = 'Information';
        break;
      case 'textQuestion':
        blockTypeFriendly = 'Text Field';
        break;
      case 'radioQuestion':
        blockTypeFriendly = 'Multiple choice block';
        break;
      case 'checkboxQuestion':
        blockTypeFriendly = 'Checkbox block';
        break;
      case 'selectQuestion':
        blockTypeFriendly = 'Dropdown select block';
        break;
      case 'emailQuestion':
        blockTypeFriendly = 'Email';
        break;
      case 'nameQuestion':
        blockTypeFriendly = 'Name';
        break;
      case 'phoneQuestion':
        blockTypeFriendly = 'Phone';
        break;
      default:
        blockTypeFriendly = 'New ' + blockType + ' Block';
      }

      var newBlock = {
        id: uuid(),
        content: '',
        pageId: newPage,
        required: false,
        title: blockTypeFriendly,
        type: blockType
      };

      $scope.$apply(function (scope) {
        scope.conference.registrationPages[newPageIndex].blocks.splice(newPosition, 0, newBlock);
      });
    };

    $scope.deleteBlock = function (blockId, growl) {
      if (growl) {
        var t = makePositionArray();
        var block = $scope.conference.registrationPages[t[blockId].page].blocks[t[blockId].block];
        var message = '"' + block.title + '" has been deleted.';
        GrowlService.growl('conferences/' + $scope.conference.id, $scope.conference, message);
      }
      $scope.deleteBlockFromPage(blockId);
    };

    $scope.deleteBlockFromPage = function (blockId) {
      var tempPositionArray = makePositionArray();
      $scope.conference.registrationPages[tempPositionArray[blockId].page].blocks.splice(
        tempPositionArray[blockId].block,
        1
      );
    };

    $scope.addNewPage = function () {
      $modal.open({
        templateUrl: 'views/promptNewPage.html',
        controller: 'confirmPromptCtrl'
      }).result.then(function (pageTitle) {
        if (pageTitle !== null && pageTitle !== '' && !angular.isUndefined(pageTitle)) {
          $scope.conference.registrationPages.push({
            id: uuid(),
            conferenceId: $scope.conference.id,
            position: 0,
            title: pageTitle,
            blocks: []
          });
        }
      });
    };

  });
<commit_msg>removed new block naming<commit_after>'use strict';

angular.module('confRegistrationWebApp')
  .controller('FormDropAreaCtrl', function ($rootScope, $scope, $modal, uuid, GrowlService) {
    $scope.$on('dragVars', function (event, x) {
      $scope.blockId = x.blockId;
      $scope.moveType = x.moveType;
    });

    function makePositionArray() {
      var tempPositionArray = [];
      $scope.conference.registrationPages.forEach(function (page, pageIndex) {
        page.blocks.forEach(function (block, blockIndex) {
          tempPositionArray[block.id] = {page: pageIndex, block: blockIndex};
        });
      });
      return tempPositionArray;
    }

    $scope.moveBlock = function (blockId, newPage, newPosition) {
      var tempPositionArray = makePositionArray();
      var newPageIndex = _.findIndex($scope.conference.registrationPages, { id: newPage });

      var origPageIndex = tempPositionArray[blockId].page;
      var origBlock = $scope.conference.registrationPages[origPageIndex].blocks[tempPositionArray[blockId].block];
      origBlock.pageId = newPage;
      $scope.$apply(function (scope) {
        scope.deleteBlock(blockId, false);
        scope.conference.registrationPages[newPageIndex].blocks.splice(newPosition, 0, origBlock);
      });
    };

    $scope.insertBlock = function (blockType, newPage, newPosition) {
      var newPageIndex = _.findIndex($scope.conference.registrationPages, { id: newPage });

      var newBlock = {
        id: uuid(),
        content: '',
        pageId: newPage,
        required: false,
        title: 'New ' + blockType + ' Block',
        type: blockType
      };

      $scope.$apply(function (scope) {
        scope.conference.registrationPages[newPageIndex].blocks.splice(newPosition, 0, newBlock);
      });
    };

    $scope.deleteBlock = function (blockId, growl) {
      if (growl) {
        var t = makePositionArray();
        var block = $scope.conference.registrationPages[t[blockId].page].blocks[t[blockId].block];
        var message = '"' + block.title + '" has been deleted.';
        GrowlService.growl('conferences/' + $scope.conference.id, $scope.conference, message);
      }
      $scope.deleteBlockFromPage(blockId);
    };

    $scope.deleteBlockFromPage = function (blockId) {
      var tempPositionArray = makePositionArray();
      $scope.conference.registrationPages[tempPositionArray[blockId].page].blocks.splice(
        tempPositionArray[blockId].block,
        1
      );
    };

    $scope.addNewPage = function () {
      $modal.open({
        templateUrl: 'views/promptNewPage.html',
        controller: 'confirmPromptCtrl'
      }).result.then(function (pageTitle) {
        if (pageTitle !== null && pageTitle !== '' && !angular.isUndefined(pageTitle)) {
          $scope.conference.registrationPages.push({
            id: uuid(),
            conferenceId: $scope.conference.id,
            position: 0,
            title: pageTitle,
            blocks: []
          });
        }
      });
    };

  });
<|endoftext|>


<commit_before>/*
 * Lunchpad Mailer module
 *
 * @author Markus Riegel <riegel.markius@googlemail.com>
 */

var nodemailer = require('nodemailer'),
	// require mailer-templates
	// require templating engine
	config = require('./config.json');

var Mailer = function(){};

// TODO: consider sending via dedicated SMTP Service later on.
// with queuing and stuff.

// TODO: write wrapper for node-mailer-templates and nodemailer
// as well as batch-sending loop

exports.mailer = new Mailer();
<commit_msg>mailer implementation<commit_after>/*
 * Lunchpad Mailer module
 *
 * @author Markus Riegel <riegel.markius@googlemail.com>
 */

var path = require('path'),
	nodemailer = require('nodemailer'),
	emailTemplates = require('email-templates'),
	// require templating engine
	config = require('./config.json'),
	from = 'Lunchpad <no-reply.lunchpad@19h13.com>';

var Mailer = function(){
	this.templatesDir = path.join(__dirname,config.mailer.templatedir); // TODO: add template Path from config
	this.transport = nodemailer.createTransport('SMTP', {
		host: config.mailer.smtp.host,
		auth: {
			user: config.mailer.smtp.user,
			pass: config.mailer.smtp.pass
		}
	});
};

// TODO: consider sending via dedicated SMTP Service later on.
// with queuing and stuff.

// TODO:
// - write wrapper for node-mailer-templates and nodemailer
// as well as batch-sending loop
// - add template Dir to config

Mailer.prototype.sendMail(templateName, subject, locals, users){
	emailTemplates(this.templatesDir, function(err, template){
		if(err){
			console.log(err);
		}else{
			var i,
				tmpLocals,
				user;
			for(i = 0; i < users.length; i++){
				user = users[i];
				tmpLocals = copyObj(locals);
				tmpLocals.user = users[i];
				template(templateName, locals, function(err, html, txt){
					if(err){
						console.log(err);
					}else{
						this.transport.sendMail({
							from: from,
							to: user.mail,
							subject: subject,
							html: html,
							txt: txt
						}, function(err, response){
							if(err){
								console.log(err);
							}else{
								console.log('message sent: ' + response.message);
							}
						})
					}
				});
			}
		}
	});
};

var copyObj = function(sourceObj){
	var copy = {},
		key;
	for(key in sourceObj){
		if(sourceObj.hasOwnProperty(key)){
			copy[key] = sourceObj[key];
		}
	}
	return copy;
}

exports.mailer = new Mailer();
<|endoftext|>


<commit_before>/**
 * calendarDemoApp - 0.9.0
 */

angular.module('reservationService', [])
	.factory('Reservations', ['$http', function($http){
		return {
			post: function(data){

				return $http.post('/calendar', data);
			}
		}
	}]);

var calendarDemoApp = angular.module('calendarDemoApp', ['ui.calendar', 'ui.bootstrap' , 'reservationService']);

	var globalDate = '';
	var globalTime = '';
	var dateSaver = '';

calendarDemoApp.controller('CalendarCtrl',
   ['$scope', '$compile', '$timeout', 'uiCalendarConfig', '$http', 'Reservations', function($scope, $compile, $timeout, uiCalendarConfig, $http, Reservations) {
    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();
	var dateSaver = '';

    $scope.changeTo = 'Hungarian';
    /* event source that pulls from google.com */
    $scope.eventSource = {
            url: "http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic",
            className: 'gcal-event',           // an option!
            currentTimezone: 'America/Chicago' // an option!

    };

    /* event source that contains custom events on the scope */
    $scope.events = [
      //{title: 'Click for Google',start: new Date(y, m, 28, 10),url: 'http://google.com/'}
	];

    /* event source that calls a function on every view switch */
    $scope.eventsF = function (start, end, timezone, callback) {
      var s = new Date(start).getTime() / 1000;
      var e = new Date(end).getTime() / 1000;
      var m = new Date(start).getMonth();
      var events = [{title: 'Feed Me ' + m,start: s + (50000),end: s + (100000),allDay: false, className: ['customFeed']}];
      callback(events);
    };

	/*alert on DateClick */
	$scope.alertOnDateClick = function(date, jsEvent, view, start, end, allDay, cell){
		//dateSaver = $scope.alertMessage = ('Clicked on: ' + date.format());

		dateSaver = date.format();
		var today = moment();
		//var test = moment();
		var todayCheck = moment(today).format('YYYY-MM-DD');
		var todayDay = moment(today).format('DD');
		todayDay = parseInt(todayDay);

		var selectionStart = date.format();
		//alert(selectionStart);
		selectionStart = Date.parse(selectionStart);
		today = Date.parse(today);
		var view = $('#myCalendar1').fullCalendar('getView');
        $scope.alertMessage = dateSaver;
		globalDate = dateSaver;
		localStorage.setItem("globalDate", globalDate);

		yearClicked = date.format('YYYY');
		yearClicked = parseInt(yearClicked);
		monthClicked = date.format('MM');
		monthClicked = parseInt(monthClicked) - 1;
		dayClicked = date.format('DD');
		dayClicked = parseInt(dayClicked);

		var dayRestriction = dayClicked - todayDay;
		var lessThan14 = true;

		if(dayRestriction <= 14){
			var lessThan14 = true;
		}
		else{
			var lessThan14 = false;
		}

		if(lessThan14){
			if(dateSaver == todayCheck || selectionStart > today){
				//$http.post

				$('#myCalendar1').fullCalendar( 'changeView', 'agendaDay' );
				$('#myCalendar1').fullCalendar( 'gotoDate', date.format());

				for(timeIncrement = 7; timeIncrement < 23; timeIncrement++){
					$http.dateCheck = new Date(yearClicked, monthClicked, dayClicked, timeIncrement);
					$http.dateCheck = moment($http.dateCheck);
					//console.log($http.dateCheck);

					var pushEvents = function(usedRooms) {
						//console.log(usedRooms);
						var availableRooms= 11 - usedRooms;
						console.log(availableRooms); //prints rooms available
						$scope.events.push({
							id: timeIncrement,
							title: 'Rooms Available [' + availableRooms + ']',
							start: new Date(yearClicked, monthClicked, dayClicked, timeIncrement),
							url: 'http://localhost:3000/reservationCheck'
						});
						console.log(timeIncrement);
						console.log($http.dateCheck);
						//if(timeIncrement == 23)
					};

					//TODO get Async calls working correctly
					// $scope.roomsUsed = function(){
						// $http.times = [];
						// for(timeIncrement = 7; timeIncrement < 23; timeIncrement++) {
							// $http.dateCheck = new Date(yearClicked, monthClicked, dayClicked, timeIncrement);
							// console.log($http.dateCheck);
							//$http.dateCheck = moment($http.dateCheck);
							// $http.times.push($http.dateCheck);
						// }
						// console.log($http.times);
						// return Reservations.post({times: $http.times})
						// .then(function(data) {
							// $scope.reservations = data.data;
							// $scope.loading = true;
							// console.log(data.data); //prints reserved rooms
							// return pushEvents($scope.reservations);
						// }).catch(function(err) {
							// console.log(err)
						// });
					// };

					pushEvents(1);
					//$scope.roomsUsed();

				}

			}
			else{
				//if(view.name == 'month'){
					alert("You have clicked a previous date.");
				//}
				//else{
				//	alert("You have clicked a previous time slot");
				//}
			}
		}
		else{
			alert("You can only reserve 14 days in advance.")
		}
};

    /* alert on eventClick */
    $scope.alertOnEventClick = function( date, jsEvent, view){
        $scope.alertMessage = (date.title + ' was clicked ');
		globalTime = date.id;
		localStorage.setItem("globalTime", globalTime);
    };
    /* alert on Drop */
     $scope.alertOnDrop = function(event, delta, revertFunc, jsEvent, ui, view){
       $scope.alertMessage = ('Event Droped to make dayDelta ' + delta);
    };
    /* alert on Resize */
    $scope.alertOnResize = function(event, delta, revertFunc, jsEvent, ui, view ){
       $scope.alertMessage = ('Event Resized to make dayDelta ' + delta);
    };
    /* add and removes an event source of choice */
    $scope.addRemoveEventSource = function(sources,source) {
      var canAdd = 0;
      angular.forEach(sources,function(value, key){
        if(sources[key] === source){
          sources.splice(key,1);
          canAdd = 1;
        }
      });
      if(canAdd === 0){
        sources.push(source);
      }
    };
    /* add custom event*/
    $scope.addEvent = function() {
      $scope.events.push({
        title: 'Open Sesame',
        //start: new Date(yearClicked, monthClicked, dayClicked),
        //end: new Date(yearClicked, monthClicked, dayClicked),
        className: ['openSesame']
      });
    };
    /* remove event */
    $scope.remove = function(index) {
      $scope.events.splice(index,1);
    };
    /* Change View */
    $scope.changeView = function(view,calendar) {
      uiCalendarConfig.calendars[calendar].fullCalendar('changeView',view);
    };
    /* Change View */
    $scope.renderCalender = function(calendar) {
      $timeout(function() {
        if(uiCalendarConfig.calendars[calendar]){
          uiCalendarConfig.calendars[calendar].fullCalendar('render');
        }
      });
    };
	/* Render Tooltip */
    $scope.eventRender = function( event, element, view ) {
        element.attr({'tooltip': event.title,
                      'tooltip-append-to-body': true});
        $compile(element)($scope);
    };

    /* config object */
    $scope.uiConfig = {
      calendar:{
        height: 650,
        editable: false,
		selectable: true,
        header:{
          left: 'month',
          center: 'title',
          right: 'today prev,next'
        },
		viewRender: function(view){
			$('#myCalendar1').fullCalendar('removeEvents');
			//var fullCalendarDayContainers = $theCalendar.find( 'td[class*="fc-day"]' );
			//foundDay = $currentContainer;

			//dateSaver.addClass( 'selected-day' );
			if(view.name == 'agendaDay'){
				$("#myCalendar1 .fc-next-button").hide();
				$("#myCalendar1 .fc-prev-button").hide();
				$("#myCalendar1 .fc-today-button").hide();
			}
			else{
				$("#myCalendar1 .fc-next-button").show();
				$("#myCalendar1 .fc-prev-button").show();
				$("#myCalendar1 .fc-today-button").show();
			}
		},
        eventClick: $scope.alertOnEventClick,
        eventDrop: $scope.alertOnDrop,
        eventResize: $scope.alertOnResize,
        eventRender: $scope.eventRender,
		dayClick: $scope.alertOnDateClick,
		timeClick: $scope.alertTest,
		eventWipe: $scope.eventWipe
      }
    };

    /* event sources array*/
    $scope.eventSources = [$scope.events, $scope.eventSource, $scope.eventsF];
    $scope.eventSources2 = [$scope.calEventsExt, $scope.eventsF, $scope.events];
	$scope.eventSources3 = [$scope.alertOnDateClick, $scope.alertTest, $scope.eventWipe];
}]);
/* EOF */<commit_msg>added 14 day restriction<commit_after>/**
 * calendarDemoApp - 0.9.0
 */

angular.module('reservationService', [])
	.factory('Reservations', ['$http', function($http){
		return {
			post: function(data){

				return $http.post('/calendar', data);
			}
		}
	}]);

var calendarDemoApp = angular.module('calendarDemoApp', ['ui.calendar', 'ui.bootstrap' , 'reservationService']);

	var globalDate = '';
	var globalTime = '';
	var dateSaver = '';

calendarDemoApp.controller('CalendarCtrl',
   ['$scope', '$compile', '$timeout', 'uiCalendarConfig', '$http', 'Reservations', function($scope, $compile, $timeout, uiCalendarConfig, $http, Reservations) {
    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();
	var dateSaver = '';

    $scope.changeTo = 'Hungarian';
    /* event source that pulls from google.com */
    $scope.eventSource = {
            url: "http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic",
            className: 'gcal-event',           // an option!
            currentTimezone: 'America/Chicago' // an option!

    };

    /* event source that contains custom events on the scope */
    $scope.events = [
      //{title: 'Click for Google',start: new Date(y, m, 28, 10),url: 'http://google.com/'}
	];

    /* event source that calls a function on every view switch */
    $scope.eventsF = function (start, end, timezone, callback) {
      var s = new Date(start).getTime() / 1000;
      var e = new Date(end).getTime() / 1000;
      var m = new Date(start).getMonth();
      var events = [{title: 'Feed Me ' + m,start: s + (50000),end: s + (100000),allDay: false, className: ['customFeed']}];
      callback(events);
    };

	/*alert on DateClick */
	$scope.alertOnDateClick = function(date, jsEvent, view, start, end, allDay, cell){
		//dateSaver = $scope.alertMessage = ('Clicked on: ' + date.format());

		dateSaver = date.format();
		var today = moment();
		var todayCheck = moment(today).format('YYYY-MM-DD');
		var todayDay = moment(today).format('DD');
		todayDay = parseInt(todayDay);

		var selectionStart = date.format();

		//retrieving epoch format
		selectionStart = Date.parse(selectionStart);
		today = Date.parse(today);

		//create a variable that is 14 days in epoch format
		var epoch14Days = 1209600000;
		var dateAdded = today + epoch14Days;

		var view = $('#myCalendar1').fullCalendar('getView');
        $scope.alertMessage = dateSaver;
		globalDate = dateSaver;
		localStorage.setItem("globalDate", globalDate);

		yearClicked = date.format('YYYY');
		yearClicked = parseInt(yearClicked);
		monthClicked = date.format('MM');
		monthClicked = parseInt(monthClicked) - 1;
		dayClicked = date.format('DD');
		dayClicked = parseInt(dayClicked);

		//ensure that the date clicked isnt 14 days past current dates
		var lessThan14 = true;
		if(selectionStart < dateAdded ){
			var lessThan14 = true;
		}
		else{
			var lessThan14 = false;
		}

		if(lessThan14){
			if(dateSaver == todayCheck || selectionStart > today){
				//$http.post

				$('#myCalendar1').fullCalendar( 'changeView', 'agendaDay' );
				$('#myCalendar1').fullCalendar( 'gotoDate', date.format());

				for(timeIncrement = 7; timeIncrement < 23; timeIncrement++){
					$http.dateCheck = new Date(yearClicked, monthClicked, dayClicked, timeIncrement);
					$http.dateCheck = moment($http.dateCheck);
					//console.log($http.dateCheck);

					var pushEvents = function(usedRooms) {
						//console.log(usedRooms);
						var availableRooms= 11 - usedRooms;
						console.log(availableRooms); //prints rooms available
						$scope.events.push({
							id: timeIncrement,
							title: 'Rooms Available [' + availableRooms + ']',
							start: new Date(yearClicked, monthClicked, dayClicked, timeIncrement),
							url: 'http://localhost:3000/reservationCheck'
						});
						console.log(timeIncrement);
						console.log($http.dateCheck);
						//if(timeIncrement == 23)
					};

					//TODO get Async calls working correctly
					// $scope.roomsUsed = function(){
						// $http.times = [];
						// for(timeIncrement = 7; timeIncrement < 23; timeIncrement++) {
							// $http.dateCheck = new Date(yearClicked, monthClicked, dayClicked, timeIncrement);
							// console.log($http.dateCheck);
							//$http.dateCheck = moment($http.dateCheck);
							// $http.times.push($http.dateCheck);
						// }
						// console.log($http.times);
						// return Reservations.post({times: $http.times})
						// .then(function(data) {
							// $scope.reservations = data.data;
							// $scope.loading = true;
							// console.log(data.data); //prints reserved rooms
							// return pushEvents($scope.reservations);
						// }).catch(function(err) {
							// console.log(err)
						// });
					// };

					pushEvents(1);
					//$scope.roomsUsed();

				}

			}
			else{
				//if(view.name == 'month'){
					alert("You have clicked a previous date.");
				//}
				//else{
				//	alert("You have clicked a previous time slot");
				//}
			}
		}
		else{
			alert("You can only reserve 14 days in advance.")
		}
};

    /* alert on eventClick */
    $scope.alertOnEventClick = function( date, jsEvent, view){
        $scope.alertMessage = (date.title + ' was clicked ');
		globalTime = date.id;
		localStorage.setItem("globalTime", globalTime);
    };
    /* alert on Drop */
     $scope.alertOnDrop = function(event, delta, revertFunc, jsEvent, ui, view){
       $scope.alertMessage = ('Event Droped to make dayDelta ' + delta);
    };
    /* alert on Resize */
    $scope.alertOnResize = function(event, delta, revertFunc, jsEvent, ui, view ){
       $scope.alertMessage = ('Event Resized to make dayDelta ' + delta);
    };
    /* add and removes an event source of choice */
    $scope.addRemoveEventSource = function(sources,source) {
      var canAdd = 0;
      angular.forEach(sources,function(value, key){
        if(sources[key] === source){
          sources.splice(key,1);
          canAdd = 1;
        }
      });
      if(canAdd === 0){
        sources.push(source);
      }
    };
    /* add custom event*/
    $scope.addEvent = function() {
      $scope.events.push({
        title: 'Open Sesame',
        //start: new Date(yearClicked, monthClicked, dayClicked),
        //end: new Date(yearClicked, monthClicked, dayClicked),
        className: ['openSesame']
      });
    };
    /* remove event */
    $scope.remove = function(index) {
      $scope.events.splice(index,1);
    };
    /* Change View */
    $scope.changeView = function(view,calendar) {
      uiCalendarConfig.calendars[calendar].fullCalendar('changeView',view);
    };
    /* Change View */
    $scope.renderCalender = function(calendar) {
      $timeout(function() {
        if(uiCalendarConfig.calendars[calendar]){
          uiCalendarConfig.calendars[calendar].fullCalendar('render');
        }
      });
    };
	/* Render Tooltip */
    $scope.eventRender = function( event, element, view ) {
        element.attr({'tooltip': event.title,
                      'tooltip-append-to-body': true});
        $compile(element)($scope);
    };

    /* config object */
    $scope.uiConfig = {
      calendar:{
        height: 650,
        editable: false,
		selectable: true,
        header:{
          left: 'month',
          center: 'title',
          right: 'today prev,next'
        },
		viewRender: function(view){
			$('#myCalendar1').fullCalendar('removeEvents');
			//var fullCalendarDayContainers = $theCalendar.find( 'td[class*="fc-day"]' );
			//foundDay = $currentContainer;

			//dateSaver.addClass( 'selected-day' );
			if(view.name == 'agendaDay'){
				$("#myCalendar1 .fc-next-button").hide();
				$("#myCalendar1 .fc-prev-button").hide();
				$("#myCalendar1 .fc-today-button").hide();
			}
			else{
				$("#myCalendar1 .fc-next-button").show();
				$("#myCalendar1 .fc-prev-button").show();
				$("#myCalendar1 .fc-today-button").show();
			}
		},
        eventClick: $scope.alertOnEventClick,
        eventDrop: $scope.alertOnDrop,
        eventResize: $scope.alertOnResize,
        eventRender: $scope.eventRender,
		dayClick: $scope.alertOnDateClick,
		timeClick: $scope.alertTest,
		eventWipe: $scope.eventWipe
      }
    };

    /* event sources array*/
    $scope.eventSources = [$scope.events, $scope.eventSource, $scope.eventsF];
    $scope.eventSources2 = [$scope.calEventsExt, $scope.eventsF, $scope.events];
	$scope.eventSources3 = [$scope.alertOnDateClick, $scope.alertTest, $scope.eventWipe];
}]);
/* EOF */<|endoftext|>


<commit_before>module.exports = {
    "button": [{
        "type": "view",
        "name": "预定",
        "url": 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65cfe45c2c6fad4a&redirect_uri=http://roscoe.cn/info&response_type=code&scope=snsapi_userinfo&state=reserve#wechat_redirect'
    }, {
        "type": "view",
        "name": "我的",
        "url": 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65cfe45c2c6fad4a&redirect_uri=http://roscoe.cn/info&response_type=code&scope=snsapi_userinfo&state=reserve#wechat_redirect'
    }]
}
<commit_msg>test fe<commit_after>var reserveUrl = 'http://115.159.119.199:8080/meeting/src/html/app.html#search'

module.exports = {
    "button": [{
        "type": "view",
        "name": "预定",
        "url": reserveUrl
    }]
}
<|endoftext|>


<commit_before>var features = {};

features.teleportOne = function(person, starOne) {
  person.kill();
  person.reset(746,300);
};

features.teleportTwo = function(person, starTwo) {
  person.kill();
  person.reset(56,300);
};

features.loseLife = function(person, ghosts) {
  lives--;
  person.kill();

  if (lives === 0) {
    features.gameOver("Player 2");
  } else {
    person.reset(100, 100);
  }
};

features.eatDot = function(person, dots) {
  score++;
  dot_count--;
  dots.kill();

  if (dot_count === 0 && powerUp_count === 0) {
    features.gameOver("Player 1");
  }
}

features.powerUp = function(person, powerUp) {
  score += 5;
  powerUp_count--;
  powerUp.kill();
  person.powerUp = true;
  setTimeout(function(){person.powerUp = false}, 5000);

  if (dot_count === 0 && powerUp_count === 0) {
    features.gameOver("Player 1");
  }
}

features.gameOver = function(winner) {
  alert("game over winner: " + winner);
};

features.eatGhosts = function(person, ghosts) {
    ghost_lives--;
    ghosts.kill();

    if (ghost_lives === 0) {
      features.gameOver("Player 1");
    }
};

features.returnCoordinates = function(sprite) {
  var coordinates = [sprite.x, sprite.y];
  return coordinates;
};
<commit_msg>change winner alert to be more descriptive when win condition is met<commit_after>var features = {};

features.teleportOne = function(person, starOne) {
  person.kill();
  person.reset(746,300);
};

features.teleportTwo = function(person, starTwo) {
  person.kill();
  person.reset(56,300);
};

features.loseLife = function(person, ghosts) {
  lives--;
  person.kill();

  if (lives === 0) {
    features.gameOver("Player 2");
  } else {
    person.reset(100, 100);
  }
};

features.eatDot = function(person, dots) {
  score++;
  dot_count--;
  dots.kill();

  if (dot_count === 0 && powerUp_count === 0) {
    features.gameOver("Player 1");
  }
}

features.powerUp = function(person, powerUp) {
  score += 5;
  powerUp_count--;
  powerUp.kill();
  person.powerUp = true;
  setTimeout(function(){person.powerUp = false}, 5000);

  if (dot_count === 0 && powerUp_count === 0) {
    features.gameOver("Player 1");
  }
}

features.gameOver = function(winner) {
  alert("Winner: " + winner);
};

features.eatGhosts = function(person, ghosts) {
    ghost_lives--;
    ghosts.kill();

    if (ghost_lives === 0) {
      features.gameOver("Player 1");
    }
};

features.returnCoordinates = function(sprite) {
  var coordinates = [sprite.x, sprite.y];
  return coordinates;
};
<|endoftext|>