<commit_before>
var common = require('./../config/common.js');
var configSmartPay = common.config();
var crypto = require('crypto');
var zlib = require('zlib');

module.exports = {

    // sets application payment data
    addApplicationData: function(appid, formFields, applicationDetail, application, userDocumentCount, loggedIn) {

        var documentCount = userDocumentCount.doc_count;
        var documentCountLabel = documentCount == 1 ? 'document.' : 'documents.';
        var orderData = 'You are paying to legalise ' + documentCount + ' ' + documentCountLabel;

        if(loggedIn === true) {
            orderData = orderData + '

When adding a new card, you\'ll see a \'Remember these details\' box. Untick this box if you don\'t want to save your card for future applications.';
        }

        formFields.merchantReference = application.unique_app_id;
        formFields.orderData = orderData;
        formFields.paymentAmount = Math.round(applicationDetail.payment_amount * 1e2); // multiply by 100 to get value in minor currency
        formFields.merchantReturnData = appid;

        formFields.allowedMethods = ''; //pre-selection of card type (obsolete)

        return formFields;
    },

    // set the date fields to one day in the future
    addDateFields: function(formFields) {

        var shipBeforeDate = new Date();
        shipBeforeDate.setDate(shipBeforeDate.getDate() + 1);
        var shipBeforeDateValue = shipBeforeDate.toISOString().substr(0, 10);

        var sessionValidityDate = new Date();
        sessionValidityDate.setMinutes(sessionValidityDate.getMinutes() + 25);
        var sessionValidityValue = sessionValidityDate.toISOString().substr(0, 19) + 'Z';

        // add date fields to form array
        formFields.shipBeforeDate = shipBeforeDateValue;
        formFields.sessionValidity = sessionValidityValue;

        // return to caller
        return formFields;
    },

    // adds data required for saving card details
    addOneClickFields : function(appid, formFields, userDetails, applicationDetail) {

        var oneclick_reference = applicationDetail.oneclick_reference;

        // if there is a user session active, get their recurring payment reference
        // and set the relevant optional fields in the SmartPay request object
        if (oneclick_reference != '0')
        {
            formFields.shopperReference = oneclick_reference;
            formFields.recurringContract = 'ONECLICK';
            formFields.shopperEmail = userDetails.email;
        }

        // return to caller
        return formFields;
    },

    lookupPaymentMethod : function(paymentMethod) {
        return configSmartPay.paymentMethods[paymentMethod];
    },

    // compress order data using gzip, encode in base64
    // also converts the order data into HTML fragment first
    compressAndEncodeOrderData : function (formFields) {

        // put order data value into HTML paragraph tags
        var htmlFragment = '
' + formFields.orderData + '
';

        // compress using gzip and encode in base64 format
        // (blocking call so no need for callback)
        htmlFragment = zlib.gzipSync(htmlFragment).toString('base64');

        // assign encoded value back into the formFields array
        formFields.orderData = htmlFragment;

        // return to caller
        return formFields;
    },

    // calculates the signature using HMAC code
    //
    //paymentAmount + currencyCode + shipBeforeDate + merchantReference + skinCode +
    //merchantAccount + sessionValidity + shopperEmail + shopperReference +
    //allowedMethods + blockedMethods + shopperStatement + billingAddressType
    calculateMerchantSignature: function(formFields) {

        // get HMAC secret key
        var hmacKey = configSmartPay.configs.HMAC;

        // get form field values
        var paymentAmount = formFields.paymentAmount;
        var currencyCode = configSmartPay.configs.currencyCode;
        var shipBeforeDate = formFields.shipBeforeDate;
        var merchantReference = formFields.merchantReference;
        var skinCode = configSmartPay.configs.skinCode;
        var merchantAccount = configSmartPay.configs.merchantAccount;
        var sessionValidity = formFields.sessionValidity;
        var shopperEmail = formFields.shopperEmail; //optional
        var shopperReference = formFields.shopperReference; //optional
        var recurringContract = formFields.recurringContract; //optional
        var allowedMethods = formFields.allowedMethods;
        var blockedMethods = '';
        var shopperStatement = '';
        var billingAddressType = '';
        var merchantReturnData = formFields.merchantReturnData;

        // concatenate form fields into one string
        var formFieldsString = paymentAmount + currencyCode + shipBeforeDate + merchantReference + skinCode +
                               merchantAccount + sessionValidity + shopperEmail + shopperReference + recurringContract +
                               allowedMethods + blockedMethods + shopperStatement + billingAddressType + merchantReturnData;

        // calculate HMAC string and encode in base64
        var hash = crypto.createHmac('sha1', hmacKey).update(formFieldsString).digest('base64');

        // return to caller
        return hash;
    },

    // decode signature returned from SmartPay to verify data integrity using HMAC code
    //
    // authResult + pspReference + merchantReference + skinCode + merchantReturnData
    decodeReturnedMerchantSignature: function(queryString) {

        // get HMAC secret key
        var hmacKey = configSmartPay.configs.HMAC;

        // get hold of query string parameters
        var authResult = queryString.authResult;
        var pspReference = queryString.pspReference;
        var merchantReference = queryString.merchantReference;
        var skinCode = queryString.skinCode;
        var merchantReturnData = ((queryString.merchantReturnData !== undefined) ? queryString.merchantReturnData : '');

        // encoded signature we are validating against
        var merchantSig = queryString.merchantSig;

        // concatenate query string values into one string
        var queryStringValues = authResult + pspReference + merchantReference + skinCode + merchantReturnData;

        // calculate HMAC string and encode in base64
        var hash = crypto.createHmac('sha1', hmacKey).update(queryStringValues).digest('base64');

        return (hash === merchantSig);
    },

    buildParameters: function(formFields, merchantSignature) {
        var params = {
            paymentAmount      : formFields.paymentAmount,
            currencyCode       : configSmartPay.configs.currencyCode,
            shipBeforeDate     : formFields.shipBeforeDate,
            merchantReference  : formFields.merchantReference,
            skinCode           : configSmartPay.configs.skinCode,
            merchantAccount    : configSmartPay.configs.merchantAccount,
            sessionValidity    : formFields.sessionValidity,
            shopperEmail       : formFields.shopperEmail,
            shopperReference   : formFields.shopperReference,
            recurringContract  : formFields.recurringContract,
            allowedMethods     : formFields.allowedMethods,
            blockedMethods     : '',
            shopperStatement   : '',
            billingAddressType : '',
            skipSelection      : ((formFields.allowedMethods !== '') ? 'true' : ''),
            orderData          : formFields.orderData,
            merchantReturnData : formFields.merchantReturnData,
            resURL             : configSmartPay.configs.resultURL,
            merchantSig        : merchantSignature
        };

        return params;
    },

    loggedInStatus: function amILoggedIn(req) {
        if (req.session && req.session.passport && req.session.passport.user) {
            return true;
        }
        else {
            return false;
        }
    },

    /**
     * Get the email address of the current in User
     * @param req
     * @returns email {string}
     */
    loggedInUserEmail: function whatsUsersEmail(req)
    {
        if (req.session && req.session.passport && req.session.passport.user && req.session.email && req.session.email !== null) {
            return req.session.email;
        } else {
            return 'Not Logged In';
        }
    },

    isSessionValid: function getSomeSessionInfo(req) {
        if (typeof(req.session.appSubmittedStatus) != 'undefined') {
            console.log('------------------------------' + req.session.appSubmittedStatus);
            console.log('session is valid');
            return true;
        }else{
            console.log('session is not valid');
            return false;
        }
    }

};
<commit_msg>Change log lines<commit_after>
var common = require('./../config/common.js');
var configSmartPay = common.config();
var crypto = require('crypto');
var zlib = require('zlib');

module.exports = {

    // sets application payment data
    addApplicationData: function(appid, formFields, applicationDetail, application, userDocumentCount, loggedIn) {

        var documentCount = userDocumentCount.doc_count;
        var documentCountLabel = documentCount == 1 ? 'document.' : 'documents.';
        var orderData = 'You are paying to legalise ' + documentCount + ' ' + documentCountLabel;

        if(loggedIn === true) {
            orderData = orderData + '

When adding a new card, you\'ll see a \'Remember these details\' box. Untick this box if you don\'t want to save your card for future applications.';
        }

        formFields.merchantReference = application.unique_app_id;
        formFields.orderData = orderData;
        formFields.paymentAmount = Math.round(applicationDetail.payment_amount * 1e2); // multiply by 100 to get value in minor currency
        formFields.merchantReturnData = appid;

        formFields.allowedMethods = ''; //pre-selection of card type (obsolete)

        return formFields;
    },

    // set the date fields to one day in the future
    addDateFields: function(formFields) {

        var shipBeforeDate = new Date();
        shipBeforeDate.setDate(shipBeforeDate.getDate() + 1);
        var shipBeforeDateValue = shipBeforeDate.toISOString().substr(0, 10);

        var sessionValidityDate = new Date();
        sessionValidityDate.setMinutes(sessionValidityDate.getMinutes() + 25);
        var sessionValidityValue = sessionValidityDate.toISOString().substr(0, 19) + 'Z';

        // add date fields to form array
        formFields.shipBeforeDate = shipBeforeDateValue;
        formFields.sessionValidity = sessionValidityValue;

        // return to caller
        return formFields;
    },

    // adds data required for saving card details
    addOneClickFields : function(appid, formFields, userDetails, applicationDetail) {

        var oneclick_reference = applicationDetail.oneclick_reference;

        // if there is a user session active, get their recurring payment reference
        // and set the relevant optional fields in the SmartPay request object
        if (oneclick_reference != '0')
        {
            formFields.shopperReference = oneclick_reference;
            formFields.recurringContract = 'ONECLICK';
            formFields.shopperEmail = userDetails.email;
        }

        // return to caller
        return formFields;
    },

    lookupPaymentMethod : function(paymentMethod) {
        return configSmartPay.paymentMethods[paymentMethod];
    },

    // compress order data using gzip, encode in base64
    // also converts the order data into HTML fragment first
    compressAndEncodeOrderData : function (formFields) {

        // put order data value into HTML paragraph tags
        var htmlFragment = '
' + formFields.orderData + '
';

        // compress using gzip and encode in base64 format
        // (blocking call so no need for callback)
        htmlFragment = zlib.gzipSync(htmlFragment).toString('base64');

        // assign encoded value back into the formFields array
        formFields.orderData = htmlFragment;

        // return to caller
        return formFields;
    },

    // calculates the signature using HMAC code
    //
    //paymentAmount + currencyCode + shipBeforeDate + merchantReference + skinCode +
    //merchantAccount + sessionValidity + shopperEmail + shopperReference +
    //allowedMethods + blockedMethods + shopperStatement + billingAddressType
    calculateMerchantSignature: function(formFields) {

        // get HMAC secret key
        var hmacKey = configSmartPay.configs.HMAC;

        // get form field values
        var paymentAmount = formFields.paymentAmount;
        var currencyCode = configSmartPay.configs.currencyCode;
        var shipBeforeDate = formFields.shipBeforeDate;
        var merchantReference = formFields.merchantReference;
        var skinCode = configSmartPay.configs.skinCode;
        var merchantAccount = configSmartPay.configs.merchantAccount;
        var sessionValidity = formFields.sessionValidity;
        var shopperEmail = formFields.shopperEmail; //optional
        var shopperReference = formFields.shopperReference; //optional
        var recurringContract = formFields.recurringContract; //optional
        var allowedMethods = formFields.allowedMethods;
        var blockedMethods = '';
        var shopperStatement = '';
        var billingAddressType = '';
        var merchantReturnData = formFields.merchantReturnData;

        // concatenate form fields into one string
        var formFieldsString = paymentAmount + currencyCode + shipBeforeDate + merchantReference + skinCode +
                               merchantAccount + sessionValidity + shopperEmail + shopperReference + recurringContract +
                               allowedMethods + blockedMethods + shopperStatement + billingAddressType + merchantReturnData;

        // calculate HMAC string and encode in base64
        var hash = crypto.createHmac('sha1', hmacKey).update(formFieldsString).digest('base64');

        // return to caller
        return hash;
    },

    // decode signature returned from SmartPay to verify data integrity using HMAC code
    //
    // authResult + pspReference + merchantReference + skinCode + merchantReturnData
    decodeReturnedMerchantSignature: function(queryString) {

        // get HMAC secret key
        var hmacKey = configSmartPay.configs.HMAC;

        // get hold of query string parameters
        var authResult = queryString.authResult;
        var pspReference = queryString.pspReference;
        var merchantReference = queryString.merchantReference;
        var skinCode = queryString.skinCode;
        var merchantReturnData = ((queryString.merchantReturnData !== undefined) ? queryString.merchantReturnData : '');

        // encoded signature we are validating against
        var merchantSig = queryString.merchantSig;

        // concatenate query string values into one string
        var queryStringValues = authResult + pspReference + merchantReference + skinCode + merchantReturnData;

        // calculate HMAC string and encode in base64
        var hash = crypto.createHmac('sha1', hmacKey).update(queryStringValues).digest('base64');

        return (hash === merchantSig);
    },

    buildParameters: function(formFields, merchantSignature) {
        var params = {
            paymentAmount      : formFields.paymentAmount,
            currencyCode       : configSmartPay.configs.currencyCode,
            shipBeforeDate     : formFields.shipBeforeDate,
            merchantReference  : formFields.merchantReference,
            skinCode           : configSmartPay.configs.skinCode,
            merchantAccount    : configSmartPay.configs.merchantAccount,
            sessionValidity    : formFields.sessionValidity,
            shopperEmail       : formFields.shopperEmail,
            shopperReference   : formFields.shopperReference,
            recurringContract  : formFields.recurringContract,
            allowedMethods     : formFields.allowedMethods,
            blockedMethods     : '',
            shopperStatement   : '',
            billingAddressType : '',
            skipSelection      : ((formFields.allowedMethods !== '') ? 'true' : ''),
            orderData          : formFields.orderData,
            merchantReturnData : formFields.merchantReturnData,
            resURL             : configSmartPay.configs.resultURL,
            merchantSig        : merchantSignature
        };

        return params;
    },

    loggedInStatus: function amILoggedIn(req) {
        if (req.session && req.session.passport && req.session.passport.user) {
            return true;
        }
        else {
            return false;
        }
    },

    /**
     * Get the email address of the current in User
     * @param req
     * @returns email {string}
     */
    loggedInUserEmail: function whatsUsersEmail(req)
    {
        if (req.session && req.session.passport && req.session.passport.user && req.session.email && req.session.email !== null) {
            return req.session.email;
        } else {
            return 'Not Logged In';
        }
    },

    isSessionValid: function getSomeSessionInfo(req) {
        if (typeof(req.session.appSubmittedStatus) != 'undefined') {
            console.log('session is valid - proceed to payment unsuccessful page');
            return true;
        }else{
            console.log('session is invalid - proceed to session expiry page');
            return false;
        }
    }

};
<|endoftext|>


