<commit_before>var React = require('react');
var ReactDOM = require('react-dom');

// require('hammerjs') when in a browser. This is safe because Hammer is only
// invoked in componentDidMount, which is not executed on the server.
var Hammer = (typeof window !== 'undefined') ? require('hammerjs') : undefined;

var privateProps = {
	children: true,
	action: true,
	onTap: true,
	onDoubleTap: true,
	onPan: true,
	onPanStart: true,
	onPanEnd: true,
	onPanCancel: true,
	onSwipe: true,
	onPress: true,
	onPressUp: true,
	onPinch: true,
	onPinchIn: true,
	onPinchOut: true,
	onPinchStart: true,
	onPinchEnd: true,
	onPinchCancel: true,
	onRotate: true,
};

/**
 * Hammer Component
 * ================
 */

var handlerToEvent = {
	action: 'tap press',
	onTap: 'tap',
	onDoubleTap: 'doubletap',
	onPanStart: 'panstart',
	onPan: 'pan',
	onPanEnd: 'panend',
	onPanCancel: 'pancancel',
	onSwipe: 'swipe',
	onPress: 'press',
	onPressUp: 'pressup',
	onPinch: 'pinch',
	onPinchIn: 'pinchin',
	onPinchOut: 'pinchout',
	onPinchStart: 'pinchstart',
	onPinchEnd: 'pinchend',
	onRotate: 'rotate',
};
function updateHammer (hammer, props) {
	if (props.vertical) {
		hammer.get('pan').set({direction: Hammer.DIRECTION_ALL});
		hammer.get('swipe').set({direction: Hammer.DIRECTION_ALL});
	} else {
		hammer.get('pan').set({direction: Hammer.DIRECTION_HORIZONTAL});
		hammer.get('swipe').set({direction: Hammer.DIRECTION_HORIZONTAL});
	}

	if (props.options) {
		Object.keys(props.options).forEach(function (option) {
			if (option === 'recognizers') {
				Object.keys(props.options.recognizers).forEach(function (gesture) {
					var recognizer = hammer.get(gesture);
					recognizer.set(props.options.recognizers[gesture]);
				}, this);
			} else {
				var key = option;
				var optionObj = {};
				optionObj[key] = props.options[option];
				hammer.set(optionObj);
			}
		}, this);
	}

	if (props.recognizeWith) {
		Object.keys(props.recognizeWith).forEach(function (gesture) {
			var recognizer = hammer.get(gesture);
			recognizer.recognizeWith(props.recognizeWith[gesture]);
		}, this);
	}

	Object.keys(props).forEach(function (p) {
		var e = handlerToEvent[p];
		if (e) {
			hammer.off(e);
			hammer.on(e, props[p]);
		}
	});
}

var HammerComponent = React.createClass({

	displayName: 'Hammer',

	propTypes: {
		className: React.PropTypes.string,
	},

	componentDidMount: function () {
		this.hammer = new Hammer(ReactDOM.findDOMNode(this));
		updateHammer(this.hammer, this.props);
	},

	componentDidUpdate: function () {
		if (this.hammer) {
			updateHammer(this.hammer, this.props);
		}
	},

	componentWillUnmount: function () {
		if (this.hammer) {
			this.hammer.stop();
			this.hammer.destroy();
		}
		this.hammer = null;
	},

	render: function () {
		var props = {};

		Object.keys(this.props).forEach(function (i) {
			if (!privateProps[i]) {
				props[i] = this.props[i];
			}
		}, this);

		// Reuse the child provided
		// This makes it flexible to use whatever element is wanted (div, ul, etc)
		return React.cloneElement(React.Children.only(this.props.children), props);
	}
});

module.exports = HammerComponent;
<commit_msg>add more rotate events<commit_after>var React = require('react');
var ReactDOM = require('react-dom');

// require('hammerjs') when in a browser. This is safe because Hammer is only
// invoked in componentDidMount, which is not executed on the server.
var Hammer = (typeof window !== 'undefined') ? require('hammerjs') : undefined;

var privateProps = {
	children: true,
	action: true,
	onTap: true,
	onDoubleTap: true,
	onPan: true,
	onPanStart: true,
	onPanEnd: true,
	onPanCancel: true,
	onSwipe: true,
	onPress: true,
	onPressUp: true,
	onPinch: true,
	onPinchIn: true,
	onPinchOut: true,
	onPinchStart: true,
	onPinchEnd: true,
	onPinchCancel: true,
	onRotate: true,
	onRotateStart: true,
	onRotateMove: true,
	onRotateEnd: true,
	onRotateCancel: true,
};

/**
 * Hammer Component
 * ================
 */

var handlerToEvent = {
	action: 'tap press',
	onTap: 'tap',
	onDoubleTap: 'doubletap',
	onPanStart: 'panstart',
	onPan: 'pan',
	onPanEnd: 'panend',
	onPanCancel: 'pancancel',
	onSwipe: 'swipe',
	onPress: 'press',
	onPressUp: 'pressup',
	onPinch: 'pinch',
	onPinchIn: 'pinchin',
	onPinchOut: 'pinchout',
	onPinchStart: 'pinchstart',
	onPinchEnd: 'pinchend',
	onRotate: 'rotate',
	onRotateStart: 'rotatestart',
	onRotateMove: 'rotatemove',
	onRotateEnd: 'rotateend',
	onRotateCancel: 'rotatecancel',
};
function updateHammer (hammer, props) {
	if (props.vertical) {
		hammer.get('pan').set({direction: Hammer.DIRECTION_ALL});
		hammer.get('swipe').set({direction: Hammer.DIRECTION_ALL});
	} else {
		hammer.get('pan').set({direction: Hammer.DIRECTION_HORIZONTAL});
		hammer.get('swipe').set({direction: Hammer.DIRECTION_HORIZONTAL});
	}

	if (props.options) {
		Object.keys(props.options).forEach(function (option) {
			if (option === 'recognizers') {
				Object.keys(props.options.recognizers).forEach(function (gesture) {
					var recognizer = hammer.get(gesture);
					recognizer.set(props.options.recognizers[gesture]);
				}, this);
			} else {
				var key = option;
				var optionObj = {};
				optionObj[key] = props.options[option];
				hammer.set(optionObj);
			}
		}, this);
	}

	if (props.recognizeWith) {
		Object.keys(props.recognizeWith).forEach(function (gesture) {
			var recognizer = hammer.get(gesture);
			recognizer.recognizeWith(props.recognizeWith[gesture]);
		}, this);
	}

	Object.keys(props).forEach(function (p) {
		var e = handlerToEvent[p];
		if (e) {
			hammer.off(e);
			hammer.on(e, props[p]);
		}
	});
}

var HammerComponent = React.createClass({

	displayName: 'Hammer',

	propTypes: {
		className: React.PropTypes.string,
	},

	componentDidMount: function () {
		this.hammer = new Hammer(ReactDOM.findDOMNode(this));
		updateHammer(this.hammer, this.props);
	},

	componentDidUpdate: function () {
		if (this.hammer) {
			updateHammer(this.hammer, this.props);
		}
	},

	componentWillUnmount: function () {
		if (this.hammer) {
			this.hammer.stop();
			this.hammer.destroy();
		}
		this.hammer = null;
	},

	render: function () {
		var props = {};

		Object.keys(this.props).forEach(function (i) {
			if (!privateProps[i]) {
				props[i] = this.props[i];
			}
		}, this);

		// Reuse the child provided
		// This makes it flexible to use whatever element is wanted (div, ul, etc)
		return React.cloneElement(React.Children.only(this.props.children), props);
	}
});

module.exports = HammerComponent;
<|endoftext|>


