<commit_before>var Q = require('q');
var Economy = require('../economy');
var User = require('../mongo').userModel;
var fs = require('fs');

var shop = [
    ['Symbol', 'Buys a custom symbol to go infront of name and puts you at top of userlist. (Temporary until restart, certain symbols are blocked)', 5],
    ['Fix', 'Buys the ability to alter your current custom avatar or trainer card. (don\'t buy if you have neither)', 10],
    ['Avatar', 'Buys an custom avatar to be applied to your name (You supply. Images larger than 80x80 may not show correctly)', 20],
    ['Declare', 'Globally declare a message to the whole server! [Can be refused](A small blue message that every chatroom can see; Uses: League Advertisements, Celebrations, ETC)', 25],
    ['Trainer', 'Buys a trainer card which shows information through a command. (You supply, can be refused)', 40],
    ['Staff Help', 'Staff member will help set up roomintros and anything else needed in a room. Response may not be immediate.', 50],
    ['League Shop', 'Purchases a League Shop for use in your league room, room must be a league room.', 75],
    ['Room', 'Buys a chatroom for you to own. (within reason, can be refused)', 100],
    ['Custom Artwork', 'Buys Elite Four Mitsaki\'s time.  The price may vary based on what\'s being done, but avatars, symbols, banners, etc.', 150]
];

var shopDisplay = getShopDisplay(shop);