<commit_before>var User = require('./../../models/user').User;
var Chat = require('./../../models/chat').Chat;
var async = require('async');

var socket_outgoing = {
  UPDATE_ONLINE: 'CHAT_IN_UPDATE_ONLINE',
  INCREMENT_ONLINE: 'CHAT_IN_INCREMENET_ONLINE',
  DECREMENT_ONLINE: 'CHAT_IN_DECREMENT_ONLINE',
  MUTE_USER: 'CHAT_IN_MUTE_USER',
  UNMUTE_USER: 'CHAT_IN_UNMUTE_USER',
  BAN_USER: 'CHAT_IN_BAN_USER',
  UNBAN_USER: 'CHAT_IN_UNBAN_USER',
  RECEIVE_MESSAGE: 'CHAT_IN_RECEIVE_MESSAGE',
  RELOAD_PAGE: 'CHAT_IN_RELOAD_PAGE',
  CLEAR_CHAT: 'CHAT_IN_CLEAR_CHAT',
  BOT_MESSAGE: 'CHAT_IN_BOT_MESSAGE',
  CHAT_MODE: 'CHAT_IN_CHAT_MODE',
  INIT_CHAT: 'CHAT_IN_INIT_CHAT',
  ALERT: 'ALERT'
};

var socket_incoming = {
  SEND_CHAT: 'CHAT_OUT_SEND_MESSAGE',
  MUTE_USER: 'CHAT_OUT_MUTE_USER',
  UNMUTE_USER: 'CHAT_OUT_UNMUTE_USER',
  BAN_USER: 'CHAT_OUT_BAN_USER',
  UNBAN_USER: 'CHAT_OUT_UNBAN_USER',
  RELOAD_PAGE: 'CHAT_OUT_RELOAD_PAGE',
  CLEAR_CHAT: 'CHAT_OUT_CLEAR_CHAT',
  BOT_MESSAGE: 'CHAT_OUT_BOT_MESSAGE',
  CHAT_MODE: 'CHAT_OUT_CHAT_MODE',
  INIT_CHAT: 'CHAT_OUT_INIT_CHAT'
};

var RECENT_MESSAGE_CAP =  50;

var recentMessages = []; //queue the 50 most recent messages for newcomers so we dont have to query the database

module.exports = function(socket, io) {

  socket.on(socket_incoming.INIT_CHAT, function() {
    var currentUsers = Object.keys(io.sockets.sockets).length;
    console.log(currentUsers);

    if (recentMessages.length < RECENT_MESSAGE_CAP) { //we need to query the database for messages if we dont have enough recent messages (very rarely)
      var previousMessages = [];

      var data = [];

      async.series([
        function(callback) {
          Chat.getRecentMessages(RECENT_MESSAGE_CAP, function(err, result) {
            if (!err && result) {
              data = result;
              callback();
            } else {
              callback(err);
            }
          });
        },
        function(callback) {
          var counter = 0;
          if (data.length > 0) {
            data.forEach(function(obj) {
              obj.formatChatMessage(function(err, msg) {
                if (!err && msg) {
                  previousMessages.push(msg);
                  counter++;
                  if (data.length == counter) {
                    callback();
                  }
                } else {
                  callback(err);
                }
              });
            });
          } else {
            callback(new Error('No local data available'));
          }
        }
      ], function(err, results) {
        if (!err) {
          socket.emit(socket_outgoing.INIT_CHAT, {
            previous_messages: previousMessages.reverse(),
            current_users: currentUsers
          });
          recentMessages = previousMessages.reverse();
        } else {
          socket.emit(socket_outgoing.ALERT, {
            header: 'Chat Error',
            type: 'error',
            message: 'Unable to load previous messages. Error: ' + err.message
          });
        }
      });
    } else {
      var reversedMessages = [].concat(recentMessages).reverse();
      socket.emit(socket_outgoing.INIT_CHAT, {
        current_users: currentUsers,
        previous_messages: reversedMessages
      });
    }

    socket.broadcast.emit(socket_outgoing.INCREMENT_ONLINE);
  });

  socket.on(socket_incoming.SEND_CHAT, function(data) {
    if (socket.request.session.passport.user) {
      User.findById(socket.request.session.passport.user, function(err, user) {
        if (!err && user) {
          var chatData = {
            id: user._id,
            profile_name: user.name,
            profile_img: user.photo,
            rank: user.rank,
            text: data.text
          }
          io.emit(socket_outgoing.RECEIVE_MESSAGE, chatData);
          recentMessages.unshift(chatData);
          recentMessages.length = RECENT_MESSAGE_CAP;

          var chatModel = new Chat({
            sender_id: user._id,
            content: data.text
          });
          chatModel.save(function(err) {
            if (err) {
              socket.emit(socket_outgoing.ALERT, {
                type: 'error',
                message: 'Error while saving your chat to the database. Please contact the developers.',
                header: 'Chat Error'
              });
            }
          });
        } else {
          socket.emit(socket_outgoing.ALERT, {
            type: 'error',
            message: 'Error while processing. Please contact developers with this message: ' + err.message,
            header: 'Chat Error'
          });
        }
      });
    } else {
      socket.emit(socket_outgoing.ALERT, {
        type: 'error',
        message: 'You are not logged in.',
        header: 'Chat Error'
      });
    }
  });

  socket.on(socket_incoming.MUTE_USER, function(data) {

  });

  socket.on(socket_outgoing.UNMUTE_USER, function(data) {

  });

  socket.on(socket_outgoing.BAN_USER, function(data) {

  });

  socket.on(socket_outgoing.UNBAN_USER, function(data) {

  });

  socket.on(socket_outgoing.RELOAD_PAGE, function(data) {

  });

  socket.on(socket_outgoing.CLEAR_CHAT, function(data) {

  });

  socket.on(socket_outgoing.BOT_MESSAGE, function(data) {

  });

  socket.on(socket_outgoing.CHAT_MODE, function(data) {

  });

  socket.on('disconnect', function() {
    io.emit(socket_outgoing.DECREMENT_ONLINE);
  });
}
<commit_msg>heroku does not like my sockets<commit_after>var User = require('./../../models/user').User;
var Chat = require('./../../models/chat').Chat;
var async = require('async');

var socket_outgoing = {
  UPDATE_ONLINE: 'CHAT_IN_UPDATE_ONLINE',
  INCREMENT_ONLINE: 'CHAT_IN_INCREMENET_ONLINE',
  DECREMENT_ONLINE: 'CHAT_IN_DECREMENT_ONLINE',
  MUTE_USER: 'CHAT_IN_MUTE_USER',
  UNMUTE_USER: 'CHAT_IN_UNMUTE_USER',
  BAN_USER: 'CHAT_IN_BAN_USER',
  UNBAN_USER: 'CHAT_IN_UNBAN_USER',
  RECEIVE_MESSAGE: 'CHAT_IN_RECEIVE_MESSAGE',
  RELOAD_PAGE: 'CHAT_IN_RELOAD_PAGE',
  CLEAR_CHAT: 'CHAT_IN_CLEAR_CHAT',
  BOT_MESSAGE: 'CHAT_IN_BOT_MESSAGE',
  CHAT_MODE: 'CHAT_IN_CHAT_MODE',
  INIT_CHAT: 'CHAT_IN_INIT_CHAT',
  ALERT: 'ALERT'
};

var socket_incoming = {
  SEND_CHAT: 'CHAT_OUT_SEND_MESSAGE',
  MUTE_USER: 'CHAT_OUT_MUTE_USER',
  UNMUTE_USER: 'CHAT_OUT_UNMUTE_USER',
  BAN_USER: 'CHAT_OUT_BAN_USER',
  UNBAN_USER: 'CHAT_OUT_UNBAN_USER',
  RELOAD_PAGE: 'CHAT_OUT_RELOAD_PAGE',
  CLEAR_CHAT: 'CHAT_OUT_CLEAR_CHAT',
  BOT_MESSAGE: 'CHAT_OUT_BOT_MESSAGE',
  CHAT_MODE: 'CHAT_OUT_CHAT_MODE',
  INIT_CHAT: 'CHAT_OUT_INIT_CHAT'
};