<commit_before>function main() {

  function factorial(n) {
    if (n <= 0) {
      return 1;
    } else {
      return n * factorial(n-1);
    }
  }

  function binomial(n, k) {
    return factorial(n) / (factorial(k) * factorial(n-k));
  }

  function getIndexToMove(n, k, subsetArray) {
    for (var i = 0; i < subsetArray.length - 1; i++) {
      if (subsetArray[i] + 1 < subsetArray[i+1]) {
        return i;
      }
    }
    if (subsetArray[subsetArray.length - 1] < n) {
      return subsetArray.length - 1;
    }
    return null;
  }

  function getCoords(row, col) {
    var cx = 1.5*radius + col * gridWidth;
    var cy = 1.5*radius + row * gridHeight;
    return [cx, cy];
  }

  Raphael.fn.numberedCircle = function(params) {
    var obj = {};

    obj.params = params;

    var pt = getCoords(params.rowIndex, params.colIndex);
    obj.circleElement = paper.circle(pt[0], pt[1], radius);
    obj.numberElement = paper.text(pt[0], pt[1], params.number);

    obj.animate = function(newParams, durationMs, easing, callback) {
      obj.params.rowIndex = newParams.rowIndex;
      obj.params.colIndex = newParams.colIndex;
      var dest = getCoords(newParams.rowIndex, newParams.colIndex);
      obj.circleElement.animate({cx: dest[0], cy: dest[1]},
          durationMs, easing, callback);
      obj.numberElement.animate({x: dest[0], y: dest[1]},
          durationMs, easing);
      // TODO: handle arrows here
    };

    obj.setNumber = function(newNumber) {
      obj.params.number = newNumber;
      obj.numberElement.attr("text", newNumber);
    };

    obj.customClone = function() {
      var paramsCopy = jQuery.extend({}, obj.params);
      return paper.numberedCircle(paramsCopy);
    };

    return obj;
  }

  function nextSubset(n, k, subsetObject) {
    if (subsetObject == null) {
      var next = [];
      for (var i = 1; i <= k; i++) {
        next.push(i);
      }
      return {
        "subset": next,
        "movedIndex": null,
      };
    }

    var oldSubsetArray = subsetObject.subset;
    var movedIndex = getIndexToMove(n, k, oldSubsetArray);

    if (movedIndex == null) {
      // We've reached the last subset.
      return null;
    }

    var newSubsetArray = [];
    for (var i = 0; i < oldSubsetArray.length; i++) {
      if (i < movedIndex) {
        newSubsetArray.push(i+1);
      } else if (i == movedIndex) {
        newSubsetArray.push(oldSubsetArray[i] + 1);
      } else {
        newSubsetArray.push(oldSubsetArray[i]);
      }
    }

    return {
      "subset": newSubsetArray,
      "movedIndex": movedIndex,
    };
  }

  function debug(msg) {
    debugElement.attr("text", msg);
  }

  var n = 6;
  var k = 3;
  var maxRows = binomial(n, k);

  var gridWidth = 30;
  var gridHeight = 1.5 * gridWidth;
  var timeUnitMs = 100;
  var radius = 10;

  var paperWidth = (n+1) * gridWidth;
  var paperHeight = (maxRows+1) * gridHeight;
  var paper = Raphael("main", paperWidth, paperHeight);

  var debugElement = paper.text(7*gridWidth, 7*gridHeight, "");

  var callbacks = {};

  callbacks.moveDown = function(state) {
    //console.log("moveDown state = " + JSON.stringify(state));
    if (state.subset == null) {
      // We've reached the final subset, so there are no more callbacks
      // to generate.
      return null;
    }
    console.log(state.subset.subset); // TODO: remove when done debugging
    console.log(state.subset.movedIndex); // TODO: remove when done debugging
    return function() {
      var newSubset = nextSubset(n, k, state.subset);
      if (newSubset == null) {
        return;
      }

      var newCircles = [];
      for (var i = 0; i < state.circles.length; i++) {
        newCircles.push(state.circles[i].customClone());
      }

      var newRowIndex = state.rowIndex+1;

      var newState = {
        circles: newCircles,
        subset: newSubset,
        rowIndex: newRowIndex,
      };
      var callback = callbacks.moveDown(newState);

      for (var i = 0; i < newCircles.length; i++) {
        var arrowType;
        if (i < newSubset.movedIndex) {
          arrowType = arrowTypes.pushLeft;
        } else if (i == newSubset.movedIndex) {
          arrowType = arrowTypes.pushRight;
        } else {
          arrowType = arrowTypes.dontTouch;
        }

        var number = newSubset.subset[i];
        newCircles[i].setNumber(number);
        newCircles[i].animate(
            {"rowIndex": newRowIndex, "colIndex": number - 1,
                "arrowType": arrowType},
            timeUnitMs, "linear",
            i == 0 ? callback : null);
      }
    }
  }

  var arrowTypes = {
    pushLeft: 0,
    pushRight: 1,
    dontTouch: 2,
  };

  var firstSubset = nextSubset(n, k, null);
  var circles = [];
  for (var i = 0; i < firstSubset.subset.length; i++) {
    var number = firstSubset.subset[i];
    var circle = paper.numberedCircle({
      rowIndex: 0,
      colIndex: number - 1,
      number: number,
    });
    circles.push(circle);
  }

  callbacks.moveDown({rowIndex: 0, subset: firstSubset, circles: circles})();
}
<commit_msg>animation with lines<commit_after>function main() {

  function factorial(n) {
    if (n <= 0) {
      return 1;
    } else {
      return n * factorial(n-1);
    }
  }

  function binomial(n, k) {
    return factorial(n) / (factorial(k) * factorial(n-k));
  }

  function getIndexToMove(n, k, subsetArray) {
    for (var i = 0; i < subsetArray.length - 1; i++) {
      if (subsetArray[i] + 1 < subsetArray[i+1]) {
        return i;
      }
    }
    if (subsetArray[subsetArray.length - 1] < n) {
      return subsetArray.length - 1;
    }
    return null;
  }

  function getCoords(row, col) {
    var cx = 1.5*radius + col * gridWidth;
    var cy = 1.5*radius + row * gridHeight;
    return [cx, cy];
  }

  function arrowPathSpec(params) {
    var tail = getCoords(params.fromRow, params.fromCol);
    // TODO: subtract radius from length of arrow?
    var head = getCoords(params.toRow, params.toCol);
    // TODO: add "point" to head of arrow
    var result = Raphael.format("M{0},{1}L{2},{3}",
        tail[0], tail[1], head[0], head[1]);
    console.log(result);
    return result;
  }

  Raphael.fn.numberedCircle = function(params) {
    var thisPaper = this;

    var obj = {};

    obj.params = params;

    var pt = getCoords(params.rowIndex, params.colIndex);
    obj.circleElement = thisPaper.circle(pt[0], pt[1], radius)
        .attr({fill: "#fff"});
    obj.numberElement = thisPaper.text(pt[0], pt[1], params.number);

    obj.animate = function(newParams, durationMs, easing, callback) {
      var dest = getCoords(newParams.rowIndex, newParams.colIndex);
      obj.circleElement.animate({cx: dest[0], cy: dest[1]},
          durationMs, easing, callback);
      obj.numberElement.animate({x: dest[0], y: dest[1]},
          durationMs, easing);

      var arrowStroke;
      if (newParams.arrowType == arrowTypes.pushLeft) {
        arrowStroke = "#c00";
      } else if (newParams.arrowType == arrowTypes.pushRight) {
        arrowStroke = "#00c";
      } else {
        arrowStroke = "#ccc";
      }
      var arrow = thisPaper.path(arrowPathSpec({
        fromRow: obj.params.rowIndex,
        fromCol: obj.params.colIndex,
        toRow: obj.params.rowIndex,
        toCol: obj.params.colIndex,
      })).attr({stroke: arrowStroke});
      arrow.toBack();
      arrow.animate({path: arrowPathSpec({
        fromRow: obj.params.rowIndex,
        fromCol: obj.params.colIndex,
        toRow: newParams.rowIndex,
        toCol: newParams.colIndex,
      })}, durationMs, easing);

      obj.params.rowIndex = newParams.rowIndex;
      obj.params.colIndex = newParams.colIndex;
    };

    obj.setNumber = function(newNumber) {
      obj.params.number = newNumber;
      obj.numberElement.attr("text", newNumber);
    };

    obj.customClone = function() {
      var paramsCopy = jQuery.extend({}, obj.params);
      return thisPaper.numberedCircle(paramsCopy);
    };

    return obj;
  }

  function nextSubset(n, k, subsetObject) {
    if (subsetObject == null) {
      var next = [];
      for (var i = 1; i <= k; i++) {
        next.push(i);
      }
      return {
        "subset": next,
        "movedIndex": null,
      };
    }

    var oldSubsetArray = subsetObject.subset;
    var movedIndex = getIndexToMove(n, k, oldSubsetArray);

    if (movedIndex == null) {
      // We've reached the last subset.
      return null;
    }

    var newSubsetArray = [];
    for (var i = 0; i < oldSubsetArray.length; i++) {
      if (i < movedIndex) {
        newSubsetArray.push(i+1);
      } else if (i == movedIndex) {
        newSubsetArray.push(oldSubsetArray[i] + 1);
      } else {
        newSubsetArray.push(oldSubsetArray[i]);
      }
    }

    return {
      "subset": newSubsetArray,
      "movedIndex": movedIndex,
    };
  }

  function debug(msg) {
    debugElement.attr("text", msg);
  }

  var n = 6;
  var k = 3;
  var maxRows = binomial(n, k);

  var gridWidth = 30;
  var gridHeight = 1.5 * gridWidth;
  var timeUnitMs = 100;
  var radius = 10;

  var paperWidth = (n+1) * gridWidth;
  var paperHeight = (maxRows+1) * gridHeight;
  var paper = Raphael("main", paperWidth, paperHeight);

  var debugElement = paper.text(7*gridWidth, 7*gridHeight, "");

  var callbacks = {};

  callbacks.moveDown = function(state) {
    //console.log("moveDown state = " + JSON.stringify(state));
    if (state.subset == null) {
      // We've reached the final subset, so there are no more callbacks
      // to generate.
      return null;
    }
    console.log(state.subset.subset); // TODO: remove when done debugging
    console.log(state.subset.movedIndex); // TODO: remove when done debugging
    return function() {
      var newSubset = nextSubset(n, k, state.subset);
      if (newSubset == null) {
        return;
      }

      var newCircles = [];
      for (var i = 0; i < state.circles.length; i++) {
        newCircles.push(state.circles[i].customClone());
      }

      var newRowIndex = state.rowIndex+1;

      var newState = {
        circles: newCircles,
        subset: newSubset,
        rowIndex: newRowIndex,
      };
      var callback = callbacks.moveDown(newState);

      for (var i = 0; i < newCircles.length; i++) {
        var arrowType;
        if (i < newSubset.movedIndex) {
          arrowType = arrowTypes.pushLeft;
        } else if (i == newSubset.movedIndex) {
          arrowType = arrowTypes.pushRight;
        } else {
          arrowType = arrowTypes.dontTouch;
        }

        var number = newSubset.subset[i];
        newCircles[i].setNumber(number);
        newCircles[i].animate(
            {"rowIndex": newRowIndex, "colIndex": number - 1,
                "arrowType": arrowType},
            timeUnitMs, "linear",
            i == 0 ? callback : null);
      }
    }
  }

  var arrowTypes = {
    pushLeft: 0,
    pushRight: 1,
    dontTouch: 2,
  };

  var firstSubset = nextSubset(n, k, null);
  var circles = [];
  for (var i = 0; i < firstSubset.subset.length; i++) {
    var number = firstSubset.subset[i];
    var circle = paper.numberedCircle({
      rowIndex: 0,
      colIndex: number - 1,
      number: number,
    });
    circles.push(circle);
  }

  callbacks.moveDown({rowIndex: 0, subset: firstSubset, circles: circles})();
}
<|endoftext|>


<commit_before>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const math = require('mathjs')
const config = require('./config')
const dotenv = require('dotenv')
const randomPuppy = require('random-puppy')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online')
  console.log('Subiex is ready')
  bot.user.setGame('┬─┬ ノ( ゜-゜ノ)-ing')
})

/*bot.on('message', (message) =>  {
	if(message.content.startsWith(config.prefix))
	{
			try {
				switch (message.content) {
					case config.prefix + 'report':
						message.reply('I am online and working!')
	    				var time = Date.now()
	   					message.channel.send('Pew').then(m => m.edit('PING TOOK : **' + (Date.now() - time) + '** ms'))
	    				message.channel.send('This report was sent in :```' + new Date() + '```');
						break;
					case config.prefix + 'help':
						message.reply('Help goes here ...')
						break;
					case config.prefix + 'hello':
						message.channel.send('Hello there ' + message.author.username)
						break;

					default:
						message.reply('**INVALID COMMAND**')
				}

			}
			catch(ex) {console.log('The error is at switch statement : ' + ex.stack)}
	}
})*/

const emojis = [
		"( ͡° ͜ʖ ͡°)",
		"¯\\_(ツ)_/¯",
		"ʕ•ᴥ•ʔ",
		"(▀̿Ĺ̯▀̿ ̿)",
		"(ง ͠° ͟ل͜ ͡°)ง",
		"ಠ_ಠ",
		"̿'̿'\\̵͇̿̿\\з=( ͠° ͟ʖ ͡°)=ε/̵͇̿̿/'̿̿ ̿ ̿ ̿ ̿ ̿",
		"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
		"﴾͡๏̯͡๏﴿ O'RLY?",
		"[̲̅$̲̅(̲̅ ͡° ͜ʖ ͡°̲̅)̲̅$̲̅]",
		"(ᵔᴥᵔ)",
		"(¬‿¬)",
		"(☞ﾟヮﾟ)☞ ☜(ﾟヮﾟ☜)",
		"(づ￣ ³￣)づ",
		"ლ(ಠ益ಠლ)",
		"ಠ╭╮ಠ",
		"♪~ ᕕ(ᐛ)ᕗ",
		"ヾ(⌐■_■)ノ♪",
		"◉_◉",
		"\\ (•◡•) /",
		"༼ʘ̚ل͜ʘ̚༽",
		"┬┴┬┴┤(･_├┬┴┬┴",
		"ᕦ(ò_óˇ)ᕤ",
		"┻━┻ ︵ヽ(`Д´)ﾉ︵ ┻━┻",
		"（╯°□°）╯︵( .o.)"
	];

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function isMoji(moji) {
	for (var i = 0; i <= emojis.Length; i++) {
		if(emojis[i] == moji)
			return true;
		else
			return false;
	}
}

