<commit_before>'use strict';

// this Babel plugin removes configuration comments such as:
//   <!-- template-lint triple-curlies=false -->
//   <!-- template-lint enabled=false -->

const AstNodeInfo = require('ember-template-lint/lib/helpers/ast-node-info');

module.exports = function() {
  function RemoveConfigurationHtmlCommentsPlugin() {}

  RemoveConfigurationHtmlCommentsPlugin.prototype.transform = function(ast) {
    let walker = new this.syntax.Walker();
    let bodyEntry;

    walker.visit(ast, node => {
      if (node.type === 'Program') {
        for (let i = 0; i < node.body.length; i++) {
          bodyEntry = node.body[i];

          if(AstNodeInfo.isConfigurationHtmlComment(bodyEntry)) {
            // remove the entry
            node.body.splice(i, 1);
          }
        }
      }
    });

    return ast;
  };

  return RemoveConfigurationHtmlCommentsPlugin;
};
<commit_msg>Support usage inside paralle babel inside inline-hbs<commit_after>'use strict';

// this Babel plugin removes configuration comments such as:
//   <!-- template-lint triple-curlies=false -->
//   <!-- template-lint enabled=false -->

const AstNodeInfo = require('ember-template-lint/lib/helpers/ast-node-info');

module.exports = function() {
  function RemoveConfigurationHtmlCommentsPlugin() {}

  RemoveConfigurationHtmlCommentsPlugin.prototype.transform = function(ast) {
    let walker = new this.syntax.Walker();
    let bodyEntry;

    walker.visit(ast, node => {
      if (node.type === 'Program') {
        for (let i = 0; i < node.body.length; i++) {
          bodyEntry = node.body[i];

          if(AstNodeInfo.isConfigurationHtmlComment(bodyEntry)) {
            // remove the entry
            node.body.splice(i, 1);
          }
        }
      }
    });

    return ast;
  };

  RemoveConfigurationHtmlCommentsPlugin.parallelBabel = {
    requireFile: __filename,
    buildUsing: 'self',
  };

  return RemoveConfigurationHtmlCommentsPlugin;
};

module.exports.self = function(){ return module.exports(); };

<|endoftext|>


<commit_before>//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//

// Edit user info ------------------------------------------------------------//
router.put('/update', function(req, res) {
  console.log('ARRIVED IN EDIT ROUTE');
  console.log('USER DATA:', req.body.userData);
  var userData = req.body.userData;

  var userType = req.userStatus.userType;
  var typeId = userType + '_id';
  var userDatabase = userType + 's';
  var userId = req.userStatus.userId;

  // This is what incoming data will look like
  // var userData = {
  //   first_name: null,
  //   last_name: null,
  //   email: null,
  //   avatar: null,
  //   company: null,
  //   job_title: null,
  //   zip: null,
  //   race: null,
  //   gender: null,
  //   orientation: null,
  //   birthday: null,
  //   school: null,
  //   degree: null,
  //   major: null,
  //   languages: null
  // };

  var query = queryBuilder(userData) + ' WHERE id = $1';
  console.log(query);

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    // Update the database
    client.query(query, [userId],
      function(error, result) {
        done(); // Close connection to the database

        if(error) {
          console.log('Unable to update user information: ', error);
          res.sendStatus(500);
        } else {
          console.log('SUCCESSFUL! USER DATA:', userData);
          res.sendStatus(200);
        }

      }
    );
  });
});

// Create a new FAQ entry ----------------------------------------------------//
router.post('/new-faq', function(req, res) {
  var userId = req.userStatus.userId;
  var question = req.body.faqData.question;
  var answer = req.body.faqData.answer;
  console.log("FAQ OBJECT:", req.body.faqData);

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    client.query(
      'INSERT INTO faq (mentor_id, question, answer) VALUES ($1, $2, $3)',
      [userId, question, answer],
      function(error, result) {
        done();
        if(error) {
          console.log('Error when creating new FAQ: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(201);
        }
      }
    );
  });
});

// Edit an existing FAQ entry ------------------------------------------------//
router.put('/edit-faq/:faq-id', function(req, res) {
  var userId = req.userStatus.userId;
  var faqId = req.body.faqId;
  var question = req.body.question;
  var answer = req.body.answer;

  pg.connect(connectionString, function(error, client, done) {
    connectionString(error);

    client.query(
      'UPDATE faq SET question = $1 AND answer = $2 WHERE id = $3',
      [question, answer, faqId],
      function(error, result) {
        done();
        if(error) {
          console.log('Error when updating FAQ: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(201);
        }
      }
    );
  });
});

module.exports = router;

// Checks for errors connecting to the database ------------------------------//
function connectionErrorCheck(error) {
  if (error) {
    console.log('Database connection error: ', error);
    res.sendStatus(500);
  }
}

// Cunstructs SQL query based off of user defined search paramaters ----------//
function queryBuilder(object) {
  console.log('OBJECT IN QUERY BUILDER', object);
  var query = 'UPDATE mentors SET';

  for(var property in object) {
    if(object[property]) {
      query += ' ' + property + ' = \'' + object[property] + '\',';
    }
  }

  query = query.slice(0, -1);

  return query;
}
<commit_msg>Add func to assign userId based on isAdmin<commit_after>//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//

// Edit user info ------------------------------------------------------------//
router.put('/update/:id', function(req, res) {
  console.log('ARRIVED IN EDIT ROUTE');
  console.log('USER DATA:', req.body.userData);
  var userData = req.body.userData;

  var userType = req.userStatus.userType;
  var typeId = userType + '_id';
  var userDatabase = userType + 's';
  var userId;

  console.log("USER ID IN PARAMS", req.params.id);
  assignUserId();
  function assignUserId(){
    if(req.userStatus.isAdmin === true){
      userId = req.params.id;
    } else {
      userId = req.userStatus.userId;
    }
  }
  // userId = req.userStatus.userId;

  // This is what incoming data will look like
  // var userData = {
  //   first_name: null,
  //   last_name: null,
  //   email: null,
  //   avatar: null,
  //   company: null,
  //   job_title: null,
  //   zip: null,
  //   race: null,
  //   gender: null,
  //   orientation: null,
  //   birthday: null,
  //   school: null,
  //   degree: null,
  //   major: null,
  //   languages: null
  // };

  var query = queryBuilder(userData) + ' WHERE id = $1';
  console.log(query);

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    // Update the database
    client.query(query, [userId],
      function(error, result) {
        done(); // Close connection to the database

        if(error) {
          console.log('Unable to update user information: ', error);
          res.sendStatus(500);
        } else {
          console.log('SUCCESSFUL! USER DATA:', userData);
          res.sendStatus(200);
        }

      }
    );
  });
});

// Create a new FAQ entry ----------------------------------------------------//
router.post('/new-faq', function(req, res) {
  var userId = req.userStatus.userId;
  var question = req.body.faqData.question;
  var answer = req.body.faqData.answer;
  console.log("FAQ OBJECT:", req.body.faqData);

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    client.query(
      'INSERT INTO faq (mentor_id, question, answer) VALUES ($1, $2, $3)',
      [userId, question, answer],
      function(error, result) {
        done();
        if(error) {
          console.log('Error when creating new FAQ: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(201);
        }
      }
    );
  });
});