var RECENT_MESSAGE_CAP =  50;

var recentMessages = []; //queue the 50 most recent messages for newcomers so we dont have to query the database

module.exports = function(socket, io) {

  socket.on(socket_incoming.INIT_CHAT, function() {
    var currentUsers = Object.keys(io.sockets.sockets).length;
    console.log(currentUsers);

    /*if (recentMessages.length < RECENT_MESSAGE_CAP) { //we need to query the database for messages if we dont have enough recent messages (very rarely)
      var previousMessages = [];

      var data = [];

      async.series([
        function(callback) {
          Chat.getRecentMessages(RECENT_MESSAGE_CAP, function(err, result) {
            if (!err && result) {
              data = result;
              callback();
            } else {
              callback(err);
            }
          });
        },
        function(callback) {
          var counter = 0;
          if (data.length > 0) {
            data.forEach(function(obj) {
              obj.formatChatMessage(function(err, msg) {
                if (!err && msg) {
                  previousMessages.push(msg);
                  counter++;
                  if (data.length == counter) {
                    callback();
                  }
                } else {
                  callback(err);
                }
              });
            });
          } else {
            callback(new Error('No local data available'));
          }
        }
      ], function(err, results) {
        if (!err) {
          socket.emit(socket_outgoing.INIT_CHAT, {
            previous_messages: previousMessages.reverse(),
            current_users: currentUsers
          });
          recentMessages = previousMessages.reverse();
        } else {
          socket.emit(socket_outgoing.ALERT, {
            header: 'Chat Error',
            type: 'error',
            message: 'Unable to load previous messages. Error: ' + err.message
          });
        }
      });
    } else {
      var reversedMessages = [].concat(recentMessages).reverse();
      socket.emit(socket_outgoing.INIT_CHAT, {
        current_users: currentUsers,
        previous_messages: reversedMessages
      });
    }*/

    socket.broadcast.emit(socket_outgoing.INCREMENT_ONLINE);
  });

  socket.on(socket_incoming.SEND_CHAT, function(data) {
    if (socket.request.session.passport.user) {
      User.findById(socket.request.session.passport.user, function(err, user) {
        if (!err && user) {
          var chatData = {
            id: user._id,
            profile_name: user.name,
            profile_img: user.photo,
            rank: user.rank,
            text: data.text
          }
          io.emit(socket_outgoing.RECEIVE_MESSAGE, chatData);
          recentMessages.unshift(chatData);
          recentMessages.length = RECENT_MESSAGE_CAP;

          var chatModel = new Chat({
            sender_id: user._id,
            content: data.text
          });
          chatModel.save(function(err) {
            if (err) {
              socket.emit(socket_outgoing.ALERT, {
                type: 'error',
                message: 'Error while saving your chat to the database. Please contact the developers.',
                header: 'Chat Error'
              });
            }
          });
        } else {
          socket.emit(socket_outgoing.ALERT, {
            type: 'error',
            message: 'Error while processing. Please contact developers with this message: ' + err.message,
            header: 'Chat Error'
          });
        }
      });
    } else {
      socket.emit(socket_outgoing.ALERT, {
        type: 'error',
        message: 'You are not logged in.',
        header: 'Chat Error'
      });
    }
  });

  socket.on(socket_incoming.MUTE_USER, function(data) {

  });

  socket.on(socket_outgoing.UNMUTE_USER, function(data) {

  });

  socket.on(socket_outgoing.BAN_USER, function(data) {

  });

  socket.on(socket_outgoing.UNBAN_USER, function(data) {

  });

  socket.on(socket_outgoing.RELOAD_PAGE, function(data) {

  });

  socket.on(socket_outgoing.CLEAR_CHAT, function(data) {

  });

  socket.on(socket_outgoing.BOT_MESSAGE, function(data) {

  });

  socket.on(socket_outgoing.CHAT_MODE, function(data) {

  });

  socket.on('disconnect', function() {
    console.log('discnnECTING');
    io.emit(socket_outgoing.DECREMENT_ONLINE);
  });
}
<|endoftext|>


<commit_before>/*jshint esversion:6*/
'use strict';

/**
 * This is the actual sort implementation.
 */
function sort(beans) {
    //TODO: we should actually sort first by priority if
    //      it was previously declared
    let graph = createGraph(beans);
    let stack = weightPriorityByDependencies(beans, graph, true);

    beans.map(plugin => plugin.priority = stack[plugin.id].priority);

    /*
     * Let's sort our modules based on their
     * collected weight.
     */
    beans.sort((a, b) => {
        if (a.priority < b.priority) return 1;
    });

    return beans;
}

/**
 * Provided a list of modules and their
 * dependencies, return an array containing
 * the modules ids ordered so that we can
 * load dependencies first.
 *
 * @argument {Object} graph Object containing modules
 *                          and their dependencies.
 *
 * @argument {Boolean} allowImplicits Should we create
 *                                    missing modules.
 *
 * @return {Array}  List of modules ordered by most
 *                  relied upon first.
 */
function weightPriorityByDependencies(beans, graph, allowImplicits = true) {
    /*
     * store weight for each module
     */
    let stack = {};

    /*
     * Collect all available modules.
     */
    let modules = Object.keys(graph);

    /*
     * All modules start with an
     * equal weight.
     */
    modules.map((id) => stack[id] = { priority: 0 });

    /*
     * Collect the weight for each module
     */
    modules.map((id) => weight(stack, id, graph[id]));

    /*
     * Our system might try to recover from
     * missing dependencies elsewhere, like
     * if we support 'global' dependencies
     * handled by require, etc.
     */
    function addMissingDependency(dependency) {
        //TODO: review how this should work exactly :P
        beans[dependency] = {
            id: dependency,
            priority: 1,
            dependencies: [],
            isLocal: false,
            //TODO: This could potentially fail.
            //How do we handle it?
            plugin: require(dependency)
        };

        graph[dependency] = [];
        stack[dependency] = 1;
    }

    function weight(stack, id, dependencies = [], i = 0) {
        if (i > 10) throw Error('Cyclical dependency found: ' + findCyclicDependencies(graph, id));

        if (!dependencies.length) return;

        dependencies.map(dependency => {
            if (!stack.hasOwnProperty(dependency)) {
                if (!allowImplicits) throw new Error('Dependency "' + dependency + '" not a module.');
                addMissingDependency(dependency);
            }

            /*
             * increase the count of the module
             * we are dependent on.
             */
            stack[dependency].priority++;

            /*
             * now, do the same for the dependency's
             * dependencies...
             */
            weight(stack, dependency, graph[dependency], ++i);
        });
    }

    /*
     * If we allow implicits and we actually
     * introduced an implicit dependency we
     * might want to re-generate our module
     * list.
     */
    if (allowImplicits) modules = Object.keys(graph);

    return stack;
}

/**
 * Just go over our graph tree and
 * figure out where it went wrong.
 */
function findCyclicDependencies(graph, identifier) {
    let stack = {};

    function find(id) {
        if (stack.hasOwnProperty(id)) return id === identifier;

        stack[id] = true;

        let found = (graph[id] || []).some(find);

        if (!found) delete stack[id];

        return found;
    }

    return find(identifier) ? Object.keys(stack).concat(identifier) : undefined;
}

/**
 * Build a structure that is easier
 * to work with.
 */
function createGraph(beans) {
    let out = {};
    beans.map((bean) => {
        out[bean.id] = bean.plugin.dependencies || [];
    });
    return out;
}

module.exports = sort;
module.exports.createGraph = createGraph;
module.exports.findCyclicDependencies = findCyclicDependencies;
module.exports.weightPriorityByDependencies = weightPriorityByDependencies;<commit_msg>clean up<commit_after>/*jshint esversion:6*/
'use strict';

/**
 * This is the actual sort implementation.
 */
function sort(beans) {
    //TODO: we should actually sort first by priority if
    //      it was previously declared
    let graph = createGraph(beans);
    let stack = weightPriorityByDependencies(beans, graph, true);

    beans.map(plugin => plugin.priority = stack[plugin.id].priority);

    /*
     * Let's sort our modules based on their
     * collected weight.
     */
    beans.sort((a, b) => {
        if (a.priority < b.priority) return 1;
    });

    return beans;
}

/**
 * Provided a list of modules and their
 * dependencies, return an array containing
 * the modules ids ordered so that we can
 * load dependencies first.
 *
 * @argument {Object} graph Object containing modules
 *                          and their dependencies.
 *
 * @argument {Boolean} allowImplicit Should we create
 *                                    missing modules.
 *
 * @return {Array}  List of modules ordered by most
 *                  relied upon first.
 */
function weightPriorityByDependencies(beans, graph, allowImplicit = true) {
    /*
     * store weight for each module
     */
    let stack = {};

    /*
     * Collect all available modules.
     */
    let modules = Object.keys(graph);

    /*
     * All modules start with an
     * equal weight.
     */
    modules.forEach(id => stack[id] = { priority: 0 });

    /*
     * Collect the weight for each module
     */
    modules.forEach(id => weight(stack, id, graph[id]));

    /*
     * Our system might try to recover from
     * missing dependencies elsewhere, like
     * if we support 'global' dependencies
     * handled by require, etc.
     */
    function addMissingDependency(dependency) {
        //TODO: review how this should work exactly :P
        beans[dependency] = {
            id: dependency,
            priority: 1,
            dependencies: [],
            isLocal: false,
            //TODO: This could potentially fail.
            //How do we handle it?
            plugin: require(dependency)
        };

        graph[dependency] = [];
        stack[dependency] = 1;
    }

    function weight(stack, id, dependencies = [], i = 0) {
        if (i > 10) throw Error('Cyclical dependency found: ' + findCyclicDependencies(graph, id));

        if (!dependencies.length) return;

        dependencies.map(dependency => {
            if (!stack.hasOwnProperty(dependency)) {
                if (!allowImplicit) throw new Error('Dependency "' + dependency + '" not a module.');
                addMissingDependency(dependency);
            }

            /*
             * increase the count of the module
             * we are dependent on.
             */
            stack[dependency].priority++;

            /*
             * now, do the same for the dependency's
             * dependencies...
             */
            weight(stack, dependency, graph[dependency], ++i);
        });
    }

    /*
     * If we allow implicit and we actually
     * introduced an implicit dependency we
     * might want to re-generate our module
     * list.
     */
    if (allowImplicit) modules = Object.keys(graph);

    return stack;
}

/**
 * Just go over our graph tree and
 * figure out where it went wrong.
 */
function findCyclicDependencies(graph, identifier) {
    let stack = {};

    function find(id) {
        if (stack.hasOwnProperty(id)) return id === identifier;

        stack[id] = true;

        let found = (graph[id] || []).some(find);

        if (!found) delete stack[id];

        return found;
    }

    return find(identifier) ? Object.keys(stack).concat(identifier) : undefined;
}

/**
 * Build a structure that is easier
 * to work with.
 */
function createGraph(beans) {
    let out = {};

    beans.map(bean => {
        out[bean.id] = bean.plugin.dependencies || [];
    });

    return out;
}

module.exports = sort;
module.exports.createGraph = createGraph;
module.exports.findCyclicDependencies = findCyclicDependencies;
module.exports.weightPriorityByDependencies = weightPriorityByDependencies;<|endoftext|>