bot.on('message', (message) => {

	if(message.content.startsWith(config.prefix + 'dog'))
	{
		randomPuppy()
		.then(url => {
        	message.channel.send(url)
    	})
	}
	else if(message.content == "(╯°□°）╯︵ ┻━┻")
	{
		message.channel.send("lemme take that table to its place")
		message.channel.send("┬─┬ ノ( ゜-゜ノ)")
	}
	else if(message.content === "!moji")
	{
		var index = getRandomInt(0,24);
		message.channel.send(emojis[index]);
	}

})

bot.on('message', (message) =>  {
	var args = message.content.split(/[ ] +/)

	if (message.content.startsWith("!setGame") && message.author.id != config.botID) {

			if (args.length === 1)
				message.reply("You didn't define a argument, ```USE: !setGame [text to say]```");

			else
			{
				bot.user.setGame(args.join(' ').substring(9));
			}
		}
})

bot.login(process.env.BOT_TOKEN)<commit_msg>:zap: setgame<commit_after>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const math = require('mathjs')
const config = require('./config')
const dotenv = require('dotenv')
const randomPuppy = require('random-puppy')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online')
  console.log('Subiex is ready')
  bot.user.setGame('┬─┬ ノ( ゜-゜ノ)-ing')
})

/*bot.on('message', (message) =>  {
	if(message.content.startsWith(config.prefix))
	{
			try {
				switch (message.content) {
					case config.prefix + 'report':
						message.reply('I am online and working!')
	    				var time = Date.now()
	   					message.channel.send('Pew').then(m => m.edit('PING TOOK : **' + (Date.now() - time) + '** ms'))
	    				message.channel.send('This report was sent in :```' + new Date() + '```');
						break;
					case config.prefix + 'help':
						message.reply('Help goes here ...')
						break;
					case config.prefix + 'hello':
						message.channel.send('Hello there ' + message.author.username)
						break;

					default:
						message.reply('**INVALID COMMAND**')
				}

			}
			catch(ex) {console.log('The error is at switch statement : ' + ex.stack)}
	}
})*/

const emojis = [
		"( ͡° ͜ʖ ͡°)",
		"¯\\_(ツ)_/¯",
		"ʕ•ᴥ•ʔ",
		"(▀̿Ĺ̯▀̿ ̿)",
		"(ง ͠° ͟ل͜ ͡°)ง",
		"ಠ_ಠ",
		"̿'̿'\\̵͇̿̿\\з=( ͠° ͟ʖ ͡°)=ε/̵͇̿̿/'̿̿ ̿ ̿ ̿ ̿ ̿",
		"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
		"﴾͡๏̯͡๏﴿ O'RLY?",
		"[̲̅$̲̅(̲̅ ͡° ͜ʖ ͡°̲̅)̲̅$̲̅]",
		"(ᵔᴥᵔ)",
		"(¬‿¬)",
		"(☞ﾟヮﾟ)☞ ☜(ﾟヮﾟ☜)",
		"(づ￣ ³￣)づ",
		"ლ(ಠ益ಠლ)",
		"ಠ╭╮ಠ",
		"♪~ ᕕ(ᐛ)ᕗ",
		"ヾ(⌐■_■)ノ♪",
		"◉_◉",
		"\\ (•◡•) /",
		"༼ʘ̚ل͜ʘ̚༽",
		"┬┴┬┴┤(･_├┬┴┬┴",
		"ᕦ(ò_óˇ)ᕤ",
		"┻━┻ ︵ヽ(`Д´)ﾉ︵ ┻━┻",
		"（╯°□°）╯︵( .o.)"
	];

	const phrases = ["Take it easy pal","Whoa","Why always i have to unflip the damn table"
	,"Awesome, another table to unflip",
	"I will have my eyes on you ┬┴┬┴┤(･_├┬┴┬┴"]

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function isMoji(moji) {
	for (var i = 0; i <= emojis.Length; i++) {
		if(emojis[i] == moji)
			return true;
		else
			return false;
	}
}

bot.on('message', (message) => {

	if(message.content.startsWith(config.prefix + 'dog'))
	{
		randomPuppy()
		.then(url => {
        	message.channel.send(url)
    	})
	}
	else if(message.content == "(╯°□°）╯︵ ┻━┻")
	{
		var index = getRandomInt(0,phrases.Length - 1);
		message.channel.send(phrases[index])
		message.channel.send("┬─┬ ノ( ゜-゜ノ)")
	}
	else if(message.content === "!moji")
	{
		var index = getRandomInt(0,24);
		message.channel.send(emojis[index]);
	}

})

bot.login(process.env.BOT_TOKEN)<|endoftext|>


<commit_before>'use strict';

module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    afterInstall: function(options) {
      return this.addBowerPackageToProject('bugsnag', '~2.5.0');
    }
  }
};
<commit_msg>fix typo in blueprint<commit_after>'use strict';

module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function(options) {
    return this.addBowerPackageToProject('bugsnag', '~2.5.0');
  }
};
<|endoftext|>


<commit_before>'use strict';

//External
//require('jquery');
require('angular');
require('angular-ui-router');

//Internal
var views = require('./views/module');
var models = require('./models/module');
var components = require('./components/module');
var appController = require('./app_controller');
var appRouter = require('./app_router');
var appSettings = require('./app_settings');
var appAuthInterceptor = require('./app_auth_interceptor');

angular.module("app", [
    //External
    'ui.router',

    //Internal
    appSettings.name,
    models.name,
    components.name,
    views.name
])
.controller('AppController', appController)
.factory('SessionInjector', appAuthInterceptor)
.config(appRouter)
.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('SessionInjector');
}]);

<commit_msg>ADD: ui bootstrap, ngAnimate as bootstrap js and css<commit_after>'use strict';

//External
require('angular');
require('angular-ui-router');
require('angular-ui-bootstrap');
require('angular-animate');

//Internal
var views = require('./views/module');
var models = require('./models/module');
var components = require('./components/module');
var appController = require('./app_controller');
var appRouter = require('./app_router');
var appSettings = require('./app_settings');
var appAuthInterceptor = require('./app_auth_interceptor');

angular.module("app", [
    //External
    'ui.router',
    'ui.bootstrap',
    'ngAnimate',

    //Internal
    appSettings.name,
    models.name,
    components.name,
    views.name
])
.controller('AppController', appController)
.factory('SessionInjector', appAuthInterceptor)
.config(appRouter)
.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('SessionInjector');
}]);

<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var VersionChecker = require('ember-cli-version-checker');

module.exports = function(blueprint) {
  blueprint.supportsAddon = function() {
    return false;
  };

  blueprint.filesPath = function() {
    var type;

    var dependencies = this.project.dependencies();
    if ('ember-qunit' in dependencies || 'ember-cli-qunit' in dependencies) {
      type = 'qunit';

    } else if ('ember-mocha' in dependencies) {
      type = 'mocha-0.12';

    } else if ('ember-cli-mocha' in dependencies) {
      var checker = new VersionChecker({ root: this.project.root });
      if (fs.existsSync(this.path + '/mocha-0.12-files') && checker.for('ember-cli-mocha', 'npm').satisfies('>=0.12.0')) {
        type = 'mocha-0.12';
      } else {
        type = 'mocha';
      }

    } else {
      this.ui.writeLine('Couldn\'t determine test style - using QUnit');
      type = 'qunit';
    }

    return path.join(this.path, type + '-files');
  };

  return blueprint;
};
<commit_msg>blueprints: Adjust test framework detector for RFC232 blueprints<commit_after>var fs = require('fs');
var path = require('path');
var VersionChecker = require('ember-cli-version-checker');

module.exports = function(blueprint) {
  blueprint.supportsAddon = function() {
    return false;
  };

  blueprint.filesPath = function() {
    var type;

    var dependencies = this.project.dependencies();
    if ('ember-qunit' in dependencies) {
      type = 'qunit-rfc-232';

    } else if ('ember-cli-qunit' in dependencies) {
      let checker = new VersionChecker(this.project);
      if (fs.existsSync(this.path + '/qunit-rfc-232-files') && checker.for('ember-cli-qunit', 'npm').gte('4.1.1')) {
        type = 'qunit-rfc-232';
      } else {
        type = 'qunit';
      }

    } else if ('ember-mocha' in dependencies) {
      type = 'mocha-0.12';

    } else if ('ember-cli-mocha' in dependencies) {
      let checker = new VersionChecker(this.project);
      if (fs.existsSync(this.path + '/mocha-0.12-files') && checker.for('ember-cli-mocha', 'npm').satisfies('>=0.12.0')) {
        type = 'mocha-0.12';
      } else {
        type = 'mocha';
      }

    } else {
      this.ui.writeLine('Couldn\'t determine test style - using QUnit');
      type = 'qunit';
    }

    return path.join(this.path, type + '-files');
  };

  return blueprint;
};
<|endoftext|>


<commit_before>"use strict";
const _ = require("lodash");
const rp = require("request-promise");
const LocalRunner = require("./LocalRunner.js");
const DockerRunner = require("./DockerRunner.js");
const endpointToUrl = require("./common.js").endpointToUrl;

class InstanceManager {
  constructor(name) {
    this.instances = [];

    if (process.env.RESILIENCE_ARANGO_BASEPATH) {
      this.runner = new LocalRunner(process.env.RESILIENCE_ARANGO_BASEPATH);
    } else if (process.env.RESILIENCE_DOCKER_IMAGE) {
      this.runner = new DockerRunner(process.env.RESILIENCE_DOCKER_IMAGE);
    }

    if (!this.runner) {
      throw new Error(
        'Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container'
      );
    }
    this.currentLog = "";
    this.agentCounter = 0;
    this.coordinatorCounter = 0;
    this.dbServerCounter = 0;
  }

  startArango(name, endpoint, role, args) {
    args.push("--server.authentication=false");

    let instance = {
      name,
      role,
      process: null,
      status: "NEW",
      exitcode: null,
      endpoint,
      args,
      logFn: line => {
        if (line.trim().length > 0) {
          let logLine =
            instance.name + "(" + instance.process.pid + "): \t" + line;
          if (process.env.LOG_IMMEDIATE) {
            console.log(logLine);
          } else {
            logLine = logLine.replace(/\x1B/g, "");
            this.currentLog += logLine + "\n";
          }
        }
      }
    };
    return this.runner.firstStart(instance);
  }

  startDbServer(name) {
    this.dbServerCounter++;
    return this.runner
      .createEndpoint()
      .then(endpoint => {
        let args = [
          "--cluster.agency-endpoint=" + this.getAgencyEndpoint(),
          "--cluster.my-role=PRIMARY",
          "--cluster.my-local-info=" + name,
          "--cluster.my-address=" + endpoint
        ];
        return this.startArango(name, endpoint, "primary", args);
      })
      .then(instance => {
        this.instances.push(instance);
        return instance;
      });
  }

  getAgencyEndpoint() {
    return this.instances.filter(instance => {
      return instance.role === "agent";
    })[0].endpoint;
  }