// Edit an existing FAQ entry ------------------------------------------------//
router.put('/edit-faq/:faq-id', function(req, res) {
  var userId = req.userStatus.userId;
  var faqId = req.body.faqId;
  var question = req.body.question;
  var answer = req.body.answer;

  pg.connect(connectionString, function(error, client, done) {
    connectionString(error);

    client.query(
      'UPDATE faq SET question = $1 AND answer = $2 WHERE id = $3',
      [question, answer, faqId],
      function(error, result) {
        done();
        if(error) {
          console.log('Error when updating FAQ: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(201);
        }
      }
    );
  });
});

module.exports = router;

// Checks for errors connecting to the database ------------------------------//
function connectionErrorCheck(error) {
  if (error) {
    console.log('Database connection error: ', error);
    res.sendStatus(500);
  }
}

// Cunstructs SQL query based off of user defined search paramaters ----------//
function queryBuilder(object) {
  console.log('OBJECT IN QUERY BUILDER', object);
  var query = 'UPDATE mentors SET';

  for(var property in object) {
    if(object[property]) {
      query += ' ' + property + ' = \'' + object[property] + '\',';
    }
  }

  query = query.slice(0, -1);

  return query;
}
<|endoftext|>


<commit_before>var config = require('./config/config'),
mongoose = require('./config/mongoose'),
Bot = require('node-telegram-bot');
var db = mongoose();

var parseRollString = function(rollStr){
	console.log(rollStr);
	if(rollStr.indexOf('d') === -1){
		return false;
	}
	var splitStr = rollStr.split('d');
	// console.log(splitStr);
	var firstPart = splitStr[0];
	var secondPart = rollStr.substring(firstPart.length + 1);

	times = parseInt(firstPart);

	if(times === NaN || times <= 0 || times > 100){
		return false;
	}
	//no more than 100 due to abuse considerations
	//firstInt is a positive integer at this point
	console.log("times: " + times);

	var dice = NaN;
	var modifier = NaN;
	if(rollStr.indexOf('+') > 0 ){
		splitStr = secondPart.split('+');
		if(splitStr.length > 2){
			return false;
		}
		dice = parseInt(splitStr[0]);
		modifier = parseInt(splitStr[1]);
	} else if (rollStr.indexOf('-') > 0 ){
		splitStr = secondPart.split('-');
		if(splitStr.length > 2){
			return false;
		}
		dice = parseInt(splitStr[0]);
		modifier = -1 * parseInt(splitStr[1]);
	} else {
		dice = parseInt(secondPart);
		modifier = 0;
	}

	if(dice === NaN || modifier === NaN){
		return false;
	}

	rollValues = {
		"times" : times,
		"dice" : dice,
		"modifier" : modifier
	};

	console.log(rollValues);

	return rollValues;

};

var calculateRoll = function(roll){
	var sum = 0;
	for (var i = 0; i < roll.times; i++) {
		sum += Math.floor(Math.random() * roll.dice) + 1;
	};
	sum += roll.modifier;
	return sum;
}

var bot = new Bot({
	token: config.token
})
.on('message', function (message) {
	console.log(message);
	var User = db.model('User');
	var Roll = db.model('Roll');

	if(message.hasOwnProperty("text"))
	{
		splitStr = message.text.split(" ");

		if(splitStr.length === 1)
		{
			if(splitStr[0] === "/register")
			{
				console.log("entered /register")
				var userRegisterCallback = function(err,user){
					// var User = db.model('User');
					if(err)
					{
						console.log("error at /register, User.findOne");
						console.log(err);
						bot.sendMessage({"chat_id" : message.chat.id , "text" : err},function(nodifiedPromise){});
						return
					}
					if(user === null)
					{
						User.create({"id": message.from.id}, function(err){
							console.log("error at /register, User.findOne, User.create");
							console.log(err);
							bot.sendMessage({"chat_id" : message.chat.id , "text" : err},function(nodifiedPromise){});
							return
						});
						console.log('added new user');
						bot.sendMessage({"chat_id" : message.chat.id , "text" : "User " + message.from.username + " is registered"},function(nodifiedPromise){});
					} else {
						bot.sendMessage({"chat_id" : message.chat.id , "text" : "User " + message.from.username + " was already registered"},function(nodifiedPromise){});
					}
				};
				userRegisterCallback.message = message;
				User.findOne({"id": message.from.id}, userRegisterCallback);
			}
			else if (splitStr[0] === "/help")
			{
				bot.sendMessage({"chat_id" : message.chat.id , "text" : "/register - register to start using the bot and save your custom rolls | usage: \"/register\"\n/qroll - quick roll without saving a custom roll | usage: \"/qroll 1d4+1\"\n/save - save a custom roll | usage \"/save magicmissile 1d4+1\"\n/roll - roll a previously saved custom roll | usage: \"/roll magicmissile\""});
			}
			else if (splitStr[0] === "/show")
			{
				console.log("showing rolls");
				var userCallback = function(err,user)
				{
					if(err)
					{
						console.log(err);
						bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
						return
					}
					if(user === null)
					{
						bot.sendMessage({"chat_id" : message.chat.id , "text" : "Please register first by typing \"/register\" (without the quotes)"});
					} else
					{
						console.log('found user');
					//found user, now display rolls
						var rollCallback = function(err,rolls)
						{
							if(err)
							{
								console.log(err);
								bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
								return
							}
							if(rolls === null)
							{
								bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "No saved rolls found. Please save a roll first with \"/save <roll name> <integer>d<integer>{+,-}<integer>\", for example: \"/save magicmissile 1d4+1\""},function(nodifiedPromise){});
							}
							else
							{
								console.log('found rolls');
								var msgText = 'Saved rolls for ' + message.from.username + '\n';
								rolls.forEach(function(val,ind,arr){
									var modifierSign = '+';
									if(val.modifier < 0) modifierSign = '';
									msgText += val.name + " | " + val.times + "d" + val.dice +  modifierSign + val.modifier + '\n';
								});
								bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : msgText },function(nodifiedPromise){});
							}
						}
						rollCallback.message = message;
						Roll.find({"id": message.from.id},rollCallback);
					}
				}
				userCallback.message = message;
				User.findOne({"id": message.from.id}, userCallback);
			}

		}
		else if (splitStr.length === 2)
		{
			if(splitStr[0] === "/roll")
			{
				var key = splitStr[1];
				var userCallback = function(err,user){
					if(err)
					{
						console.log(err);
						bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
						return
					}
					if(user === null)
					{
						bot.sendMessage({"chat_id" : message.chat.id , "text" : "Please register first by typing \"/register\" (without the quotes)"});
					} else
					{
						//found user, now find roll if exists
						var rollCallback = function(err,roll){
							if(err)
							{
								console.log(err);
								bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
								return
							}
							if(roll === null)
							{
								bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Unsaved custom roll. Please save first with \"/save <roll name> <integer>d<integer>{+,-}<integer>\", for example: \"/save magicmissile 1d4+1\""},function(nodifiedPromise){});
							} else
							{
								var newRoll = {};
								newRoll.times = roll.times;
								newRoll.dice = roll.dice;
								newRoll.modifier = roll.modifier;
								result = calculateRoll(newRoll);
								bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : message.from.username + " | " + key + " | " + result },function(nodifiedPromise){});
							}

						}
						rollCallback.message = message;
						rollCallback.key = key;
						Roll.findOne({"id": message.from.id , "name" : key},rollCallback);
					// 	if(user.rolls.hasOwnProperty(key))
					// 	{
					// 		roll = user.rolls[key];
					// 		result = calculateRoll(roll);
					// 		bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : message.from.username + " | " + key + " | " + result },function(nodifiedPromise){});
					// 	// bot.sendMessage({"chat_id" : message.chat.id ,"text" : },function(nodifiedPromise){});

					// } else {
					// 	bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Roll name not found. Please save this roll first by \"/save <rollName> <integer>d<integer>{+,-}<integer>\", for example: \"/save magicmissile 1d4+1\""},function(nodifiedPromise){});
					// }
				}
			};
			userCallback.message = message;
			userCallback.key = key;
			User.findOne({"id": message.from.id}, userCallback);
			}
			else if(splitStr[0] === "/qroll")
			{
				var roll = parseRollString(splitStr[1]);
				if(roll === false){
					bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Invalid roll format or unsaved custom roll. The expected format is \"/qroll <integer>d<integer>{+,-}<integer>\", for example: \"/qroll 2d12+4\""},function(nodifiedPromise){});
					return
				}
				var result = calculateRoll(roll);
				bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : message.from.username + " | " + splitStr[1] + " | " + result },function(nodifiedPromise){});
			}
			// else
			// {
			// 	bot.sendMessage({"chat_id" : message.chat.id , "text" : "Unknown request. Try /help for options"});
			// }
		}
		else if (splitStr.length === 3)
		{
			if(splitStr[0] === "/save")
			{
			var key = splitStr[1];
			var roll = parseRollString(splitStr[2]);

			if(roll === false)
			{
				bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Invalid save format. The expected format is \"/save <roll name> <integer>d<integer>{+,-}<integer>\", for example: \"/save magicmissile 1d4+1\""},function(nodifiedPromise){});
				return
			}

			var saveCallback = function(err,user){
				// var User = db.model('User');
				if(err)
				{
					console.log(err);
					bot.sendMessage({"chat_id" : message.chat.id , "text" : "Unknown error" },function(nodifiedPromise){});
					return
				}
				if(user === null)
				{
					bot.sendMessage({"chat_id" : message.chat.id , "text" : "Please register first by typing \"/register\" (without the quotes)"});
				}
				else
				{
					if(roll === false)
					{
						bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Invalid roll format. The expected format is \"<integer>d<integer>{+,-}<integer>\", for example: \"2d12+4\""},function(nodifiedPromise){});
					}
					else
					{
						// user = user.toObject();
						// console.log(typeof(user.rolls));
						// console.log('user before adding roll');
						// console.log(user);
						// user.rolls[key.toString()] = roll;
						// console.log('user after adding roll');
						// console.log(user);

						// var rollArray = new Array();
						// rollArray[key] = roll;
						// console.log(rollArray);

						Roll.update({"id": user.id, "name": key}, {$set: {"dice": roll.dice, "times": roll.times, "modifier": roll.modifier}}, {"upsert": true, "new": true}, function(err,result){
							console.log(result);
							console.log('recorded roll');
							bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : message.from.username + " | " + key + " | saved"},function(nodifiedPromise){});
						});
					}
				}
			};
			saveCallback.message = message;
			saveCallback.roll = roll;
			saveCallback.key = key;
			// saveCallback.rollString = splitStr[2];
			User.findOne({"id": message.from.id}, saveCallback);

			}
			// else
			// {
			// 	bot.sendMessage({"chat_id" : message.chat.id , "text" : "Unknown request. Try /help for options"});
			// }
		}
	}
}).start();<commit_msg>new feature: repeat saved roll n times<commit_after>var config = require('./config/config'),
mongoose = require('./config/mongoose'),
Bot = require('node-telegram-bot');
var db = mongoose();

var parseRollString = function(rollStr){
	console.log(rollStr);
	if(rollStr.indexOf('d') === -1){
		return false;
	}
	var splitStr = rollStr.split('d');
	// console.log(splitStr);
	var firstPart = splitStr[0];
	var secondPart = rollStr.substring(firstPart.length + 1);

	times = parseInt(firstPart);

	if(times === NaN || times <= 0 || times > 100){
		return false;
	}
	//no more than 100 due to abuse considerations
	//firstInt is a positive integer at this point
	console.log("times: " + times);

	var dice = NaN;
	var modifier = NaN;
	if(rollStr.indexOf('+') > 0 ){
		splitStr = secondPart.split('+');
		if(splitStr.length > 2){
			return false;
		}
		dice = parseInt(splitStr[0]);
		modifier = parseInt(splitStr[1]);
	} else if (rollStr.indexOf('-') > 0 ){
		splitStr = secondPart.split('-');
		if(splitStr.length > 2){
			return false;
		}
		dice = parseInt(splitStr[0]);
		modifier = -1 * parseInt(splitStr[1]);
	} else {
		dice = parseInt(secondPart);
		modifier = 0;
	}

	if(dice === NaN || modifier === NaN){
		return false;
	}

	rollValues = {
		"times" : times,
		"dice" : dice,
		"modifier" : modifier
	};

	console.log(rollValues);

	return rollValues;

};