<commit_before>'use strict';

// Load environment configurations
require('dotenv').load();

// Dependencies
var pkg = require('../package');
var sparkpost = require('sparkpost');

// Constructor
var SparkpostTransport = function SparkpostTransport(options) {
  // Set required properties
  this.name = 'Sparkpost';
  this.version = pkg.version;
  options = options || {};

  // Set the SparkPost API Key (must have appropriate Transmission resource permissions)
  this.sparpostApiKey = process.env.SPARKPOST_API_KEY || options.sparkpostApiKey;
  this.sparkpostEmailClient = new sparkpost( this.sparkpostApiKey );

  // Set any options which are valid
  for( var opt in options ) {
    this[opt] = (options.hasOwnProperty( opt )) ? options[opt] : undefined;
  }

  return this;
};

SparkpostTransport.prototype.send = function send(payload, callback) {
  var email = {
    transmissionBody: {}
  };

  // Apply default options and override if provided in mail object
  email.transmissionBody.tags              = payload.tags || this.tags;
  email.transmissionBody.campaign_id       = payload.campaign_id || this.campaign_id;
  email.transmissionBody.metadata          = payload.metadata || this.metadata;
  email.transmissionBody.substitution_data = payload.substitution_data || this.substitution_data;
  email.transmissionBody.options           = payload.options || this.options;
  email.transmissionBody.content           = payload.content || this.content;
  email.transmissionBody.recipients        = payload.recipients || this.recipients;

  // Send the transmission using Sparkpost
  this.sparkpostClient.transmissions.send(email, function( err, res ) {
    if( err ) {
      return callback( err );
    } else {
      // Example successful Sparkpost transmission response:
      // { "results": { "total_rejected_recipients": 0, "total_accepted_recipients": 1, "id": "66123596945797072" } }
      return callback( null, {
        messageId: res.body.results.id,
        accepted: res.body.results.total_accepted_recipients,
        rejected: res.body.results.total_rejected_recipients
      });
    }
  });
};

module.exports = function(options) {
  return new SparkpostTransport(options);
};
<commit_msg>Include proper data path for overrides<commit_after>'use strict';

// Load environment configurations
require('dotenv').load();

// Dependencies
var pkg = require('../package');
var sparkpost = require('sparkpost');

// Constructor
var SparkpostTransport = function SparkpostTransport(options) {
  // Set required properties
  this.name = 'Sparkpost';
  this.version = pkg.version;
  options = options || {};

  // Set the SparkPost API Key (must have appropriate Transmission resource permissions)
  this.sparpostApiKey = process.env.SPARKPOST_API_KEY || options.sparkpostApiKey;
  this.sparkpostEmailClient = new sparkpost( this.sparkpostApiKey );

  // Set any options which are valid
  for( var opt in options ) {
    this[opt] = (options.hasOwnProperty( opt )) ? options[opt] : undefined;
  }

  return this;
};

SparkpostTransport.prototype.send = function send(payload, callback) {
  var email = {
    transmissionBody: {}
  };

  // Apply default options and override if provided in mail object
  email.transmissionBody.tags              = (payload.data.tags) ? payload.data.tags : this.tags;
  email.transmissionBody.campaign_id       = (payload.data.campaign_id) ? payload.data.campaign_id : this.campaign_id;
  email.transmissionBody.metadata          = (payload.data.metadata) ? payload.data.metadata : this.metadata;
  email.transmissionBody.substitution_data = (payload.data.substitution_data) ? payload.data.substitution_data : this.substitution_data;
  email.transmissionBody.options           = (payload.data.options) ? payload.data.options : this.options;
  email.transmissionBody.content           = (payload.data.content) ? payload.data.content : this.content;
  email.transmissionBody.recipients        = (payload.data.recipients) ? payload.data.recipients : this.recipients;

  // Send the transmission using Sparkpost
  this.sparkpostEmailClient.transmissions.send(email, function( err, res ) {
    if( err ) {
      return callback( err );
    } else {
      // Example successful Sparkpost transmission response:
      // { "results": { "total_rejected_recipients": 0, "total_accepted_recipients": 1, "id": "66123596945797072" } }
      return callback( null, {
        messageId: res.body.results.id,
        accepted: res.body.results.total_accepted_recipients,
        rejected: res.body.results.total_rejected_recipients
      });
    }
  });
};

module.exports = function(options) {
  return new SparkpostTransport(options);
};
<|endoftext|>