  startCoordinator(name) {
    this.coordinatorCounter++;
    return this.runner
      .createEndpoint()
      .then(endpoint => {
        let args = [
          "--cluster.agency-endpoint=" + this.getAgencyEndpoint(),
          "--cluster.my-role=COORDINATOR",
          "--cluster.my-local-info=" + name,
          "--cluster.my-address=" + endpoint
        ];
        return this.startArango(name, endpoint, "coordinator", args);
      })
      .then(instance => {
        this.instances.push(instance);
        return instance;
      });
  }

  replace(instance) {
    let name, role;
    switch (instance.role) {
      case "coordinator":
        this.coordinatorCounter++;
        name = "coordinator-" + this.coordinatorCounter;
        role = "COORDINATOR";
        break;
      case "primary":
        this.dbServerCounter++;
        name = "dbServer-" + this.dbServerCounter;
        role = "PRIMARY";
        break;
      default:
        throw new Error("Can only replace coordinators/dbServers");
    }
    if (this.instances.includes(instance)) {
      throw new Error("Instance must be destroyed before it can be replaced");
    }
    let args = [
      "--cluster.agency-endpoint=" + this.getAgencyEndpoint(),
      "--cluster.my-role=" + role,
      "--cluster.my-local-info=" + name,
      "--cluster.my-address=" + instance.endpoint
    ];
    return this.startArango(name, instance.endpoint, instance.role, args)
      .then(instance => this.waitForInstance(instance))
      .then(instance => {
        this.instances.push(instance);
        return instance;
      });
  }

  startAgency(options = {}) {
    let size = options.agencySize || 1;
    if (options.agencyWaitForSync === undefined) {
      options.agencyWaitForSync = false;
    }
    const wfs = options.agencyWaitForSync;
    let promise = Promise.resolve([]);
    for (var i = 0; i < size; i++) {
      promise = promise.then(instances => {
        return this.runner
          .createEndpoint()
          .then(endpoint => {
            let args = [
              "--agency.activate=true",
              "--agency.size=" + size,
              "--agency.pool-size=" + size,
              "--agency.wait-for-sync=false",
              "--agency.supervision=true",
              "--server.threads=16",
              "--agency.supervision-frequency=1.0",
              "--agency.supervision-grace-period=5.0",
              "--agency.my-address=" + endpoint,
              "--log.force-direct=true"
            ];
            if (instances.length === 0) {
              args.push("--agency.endpoint=" + endpoint);
            } else {
              args.push("--agency.endpoint=" + instances[0].endpoint);
            }
            this.agentCounter++;
            return this.startArango(
              "agency-" + this.agentCounter,
              endpoint,
              "agent",
              args
            );
          })
          .then(instance => {
            return [...instances, instance];
          });
      });
    }
    return promise.then(agents => {
      this.instances = agents;
      return agents;
    });
  }

  findPrimaryDbServer(collectionName) {
    const baseUrl = endpointToUrl(this.getAgencyEndpoint());
    return rp({
      method: "POST",
      uri: baseUrl + "/_api/agency/read",
      json: true,
      body: [
        [
          "/arango/Plan/Collections/_system",
          "/arango/Current/ServersRegistered"
        ]
      ]
    }).then(([info]) => {
      const collections = info.arango.Plan.Collections._system;
      const servers = info.arango.Current.ServersRegistered;
      for (const id of Object.keys(collections)) {
        const collection = collections[id];
        if (collection.name !== collectionName) {
          continue;
        }
        const shards = collection.shards;
        const shardsId = Object.keys(shards)[0];
        const uuid = shards[shardsId][0];
        const endpoint = servers[uuid].endpoint;
        const dbServers = this.dbServers().filter(
          instance => instance.endpoint === endpoint
        );
        if (!dbServers.length) {
          return Promise.reject(new Error(`Unknown endpoint "${endpoint}"`));
        }
        return dbServers[0];
      }
      return Promise.reject(
        new Error(`Unknown collection "${collectionName}"`)
      );
    });
  }

  startCluster(numAgents, numCoordinators, numDbServers, options = {}) {
    let agencyOptions = options.agents || {};
    _.extend(agencyOptions, { agencySize: numAgents });

    return this.startAgency(agencyOptions)
      .then(agents => {
        let promises = [Promise.resolve(agents)];

        let coordinators = Array.from(
          Array(numCoordinators).keys()
        ).map(index => {
          return this.startCoordinator("coordinator-" + (index + 1));
        });
        let dbServers = Array.from(Array(numDbServers).keys()).map(index => {
          return this.startDbServer("dbServer-" + (index + 1));
        });
        return Promise.all([].concat(coordinators, dbServers));
      })
      .then(servers => {
        return this.waitForAllInstances();
      })
      .then(() => {
        return this.getEndpoint();
      });
  }

  waitForInstance(instance) {
    if (instance.status !== "RUNNING") {
      return Promise.reject(
        new Error("Instance " + instance.name + " is down!")
      );
    }
    return rp(endpointToUrl(instance.endpoint) + "/_api/version").then(
      () => {
        return instance;
      },
      () => {
        return new Promise((resolve, reject) => {
          setTimeout(resolve, 100);
        }).then(() => {
          return this.waitForInstance(instance);
        });
      }
    );
  }

  waitForAllInstances() {
    return Promise.all(
      this.instances.map(instance => {
        return this.waitForInstance(instance);
      })
    );
  }

  getEndpoint(instance) {
    return (instance || this.coordinators()[0]).endpoint;
  }

  getEndpointUrl(instance) {
    return endpointToUrl(this.getEndpoint(instance));
  }

  check() {
    return this.instances.every(instance => {
      return instance.status === "RUNNING";
    });
  }

  shutdownCluster() {
    let shutdownPromise;

    let nonAgents = [].concat(this.coordinators(), this.dbServers());

    return Promise.all(
      nonAgents.map(server => {
        server.process.kill();
      })
    )
      .then(() => {
        return Promise.all(
          this.agents().map(agent => {
            return agent.process.kill();
          })
        );
      })
      .then(() => {
        let checkDown = () => {
          let allDown = this.instances.every(instance => {
            return instance.status === "EXITED";
          });

          if (allDown) {
            return Promise.resolve(true);
          } else {
            return new Promise((resolve, reject) => {
              setTimeout(() => {
                checkDown.bind(this)().then(resolve, reject);
              }, 100);
            });
          }
        };
        return checkDown();
      });
  }

  cleanup() {
    return this.shutdownCluster()
      .then(() => {
        this.instances = [];
        this.agentCounter = 0;
        this.coordinatorCounter = 0;
        this.dbServerCounter = 0;
        return this.runner.cleanup();
      })
      .then(() => {
        let log = this.currentLog;
        this.currentLog = "";
        return log;
      });
  }

  dbServers() {
    return this.instances.filter(instance => {
      return instance.role === "primary";
    });
  }

  coordinators() {
    return this.instances.filter(instance => {
      return instance.role === "coordinator";
    });
  }

  agents() {
    return this.instances.filter(instance => {
      return instance.role === "agent";
    });
  }

  assignNewEndpoint(instance) {
    let index = this.instances.indexOf(instance);
    if (index === -1) {
      throw new Error("Couldn't find instance " + instance.name);
    }

    var createNewEndpoint = () => {
      return this.runner.createEndpoint().then(endpoint => {
        if (endpoint != instance.endpoint) {
          return endpoint;
        } else {
          return createNewEndpoint();
        }
      });
    };

    return createNewEndpoint().then(endpoint => {
      [
        "server.endpoint",
        "agency.my-address",
        "cluster.my-address"
      ].filter(arg => {
        index = instance.args.indexOf("--" + arg + "=" + instance.endpoint);
        if (index !== -1) {
          instance.args[index] = "--" + arg + "=" + endpoint;
        }
      });
      return this.runner.updateEndpoint(instance, endpoint);
    });
  }

  kill(instance, signal = "SIGTERM") {
    if (!this.instances.includes(instance)) {
      throw new Error("Couldn't find instance " + instance.name);
    }

    instance.process.kill(signal);
    instance.status = "KILLED";
    return new Promise((resolve, reject) => {
      let check = function() {
        if (instance.status !== "EXITED") {
          setTimeout(check, 50);
        } else {
          resolve();
        }
      };
      check();
    });
  }

  destroy(instance) {
    let promise;
    if (this.instances.includes(instance)) {
      promise = this.kill(instance);
    } else {
      promise = Promise.resolve();
    }
    return promise.then(() => this.runner.destroy(instance)).then(() => {
      const i = this.instances.indexOf(instance);
      if (i !== -1) {
        this.instances = [
          ...this.instances.slice(0, i),
          ...this.instances.slice(i + 1)
        ];
      }
    });
  }

  restart(instance) {
    if (!this.instances.includes(instance)) {
      throw new Error("Couldn't find instance " + instance.name);
    }

    return this.runner.restart(instance).then(() => {
      return this.waitForInstance(instance);
    });
  }

  // this will append the logs to the test in case of a failure so
  // you get a nice combined log of what happened on the server and client
  moveServerLogs(test) {
    if (test.state === "failed") {
      test.err.message = this.currentLog + "\n\n" + test.err.message;
    }
    this.currentLog = "";
  }
}

module.exports = InstanceManager;
<commit_msg>We cann now start all instances with a different storage engine by passing environment variable: ARANGODB_STORAGE_ENGINE<commit_after>"use strict";
const _ = require("lodash");
const rp = require("request-promise");
const LocalRunner = require("./LocalRunner.js");
const DockerRunner = require("./DockerRunner.js");
const endpointToUrl = require("./common.js").endpointToUrl;

class InstanceManager {
  constructor(name) {
    this.instances = [];

    if (process.env.RESILIENCE_ARANGO_BASEPATH) {
      this.runner = new LocalRunner(process.env.RESILIENCE_ARANGO_BASEPATH);
    } else if (process.env.RESILIENCE_DOCKER_IMAGE) {
      this.runner = new DockerRunner(process.env.RESILIENCE_DOCKER_IMAGE);
    }

    if (process.env.ARANGO_STORAGE_ENGINE) {
      this.storageEngine = process.env.ARANGO_STORAGE_ENGINE;
      if (this.storageEngine !== "rocksdb") {
        this.storageEngine = "mmfiles";
      }
    } else {
      this.storageEngine = "mmfiles";
    }

    if (!this.runner) {
      throw new Error(
        'Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container'
      );
    }
    this.currentLog = "";
    this.agentCounter = 0;
    this.coordinatorCounter = 0;
    this.dbServerCounter = 0;
  }

  startArango(name, endpoint, role, args) {
    args.push("--server.authentication=false");
    args.push("--server.storage-engine=" + this.storageEngine);

    let instance = {
      name,
      role,
      process: null,
      status: "NEW",
      exitcode: null,
      endpoint,
      args,
      logFn: line => {
        if (line.trim().length > 0) {
          let logLine =
            instance.name + "(" + instance.process.pid + "): \t" + line;
          if (process.env.LOG_IMMEDIATE) {
            console.log(logLine);
          } else {
            logLine = logLine.replace(/\x1B/g, "");
            this.currentLog += logLine + "\n";
          }
        }
      }
    };
    return this.runner.firstStart(instance);
  }