var calculateRoll = function(roll){
	var sum = 0;
	for (var i = 0; i < roll.times; i++) {
		sum += Math.floor(Math.random() * roll.dice) + 1;
	};
	sum += roll.modifier;
	return sum;
}

var bot = new Bot({
	token: config.token
})
.on('message', function (message) {
	console.log(message);
	var User = db.model('User');
	var Roll = db.model('Roll');

	if(message.hasOwnProperty("text"))
	{
		splitStr = message.text.split(" ");

		if(splitStr.length === 1)
		{
			if(splitStr[0] === "/register")
			{
				console.log("entered /register")
				var userRegisterCallback = function(err,user){
					// var User = db.model('User');
					if(err)
					{
						console.log("error at /register, User.findOne");
						console.log(err);
						bot.sendMessage({"chat_id" : message.chat.id , "text" : err},function(nodifiedPromise){});
						return
					}
					if(user === null)
					{
						User.create({"id": message.from.id}, function(err){
							console.log("error at /register, User.findOne, User.create");
							console.log(err);
							bot.sendMessage({"chat_id" : message.chat.id , "text" : err},function(nodifiedPromise){});
							return
						});
						console.log('added new user');
						bot.sendMessage({"chat_id" : message.chat.id , "text" : "User " + message.from.username + " is registered"},function(nodifiedPromise){});
					} else {
						bot.sendMessage({"chat_id" : message.chat.id , "text" : "User " + message.from.username + " was already registered"},function(nodifiedPromise){});
					}
				};
				userRegisterCallback.message = message;
				User.findOne({"id": message.from.id}, userRegisterCallback);
			}
			else if (splitStr[0] === "/help")
			{
				bot.sendMessage({"chat_id" : message.chat.id , "text" : "/register - register to start using the bot and save your custom rolls | usage: \"/register\"\n/qroll - quick roll without saving a custom roll | usage: \"/qroll 1d4+1\"\n/save - save a custom roll | usage \"/save magicmissile 1d4+1\"\n/roll - roll a previously saved custom roll | usage: \"/roll magicmissile\""});
			}
			else if (splitStr[0] === "/show")
			{
				var userCallback = function(err,user)
				{
					if(err)
					{
						console.log(err);
						bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
						return
					}
					if(user === null)
					{
						bot.sendMessage({"chat_id" : message.chat.id , "text" : "Please register first by typing \"/register\" (without the quotes)"});
					} else
					{
					//found user, now display rolls
						var rollCallback = function(err,rolls)
						{
							if(err)
							{
								console.log(err);
								bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
								return
							}
							if(rolls === null)
							{
								bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "No saved rolls found. Please save a roll first with \"/save <roll name> <integer>d<integer>{+,-}<integer>\", for example: \"/save magicmissile 1d4+1\""},function(nodifiedPromise){});
							}
							else
							{
								console.log('found rolls');
								var msgText = 'Saved rolls for ' + message.from.username + '\n';
								rolls.forEach(function(val,ind,arr){
									var modifierSign = '+';
									if(val.modifier < 0) modifierSign = '';
									msgText += val.name + " | " + val.times + "d" + val.dice +  modifierSign + val.modifier + '\n';
								});
								bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : msgText },function(nodifiedPromise){});
							}
						}
						rollCallback.message = message;
						Roll.find({"id": message.from.id},rollCallback);
					}
				}
				userCallback.message = message;
				User.findOne({"id": message.from.id}, userCallback);
			}
		}
		else if (splitStr.length === 2)
		{
			if(splitStr[0] === "/roll")
			{
				var key = splitStr[1];
				var userCallback = function(err,user){
					if(err)
					{
						console.log(err);
						bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
						return
					}
					if(user === null)
					{
						bot.sendMessage({"chat_id" : message.chat.id , "text" : "Please register first by typing \"/register\" (without the quotes)"});
					} else
					{
						//found user, now find roll if exists
						var rollCallback = function(err,roll){
							if(err)
							{
								console.log(err);
								bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
								return
							}
							if(roll === null)
							{
								bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Unsaved custom roll. Please save first with \"/save <roll name> <integer>d<integer>{+,-}<integer>\", for example: \"/save magicmissile 1d4+1\""},function(nodifiedPromise){});
							} else
							{
								var newRoll = {};
								newRoll.times = roll.times;
								newRoll.dice = roll.dice;
								newRoll.modifier = roll.modifier;
								result = calculateRoll(newRoll);
								bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : message.from.username + " | " + key + " | " + result },function(nodifiedPromise){});
							}

						}
						rollCallback.message = message;
						rollCallback.key = key;
						Roll.findOne({"id": message.from.id , "name" : key},rollCallback);
				}
			};
			userCallback.message = message;
			userCallback.key = key;
			User.findOne({"id": message.from.id}, userCallback);
			}
			else if(splitStr[0] === "/qroll")
			{
				var roll = parseRollString(splitStr[1]);
				if(roll === false){
					bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Invalid roll format or unsaved custom roll. The expected format is \"/qroll <integer>d<integer>{+,-}<integer>\", for example: \"/qroll 2d12+4\""},function(nodifiedPromise){});
					return
				}
				var result = calculateRoll(roll);
				bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : message.from.username + " | " + splitStr[1] + " | " + result },function(nodifiedPromise){});
			}
			// else
			// {
			// 	bot.sendMessage({"chat_id" : message.chat.id , "text" : "Unknown request. Try /help for options"});
			// }
		}
		else if (splitStr.length === 3)
		{
			if(splitStr[0] === "/save")
			{
			var key = splitStr[1];
			var roll = parseRollString(splitStr[2]);

			if(roll === false)
			{
				bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Invalid save format. The expected format is \"/save <roll name> <integer>d<integer>{+,-}<integer>\", for example: \"/save magicmissile 1d4+1\""},function(nodifiedPromise){});
				return
			}

			var saveCallback = function(err,user){
				// var User = db.model('User');
				if(err)
				{
					console.log(err);
					bot.sendMessage({"chat_id" : message.chat.id , "text" : "Unknown error" },function(nodifiedPromise){});
					return
				}
				if(user === null)
				{
					bot.sendMessage({"chat_id" : message.chat.id , "text" : "Please register first by typing \"/register\" (without the quotes)"});
				}
				else
				{
					if(roll === false)
					{
						bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Invalid roll format. The expected format is \"<integer>d<integer>{+,-}<integer>\", for example: \"2d12+4\""},function(nodifiedPromise){});
					}
					else
					{
						// user = user.toObject();
						// console.log(typeof(user.rolls));
						// console.log('user before adding roll');
						// console.log(user);
						// user.rolls[key.toString()] = roll;
						// console.log('user after adding roll');
						// console.log(user);

						// var rollArray = new Array();
						// rollArray[key] = roll;
						// console.log(rollArray);

						Roll.update({"id": user.id, "name": key}, {$set: {"dice": roll.dice, "times": roll.times, "modifier": roll.modifier}}, {"upsert": true, "new": true}, function(err,result){
							console.log(result);
							console.log('recorded roll');
							bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : message.from.username + " | " + key + " | saved"},function(nodifiedPromise){});
						});
					}
				}
			};
			saveCallback.message = message;
			saveCallback.roll = roll;
			saveCallback.key = key;
			// saveCallback.rollString = splitStr[2];
			User.findOne({"id": message.from.id}, saveCallback);

			}
			else if(splitStr[0] === "/roll")
			{
				var nTimes = parseInt(splitStr[0]);
				if( nTimes > 0)
				{
					if(nTimes > 100)
					{
						bot.sendMessage({"chat_id" : message.chat.id , "text" : "I can repeat the roll to a maximum of 100 times at a time. Please try a smaller number."},function(nodifiedPromise){});
						return
					}
					var key = splitStr[1];
					var userCallback = function(err,user){
						if(err)
						{
							console.log(err);
							bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
							return
						}
						if(user === null)
						{
							bot.sendMessage({"chat_id" : message.chat.id , "text" : "Please register first by typing \"/register\" (without the quotes)"});
						} else
						{
							//found user, now find roll if exists
							var rollCallback = function(err,roll){
								if(err)
								{
									console.log(err);
									bot.sendMessage({"chat_id" : message.chat.id , "text" : err.toString()},function(nodifiedPromise){});
									return
								}
								if(roll === null)
								{
									bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : "Unsaved custom roll. Please save first with \"/save <roll name> <integer>d<integer>{+,-}<integer>\", for example: \"/save magicmissile 1d4+1\""},function(nodifiedPromise){});
								} else
								{
									var newRoll = {};
									newRoll.times = roll.times;
									newRoll.dice = roll.dice;
									newRoll.modifier = roll.modifier;
									var msgText = 'Rolling ' + key + ' ' + nTimes + ' for ' + message.from.username + '\n';
									var sum = 0;
									for (var i = 0; i < nTimes; i++) {
										var rollResult = calculateRoll(newRoll);
										msgText += rollResult + " | ";
										sum += rollResult;
									};
									msgText += '\n' + 'Sum of rolls: ' + sum;
									bot.sendMessage({"chat_id" : message.chat.id , "reply_to_message_id" : message.message_id ,"text" : msgText},function(nodifiedPromise){});
								}
							};
							rollCallback.message = message;
							rollCallback.key = key;
							Roll.findOne({"id": message.from.id , "name" : key},rollCallback);
						}
					};
					userCallback.message = message;
					userCallback.key = key;
					User.findOne({"id": message.from.id}, userCallback);
				}
				else
				{
					//TODO: wrong roll ntimes syntax
				}

			}
			// else
			// {
			// 	bot.sendMessage({"chat_id" : message.chat.id , "text" : "Unknown request. Try /help for options"});
			// }
		}
	}
}).start();<|endoftext|>