<commit_before>var Cobble = {
  get_next_slide: function (slide) {
    return slide.next(".slide").size() == 0 ? $(".slide:first") : slide.next(".slide");
  },

  get_prev_slide: function (slide) {
    return slide.prev(".slide").size() == 0 ? $(".slide:last") : slide.prev(".slide");
  },

  refresh_next_prev: function () {
    $(".slide").removeClass('next').removeClass('prev');
    this.get_next_slide($(".slide.current")).addClass('next');
    this.get_prev_slide($(".slide.current")).addClass('prev');
    if(this.current_slide_number() >= 0)
      window.location.hash = this.current_slide_number() + 1;
  },

  next_slide: function () {
    var current_slide = $(".slide.current");
    current_slide.removeClass("current");
    this.get_next_slide(current_slide).addClass("current");

    $("#navigation .current").html(this.current_slide_number() + 1);
    this.refresh_next_prev();
  },

  prev_slide: function () {
    var current_slide = $(".slide.current");
    current_slide.removeClass("current");
    this.get_prev_slide(current_slide).addClass("current");

    $("#navigation .current").html(this.current_slide_number() + 1);
    this.refresh_next_prev();
  },

  goto_slide: function(n) {
    var current_slide = $(".slide.current");
    current_slide.removeClass("current");
    $(".slide").eq(n).addClass("current");

    $("#navigation .current").html(this.current_slide_number() + 1);
    this.refresh_next_prev();
  },

  current_slide_number: function() {
    return $(".slide").index($(".slide.current"));
  },

  present: function(content, container) {
    // content = content.trim();
    if(!container) container = "body";

    $container = $(container);

    $container.addClass('cobble');
    $container.addClass('loading');

    // clear and append navigation elements
    $container.append('\

 \

\
          <button class="prev iconic iconic-arrow-left" />\
          <button class="next iconic iconic-arrow-right" />\

\

\

\

');

    // navigation button scrolling
    $("#navigation button.prev").click(function() { Cobble.prev_slide() });
    $("#navigation button.next").click(function() { Cobble.next_slide() });

    // keyboard input
    $(window).keyup(function(e) {
      $("#navigation").removeClass("hover");
    });

    // populate slides
    $("#navigation .total").html($(".slide").size());
    this.goto_slide(window.location.hash.length > 0 ? parseInt(window.location.hash.substring(1)) - 1 : 0);

    $(window).keydown(function(e) {
      console.log(e.which)
      if(e.ctrlKey)
        $("#navigation").addClass("hover");

      if(e.which == 39) { // right
        if(!$("#editor").hasClass('down'))
          Cobble.next_slide();

      } else if(e.which == 37) { // left
        if(!$("#editor").hasClass('down'))
          Cobble.prev_slide();

      } else if(e.which == 27) { // esc
        if($("#editor").hasClass('down')) {
          Cobble.replace_current_slide($("#editor textarea").val());
          $("#editor").removeClass('down');
        }

      }
    });
  }
}

$(function(){
  Cobble.present()
})

window.onload = function() {
  $(".cobble").removeClass('loading');
}
<commit_msg>Auto resize images<commit_after>var Cobble = {
  get_next_slide: function (slide) {
    return slide.next(".slide").size() == 0 ? $(".slide:first") : slide.next(".slide");
  },

  get_prev_slide: function (slide) {
    return slide.prev(".slide").size() == 0 ? $(".slide:last") : slide.prev(".slide");
  },

  refresh_next_prev: function () {
    $(".slide").removeClass('next').removeClass('prev');
    this.get_next_slide($(".slide.current")).addClass('next');
    this.get_prev_slide($(".slide.current")).addClass('prev');
    if(this.current_slide_number() >= 0)
      window.location.hash = this.current_slide_number() + 1;
  },

  next_slide: function () {
    var current_slide = $(".slide.current");
    current_slide.removeClass("current");
    this.get_next_slide(current_slide).addClass("current");

    $("#navigation .current").html(this.current_slide_number() + 1);
    this.refresh_next_prev();
  },

  prev_slide: function () {
    var current_slide = $(".slide.current");
    current_slide.removeClass("current");
    this.get_prev_slide(current_slide).addClass("current");

    $("#navigation .current").html(this.current_slide_number() + 1);
    this.refresh_next_prev();
  },

  goto_slide: function(n) {
    var current_slide = $(".slide.current");
    current_slide.removeClass("current");
    $(".slide").eq(n).addClass("current");

    $("#navigation .current").html(this.current_slide_number() + 1);
    this.refresh_next_prev();
  },

  current_slide_number: function() {
    return $(".slide").index($(".slide.current"));
  },

  present: function(content, container) {
    // content = content.trim();
    if(!container) container = "body";

    $container = $(container);

    $container.addClass('cobble');
    $container.addClass('loading');

    // clear and append navigation elements
    $container.append('\

 \

\
          <button class="prev iconic iconic-arrow-left" />\
          <button class="next iconic iconic-arrow-right" />\

\

\

\

');

    // navigation button scrolling
    $("#navigation button.prev").click(function() { Cobble.prev_slide() });
    $("#navigation button.next").click(function() { Cobble.next_slide() });

    // keyboard input
    $(window).keyup(function(e) {
      $("#navigation").removeClass("hover");
    });

    // populate slides
    $("#navigation .total").html($(".slide").size());
    this.goto_slide(window.location.hash.length > 0 ? parseInt(window.location.hash.substring(1)) - 1 : 0);

    $(window).keydown(function(e) {
      console.log(e.which)
      if(e.ctrlKey)
        $("#navigation").addClass("hover");

      if(e.which == 39) { // right
        if(!$("#editor").hasClass('down'))
          Cobble.next_slide();

      } else if(e.which == 37) { // left
        if(!$("#editor").hasClass('down'))
          Cobble.prev_slide();

      } else if(e.which == 27) { // esc
        if($("#editor").hasClass('down')) {
          Cobble.replace_current_slide($("#editor textarea").val());
          $("#editor").removeClass('down');
        }

      }
    });
  }
}

$(function(){
  Cobble.present()
})

window.onresize = function() {
  var img = new Image();
  var bodyStyle = window.getComputedStyle(document.body, null);

  Array.prototype.slice.call(document.querySelectorAll(".slide.image")).map(function(slide) {
    img.src = slide.style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2') .split(',')[0];
    if(img.width > parseInt(bodyStyle.width) || img.height > parseInt(bodyStyle.height)) {
      slide.style.backgroundSize = "contain";
    } else {
      slide.style.backgroundSize = "";
    }
  });
}

window.onload = function() {
  $(".cobble").removeClass('loading');
  window.onresize();
}<|endoftext|>


<commit_before>const isFn = /^\$fn\|/
const dummy = () => false
// const client = (tree) => {
//   while (tree) {
//     if (tree._ && tree._.client) {
//       return tree._.client
//     }
//     tree = tree._p
//   }
// }

// const clientContext = fn => (state, subs, tree, key) => {
//   if (state) {
//     const $root = state.root
//     const inContext = $root._client
//     var prev
//     if (inContext) {
//       $root._client = client(tree)
//     } else {
//       prev = $root.client
//       $root.client = client(tree)
//     }
//     const ret = fn(state, tree, subs, key)
//     if (inContext) {
//       $root._client = inContext
//     } else {
//       $root.client = prev
//     }
//     return ret
//   } else {
//     return fn(state, tree, subs, key)
//   }
// }

const parse = (obj, state, key) => {
  const result = {}
  for (let i in obj) {
    if (isFn.test(i)) {
      let val = obj[i]
      i = i.slice(4)
      // need to fix buble stuff in these fn creations -- prop need to add buble
      // runtime in a hub
      let pass
      try {
        obj[i] = new Function('return ' + val)() // eslint-disable-line
        // if (/\.client|\[['"']client['"]\]/.test(val)) { // eslint-disable-line
        //   obj[i] = clientContext(obj[i])
        // }
        pass = true
        console.log('??????', obj[i])
        // do dry run with your own key in a props object
        // 2 options for this ofcourse
        // obj[i](state, {}, {}, i)
        // do we want to test for null / void 0?
      } catch (e) {
        let msg
        if (!pass) {
          msg = `cannot parse function ${key}.exec\n${val}`
        } else {
          msg = `cannot run function ${key}.exec\n${val}`
        }
        state.emit('error', new Error(msg))
        obj[i] = dummy
      }
    }
    if (typeof obj[i] !== 'object') {
      result[i] = obj[i]
    } else {
      result[i] = parse(obj[i], state, i)
    }
  }
  return result
}

export default parse
<commit_msg>remove logs<commit_after>const isFn = /^\$fn\|/
const dummy = () => false
// const client = (tree) => {
//   while (tree) {
//     if (tree._ && tree._.client) {
//       return tree._.client
//     }
//     tree = tree._p
//   }
// }

// const clientContext = fn => (state, subs, tree, key) => {
//   if (state) {
//     const $root = state.root
//     const inContext = $root._client
//     var prev
//     if (inContext) {
//       $root._client = client(tree)
//     } else {
//       prev = $root.client
//       $root.client = client(tree)
//     }
//     const ret = fn(state, tree, subs, key)
//     if (inContext) {
//       $root._client = inContext
//     } else {
//       $root.client = prev
//     }
//     return ret
//   } else {
//     return fn(state, tree, subs, key)
//   }
// }

const parse = (obj, state, key) => {
  const result = {}
  for (let i in obj) {
    if (isFn.test(i)) {
      let val = obj[i]
      i = i.slice(4)
      // need to fix buble stuff in these fn creations -- prop need to add buble
      // runtime in a hub
      let pass
      try {
        obj[i] = new Function('return ' + val)() // eslint-disable-line
        // if (/\.client|\[['"']client['"]\]/.test(val)) { // eslint-disable-line
        //   obj[i] = clientContext(obj[i])
        // }
        pass = true
        // do dry run with your own key in a props object
        // 2 options for this ofcourse
        // obj[i](state, {}, {}, i)
        // do we want to test for null / void 0?
      } catch (e) {
        let msg
        if (!pass) {
          msg = `cannot parse function ${key}.exec\n${val}`
        } else {
          msg = `cannot run function ${key}.exec\n${val}`
        }
        state.emit('error', new Error(msg))
        obj[i] = dummy
      }
    }
    if (typeof obj[i] !== 'object') {
      result[i] = obj[i]
    } else {
      result[i] = parse(obj[i], state, i)
    }
  }
  return result
}

export default parse
<|endoftext|>


<commit_before>//placeholder for
//https://github.com/mykabam/kabam-kernel/issues/37<commit_msg>[fix] - extended placeholder<commit_after>'use strict';
var async = require('async');
exports.name = 'document';
//placeholder for
//https://github.com/mykabam/kabam-kernel/issues/37
<|endoftext|>


<commit_before>'use strict'
var _setKeyInternal = require('vigour-js/lib/observable').prototype.setKeyInternal
exports.define = {
  setKeyInternal: function (key, val, property, event, nocontext, escape) {
    // double check this
    console.error('hello!????')
    if (val instanceof Array && val[0] === '$') {
      // maybe add a symbol or something?
      val.shift()
      val = (this.adapter ? this : this.lookUp('adapter').parent).get(val, {}, event)
      console.error('yo set a reference bitch godamit', event)
    }
    return _setKeyInternal.call(this, key, val, property, event, nocontext, escape)
  }
}
<commit_msg>removed log<commit_after>'use strict'
var _setKeyInternal = require('vigour-js/lib/observable').prototype.setKeyInternal
exports.define = {
  setKeyInternal: function (key, val, property, event, nocontext, escape) {
    // double check this
    // console.error('hello!????')
    if (val instanceof Array && val[0] === '$') {
      // maybe add a symbol or something?
      val.shift()
      val = (this.adapter ? this : this.lookUp('adapter').parent).get(val, {}, event)
      // console.error('yo set a reference bitch godamit', event)
    }
    return _setKeyInternal.call(this, key, val, property, event, nocontext, escape)
  }
}
<|endoftext|>


<commit_before>var LLVM              = require('../../../../llvm2'),
    types             = require('../../types'),
    nativeTypeForType = require('./native-types').nativeTypeForType

var Int8PtrType = LLVM.Types.pointerType(LLVM.Types.Int8Type),
    Int32Type   = LLVM.Types.Int32Type,
    Int32Zero   = LLVM.Library.LLVMConstInt(Int32Type, 0, true)

// Function to check if the type has been compiled
function typeCompiled (type) {
  switch (type.constructor) {
    case types.Instance:
      var instance = type
      return typeCompiled(instance.type)
    case types.Object:
      if (type.hasNativeObject()) { return true }
      break
    case types.Function:
      if (type.hasNativeFunction()) { return true }
      break
  }
  return false
}

function Slots () {
  this.slots      = {}
  this.slotsTypes = {}
  // Queue of slots to be built once type has become available. Items
  // are 2-tuples of name (string) and type (Type)
  this.allocQueue = []
}
Slots.prototype.checkAllocQueue = function (ctx) {
  var self     = this,
      toDelete = []
  for (var i = 0; i < this.allocQueue.length; i++) {
    var pair = this.allocQueue[i],
        name = pair[0],
        type = pair[1]
    if (typeCompiled(type)) {
      toDelete.push(name)
    }
  }
  // Didn't find any slots to allocate
  if (toDelete.length === 0) { return }
  // Update the alloc queue if there were items to delete
  this.allocQueue = this.allocQueue.filter(function (pair) {
    var name = pair[0],
        idx  = toDelete.indexOf(name)
    if (idx === -1) {
      return true
    }
    var type = pair[1]
    var nativeType = nativeTypeForType(type)
    // Alloc the slot now that we have a type
    self.buildAlloc(ctx, name, nativeType)
    return false
  })
}
Slots.prototype.assertSlotNotAllocated = function (name) {
  if (this.slots[name]) {
    throw new Error('Slot already allocated: '+name)
  }
}
Slots.prototype.assertSlotAllocated = function (name) {
  if (!this.slots[name]) {
    throw new Error('Slot not allocated: '+name)
  }
}
Slots.prototype.enqueueAlloc = function (name, type) {
  this.assertSlotNotAllocated(name)
  this.allocQueue.push([name, type])
}
Slots.prototype.buildAlloc = function (ctx, name, type) {
  this.assertSlotNotAllocated(name)
  if (type === undefined) {
    type = Int8PtrType
  }
  var slot = ctx.builder.buildAlloca(Int8PtrType, name)
  this.slots[name]      = slot
  this.slotsTypes[name] = Int8PtrType
}
Slots.prototype.buildSet = function (ctx, name, value) {
  this.checkAllocQueue(ctx)
  this.assertSlotAllocated(name)
  if (!(value instanceof Buffer)) {
    throw new Error('Expected Buffer as value for setting a slot')
  }
  var slot = this.slots[name]
  // Get the element pointer
  var ptr = ctx.builder.buildGEP(slot, [Int32Zero], name)
  // console.log('storing in slot: '+name)
  return ctx.builder.buildStore(value, ptr)
}
Slots.prototype.buildGet = function (ctx, name) {
  this.assertSlotAllocated(name)
  var slot = this.slots[name],
      ptr  = ctx.builder.buildGEP(slot, [Int32Zero], name)
  return ctx.builder.buildLoad(ptr, name)
}
Slots.prototype.buildAllocAndSet = function (ctx, name, value) {
  this.buildAlloc(ctx, name)
  return this.buildSet(ctx, name, value)
}
Slots.prototype.getStorable = function (ctx, name) {
  this.assertSlotAllocated(name)
  // slot will just be a pointer to a pointer
  var slot = this.slots[name]
  return slot
}

function ConstantSlots () {
  this.slots = {}
}
ConstantSlots.prototype.buildSet = function (ctx, name, value) {
  if (this.slots[name]) {
    throw new Error('Cannot re-set constant slot: '+name)
  }
  this.slots[name] = value
}
ConstantSlots.prototype.buildGet = function (ctx, name) {
  var value = this.slots[name]
  if (!value) {
    throw new Error('Constant slot not found: '+name)
  }
  return value
}
ConstantSlots.prototype.getStorable = function (ctx, name) {
  throw new Error('Cannot get a storable for a constant slot: '+name)
}

module.exports = {
  Slots: Slots,
  ConstantSlots: ConstantSlots
}

<commit_msg>Bugfix in slots<commit_after>var LLVM              = require('../../../../llvm2'),
    types             = require('../../types'),
    nativeTypeForType = require('./native-types').nativeTypeForType

var Int8PtrType = LLVM.Types.pointerType(LLVM.Types.Int8Type),
    Int32Type   = LLVM.Types.Int32Type,
    Int32Zero   = LLVM.Library.LLVMConstInt(Int32Type, 0, true)

// Function to check if the type has been compiled
function typeCompiled (type) {
  switch (type.constructor) {
    case types.Instance:
      var instance = type
      return typeCompiled(instance.type)
    case types.Object:
      if (type.hasNativeObject()) { return true }
      break
    case types.Function:
      if (type.hasNativeFunction()) { return true }
      break
  }
  return false
}

function Slots () {
  this.slots      = {}
  this.slotsTypes = {}
  // Queue of slots to be built once type has become available. Items
  // are 2-tuples of name (string) and type (Type)
  this.allocQueue = []
}
Slots.prototype.checkAllocQueue = function (ctx) {
  var self     = this,
      toDelete = []
  for (var i = 0; i < this.allocQueue.length; i++) {
    var pair = this.allocQueue[i],
        name = pair[0],
        type = pair[1]
    if (typeCompiled(type)) {
      toDelete.push(name)
    }
  }
  // Didn't find any slots to allocate
  if (toDelete.length === 0) { return }
  // Update the alloc queue if there were items to delete
  this.allocQueue = this.allocQueue.filter(function (pair) {
    var name = pair[0],
        idx  = toDelete.indexOf(name)
    if (idx === -1) {
      return true
    }
    var type = pair[1]
    var nativeType = nativeTypeForType(type)
    // Alloc the slot now that we have a type
    self.buildAlloc(ctx, name, nativeType)
    return false
  })
}
Slots.prototype.assertSlotNotAllocated = function (name) {
  if (this.slots[name]) {
    throw new Error('Slot already allocated: '+name)
  }
}
Slots.prototype.assertSlotAllocated = function (name) {
  if (!this.slots[name]) {
    throw new Error('Slot not allocated: '+name)
  }
}
Slots.prototype.enqueueAlloc = function (name, type) {
  this.assertSlotNotAllocated(name)
  this.allocQueue.push([name, type])
}
Slots.prototype.buildAlloc = function (ctx, name, type) {
  this.assertSlotNotAllocated(name)
  if (type === undefined) {
    type = Int8PtrType
  }
  var slot = ctx.builder.buildAlloca(type, name)
  this.slots[name]      = slot
  this.slotsTypes[name] = type
}
Slots.prototype.buildSet = function (ctx, name, value) {
  this.checkAllocQueue(ctx)
  this.assertSlotAllocated(name)
  if (!(value instanceof Buffer)) {
    throw new Error('Expected Buffer as value for setting a slot')
  }
  var slot = this.slots[name]
  // Get the element pointer
  var ptr = ctx.builder.buildGEP(slot, [Int32Zero], name)
  // console.log('storing in slot: '+name)
  return ctx.builder.buildStore(value, ptr)
}
Slots.prototype.buildGet = function (ctx, name) {
  this.assertSlotAllocated(name)
  var slot = this.slots[name],
      ptr  = ctx.builder.buildGEP(slot, [Int32Zero], name)
  return ctx.builder.buildLoad(ptr, name)
}
Slots.prototype.buildAllocAndSet = function (ctx, name, value) {
  this.buildAlloc(ctx, name)
  return this.buildSet(ctx, name, value)
}
Slots.prototype.getStorable = function (ctx, name) {
  this.assertSlotAllocated(name)
  // slot will just be a pointer to a pointer
  var slot = this.slots[name]
  return slot
}

function ConstantSlots () {
  this.slots = {}
}
ConstantSlots.prototype.buildSet = function (ctx, name, value) {
  if (this.slots[name]) {
    throw new Error('Cannot re-set constant slot: '+name)
  }
  this.slots[name] = value
}
ConstantSlots.prototype.buildGet = function (ctx, name) {
  var value = this.slots[name]
  if (!value) {
    throw new Error('Constant slot not found: '+name)
  }
  return value
}
ConstantSlots.prototype.getStorable = function (ctx, name) {
  throw new Error('Cannot get a storable for a constant slot: '+name)
}

module.exports = {
  Slots: Slots,
  ConstantSlots: ConstantSlots
}

<|endoftext|>


<commit_before>var child_process = require('child_process')
var events = require('events')
var gtp = require('./index')

/**
 * Attention! The GTP 2.0 draft specifies that the engine
 * has to respond to the commands in the same order as they
 * come in. Unfortunately, due to the asynchronous nature of
 * node.js, the `response` event could be handled *not*
 * in the given order.
 */

var Controller = function(exec, args) {
    var self = this
    events.EventEmitter.call(self)

    self._buffer = ''
    self.process = child_process.spawn(exec, args)
    self.commands = []

    self.process.stdout.on('data', function(data) {
        self._buffer += (data + '').replace(/\r/g, '').replace(/#.*?\n/g, '').replace(/\t/g, ' ')

        var start = self._buffer.indexOf('\n\n')

        while (start != -1) {
            var response = gtp.parseResponse(self._buffer.substr(0, start))
            self._buffer = self._buffer.substr(start + 2)

            if (self.commands.length > 0) {
                self.emit('response', response, self.commands[0])
                self.commands.splice(0, 1)
            }

            start = self._buffer.indexOf('\n\n')
        }
    })
}

require('util').inherits(Controller, events.EventEmitter)

Controller.prototype.sendCommand = function(command) {
    this.commands.push(command)
    this.process.stdin.write(command.toString() + '\n')
}

module.exports = Controller
<commit_msg>Show 'process already quit' error msg<commit_after>var child_process = require('child_process')
var events = require('events')
var gtp = require('./index')

/**
 * Attention! The GTP 2.0 draft specifies that the engine
 * has to respond to the commands in the same order as they
 * come in. Unfortunately, due to the asynchronous nature of
 * node.js, the `response` event could be handled *not*
 * in the given order.
 */

var Controller = function(exec, args) {
    var self = this
    events.EventEmitter.call(self)

    self._buffer = ''
    self.process = child_process.spawn(exec, args)
    self.commands = []

    self.process.stdout.on('data', function(data) {
        self._buffer += (data + '').replace(/\r/g, '').replace(/#.*?\n/g, '').replace(/\t/g, ' ')

        var start = self._buffer.indexOf('\n\n')

        while (start != -1) {
            var response = gtp.parseResponse(self._buffer.substr(0, start))
            self._buffer = self._buffer.substr(start + 2)

            if (self.commands.length > 0) {
                self.emit('response', response, self.commands[0])
                self.commands.splice(0, 1)
            }

            start = self._buffer.indexOf('\n\n')
        }
    })
}

require('util').inherits(Controller, events.EventEmitter)

Controller.prototype.sendCommand = function(command) {
    this.commands.push(command)

    try {
        this.process.stdin.write(command.toString() + '\n')
    } catch(e) {
        this.emit('response', new gtp.Response(command.id, 'process already quit', true, true), command)
        this.commands.splice(0, 1)
    }
}

module.exports = Controller
<|endoftext|>


<commit_before>"use strict";

const MongoClient = require("mongodb").MongoClient;
const debug = require("debug")("bot-express:memory");
const assert = require('assert');
Promise = require("bluebird");

class MemoryMongodb {
    constructor(options){
        this.url = options.url;
    }

    get(key){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                return db.collection('bot-express').findOne([key]).then((response) => {
                    debug(response);
                    return resolve(response);
                }).catch((error) => {
                    return reject(error);
                });
            });
        });
    }

    put(key, value, retention){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                return db.collection('bot-express').insertOne({key: value}, function(err, r) {
                    try {
                        assert.equal(null, err);
                        assert.equal(1, r.insertedCount);
                        return resolve();
                    } catch(e) {
                        return reject(e);
                    }
                });
            });
        });
    }

    del(key){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                return db.collection('bot-express').deleteOne([key], function(err, r) {
                    try {
                        assert.equal(null, err);
                        assert.equal(1, r.insertedCount);
                        return resolve();
                    } catch(e) {
                        return reject(e);
                    }
                });
            });
        });
    }
}