  startDbServer(name) {
    this.dbServerCounter++;
    return this.runner
      .createEndpoint()
      .then(endpoint => {
        let args = [
          "--cluster.agency-endpoint=" + this.getAgencyEndpoint(),
          "--cluster.my-role=PRIMARY",
          "--cluster.my-local-info=" + name,
          "--cluster.my-address=" + endpoint
        ];
        return this.startArango(name, endpoint, "primary", args);
      })
      .then(instance => {
        this.instances.push(instance);
        return instance;
      });
  }

  getAgencyEndpoint() {
    return this.instances.filter(instance => {
      return instance.role === "agent";
    })[0].endpoint;
  }

  startCoordinator(name) {
    this.coordinatorCounter++;
    return this.runner
      .createEndpoint()
      .then(endpoint => {
        let args = [
          "--cluster.agency-endpoint=" + this.getAgencyEndpoint(),
          "--cluster.my-role=COORDINATOR",
          "--cluster.my-local-info=" + name,
          "--cluster.my-address=" + endpoint
        ];
        return this.startArango(name, endpoint, "coordinator", args);
      })
      .then(instance => {
        this.instances.push(instance);
        return instance;
      });
  }

  replace(instance) {
    let name, role;
    switch (instance.role) {
      case "coordinator":
        this.coordinatorCounter++;
        name = "coordinator-" + this.coordinatorCounter;
        role = "COORDINATOR";
        break;
      case "primary":
        this.dbServerCounter++;
        name = "dbServer-" + this.dbServerCounter;
        role = "PRIMARY";
        break;
      default:
        throw new Error("Can only replace coordinators/dbServers");
    }
    if (this.instances.includes(instance)) {
      throw new Error("Instance must be destroyed before it can be replaced");
    }
    let args = [
      "--cluster.agency-endpoint=" + this.getAgencyEndpoint(),
      "--cluster.my-role=" + role,
      "--cluster.my-local-info=" + name,
      "--cluster.my-address=" + instance.endpoint
    ];
    return this.startArango(name, instance.endpoint, instance.role, args)
      .then(instance => this.waitForInstance(instance))
      .then(instance => {
        this.instances.push(instance);
        return instance;
      });
  }

  startAgency(options = {}) {
    let size = options.agencySize || 1;
    if (options.agencyWaitForSync === undefined) {
      options.agencyWaitForSync = false;
    }
    const wfs = options.agencyWaitForSync;
    let promise = Promise.resolve([]);
    for (var i = 0; i < size; i++) {
      promise = promise.then(instances => {
        return this.runner
          .createEndpoint()
          .then(endpoint => {
            let args = [
              "--agency.activate=true",
              "--agency.size=" + size,
              "--agency.pool-size=" + size,
              "--agency.wait-for-sync=false",
              "--agency.supervision=true",
              "--server.threads=16",
              "--agency.supervision-frequency=1.0",
              "--agency.supervision-grace-period=5.0",
              "--agency.my-address=" + endpoint,
              "--log.force-direct=true"
            ];
            if (instances.length === 0) {
              args.push("--agency.endpoint=" + endpoint);
            } else {
              args.push("--agency.endpoint=" + instances[0].endpoint);
            }
            this.agentCounter++;
            return this.startArango(
              "agency-" + this.agentCounter,
              endpoint,
              "agent",
              args
            );
          })
          .then(instance => {
            return [...instances, instance];
          });
      });
    }
    return promise.then(agents => {
      this.instances = agents;
      return agents;
    });
  }

  findPrimaryDbServer(collectionName) {
    const baseUrl = endpointToUrl(this.getAgencyEndpoint());
    return rp({
      method: "POST",
      uri: baseUrl + "/_api/agency/read",
      json: true,
      body: [
        [
          "/arango/Plan/Collections/_system",
          "/arango/Current/ServersRegistered"
        ]
      ]
    }).then(([info]) => {
      const collections = info.arango.Plan.Collections._system;
      const servers = info.arango.Current.ServersRegistered;
      for (const id of Object.keys(collections)) {
        const collection = collections[id];
        if (collection.name !== collectionName) {
          continue;
        }
        const shards = collection.shards;
        const shardsId = Object.keys(shards)[0];
        const uuid = shards[shardsId][0];
        const endpoint = servers[uuid].endpoint;
        const dbServers = this.dbServers().filter(
          instance => instance.endpoint === endpoint
        );
        if (!dbServers.length) {
          return Promise.reject(new Error(`Unknown endpoint "${endpoint}"`));
        }
        return dbServers[0];
      }
      return Promise.reject(
        new Error(`Unknown collection "${collectionName}"`)
      );
    });
  }

  startCluster(numAgents, numCoordinators, numDbServers, options = {}) {
    let agencyOptions = options.agents || {};
    _.extend(agencyOptions, { agencySize: numAgents });

    return this.startAgency(agencyOptions)
      .then(agents => {
        let promises = [Promise.resolve(agents)];

        let coordinators = Array.from(
          Array(numCoordinators).keys()
        ).map(index => {
          return this.startCoordinator("coordinator-" + (index + 1));
        });
        let dbServers = Array.from(Array(numDbServers).keys()).map(index => {
          return this.startDbServer("dbServer-" + (index + 1));
        });
        return Promise.all([].concat(coordinators, dbServers));
      })
      .then(servers => {
        return this.waitForAllInstances();
      })
      .then(() => {
        return this.getEndpoint();
      });
  }

  waitForInstance(instance) {
    if (instance.status !== "RUNNING") {
      return Promise.reject(
        new Error("Instance " + instance.name + " is down!")
      );
    }
    return rp(endpointToUrl(instance.endpoint) + "/_api/version").then(
      () => {
        return instance;
      },
      () => {
        return new Promise((resolve, reject) => {
          setTimeout(resolve, 100);
        }).then(() => {
          return this.waitForInstance(instance);
        });
      }
    );
  }

  waitForAllInstances() {
    return Promise.all(
      this.instances.map(instance => {
        return this.waitForInstance(instance);
      })
    );
  }

  getEndpoint(instance) {
    return (instance || this.coordinators()[0]).endpoint;
  }

  getEndpointUrl(instance) {
    return endpointToUrl(this.getEndpoint(instance));
  }

  check() {
    return this.instances.every(instance => {
      return instance.status === "RUNNING";
    });
  }

  shutdownCluster() {
    let shutdownPromise;

    let nonAgents = [].concat(this.coordinators(), this.dbServers());

    return Promise.all(
      nonAgents.map(server => {
        server.process.kill();
      })
    )
      .then(() => {
        return Promise.all(
          this.agents().map(agent => {
            return agent.process.kill();
          })
        );
      })
      .then(() => {
        let checkDown = () => {
          let allDown = this.instances.every(instance => {
            return instance.status === "EXITED";
          });

          if (allDown) {
            return Promise.resolve(true);
          } else {
            return new Promise((resolve, reject) => {
              setTimeout(() => {
                checkDown.bind(this)().then(resolve, reject);
              }, 100);
            });
          }
        };
        return checkDown();
      });
  }

  cleanup() {
    return this.shutdownCluster()
      .then(() => {
        this.instances = [];
        this.agentCounter = 0;
        this.coordinatorCounter = 0;
        this.dbServerCounter = 0;
        return this.runner.cleanup();
      })
      .then(() => {
        let log = this.currentLog;
        this.currentLog = "";
        return log;
      });
  }

  dbServers() {
    return this.instances.filter(instance => {
      return instance.role === "primary";
    });
  }

  coordinators() {
    return this.instances.filter(instance => {
      return instance.role === "coordinator";
    });
  }

  agents() {
    return this.instances.filter(instance => {
      return instance.role === "agent";
    });
  }

  assignNewEndpoint(instance) {
    let index = this.instances.indexOf(instance);
    if (index === -1) {
      throw new Error("Couldn't find instance " + instance.name);
    }

    var createNewEndpoint = () => {
      return this.runner.createEndpoint().then(endpoint => {
        if (endpoint != instance.endpoint) {
          return endpoint;
        } else {
          return createNewEndpoint();
        }
      });
    };

    return createNewEndpoint().then(endpoint => {
      [
        "server.endpoint",
        "agency.my-address",
        "cluster.my-address"
      ].filter(arg => {
        index = instance.args.indexOf("--" + arg + "=" + instance.endpoint);
        if (index !== -1) {
          instance.args[index] = "--" + arg + "=" + endpoint;
        }
      });
      return this.runner.updateEndpoint(instance, endpoint);
    });
  }

  kill(instance, signal = "SIGTERM") {
    if (!this.instances.includes(instance)) {
      throw new Error("Couldn't find instance " + instance.name);
    }

    instance.process.kill(signal);
    instance.status = "KILLED";
    return new Promise((resolve, reject) => {
      let check = function() {
        if (instance.status !== "EXITED") {
          setTimeout(check, 50);
        } else {
          resolve();
        }
      };
      check();
    });
  }

  destroy(instance) {
    let promise;
    if (this.instances.includes(instance)) {
      promise = this.kill(instance);
    } else {
      promise = Promise.resolve();
    }
    return promise.then(() => this.runner.destroy(instance)).then(() => {
      const i = this.instances.indexOf(instance);
      if (i !== -1) {
        this.instances = [
          ...this.instances.slice(0, i),
          ...this.instances.slice(i + 1)
        ];
      }
    });
  }

  restart(instance) {
    if (!this.instances.includes(instance)) {
      throw new Error("Couldn't find instance " + instance.name);
    }

    return this.runner.restart(instance).then(() => {
      return this.waitForInstance(instance);
    });
  }

  // this will append the logs to the test in case of a failure so
  // you get a nice combined log of what happened on the server and client
  moveServerLogs(test) {
    if (test.state === "failed") {
      test.err.message = this.currentLog + "\n\n" + test.err.message;
    }
    this.currentLog = "";
  }
}