<commit_before>/*
 * Webserver -> Express
 * textbox con le carte che aggiorna la pagina dando i dati in un jumbotron
 * get request che ritorna la pagina creata con jade
 * quando viene fatta la get request viene eseguito lo script che CRAWLA
 * prendi input dalla textbox, formattali
 * passali allo script attraverso POST
 * per ogni inserzione, getta la pagina
 * https://it.magiccardmarket.eu/?mainPage=showSearchResult&searchFor=NOMECARTA
 *
 * per ogni inserzione della pagina getta la pagina del singolo item
 * ottieni il prezzo medio
 */
var RSVP = require('RSVP');
var cheerio = require('cheerio');
var request = require('request');
var querystring = require('querystring');

var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
// in latest body-parser use like bellow.
app.use(bodyParser.urlencoded({ extended: false }));

function parseData(data, callback) {
    var parsedData = data.split('\n');
    return callback(parsedData);
}

function parsePrices(i, names, body, $, callback) {

    var promise = new RSVP.Promise(function(series_callback) {
        $ = cheerio.load(body);

        //Remove half of the string to remove the double repeated price
        var tmp = $('table.availTable tr td.cell_2_1').text();
        tmp = tmp.slice(tmp.length/2);
        names.price[i] = tmp;

        console.log('Checking price: '+names.price[i]);
        resolve();
    }
}

//TODOOOO: this function is fucking long, boy
function crawl(cardname, callback) {
    //Building the url for the search page
    var searchUrl = 'https://it.magiccardmarket.eu/?mainPage=showSearchResult&searchFor=';
    var url = searchUrl + encodeURIComponent(cardname);
    var header = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.10 Safari/537.36'
    };
    var options = {
        url: url,
        headers: header
    };

    console.log('Requesting: '+url);
    request(options , function(error, response, body) {

        if (!error && response.statusCode === 200) {
            console.log('Downloaded search page');

            var names = {
                text: [],
                href: [],
                price: [],
                ok: true
            };

            var $ = cheerio.load(body);
            console.log('Parsing the page');

            //Check if there are hrefs in the search page
            var href_lenght =  $('tbody > tr > td.col_3 > a').length;
            if (href_lenght < 1) {
                console.log('No hrefs found');
                return callback({ok: false});
            }
            console.log('Found ' + href_lenght + ' hrefs');

            //For each href compare its name with the cardname, after lowercasing it
            //if they match add the name and the href to the names object
            $('tbody > tr > td.col_3 > a').each(function(i, elem) {
                if(cardname.toLowerCase() === $(elem).text().toLowerCase()) {
                    console.log('Found a cardname');
                    names.text[i] = $(elem).text();
                    names.href[i] = $(elem).attr('href');
                }
            });

            //Reset cheerio
            $ = null;

            console.log(names);

            //If hrefs have been found
            if (names.href.length < 1) {
                console.log('No links found, returning false');
                return callback({ok: false});
            }

            names.href.forEach(function(link, i) {
                //Build the url and request
                var pricesUrl = "https://it.magiccardmarket.eu" + link;
                var prices_options = {
                    url: pricesUrl,
                    headers: header
                };

                console.log(i + ' Downloading: ' + link);
                request(prices_options, function(error, response, body) {

                    if (!error && response.statusCode === 200) {
                        parsePrices(i, names, body, $, callback);
                    } else {
                        console.log('Price page request returned error: '+ response.statusCode);
                        return callback({ok: false});
                    }

                });//End of request
            });//End of foreachLink

        } else {
            console.log('Search page request returned error: ' + error + " and statusCode: "+ response.statusCode);
            return callback({ok: false});
        }
    });
}

app.set('view engine', 'jade');

app.get('/', function (req, res) {
    console.log('Got: ' + res.method + ' request from: ' +req.connection.remoteAddress);
    var results = '';
    res.render('index', {
        results: results
    });
});

app.post('/', function(req, res){
    parseData(req.body.cards, function(cards) {
        console.log(cards);
        crawl(cards[0], function(data) {
            if (data.length < 0) {
                data = {ok: false};
            }
            console.log("Rendering .jade");
            res.render('index', {
                    results: data
            });
        });
    });
});

app.listen(8080);
<commit_msg>work on parseprices<commit_after>/*
 * Webserver -> Express
 * textbox con le carte che aggiorna la pagina dando i dati in un jumbotron
 * get request che ritorna la pagina creata con jade
 * quando viene fatta la get request viene eseguito lo script che CRAWLA
 * prendi input dalla textbox, formattali
 * passali allo script attraverso POST
 * per ogni inserzione, getta la pagina
 * https://it.magiccardmarket.eu/?mainPage=showSearchResult&searchFor=NOMECARTA
 *
 * per ogni inserzione della pagina getta la pagina del singolo item
 * ottieni il prezzo medio
 */
var RSVP = require('rsvp');
var cheerio = require('cheerio');
var request = require('request');
var querystring = require('querystring');

var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
// in latest body-parser use like bellow.
app.use(bodyParser.urlencoded({ extended: false }));

function parseData(data, callback) {
    var parsedData = data.split('\n');
    return callback(parsedData);
}

function parsePrices(i, names, body, $, callback) {
        $ = cheerio.load(body);

        //Remove half of the string to remove the double repeated price
        var tmp = $('table.availTable tr td.cell_2_1').text();
        tmp = tmp.slice(tmp.length/2);
        names.price[i] = tmp;

        console.log('Checking price: '+names.price[i]);
        if(i === names.href.length-1) {
            callback(names);
        }

}

//TODOOOO: this function is fucking long, boy
function crawl(cardname, callback) {
    //Building the url for the search page
    var searchUrl = 'https://it.magiccardmarket.eu/?mainPage=showSearchResult&searchFor=';
    var url = searchUrl + encodeURIComponent(cardname);
    var header = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.10 Safari/537.36'
    };
    var options = {
        url: url,
        headers: header
    };

    console.log('Requesting: '+url);
    request(options , function(error, response, body) {

        if (!error && response.statusCode === 200) {
            console.log('Downloaded search page');

            var names = {
                text: [],
                href: [],
                price: [],
                ok: true
            };

            var $ = cheerio.load(body);
            console.log('Parsing the page');

            //Check if there are hrefs in the search page
            var href_lenght =  $('tbody > tr > td.col_3 > a').length;
            if (href_lenght < 1) {
                console.log('No hrefs found');
                return callback({ok: false});
            }
            console.log('Found ' + href_lenght + ' hrefs');

            //For each href compare its name with the cardname, after lowercasing it
            //if they match add the name and the href to the names object
            $('tbody > tr > td.col_3 > a').each(function(i, elem) {
                if(cardname.toLowerCase() === $(elem).text().toLowerCase()) {
                    console.log('Found a cardname');
                    names.text[i] = $(elem).text();
                    names.href[i] = $(elem).attr('href');
                }
            });

            //Reset cheerio
            $ = null;

            console.log(names);

            //If hrefs have been found
            if (names.href.length < 1) {
                console.log('No links found, returning false');
                return callback({ok: false});
            }

            names.href.forEach(function(link, i) {
                //Build the url and request
                var pricesUrl = "https://it.magiccardmarket.eu" + link;
                var prices_options = {
                    url: pricesUrl,
                    headers: header
                };

                console.log(i + ' Downloading: ' + link);
                request(prices_options, function(error, response, body) {

                    if (!error && response.statusCode === 200) {
                        parsePrices(i, names, body, $, callback);
                    } else {
                        console.log('Price page request returned error: '+ response.statusCode);
                        return callback({ok: false});
                    }

                });//End of request
            });//End of foreachLink

        } else {
            console.log('Search page request returned error: ' + error + " and statusCode: "+ response.statusCode);
            return callback({ok: false});
        }
    });
}

app.set('view engine', 'jade');

app.get('/', function (req, res) {
    console.log('Got: ' + res.method + ' request from: ' +req.connection.remoteAddress);
    var results = '';
    res.render('index', {
        results: results
    });
});

app.post('/', function(req, res){
    parseData(req.body.cards, function(cards) {
        console.log(cards);
        crawl(cards[0], function(data) {
            if (data.length < 0) {
                data = {ok: false};
            }
            console.log("Rendering .jade");
            res.render('index', {
                    results: data
            });
        });
    });
});

app.listen(8080);
<|endoftext|>


<commit_before>var currentlyFocusedSympalEditor = null;

$(function()
{
  shortcut.add('Ctrl+P', function() {
    $('.sympal_inline_edit_bar_publish a').click();
  });

  // Content publishing fancybox
  $('#sympal_assets #sympal_ask_confirmation input.no').live('click', function() {
    $('#sympal_assets').load($('.toggle_sympal_assets').attr('rel'));
    return false;
  });

  $('#fancy_content #sympal_ask_confirmation input.no').live('click', function() {
    $.fn.fancybox.close();
    return false;
  });

  $('#fancy_content #sympal_ask_confirmation input.yes').live('click', function() {
    $.fn.fancybox.close();
    setTimeout(function() {
      location.href = location.href;
    }, 750);
  });

  $('.sympal_inline_edit_bar_publish a').fancybox({
    'zoomSpeedIn': 300,
    'zoomSpeedOut': 300,
    'overlayShow': true,
    'hideOnContentClick': false,
  });

  // Keep track of the currently focused editor
  $('.sympal_slot_wrapper form input, .sympal_slot_wrapper form textarea').focus(function() {
    currentlyFocusedSympalEditor = $(this);
  });

  // Close all dropdowns with class="sympal_close_menu" is clicked
  $('.sympal_close_menu').live('click', function() {
    sympalCloseAllDropdowns();
  });

  $('.sympal_content_slot_error').live('mouseover', function () {
    sympalHighlightContentSlot($(this).attr('rel'));
  });

  $('#sympal_slot_errors #close').live('click', function() {
    $('#sympal_slot_errors_icon').show();
    $('#sympal_slot_errors').slideToggle();
  });

  $('#sympal_slot_errors_icon').live('click', function() {
    $('#sympal_slot_errors').slideToggle();
  });

  // Setup the sympal dropdown menu panels (assets and links)
  sympalSetupDropdownMenus();
});