module.exports = MemoryMongodb;
<commit_msg>improving<commit_after>"use strict";

const MongoClient = require("mongodb").MongoClient;
const debug = require("debug")("bot-express:memory");
const assert = require('assert');
Promise = require("bluebird");

class MemoryMongodb {
    constructor(options){
        this.url = options.url;
    }

    get(key){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                return db.collection('bot-express').findOne({context_id: key).then((response) => {
                    debug(response);
                    return resolve(response);
                }).catch((error) => {
                    return reject(error);
                });
            });
        });
    }

    put(key, value, retention){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                value.context_id = key;
                return db.collection('bot-express').insertOne(value, function(err, r) {
                    try {
                        assert.equal(null, err);
                        assert.equal(1, r.insertedCount);
                        return resolve();
                    } catch(e) {
                        return reject(e);
                    }
                });
            });
        });
    }

    del(key){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                return db.collection('bot-express').deleteOne({context_id: key}, function(err, r) {
                    try {
                        assert.equal(null, err);
                        assert.equal(1, r.insertedCount);
                        return resolve();
                    } catch(e) {
                        return reject(e);
                    }
                });
            });
        });
    }
}

module.exports = MemoryMongodb;
<|endoftext|>


<commit_before>// inspired by tiny-events:
// https://github.com/ZauberNerd/tiny-events
// MIT License (MIT), Copyright (c) 2014 Björn Brauer

define(['mmirf/util/isArray', 'mmirf/util/toArray'], function(isArray, toArray){

/**
 *

 * Inspired by tiny-events

 * MIT License (MIT), Copyright (c) 2014 Björn Brauer
 *

 *
 * Simple Event Emitter / Manager.
 *
 * Optionally, a list of supported events can be specified:
 * if a list of supported events is given, trying the register a listener for an
 * unsupported event will cause an error.
 *
 * @param       {any} [thisArg] OPTIONAL
 *                              this context when emitting events:
 *                              if omitted, the this context will be the EventEmitter
 *                              instance.
 *                              WARNING: if thisArg is an Array, then events argument
 *                                       must also be given, either as an Array, or
 *                                       false for disabling the
 *                                       supported events restriction
 *
 * @param       {Array<string>} [events] OPTIONAL
 * 															A list of supported event types/names:
 * 															if calling EventEmitter.on() with an unsupported
 * 															type, an error will be thrown.
 * 															If omitted, any event type/names is allowed.
 * @constructor
 * @memberOf mmir.tools
 */
function EventEmitter(thisArg, events) {
	if (isArray(thisArg) && typeof events === 'undefined') {
		events = thisArg;
		thisArg = void(0);
	}
	this._ctx = typeof thisArg === 'undefined'? this : thisArg;
	this._events = events? new Set(events) : null;
	this._listeners = new Map();
}

/**
 * Verifies that an event type can be used with the EventEmitter instance
 * (see events argument in constructor).
 *
 * @param       {string} type the event type to check
 *
 * @throws Error if the event type is not supported by the EventEmitter instance
 */
EventEmitter.prototype.verify = function _on(type) {
	if (this._events && !this._events.has(type)) {
		throw new Error('unsupported event '+type+', must be one of '+Array.from(this._events));
	}
};

/**
 * Register a listener for an event type.
 *
 * Will be ignored, if the listener already is registered for that event type.
 *
 * If a list of supported event types is specified for the EventEmitter instance,
 * and type is not a supported type, an error will be thrown.
 *
 * @param       {string} type the event type
 * @param       {Function} listener this listener that will be registered
 * @return      {boolean} true if the listener was registered
 *
 * @throws Error if the event type is not supported by the EventEmitter instance
 */
EventEmitter.prototype.on = function _on(type, listener) {
	this.verify(type);

	var l = this._listeners.get(type);
	if (!l) {
		l = new Set();
		this._listeners.set(type, l);
	}

	if(!l.has(listener)){
		l.add(listener);
		return true;
	}

	return false;
};

/**
 * Register a listener for an event type to be called one time.
 *
 * @param       {string} type the event type
 * @param       {Function} listener this listener that will be registered
 * @return      {boolean} true if the listener was registered
 *
 * @throws Error if the event type is not supported by the EventEmitter instance
 *
 * @see #on
 */
EventEmitter.prototype.once = function _once(type, listener) {
	var self = this;

	function __once() {
		var args = toArray(arguments);
		self.off(type, __once);
		listener.apply(self._ctx, args);
	}

	__once.listener = listener;

	return this.on(type, __once);
};

/**
 * Unregister a listener for an event.
 *
 * @param       {string} type the event type
 * @param       {Function} [listener] OPTIONAL
 * 												 The listener to be removed.
 * 												 If omitted, all listeners for the event type will be
 * 												 removed.
 * @return      {boolean} true if the listener was removed
 */
EventEmitter.prototype.off = function _off(type, listener) {
	var l = this._listeners.get(type);
	if (!l) {
		return false;
	}

	if (typeof listener === 'undefined') {
		this._listeners.delete(type);
		return l.size > 0;
	}

	if(l.delete(listener)) {
		//NOTE remove l, if it becomes empty!
		if(l.size === 0) {
			this._listeners.delete(type);
		}
		return true;
	}

	return false;
};

/**
 * Emit an event to registered listeners.
 *
 * @param       {string} type the event type that will be emitted
 * @param       {...any} [args] OPTIONAL arguments that will be emitted to
 *                              the listeners
 * @return      {boolean} true if at least one listener was notified
 */
EventEmitter.prototype.emit = function _emit(type) {
	var l = this._listeners.get(type);
	if (!l || l.size === 0) {
		return false;
	}

	var size = arguments.length;
	var args = new Array(size - 1);
	for (var i = 1; i < size; ++i) {
		args[i - 1] = arguments[i];
	}

	l.forEach(function __emit(listener) {
		listener.apply(this, args);
	}, this._ctx);

	return true;
};

/**
 * Check if the EventEmitter instance has any listener registered.
 *
 * @return      {boolean} true if no listener is registered
 */
EventEmitter.prototype.empty = function _empty() {
	//ASSERT this._listeners does not contain empty event type collections/Sets
	//       (that is: no empty Sets will be added & if a Set becomes empty, it will be removed)
	return this._listeners.size === 0;
};

/**
 * Get a list of event types (if no argument is given) or a list of registered
 * listeners for an event type (if event type is given).
 *
 * @param       {string} [type] the event type.
 * 															If omitted returns a list of event types, or
 * 															undefined, if there are no listener
 * 															for any event registered.
 * 															If an event type is specified, returns a list of
 * 															listeners, or undefined, if no
 * 															listeners for the event type or registered.
 * @return      {Array<Function>|Array<String>} a list of listeners or a list of
 * 															event types or undefined, if there
 * 															are none.
 */
EventEmitter.prototype.get = function _get(type) {
	if(typeof type === 'undefined'){
		return !this.empty()? toArray(this._listeners.keys()) : void(0);
	}
	var l = this._listeners.get(type);
	//ASSERT if l is present, then l.size > 0
	return l? toArray(l) : l;
};

/**
 * Check if listener is registered for an event.
 *
 * @param       {string} type the event type
 * @param       {Function} [listener] OPTIONAL
 * 												 The listener to be checked.
 * 												 If omitted, it will be checked, if there is any listener
 * 												 of the event type.
 * @return      {boolean} true if the listener (or any if listener
 * 												 was not specified) is registered for the event type
 */
EventEmitter.prototype.has = function _has(type, listener) {
	var l = this._listeners.get(type);
	//ASSERT if l is present, then l.size > 0
	return l? (listener? l.has(listener) : true) : false;
};

/**
 * Release all resources of EventEmitter instance:
 * unregister any listeners and unlink any external references
 * (e.g. thisArg if given in constructor).
 *
 */
EventEmitter.prototype.destroy = function _destroy() {
	this._listeners.forEach(function(l){
		l.clear();
	});
	this._listeners.clear();
	if(this._events){
		this._events.clear();
		this._events = null;
	}
	this._ctx = null;
};

return EventEmitter;

});
<commit_msg>support event hooks on<event name><commit_after>// inspired by tiny-events:
// https://github.com/ZauberNerd/tiny-events
// MIT License (MIT), Copyright (c) 2014 Björn Brauer