module.exports = InstanceManager;
<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function() {

var IMPORT_LINK_TYPE = 'import';

// highlander object for parsing a document tree

var componentParser = {
  selectors: [
    'link[rel=' + IMPORT_LINK_TYPE + ']',
    'link[rel=stylesheet]',
    'script[src]',
    'script',
    'style',
    'element'
  ],
  map: {
    link: 'parseLink',
    script: 'parseScript',
    element: 'parseElement',
    style: 'parseStyle'
  },
  parse: function(inDocument) {
    if (!inDocument.__parsed) {
      // only parse once
      inDocument.__parsed = true;
      // upgrade all upgradeable static elements, anything dynamically
      // created should be caught by a watchDOM() observer
      document.upgradeElements(inDocument);
      // all parsable elements in inDocument (depth-first pre-order traversal)
      var elts = inDocument.querySelectorAll(cp.selectors);
      // for each parsable node type in inDocument, call the parsing method
      // to it's local name
      forEach(elts, function(e) {
        //console.log(map[e.localName] + ":", path.nodeUrl(e));
        cp[cp.map[e.localName]](e);
      });
    }
  },
  parseLink: function(inLinkElt) {
    // imports
    if (isDocumentLink(inLinkElt)) {
      if (inLinkElt.content) {
        cp.parse(inLinkElt.content);
      }
    } else if (!inMainDocument(inLinkElt)
        && inLinkElt.parentNode
        && !isElementElementChild(inLinkElt)) {
      document.head.appendChild(inLinkElt);
    }
  },
  parseScript: function(inScriptElt) {
    // ignore scripts in primary document, they are already loaded
    if (inMainDocument(inScriptElt)) {
      return;
    }
    // ignore scripts inside <element>
    if (isElementElementChild(inScriptElt)) {
      return;
    }
    // otherwise, evaluate now
    var code = inScriptElt.__resource || inScriptElt.textContent;
    if (code) {
      eval.call(window, code);
    }
  },
  parseStyle: function(inStyleElt) {
    if (!isElementElementChild(inStyleElt)) {
      document.querySelector('head').appendChild(inStyleElt);
    }
  },
  parseElement: function(inElementElt) {
    new HTMLElementElement(inElementElt);
  }
};

var cp = componentParser;

function inMainDocument(inElt) {
  return inElt.ownerDocument === document ||
    // TODO(sjmiles): ShadowDOMPolyfill intrusion
    inElt.ownerDocument.impl === document;
}

function isDocumentLink(inElt) {
  return (inElt.localName === 'link'
      && inElt.getAttribute('rel') === IMPORT_LINK_TYPE);
}

function isElementElementChild(inElt) {
  if (inElt.parentNode && inElt.parentNode.localName === 'element') {
    return true;
  }
}

var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);

// bootstrap parsing

// IE shim for CustomEvent
if (typeof window.CustomEvent !== 'function') {
  window.CustomEvent = function(inType) {
     var e = document.createEvent('HTMLEvents');
     e.initEvent(inType, true, true);
     return e;
  };
}

function bootstrap() {
  // go async so call stack can unwind
  setTimeout(function() {
    // install auto-upgrader on main document
    document.watchDOM(document.body);
    // parse document
    componentParser.parse(document);
    // TODO(sjmiles): ShadowDOM polyfill pollution
    var doc = window.ShadowDOMPolyfill ?
          ShadowDOMPolyfill.wrap(document)
              : document;
    // notify system
    doc.body.dispatchEvent(
      new CustomEvent('WebComponentsReady', {bubbles: true})
    );
  }, 0);
}

// TODO(sjmiles): 'window' has no wrappability under ShadowDOM polyfill, so
// we are forced to split into two versions

if (window.HTMLImports) {
  document.addEventListener('HTMLImportsLoaded', bootstrap);
} else {
  window.addEventListener('load', bootstrap);
}

})();<commit_msg>add source map to executed scripts to facilitate debugging.<commit_after>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function() {

var IMPORT_LINK_TYPE = 'import';

// highlander object for parsing a document tree

var componentParser = {
  selectors: [
    'link[rel=' + IMPORT_LINK_TYPE + ']',
    'link[rel=stylesheet]',
    'script[src]',
    'script',
    'style',
    'element'
  ],
  map: {
    link: 'parseLink',
    script: 'parseScript',
    element: 'parseElement',
    style: 'parseStyle'
  },
  parse: function(inDocument) {
    if (!inDocument.__parsed) {
      // only parse once
      inDocument.__parsed = true;
      // upgrade all upgradeable static elements, anything dynamically
      // created should be caught by a watchDOM() observer
      document.upgradeElements(inDocument);
      // all parsable elements in inDocument (depth-first pre-order traversal)
      var elts = inDocument.querySelectorAll(cp.selectors);
      // for each parsable node type in inDocument, call the parsing method
      // to it's local name
      forEach(elts, function(e) {
        //console.log(map[e.localName] + ":", path.nodeUrl(e));
        cp[cp.map[e.localName]](e);
      });
    }
  },
  parseLink: function(inLinkElt) {
    // imports
    if (isDocumentLink(inLinkElt)) {
      if (inLinkElt.content) {
        cp.parse(inLinkElt.content);
      }
    } else if (!inMainDocument(inLinkElt)
        && inLinkElt.parentNode
        && !isElementElementChild(inLinkElt)) {
      document.head.appendChild(inLinkElt);
    }
  },
  parseScript: function(inScriptElt) {
    // ignore scripts in primary document, they are already loaded
    if (inMainDocument(inScriptElt)) {
      return;
    }
    // ignore scripts inside <element>
    if (isElementElementChild(inScriptElt)) {
      return;
    }
    // otherwise, evaluate now
    var code = inScriptElt.__resource || inScriptElt.textContent;
    if (code) {
      code += "\n//@ sourceURL=" + inScriptElt.__nodeUrl + "\n";
      eval.call(window, code);
    }
  },
  parseStyle: function(inStyleElt) {
    if (!isElementElementChild(inStyleElt)) {
      document.querySelector('head').appendChild(inStyleElt);
    }
  },
  parseElement: function(inElementElt) {
    new HTMLElementElement(inElementElt);
  }
};

var cp = componentParser;

function inMainDocument(inElt) {
  return inElt.ownerDocument === document ||
    // TODO(sjmiles): ShadowDOMPolyfill intrusion
    inElt.ownerDocument.impl === document;
}

function isDocumentLink(inElt) {
  return (inElt.localName === 'link'
      && inElt.getAttribute('rel') === IMPORT_LINK_TYPE);
}

function isElementElementChild(inElt) {
  if (inElt.parentNode && inElt.parentNode.localName === 'element') {
    return true;
  }
}

var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);

// bootstrap parsing

// IE shim for CustomEvent
if (typeof window.CustomEvent !== 'function') {
  window.CustomEvent = function(inType) {
     var e = document.createEvent('HTMLEvents');
     e.initEvent(inType, true, true);
     return e;
  };
}

function bootstrap() {
  // go async so call stack can unwind
  setTimeout(function() {
    // install auto-upgrader on main document
    document.watchDOM(document.body);
    // parse document
    componentParser.parse(document);
    // TODO(sjmiles): ShadowDOM polyfill pollution
    var doc = window.ShadowDOMPolyfill ?
          ShadowDOMPolyfill.wrap(document)
              : document;
    // notify system
    doc.body.dispatchEvent(
      new CustomEvent('WebComponentsReady', {bubbles: true})
    );
  }, 0);
}

// TODO(sjmiles): 'window' has no wrappability under ShadowDOM polyfill, so
// we are forced to split into two versions

if (window.HTMLImports) {
  document.addEventListener('HTMLImportsLoaded', bootstrap);
} else {
  window.addEventListener('load', bootstrap);
}

})();<|endoftext|>


<commit_before>import "babel-core/polyfill";

import flattenDeep from "lodash.flattendeep";
import assign from "lodash.assign";
import TextItem from "./TextItem";
import ParsedItem from "./ParsedItem";

let funDepth = 0;

function error(msg) {
    throw new Error(msg);
}

function confess(msg) {
    throw new Error(`Internal Error: ${msg}`);
}

function execRegex(str, regex) {
    let match = regex.exec(str);

    if (match === null) {
        return null;
    }

    let matched = match[0];
    let startPos = match.index - 1;
    let endPos = match.index + matched.length;

    return assign(match, {
        matched,

        startPos,
        endPos,

        before: match.input.substr(0, startPos + 1),
        after: match.input.substr(endPos)
    });
}

function ifRegex(str, regex, callback) {
    let result = execRegex(str, regex);

    if (result !== null) {
        return callback(result);
    }
}