function sympalHighlightContentSlot(id)
{
  $('#sympal_content_slot_' + id + ' input, #sympal_content_slot_' + id + ' textarea').focus();
}

function sympalTinyMCETriggerSave()
{
  tinyMCE.triggerSave();
}

function sympalHandleTinyMCEEvent(e)
{
  if (e.type == 'click')
  {
    currentlyFocusedSympalEditor = $('#' + tinyMCE.activeEditor.id);
  }
}

function sympalInsertIntoCurrentEditor(text)
{
  if (currentlyFocusedSympalEditor === null)
  {
    currentlyFocusedSympalEditor = $('.sympal_content_slot .editor textarea:first');
  }

  if (currentlyFocusedSympalEditor !== null)
  {
    // Check if is tinymce
    if (currentlyFocusedSympalEditor.parents('span').hasClass('sympal_tiny_mce_content_slot_editor_form'))
    {
      tinyMCE.execInstanceCommand(currentlyFocusedSympalEditor.attr('id'), 'mceInsertContent', false, text);
    } else {
      currentlyFocusedSympalEditor.insertAtCaret(text);
    }
  }
}

$.fn.insertAtCaret = function (myValue) {
  return this.each(function() {
    //IE support
    if (document.selection) {
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    //MOZILLA/NETSCAPE support
    else if (this.selectionStart || this.selectionStart == '0')
    {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  });
};

function sympalSetupDropdownMenu(id, control)
{
  $(id).hide();

  $(control).click(function() {
    if ($(this).attr('rel'))
    {
      if (!$(id).html())
      {
        $(id).load($(this).attr('rel'), {
          success: function() {
            $(id).slideToggle('fast');
            sympalCloseAllDropdowns();
          }
        });
      } else {
        $(id).slideToggle('fast');
        sympalCloseAllDropdowns();
      }
    } else {
      $(id).slideToggle('fast');
      sympalCloseAllDropdowns();
    }
  });
}

function sympalCloseAllDropdowns()
{
  $('#sympal_editor').hide();
  $('#sympal_assets').hide();
  $('#sympal_links').hide();
  $('#sympal_objects').hide();
}

function sympalSetupDropdownMenus()
{
  sympalSetupDropdownMenu('#sympal_assets', '.toggle_sympal_assets');
  sympalSetupDropdownMenu('#sympal_links', '.toggle_sympal_links');
  sympalSetupDropdownMenu('#sympal_objects', '.toggle_sympal_objects');
}<commit_msg>[1.4][sfSympalPlugin][1.0] Fixing publish javascript for new 1.3 version of fancybox.<commit_after>var currentlyFocusedSympalEditor = null;

$(function()
{
  shortcut.add('Ctrl+P', function() {
    $('.sympal_inline_edit_bar_publish a').click();
  });

  // Content publishing fancybox
  $('#sympal_assets #sympal_ask_confirmation input.no').live('click', function() {
    $('#sympal_assets').load($('.toggle_sympal_assets').attr('rel'));
    return false;
  });

  $('#fancybox-wrap #sympal_ask_confirmation input.no').live('click', function() {
    $.fancybox.close();
    return false;
  });

  $('#fancybox-wrap #sympal_ask_confirmation input.yes').live('click', function() {
    $.fancybox.close();
    setTimeout(function() {
      location.href = location.href;
    }, 750);
  });

  $('.sympal_inline_edit_bar_publish a').fancybox({
    'zoomSpeedIn': 300,
    'zoomSpeedOut': 300,
    'overlayShow': true,
    'hideOnContentClick': false,
  });

  // Keep track of the currently focused editor
  $('.sympal_slot_wrapper form input, .sympal_slot_wrapper form textarea').focus(function() {
    currentlyFocusedSympalEditor = $(this);
  });

  // Close all dropdowns with class="sympal_close_menu" is clicked
  $('.sympal_close_menu').live('click', function() {
    sympalCloseAllDropdowns();
  });

  $('.sympal_content_slot_error').live('mouseover', function () {
    sympalHighlightContentSlot($(this).attr('rel'));
  });

  $('#sympal_slot_errors #close').live('click', function() {
    $('#sympal_slot_errors_icon').show();
    $('#sympal_slot_errors').slideToggle();
  });

  $('#sympal_slot_errors_icon').live('click', function() {
    $('#sympal_slot_errors').slideToggle();
  });

  // Setup the sympal dropdown menu panels (assets and links)
  sympalSetupDropdownMenus();
});

function sympalHighlightContentSlot(id)
{
  $('#sympal_content_slot_' + id + ' input, #sympal_content_slot_' + id + ' textarea').focus();
}

function sympalTinyMCETriggerSave()
{
  tinyMCE.triggerSave();
}

function sympalHandleTinyMCEEvent(e)
{
  if (e.type == 'click')
  {
    currentlyFocusedSympalEditor = $('#' + tinyMCE.activeEditor.id);
  }
}

function sympalInsertIntoCurrentEditor(text)
{
  if (currentlyFocusedSympalEditor === null)
  {
    currentlyFocusedSympalEditor = $('.sympal_content_slot .editor textarea:first');
  }

  if (currentlyFocusedSympalEditor !== null)
  {
    // Check if is tinymce
    if (currentlyFocusedSympalEditor.parents('span').hasClass('sympal_tiny_mce_content_slot_editor_form'))
    {
      tinyMCE.execInstanceCommand(currentlyFocusedSympalEditor.attr('id'), 'mceInsertContent', false, text);
    } else {
      currentlyFocusedSympalEditor.insertAtCaret(text);
    }
  }
}

$.fn.insertAtCaret = function (myValue) {
  return this.each(function() {
    //IE support
    if (document.selection) {
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    //MOZILLA/NETSCAPE support
    else if (this.selectionStart || this.selectionStart == '0')
    {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  });
};

function sympalSetupDropdownMenu(id, control)
{
  $(id).hide();

  $(control).click(function() {
    if ($(this).attr('rel'))
    {
      if (!$(id).html())
      {
        $(id).load($(this).attr('rel'), {
          success: function() {
            $(id).slideToggle('fast');
            sympalCloseAllDropdowns();
          }
        });
      } else {
        $(id).slideToggle('fast');
        sympalCloseAllDropdowns();
      }
    } else {
      $(id).slideToggle('fast');
      sympalCloseAllDropdowns();
    }
  });
}

function sympalCloseAllDropdowns()
{
  $('#sympal_editor').hide();
  $('#sympal_assets').hide();
  $('#sympal_links').hide();
  $('#sympal_objects').hide();
}

function sympalSetupDropdownMenus()
{
  sympalSetupDropdownMenu('#sympal_assets', '.toggle_sympal_assets');
  sympalSetupDropdownMenu('#sympal_links', '.toggle_sympal_links');
  sympalSetupDropdownMenu('#sympal_objects', '.toggle_sympal_objects');
}<|endoftext|>


<commit_before>var express = require("express"),
	app = express(),
	http = require("http").Server(app),
	io = require("socket.io")(http),
	     require("./index.js");

var ipAddress = process.env.OPENSHIFT_INTERNAL_IP || process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_INTERNAL_IP || process.env.OPENSHIFT_NODEJS_PORT || 3030;

app.use(express.static("static"));

io.on("connection", function(socket) {
	console.log("a user connnected");
	socket.on("disconnect", function() {
		console.log("user disconnected");
	});

	socket.on("chat message", function(msg) {
		console.log("message " + msg);
		io.emit("chat message", {m: msg.m, u: msg.u});
	});
});

var port;

if(process.argv[2]) {port = process.argv[2]} else {port = 3000}

http.listen(port, ipAddress, function() {
	console.log("chat listening on port " + port + ".");
});
<commit_msg>cleared up a few things£<commit_after>var express = require("express"),
	app = express(),
	http = require("http").Server(app),
	io = require("socket.io")(http),

var ipAddress = process.env.OPENSHIFT_INTERNAL_IP || process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_INTERNAL_IP || process.env.OPENSHIFT_NODEJS_PORT || process.argv[2] || 3030;

app.use(express.static("static"));

io.on("connection", function(socket) {
	console.log("a user connnected");
	socket.on("disconnect", function() {
		console.log("user disconnected");
	});

	socket.on("chat message", function(msg) {
		console.log("message " + msg);
		io.emit("chat message", {m: msg.m, u: msg.u});
	});
});

http.listen(port, ipAddress, function() {
	console.log("chat listening on port " + port + ".");
});
<|endoftext|>


<commit_before>/**
Copyright © 2015 Luis Sieira Garcia

This file is part of Planète.

    Planète is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Planète is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>
**/
var core = require('_'),
    logger = core.logger,
    config = core.config;

// Consider if this could be placed on the core code
function shutdown(event, logger) {
  return function() {
    logger('Gracefully exiting on \''+ event +'\' event');
    core.close(function () {
      process.exit(0);
    });
  }
}

process.on('SIGTERM', shutdown('SIGTERM', logger.info));
process.on('SIGINT', shutdown('SIGINT', logger.info));
process.on('uncaughtException', shutdown('uncaughtException', logger.error));

core.init(function(err) {
  if(err) {
    logger.error('Error loading core: ' + err);
  }
  if (!err) {
    logger.info('Planète\'s core bootstraped, configured in %s mode', config.NODE_ENV);
  }
});
<commit_msg>print stacktrace on uncaughtException<commit_after>/**
Copyright © 2015 Luis Sieira Garcia

This file is part of Planète.

    Planète is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Planète is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>
**/
var core = require('_'),
    logger = core.logger,
    config = core.config;

// Consider if this could be placed on the core code
function shutdown(event, logger) {
  return function(err) {
    logger('Gracefully exiting on \''+ event +'\' event');
    if(err) { logger.error(err.stack); }
    core.close(function () {
      process.exit(0);
    });
  }
}

process.on('SIGTERM', shutdown('SIGTERM', logger.info));
process.on('SIGINT', shutdown('SIGINT', logger.info));
process.on('uncaughtException', shutdown('uncaughtException', logger.error));

core.init(function(err) {
  if(err) {
    logger.error('Error loading core: ' + err);
  }
  if (!err) {
    logger.info('Planète\'s core bootstraped, configured in %s mode', config.NODE_ENV);
  }
});
<|endoftext|>


<commit_before>'use strict';

require('./lib/verdoux/predicates.js');
var accounting = require('accounting')
  , _ = require('underscore')
  , util = require('util')
  , MtGox = require('mtgox')
  , ElapsedTime = require('./lib/verdoux/elapsedTime.js')
  , GameLoop = require('./lib/verdoux/gameloop.js')
  , PubSub = require('./lib/verdoux/pubsub.js')
  , Task = require('./lib/koufax/task.js');

function Bernie(options) {
  var that = PubSub.create();

  Object.defineProperty(that, 'options', {get : function() {return _options;},enumerable : true});

  that.start = function() {gameLoop.start(); return that;};
  that.drone = Drone.create();

  function onGameLoopTick() {that.drone.performWork();};

  var gameLoop = GameLoop.create(onGameLoopTick);
  var _options = options;

  return that;
};
Bernie.create = function(options) {return new Bernie(options);};
module.exports = Bernie;

function Drone() {
  var that = PubSub.create();

  that.performWork = function(){
    if (notExisty(oneSecondTimer))  {
      /*
      oneSecondTimer = setInterval(retrieveMarketData, 10 * 1000);
      retrieveMarketData();
      */
      if (notExisty(retrieveMarketDataTask)) {
        retrieveMarketDataTask = Task.create('market', retrieveMarketData);
        retrieveMarketDataTask.on(Task.Events.Done, onMarketDone);
        retrieveMarketDataTask.on(Task.Events.MarkedCompleted, onMarketCompleted);
      }

      oneSecondTimer = setInterval(onTrigger, 10 * 1000);
      onTrigger();
    }
  };

  function onTrigger() {
    if (retrieveMarketDataTask.isReady()) {
      retrieveMarketDataTask.begin();
    }
  };

  function onMarketDone(result) {
    logResult({market:result.value.market}, result.value.timestamp);
    retrieveMarketDataTask.markCompleted();
  };

  function onMarketCompleted() {
    retrieveMarketDataTask.reset();
  };

  function retrieveMarketData(done) {
    var timestamp = Date.now();
    gox.market('BTCUSD', function(err, market) {
      done({market:market, timestamp:timestamp});
      previousLast = market.last;
    });
  };

  function retrieveDepthData(done) {
    var timestamp = Date.now();
    gox.depth('BTCUSD', function(err, depth) {
      done(depth);
    });
  };

  function onDepthDone(result) {
    console.log('#' + result.task.name + ': ' + util.inspect(result.value.bids.length));
    retrieveDepthDataTask.markCompleted();
  };

  function onDepthCompleted() {retrieveDepthDataTask.reset();};

  function logResult(result, timestamp) {
    var market = result.market;
    var now = Date.now();
    var elapsed = now - timestamp;
    var position = btc * market.last;
    var delta = market.last - previousLast;
    var positionDelta = position - originalPosition;
    var positionDeltaPercent = (positionDelta / originalPosition) * 100;

    if (delta !== 0) {
      var message = new Date().toString() + '(' + elapsed + 'ms)';
      message += ' : ' + accounting.formatNumber(market.last, 4);
      message += ' [' + accounting.formatNumber(market.volume, 2, '') + ']';

      if (existy(previousLast)) {
        var deltaPercent = (delta / market.last) * 100;
        message += '\t[' + accounting.formatNumber(position, 4, '') + ']';
        if (deltaPercent >= 0) {message += '(+';}
        else {message += '('}
        message += accounting.formatNumber(deltaPercent, 2) + '%)\t';
      }
      else {
        message += '\t[' + accounting.formatNumber(position, 4, '') + ']';
        message += '[' + accounting.formatNumber(originalPosition, 4, '') + ']';
      }
      if (positionDeltaPercent > 0) {message += '+';}
      message += '\t(' + accounting.formatNumber(positionDeltaPercent, 2) + '%)';
      console.log(message);
    }
  }

  var btc = 331.0578
    , originalPrice = 912.575
    , gox = new MtGox()
    , oneSecondTimer = null
    , originalPosition = (btc * originalPrice)
    , previousLast = null
    , retrieveMarketDataTask;

  return that;
}
Drone.create = function() {return new Drone();};<commit_msg>Make logging output nicer<commit_after>'use strict';

require('./lib/verdoux/predicates.js');
var accounting = require('accounting')
  , _ = require('underscore')
  , util = require('util')
  , MtGox = require('mtgox')
  , ElapsedTime = require('./lib/verdoux/elapsedTime.js')
  , GameLoop = require('./lib/verdoux/gameloop.js')
  , PubSub = require('./lib/verdoux/pubsub.js')
  , Task = require('./lib/koufax/task.js');

function Bernie(options) {
  var that = PubSub.create();

  Object.defineProperty(that, 'options', {get : function() {return _options;},enumerable : true});

  that.start = function() {gameLoop.start(); return that;};
  that.drone = Drone.create();

  function onGameLoopTick() {that.drone.performWork();};

  var gameLoop = GameLoop.create(onGameLoopTick);
  var _options = options;

  return that;
};
Bernie.create = function(options) {return new Bernie(options);};
module.exports = Bernie;

function Drone() {
  var that = PubSub.create();

  that.performWork = function(){
    if (notExisty(oneSecondTimer))  {
      /*
      oneSecondTimer = setInterval(retrieveMarketData, 10 * 1000);
      retrieveMarketData();
      */
      if (notExisty(retrieveMarketDataTask)) {
        retrieveMarketDataTask = Task.create('market', retrieveMarketData);
        retrieveMarketDataTask.on(Task.Events.Done, onMarketDone);
        retrieveMarketDataTask.on(Task.Events.MarkedCompleted, onMarketCompleted);
      }

      oneSecondTimer = setInterval(onTrigger, 10 * 1000);
      onTrigger();
    }
  };

  function onTrigger() {
    if (retrieveMarketDataTask.isReady()) {
      retrieveMarketDataTask.begin();
    }
  };

  function onMarketDone(result) {
    logResult({market:result.value.market}, result.value.timestamp);
    retrieveMarketDataTask.markCompleted();
  };

  function onMarketCompleted() {
    retrieveMarketDataTask.reset();
  };

  function retrieveMarketData(done) {
    var timestamp = Date.now();
    gox.market('BTCUSD', function(err, market) {
      done({market:market, timestamp:timestamp});
      previousLast = market.last;
    });
  };

  function retrieveDepthData(done) {
    var timestamp = Date.now();
    gox.depth('BTCUSD', function(err, depth) {
      done(depth);
    });
  };

  function onDepthDone(result) {
    console.log('#' + result.task.name + ': ' + util.inspect(result.value.bids.length));
    retrieveDepthDataTask.markCompleted();
  };

  function onDepthCompleted() {retrieveDepthDataTask.reset();};

  function logResult(result, timestamp) {
    var market = result.market;
    var now = Date.now();
    var elapsed = now - timestamp;
    var position = btc * market.last;
    var delta = market.last - previousLast;
    var positionDelta = position - originalPosition;
    var positionDeltaPercent = (positionDelta / originalPosition) * 100;

    if (delta !== 0) {
      var message = new Date().toString() + '(' + elapsed + 'ms)';
      message += ' : ' + accounting.formatNumber(market.last, 4);
      message += ' [' + accounting.formatNumber(market.volume, 2, '') + ']';

      if (existy(previousLast)) {
        var deltaPercent = (delta / market.last) * 100;
        message += '\t[' + accounting.formatNumber(position, 4, '') + ']';
        if (deltaPercent >= 0) {message += '(+';}
        else {message += '('}
        message += accounting.formatNumber(deltaPercent, 4) + '%)\t';
      }
      else {
        message += '\t[' + accounting.formatNumber(position, 4, '') + ']';
        message += '[' + accounting.formatNumber(originalPosition, 4, '') + ']';
      }
      if (positionDeltaPercent > 0) {message += '\t(+';}
      else {message += '\t('}
      message += accounting.formatNumber(positionDeltaPercent, 2) + '%)';
      console.log(message);
    }
  }

  var btc = 331.0578
    , originalPrice = 912.575
    , gox = new MtGox()
    , oneSecondTimer = null
    , originalPosition = (btc * originalPrice)
    , previousLast = null
    , retrieveMarketDataTask;

  return that;
}
Drone.create = function() {return new Drone();};<|endoftext|>


<commit_before>'use strict';

/**
 * module dependencies
 */
global.Promise = require('bluebird');
var co = require('co');
var pathFn = require('path');
var fs = require('fs');
var _ = require('lodash');
var send = require('koa-send');
var glob = require('glob');
var swig = require('swig');
var browserify = require('browserify');
var stringify = require('stringify');
var Router = require('impress-router');

/**
 * set swig view cache
 */
swig.setDefaults({
  cache: process.env.NODE_ENV === 'production' && 'memory'
});

/**
 * do exports
 */
exports = module.exports = Predator;
var less = exports.less = require('./less');

/**
 * Preadtor class def
 *
 * options
 *   - home: 主目录
 *   - app: koa app
 *   - buildDir: build static files
 */
function Predator(options) {
  if (!(this instanceof Predator)) {
    return new Predator(options);
  }

  if (!options || !options.app) {
    throw new Error('options.app is required');
  }

  // 主目录
  this.home = pathFn.resolve(options.home || '.');

  // app
  this.app = options.app;

  // build 目录
  this.buildDir = pathFn.resolve(options.buildDir || './public');
}

/**
 * serve static file when dev
 *
 * @example
 *
 * router.use('/:component/img', predator.static());
 */
Predator.prototype.static = function() {
  var self = this;
  var root = pathFn.join(this.home, 'app');

  return function* predatorStatic(next) {

    // koa-send
    var filePath = yield send(this, this.originalPath, {
      root: root
    });

    // 304 在 dev 环境下也是更快的
    if (this.fresh) {
      this.status = 304;
      this.body = null;
    }
  };
};

/**
 * load all router
 */
Predator.prototype.loadAllRouter = function() {
  var self = this;

  var routers = glob.sync('app/*/index.js', {
    cwd: this.home
  });

  routers.forEach(function(item) {
    var router = require(self.home + '/' + item);
    self.app.use(router);
  });
};

/**
 * less生成器
 */
Predator.prototype.renderLessAsync = co.wrap(function*(file) {
  var env = process.env.NODE_ENV;
  var paths = [
    '.',
    pathFn.join(this.home, 'app')
  ];

  if (env === 'production') {
    return yield less.renderFileAsync(file, {
      paths: paths
    });
  } else {
    return yield less.renderFileAsync(file, {
      sourceMap: {
        sourceMapFileInline: true
      },
      paths: paths
    });
  }
});

/**
 * for js middleware use
 */

Predator.prototype.createBrowserify = function(file) {
  if (!this.jsGlobals) {
    this.jsGlobals = require(this.home + '/' + 'app/global/js/main/index.json');
  }

  // when not production, enable source maps
  var env = process.env.NODE_ENV;

  // b as ret
  var b;

  // global
  if (file === this.home + '/app/global/js/main/index.js') {
    b = browserify({
      basedir: pathFn.dirname(file),
      debug: env !== 'production'
    });

    this.jsGlobals.forEach(function(item) {
      b.require(item.require, {
        expose: item.expose
      });
    });
  } else {

    // normal js
    b = browserify(file, {
      basedir: pathFn.dirname(file),
      debug: env !== 'production'
    });

    this.jsGlobals.forEach(function(item) {
      b.external(item.expose);
    });
  }

  // commom operation
  b.transform(stringify({
    extensions: ['.html', '.swig', 'tpl', '.txt']
  }));

  // ret
  return b;
};

/**
 * use for js dev env
 */
Predator.prototype.createBrowserifyStream = function(file) {
  return this.createBrowserify(file).bundle();
};

/**
 * development assets manager
 */
Predator.prototype.startAssetsManager = function() {
  var predator = this;
  var home = this.home;

  // router
  var router = Router();
  this.app.use(router);

  // debug
  var debugLess = require('debug')('predator:less');
  var debugBrowserify = require('debug')('predator:browserify');

  /**
   * img fonts assets
   */
  router.use('/:component/fonts', predator.static());
  router.use('/:component/assets', predator.static());
  router.use('/:component/img', predator.static());

  /**
   * less
   *
   * only `css/main/*.css` should be handled via less
   */
  router.get('/:component/css/:css+.css', function*(next) {
    if (_.startsWith(this.params.css, 'main/')) {
      var appHome = pathFn.join(home, 'app');
      var parsed = pathFn.parse(this.originalPath);
      var lessFile = pathFn.join(appHome, parsed.dir, parsed.name + '.less');
      debugLess('%s -> %s', this.path, lessFile);

      this.type = 'css';
      this.body = yield predator.renderLessAsync(lessFile);
    } else {
      yield * next;
    }
  }, predator.static());

  /**
   * js
   *
   * only `js/main/*.js` should be handled via browserify
   */
  router.get('/:component/js/:js+.js', function*(next) {
    if (_.startsWith(this.params.js, 'main/')) {
      var appHome = pathFn.join(home, 'app');
      var parsed = pathFn.parse(this.originalPath);
      var jsFile = pathFn.join(appHome, parsed.dir, parsed.name + parsed.ext);
      debugBrowserify('%s -> %s', this.path, jsFile);

      this.type = 'js';
      this.body = predator.createBrowserifyStream(jsFile); // stream
    } else {
      yield * next;
    }
  }, predator.static());
};

/**
 * get render for context
 *
 * @example
 * Predator.getRender(__dirname)
 */
Predator.getRender = function(dir) {
  var env = process.env.NODE_ENV;
  var base;

  // decide view base
  if (env === 'production') {
    base = pathFn.join(dir, 'view_build');
  } else {
    base = pathFn.join(dir, 'view');
  }

  // render
  return function redner(view, locals) {
    return new Promise(function(resolve, reject) {

      // fix, 在js 中 yield render('../../global/view/error') case
      if (env === 'production') {
        view = view.replace(/\/view(?=\/)/g, '/view_build');
      }

      view = pathFn.join(base, view);
      if (!pathFn.extname(view)) {
        view += '.swig';
      }

      // renderFile
      swig.renderFile(view, locals, function(err, res) {
        if (err) {
          return reject(err);
        }
        resolve(res);
      });
    });
  };
};

/**
 * load build actions
 */
var build = require('./build');
_.assign(Predator.prototype, build);<commit_msg>predator: some midifications<commit_after>'use strict';

/**
 * module dependencies
 */
global.Promise = require('bluebird');
var co = require('co');
var pathFn = require('path');
var fs = require('fs');
var _ = require('lodash');
var send = require('koa-send');
var glob = require('glob');
var swig = require('swig');
var browserify = require('browserify');
var stringify = require('stringify');
var Router = require('impress-router');

/**
 * set swig view cache
 */
swig.setDefaults({
  cache: process.env.NODE_ENV === 'production' && 'memory'
});

/**
 * do exports
 */
exports = module.exports = Predator;
var less = exports.less = require('./less');

/**
 * Preadtor class def
 *
 * options
 *   - home: 主目录
 *   - app: koa app
 *   - buildDir: build static files
 */
function Predator(options) {
  if (!(this instanceof Predator)) {
    return new Predator(options);
  }

  if (!options || !options.app) {
    throw new Error('options.app is required');
  }

  // 主目录
  this.home = pathFn.resolve(options.home || '.');

  // app
  this.app = options.app;

  // build 目录
  this.buildDir = pathFn.resolve(options.buildDir || './public');
}

/**
 * serve static file when dev
 *
 * @example
 *
 * router.use('/:component/img', predator.static());
 */
Predator.prototype.static = function() {
  var self = this;
  var root = pathFn.join(this.home, 'app');

  return function* predatorStatic(next) {

    // koa-send
    var filePath = yield send(this, this.originalPath, {
      root: root
    });

    // 304 在 dev 环境下也是更快的
    if (this.fresh) {
      this.status = 304;
      this.body = null;
    }
  };
};

/**
 * load all router
 */
Predator.prototype.loadAllRouter = function() {
  var self = this;

  var routers = glob.sync('app/*/index.js', {
    cwd: this.home
  });

  routers.forEach(function(item) {
    var router = require(self.home + '/' + item);
    self.app.use(router);
  });
};

/**
 * less生成器
 */
Predator.prototype.renderLessAsync = co.wrap(function*(file) {
  var env = process.env.NODE_ENV;
  var paths = [
    '.',
    pathFn.join(this.home, 'app')
  ];

  if (env === 'production') {
    return yield less.renderFileAsync(file, {
      paths: paths
    });
  } else {
    return yield less.renderFileAsync(file, {
      sourceMap: {
        sourceMapFileInline: true
      },
      paths: paths
    });
  }
});

/**
 * for js middleware use
 */

Predator.prototype.createBrowserify = function(file) {
  if (!this.jsGlobals) {
    this.jsGlobals = require(this.home + '/app/global/js/main/index.json');
  }

  // when not production, enable source maps
  var env = process.env.NODE_ENV;

  // b as ret
  var b;

  // global
  if (file === this.home + '/app/global/js/main/index.js') {
    b = browserify({
      basedir: pathFn.dirname(file),
      debug: env !== 'production'
    });

    this.jsGlobals.forEach(function(item) {
      b.require(item.require, {
        expose: item.expose
      });
    });
  } else {

    // normal js
    b = browserify(file, {
      basedir: pathFn.dirname(file),
      debug: env !== 'production'
    });

    this.jsGlobals.forEach(function(item) {
      b.external(item.expose);
    });
  }

  // commom operation
  b.transform(stringify({
    extensions: ['.html', '.swig', '.tpl', '.txt']
  }));

  // ret
  return b;
};

/**
 * use for js dev env
 */
Predator.prototype.createBrowserifyStream = function(file) {
  return this.createBrowserify(file).bundle();
};

/**
 * development assets manager
 */
Predator.prototype.startAssetsManager = function() {
  var predator = this;
  var home = this.home;

  // router
  var router = Router();
  this.app.use(router);

  // debug
  var debugLess = require('debug')('predator:less');
  var debugBrowserify = require('debug')('predator:browserify');

  /**
   * img fonts assets
   */
  router.use('/:component/fonts', predator.static());
  router.use('/:component/assets', predator.static());
  router.use('/:component/img', predator.static());

  /**
   * less
   *
   * only `css/main/*.css` should be handled via less
   */
  router.get('/:component/css/:css+.css', function*(next) {
    if (_.startsWith(this.params.css, 'main/')) {
      var appHome = pathFn.join(home, 'app');
      var parsed = pathFn.parse(this.originalPath);
      var lessFile = pathFn.join(appHome, parsed.dir, parsed.name + '.less');
      debugLess('%s -> %s', this.path, lessFile);

      this.type = 'css';
      this.body = yield predator.renderLessAsync(lessFile);
    } else {
      yield * next;
    }
  }, predator.static());

  /**
   * js
   *
   * only `js/main/*.js` should be handled via browserify
   */
  router.get('/:component/js/:js+.js', function*(next) {
    if (_.startsWith(this.params.js, 'main/')) {
      var appHome = pathFn.join(home, 'app');
      var parsed = pathFn.parse(this.originalPath);
      var jsFile = pathFn.join(appHome, parsed.dir, parsed.name + parsed.ext);
      debugBrowserify('%s -> %s', this.path, jsFile);

      this.type = 'js';
      this.body = predator.createBrowserifyStream(jsFile); // stream
    } else {
      yield * next;
    }
  }, predator.static());
};

/**
 * get render for context
 *
 * @example
 * Predator.getRender(__dirname)
 */
Predator.getRender = function(dir) {
  var env = process.env.NODE_ENV;
  var base;

  // decide view base
  if (env === 'production') {
    base = pathFn.join(dir, 'view_build');
  } else {
    base = pathFn.join(dir, 'view');
  }

  // render
  return function redner(view, locals) {
    return new Promise(function(resolve, reject) {

      // fix, 在js 中 yield render('../../global/view/error') case
      if (env === 'production') {
        view = view.replace(/\/view(?=\/)/g, '/view_build');
      }

      view = pathFn.join(base, view);
      if (!pathFn.extname(view)) {
        view += '.swig';
      }

      // renderFile
      swig.renderFile(view, locals, function(err, res) {
        if (err) {
          return reject(err);
        }
        resolve(res);
      });
    });
  };
};

/**
 * load build actions
 */
var build = require('./build');
_.assign(Predator.prototype, build);<|endoftext|>


<commit_before>'use strict'

var Raven = require('raven')

exports.register = function (server, options, next) {
  Raven.config(options.dsn, options.client)
  server.expose('client', Raven)
  server.on('request-error', function (request, err) {
    var baseUrl = request.info.uri ||
      request.info.host && `${server.info.protocol}://${request.info.host}` ||
      server.info.uri

    Raven.captureException(err, {
      request: {
        method: request.method,
        query_string: request.query,
        headers: request.headers,
        cookies: request.state,
        url: baseUrl + request.path
      },
      extra: {
        timestamp: request.info.received,
        id: request.id,
        remoteAddress: request.info.remoteAddress
      },
      tags: options.tags
    })
  })

  next()
}

exports.register.attributes = {
  pkg: require('./package.json')
}
<commit_msg>coverage: ignore server.info.uri fallback, too hard to test<commit_after>'use strict'

var Raven = require('raven')

exports.register = function (server, options, next) {
  Raven.config(options.dsn, options.client)
  server.expose('client', Raven)
  server.on('request-error', function (request, err) {
    var baseUrl = request.info.uri ||
      request.info.host && `${server.info.protocol}://${request.info.host}` ||
      /* istanbul ignore next */
      server.info.uri

    Raven.captureException(err, {
      request: {
        method: request.method,
        query_string: request.query,
        headers: request.headers,
        cookies: request.state,
        url: baseUrl + request.path
      },
      extra: {
        timestamp: request.info.received,
        id: request.id,
        remoteAddress: request.info.remoteAddress
      },
      tags: options.tags
    })
  })

  next()
}

exports.register.attributes = {
  pkg: require('./package.json')
}
<|endoftext|>


<commit_before>import test from 'ava';
import Tree from '../';

test('should delete a single key', function (t) {
  var tree = new Tree();
  tree.insert(1);
  tree.delete(1);
  t.true(tree.isEmpty());
});

/**
 *       _4_                       _2_
 *      /   \                     /   \
 *     2     6  -> delete(6) ->  1     4
 *    / \                             /
 *   1   3                           3
 */
test('should correctly balance the left left case', function (t) {
  var tree = new Tree();
  tree.insert(4);
  tree.insert(2);
  tree.insert(6);
  tree.insert(3);
  tree.insert(5);
  tree.insert(1);
  tree.insert(7);
  tree.delete(7);
  tree.delete(5);
  tree.delete(6);
  t.is(tree._root.key, 2);
  t.is(tree._root.left.key, 1);
  t.is(tree._root.right.key, 4);
  t.is(tree._root.right.left.key, 3);
});

/**
 *       _4_                       _6_
 *      /   \                     /   \
 *     2     6  -> delete(2) ->  4     7
 *          / \                   \
 *         5   7                  5
 */
test('should correctly balance the right right case', function (t) {
  var tree = new Tree();
  tree.insert(4);
  tree.insert(2);
  tree.insert(6);
  tree.insert(3);
  tree.insert(5);
  tree.insert(1);
  tree.insert(7);
  tree.delete(1);
  tree.delete(3);
  tree.delete(2);
  t.is(tree._root.key, 6);
  t.is(tree._root.left.key, 4);
  t.is(tree._root.left.right.key, 5);
  t.is(tree._root.right.key, 7);
});

/**
 *       _6_                       _4_
 *      /   \                     /   \
 *     2     7  -> delete(8) ->  2     6
 *    / \     \                 / \   / \
 *   1   4     8               1   3 5   7
 *      / \
 *     3   5
 */
test('should correctly balance the left right case', function (t) {
  var tree = new Tree();
  tree.insert(6);
  tree.insert(2);
  tree.insert(7);
  tree.insert(1);
  tree.insert(8);
  tree.insert(4);
  tree.insert(3);
  tree.insert(5);
  tree.delete(8);
  t.is(tree._root.key, 4);
  t.is(tree._root.left.key, 2);
  t.is(tree._root.left.left.key, 1);
  t.is(tree._root.left.right.key, 3);
  t.is(tree._root.right.key, 6);
  t.is(tree._root.right.left.key, 5);
  t.is(tree._root.right.right.key, 7);
});

/**
 *       _3_                       _5_
 *      /   \                     /   \
 *     2     7  -> delete(1) ->  3     7
 *    /     / \                 / \   / \
 *   1     5   8               2   4 6   8
 *        / \
 *       4   6
 */
test('should correctly balance the right left case', function (t) {
  var tree = new Tree();
  tree.insert(3);
  tree.insert(2);
  tree.insert(7);
  tree.insert(1);
  tree.insert(8);
  tree.insert(5);
  tree.insert(4);
  tree.insert(6);
  tree.delete(1);
  t.is(tree._root.key, 5);
  t.is(tree._root.left.key, 3);
  t.is(tree._root.left.left.key, 2);
  t.is(tree._root.left.right.key, 4);
  t.is(tree._root.right.key, 7);
  t.is(tree._root.right.left.key, 6);
  t.is(tree._root.right.right.key, 8);
});
<commit_msg>Add delete null root case<commit_after>import test from 'ava';
import Tree from '../';

test('should not change the size of a tree with no root', function (t) {
  var tree = new Tree();
  tree.delete(1);
  t.is(tree.size(), 0);
});

test('should delete a single key', function (t) {
  var tree = new Tree();
  tree.insert(1);
  tree.delete(1);
  t.true(tree.isEmpty());
});

/**
 *       _4_                       _2_
 *      /   \                     /   \
 *     2     6  -> delete(6) ->  1     4
 *    / \                             /
 *   1   3                           3
 */
test('should correctly balance the left left case', function (t) {
  var tree = new Tree();
  tree.insert(4);
  tree.insert(2);
  tree.insert(6);
  tree.insert(3);
  tree.insert(5);
  tree.insert(1);
  tree.insert(7);
  tree.delete(7);
  tree.delete(5);
  tree.delete(6);
  t.is(tree._root.key, 2);
  t.is(tree._root.left.key, 1);
  t.is(tree._root.right.key, 4);
  t.is(tree._root.right.left.key, 3);
});

/**
 *       _4_                       _6_
 *      /   \                     /   \
 *     2     6  -> delete(2) ->  4     7
 *          / \                   \
 *         5   7                  5
 */
test('should correctly balance the right right case', function (t) {
  var tree = new Tree();
  tree.insert(4);
  tree.insert(2);
  tree.insert(6);
  tree.insert(3);
  tree.insert(5);
  tree.insert(1);
  tree.insert(7);
  tree.delete(1);
  tree.delete(3);
  tree.delete(2);
  t.is(tree._root.key, 6);
  t.is(tree._root.left.key, 4);
  t.is(tree._root.left.right.key, 5);
  t.is(tree._root.right.key, 7);
});

/**
 *       _6_                       _4_
 *      /   \                     /   \
 *     2     7  -> delete(8) ->  2     6
 *    / \     \                 / \   / \
 *   1   4     8               1   3 5   7
 *      / \
 *     3   5
 */
test('should correctly balance the left right case', function (t) {
  var tree = new Tree();
  tree.insert(6);
  tree.insert(2);
  tree.insert(7);
  tree.insert(1);
  tree.insert(8);
  tree.insert(4);
  tree.insert(3);
  tree.insert(5);
  tree.delete(8);
  t.is(tree._root.key, 4);
  t.is(tree._root.left.key, 2);
  t.is(tree._root.left.left.key, 1);
  t.is(tree._root.left.right.key, 3);
  t.is(tree._root.right.key, 6);
  t.is(tree._root.right.left.key, 5);
  t.is(tree._root.right.right.key, 7);
});

/**
 *       _3_                       _5_
 *      /   \                     /   \
 *     2     7  -> delete(1) ->  3     7
 *    /     / \                 / \   / \
 *   1     5   8               2   4 6   8
 *        / \
 *       4   6
 */
test('should correctly balance the right left case', function (t) {
  var tree = new Tree();
  tree.insert(3);
  tree.insert(2);
  tree.insert(7);
  tree.insert(1);
  tree.insert(8);
  tree.insert(5);
  tree.insert(4);
  tree.insert(6);
  tree.delete(1);
  t.is(tree._root.key, 5);
  t.is(tree._root.left.key, 3);
  t.is(tree._root.left.left.key, 2);
  t.is(tree._root.left.right.key, 4);
  t.is(tree._root.right.key, 7);
  t.is(tree._root.right.left.key, 6);
  t.is(tree._root.right.right.key, 8);
});
<|endoftext|>