define(['mmirf/util/isArray', 'mmirf/util/toArray'], function(isArray, toArray){

/**
 *

 * Inspired by tiny-events

 * MIT License (MIT), Copyright (c) 2014 Björn Brauer
 *

 *
 * Simple Event Emitter / Manager.
 *
 * Optionally, a list of supported events can be specified:
 * if a list of supported events is given, trying the register a listener for an
 * unsupported event will cause an error.
 *
 * @param       {any} [thisArg] OPTIONAL
 *                              this context when emitting events:
 *                              if omitted, the this context will be the EventEmitter
 *                              instance.
 *                              WARNING: if thisArg is an Array, then events argument
 *                                       must also be given, either as an Array, or
 *                                       false for disabling the
 *                                       supported events restriction
 *
 * @param       {Array<string>} [events] OPTIONAL
 * 															A list of supported event types/names:
 * 															if calling EventEmitter.on() with an unsupported
 * 															type, an error will be thrown.
 * 															If omitted, any event type/names is allowed.
 *
 * @param       {Boolean} [enableHooks] OPTIONAL
 * 															If true, upon emitting events, existing handler functions
 * 															on the thisArg with name "on<event name>"
 * 															will be triggered, after registered listeners were triggered.
 * @constructor
 * @memberOf mmir.tools
 */
function EventEmitter(thisArg, events, enableHooks) {
	if (typeof events === 'boolean' && typeof enableHooks === 'undefined') {
		enableHooks = events;
		events = void(0);
	}
	if (typeof thisArg === 'boolean' && typeof events === 'undefined' && typeof enableHooks === 'undefined') {
		enableHooks = thisArg;
		thisArg = void(0);
	}
	if (isArray(thisArg) && typeof events === 'undefined') {
		events = thisArg;
		thisArg = void(0);
	}
	this._ctx = typeof thisArg === 'undefined'? this : thisArg;
	this._events = events? new Set(events) : null;
	this._listeners = new Map();
	this._enableHooks = !!enableHooks;
}

/**
 * Verifies that an event type can be used with the EventEmitter instance
 * (see events argument in constructor).
 *
 * @param       {string} type the event type to check
 *
 * @throws Error if the event type is not supported by the EventEmitter instance
 */
EventEmitter.prototype.verify = function _on(type) {
	if (this._events && !this._events.has(type)) {
		throw new Error('unsupported event '+type+', must be one of '+Array.from(this._events));
	}
};

/**
 * Register a listener for an event type.
 *
 * Will be ignored, if the listener already is registered for that event type.
 *
 * If a list of supported event types is specified for the EventEmitter instance,
 * and type is not a supported type, an error will be thrown.
 *
 * @param       {string} type the event type
 * @param       {Function} listener this listener that will be registered
 * @return      {boolean} true if the listener was registered
 *
 * @throws Error if the event type is not supported by the EventEmitter instance
 */
EventEmitter.prototype.on = function _on(type, listener) {
	this.verify(type);

	var l = this._listeners.get(type);
	if (!l) {
		l = new Set();
		this._listeners.set(type, l);
	}

	if(!l.has(listener)){
		l.add(listener);
		return true;
	}

	return false;
};

/**
 * Register a listener for an event type to be called one time.
 *
 * @param       {string} type the event type
 * @param       {Function} listener this listener that will be registered
 * @return      {boolean} true if the listener was registered
 *
 * @throws Error if the event type is not supported by the EventEmitter instance
 *
 * @see #on
 */
EventEmitter.prototype.once = function _once(type, listener) {
	var self = this;

	function __once() {
		var args = toArray(arguments);
		self.off(type, __once);
		listener.apply(self._ctx, args);
	}

	__once.listener = listener;

	return this.on(type, __once);
};

/**
 * Unregister a listener for an event.
 *
 * @param       {string} type the event type
 * @param       {Function} [listener] OPTIONAL
 * 												 The listener to be removed.
 * 												 If omitted, all listeners for the event type will be
 * 												 removed.
 * @return      {boolean} true if the listener was removed
 */
EventEmitter.prototype.off = function _off(type, listener) {
	var l = this._listeners.get(type);
	if (!l) {
		return false;
	}

	if (typeof listener === 'undefined') {
		this._listeners.delete(type);
		return l.size > 0;
	}

	if(l.delete(listener)) {
		//NOTE remove l, if it becomes empty!
		if(l.size === 0) {
			this._listeners.delete(type);
		}
		return true;
	}

	return false;
};

/**
 * Emit an event to registered listeners.
 *
 * @param       {string} type the event type that will be emitted
 * @param       {...any} [args] OPTIONAL arguments that will be emitted to
 *                              the listeners
 * @return      {boolean} true if at least one listener was notified
 */
EventEmitter.prototype.emit = function _emit(type) {
	var l = this._listeners.get(type);

	var hasListeners = l && l.size > 0;
	var hook = this._enableHooks && this._ctx['on'+type];
	if(typeof hook !== 'function'){
		hook = null;
	}

	if(hasListeners || hook){

		var size = arguments.length;
		var args = new Array(size - 1);
		for (var i = 1; i < size; ++i) {
			args[i - 1] = arguments[i];
		}

		if(hasListeners){
			l.forEach(function __emit(listener) {
				listener.apply(this, args);
			}, this._ctx);
		}

		if(hook){
			hook.apply(this._ctx, args);
		}

		return true;
	}

	return false;
};

/**
 * Check if the EventEmitter instance has any listener registered.
 *
 * @return      {boolean} true if no listener is registered
 */
EventEmitter.prototype.empty = function _empty() {
	//ASSERT this._listeners does not contain empty event type collections/Sets
	//       (that is: no empty Sets will be added & if a Set becomes empty, it will be removed)
	return this._listeners.size === 0;
};

/**
 * Get a list of event types (if no argument is given) or a list of registered
 * listeners for an event type (if event type is given).
 *
 * @param       {string} [type] the event type.
 * 															If omitted returns a list of event types, or
 * 															undefined, if there are no listener
 * 															for any event registered.
 * 															If an event type is specified, returns a list of
 * 															listeners, or undefined, if no
 * 															listeners for the event type or registered.
 * @return      {Array<Function>|Array<String>} a list of listeners or a list of
 * 															event types or undefined, if there
 * 															are none.
 */
EventEmitter.prototype.get = function _get(type) {
	if(typeof type === 'undefined'){
		return !this.empty()? toArray(this._listeners.keys()) : void(0);
	}
	var l = this._listeners.get(type);
	//ASSERT if l is present, then l.size > 0
	return l? toArray(l) : l;
};

/**
 * Check if listener is registered for an event.
 *
 * @param       {string} type the event type
 * @param       {Function} [listener] OPTIONAL
 * 												 The listener to be checked.
 * 												 If omitted, it will be checked, if there is any listener
 * 												 of the event type.
 * @return      {boolean} true if the listener (or any if listener
 * 												 was not specified) is registered for the event type
 */
EventEmitter.prototype.has = function _has(type, listener) {
	var l = this._listeners.get(type);
	//ASSERT if l is present, then l.size > 0
	return l? (listener? l.has(listener) : true) : false;
};

/**
 * Release all resources of EventEmitter instance:
 * unregister any listeners and unlink any external references
 * (e.g. thisArg if given in constructor).
 *
 */
EventEmitter.prototype.destroy = function _destroy() {
	this._listeners.forEach(function(l){
		l.clear();
	});
	this._listeners.clear();
	if(this._events){
		this._events.clear();
		this._events = null;
	}
	this._ctx = null;
};

return EventEmitter;

});
<|endoftext|>


<commit_before>'use strict';

var Class = require( 'uberclass' )
  , path = require( 'path' )
  , packageJson = require( path.resolve( __dirname + '/../../' ) + '/package.json' )
  , fs = require( 'fs' )
  , async = require( 'async' )
  , debug = require( 'debug' )( 'moduleLoader' )
  , moduleClass;