function escapeRegexp(str) {
    return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

// function indentedLogger(...messages) {
//     let indent = funDepth * 4;
//     console.log(" ".repeat(indent), ...messages);
// }

// function wrapString(str) {
//     return `"${str.replace(/\n/g, "\\n")}"`;
// }

function filterParsed(...parsedItems) {
    return parsedItems.filter(item => {
        return item !== undefined;
    });
}

const Borders = {
    '{': '}',
    '[': ']',
    '<': '>',
    '(': ')'
};

let testRegexMap = new Map();

testRegexMap.set(/^:::/, () => /$/); // end of file

testRegexMap.set(/^::/, () => /(?=\n\s*\n|$)/); // end of paragraph

testRegexMap.set(/^:/, (match, raw) => { // end of line
    if (/^\S/.test(raw)) {
        error(`reserved function delimiter sequence in .${name}:${match}`);
    }
    return /(?=\n|$)/;
});

testRegexMap.set(/^\s+/, () => /(?=\W|$)/m); // end of word

testRegexMap.set(/^\./, () => {  // dot is a reserved delimeter
    error("reserved function delimiter sequence in .${name}");
});

testRegexMap.set(/^\W/, (match) => { // until that delimiter (or its mirror match)
    let closingSymbol = Borders[match] ? Borders[match]: match;
    closingSymbol = escapeRegexp(closingSymbol);
    return new RegExp(closingSymbol);
});

class Parser {
    constructor() {
        this._Functions = {};
    }
    parse(raw) {
        let result = this.parseRecursive(raw, /$/);
        return new ParsedItem({children: result.parsed}).toString();
    }
    addFunction(name, func) {
        if (name === "") error("Please call addFunction with a named function");
        this._Functions[name] = func;
    }
    newResult(parsed, raw) {
        if (!(parsed instanceof Array)) {
            parsed = [parsed];
        }

        // Flatten children, because we don't want nested arrays -- they are bad
        // for .join("") (leave commas)
        parsed = flattenDeep(parsed);
        return {parsed, raw};
    }
    parseRecursive(raw, stopRegex) {
        let functionStartPos;
        let stopPos;
        let name;

        if (raw === undefined || raw === null) {
            error("raw is undefined");
        }

        let stopHead, stopTail;
        let funHead, funTail;

        ifRegex(raw, stopRegex, (matchResult) => {
            stopPos = matchResult.endPos;
            stopHead = matchResult.before;
            stopTail = matchResult.after;
        });

        ifRegex(raw, /\.([a-z_A-Z]\w*)/, (matchResult) => {
            functionStartPos = matchResult.startPos;
            name = matchResult[1];
            funHead = matchResult.before;
            funTail = matchResult.after;
        });

        let doFun = false;

        if (stopPos === undefined) {
            error("unbounded function call");
        }
        else if (functionStartPos === undefined) {
            doFun = false;
        }
        // both previous function end and current function start are present
        else if (stopPos < functionStartPos) { // end regex is before function start
            doFun = false;
        }
        else {
            doFun = true;
        }

        if (doFun === true) {
            let result = this._parseFun(name, funTail);
            let recursiveParseResult = this.parseRecursive(result.raw, stopRegex);

            let parsed = filterParsed(new TextItem(funHead), result.parsed, recursiveParseResult.parsed);

            return this.newResult(parsed, recursiveParseResult.raw);
        }
        else {
            let parsed = filterParsed(new TextItem(stopHead));

            return this.newResult(parsed, stopTail);
        }
    }
    _callFun(name, raw, stopRegex) {
        if (typeof this._Functions[name] !== 'function') error(`unknown function: ${name}`);
        return this._Functions[name].call(this, raw, stopRegex);
    }
    _parseFun(name, raw) {
        funDepth += 1;
        if (name === undefined) confess("name is undefined");
        if (raw === undefined) confess("raw is undefined");

        if (typeof this._Functions[name] !== 'function') error(`unknown function: ${name}`);

        // parameterless function at the end of the file
        if (raw.length === 0) return this.callFun(name, '', /$/); // The stop regex doesn't really matter as raw is empty

        let stopRegex;

        for (let [regex, callback] of testRegexMap) {
            let result = ifRegex(raw, regex, (match) => {
                // let matchedStr = raw.match(regex)[0];
                // indentedLogger(name, "removed", wrapString(matchedStr), wrapString(raw));
                raw = raw.replace(regex, "");
                stopRegex = callback(match.matched, raw);

                return "break";
            });

            if (result === "break") break; // Allows us to "break" from the callback function
        }

        if (stopRegex === undefined) error(`impossible function call delimiter after .${name}, stopped`);

        let val = this._callFun(name, raw, stopRegex);
        // figure out where new lines are being eaten
        // indentedLogger(name, "raw", wrapString(raw));
        // indentedLogger(name, "parsed", wrapString(val.parsed.toString().substr(-15)));
        funDepth -= 1;
        return val;
    }
}

export default Parser;
Parser.ParsedItem = ParsedItem;
<commit_msg>Add parseFlat, which allows for parsing comments and other such blocks without executing functions within those blocks.<commit_after>import "babel-core/polyfill";

import flattenDeep from "lodash.flattendeep";
import assign from "lodash.assign";
import TextItem from "./TextItem";
import ParsedItem from "./ParsedItem";

let funDepth = 0;

function error(msg) {
    throw new Error(msg);
}

function confess(msg) {
    throw new Error(`Internal Error: ${msg}`);
}

function execRegex(str, regex) {
    let match = regex.exec(str);

    if (match === null) {
        return null;
    }

    let matched = match[0];
    let startPos = match.index - 1;
    let endPos = match.index + matched.length;

    return assign(match, {
        matched,

        startPos,
        endPos,

        before: match.input.substr(0, startPos + 1),
        after: match.input.substr(endPos)
    });
}

function ifRegex(str, regex, callback) {
    let result = execRegex(str, regex);

    if (result !== null) {
        return callback(result);
    }
}

function escapeRegexp(str) {
    return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

// function indentedLogger(...messages) {
//     let indent = funDepth * 4;
//     console.log(" ".repeat(indent), ...messages);
// }

// function wrapString(str) {
//     return `"${str.replace(/\n/g, "\\n")}"`;
// }

function filterParsed(...parsedItems) {
    return parsedItems.filter(item => {
        return item !== undefined;
    });
}

const Borders = {
    '{': '}',
    '[': ']',
    '<': '>',
    '(': ')'
};

let testRegexMap = new Map();

testRegexMap.set(/^:::/, () => /$/); // end of file

testRegexMap.set(/^::/, () => /(?=\n\s*\n|$)/); // end of paragraph

testRegexMap.set(/^:/, (match, raw) => { // end of line
    if (/^\S/.test(raw)) {
        error(`reserved function delimiter sequence in .${name}:${match}`);
    }
    return /(?=\n|$)/;
});

testRegexMap.set(/^\s+/, () => /(?=\W|$)/m); // end of word

testRegexMap.set(/^\./, () => {  // dot is a reserved delimeter
    error("reserved function delimiter sequence in .${name}");
});

testRegexMap.set(/^\W/, (match) => { // until that delimiter (or its mirror match)
    let closingSymbol = Borders[match] ? Borders[match]: match;
    closingSymbol = escapeRegexp(closingSymbol);
    return new RegExp(closingSymbol);
});

class Parser {
    constructor() {
        this._Functions = {};
    }
    parse(raw) {
        let result = this.parseRecursive(raw, /$/);
        return new ParsedItem({children: result.parsed}).toString();
    }
    addFunction(name, func) {
        if (name === "") error("Please call addFunction with a named function");
        this._Functions[name] = func;
    }
    newResult(parsed, raw) {
        if (!(parsed instanceof Array)) {
            parsed = [parsed];
        }

        // Flatten children, because we don't want nested arrays -- they are bad
        // for .join("") (leave commas)
        parsed = flattenDeep(parsed);
        return {parsed, raw};
    }
    parseRecursive(raw, stopRegex) {
        let functionStartPos;
        let stopPos;
        let name;

        if (raw === undefined || raw === null) {
            error("raw is undefined");
        }

        let stopHead, stopTail;
        let funHead, funTail;

        ifRegex(raw, stopRegex, (matchResult) => {
            stopPos = matchResult.endPos;
            stopHead = matchResult.before;
            stopTail = matchResult.after;
        });

        ifRegex(raw, /\.([a-z_A-Z]\w*)/, (matchResult) => {
            functionStartPos = matchResult.startPos;
            name = matchResult[1];
            funHead = matchResult.before;
            funTail = matchResult.after;
        });

        let doFun = false;

        if (stopPos === undefined) {
            error("unbounded function call");
        }
        else if (functionStartPos === undefined) {
            doFun = false;
        }
        // both previous function end and current function start are present
        else if (stopPos < functionStartPos) { // end regex is before function start
            doFun = false;
        }
        else {
            doFun = true;
        }

        if (doFun === true) {
            let result = this._parseFun(name, funTail);
            let recursiveParseResult = this.parseRecursive(result.raw, stopRegex);

            let parsed = filterParsed(new TextItem(funHead), result.parsed, recursiveParseResult.parsed);

            return this.newResult(parsed, recursiveParseResult.raw);
        }
        else {
            let parsed = filterParsed(new TextItem(stopHead));

            return this.newResult(parsed, stopTail);
        }
    }
    parseFlat(raw, stopRegex) {
        if (raw === undefined || raw === null) {
            error("raw is undefined");
        }

        let stopHead, stopTail;

        ifRegex(raw, stopRegex, (matchResult) => {
            stopHead = matchResult.before;
            stopTail = matchResult.after;
        });

        if (stopHead !== undefined) {
            return this.newResult(stopHead, stopTail);
        } else {
            error("unbounded function call");
        }
    }
    _callFun(name, raw, stopRegex) {
        if (typeof this._Functions[name] !== 'function') error(`unknown function: ${name}`);
        return this._Functions[name].call(this, raw, stopRegex);
    }
    _parseFun(name, raw) {
        funDepth += 1;
        if (name === undefined) confess("name is undefined");
        if (raw === undefined) confess("raw is undefined");

        if (typeof this._Functions[name] !== 'function') error(`unknown function: ${name}`);

        // parameterless function at the end of the file
        if (raw.length === 0) return this.callFun(name, '', /$/); // The stop regex doesn't really matter as raw is empty

        let stopRegex;

        for (let [regex, callback] of testRegexMap) {
            let result = ifRegex(raw, regex, (match) => {
                // let matchedStr = raw.match(regex)[0];
                // indentedLogger(name, "removed", wrapString(matchedStr), wrapString(raw));
                raw = raw.replace(regex, "");
                stopRegex = callback(match.matched, raw);

                return "break";
            });

            if (result === "break") break; // Allows us to "break" from the callback function
        }

        if (stopRegex === undefined) error(`impossible function call delimiter after .${name}, stopped`);

        let val = this._callFun(name, raw, stopRegex);
        // figure out where new lines are being eaten
        // indentedLogger(name, "raw", wrapString(raw));
        // indentedLogger(name, "parsed", wrapString(val.parsed.toString().substr(-15)));
        funDepth -= 1;
        return val;
    }
}

export default Parser;
Parser.ParsedItem = ParsedItem;
<|endoftext|>


<commit_before>const Log = require("./Log");
const fs = require("fs");

module.exports = class Plugin {

    static get Type() {
        return {
            NORMAL: 0x01,
            INLINE: 0x02,
            PROXY: 0x04,
            SPECIAL: 0x08
        };
    }

    static get Visibility() {
        return {
            VISIBLE: 0,
            HIDDEN: 1
        };
    }

    static get plugin() {
        return {
            name: "Plugin",
            description: "Base Plugin",
            help: "There is no need to ask for help",
            needs: {
                database: false,
                utils: false
            },

            visibility: Plugin.Visibility.HIDDEN,
            type: Plugin.Type.SPECIAL
        };
    }

    get plugin() {
        return this.constructor.plugin;
    }

    synchronize(cb = err => {
        if (err) throw err;
    }) {
        if (!this.db) return;
        fs.writeFile(
            `./db/plugin_${this.plugin.name}.json`,
            JSON.stringify(this.db, null, 4),
            cb
        );
    }

    constructor(listener, config) {
        if (new.target === Plugin) {
            throw new TypeError("Cannot construct Plugin instances directly!");
        }

        this.log = Log.get(this.plugin.name, config);
        this.listener = listener;
        this.blacklist = new Set(); // Chats where the plugin is disabled

        if (this.plugin.needs) {
            if (this.plugin.needs.database) {
                try {
                    const serialized = fs.readFileSync(`./db/plugin_${this.plugin.name}.json`, "utf8");
                    this.db = JSON.parse(serialized);
                } catch (e) {
                    this.db = {};
                }
            }
        }

        this.syncInterval = 5000;

        this.syncTimer = setInterval(() => this.synchronize(), this.syncInterval);

        this.handlerNames = {
            text: "onText",
            inline_query: "onInline",
            _command: "onCommand",
            _inline_command: "onInlineCommand",
            audio: "onAudio",
            document: "onDocument",
            photo: "onPhoto",
            sticker: "onSticker",
            video: "onVideo",
            voice: "onVoice",
            contact: "onContact",
            location: "onLocation",
            new_chat_participant: "onNewChatParticipant",
            left_chat_participant: "onLeftChatParticipant"
        };

        this.handlers = {};

        const eventNames = Object.keys(this.handlerNames);
        for (const eventName of eventNames) {
            const handlerName = this.handlerNames[eventName];
            if (typeof this[handlerName] !== 'function') continue;
            const isEnabled = id => !this.blacklist.has(id); // A function that says whether the plugin is enabled or not in a given chat.
            const eventHandler = this[handlerName].bind(this); // A function that refers to the appropriate handler (this.onText, this.onCommand, etc.)
            const wrappedHandler = function({message}) {
                if (isEnabled(message.chat.id)) eventHandler.apply(null, arguments);
            }; // A function that receives the event, checks the message against the blacklist, and calls the appropriate handler
            this.listener.on(eventName, wrappedHandler);
            this.handlers[eventName] = wrappedHandler; // Keeps a reference to the handler so that it can be removed later
        }
    }

    start() {
        return;
    }

    stop() {
        clearInterval(this.syncTimer);
        const eventNames = Object.keys(this.handlers);
        for (const eventName of eventNames) {
            const handler = this.handlers[eventName];
            this.listener.removeListener(eventName, handler);
        }
    }
};
<commit_msg>Save blacklist to database<commit_after>const Log = require("./Log");
const fs = require("fs");

module.exports = class Plugin {

    static get Type() {
        return {
            NORMAL: 0x01,
            INLINE: 0x02,
            PROXY: 0x04,
            SPECIAL: 0x08
        };
    }

    static get Visibility() {
        return {
            VISIBLE: 0,
            HIDDEN: 1
        };
    }

    static get plugin() {
        return {
            name: "Plugin",
            description: "Base Plugin",
            help: "There is no need to ask for help",
            needs: {
                database: false,
                utils: false
            },

            visibility: Plugin.Visibility.HIDDEN,
            type: Plugin.Type.SPECIAL
        };
    }

    get plugin() {
        return this.constructor.plugin;
    }

    synchronize(cb = err => {
        if (err) throw err;
    }) {
        if (!this.db) return;
        fs.writeFile(
            `./db/plugin_${this.plugin.name}.json`,
            JSON.stringify({
                db: this.db,
                blacklist: Array.from(this.blacklist)
            }, null, 2),
            cb
        );
    }

    constructor(listener, config) {
        if (new.target === Plugin) {
            throw new TypeError("Cannot construct Plugin instances directly!");
        }

        this.log = Log.get(this.plugin.name, config);
        this.listener = listener;

        this.db = {};
        this.blacklist = new Set(); // Chats where the plugin is disabled
        try {
            const {db, blacklist} = JSON.parse(fs.readFileSync(`./db/plugin_${this.plugin.name}.json`, "utf8"));
            if (db) this.db = db;
            if (blacklist) this.blacklist = new Set(blacklist);
        } catch(e) {}

        this.syncInterval = 5000;

        this.syncTimer = setInterval(() => this.synchronize(), this.syncInterval);

        this.handlerNames = {
            text: "onText",
            inline_query: "onInline",
            _command: "onCommand",
            _inline_command: "onInlineCommand",
            audio: "onAudio",
            document: "onDocument",
            photo: "onPhoto",
            sticker: "onSticker",
            video: "onVideo",
            voice: "onVoice",
            contact: "onContact",
            location: "onLocation",
            new_chat_participant: "onNewChatParticipant",
            left_chat_participant: "onLeftChatParticipant"
        };

        this.handlers = {};

        const eventNames = Object.keys(this.handlerNames);
        for (const eventName of eventNames) {
            const handlerName = this.handlerNames[eventName];
            if (typeof this[handlerName] !== 'function') continue;
            const isEnabled = id => !this.blacklist.has(id); // A function that says whether the plugin is enabled or not in a given chat.
            const eventHandler = this[handlerName].bind(this); // A function that refers to the appropriate handler (this.onText, this.onCommand, etc.)
            const wrappedHandler = function({message}) {
                if (isEnabled(message.chat.id)) eventHandler.apply(null, arguments);
            }; // A function that receives the event, checks the message against the blacklist, and calls the appropriate handler
            this.listener.on(eventName, wrappedHandler);
            this.handlers[eventName] = wrappedHandler; // Keeps a reference to the handler so that it can be removed later
        }
    }

    start() {
        return;
    }

    stop() {
        clearInterval(this.syncTimer);
        const eventNames = Object.keys(this.handlers);
        for (const eventName of eventNames) {
            const handler = this.handlers[eventName];
            this.listener.removeListener(eventName, handler);
        }
    }
};
<|endoftext|>


<commit_before>function getRandomColor() {
    //http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript/1484514#1484514
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

var Scores = Backbone.View.extend({

    initialize: function (options) {
        _(this).bindAll('onScores');
    },

    onScores: function (scores) {
        this.scores = scores;
        this.render();
    },

    render: function () {
        var self = this;
        var scores = _.map(self.scores, function (value, key) {
            return {
                name: key,
                length: value
            }
        });

        scores = _.sortBy(scores, function (item) {
            return -item.length;
        });

        self.$el.html('

');
        _.each(scores, function (item) {
            self.$('ul').append('
' + item.length + ' ' + item.name + '
');
        });
    }

});

var Board = Backbone.View.extend({
    isFree: true,
    colors: {
        snakes: _.map(_.range(100), function () {
            return getRandomColor();
        }),
        apple: '#ff0000',
        empty: '#ffffff'
    },

    initialize: function (options) {
        _(this).bindAll(
            'onConfig', 'onBoard',
            'drawApple', 'drawSnake',
            'render');
        this.size = options.size;

        this.canvas = this.$('canvas')[0];
        this.canvasContext = this.canvas.getContext("2d");
    },

    onConfig: function (config) {
        var width = config.size * this.size;
        var height = config.size * this.size;

        this.$el.css('width', width + 20);
        this.$el.css('height', width + 20);
        this.canvas.width = width;
        this.canvas.height = height;
    },

    onBoard: function (board) {
        if (this.isFree){
            this.isFree = false;
            this.render(board);
            this.isFree = true;
        }
    },

    render: function (board) {
        this.canvasContext.fillStyle = this.colors.empty;
        this.canvasContext.fillRect(0, 0, board.size * this.size, board.size * this.size);

        var snakes = board.state.snakes;
        var apples = board.state.apples;

        this.drawApples(apples);
        this.drawSnakes(snakes);
    },

    drawApples: function (apples) {
        this.canvasContext.fillStyle = this.colors.apple;
        _.each(apples, this.drawApple);
    },

    drawApple: function (coords) {
        this.canvasContext.beginPath();
        this.canvasContext.arc(
            coords.x * this.size + (this.size/2),
            coords.y * this.size + (this.size/2),
            this.size/2, 0, 2*Math.PI);
        this.canvasContext.fill();
        this.canvasContext.stroke();
    },

    drawSnakes: function (snakes) {
        _.each(snakes, this.drawSnake);
    },

    drawSnake: function (snake) {
        var self = this;
        self.canvasContext.fillStyle = self.colors.snakes[snake.uniqueId];;
        _.each(snake.body, function (coords, index) {
            self.canvasContext.beginPath();
            self.canvasContext.arc(
                coords.x * self.size + (self.size/2),
                coords.y * self.size + (self.size/2),
                self.size/2, 0, 2*Math.PI);
            self.canvasContext.fill();
            self.canvasContext.stroke();
            if (index == 0) {
                self.canvasContext.fillText(
                    snake.options.name,
                    coords.x * self.size - 2,
                    coords.y * self.size - 2);
            }
        });
    }
});

var Management = Backbone.View.extend({

    events: {
        'submit form': 'addSnake'
    },

    initialize: function (options) {
        this.socket = options.socket;
    },

    addSnake: function (e) {
        e.preventDefault();
        var name = this.$('input[name="name"]').val();
        var url = this.$('input[name="url"]').val();
        this.socket.emit('add-snake', {
            name: name,
            url: url
        });
    }
});

var Client = Backbone.View.extend({

    initialize: function (options) {
        this.socket = io.connect(); //connect to source domain

        //Board
        this.board = new Board({
            el: this.$('.board'),
            size: options.size
        });
        this.socket.on('config', this.board.onConfig);
        this.socket.on('board', this.board.onBoard);

        //Scores
        this.scores = new Scores({
            el: this.$('.scores'),
        });
        this.socket.on('scores', this.scores.onScores);

        //Management
        this.management = new Management({
            el: this.$('.management'),
            socket: this.socket
        });
    }
});<commit_msg>use requestAnimationFrame in client<commit_after>function getRandomColor() {
    //http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript/1484514#1484514
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

var Scores = Backbone.View.extend({

    initialize: function (options) {
        _(this).bindAll('onScores');
    },

    onScores: function (scores) {
        this.scores = scores;
        this.render();
    },

    render: function () {
        var self = this;
        var scores = _.map(self.scores, function (value, key) {
            return {
                name: key,
                length: value
            }
        });

        scores = _.sortBy(scores, function (item) {
            return -item.length;
        });

        self.$el.html('

');
        _.each(scores, function (item) {
            self.$('ul').append('
' + item.length + ' ' + item.name + '
');
        });
    }

});

var Board = Backbone.View.extend({
    isFree: true,
    colors: {
        snakes: _.map(_.range(100), function () {
            return getRandomColor();
        }),
        apple: '#ff0000',
        empty: '#ffffff'
    },

    initialize: function (options) {
        _(this).bindAll(
            'onConfig', 'onBoard',
            'drawApple', 'drawSnake',
            'render', 'updateScreen');
        this.size = options.size;

        this.canvas = this.$('canvas')[0];
        this.canvasContext = this.canvas.getContext("2d");
    },

    onConfig: function (config) {
        var width = config.size * this.size;
        var height = config.size * this.size;

        this.$el.css('width', width + 20);
        this.$el.css('height', width + 20);
        this.canvas.width = width;
        this.canvas.height = height;
    },

    onBoard: function (board) {
        this.board = board;
        if (this.isFree){
            this.isFree = false;
            this.updateScreen();
        }
    },

    updateScreen: function () {
        this.render();
        requestAnimationFrame(this.updateScreen);
    },

    render: function () {
        this.canvasContext.fillStyle = this.colors.empty;
        this.canvasContext.fillRect(0, 0, this.board.size * this.size, this.board.size * this.size);

        var snakes = this.board.state.snakes;
        var apples = this.board.state.apples;

        this.drawApples(apples);
        this.drawSnakes(snakes);
    },

    drawApples: function (apples) {
        this.canvasContext.fillStyle = this.colors.apple;
        _.each(apples, this.drawApple);
    },

    drawApple: function (coords) {
        this.canvasContext.beginPath();
        this.canvasContext.arc(
            coords.x * this.size + (this.size/2),
            coords.y * this.size + (this.size/2),
            this.size/2, 0, 2*Math.PI);
        this.canvasContext.fill();
        this.canvasContext.stroke();
    },

    drawSnakes: function (snakes) {
        _.each(snakes, this.drawSnake);
    },

    drawSnake: function (snake) {
        var self = this;
        self.canvasContext.fillStyle = self.colors.snakes[snake.uniqueId];;
        _.each(snake.body, function (coords, index) {
            self.canvasContext.beginPath();
            self.canvasContext.arc(
                coords.x * self.size + (self.size/2),
                coords.y * self.size + (self.size/2),
                self.size/2, 0, 2*Math.PI);
            self.canvasContext.fill();
            self.canvasContext.stroke();
            if (index == 0) {
                self.canvasContext.fillText(
                    snake.options.name,
                    coords.x * self.size - 2,
                    coords.y * self.size - 2);
            }
        });
    }
});

var Management = Backbone.View.extend({

    events: {
        'submit form': 'addSnake'
    },

    initialize: function (options) {
        this.socket = options.socket;
    },

    addSnake: function (e) {
        e.preventDefault();
        var name = this.$('input[name="name"]').val();
        var url = this.$('input[name="url"]').val();
        this.socket.emit('add-snake', {
            name: name,
            url: url
        });
    }
});

var Client = Backbone.View.extend({

    initialize: function (options) {
        this.socket = io.connect(); //connect to source domain

        //Board
        this.board = new Board({
            el: this.$('.board'),
            size: options.size
        });
        this.socket.on('config', this.board.onConfig);
        this.socket.on('board', this.board.onBoard);

        //Scores
        this.scores = new Scores({
            el: this.$('.scores'),
        });
        this.socket.on('scores', this.scores.onScores);

        //Management
        this.management = new Management({
            el: this.$('.management'),
            socket: this.socket
        });
    }
});<|endoftext|>