module.exports = {
    atm: 'wallet',
    purse: 'wallet',
    wallet: function(target, room, user) {
        if (!this.canBroadcast()) return;
        if (!target) target = user.name;
        Economy.get(target).then(function(amount) {
            this.sendReplyBox(Tools.escapeHTML(target) + ' has ' + amount + Economy.currency(amount) + '.');
            room.update();
        }.bind(this));
    },

    givebuck: 'givemoney',
    givebucks: 'givemoney',
    givemoney: function(target, room, user) {
        if (!user.can('announce')) return this.sendReply('/givemoney - Access denied.');
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/givemoney [user], [amount] - Give a user a certain amount of money.');
        }

        var parts = target.split(',');
        this.splitTarget(parts[0]);
        var amount = Number(parts[1].trim());
        var currency = amount + Economy.currency(amount);

        if (!this.targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        Economy.give(this.targetUsername, amount).then(function(total) {
            this.sendReply(this.targetUsername + ' was given ' + currency  + '. This user now has ' + total + Economy.currency(total) + '.');
            Users.get(this.targetUsername).connections[0].sendTo(room.id, user.name + ' has given you ' + currency + '. You now have ' + total + Economy.currency(total) + '.');
        }.bind(this));
    },

    takebuck: 'takemoney',
    takebucks: 'takemoney',
    takemoney: function(target, room, user) {
        if (!user.can('announce')) return this.sendReply('/takemoney - Access denied.');
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/takemoney [user], [amount] - Take a certain amount of money from a user.');
        }

        var parts = target.split(',');
        this.splitTarget(parts[0]);
        var amount = Number(parts[1].trim());
        var currency = amount + Economy.currency(amount);

        if (!this.targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        Economy.take(this.targetUsername, amount).then(function(total) {
            this.sendReply(this.targetUsername + ' losted ' + currency + '. This user now has ' + total + Economy.currency(total) + '.');
            Users.get(this.targetUsername).send(user.name + ' has taken ' + currency + ' from you. You now have ' + total + Economy.currency(total) + '.');
        }.bind(this));
    },

    transfer: 'transfermoney',
    transferbuck: 'transfermoney',
    transferbucks: 'transfermoney',
    transfermoney: function(target, room, user) {
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/transfer [user], [amount] - Transfer a certain amount of money to a user.');
        }

        var parts = target.split(',');
        var amount = Number(parts[1].trim());
        var targetName = parts[0];
        var currency = amount + Economy.currency(amount);

        if (toId(targetName) === user.userid) return this.sendReply('You cannot transfer to yourself.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        var self = this;
        Economy.get(user.name)
            .then(function(money) {
                if (amount > money) return self.sendReply('You cannot transfer more money than what you have.');
                return [Economy.give(targetName, amount), Economy.take(user.name, amount)];
            })
            .spread(function(targetTotal, userTotal) {
                self.sendReply('You have successfully transferred ' + currency + '. You now have ' + userTotal + Economy.currency(userTotal) + '.');
                if (Users.get(targetName)) {
                    Users.get(targetName).connections[0].sendTo(room.id, user.name + ' has transferred ' + currency + '. You now have ' + targetTotal + Economy.currency(targetTotal) + '.');
                }
            }, function(err) {
                if (err) console.error(err);
            }).done();
    },

    shop: function(target, room, user) {
       if (!this.canBroadcast()) return;
       return this.sendReply('|raw|' + shopDisplay);
    },

    buy: function(target, room, user) {
        if (!target) return this.sendReply('/buy [command] - Buys an item from the shop.');
        var self = this;
        Economy.get(user.name).then(function(money) {
            var cost = findItem.call(self, target, money);
            if (!cost) return room.update();

            Economy.take(user.name, cost).then(function(total) {
                self.sendReply('You have bought ' + target + ' for ' + cost +
                    Economy.currency(cost) + '. You now have ' + total +
                    Economy.currency(total) + ' left.');
                room.addRaw(user.name + ' has bought ' + target + ' from the shop.');
                handleBoughtItem.call(self, target.toLowerCase(), user);
                room.update();
            });
        });
    },

    customsymbol: function(target, room, user) {
        if (!user.canCustomSymbol) return this.sendReply('You need to buy this item from the shop.');
        if (!target || target.length > 1) return this.sendReply('/customsymbol [symbol] - Get a custom symbol.');
        if (target.match(/[A-Za-z\d]+/g) || '?!+%@\u2605&~#'.indexOf(target) >= 0) return this.sendReply('Sorry, but you cannot change your symbol to this for safety/stability reasons.');
        user.customSymbol = target;
        user.updateIdentity();
        user.canCustomSymbol = false;
        user.hasCustomSymbol = true;
    },

    resetcustomsymbol: 'resetsymbol',
    resetsymbol: function(target, room, user) {
        if (!user.hasCustomSymbol) return this.sendReply('You don\'t have a custom symbol.');
        user.customSymbol = null;
        user.updateIdentity();
        user.hasCustomSymbol = false;
        this.sendReply('Your symbol has been reset.');
    },

    moneyladder: 'richestuser',
    richladder: 'richestuser',
    richestusers: 'richestuser',
    richestuser: function(target, room) {
        if (!this.canBroadcast()) return;
        var self = this;
        var display = 'Richest Users
\

\

\

\
                       Rank	\
                       Username	\
                       Money	\

';
        User
            .find()
            .sort({money: -1})
            .limit(10)
            .exec(function(err, users) {
                if (err) return;
                users.forEach(function(user, index) {
                    display += '
\
                                    ' + (index + 1) + '	\
                                    ' + user.name + '	\
                                    ' + user.money + '	\

';
                });
                display += '

';
                self.sendReply('|raw|' + display);
                room.update();
            });
    },

    resetbuck: 'resetmoney',
    resetbucks: 'resetmoney',
    resetmoney: function(target, room, user) {
        if (!user.can('resetmoney')) return this.sendReply('/resetmoney - Access denied.');
        var self = this;
        User.findOne({name: toId(target)}, function(err, user) {
            if (err) throw err;
            if (!user) {
                self.sendReply(target + ' already has 0 bucks.');
                return room.update();
            }
            user.money = 0;
            user.save(function(err) {
                if (err) throw err;
                self.sendReply(target + ' now has 0 bucks.');
                room.update();
            });
        });
    },

    registershop: function (target, room, user) {
    	if (!user.can('takemoney')) return this.sendReply('/registershop - Access Denied you silly goose!');
    	if (!target) return this.sendReply('Please specify a room you silly goose!');
    	if (!Rooms(toId(target))) return this.sendReply('That\'s not a real room you silly goose!');
    	var targetRoom = Rooms(toId(target));
    	targetRoom.add('|raw|
'+user.name+' has just added a league shop to this room.
');
	 				targetRoom.update();
	 				targetRoom.shop = new Object();
	 				targetRoom.shopList = new Array();
					targetRoom.chatRoomData.shop = targetRoom.shop;
					targetRoom.chatRoomData.shopList = targetRoom.shopList;
					Rooms.global.writeChatRoomData();
    },

    shopdeclare: function (target, room, user) {
        if (!user.canShopDeclare) return this.sendReply('You need to buy this item from the shop to use.');
        if (!target) return this.sendReply('/shopdeclare [message] - Send message to lobby.');
	Rooms.rooms['lobby'].add('|raw|
' + target + '
');
        this.logModCommand(user.name + " shop declared " + target);
        user.canShopDeclare = false;
    },

    shoppm: function (target, room, user) {
        if (!user.canShopPM) return this.sendReply('You need to buy this item from the shop to use.');
        if (!target) return this.sendReply('/shoppm [message] - PM all users in the server.');
        if (target.indexOf('/html') >= 0) return this.sendReply('Cannot contain /html.');

        var pmName = '~Global PM from ' + user.name +' [Do not reply]';

        for (var name in Users.users) {
            var message = '|pm|' + pmName + '|' + Users.users[name].getIdentity() + '|' + target;
            Users.users[name].send(message);
        }
        user.canShopPM = false;
    }
};

/**
 * Displays the shop
 *
 * @param {Array} shop
 * @return {String} display
 */

function getShopDisplay(shop) {
    var display = '
\

\

\
                            Command	\
                            Description	\
                            Cost	\

';
    var start = 0;
    while (start < shop.length) {
        display += '
\
                        <button name="send" value="/buy ' + shop[start][0] + '">' + shop[start][0] + '</button>' + '	\
                        ' + shop[start][1] + '	\
                        ' + shop[start][2] + '	\

';
        start++;
    }
    display += '

To buy an item from the shop, use /buy command.';
    return display;
}

/**
 * Find the item in the shop.
 *
 * @param {String} item
 * @param {Number} money
 * @return {Object}
 */

function findItem(item, money) {
    var len = shop.length;
    var price = 0;
    var amount = 0;
    while(len--) {
        if (item.toLowerCase() !== shop[len][0].toLowerCase()) continue;
        price = shop[len][2];
        if (price > money) {
            amount = price - money;
            this.sendReply('You don\'t have you enough money for this. You need ' + amount + Economy.currency(amount) + ' more to buy ' + item + '.');
            return false;
        }
        return price;
    }
    this.sendReply(item + ' not found in shop.');
}

/**
 * Handling the bought item from the shop.
 *
 * @param {String} item
 * @param {Object} user
 */

function handleBoughtItem(item, user) {
    if (item === 'symbol') {
        user.canCustomSymbol = true;
        this.sendReply('You have purchased a custom symbol. You can use /customsymbol to get your custom symbol.');
        this.sendReply('You will have this until you log off for more than an hour.');
        this.sendReply('If you do not want your custom symbol anymore, you may use /resetsymbol to go back to your old symbol.');
   } else if (item === 'declare') {
        user.canShopDeclare = true;
        this.sendReply('You have purchased a declare. You can use /shopdeclare to declare your message.');
   } else if (item === 'pm') {
        user.canShopPM = true;
        this.sendReply('You have purchased a pm. You can use /shoppm to declare your message.');
   } else {
        var msg = user.name + ' has bought ' + item + '.';
        for (var i in Users.users) {
            if (Users.users[i].group === '~') {
                Users.users[i].send('|pm|~Shop Alert|' + Users.users[i].getIdentity() + '|' + msg);
            }
        }
   }
}
<commit_msg>Update money.js<commit_after>var Q = require('q');
var Economy = require('../economy');
var User = require('../mongo').userModel;
var fs = require('fs');

var shop = [
    ['Symbol', 'Buys a custom symbol to go infront of name and puts you at top of userlist. (Temporary until restart, certain symbols are blocked)', 5],
    ['Fix', 'Buys the ability to alter your current custom avatar or trainer card. (don\'t buy if you have neither)', 10],
    ['Avatar', 'Buys an custom avatar to be applied to your name (You supply. Images larger than 80x80 may not show correctly)', 20],
    ['Trainer', 'Buys a trainer card which shows information through a command. (You supply, can be refused)', 40],
    ['Staff Help', 'Staff member will help set up roomintros and anything else needed in a room. Response may not be immediate.', 50],
    ['League Shop', 'Purchases a League Shop for use in your league room, room must be a league room.', 75],
    ['Room', 'Buys a chatroom for you to own. (within reason, can be refused)', 100],
    ['Custom Artwork', 'Buys Elite Four Mitsaki\'s time.  The price may vary based on what\'s being done, but avatars, symbols, banners, etc.', 150]
];

var shopDisplay = getShopDisplay(shop);

module.exports = {
    atm: 'wallet',
    purse: 'wallet',
    wallet: function(target, room, user) {
        if (!this.canBroadcast()) return;
        if (!target) target = user.name;
        Economy.get(target).then(function(amount) {
            this.sendReplyBox(Tools.escapeHTML(target) + ' has ' + amount + Economy.currency(amount) + '.');
            room.update();
        }.bind(this));
    },

    givebuck: 'givemoney',
    givebucks: 'givemoney',
    givemoney: function(target, room, user) {
        if (!user.can('announce')) return this.sendReply('/givemoney - Access denied.');
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/givemoney [user], [amount] - Give a user a certain amount of money.');
        }

        var parts = target.split(',');
        this.splitTarget(parts[0]);
        var amount = Number(parts[1].trim());
        var currency = amount + Economy.currency(amount);

        if (!this.targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        Economy.give(this.targetUsername, amount).then(function(total) {
            this.sendReply(this.targetUsername + ' was given ' + currency  + '. This user now has ' + total + Economy.currency(total) + '.');
            Users.get(this.targetUsername).connections[0].sendTo(room.id, user.name + ' has given you ' + currency + '. You now have ' + total + Economy.currency(total) + '.');
        }.bind(this));
    },

    takebuck: 'takemoney',
    takebucks: 'takemoney',
    takemoney: function(target, room, user) {
        if (!user.can('announce')) return this.sendReply('/takemoney - Access denied.');
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/takemoney [user], [amount] - Take a certain amount of money from a user.');
        }

        var parts = target.split(',');
        this.splitTarget(parts[0]);
        var amount = Number(parts[1].trim());
        var currency = amount + Economy.currency(amount);

        if (!this.targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        Economy.take(this.targetUsername, amount).then(function(total) {
            this.sendReply(this.targetUsername + ' losted ' + currency + '. This user now has ' + total + Economy.currency(total) + '.');
            Users.get(this.targetUsername).send(user.name + ' has taken ' + currency + ' from you. You now have ' + total + Economy.currency(total) + '.');
        }.bind(this));
    },

    transfer: 'transfermoney',
    transferbuck: 'transfermoney',
    transferbucks: 'transfermoney',
    transfermoney: function(target, room, user) {
        if (!target || target.indexOf(',') < 0) {
            return this.sendReply('/transfer [user], [amount] - Transfer a certain amount of money to a user.');
        }

        var parts = target.split(',');
        var amount = Number(parts[1].trim());
        var targetName = parts[0];
        var currency = amount + Economy.currency(amount);

        if (toId(targetName) === user.userid) return this.sendReply('You cannot transfer to yourself.');
        if (isNaN(parts[1])) return this.sendReply('Must be a number.');
        if (String(parts[1]).indexOf('.') >= 0) return this.sendReply('Cannot contain a decimal.');
        if (amount < 1) return this.sendReply('You can\'t give less than one' + Economy.currency(amount));

        var self = this;
        Economy.get(user.name)
            .then(function(money) {
                if (amount > money) return self.sendReply('You cannot transfer more money than what you have.');
                return [Economy.give(targetName, amount), Economy.take(user.name, amount)];
            })
            .spread(function(targetTotal, userTotal) {
                self.sendReply('You have successfully transferred ' + currency + '. You now have ' + userTotal + Economy.currency(userTotal) + '.');
                if (Users.get(targetName)) {
                    Users.get(targetName).connections[0].sendTo(room.id, user.name + ' has transferred ' + currency + '. You now have ' + targetTotal + Economy.currency(targetTotal) + '.');
                }
            }, function(err) {
                if (err) console.error(err);
            }).done();
    },

    shop: function(target, room, user) {
       if (!this.canBroadcast()) return;
       return this.sendReply('|raw|' + shopDisplay);
    },

    buy: function(target, room, user) {
        if (!target) return this.sendReply('/buy [command] - Buys an item from the shop.');
        var self = this;
        Economy.get(user.name).then(function(money) {
            var cost = findItem.call(self, target, money);
            if (!cost) return room.update();

            Economy.take(user.name, cost).then(function(total) {
                self.sendReply('You have bought ' + target + ' for ' + cost +
                    Economy.currency(cost) + '. You now have ' + total +
                    Economy.currency(total) + ' left.');
                room.addRaw(user.name + ' has bought ' + target + ' from the shop.');
                handleBoughtItem.call(self, target.toLowerCase(), user);
                room.update();
            });
        });
    },

    customsymbol: function(target, room, user) {
        if (!user.canCustomSymbol) return this.sendReply('You need to buy this item from the shop.');
        if (!target || target.length > 1) return this.sendReply('/customsymbol [symbol] - Get a custom symbol.');
        if (target.match(/[A-Za-z\d]+/g) || '?!+%@\u2605&~#'.indexOf(target) >= 0) return this.sendReply('Sorry, but you cannot change your symbol to this for safety/stability reasons.');
        user.customSymbol = target;
        user.updateIdentity();
        user.canCustomSymbol = false;
        user.hasCustomSymbol = true;
    },

    resetcustomsymbol: 'resetsymbol',
    resetsymbol: function(target, room, user) {
        if (!user.hasCustomSymbol) return this.sendReply('You don\'t have a custom symbol.');
        user.customSymbol = null;
        user.updateIdentity();
        user.hasCustomSymbol = false;
        this.sendReply('Your symbol has been reset.');
    },

    moneyladder: 'richestuser',
    richladder: 'richestuser',
    richestusers: 'richestuser',
    richestuser: function(target, room) {
        if (!this.canBroadcast()) return;
        var self = this;
        var display = 'Richest Users
\

\

\

\
                       Rank	\
                       Username	\
                       Money	\

';
        User
            .find()
            .sort({money: -1})
            .limit(10)
            .exec(function(err, users) {
                if (err) return;
                users.forEach(function(user, index) {
                    display += '
\
                                    ' + (index + 1) + '	\
                                    ' + user.name + '	\
                                    ' + user.money + '	\

';
                });
                display += '

';
                self.sendReply('|raw|' + display);
                room.update();
            });
    },

    resetbuck: 'resetmoney',
    resetbucks: 'resetmoney',
    resetmoney: function(target, room, user) {
        if (!user.can('resetmoney')) return this.sendReply('/resetmoney - Access denied.');
        var self = this;
        User.findOne({name: toId(target)}, function(err, user) {
            if (err) throw err;
            if (!user) {
                self.sendReply(target + ' already has 0 bucks.');
                return room.update();
            }
            user.money = 0;
            user.save(function(err) {
                if (err) throw err;
                self.sendReply(target + ' now has 0 bucks.');
                room.update();
            });
        });
    },

    registershop: function (target, room, user) {
    	if (!user.can('takemoney')) return this.sendReply('/registershop - Access Denied you silly goose!');
    	if (!target) return this.sendReply('Please specify a room you silly goose!');
    	if (!Rooms(toId(target))) return this.sendReply('That\'s not a real room you silly goose!');
    	var targetRoom = Rooms(toId(target));
    	targetRoom.add('|raw|
'+user.name+' has just added a league shop to this room.
');
	 				targetRoom.update();
	 				targetRoom.shop = new Object();
	 				targetRoom.shopList = new Array();
					targetRoom.chatRoomData.shop = targetRoom.shop;
					targetRoom.chatRoomData.shopList = targetRoom.shopList;
					Rooms.global.writeChatRoomData();
    },

    shopdeclare: function (target, room, user) {
        if (!user.canShopDeclare) return this.sendReply('You need to buy this item from the shop to use.');
        if (!target) return this.sendReply('/shopdeclare [message] - Send message to lobby.');
	Rooms.rooms['lobby'].add('|raw|
' + target + '
');
        this.logModCommand(user.name + " shop declared " + target);
        user.canShopDeclare = false;
    },

    shoppm: function (target, room, user) {
        if (!user.canShopPM) return this.sendReply('You need to buy this item from the shop to use.');
        if (!target) return this.sendReply('/shoppm [message] - PM all users in the server.');
        if (target.indexOf('/html') >= 0) return this.sendReply('Cannot contain /html.');

        var pmName = '~Global PM from ' + user.name +' [Do not reply]';

        for (var name in Users.users) {
            var message = '|pm|' + pmName + '|' + Users.users[name].getIdentity() + '|' + target;
            Users.users[name].send(message);
        }
        user.canShopPM = false;
    }
};

/**
 * Displays the shop
 *
 * @param {Array} shop
 * @return {String} display
 */

function getShopDisplay(shop) {
    var display = '
\

\

\
                            Command	\
                            Description	\
                            Cost	\

';
    var start = 0;
    while (start < shop.length) {
        display += '
\
                        <button name="send" value="/buy ' + shop[start][0] + '">' + shop[start][0] + '</button>' + '	\
                        ' + shop[start][1] + '	\
                        ' + shop[start][2] + '	\

';
        start++;
    }
    display += '

To buy an item from the shop, use /buy command.';
    return display;
}

/**
 * Find the item in the shop.
 *
 * @param {String} item
 * @param {Number} money
 * @return {Object}
 */

function findItem(item, money) {
    var len = shop.length;
    var price = 0;
    var amount = 0;
    while(len--) {
        if (item.toLowerCase() !== shop[len][0].toLowerCase()) continue;
        price = shop[len][2];
        if (price > money) {
            amount = price - money;
            this.sendReply('You don\'t have you enough money for this. You need ' + amount + Economy.currency(amount) + ' more to buy ' + item + '.');
            return false;
        }
        return price;
    }
    this.sendReply(item + ' not found in shop.');
}

/**
 * Handling the bought item from the shop.
 *
 * @param {String} item
 * @param {Object} user
 */

function handleBoughtItem(item, user) {
    if (item === 'symbol') {
        user.canCustomSymbol = true;
        this.sendReply('You have purchased a custom symbol. You can use /customsymbol to get your custom symbol.');
        this.sendReply('You will have this until you log off for more than an hour.');
        this.sendReply('If you do not want your custom symbol anymore, you may use /resetsymbol to go back to your old symbol.');
   } else if (item === 'declare') {
        user.canShopDeclare = true;
        this.sendReply('You have purchased a declare. You can use /shopdeclare to declare your message.');
   } else if (item === 'pm') {
        user.canShopPM = true;
        this.sendReply('You have purchased a pm. You can use /shoppm to declare your message.');
   } else {
        var msg = user.name + ' has bought ' + item + '.';
        for (var i in Users.users) {
            if (Users.users[i].group === '~') {
                Users.users[i].send('|pm|~Shop Alert|' + Users.users[i].getIdentity() + '|' + msg);
            }
        }
   }
}
<|endoftext|>


<commit_before>var _ = require('lodash');
var path = require('path');
var util = require('util');
var consolidate = require('consolidate');

/**
 * Marshal relevant parts of sails global configuration,
 * issue deprecation notices, etc.
 *
 * @param  {Sails} sails
 */
module.exports = function configure ( sails ) {

  if (sails.config.viewEngine) {
    sails.log.warn('The `config.viewEngine` config has been deprecated in favor of `config.views.engine`.');
    sails.log.warn('It has been automatically migrated, but you\'ll continue to see this warning until you change your configuration files.');
    sails.config.views.engine = sails.config.viewEngine;
  }

  // Normalize view engine config and allow defining a custom extension
  if (_.isString(sails.config.views.engine)) {
    var viewExt = sails.config.views.extension || sails.config.views.engine;
    sails.config.views.engine = {
      name: sails.config.views.engine,
      ext: viewExt
    };
  }

  // Get the view engine name
  var engineName = sails.config.views.engine.name || sails.config.views.engine.ext;

  // Ensure valid config
  if (! (sails.config.views.engine && sails.config.views.engine.ext) ) {
    sails.log.error('Invalid view engine configuration. `config.views.engine` should');
    sails.log.error('be set to either a `string` or an `object` with the following properties:');
    sails.log.error('    {');
    sails.log.error('        ext: <string>,   // the file extension');
    sails.log.error('        fn: <function>   // the template engine render function');
    sails.log.error('    }');
    sails.log.error('For example: {ext:"html", fn: require("consolidate").swig}');
    sails.log.error('For details: http://expressjs.com/api.html#app.engine');
    throw new Error('Invalid view engine configuration.');
  }

  // Try to load view module if a function wasn't specified directly
  if ( !sails.config.views.engine.fn ) {

    var appDependenciesPath;
    var fn;

    appDependenciesPath = path.join(sails.config.appPath, 'node_modules');

    try {

      // Try to load the view engine, optionally using a separate module
      // (see https://github.com/tj/consolidate.js/blob/master/lib/consolidate.js#L568)
      fn = getEngine(appDependenciesPath,engineName,sails.config.views.engine.module, sails);

      // If the engine doesn't export a function, it's not consolidate-compatible
      if ( !_.isFunction(fn) ) {
        sails.log.error(util.format('Invalid view engine (%s)-- are you sure it supports `consolidate`?', engineName));
        throw new Error();
      }
    }

    // If the engine can't be loaded, we can't continue
    catch (e) {
      sails.log.error('Your configured server-side view engine (' + engineName + ') could not be found.');
      sails.log.error('Usually, this just means you need to install a dependency.');
      sails.log.error('To install ' + engineName + ', try running:  `npm install ' + engineName + ' --save`');
      sails.log.error('Otherwise, please change your `engine` configuration in config/views.js.');
      throw e;
    }

    // Save reference to view rendering function
    sails.config.views.engine.fn = fn;
    sails.log.silly('Configured view engine, `' + engineName + '`');
  }

  // Let user know that a leading . is not required in the viewEngine option and then fix it
  if (sails.config.views.engine.ext[0] === '.') {
    sails.log.warn('A leading `.` is not required in the views.engine option.  Removing it for you...');
    sails.config.views.engine.ext = sails.config.views.engine.ext.substr(1);
  }

  // Custom layout location
  // (if string specified, it's used as the relative path from the views folder)
  // (if not string, but truthy, relative path from views folder defaults to ./layout.*)
  // (if falsy, don't use layout)
  if ( !_.isString(sails.config.views.layout) && sails.config.views.layout ) {
    sails.config.views.layout = 'layout.' + sails.config.views.engine.ext;
  }

  var layoutableEngines = [
    'ejs',
    'handlebars',
    'ractive'
  ];
  if ( sails.config.views.layout && layoutableEngines.indexOf(engineName) < 0 ) {
    sails.log.warn('Sails\' built-in layout support only works with the `' +
      layoutableEngines.join('`, `') + '` view engines.');
    sails.log.warn('You\'re using `'+ engineName +'`.');
    sails.log.warn('Ignoring `sails.config.views.layout`...');
  }
};

// Load a view engine either from the Consolidate cache or from a module installed
// locally to the Sails app.
function getEngine(appDependenciesPath, engineName, moduleName, sails) {

  // Most of the time the module name and engine name are the same
  moduleName = moduleName || engineName;

  // Get the base template loading function from consolidate
  var fn = consolidate[engineName];

  // If we haven't cached the engine module in consolidate's requires cache, do it now.
  if(!consolidate.requires[moduleName]) {
    try {
      //ensure the engine is required relative to the path of our app
      consolidate.requires[moduleName] = require(appDependenciesPath+'/' + moduleName);
      // If the engine name and module names are different, cache the engine under both
      // keys, since Consolidate likes it both ways:
      // https://github.com/tj/consolidate.js/blob/master/lib/consolidate.js#L195
      // https://github.com/tj/consolidate.js/blob/master/lib/consolidate.js#L568
      if (engineName != moduleName) {
        consolidate.requires[engineName] = consolidate.requires[moduleName];
      }
    } catch(e) {
      sails.log.info('Could not find module:', moduleName , 'in path:', appDependenciesPath);
    }
  }

  return fn;
}
<commit_msg>!== instead of !=<commit_after>var _ = require('lodash');
var path = require('path');
var util = require('util');
var consolidate = require('consolidate');

/**
 * Marshal relevant parts of sails global configuration,
 * issue deprecation notices, etc.
 *
 * @param  {Sails} sails
 */
module.exports = function configure ( sails ) {

  if (sails.config.viewEngine) {
    sails.log.warn('The `config.viewEngine` config has been deprecated in favor of `config.views.engine`.');
    sails.log.warn('It has been automatically migrated, but you\'ll continue to see this warning until you change your configuration files.');
    sails.config.views.engine = sails.config.viewEngine;
  }

  // Normalize view engine config and allow defining a custom extension
  if (_.isString(sails.config.views.engine)) {
    var viewExt = sails.config.views.extension || sails.config.views.engine;
    sails.config.views.engine = {
      name: sails.config.views.engine,
      ext: viewExt
    };
  }

  // Get the view engine name
  var engineName = sails.config.views.engine.name || sails.config.views.engine.ext;

  // Ensure valid config
  if (! (sails.config.views.engine && sails.config.views.engine.ext) ) {
    sails.log.error('Invalid view engine configuration. `config.views.engine` should');
    sails.log.error('be set to either a `string` or an `object` with the following properties:');
    sails.log.error('    {');
    sails.log.error('        ext: <string>,   // the file extension');
    sails.log.error('        fn: <function>   // the template engine render function');
    sails.log.error('    }');
    sails.log.error('For example: {ext:"html", fn: require("consolidate").swig}');
    sails.log.error('For details: http://expressjs.com/api.html#app.engine');
    throw new Error('Invalid view engine configuration.');
  }

  // Try to load view module if a function wasn't specified directly
  if ( !sails.config.views.engine.fn ) {

    var appDependenciesPath;
    var fn;

    appDependenciesPath = path.join(sails.config.appPath, 'node_modules');

    try {

      // Try to load the view engine, optionally using a separate module
      // (see https://github.com/tj/consolidate.js/blob/master/lib/consolidate.js#L568)
      fn = getEngine(appDependenciesPath,engineName,sails.config.views.engine.module, sails);

      // If the engine doesn't export a function, it's not consolidate-compatible
      if ( !_.isFunction(fn) ) {
        sails.log.error(util.format('Invalid view engine (%s)-- are you sure it supports `consolidate`?', engineName));
        throw new Error();
      }
    }

    // If the engine can't be loaded, we can't continue
    catch (e) {
      sails.log.error('Your configured server-side view engine (' + engineName + ') could not be found.');
      sails.log.error('Usually, this just means you need to install a dependency.');
      sails.log.error('To install ' + engineName + ', try running:  `npm install ' + engineName + ' --save`');
      sails.log.error('Otherwise, please change your `engine` configuration in config/views.js.');
      throw e;
    }

    // Save reference to view rendering function
    sails.config.views.engine.fn = fn;
    sails.log.silly('Configured view engine, `' + engineName + '`');
  }

  // Let user know that a leading . is not required in the viewEngine option and then fix it
  if (sails.config.views.engine.ext[0] === '.') {
    sails.log.warn('A leading `.` is not required in the views.engine option.  Removing it for you...');
    sails.config.views.engine.ext = sails.config.views.engine.ext.substr(1);
  }

  // Custom layout location
  // (if string specified, it's used as the relative path from the views folder)
  // (if not string, but truthy, relative path from views folder defaults to ./layout.*)
  // (if falsy, don't use layout)
  if ( !_.isString(sails.config.views.layout) && sails.config.views.layout ) {
    sails.config.views.layout = 'layout.' + sails.config.views.engine.ext;
  }

  var layoutableEngines = [
    'ejs',
    'handlebars',
    'ractive'
  ];
  if ( sails.config.views.layout && layoutableEngines.indexOf(engineName) < 0 ) {
    sails.log.warn('Sails\' built-in layout support only works with the `' +
      layoutableEngines.join('`, `') + '` view engines.');
    sails.log.warn('You\'re using `'+ engineName +'`.');
    sails.log.warn('Ignoring `sails.config.views.layout`...');
  }
};

// Load a view engine either from the Consolidate cache or from a module installed
// locally to the Sails app.
function getEngine(appDependenciesPath, engineName, moduleName, sails) {

  // Most of the time the module name and engine name are the same
  moduleName = moduleName || engineName;

  // Get the base template loading function from consolidate
  var fn = consolidate[engineName];

  // If we haven't cached the engine module in consolidate's requires cache, do it now.
  if(!consolidate.requires[moduleName]) {
    try {
      //ensure the engine is required relative to the path of our app
      consolidate.requires[moduleName] = require(appDependenciesPath+'/' + moduleName);
      // If the engine name and module names are different, cache the engine under both
      // keys, since Consolidate likes it both ways:
      // https://github.com/tj/consolidate.js/blob/master/lib/consolidate.js#L195
      // https://github.com/tj/consolidate.js/blob/master/lib/consolidate.js#L568
      if (engineName !== moduleName) {
        consolidate.requires[engineName] = consolidate.requires[moduleName];
      }
    } catch(e) {
      sails.log.info('Could not find module:', moduleName , 'in path:', appDependenciesPath);
    }
  }

  return fn;
}
<|endoftext|>


<commit_before>db.rubytest_students.remove({});
db.rubytest_courses.remove({});
db.rubytest.remove({});
<commit_msg>removed temp file from git<commit_after><|endoftext|>


<commit_before>/*
   Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.

   This file is licensed under the Apache License, Version 2.0 (the "License").
   You may not use this file except in compliance with the License. A copy of
   the License is located at

    http://aws.amazon.com/apache2.0/

   This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied. See the License for the
   specific language governing permissions and limitations under the License.

   ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
   https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ec2-example-elastic-ip-addresses.html
*/

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});

var paramsReleaseAddress = {
   AllocationId: 'ALLOCATION_ID'
};

// Disassociate the Elastic IP address from EC2 instance
ec2.releaseAddress(paramsReleaseAddress, function(err, data) {
   if (err) {
      console.log("Error", err);
   } else {
      console.log("Address released");
   }
});
<commit_msg>Update ec2_releaseaddress.js<commit_after>// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ec2-example-elastic-ip-addresses.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});

var paramsReleaseAddress = {
   AllocationId: 'ALLOCATION_ID'
};

// Disassociate the Elastic IP address from EC2 instance
ec2.releaseAddress(paramsReleaseAddress, function(err, data) {
   if (err) {
      console.log("Error", err);
   } else {
      console.log("Address released");
   }
});
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

ESLint rules for volebo.net

Copyright (C) 2016  Volebo.Net <volebo.net@gmail.com>
Copyright (C) 2016  Koryukov Maksim <maxkoryukov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

exports = module.exports = {
	"extends": [
		"eslint:recommended"
		//"./node_modules/coding-standard/eslintDefaults.js",
		// Override eslintDefaults.js
		//"./node_modules/coding-standard/.eslintrc-es6",
		// Override .eslintrc-es6
		//"./node_modules/coding-standard/.eslintrc-jsx",
	],

	"env": {
		"node": true,
		"es6": true,
	},

	"rules": {
		// Override any settings from the "parent" configuration
		"comma-dangle" : ["error", "only-multiline"],
		"no-unused-vars" : ["warn", { "argsIgnorePattern": "next" }],
		"curly" : ["error"],
		"eqeqeq": ["error"],
		"no-process-exit": ["error"],
		"no-path-concat": ["error"],
		"no-extra-parens": ["error", "all", { "nestedBinaryExpressions": false }],
		"no-cond-assign": ["error"],
		"strict": ["error", "global"],

		/* CODE STYLE */
		"indent": ["warn", "tab"],
	},

	"quiet": true
};
<commit_msg>more rules from (see #3)<commit_after>/*
The MIT License (MIT)

ESLint rules for volebo.net

Copyright (C) 2016  Volebo.Net <volebo.net@gmail.com>
Copyright (C) 2016  Koryukov Maksim <maxkoryukov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

exports = module.exports = {
	"extends": [
		"eslint:recommended"
		//"./node_modules/coding-standard/eslintDefaults.js",
		// Override eslintDefaults.js
		//"./node_modules/coding-standard/.eslintrc-es6",
		// Override .eslintrc-es6
		//"./node_modules/coding-standard/.eslintrc-jsx",
	],

	"env": {
		"node": true,
		"es6": true,
	},

	"rules": {
		// Override any settings from the "parent" configuration
		"comma-dangle" : ["error", "only-multiline"],
		"no-process-exit": ["error"],
		"no-path-concat": ["error"],
		"no-extra-parens": ["error", "all", { "nestedBinaryExpressions": false }],
		"no-cond-assign": ["error"],

		/* CODE STYLE */
		"indent": ["warn", "tab"],
		"curly": ["warn"],
		"new-cap": ["warn"],

		/* STATIC SECURITY */
		"eqeqeq": ["error"],
		"guard-for-in": ["error"],
		"no-use-before-define": ["error", { "functions": true, "classes": true }],
		"no-caller": ["error"],
		"no-empty": ["error", { "allowEmptyCatch": false }],
		"no-empty-function": ["error"],

		"no-native-reassign": ["error"],
		"no-extend-native": ["error"],
		"strict": ["error", "global"],
		"no-unused-vars" : ["warn", { "argsIgnorePattern": "next" }],
		"no-bitwise": ["error"],
	},

	"quiet": true
};
<|endoftext|>


<commit_before>import './TodoList.css'
import React from 'react'
import PropTypes from 'prop-types'
import { ALL_STATUSES, ACTIVE, CANCELED, COMPLETED, TodoStatus } from '../model/todo-model'
import TodoItem from './TodoItem'

const TodoList = ({ todos, ...props }) => {
    return (

            {todos.map(todo => (
                <TodoItem key={todo.id} todo={todo} {...props} />
            ))}

    )
}

TodoList.propTypes = {
    todos: PropTypes.arrayOf(PropTypes.shape({
        id: PropTypes.number.isRequired,
        text: PropTypes.string.isRequired,
        status: PropTypes.oneOf([ALL_STATUSES, ACTIVE, COMPLETED, CANCELED])
    })).isRequired
}

export default TodoList<commit_msg>status change complete<commit_after>import './TodoList.css'
import React from 'react'
import PropTypes from 'prop-types'
import { ALL_STATUSES, ACTIVE, CANCELED, COMPLETED } from '../model/todo-model'
import TodoItem from './TodoItem'

const TodoList = ({ todos, ...props }) => {
    return (

            {todos.map(todo => (
                <TodoItem key={todo.id} todo={todo} {...props} />
            ))}

    )
}

TodoList.propTypes = {
    todos: PropTypes.arrayOf(PropTypes.shape({
        id: PropTypes.number.isRequired,
        text: PropTypes.string.isRequired,
        status: PropTypes.oneOf([ALL_STATUSES, ACTIVE, COMPLETED, CANCELED])
    })).isRequired
}

export default TodoList<|endoftext|>


<commit_before>/**
 * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * This file is licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 * http://aws.amazon.com/apache2.0/
 *
 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 */

//snippet-sourcedescription:[ses_updatetemplate.js demonstrates how to update an Amazon SES email template.]
//snippet-keyword:[JavaScript]
//snippet-sourcesyntax:[javascript]
//snippet-keyword:[Code Sample]
//snippet-keyword:[Amazon Simple Email Service]
//snippet-service:[ses]
//snippet-sourcetype:[full-example]
//snippet-sourcedate:[2018-06-02]
//snippet-sourceauthor:[AWS-JSDG]

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-creating-template.html

// snippet-start:[ses.JavaScript.templates.updateTemplate]
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create updateTemplate parameters
var params = {
  Template: {
    TemplateName: 'TEMPLATE_NAME', /* required */
    HtmlPart: 'HTML_CONTENT',
    SubjectPart: 'SUBJECT_LINE',
    TextPart: 'TEXT_CONTENT'
  }
};

// Create the promise and SES service object
var templatePromise = new AWS.SES({apiVersion: '2010-12-01'}).updateTemplate(params).promise();

// Handle promise's fulfilled/rejected states
templatePromise.then(
  function(data) {
    console.log("Template Updated");
  }).switch(
    function(err) {
    console.error(err, err.stack);
  });
// snippet-end:[ses.JavaScript.templates.updateTemplate]
<commit_msg>Change promise switch to catch<commit_after>/**
 * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * This file is licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 * http://aws.amazon.com/apache2.0/
 *
 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 */

//snippet-sourcedescription:[ses_updatetemplate.js demonstrates how to update an Amazon SES email template.]
//snippet-keyword:[JavaScript]
//snippet-sourcesyntax:[javascript]
//snippet-keyword:[Code Sample]
//snippet-keyword:[Amazon Simple Email Service]
//snippet-service:[ses]
//snippet-sourcetype:[full-example]
//snippet-sourcedate:[2018-06-02]
//snippet-sourceauthor:[AWS-JSDG]

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-creating-template.html

// snippet-start:[ses.JavaScript.templates.updateTemplate]
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create updateTemplate parameters
var params = {
  Template: {
    TemplateName: 'TEMPLATE_NAME', /* required */
    HtmlPart: 'HTML_CONTENT',
    SubjectPart: 'SUBJECT_LINE',
    TextPart: 'TEXT_CONTENT'
  }
};

// Create the promise and SES service object
var templatePromise = new AWS.SES({apiVersion: '2010-12-01'}).updateTemplate(params).promise();

// Handle promise's fulfilled/rejected states
templatePromise.then(
  function(data) {
    console.log("Template Updated");
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
// snippet-end:[ses.JavaScript.templates.updateTemplate]
<|endoftext|>


<commit_before>module.exports = function (graph, settings){
  var merge = require('ngraph.merge');
  var fabric = require('./lib/fabric');

  settings = merge(settings, {
    // canvasId: "id", // identifier of dom element which sould be used as a container
    // container: DomElement, // DOM element where you want to attach generated canvas
    // Default physics engine settings
      physics: {
        springLength: 30,
        springCoeff: 0.0008,
        dragCoeff: 0.01,
        gravity: -1.2,
        theta: 1
      },
      // default canvas size when rendering from node
      width: 640,
      height: 480
  });

  var defaults = require('./lib/defaults');
  var domContainer = require('./lib/createContainer')(settings);
  var canvas = require('./lib/createCanvas')(settings, domContainer);

  var layout = createLayout(settings); // Our layout algorithm

  var dx, dy, scale; // Global canvas transforms

  // Default callbacks to build/render nodes and links
  var nodeUIBuilder, nodeRenderer, linkUIBuilder, linkRenderer;

  var nodeUI, linkUI; // Storage for UI of nodes/links
  var getNodeAt; // node lookup by cooridnates

  // Public API:
  var graphics = {
    run : animationLoop,
    renderOneFrame: renderOneFrame,
    canvas: canvas,
    layout: layout,

    /**
     * Sets absolute transform for a canvas
     * @param {Number} tx - X translate
     * @param {Number} ty - Y translate
     * @param {Number} newScale - Scale level
     */
    setTransform: function(tx, ty, newScale) {
      scale = newScale; dx = tx; dy = ty;
      canvas.contextContainer.setTransform(scale, 0, 0, scale, dx, dy);
    },

    /**
     * Gets current transforms applied to canvas
     */
    getTransform: function () {
      return {
        scale: scale,
        dx: dx,
        dy: dy
      };
    },

    /**
     * Zooms to a point cx, cy (in canvas coordinates) with given scale level
     */
    zoom: function (cx, cy, newScale) {
      var ds = (scale - newScale);
      graphics.setTransform(dx + cx * ds, dy + cy * ds, newScale);
    },

    /**
     * Gets canvas position from world position (e.g. mouse cursor)
     * @param {Number} x - coordinate X relative to top left corner of a canvas
     * @param {Number} y - coordinate Y relative to top left corner of a canvas
     */
    getLocalPosition: getLocalPosition,

    /**
     * Resets all transforms and center graph
     */
    resetTransform: function () {
      graphics.setTransform(canvas.width/2, canvas.height/2, 1);
    },

    /**
     * Gets UI object for a given node id
     */
    getNodeUI : function (nodeId) {
      return nodeUI[nodeId];
    },

    getLinkUI: function (linkId) {
      return linkUI[linkId];
    },

    /**
     * This callback creates new UI for a graph node. This becomes helpful
     * when you want to precalculate some properties, which otherwise could be
     * expensive during rendering frame.
     *
     * @callback createNodeUICallback
     * @param {object} node - graph node for which UI is required.
     * @returns {object} arbitrary object which will be later passed to renderNode
     */
    /**
     * This function allows clients to pass custon node UI creation callback
     *
     * @param {createNodeUICallback} createNodeUICallback - The callback that
     * creates new node UI
     * @returns {object} this for chaining.
     */
    createNodeUI : function (createNodeUICallback) {
      nodeUI = {};
      nodeUIBuilder = createNodeUICallback;
      getNodeAt = require('./lib/spatialIndex')(graph, nodeUI);
      rebuildUI();
      return this;
    },

    /**
     * This callback is called by pixiGraphics when it wants to render node on
     * a screen.
     *
     * @callback renderNodeCallback
     * @param {object} node - result of createNodeUICallback(). It contains anything
     * you'd need to render a node
     * @param {PIXI.Graphics} ctx - PIXI's rendering context.
     */
    /**
     * Allows clients to pass custom node rendering callback
     *
     * @param {renderNodeCallback} renderNodeCallback - Callback which renders
     * node.
     *
     * @returns {object} this for chaining.
     */
    renderNode: function (renderNodeCallback) {
      nodeRenderer = renderNodeCallback;
      return this;
    },

    /**
     * This callback creates new UI for a graph link. This becomes helpful
     * when you want to precalculate some properties, which otherwise could be
     * expensive during rendering frame.
     *
     * @callback createLinkUICallback
     * @param {object} link - graph link for which UI is required.
     * @returns {object} arbitrary object which will be later passed to renderNode
     */
    /**
     * This function allows clients to pass custon node UI creation callback
     *
     * @param {createLinkUICallback} createLinkUICallback - The callback that
     * creates new link UI
     * @returns {object} this for chaining.
     */
    createLinkUI : function (createLinkUICallback) {
      linkUI = {};
      linkUIBuilder = createLinkUICallback;
      rebuildUI();
      return this;
    },

    /**
     * This callback is called by pixiGraphics when it wants to render link on
     * a screen.
     *
     * @callback renderLinkCallback
     * @param {object} link - result of createLinkUICallback(). It contains anything
     * you'd need to render a link
     * @param {PIXI.Graphics} ctx - PIXI's rendering context.
     */
    /**
     * Allows clients to pass custom link rendering callback
     *
     * @param {renderLinkCallback} renderLinkCallback - Callback which renders
     * link.
     *
     * @returns {object} this for chaining.
     */
    renderLink: function (renderLinkCallback) {
      linkRenderer = renderLinkCallback;
      return this;
    }
  };

  // teach graphics object to fire events
  require('ngraph.events')(graphics);

  // Make sure everything is initialized before returning API:
  initialize();

  return graphics;

///////////////////////////////////////////////////////////////////////////////

  function initialize() {
    nodeUIBuilder = defaults.createNodeUI,
    nodeRenderer  = defaults.nodeRenderer,
    linkUIBuilder = defaults.createLinkUI,
    linkRenderer  = defaults.linkRenderer;
    nodeUI = {}, linkUI = {}; // Storage for UI of nodes/links

    getNodeAt = require('./lib/spatialIndex')(graph, nodeUI);

    graph.forEachLink(initLink);
    graph.forEachNode(initNode);

    graph.on('changed', onGraphChanged);

    graphics.resetTransform();
    listenToInputEvents(domContainer);
  }

  function animationLoop() {
    layout.step();
    renderOneFrame();
    fabric.util.requestAnimFrame(animationLoop, canvas.getElement());
  }

  function renderOneFrame() {
    Object.keys(linkUI).forEach(renderLink);
    Object.keys(nodeUI).forEach(renderNode);

    // Fabric does not repsect transforms when it clears context; Doing it ourselves:
    clearContext(canvas.contextContainer);
    canvas.renderAll();
  }

  function clearContext(ctx) {
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    canvas.clearContext(ctx);
    ctx.restore();
  }

  function renderNode(nodeId) {
    nodeRenderer(nodeUI[nodeId]);
  }

  function renderLink(linkId) {
    linkRenderer(linkUI[linkId]);
  }

  function initNode(node) {
    var ui = nodeUIBuilder(node);
    if (!ui) return;
    // augment it with position data:
    ui.pos = layout.getNodePosition(node.id);
    // and store for subsequent use:
    nodeUI[node.id] = ui;

    canvas.add(ui);
  }

  function initLink(link) {
    var ui = linkUIBuilder(link);
    if (!ui) return;

    ui.from = layout.getNodePosition(link.fromId);
    ui.to = layout.getNodePosition(link.toId);

    linkUI[link.id] = ui;
    canvas.insertAt(ui, 0);
  }

  function rebuildUI() {
    // fabric does not have fast method to clear scene. This is a dirty hack:
    canvas.getObjects().length = 0;
    graph.forEachLink(initLink);
    graph.forEachNode(initNode);
  }

  function listenToInputEvents(container) {
    var domEvents = require('./lib/domEvents')(container);

    domEvents.on('wheel', handleMouseWheel)
      .on('mousedown', handleMouseDown)
      .on('mouseup', handleMouseUp)
      .on('mousemove', handleMouseMove);

    var isDragging = false,
        prevX, prevY,
        lastOver, nodeUnderCursor;

    function handleMouseDown(e) {
      isDragging = true;
      prevX = e.clientX;
      prevY = e.clientY;

      var pos = getLocalPosition(e.clientX, e.clientY);
      nodeUnderCursor = getNodeAt(pos.x, pos.y);
      if (nodeUnderCursor) {
        layout.pinNode(nodeUnderCursor, true);
        graphics.fire('mouseDownNode', nodeUnderCursor);
      }
    }

    function handleMouseUp(e) {
      isDragging = false;
      if (nodeUnderCursor) {
        layout.pinNode(nodeUnderCursor, false);
        graphics.fire('mouseUpNode', nodeUnderCursor);
      }
      nodeUnderCursor = null;
    }

    function handleMouseMove(e) {
      var pos = getLocalPosition(e.clientX, e.clientY);
      if (!isDragging) {
        var node  = getNodeAt(pos.x, pos.y);
        if (lastOver && lastOver != node) {
          graphics.fire('mouseLeaveNode', lastOver);
          lastOver = node;
          if (node) graphics.fire('mouseOverNode', node);
        } else if (node && !lastOver) {
          lastOver = node;
          graphics.fire('mouseOverNode', node);
        }
        return;
      }

      if (nodeUnderCursor) {
        layout.setNodePosition(nodeUnderCursor.id, pos.x, pos.y);
      } else {
        if (node) graphics.fire('mouseovernode', node);
        var offsetX = (e.clientX - prevX);
        var offsetY = (e.clientY - prevY);
        graphics.setTransform(dx + offsetX, dy + offsetY, scale);
        prevX = e.clientX;
        prevY = e.clientY;
      }
    }
  }

  function handleMouseWheel(e) {
    var isZoomIn = e.deltaY < 0;
    var direction = isZoomIn ? 1 : -1;
    var factor = (1 + direction * 0.1);
    var mousePos = {
      x: e.clientX,
      y: e.clientY
    };

    var before = getLocalPosition(mousePos.x, mousePos.y, scale);
    graphics.zoom(before.x, before.y, scale * factor);
  }

  function getLocalPosition(x, y, scaleLevel) {
    if (scaleLevel === undefined) {
      scaleLevel = scale; // use current scale then;
    }

    return {
      x: (x - dx) / scaleLevel,
      y: (y - dy) / scaleLevel
    };
  }

  function createLayout(settings) {
    if (settings.layout) {
      return settings.layout; // user has its own layout algorithm. Use it;
    }
    // otherwise let's create a default force directed layout:
    var physics = require('ngraph.physics.simulator');
    return require('ngraph.forcelayout')(graph, physics(settings.physics));
  }

  function onGraphChanged(changes) {
    for (var i = 0; i < changes.length; ++i) {
      var change = changes[i];
      if (change.changeType === 'add') {
        if (change.node) {
          initNode(change.node);
        }
        if (change.link) {
          initLink(change.link);
        }
      } else if (change.changeType === 'remove') {
        if (change.node) {
          var node = nodeUI[change.node.id];
          if (node) { canvas.remove(node); }
          delete nodeUI[change.node.id];
        }
        if (change.link) {
          var link = linkUI[change.link.id];
          if (link) canvas.remove(link);
          delete linkUI[change.link.id];
        }
      }
    }
  }
}
<commit_msg>Updated comments<commit_after>module.exports = function (graph, settings){
  var merge = require('ngraph.merge');
  var fabric = require('./lib/fabric');

  settings = merge(settings, {
    // canvasId: "id", // identifier of dom element which sould be used as a container
    // container: DomElement, // DOM element where you want to attach generated canvas
    // Default physics engine settings
      physics: {
        springLength: 30,
        springCoeff: 0.0008,
        dragCoeff: 0.01,
        gravity: -1.2,
        theta: 1
      },
      // default canvas size when rendering from node
      width: 640,
      height: 480
  });

  var defaults = require('./lib/defaults');
  var domContainer = require('./lib/createContainer')(settings);
  var canvas = require('./lib/createCanvas')(settings, domContainer);

  var layout = createLayout(settings); // Our layout algorithm

  var dx, dy, scale; // Global canvas transforms

  // Default callbacks to build/render nodes and links
  var nodeUIBuilder, nodeRenderer, linkUIBuilder, linkRenderer;

  var nodeUI, linkUI; // Storage for UI of nodes/links
  var getNodeAt; // node lookup by cooridnates

  // Public API:
  var graphics = {
    run : animationLoop,
    renderOneFrame: renderOneFrame,
    canvas: canvas,
    layout: layout,

    /**
     * Sets absolute transform for a canvas
     * @param {Number} tx - X translate
     * @param {Number} ty - Y translate
     * @param {Number} newScale - Scale level
     */
    setTransform: function(tx, ty, newScale) {
      scale = newScale; dx = tx; dy = ty;
      canvas.contextContainer.setTransform(scale, 0, 0, scale, dx, dy);
    },

    /**
     * Gets current transforms applied to canvas
     */
    getTransform: function () {
      return {
        scale: scale,
        dx: dx,
        dy: dy
      };
    },

    /**
     * Zooms to a point cx, cy (in canvas coordinates) with given scale level
     */
    zoom: function (cx, cy, newScale) {
      var ds = (scale - newScale);
      graphics.setTransform(dx + cx * ds, dy + cy * ds, newScale);
    },

    /**
     * Gets canvas position from world position (e.g. mouse cursor)
     * @param {Number} x - coordinate X relative to top left corner of a canvas
     * @param {Number} y - coordinate Y relative to top left corner of a canvas
     */
    getLocalPosition: getLocalPosition,

    /**
     * Resets all transforms and center graph
     */
    resetTransform: function () {
      graphics.setTransform(canvas.width/2, canvas.height/2, 1);
    },

    /**
     * Gets UI object for a given node id
     */
    getNodeUI : function (nodeId) {
      return nodeUI[nodeId];
    },

    getLinkUI: function (linkId) {
      return linkUI[linkId];
    },

    /**
     * This callback creates new UI for a graph node. This becomes helpful
     * when you want to precalculate some properties, which otherwise could be
     * expensive during rendering frame.
     *
     * @callback createNodeUICallback
     * @param {object} node - graph node for which UI is required.
     * @returns {object} arbitrary object which will be later passed to renderNode
     */
    /**
     * This function allows clients to pass custon node UI creation callback
     *
     * @param {createNodeUICallback} createNodeUICallback - The callback that
     * creates new node UI
     * @returns {object} this for chaining.
     */
    createNodeUI : function (createNodeUICallback) {
      nodeUI = {};
      nodeUIBuilder = createNodeUICallback;
      getNodeAt = require('./lib/spatialIndex')(graph, nodeUI);
      rebuildUI();
      return this;
    },

    /**
     * This callback is called by graphics when it wants to render node on
     * a screen.
     *
     * @callback renderNodeCallback
     * @param {object} node - result of createNodeUICallback(). It contains anything
     * you'd need to render a node
     */
    /**
     * Allows clients to pass custom node rendering callback
     *
     * @param {renderNodeCallback} renderNodeCallback - Callback which renders
     * node.
     *
     * @returns {object} this for chaining.
     */
    renderNode: function (renderNodeCallback) {
      nodeRenderer = renderNodeCallback;
      return this;
    },

    /**
     * This callback creates new UI for a graph link. This becomes helpful
     * when you want to precalculate some properties, which otherwise could be
     * expensive during rendering frame.
     *
     * @callback createLinkUICallback
     * @param {object} link - graph link for which UI is required.
     * @returns {object} arbitrary object which will be later passed to renderNode
     */
    /**
     * This function allows clients to pass custon node UI creation callback
     *
     * @param {createLinkUICallback} createLinkUICallback - The callback that
     * creates new link UI
     * @returns {object} this for chaining.
     */
    createLinkUI : function (createLinkUICallback) {
      linkUI = {};
      linkUIBuilder = createLinkUICallback;
      rebuildUI();
      return this;
    },

    /**
     * This callback is called by graphics when it wants to render link on
     * a screen.
     *
     * @callback renderLinkCallback
     * @param {object} link - result of createLinkUICallback(). It contains anything
     * you'd need to render a link
     */
    /**
     * Allows clients to pass custom link rendering callback
     *
     * @param {renderLinkCallback} renderLinkCallback - Callback which renders
     * link.
     *
     * @returns {object} this for chaining.
     */
    renderLink: function (renderLinkCallback) {
      linkRenderer = renderLinkCallback;
      return this;
    }
  };

  // teach graphics object to fire events
  require('ngraph.events')(graphics);

  // Make sure everything is initialized before returning API:
  initialize();

  return graphics;

///////////////////////////////////////////////////////////////////////////////

  function initialize() {
    nodeUIBuilder = defaults.createNodeUI,
    nodeRenderer  = defaults.nodeRenderer,
    linkUIBuilder = defaults.createLinkUI,
    linkRenderer  = defaults.linkRenderer;
    nodeUI = {}, linkUI = {}; // Storage for UI of nodes/links

    getNodeAt = require('./lib/spatialIndex')(graph, nodeUI);

    graph.forEachLink(initLink);
    graph.forEachNode(initNode);

    graph.on('changed', onGraphChanged);

    graphics.resetTransform();
    listenToInputEvents(domContainer);
  }

  function animationLoop() {
    layout.step();
    renderOneFrame();
    fabric.util.requestAnimFrame(animationLoop, canvas.getElement());
  }

  function renderOneFrame() {
    Object.keys(linkUI).forEach(renderLink);
    Object.keys(nodeUI).forEach(renderNode);

    // Fabric does not repsect transforms when it clears context; Doing it ourselves:
    clearContext(canvas.contextContainer);
    canvas.renderAll();
  }

  function clearContext(ctx) {
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    canvas.clearContext(ctx);
    ctx.restore();
  }

  function renderNode(nodeId) {
    nodeRenderer(nodeUI[nodeId]);
  }

  function renderLink(linkId) {
    linkRenderer(linkUI[linkId]);
  }

  function initNode(node) {
    var ui = nodeUIBuilder(node);
    if (!ui) return;
    // augment it with position data:
    ui.pos = layout.getNodePosition(node.id);
    // and store for subsequent use:
    nodeUI[node.id] = ui;

    canvas.add(ui);
  }

  function initLink(link) {
    var ui = linkUIBuilder(link);
    if (!ui) return;

    ui.from = layout.getNodePosition(link.fromId);
    ui.to = layout.getNodePosition(link.toId);

    linkUI[link.id] = ui;
    canvas.insertAt(ui, 0);
  }

  function rebuildUI() {
    // fabric does not have fast method to clear scene. This is a dirty hack:
    canvas.getObjects().length = 0;
    graph.forEachLink(initLink);
    graph.forEachNode(initNode);
  }

  function listenToInputEvents(container) {
    var domEvents = require('./lib/domEvents')(container);

    domEvents.on('wheel', handleMouseWheel)
      .on('mousedown', handleMouseDown)
      .on('mouseup', handleMouseUp)
      .on('mousemove', handleMouseMove);

    var isDragging = false,
        prevX, prevY,
        lastOver, nodeUnderCursor;

    function handleMouseDown(e) {
      isDragging = true;
      prevX = e.clientX;
      prevY = e.clientY;

      var pos = getLocalPosition(e.clientX, e.clientY);
      nodeUnderCursor = getNodeAt(pos.x, pos.y);
      if (nodeUnderCursor) {
        layout.pinNode(nodeUnderCursor, true);
        graphics.fire('mouseDownNode', nodeUnderCursor);
      }
    }

    function handleMouseUp(e) {
      isDragging = false;
      if (nodeUnderCursor) {
        layout.pinNode(nodeUnderCursor, false);
        graphics.fire('mouseUpNode', nodeUnderCursor);
      }
      nodeUnderCursor = null;
    }

    function handleMouseMove(e) {
      var pos = getLocalPosition(e.clientX, e.clientY);
      if (!isDragging) {
        var node  = getNodeAt(pos.x, pos.y);
        if (lastOver && lastOver != node) {
          graphics.fire('mouseLeaveNode', lastOver);
          lastOver = node;
          if (node) graphics.fire('mouseOverNode', node);
        } else if (node && !lastOver) {
          lastOver = node;
          graphics.fire('mouseOverNode', node);
        }
        return;
      }

      if (nodeUnderCursor) {
        layout.setNodePosition(nodeUnderCursor.id, pos.x, pos.y);
      } else {
        if (node) graphics.fire('mouseovernode', node);
        var offsetX = (e.clientX - prevX);
        var offsetY = (e.clientY - prevY);
        graphics.setTransform(dx + offsetX, dy + offsetY, scale);
        prevX = e.clientX;
        prevY = e.clientY;
      }
    }
  }

  function handleMouseWheel(e) {
    var isZoomIn = e.deltaY < 0;
    var direction = isZoomIn ? 1 : -1;
    var factor = (1 + direction * 0.1);
    var mousePos = {
      x: e.clientX,
      y: e.clientY
    };

    var before = getLocalPosition(mousePos.x, mousePos.y, scale);
    graphics.zoom(before.x, before.y, scale * factor);
  }

  function getLocalPosition(x, y, scaleLevel) {
    if (scaleLevel === undefined) {
      scaleLevel = scale; // use current scale then;
    }

    return {
      x: (x - dx) / scaleLevel,
      y: (y - dy) / scaleLevel
    };
  }

  function createLayout(settings) {
    if (settings.layout) {
      return settings.layout; // user has its own layout algorithm. Use it;
    }
    // otherwise let's create a default force directed layout:
    var physics = require('ngraph.physics.simulator');
    return require('ngraph.forcelayout')(graph, physics(settings.physics));
  }

  function onGraphChanged(changes) {
    for (var i = 0; i < changes.length; ++i) {
      var change = changes[i];
      if (change.changeType === 'add') {
        if (change.node) {
          initNode(change.node);
        }
        if (change.link) {
          initLink(change.link);
        }
      } else if (change.changeType === 'remove') {
        if (change.node) {
          var node = nodeUI[change.node.id];
          if (node) { canvas.remove(node); }
          delete nodeUI[change.node.id];
        }
        if (change.link) {
          var link = linkUI[change.link.id];
          if (link) canvas.remove(link);
          delete linkUI[change.link.id];
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>function ViewController ($scope, authHttp, $route) {

	$scope.roles = authHttp.get('/api/v2013/roles', { cache: true }).then(function (response) {
		var map = {};
		response.data.forEach(function (role) {
			map[role.roleId] = role;
		});
		return map;
	});

	function populate () {
		authHttp.get('/api/v2013/users', { params: { q: $scope.freetext, sk: $scope.currentPage*25, l: 25 } }).then(function (response) {
			$scope.users =  response.data;
		});
	};

	function setPage (page) {
		$scope.currentPage = Math.max(0, Math.min($scope.pageCount-1, page|0));
	};

	//

    $scope.pageCount = 4;
    $scope.pages = [0, 1, 2, 3];
    $scope.currentPage = 0;

    $scope.actionSetPage = setPage;

	$scope.$watch('freetext', populate);
	$scope.$watch('currentPage', populate);
}<commit_msg>force signin<commit_after>function ViewController ($scope, authHttp, $route, navigation) {

	navigation.securize();

	$scope.roles = authHttp.get('/api/v2013/roles', { cache: true }).then(function (response) {
		var map = {};
		response.data.forEach(function (role) {
			map[role.roleId] = role;
		});
		return map;
	});

	function populate () {
		authHttp.get('/api/v2013/users', { params: { q: $scope.freetext, sk: $scope.currentPage*25, l: 25 } }).then(function (response) {
			$scope.users =  response.data;
		});
	};

	function setPage (page) {
		$scope.currentPage = Math.max(0, Math.min($scope.pageCount-1, page|0));
	};

	//

    $scope.pageCount = 4;
    $scope.pages = [0, 1, 2, 3];
    $scope.currentPage = 0;

    $scope.actionSetPage = setPage;

	$scope.$watch('freetext', populate);
	$scope.$watch('currentPage', populate);
}<|endoftext|>


<commit_before>/*
   Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.

   This file is licensed under the Apache License, Version 2.0 (the "License").
   You may not use this file except in compliance with the License. A copy of
   the License is located at

    http://aws.amazon.com/apache2.0/

   This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied. See the License for the
   specific language governing permissions and limitations under the License.

   ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
   https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-send-receive-messages.html
*/

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create SQS service object
var sqs = new AWS.SQS({apiVersion: '2012-11-05'});

var queueURL = "QUEUE_URL";

var params = {
 AttributeNames: [
    "SentTimestamp"
 ],
 MaxNumberOfMessages: 1,
 MessageAttributeNames: [
    "All"
 ],
 QueueUrl: queueURL,
 VisibilityTimeout: 0,
 WaitTimeSeconds: 0
};

sqs.receiveMessage(params, function(err, data) {
  if (err) {
    console.log("Receive Error", err);
  } else if (data.Messages) {
    var deleteParams = {
      QueueUrl: queueURL,
      ReceiptHandle: data.Messages[0].ReceiptHandle
    };
    sqs.deleteMessage(deleteParams, function(err, data) {
      if (err) {
        console.log("Delete Error", err);
      } else {
        console.log("Message Deleted", data);
      }
    });
  }
});
<commit_msg>Update sqs_receivemessage.js<commit_after>// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-send-receive-messages.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create SQS service object
var sqs = new AWS.SQS({apiVersion: '2012-11-05'});

var queueURL = "QUEUE_URL";

var params = {
 AttributeNames: [
    "SentTimestamp"
 ],
 MaxNumberOfMessages: 1,
 MessageAttributeNames: [
    "All"
 ],
 QueueUrl: queueURL,
 VisibilityTimeout: 0,
 WaitTimeSeconds: 0
};

sqs.receiveMessage(params, function(err, data) {
  if (err) {
    console.log("Receive Error", err);
  } else if (data.Messages) {
    var deleteParams = {
      QueueUrl: queueURL,
      ReceiptHandle: data.Messages[0].ReceiptHandle
    };
    sqs.deleteMessage(deleteParams, function(err, data) {
      if (err) {
        console.log("Delete Error", err);
      } else {
        console.log("Message Deleted", data);
      }
    });
  }
});
<|endoftext|>


<commit_before>const Discord = require("discord.js");
const fs = require("fs");
const date = require("date");
const bot = new Discord.Client();
const prefix = "!";
const botToken = require("./bottoken");

bot.on("ready", () => {
    console.log("Klar");
    bot.user.setGame("Skriv !help för hjälp.");
});

var dabRespond = [
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Vad är det du inte förstår?",
    "Jävla människor ska alltid komma och tjata",
    "Okej då, ***DAB***"
];

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var weekNumber = (new Date()).getWeek();
var widthSchema = "600"
var heightSchema = "600"

var schemaLink = "http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+weekNumber+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847"

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

    if (!message.content.startsWith(prefix)) return;
    if (message.author.bot) return;

    //console.log(test);

    var split = message.content.substring(prefix.length).split(' ');

    switch (split[0].toLowerCase()) {

        case "help":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Kommandon:", bot.user.avatarURL)
                    .addField("Allmäna kommandon:", "!help - visar denna meny\n!github - skickar länken till botens github repo\n!ping - visar botens internal ping (för felsökning)")
                    .addField("Skolrelaterade kommandon:", "!schema - visar veckans schema")
                    .setColor("0x111111")
            });
            break;
        case "schema":
            message.channel.send({
            embed: new Discord.RichEmbed()
                .setAuthor("Schema:", bot.user.avatarURL)
                .setImage(schemaLink)
                .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        case "github":
            message.author.send("https://github.com/ChilladeChillin/ITGDiscordBot");
            break;
        case "dab":
            message.channel.send(dabRespond[Math.floor(Math.random() * dabRespond.length)]);
            break;
        case "say":
            var textFromSender = message.content;
            message.delete(0);
            if (message.author.id==="164283691802165250") {
                message.channel.send(message.content.substring(5));
                break;
            }
            else {
                break;
            }
        case "ping":
            message.channel.send(bot.ping+" ms");
            break;

        //case "bordejag"
            //[Math.floor(Math.random() * bordejag.length)]
    }
});

bot.login(botToken);<commit_msg>La till funktionen !hex<commit_after>const Discord = require("discord.js");
const fs = require("fs");
const date = require("date");
const bot = new Discord.Client();
const prefix = "!";
const botToken = require("./bottoken");

bot.on("ready", () => {
    console.log("Klar");
    bot.user.setGame("Skriv !help för hjälp.");
});

var dabRespond = [
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Vad är det du inte förstår?",
    "Jävla människor ska alltid komma och tjata",
    "Okej då, ***DAB***"
];

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var weekNumber = (new Date()).getWeek();
var widthSchema = "600"
var heightSchema = "600"

var schemaLink = "http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+weekNumber+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847"

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

    if (!message.content.startsWith(prefix)) return;
    if (message.author.bot) return;

    //console.log(test);

    var split = message.content.substring(prefix.length).split(' ');

    switch (split[0].toLowerCase()) {

        case "help":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Kommandon:", bot.user.avatarURL)
                    .addField("Allmäna kommandon:", "!help - visar denna meny\n!github - skickar länken till botens github repo\n!ping - visar botens internal ping (för felsökning)")
                    .addField("Skolrelaterade kommandon:", "!schema - visar veckans schema\n!hex - ger dig en slumpmässig färg")
                    .setColor("0x111111")
            });
            break;
        case "schema":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Schema:")
                    .setImage(schemaLink)
                    .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        case "github":
            message.author.send("https://github.com/ChilladeChillin/ITGDiscordBot");
            break;
        case "dab":
            message.channel.send(dabRespond[Math.floor(Math.random() * dabRespond.length)]);
            break;
        case "say":
            var textFromSender = message.content;
            message.delete(0);
            if (message.author.id==="164283691802165250") {
                message.channel.send(message.content.substring(5));
                break;
            }
            else {
                break;
            }
        case "ping":
            message.channel.send(bot.ping+" ms");
            break;
        case "hex":
            var randomhex = ("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6);
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Hex:")
                    .setDescription("#"+randomhex)
                    .setColor("0x"+randomhex)
            });
        //case "bordejag"
            //[Math.floor(Math.random() * bordejag.length)]
    }
});

bot.login(botToken);<|endoftext|>


<commit_before>$(document).ready(function() {
  if (window.location.hash) {
    anchor = window.location.hash.substr(1);
    $.scrollTo($('div#main_content div#' + anchor + '_list').position().top-100, 1000, {queue:true});
  };

  $('#header_content a').click(function(evt){
    evt.preventDefault();
  });

  $('a#features_menu_link').click(function(e) {
    e.stopPropagation();
    $.scrollTo($('div#main_content div#features_list').position().top-100, 1000, {queue:true});
  });
  $('a#pages_menu_link').click(function(e) {
    e.stopPropagation();
    $.scrollTo($('div#main_content div#pages_list').position().top-100, 1000, {queue:true});
  });
  $('a#settings_menu_link').click(function(e) {
    e.stopPropagation();
    $.scrollTo($('div#main_content div#settings_list').position().top-100, 1000, {queue:true});
  });

  $('div.setting_value a').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $('div.edit_value').hide();
    $('div.setting_value').show();
    var clickedId = $(this).parent().parent().attr("id");
    $(this).parent().hide();
    $('div.settings_list_container ul li#'+clickedId+' div.edit_value').show();
    $('div.settings_list_container ul li#'+clickedId+' div.edit_value input[type="text"]').focus();
  });

  $('span.cancel_value a').click(function(e) {
    e.preventDefault();
    e.stopPropagation();

    var clickedId = $(this).parent().parent().parent().attr("id");
    $(this).parent().parent().hide();
    $('div.settings_list_container ul li#'+clickedId+' div.setting_value').show();
    var previousVal = $('div.settings_list_container ul li#'+clickedId+' div.edit_value input[type="hidden"]').val();
    $('div.settings_list_container ul li#'+clickedId+' div.edit_value input[type="text"]').val(previousVal);
  });

  var column_width = null,
      first_column_position = 1,
      table_container_width = parseInt($('#features_table').outerWidth()),
      columns_widths = $('div#features_table table tr.header th').map(function(){
        return parseInt($(this).outerWidth());
      }),
      visible_columns_width = 0,
      current_pos = -1,
      moves = $.map(columns_widths, function(val, i){
        visible_columns_width += val;
        value = -(visible_columns_width - table_container_width);
        if (value < 0) {
          return value;
        };
      });

  $('#scroll_left').click(function(evt){
    evt.preventDefault();

    if (current_pos < 0) {
      return;
    }else if(current_pos >= 0){
      current_pos -= 1;
    };

    $('#features_table table').animate({'left': (moves[current_pos] || 0) + 'px'}, 'fast');
  })

  $('#scroll_right').click(function(evt){
    evt.preventDefault();

    if (current_pos < 0) {
      current_pos = 0;
    }else if (current_pos >= 0 && current_pos < moves.length - 1) {
      current_pos += 1;
    };

    $('#features_table table').animate({'left': moves[current_pos] + 'px'}, 'fast');
  })

 });
<commit_msg>Fix a bug not allowing logged in users to logout from dashboard<commit_after>$(document).ready(function() {
  if (window.location.hash) {
    anchor = window.location.hash.substr(1);
    $.scrollTo($('div#main_content div#' + anchor + '_list').position().top-100, 1000, {queue:true});
  };

  // $('#header_content a').click(function(evt){
  //   evt.preventDefault();
  // });

  $('a#features_menu_link').click(function(e) {
    e.stopPropagation();
    $.scrollTo($('div#main_content div#features_list').position().top-100, 1000, {queue:true});
  });
  $('a#pages_menu_link').click(function(e) {
    e.stopPropagation();
    $.scrollTo($('div#main_content div#pages_list').position().top-100, 1000, {queue:true});
  });
  $('a#settings_menu_link').click(function(e) {
    e.stopPropagation();
    $.scrollTo($('div#main_content div#settings_list').position().top-100, 1000, {queue:true});
  });

  $('div.setting_value a').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $('div.edit_value').hide();
    $('div.setting_value').show();
    var clickedId = $(this).parent().parent().attr("id");
    $(this).parent().hide();
    $('div.settings_list_container ul li#'+clickedId+' div.edit_value').show();
    $('div.settings_list_container ul li#'+clickedId+' div.edit_value input[type="text"]').focus();
  });

  $('span.cancel_value a').click(function(e) {
    e.preventDefault();
    e.stopPropagation();

    var clickedId = $(this).parent().parent().parent().attr("id");
    $(this).parent().parent().hide();
    $('div.settings_list_container ul li#'+clickedId+' div.setting_value').show();
    var previousVal = $('div.settings_list_container ul li#'+clickedId+' div.edit_value input[type="hidden"]').val();
    $('div.settings_list_container ul li#'+clickedId+' div.edit_value input[type="text"]').val(previousVal);
  });

  var column_width = null,
      first_column_position = 1,
      table_container_width = parseInt($('#features_table').outerWidth()),
      columns_widths = $('div#features_table table tr.header th').map(function(){
        return parseInt($(this).outerWidth());
      }),
      visible_columns_width = 0,
      current_pos = -1,
      moves = $.map(columns_widths, function(val, i){
        visible_columns_width += val;
        value = -(visible_columns_width - table_container_width);
        if (value < 0) {
          return value;
        };
      });

  $('#scroll_left').click(function(evt){
    evt.preventDefault();

    if (current_pos < 0) {
      return;
    }else if(current_pos >= 0){
      current_pos -= 1;
    };

    $('#features_table table').animate({'left': (moves[current_pos] || 0) + 'px'}, 'fast');
  })

  $('#scroll_right').click(function(evt){
    evt.preventDefault();

    if (current_pos < 0) {
      current_pos = 0;
    }else if (current_pos >= 0 && current_pos < moves.length - 1) {
      current_pos += 1;
    };

    $('#features_table table').animate({'left': moves[current_pos] + 'px'}, 'fast');
  })

 });
<|endoftext|>