var Module = module.exports = Class.extend(
{
    instance: null,

    getInstance: function() {
        if ( this.instance === null ) {
            this.instance = new this();
        }
        return this.instance;
    }
},
{
    modules: null,

    modulesLoaded: null,

    routesInitialized: null,

    shutdown: function() {
        this.modules.forEach( this.proxy( 'preShutdownHook' ) );
        debug( 'Shutdown complete, if your app hangs one of your modules has not closed all its connections/resources.' );
    },

    preShutdownHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.preShutdown === 'function' ) {
            debug( [ 'preShutdown (hook) for module', module.name ].join( ' ' ) );
            module.preShutdown();
        }
    },

    init: function() {
        this.modules = [];
        this.modulesLoaded = false;
        this.routesInitialized = false;
    },

    moduleIsEnabled: function( moduleName ) {
        return packageJson.bundledDependencies.indexOf( moduleName ) !== -1;
    },

    loadModules: function( env ) {
        var self = this;

        if ( this.modulesLoaded === false ) {
            debug( 'Loading modules...' );

            // Load each of our modules
            packageJson.bundledDependencies.forEach( this.proxy( 'loadModule', env ) );

            // Fire the configureApp hook on each of our modules giving them a chance to configure the express app
            this.modules.forEach( this.proxy( 'configureAppHook' ) );

            // Load each modules resources
            this.modules.forEach( this.proxy( 'preResourcesHook' ) );

            // Load each modules resources
            this.modules.forEach( this.proxy( 'loadModuleResources' ) );

            // Fire the modulesLoadedHook hook on each of our modules letting them know that all modules have finished loading
            this.modules.forEach( this.proxy( 'modulesLoadedHook' ) );

            // Let the module loader know we have already loaded our modules
            this.modulesLoaded = true;
        } else {
            debug( 'Warning: All modules have already been loaded.' );
        }
    },

    loadModule: function( env, moduleName ) {
        if (typeof env !== "undefined" && env !== null) {
            process.env = env;
        }

        debug( [ 'Loading the', moduleName, 'module' ].join( ' ' ) );

        // Get a copy of the module class
        moduleClass = require( 'classes' ).ModuleClass;

        // Load (require) the module and add to our modules array
        this.modules.push( require( moduleName ) );
    },

    configureAppHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.configureApp === 'function' ) {
            debug( 'configureApp hook called for module ' + module.name );
            injector.getInstance( 'app' ).configure( module.proxy( 'configureApp', injector.getInstance( 'app' ), injector.getInstance( 'express' ) ) );
        }
    },

    preResourcesHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.preResources === 'function' ) {
            module.hook( 'preResources' );
        }
    },

    loadModuleResources: function( module ) {
        if ( module instanceof moduleClass && typeof module.loadResources === 'function' ) {
            debug( [ 'loadResources for module', module.name ].join( ' ' ) );
            module.loadResources();
        }
    },

    modulesLoadedHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.modulesLoaded === 'function' ) {
            module.hook( 'modulesLoaded' );
        }
    },

    initializeRoutes: function() {
        if ( this.routesInitialized === false ) {
            // Give the modules notice that we are about to add our routes to the app
            this.modules.forEach( this.proxy( 'preRouteHook' ) );

            // Initialize all the modules routes
            this.modules.forEach( this.proxy( 'initializeModuleRoutes' ) );

            // We only want to do this once
            this.routesInitialized = true;
        } else {
            debug( 'Warning: All modules routes have been initialized already.' );
        }
    },

    preRouteHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.preRoute === 'function' ) {
            debug( [ 'preRoute (hook) for module', module.name ].join( ' ' ) );
            module.preRoute();
        }
    },

    initializeModuleRoutes: function( module ) {
        if ( module instanceof moduleClass ) {
            debug( [ 'Initializing the', module.name, 'modules routes.' ].join( ' ' ) );
            module.initRoutes();
        }
    }
});<commit_msg>feature(moduleLoader): Added injector instances for backend modules, clever-auth becomes cleverAuth<commit_after>'use strict';

var Class = require( 'uberclass' )
  , path = require( 'path' )
  , packageJson = require( path.resolve( __dirname + '/../../' ) + '/package.json' )
  , fs = require( 'fs' )
  , async = require( 'async' )
  , debug = require( 'debug' )( 'moduleLoader' )
  , i = require( 'i' )()
  , moduleClass;

var Module = module.exports = Class.extend(
{
    instance: null,

    getInstance: function() {
        if ( this.instance === null ) {
            this.instance = new this();
        }
        return this.instance;
    }
},
{
    modules: null,

    modulesLoaded: null,

    routesInitialized: null,

    shutdown: function() {
        this.modules.forEach( this.proxy( 'preShutdownHook' ) );
        debug( 'Shutdown complete, if your app hangs one of your modules has not closed all its connections/resources.' );
    },

    preShutdownHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.preShutdown === 'function' ) {
            debug( [ 'preShutdown (hook) for module', module.name ].join( ' ' ) );
            module.preShutdown();
        }
    },

    init: function() {
        this.modules = [];
        this.modulesLoaded = false;
        this.routesInitialized = false;
    },

    moduleIsEnabled: function( moduleName ) {
        return packageJson.bundledDependencies.indexOf( moduleName ) !== -1;
    },

    loadModules: function( env ) {
        var self = this;

        if ( this.modulesLoaded === false ) {
            debug( 'Loading modules...' );

            // Get a copy of the module class
            moduleClass = require( 'classes' ).ModuleClass;

            // Load each of our modules
            packageJson.bundledDependencies.forEach( this.proxy( 'loadModule', env ) );

            // Fire the configureApp hook on each of our modules giving them a chance to configure the express app
            this.modules.forEach( this.proxy( 'configureAppHook' ) );

            // Load each modules resources
            this.modules.forEach( this.proxy( 'preResourcesHook' ) );

            // Load each modules resources
            this.modules.forEach( this.proxy( 'loadModuleResources' ) );

            // Fire the modulesLoadedHook hook on each of our modules letting them know that all modules have finished loading
            this.modules.forEach( this.proxy( 'modulesLoadedHook' ) );

            // Let the module loader know we have already loaded our modules
            this.modulesLoaded = true;
        } else {
            debug( 'Warning: All modules have already been loaded.' );
        }
    },

    loadModule: function( env, moduleName ) {
        if (typeof env !== "undefined" && env !== null) {
            process.env = env;
        }

        debug( [ 'Loading the', moduleName, 'module' ].join( ' ' ) );
        var module = require( moduleName );

        var moduleLowerCamelCase = i.camelize( moduleName.replace( /\-/ig, '_' ), false );

        debug( [ 'Adding the', moduleLowerCamelCase, 'module to the injector' ].join( ' ' ) );
        injector.instance( moduleLowerCamelCase, module );

        // Add the module into our modules array so we can keep track of them internally and call hooks in their module.js file
        this.modules.push( module );
    },

    configureAppHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.configureApp === 'function' ) {
            debug( 'configureApp hook called for module ' + module.name );
            injector.getInstance( 'app' ).configure( module.proxy( 'configureApp', injector.getInstance( 'app' ), injector.getInstance( 'express' ) ) );
        }
    },

    preResourcesHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.preResources === 'function' ) {
            module.hook( 'preResources' );
        }
    },

    loadModuleResources: function( module ) {
        if ( module instanceof moduleClass && typeof module.loadResources === 'function' ) {
            debug( [ 'loadResources for module', module.name ].join( ' ' ) );
            module.loadResources();
        }
    },

    modulesLoadedHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.modulesLoaded === 'function' ) {
            module.hook( 'modulesLoaded' );
        }
    },

    initializeRoutes: function() {
        if ( this.routesInitialized === false ) {
            // Give the modules notice that we are about to add our routes to the app
            this.modules.forEach( this.proxy( 'preRouteHook' ) );

            // Initialize all the modules routes
            this.modules.forEach( this.proxy( 'initializeModuleRoutes' ) );

            // We only want to do this once
            this.routesInitialized = true;
        } else {
            debug( 'Warning: All modules routes have been initialized already.' );
        }
    },

    preRouteHook: function( module ) {
        if ( module instanceof moduleClass && typeof module.preRoute === 'function' ) {
            debug( [ 'preRoute (hook) for module', module.name ].join( ' ' ) );
            module.preRoute();
        }
    },

    initializeModuleRoutes: function( module ) {
        if ( module instanceof moduleClass ) {
            debug( [ 'Initializing the', module.name, 'modules routes.' ].join( ' ' ) );
            module.initRoutes();
        }
    }
});<|endoftext|>


<commit_before>/**
 * UX Rocket
 * jQuery based accordion
 * @author Bilal Cinarli
 */

;(function($){
	var ux, // local shorthand

		defaults = {
			header: ".collapsible-header",
			content: ".collapsible-content",
			current: 'current',
			closeSiblings: false
		},
		events = {
			click: 'click.uxCollapsible'
		};

	// constructor method
    var Collapsible = function(el, options){
        var opts = $.extend({}, defaults, options, $(el).data()),

        // cached variables
        $collapsible = $(el),
        $header = $collapsible.find(opts.header),
        $siblings = $collapsible.siblings(),
        $children = $siblings.find('.uxitd-collapsible-ready');

        $(el).on(events.click , opts.header , function(e){
            e.preventDefault();
            e.stopPropagation();
            $collapsible.toggleClass(opts.current);
            if(opts.closeSiblings === true){
                $siblings.removeClass(opts.current);
                //check nested collapsibles
                if($children.length) {
                    $children.removeClass(opts.current);
                }
            }
        });
    };

	// jquery bindings
    ux = $.fn.collapsible = $.uxcollapsible = function(options){
		var selector = this.selector;

        return this.each(function(){
            var $el = $(this),
				uxrocket = $el.data('uxRocket') || {},
                collapsible;

			if($el.hasClass('uxitd-collapsible-ready')){
				return;
			}

			$el.addClass('uxitd-collapsible-ready');

            uxrocket['uxCollapsible'] = {'hasWrapper': false, 'ready': 'uxitd-collapsible-ready', 'selector': selector, 'options': options};

            $el.data('uxRocket', uxrocket);

            collapsible = new Collapsible(this, options);
        });
    };

    // Version
    ux.version = "0.3.0";

	// settings
	ux.settings = defaults;

})(jQuery);<commit_msg>Update uxrocket.accordion.js<commit_after>/**
 * UX Rocket
 * jQuery based accordion
 * @author Bilal Cinarli
 */

;(function($){
	var ux, // local shorthand

		defaults = {
			header: ".collapsible-header",
			content: ".collapsible-content",
			current: 'current',
			closeSiblings: false
		},
		events = {
			click: 'click.uxCollapsible'
		};

	// constructor method
    var Collapsible = function(el, options){
        var opts = $.extend({}, defaults, options, $(el).data()),

        // cached variables
        $collapsible = $(el),
        $header = $collapsible.find(opts.header),
        $siblings = $collapsible.siblings(),
        $children = $siblings.find('.uxitd-collapsible-ready');

        $(el).on(events.click , opts.header , function(e){
            e.preventDefault();
            e.stopPropagation();
            $collapsible.toggleClass(opts.current);
            if(opts.closeSiblings === true){
                $siblings.removeClass(opts.current);
                //check nested collapsibles
                if($children.length) {
                    $children.removeClass(opts.current);
                }
            }
        });
    };

	// jquery bindings
    ux = $.fn.collapsible = $.uxcollapsible = function(options){
		var selector = this.selector;

        return this.each(function(){
            var $el = $(this),
				uxrocket = $el.data('uxRocket') || {},
                collapsible;

			if($el.hasClass('uxitd-collapsible-ready')){
				return;
			}

			$el.addClass('uxitd-collapsible-ready');

            uxrocket['uxCollapsible'] = {'hasWrapper': false, 'ready': 'uxitd-collapsible-ready', 'selector': selector, 'options': options};

            $el.data('uxRocket', uxrocket);

            collapsible = new Collapsible(this, options);
        });
    };

    // Version
    ux.version = "0.3.1";

	// settings
	ux.settings = defaults;

})(jQuery);
<|endoftext|>