<commit_before>'use strict';

const gambitCampaigns = require('../gambit-campaigns');
const helpers = require('../helpers');
const logger = require('../logger');
const config = require('../../config/lib/helpers/topic');

/**
 * @param {String} topicId
 * @return {Promise}
 */
function fetchById(topicId) {
  logger.debug('helpers.topic.fetchById', { topicId });
  if (module.exports.isRandomTopicId(topicId)) {
    return Promise.reject({ status: 404 });
  }
  if (module.exports.isHardcodedTopicId(topicId)) {
    return Promise.resolve(topicId);
  }
  return gambitCampaigns.fetchTopicById(topicId);
}

/**
 * @param {Number} campaignId
 * @return {Promise}
 */
function fetchByCampaignId(campaignId) {
  logger.debug('helpers.topic.fetchByCampaignId', { campaignId });
  return helpers.campaign.fetchById(campaignId)
    .then(campaign => campaign.topics.map(topic => Object.assign(topic, { campaign })));
}

/**
 * @param {Object} topic
 * @param {String} templateName
 */
function getRenderedTextFromTopicAndTemplateName(topic, templateName) {
  const template = topic.templates[templateName];
  // This rendered property will eventually get phased out, always query by text.
  if (template.rendered) {
    return template.rendered;
  }
  return template.text;
}

/**
 * @param {Object} topic
 * @return {Boolean}
 */
function isAutoReplyTopic(topic) {
  return config.autoReplyTypes.includes(topic.type);
}

/**
 * @param {String} topicId
 * @return {Boolean}
 */
function isHardcodedTopicId(topicId) {
  return config.hardcodedTopicIds.includes(topicId);
}

/**
 * @param {String} topicId
 * @return {Boolean}
 */
function isRandomTopicId(topicId) {
  return topicId === config.randomTopicId;
}

module.exports = {
  fetchById,
  fetchByCampaignId,
  getRenderedTextFromTopicAndTemplateName,
  isAutoReplyTopic,
  isHardcodedTopicId,
  isRandomTopicId,
};
<commit_msg>Cleanup per https://github.com/DoSomething/gambit-conversations/pull/373#discussion_r205526143<commit_after>'use strict';

const gambitCampaigns = require('../gambit-campaigns');
const helpers = require('../helpers');
const logger = require('../logger');
const config = require('../../config/lib/helpers/topic');

/**
 * @param {String} topicId
 * @return {Promise}
 */
function fetchById(topicId) {
  logger.debug('helpers.topic.fetchById', { topicId });
  if (module.exports.isRandomTopicId(topicId)) {
    return Promise.reject({ status: 404 });
  }
  if (module.exports.isHardcodedTopicId(topicId)) {
    return Promise.resolve(topicId);
  }
  return gambitCampaigns.fetchTopicById(topicId);
}

/**
 * @param {Number} campaignId
 * @return {Promise}
 */
function fetchByCampaignId(campaignId) {
  logger.debug('helpers.topic.fetchByCampaignId', { campaignId });
  return helpers.campaign.fetchById(campaignId)
    .then(campaign => campaign.topics.map(topic => Object.assign(topic, { campaign })));
}

/**
 * @param {Object} topic
 * @param {String} templateName
 */
function getRenderedTextFromTopicAndTemplateName(topic, templateName) {
  const template = topic.templates[templateName];
  // This rendered property will eventually get phased out, always query by text.
  return template.rendered || template.text;
}

/**
 * @param {Object} topic
 * @return {Boolean}
 */
function isAutoReplyTopic(topic) {
  return config.autoReplyTypes.includes(topic.type);
}

/**
 * @param {String} topicId
 * @return {Boolean}
 */
function isHardcodedTopicId(topicId) {
  return config.hardcodedTopicIds.includes(topicId);
}

/**
 * @param {String} topicId
 * @return {Boolean}
 */
function isRandomTopicId(topicId) {
  return topicId === config.randomTopicId;
}

module.exports = {
  fetchById,
  fetchByCampaignId,
  getRenderedTextFromTopicAndTemplateName,
  isAutoReplyTopic,
  isHardcodedTopicId,
  isRandomTopicId,
};
<|endoftext|>


<commit_before>module.exports = function(less) {

	var ParamStringReplacementNode = require('./param-string-replacement-node')(less);

    function InlineImages() {
        this._visitor = new less.visitors.Visitor(this);
    }

    InlineImages.prototype = {
        isReplacing: true,
        isPreEvalVisitor: true,
        run: function (root) {
            return this._visitor.visit(root);
        },
        visitRule: function (ruleNode, visitArgs) {
            this._inRule = true;
            return ruleNode;
        },
        visitRuleOut: function (ruleNode, visitArgs) {
            this._inRule = false;
        },
        visitUrl: function (URLNode, visitArgs) {
            if (!this._inRule) {
                return URLNode;
            }
            if (URLNode.value.value.indexOf('#') === 0) {
              // Might be part of a VML url-node value like:
              // ``behavior:url(#default#VML);``
              return URLNode;
            }
            return new less.tree.Call("data-uri", [new ParamStringReplacementNode(URLNode.value)], URLNode.index || 0, URLNode.currentFileInfo);
        }
    };
    return InlineImages;
};
<commit_msg>check url value safely<commit_after>module.exports = function(less) {

	var ParamStringReplacementNode = require('./param-string-replacement-node')(less);

    function InlineImages() {
        this._visitor = new less.visitors.Visitor(this);
    }

    InlineImages.prototype = {
        isReplacing: true,
        isPreEvalVisitor: true,
        run: function (root) {
            return this._visitor.visit(root);
        },
        visitRule: function (ruleNode, visitArgs) {
            this._inRule = true;
            return ruleNode;
        },
        visitRuleOut: function (ruleNode, visitArgs) {
            this._inRule = false;
        },
        visitUrl: function (URLNode, visitArgs) {
            if (!this._inRule) {
                return URLNode;
            }
            if (URLNode.value && URLNode.value.value && URLNode.value.value.indexOf('#') === 0) {
              // Might be part of a VML url-node value like:
              // ``behavior:url(#default#VML);``
              return URLNode;
            }
            return new less.tree.Call("data-uri", [new ParamStringReplacementNode(URLNode.value)], URLNode.index || 0, URLNode.currentFileInfo);
        }
    };
    return InlineImages;
};
<|endoftext|>


<commit_before>'use strict';

const nunjucks = require('nunjucks');

// const sass = require('node-sass');

/**
 *  TODO: Use the actual renderer in here
 */
nunjucks.configure({ autoescape: true });

/*
 * Common tests for input plugins
 *
 * @param {object} test ava test runner
 * @param {object} plugin input plugin
 *
 * @returns {object} plugin input plugin
 */
module.exports = function pluginTests(test, plugin) {
  const validation = Object.keys(plugin.validation);
  let inputs = [];

  if (!test) {
    return 'you must include a test runner';
  }
  if (!plugin) {
    return 'you must include a plugin to test';
  }
  if (typeof plugin !== 'object') {
    return 'plugin must be an object';
  }

  test('Required core keys available', t => {
    t.true(plugin.hasOwnProperty('html'), 'HTML is included');
    t.true(plugin.hasOwnProperty('inputs'), 'Inputs are included');
    t.true(plugin.hasOwnProperty('validation'), 'Validation is included');
    t.true(plugin.hasOwnProperty('name'), 'Input has a name');
    t.true(plugin.hasOwnProperty('description'), 'Input has a description');
  });

  test('Validation configured correctly', t => {
    t.true(validation.length > 0, 'There is at least one validation function');

    validation.map(func => {
      t.true(typeof plugin.validation[func] === 'function', 'All validation functions are run-able functions');

      return func;
    });
  });

  test('Inputs configured correctly', t => {
    inputs = Object.keys(plugin.inputs);

    t.true(inputs.length > 0, 'There is at least one input');

    inputs.map(input => {
      const imp = plugin.inputs[input];

      // Validation
      t.true(imp.hasOwnProperty('validation'), 'Input has validation');
      t.true(typeof imp.validation === 'object', 'Validation is an object');

      // Validation Function
      t.true(imp.validation.hasOwnProperty('function'), 'Input validation has a `function` property');
      t.true(validation.indexOf(imp.validation.function) >= 0, 'Input validation function exists in the plugin\'s validation list');

      // Validation On
      t.true(imp.validation.hasOwnProperty('on'), 'Input validation has an `on` property');
      t.true(typeof imp.validation.on === 'string', 'Input validation on is a string');

      // Label
      t.true(imp.hasOwnProperty('label'), 'Input has a `label` property');
      t.true(typeof imp.label === 'string', 'Input label is a string');

      // Type
      t.true(imp.hasOwnProperty('type'), 'Input has a `type` property');
      t.true(typeof imp.type === 'string', 'Input type is a string');

      if (imp.hasOwnProperty('options')) {
        t.true(Array.isArray(imp.options), 'Options is an array');
        imp.options.forEach(option => {
          t.true(option.hasOwnProperty('value'), 'Option has a `value` property');
          t.true(typeof option.value === 'string', 'Option value is a string');
          t.true(option.hasOwnProperty('label'), 'Option has a `label` property');
          t.true(typeof option.label === 'string', 'Option label is a string');
        });
      }

      return input;
    });
  });

  test('HTML is written correctly, includes required attributes, and is render-able', t => {
    const htmls = [
      {
        tag: ['label'],
        prop: 'for',
        key: 'id',
        message: 'Label exists and contains the input\'s ID',
      },
      {
        tag: ['input', 'select', 'textarea'],
        prop: 'id',
        key: 'id',
        message: 'Input exists and contains its ID',
      },
      {
        tag: ['input'],
        prop: 'type',
        key: 'type',
        message: 'Input exists and contains its type',
      },
      {
        tag: ['input', 'textarea'],
        prop: 'value',
        key: 'value',
        message: 'Input exists and contains its value',
      },
      {
        tag: ['input', 'select', 'textarea'],
        prop: 'name',
        key: 'name',
        message: 'Input exists and contains its name',
      },
    ];
    const options = ['select', 'checkbox', 'radio'];
    let inputTests = [];
    let optionsTests = [];

    // Make sure tests are a string
    t.true(typeof plugin.html === 'string', 'HTML is a string');

    // Try and render it
    const rendered = nunjucks.renderString(plugin.html, {});
    t.true(typeof rendered === 'string', 'HTML must be a render-able by nunjucks');

    inputTests = inputs.map(input => {
      return htmls.map(tst => {
        let htmlRegex;
        let tag = 'input';
        const thisTest = tst;

        // do not these run tests on radios or checkboxes
        if ((plugin.inputs[input].type === 'radio') || (plugin.inputs[input].type === 'checkbox')) {
          return {};
        }

        if (thisTest.tag[0] === 'label') {
          tag = 'label';
        }

        // not all tests should be run on selects/textareas
        if (((plugin.inputs[input].type === 'select') || (plugin.inputs[input].type === 'textarea')) && tag !== 'label') {
          if (thisTest.tag.indexOf(plugin.inputs[input].type) < 0) {
            return {};
          }
          tag = plugin.inputs[input].type;
        }

        if (plugin.inputs[input].type === 'textarea') {
          if (thisTest.prop === 'value') {
            htmlRegex = new RegExp(`<textarea.*>{{\\s*${input}.value\\s*}}<\/textarea>`);
          }
        }

        htmlRegex = htmlRegex || new RegExp(`<${tag}[a-zA-Z\\d\\=\\"\\{\\}\\s\\-\\_\\|\\.\\(\\)\\%\\']*(${thisTest.prop}=['"]\\s*{{\\s*${input}.${thisTest.key}\\s*}}\\s*['"])`);

        return {
          regex: htmlRegex,
          message: `${thisTest.message} [${input}]`,
        };
      });
    });

    optionsTests = inputs.map(input => {
      return htmls.map(tst => {
        const thisTest = tst;
        let htmlRegex;
        let key;
        let tag = 'input';
        if (options.indexOf(plugin.inputs[input].type) < 0) {
          return {};
        }

        if (thisTest.tag[0] === 'label') {
          tag = 'label';
        }
        if (plugin.inputs[input].type === 'select') {
          tag = 'option';
        }
        else {
          const iterator = plugin.html.match(new RegExp('{%\\s*?for\\s*([\\w\S]*)'));

          if ((thisTest.prop === 'id') || (thisTest.prop === 'for')) {
            key = `${input}.${thisTest.key}}}--{{loop.index`;
          }
          else if (thisTest.prop === 'value') {
            key = `${iterator[1]}.value`;
          }
          else {
            key = `${input}.${thisTest.key}`;
          }

          htmlRegex = new RegExp(`<${tag}[a-zA-Z\\d\\=\\"\\{\\}\\s\\-\\_\\|\\.\\(\\)\\%\\']*(${thisTest.prop}=['"]\\s*{{\\s*${key}\\s*}}\\s*['"])`);
        }

        return {
          regex: htmlRegex,
          message: `${thisTest.message} [${input}]`,
        };
      });
    });

    inputTests = [].concat.apply([], inputTests);
    optionsTests = [].concat.apply([], optionsTests);
    inputTests = inputTests.concat(optionsTests);

    inputTests = inputTests.filter(tst => {
      if (!tst) {
        return false;
      }

      return true;
    });

    // Regex test all of the htmls we need
    inputTests.map(tst => {
      if (tst.regex) {
        t.regex(plugin.html, tst.regex, tst.message);
      }
    });
  });

  // test('npm-based Javascript should be a string or array', t => {
  //   if (plugin.hasOwnProperty('javascript') && plugin.javascript.hasOwnProperty('npm')) {
  //     let validated = false;
  //     if (typeof (plugin.javascript.npm) === 'string' || Array.isArray(plugin.javascript.npm)) {
  //       validated = true;
  //     }
  //     t.ok(validated, 'if local Javascript exists, it must be a string or array');
  //   }
  // });

  // test('local Javascript should be a string or array', t => {
  //   if (plugin.hasOwnProperty('javascript') && plugin.javascript.hasOwnProperty('local')) {
  //     let validated = false;
  //     if (typeof (plugin.javascript.local) === 'string' || Array.isArray(plugin.javascript.local)) {
  //       validated = true;
  //     }
  //     t.ok(validated, 'if UX Javascript exists, it must be a string or array');
  //   }
  // });

  // test.cb('UX Styling must be a actual css', t => {
  //   if (plugin.hasOwnProperty('styling')) {
  //     let validated = false;
  //     const renderedVars = nunjucks.renderString(plugin.styling, plugin);
  //     sass.render({
  //       data: renderedVars
  //       },
  //       function(err, result) {
  //         if (!err) {
  //           validated = true;
  //         }
  //         t.ok(validated, 'UX styling must be CSS');
  //         t.end();
  //       }
  //     );
  //   }
  //   else {
  //     t.end();
  //   }
  // });

  return plugin;
};
<commit_msg>:bug: was finding all nunjucks fors<commit_after>'use strict';

const nunjucks = require('nunjucks');

// const sass = require('node-sass');

/**
 *  TODO: Use the actual renderer in here
 */
nunjucks.configure({ autoescape: true });

/*
 * Common tests for input plugins
 *
 * @param {object} test ava test runner
 * @param {object} plugin input plugin
 *
 * @returns {object} plugin input plugin
 */
module.exports = function pluginTests(test, plugin) {
  let validation;
  let inputs = [];

  if (!test) {
    return 'you must include a test runner';
  }
  if (!plugin) {
    return 'you must include a plugin to test';
  }
  if (typeof plugin !== 'object') {
    return 'plugin must be an object';
  }

  if (plugin.hasOwnProperty('validation')) {
    validation = Object.keys(plugin.validation);
  }

  test('Required core keys available', t => {
    t.true(plugin.hasOwnProperty('html'), 'HTML is included');
    t.true(plugin.hasOwnProperty('inputs'), 'Inputs are included');
    t.true(plugin.hasOwnProperty('validation'), 'Validation is included');
    t.true(plugin.hasOwnProperty('name'), 'Input has a name');
    t.true(plugin.hasOwnProperty('description'), 'Input has a description');
  });

  test('Validation configured correctly', t => {
    t.true(validation.length > 0, 'There is at least one validation function');

    validation.map(func => {
      t.true(typeof plugin.validation[func] === 'function', 'All validation functions are run-able functions');

      return func;
    });
  });

  test('Inputs configured correctly', t => {
    inputs = Object.keys(plugin.inputs);

    t.true(inputs.length > 0, 'There is at least one input');

    inputs.map(input => {
      const imp = plugin.inputs[input];

      // Validation
      t.true(imp.hasOwnProperty('validation'), 'Input has validation');
      t.true(typeof imp.validation === 'object', 'Validation is an object');

      // Validation Function
      t.true(imp.validation.hasOwnProperty('function'), 'Input validation has a `function` property');
      t.true(validation.indexOf(imp.validation.function) >= 0, 'Input validation function exists in the plugin\'s validation list');

      // Validation On
      t.true(imp.validation.hasOwnProperty('on'), 'Input validation has an `on` property');
      t.true(typeof imp.validation.on === 'string', 'Input validation on is a string');

      // Label
      t.true(imp.hasOwnProperty('label'), 'Input has a `label` property');
      t.true(typeof imp.label === 'string', 'Input label is a string');

      // Type
      t.true(imp.hasOwnProperty('type'), 'Input has a `type` property');
      t.true(typeof imp.type === 'string', 'Input type is a string');

      if (imp.hasOwnProperty('options')) {
        t.true(Array.isArray(imp.options), 'Options is an array');
        imp.options.forEach(option => {
          t.true(option.hasOwnProperty('value'), 'Option has a `value` property');
          t.true(typeof option.value === 'string', 'Option value is a string');
          t.true(option.hasOwnProperty('label'), 'Option has a `label` property');
          t.true(typeof option.label === 'string', 'Option label is a string');
        });
      }

      return input;
    });
  });

  test('HTML is written correctly, includes required attributes, and is render-able', t => {
    const htmls = [
      {
        tag: ['label'],
        prop: 'for',
        key: 'id',
        message: 'Label exists and contains the input\'s ID',
      },
      {
        tag: ['input', 'select', 'textarea'],
        prop: 'id',
        key: 'id',
        message: 'Input exists and contains its ID',
      },
      {
        tag: ['input'],
        prop: 'type',
        key: 'type',
        message: 'Input exists and contains its type',
      },
      {
        tag: ['input', 'textarea'],
        prop: 'value',
        key: 'value',
        message: 'Input exists and contains its value',
      },
      {
        tag: ['input', 'select', 'textarea'],
        prop: 'name',
        key: 'name',
        message: 'Input exists and contains its name',
      },
    ];
    const options = ['select', 'checkbox', 'radio'];
    let inputTests = [];
    let optionsTests = [];

    // Make sure tests are a string
    t.true(typeof plugin.html === 'string', 'HTML is a string');

    // Try and render it
    const rendered = nunjucks.renderString(plugin.html, {});
    t.true(typeof rendered === 'string', 'HTML must be a render-able by nunjucks');

    inputTests = inputs.map(input => {
      return htmls.map(tst => {
        let htmlRegex;
        let tag = 'input';
        const thisTest = tst;

        // do not these run tests on radios or checkboxes
        if ((plugin.inputs[input].type === 'radio') || (plugin.inputs[input].type === 'checkbox')) {
          return {};
        }

        if (thisTest.tag[0] === 'label') {
          tag = 'label';
        }

        // not all tests should be run on selects/textareas
        if (((plugin.inputs[input].type === 'select') || (plugin.inputs[input].type === 'textarea')) && tag !== 'label') {
          if (thisTest.tag.indexOf(plugin.inputs[input].type) < 0) {
            return {};
          }
          tag = plugin.inputs[input].type;
        }

        if (plugin.inputs[input].type === 'textarea') {
          if (thisTest.prop === 'value') {
            htmlRegex = new RegExp(`<textarea.*>{{\\s*${input}.value\\s*}}<\/textarea>`);
          }
        }

        htmlRegex = htmlRegex || new RegExp(`<${tag}[a-zA-Z\\d\\=\\"\\{\\}\\s\\-\\_\\|\\.\\(\\)\\%\\']*(${thisTest.prop}=['"]\\s*{{\\s*${input}.${thisTest.key}\\s*}}\\s*['"])`);

        return {
          regex: htmlRegex,
          message: `${thisTest.message} [${input}]`,
        };
      });
    });

    optionsTests = inputs.map(input => {
      return htmls.map(tst => {
        const thisTest = tst;
        let htmlRegex;
        let key;
        let tag = 'input';
        if (options.indexOf(plugin.inputs[input].type) < 0) {
          return {};
        }

        if (thisTest.tag[0] === 'label') {
          tag = 'label';
        }
        if (plugin.inputs[input].type === 'select') {
          tag = 'option';
        }
        else {
          const iterator = plugin.html.match(new RegExp(`{%\\s*?for\\s*([\\w\S]*)\\s*?in\\s*?${input}`));

          if ((thisTest.prop === 'id') || (thisTest.prop === 'for')) {
            key = `${input}.${thisTest.key}}}--{{loop.index`;
          }
          else if (thisTest.prop === 'value') {
            key = `${iterator[1]}.value`;
          }
          else {
            key = `${input}.${thisTest.key}`;
          }

          htmlRegex = new RegExp(`<${tag}[a-zA-Z\\d\\=\\"\\{\\}\\s\\-\\_\\|\\.\\(\\)\\%\\']*(${thisTest.prop}=['"]\\s*{{\\s*${key}\\s*}}\\s*['"])`);
        }

        return {
          regex: htmlRegex,
          message: `${thisTest.message} [${input}]`,
        };
      });
    });

    inputTests = [].concat.apply([], inputTests);
    optionsTests = [].concat.apply([], optionsTests);
    inputTests = inputTests.concat(optionsTests);

    inputTests = inputTests.filter(tst => {
      if (!tst) {
        return false;
      }

      return true;
    });

    // Regex test all of the htmls we need
    inputTests.map(tst => {
      if (tst.regex) {
        t.regex(plugin.html, tst.regex, tst.message);
      }
    });
  });

  // test('npm-based Javascript should be a string or array', t => {
  //   if (plugin.hasOwnProperty('javascript') && plugin.javascript.hasOwnProperty('npm')) {
  //     let validated = false;
  //     if (typeof (plugin.javascript.npm) === 'string' || Array.isArray(plugin.javascript.npm)) {
  //       validated = true;
  //     }
  //     t.ok(validated, 'if local Javascript exists, it must be a string or array');
  //   }
  // });

  // test('local Javascript should be a string or array', t => {
  //   if (plugin.hasOwnProperty('javascript') && plugin.javascript.hasOwnProperty('local')) {
  //     let validated = false;
  //     if (typeof (plugin.javascript.local) === 'string' || Array.isArray(plugin.javascript.local)) {
  //       validated = true;
  //     }
  //     t.ok(validated, 'if UX Javascript exists, it must be a string or array');
  //   }
  // });

  // test.cb('UX Styling must be a actual css', t => {
  //   if (plugin.hasOwnProperty('styling')) {
  //     let validated = false;
  //     const renderedVars = nunjucks.renderString(plugin.styling, plugin);
  //     sass.render({
  //       data: renderedVars
  //       },
  //       function(err, result) {
  //         if (!err) {
  //           validated = true;
  //         }
  //         t.ok(validated, 'UX styling must be CSS');
  //         t.end();
  //       }
  //     );
  //   }
  //   else {
  //     t.end();
  //   }
  // });

  return plugin;
};
<|endoftext|>


<commit_before>/*jshint eqnull:true */
/*!
 * jQuery Cookie Plugin v1.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function($, document) {

	var pluses = /\+/g;
	function raw(s) {
		return s;
	}
	function decoded(s) {
		return decodeURIComponent(s.replace(pluses, ' '));
	}

	$.cookie = function(key, value, options) {

		// key and at least value given, set cookie...
		if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) {
			options = $.extend({}, $.cookie.defaults, options);

			if (value == null) {
				options.expires = -1;
			}

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}

			value = String(value);

			return (document.cookie = [
				encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
			].join(''));
		}

		// key and possibly options given, get cookie...
		options = value || $.cookie.defaults || {};
		var decode = options.raw ? raw : decoded;
		var cookies = document.cookie.split('; ');
		for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
			if (decode(parts.shift()) === key) {
				return decode(parts.join('='));
			}
		}
		return null;
	};

	$.cookie.defaults = {};

})(jQuery, document);<commit_msg>Update jquery.cookie.js to 1.3.1<commit_after>/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals.
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function raw(s) {
        return s;
    }

    function decoded(s) {
        return decodeURIComponent(s.replace(pluses, ' '));
    }

    function converted(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }
        try {
            return config.json ? JSON.parse(s) : s;
        } catch(er) {}
    }

    var config = $.cookie = function (key, value, options) {

        // write
        if (value !== undefined) {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = config.json ? JSON.stringify(value) : String(value);

            return (document.cookie = [
                config.raw ? key : encodeURIComponent(key),
                '=',
                config.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // read
        var decode = config.raw ? raw : decoded;
        var cookies = document.cookie.split('; ');
        var result = key ? undefined : {};
        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = decode(parts.join('='));

            if (key && key === name) {
                result = converted(cookie);
                break;
            }

            if (!key) {
                result[name] = converted(cookie);
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) !== undefined) {
            $.cookie(key, '', $.extend(options, { expires: -1 }));
            return true;
        }
        return false;
    };

}));<|endoftext|>


<commit_before>JS.require('JS.Class');

var __ = require('./import')('types');

exports.Node = new JS.Class('Node', {
  initialize: function (tag, value, startMark, endMark) {
    this.tag = tag;
    this.value = value;
    this.startMark = startMark;
    this.endMark = endMark;
  },
  hash: function () {
    var value = this.value.toString();
    return this.klass + '(' + this.tag + ', ' + value + ')';
  }
});

exports.Node.include(__.Hashable);

exports.ScalarNode = new JS.Class('ScalarNode', exports.Node, {
  extend: { id: 'scalar' },
  initialize: function (tag, value, startMark, endMark, style) {
    this.tag = tag;
    this.value = value;
    this.startMark = startMark || null;
    this.endMark = endMark || null;
    this.style = style || null;
  }
});

exports.CollectionNode = new JS.Class('CollectionNode', exports.Node, {
  initialize: function (tag, value, startMark, endMark, flowStyle) {
    this.tag = tag;
    this.value = value;
    this.startMark = startMark || null;
    this.endMark = endMark || null;
    this.flowStyle = flowStyle || null;
  }
});

exports.SequenceNode = new JS.Class('SequenceNode', exports.CollectionNode, {
  extend: { id: 'sequence' }
});

exports.MappingNode = new JS.Class('CollectionNode', exports.CollectionNode, {
  extend: { id: 'mapping' }
});

////////////////////////////////////////////////////////////////////////////////
// vim:ts=2:sw=2
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Fixed MappingNode class name<commit_after>JS.require('JS.Class');

var __ = require('./import')('types');

exports.Node = new JS.Class('Node', {
  initialize: function (tag, value, startMark, endMark) {
    this.tag = tag;
    this.value = value;
    this.startMark = startMark;
    this.endMark = endMark;
  },
  hash: function () {
    var value = this.value.toString();
    return this.klass + '(' + this.tag + ', ' + value + ')';
  }
});

exports.Node.include(__.Hashable);

exports.ScalarNode = new JS.Class('ScalarNode', exports.Node, {
  extend: { id: 'scalar' },
  initialize: function (tag, value, startMark, endMark, style) {
    this.tag = tag;
    this.value = value;
    this.startMark = startMark || null;
    this.endMark = endMark || null;
    this.style = style || null;
  }
});

exports.CollectionNode = new JS.Class('CollectionNode', exports.Node, {
  initialize: function (tag, value, startMark, endMark, flowStyle) {
    this.tag = tag;
    this.value = value;
    this.startMark = startMark || null;
    this.endMark = endMark || null;
    this.flowStyle = flowStyle || null;
  }
});

exports.SequenceNode = new JS.Class('SequenceNode', exports.CollectionNode, {
  extend: { id: 'sequence' }
});

exports.MappingNode = new JS.Class('MappingNode', exports.CollectionNode, {
  extend: { id: 'mapping' }
});

////////////////////////////////////////////////////////////////////////////////
// vim:ts=2:sw=2
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, Groupon, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * Neither the name of GROUPON nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
'use strict';

var fs = require('fs');
var path = require('path');

var Bluebird = require('bluebird');
var debug = require('debug')('nlm:license');
var globAsync = Bluebird.promisify(require('glob'));
var _ = require('lodash');

var readFileAsync = Bluebird.promisify(fs.readFile);
var writeFileAsync = Bluebird.promisify(fs.writeFile);

var COMMENT_TYPES = {
  '.js': {
    getLicenseHeader: function getLicenseHeader(licenseText) {
      var body = licenseText.split('\n')
        .map(function prefixLine(line) {
          return ' ' + ('* ' + line).trim();
        })
        .join('\n');
      return '/*\n' + body + '\n */';
    },
  },
  '.coffee': {
    getLicenseHeader: function getLicenseHeader(licenseText) {
      return '###\n' + licenseText + '\n###';
    },
  },
};

function collectFiles(cwd, whitelist, optionalExclude) {
  var exclude = [
    'node_modules/**/*', './node_modules/**/*',
  ].concat(optionalExclude || []);

  function scanDirectory(directory) {
    return globAsync(directory + '/**/*.{js,coffee}', {
      ignore: exclude,
      nodir: true,
      cwd: cwd,
      root: cwd, // so /lib works as "expected"
    });
  }

  return Bluebird
    .map(whitelist || ['.'], scanDirectory)
    .then(_.flatten)
    .map(function loadFile(relFilename) {
      var filename = path.join(cwd, relFilename);
      return Bluebird.props({
        filename: filename,
        content: readFileAsync(filename, 'utf8'),
      });
    });
}

function hasNoLicenseHeader(entry) {
  return entry.content.indexOf(entry.licenseHeader) === -1;
}

function addLicenseHeader(entry) {
  debug('Adding license', entry.filename);
  entry.content = entry.licenseHeader + '\n' + entry.content;
  return entry;
}

function addMissingLicenseHeaders(files, licenseText) {
  // No license available?
  if (licenseText === null) {
    debug('No LICENSE file found, skipping license headers');
    return [];
  }

  var licenseHeaders = {
    '.js': COMMENT_TYPES['.js'].getLicenseHeader(licenseText),
    '.coffee': COMMENT_TYPES['.coffee'].getLicenseHeader(licenseText),
  };
  return files
    .map(function buildLicenseHeader(file) {
      file.licenseHeader = licenseHeaders[path.extname(file.filename)];
      return file;
    })
    .filter(hasNoLicenseHeader)
    .map(addLicenseHeader);
}

function getLicenseText(cwd) {
  return readFileAsync(path.join(cwd, 'LICENSE'), 'utf8')
    .then(_.trim)
    .catch(function catchNotFound(error) {
      if (error.code === 'ENOENT') {
        return null;
      }
      throw error;
    });
}

function collectMissingHeaders(cwd, whitelist, optionalExclude) {
  return Bluebird.all([
    // Collect all files that need a license header
    collectFiles(cwd, whitelist, optionalExclude),

    // Load the license text, minus surrounding whitespace
    getLicenseText(cwd),

  ]).spread(addMissingLicenseHeaders);
}

function writeLicenseHeaders(entry) {
  return writeFileAsync(entry.filename, entry.content, 'utf8')
    .then(_.constant(entry.filename));
}

function addLicenseHeaders(cwd, whitelist, optionalExclude) {
  return collectMissingHeaders(cwd, whitelist, optionalExclude)
    .map(writeLicenseHeaders);
}
module.exports = addLicenseHeaders;

addLicenseHeaders.collectMissing = collectMissingHeaders;
<commit_msg>fix: Only scan for files if LICENSE is present<commit_after>/*
 * Copyright (c) 2015, Groupon, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * Neither the name of GROUPON nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
'use strict';

var fs = require('fs');
var path = require('path');

var Bluebird = require('bluebird');
var debug = require('debug')('nlm:license');
var globAsync = Bluebird.promisify(require('glob'));
var _ = require('lodash');

var readFileAsync = Bluebird.promisify(fs.readFile);
var writeFileAsync = Bluebird.promisify(fs.writeFile);

var COMMENT_TYPES = {
  '.js': {
    getLicenseHeader: function getLicenseHeader(licenseText) {
      var body = licenseText.split('\n')
        .map(function prefixLine(line) {
          return ' ' + ('* ' + line).trim();
        })
        .join('\n');
      return '/*\n' + body + '\n */';
    },
  },
  '.coffee': {
    getLicenseHeader: function getLicenseHeader(licenseText) {
      return '###\n' + licenseText + '\n###';
    },
  },
};

function collectFiles(cwd, whitelist, optionalExclude) {
  var exclude = [
    'node_modules/**/*', './node_modules/**/*',
  ].concat(optionalExclude || []);

  function scanDirectory(directory) {
    return globAsync(directory + '/**/*.{js,coffee}', {
      ignore: exclude,
      nodir: true,
      cwd: cwd,
      root: cwd, // so /lib works as "expected"
    });
  }

  return Bluebird
    .map(whitelist || ['.'], scanDirectory)
    .then(_.flatten)
    .map(function loadFile(relFilename) {
      var filename = path.join(cwd, relFilename);
      return Bluebird.props({
        filename: filename,
        content: readFileAsync(filename, 'utf8'),
      });
    });
}

function hasNoLicenseHeader(entry) {
  return entry.content.indexOf(entry.licenseHeader) === -1;
}

function addLicenseHeader(entry) {
  debug('Adding license', entry.filename);
  entry.content = entry.licenseHeader + '\n' + entry.content;
  return entry;
}

function addMissingLicenseHeaders(licenseText, files) {
  var licenseHeaders = {
    '.js': COMMENT_TYPES['.js'].getLicenseHeader(licenseText),
    '.coffee': COMMENT_TYPES['.coffee'].getLicenseHeader(licenseText),
  };
  return files
    .map(function buildLicenseHeader(file) {
      file.licenseHeader = licenseHeaders[path.extname(file.filename)];
      return file;
    })
    .filter(hasNoLicenseHeader)
    .map(addLicenseHeader);
}

function getLicenseText(cwd) {
  return readFileAsync(path.join(cwd, 'LICENSE'), 'utf8')
    .then(_.trim)
    .catch(function catchNotFound(error) {
      if (error.code === 'ENOENT') {
        return null;
      }
      throw error;
    });
}

function collectMissingHeaders(cwd, whitelist, optionalExclude, licenseText) {
  // No license available?
  if (licenseText === null) {
    debug('No LICENSE file found, skipping license headers');
    return [];
  }

  return collectFiles(cwd, whitelist, optionalExclude)
    .then(_.partial(addMissingLicenseHeaders, licenseText));
}

function writeLicenseHeaders(entry) {
  return writeFileAsync(entry.filename, entry.content, 'utf8')
    .then(_.constant(entry.filename));
}

function addLicenseHeaders(cwd, whitelist, optionalExclude) {
  return getLicenseText(cwd)
    .then(_.partial(collectMissingHeaders, cwd, whitelist, optionalExclude))
    .map(writeLicenseHeaders);
}
module.exports = addLicenseHeaders;

addLicenseHeaders.collectMissing = collectMissingHeaders;
<|endoftext|>


<commit_before>(function(globalScope, undefined){

  // Context is the constructor for new rednering contexts
  var Context = function(){
    this.string = '';
    this.currentNode = this;
  };

  Context.addTag = function(tagName, isSelfClosing){
    if (isSelfClosing) {
      this.prototype[tagName] = function(attributes){
        this.string = this.string + '<' + tagName + '/>';
        return this;
      }
    } else {
      this.prototype[tagName] = function(attributes, text){
        var s = '<' + tagName;

        if (attributes) {
          for (attribute in attributes) {
            s = s + ' ' + attribute + "='" + attributes[attribute] + "' ";
          };
        };

        s = s + '>'

        if (text) {
          s = s + text;
        };

        this.string = this.string + s;

        var node = {tagName: tagName, parent: this.currentNode};
        this.currentNode = node;

        return this;
      }
    };
  };

  // javascript object literal that will become the prototype for Context
  var prototype = {
    toString: function(){
      return this.string;
    },
    end: function(){
      this.string = this.string + '</' + this.currentNode.tagName +'>'
      this.currentNode = this.currentNode.parent;
      return this;
    },
    text: function(value){
      this.string = this.string + value;
      return this;
    },
    append: function(value){
      this.text(value.toString);
    }
  };

  // a name space for the library
  var lib = {};

  // assign object literal to the Context constructor prototype
  Context.prototype = prototype;

  var tags = ['a','abbr','address','article','aside','audio','b','bdo','blockquote','body','button','canvas','caption','cite','code','col','colgroup','command','datalist','dd','del','details','dfn','div','dl','dt','em','embed','fieldset','figcaption','figure','footer','form','h1','h2','h3','h4','h5','h6','head','header','hgroup','html','i','iframe','ins','keygen','kbd','label','legend','li','map','mark','menu','meter','nav','noscript','object','ol','optgroup','option','output','p','pre','progress','q','rp','rt','ruby','samp','script','section','select','small','source','span','strike','strong','style','sub','summary','sup','table','tbody','td','textarea','tfoot','th','thead','time','title','tr','ul','var','video'];
  var selfClosingTags = ['area','br','hr','input','img','link','meta','param'];

  for (var i = tags.length - 1; i >= 0; i--){
    Context.addTag(tags[i], false)
  };

  for (var i = selfClosingTags.length - 1; i >= 0; i--){
    Context.addTag(selfClosingTags[i], true)
  };

  lib.build = function(){ return new Context(); };
  lib.Context = Context;

  globalScope.littleBuilder = lib;
})(window);<commit_msg>play nicer with libraries that alter Object.prototype<commit_after>(function(globalScope, undefined){

  // Context is the constructor for new rednering contexts
  var Context = function(){
    this.string = '';
    this.currentNode = this;
  };

  Context.addTag = function(tagName, isSelfClosing){
    if (isSelfClosing) {
      this.prototype[tagName] = function(attributes){
        this.string = this.string + '<' + tagName + '/>';
        return this;
      }
    } else {
      this.prototype[tagName] = function(attributes, text){
        var s = '<' + tagName;

        if (attributes) {
          for (attribute in attributes) {
            if (attributes.hasOwnProperty(attribute)) {
              s = s + ' ' + attribute + "='" + attributes[attribute] + "' ";
            }
          };
        };

        s = s + '>'

        if (text) {
          s = s + text;
        };

        this.string = this.string + s;

        var node = {tagName: tagName, parent: this.currentNode};
        this.currentNode = node;

        return this;
      }
    };
  };

  // javascript object literal that will become the prototype for Context
  var prototype = {
    toString: function(){
      return this.string;
    },
    end: function(){
      this.string = this.string + '</' + this.currentNode.tagName +'>'
      this.currentNode = this.currentNode.parent;
      return this;
    },
    text: function(value){
      this.string = this.string + value;
      return this;
    },
    append: function(value){
      this.text(value.toString);
    }
  };

  // a name space for the library
  var lib = {};

  // assign object literal to the Context constructor prototype
  Context.prototype = prototype;

  var tags = ['a','abbr','address','article','aside','audio','b','bdo','blockquote','body','button','canvas','caption','cite','code','col','colgroup','command','datalist','dd','del','details','dfn','div','dl','dt','em','embed','fieldset','figcaption','figure','footer','form','h1','h2','h3','h4','h5','h6','head','header','hgroup','html','i','iframe','ins','keygen','kbd','label','legend','li','map','mark','menu','meter','nav','noscript','object','ol','optgroup','option','output','p','pre','progress','q','rp','rt','ruby','samp','script','section','select','small','source','span','strike','strong','style','sub','summary','sup','table','tbody','td','textarea','tfoot','th','thead','time','title','tr','ul','var','video'];
  var selfClosingTags = ['area','br','hr','input','img','link','meta','param'];

  for (var i = tags.length - 1; i >= 0; i--){
    Context.addTag(tags[i], false)
  };

  for (var i = selfClosingTags.length - 1; i >= 0; i--){
    Context.addTag(selfClosingTags[i], true)
  };

  lib.build = function(){ return new Context(); };
  lib.Context = Context;

  globalScope.littleBuilder = lib;
})(window);<|endoftext|>


<commit_before>'use strict';

const co = require('co');
const path = require('path');
const pgp = require('pg-promise');

exports = module.exports = co.wrap(function* (driver, config) {
  let tableSql = path.resolve(__dirname, '../scripts/tables.sql');
  let parameters = [config.allowedSchemas, config.blacklist, config.exceptions];

  // ONLY allow whitelisted items:
  if (config.whitelist) {
    tableSql = path.resolve(__dirname, '../scripts/tables-whitelist.sql');
    parameters = [config.whitelist];
  }

  return yield driver.query(new pgp.QueryFile(tableSql), parameters);
});

<commit_msg>Update tables.js (#367)<commit_after>'use strict';

const co = require('co');
const path = require('path');
const pgp = require('pg-promise');

function sql(file) {
  var fullPath = path.join(__dirname, '../scripts/', file);
  return new pgp.QueryFile(fullPath, {minify: true});
}

let tableSql = sql('tables.sql');
let tableWhiteListSql = sql('tables-whitelist.sql');

exports = module.exports = co.wrap(function* (driver, config) {
  if(config.whitelist) {
      return yield driver.query(tableWhiteListSql, [config.whitelist]);
  } else {
      return yield driver.query(tableSql, [config.allowedSchemas, config.blacklist, config.exceptions]);
  }
});

<|endoftext|>


<commit_before>var os = Npm.require('os');
var uvmon = Npm.require('nodefly-uvmon');

var SYSTEM_METRICS_FIELDS = ['testfield'];

SystemModel = function () {
  var self = this;
  this.lastGetData = new Date().getTime();
}

_.extend(SystemModel.prototype, ApmModel.prototype);

SystemModel.prototype.getEventLoopData = function() {
  var data = uvmon.getData();
  var time = new Date().getTime();
  data.time = time - this.lastGetData;
  this.lastGetData = time;
  return data;
};

SystemModel.prototype.buildPayload = function() {
  var metrics = {};
  var uvData = this.getEventLoopData();
  metrics.sessions = Meteor.default_server.sessions.length;
  metrics.rssBytes = process.memoryUsage().rss;
  metrics.loadAverage = os.loadavg()[0];
  metrics.eventLoopTime = uvData.sum_ms;
  metrics.eventLoopCount = uvData.count;
  metrics.totalTime = uvData.time;
  return {systemMetrics: metrics};
};
<commit_msg>Use Date.now() and add startTime<commit_after>var os = Npm.require('os');
var uvmon = Npm.require('nodefly-uvmon');

var SYSTEM_METRICS_FIELDS = ['testfield'];

SystemModel = function () {
  var self = this;
  this.lastGetData = Date.now();
}

_.extend(SystemModel.prototype, ApmModel.prototype);

SystemModel.prototype.getEventLoopData = function() {
  var data = uvmon.getData();
  var time = Date.now();
  data.time = time - this.lastGetData;
  this.lastGetData = time;
  return data;
};

SystemModel.prototype.buildPayload = function() {
  var metrics = {};
  var uvData = this.getEventLoopData();
  metrics.startTime = Date.now();
  metrics.sessions = Meteor.default_server.sessions.length;
  metrics.rssBytes = process.memoryUsage().rss;
  metrics.loadAverage = os.loadavg()[0];
  metrics.eventLoopTime = uvData.sum_ms;
  metrics.eventLoopCount = uvData.count;
  metrics.totalTime = uvData.time;
  return {systemMetrics: metrics};
};
<|endoftext|>


<commit_before>var https = require('https');
var inquirer = require('inquirer');
module.exports = function () {
  var questions = [{
    type: "input",
    name: "username",
    message: "PayPal username:"
  }, {
    type: "password",
    name: "password",
    message: "PayPal password:"
  }];

  console.log('Obtaining OAuth2 access_token from PayPal.');
  inquirer.prompt(questions, function(credentials) {
    console.log(credentials);
  });
};
<commit_msg>Minor tweaks to login.js<commit_after>var https = require('https');
var inquirer = require('inquirer');

module.exports = function () {
  var questions = [{
    type: "input",
    name: "username",
    message: "PayPal username:"
  }, {
    type: "password",
    name: "password",
    message: "PayPal password:"
  }];

  console.log('Obtaining OAuth2 access_token from PayPal.');
  inquirer.prompt(questions, function(credentials) {
    console.log(credentials);
  });
};
<|endoftext|>


<commit_before>var timers = require('timers');

/**
 * Sort functions, Normalize and prepare sort parameters
 */
var formatSortValue = exports.formatSortValue = function(sortDirection) {
  var value = ("" + sortDirection).toLowerCase();

  switch (value) {
    case 'ascending':
    case 'asc':
    case '1':
      return 1;
    case 'descending':
    case 'desc':
    case '-1':
      return -1;
    default:
      throw new Error("Illegal sort clause, must be of the form "
                    + "[['field1', '(ascending|descending)'], "
                    + "['field2', '(ascending|descending)']]");
  }
};

var formattedOrderClause = exports.formattedOrderClause = function(sortValue) {
  var orderBy = {};
  if(sortValue == null) return null;
  if (Array.isArray(sortValue)) {
    if(sortValue.length === 0) {
      return null;
    }

    for(var i = 0; i < sortValue.length; i++) {
      if(sortValue[i].constructor == String) {
        orderBy[sortValue[i]] = 1;
      } else {
        orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]);
      }
    }
  } else if(sortValue != null && typeof sortValue == 'object') {
    orderBy = sortValue;
  } else if (typeof sortValue == 'string') {
    orderBy[sortValue] = 1;
  } else {
    throw new Error("Illegal sort clause, must be of the form " +
      "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");
  }

  return orderBy;
};

exports.encodeInt = function(value) {
  var buffer = new Buffer(4);
  buffer[3] = (value >> 24) & 0xff;
  buffer[2] = (value >> 16) & 0xff;
  buffer[1] = (value >> 8) & 0xff;
  buffer[0] = value & 0xff;
  return buffer;
}

exports.encodeIntInPlace = function(value, buffer, index) {
  buffer[index + 3] = (value >> 24) & 0xff;
	buffer[index + 2] = (value >> 16) & 0xff;
	buffer[index + 1] = (value >> 8) & 0xff;
	buffer[index] = value & 0xff;
}

exports.encodeCString = function(string) {
  var buf = new Buffer(string, 'utf8');
  return [buf, new Buffer([0])];
}

exports.decodeUInt32 = function(array, index) {
  return array[index] | array[index + 1] << 8 | array[index + 2] << 16 | array[index + 3] << 24;
}

// Decode the int
exports.decodeUInt8 = function(array, index) {
  return array[index];
}

/**
 * Context insensitive type checks
 */

var toString = Object.prototype.toString;

var isObject = exports.isObject = function (arg) {
  return '[object Object]' == toString.call(arg)
}

exports.isArray = function (arg) {
  return Array.isArray(arg) ||
    'object' == typeof arg && '[object Array]' == toString.call(arg)
}

exports.isDate = function (arg) {
  return 'object' == typeof arg && '[object Date]' == toString.call(arg)
}

exports.isRegExp = function (arg) {
  return 'object' == typeof arg && '[object RegExp]' == toString.call(arg)
}

/**
 * Wrap a Mongo error document in an Error instance
 * @ignore
 * @api private
 */
var toError = function(error) {
  if (error instanceof Error) return error;

  var msg = error.err || error.errmsg || error.errMessage || error;
  var e = new Error(msg);
  e.name = 'MongoError';

  // Get all object keys
  var keys = typeof error == 'object'
    ? Object.keys(error)
    : [];

  for(var i = 0; i < keys.length; i++) {
    e[keys[i]] = error[keys[i]];
  }

  return e;
}
exports.toError = toError;

/**
 * Convert a single level object to an array
 * @ignore
 * @api private
 */
exports.objectToArray = function(object) {
  var list = [];

  for(var name in object) {
    list.push(object[name])
  }

  return list;
}

/**
 * Handle single command document return
 * @ignore
 * @api private
 */
exports.handleSingleCommandResultReturn = function(override_value_true, override_value_false, callback) {
  return function(err, result, connection) {
    if(err && typeof callback == 'function') return callback(err, null);
    if(!result || !result.documents || result.documents.length == 0)
      if(typeof callback == 'function') return callback(toError("command failed to return results"), null)
    if(result && result.documents[0].ok == 1) {
      if(override_value_true) return callback(null, override_value_true)
      if(typeof callback == 'function') return callback(null, result.documents[0]);
    }

    // Return the error from the document
    if(typeof callback == 'function') return callback(toError(result.documents[0]), override_value_false);
  }
}

/**
 * Return correct processor
 * @ignore
 * @api private
 */
exports.processor = function() {
  // Set processor, setImmediate if 0.10 otherwise nextTick
  process.maxTickDepth = Infinity;
  // Only use nextTick
  return process.nextTick;
}

/**
 * Allow setting the socketTimeoutMS on all connections
 * to work around issues such as secondaries blocking due to compaction
 *
 * @ignore
 * @api private
 */
exports.setSocketTimeoutProperty = function(self, options) {
  Object.defineProperty(self, "socketTimeoutMS", {
      enumerable: true
    , get: function () { return options.socketTimeoutMS; }
    , set: function (value) {
      // Set the socket timeoutMS value
      options.socketTimeoutMS = value;

      // Get all the connections
      var connections = self.allRawConnections();
      for(var i = 0; i < connections.length; i++) {
        connections[i].socketTimeoutMS = value;
      }
    }
  });
}

/**
 * Determine if the server supports write commands
 *
 * @ignore
 * @api private
 */
exports.hasWriteCommands = function(connection) {
  return connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasWriteCommands;
}

/**
 * Fetch server capabilities
 *
 * @ignore
 * @api private
 */
exports.serverCapabilities = function(connection) {
  return connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasWriteCommands;
}

/**
 * Create index name based on field spec
 *
 * @ignore
 * @api private
 */
exports.parseIndexOptions = function(fieldOrSpec) {
  var fieldHash = {};
  var indexes = [];
  var keys;

  // Get all the fields accordingly
  if('string' == typeof fieldOrSpec) {
    // 'type'
    indexes.push(fieldOrSpec + '_' + 1);
    fieldHash[fieldOrSpec] = 1;
  } else if(Array.isArray(fieldOrSpec)) {
    fieldOrSpec.forEach(function(f) {
      if('string' == typeof f) {
        // [{location:'2d'}, 'type']
        indexes.push(f + '_' + 1);
        fieldHash[f] = 1;
      } else if(Array.isArray(f)) {
        // [['location', '2d'],['type', 1]]
        indexes.push(f[0] + '_' + (f[1] || 1));
        fieldHash[f[0]] = f[1] || 1;
      } else if(isObject(f)) {
        // [{location:'2d'}, {type:1}]
        keys = Object.keys(f);
        keys.forEach(function(k) {
          indexes.push(k + '_' + f[k]);
          fieldHash[k] = f[k];
        });
      } else {
        // undefined (ignore)
      }
    });
  } else if(isObject(fieldOrSpec)) {
    // {location:'2d', type:1}
    keys = Object.keys(fieldOrSpec);
    keys.forEach(function(key) {
      indexes.push(key + '_' + fieldOrSpec[key]);
      fieldHash[key] = fieldOrSpec[key];
    });
  }

  return {
    name: indexes.join("_"), keys: keys, fieldHash: fieldHash
  }
}

exports.decorateCommand = function(command, options, exclude) {
  for(var name in options) {
    if(exclude[name] == null) command[name] = options[name];
  }

  return command;
}

exports.shallowObjectCopy = function(object) {
  var c = {};
  for(var n in object) c[n] = object[n];
  return c;
}

<commit_msg>Ignore callback in single result returned if null<commit_after>var timers = require('timers');

/**
 * Sort functions, Normalize and prepare sort parameters
 */
var formatSortValue = exports.formatSortValue = function(sortDirection) {
  var value = ("" + sortDirection).toLowerCase();

  switch (value) {
    case 'ascending':
    case 'asc':
    case '1':
      return 1;
    case 'descending':
    case 'desc':
    case '-1':
      return -1;
    default:
      throw new Error("Illegal sort clause, must be of the form "
                    + "[['field1', '(ascending|descending)'], "
                    + "['field2', '(ascending|descending)']]");
  }
};

var formattedOrderClause = exports.formattedOrderClause = function(sortValue) {
  var orderBy = {};
  if(sortValue == null) return null;
  if (Array.isArray(sortValue)) {
    if(sortValue.length === 0) {
      return null;
    }

    for(var i = 0; i < sortValue.length; i++) {
      if(sortValue[i].constructor == String) {
        orderBy[sortValue[i]] = 1;
      } else {
        orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]);
      }
    }
  } else if(sortValue != null && typeof sortValue == 'object') {
    orderBy = sortValue;
  } else if (typeof sortValue == 'string') {
    orderBy[sortValue] = 1;
  } else {
    throw new Error("Illegal sort clause, must be of the form " +
      "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");
  }

  return orderBy;
};

exports.encodeInt = function(value) {
  var buffer = new Buffer(4);
  buffer[3] = (value >> 24) & 0xff;
  buffer[2] = (value >> 16) & 0xff;
  buffer[1] = (value >> 8) & 0xff;
  buffer[0] = value & 0xff;
  return buffer;
}

exports.encodeIntInPlace = function(value, buffer, index) {
  buffer[index + 3] = (value >> 24) & 0xff;
	buffer[index + 2] = (value >> 16) & 0xff;
	buffer[index + 1] = (value >> 8) & 0xff;
	buffer[index] = value & 0xff;
}

exports.encodeCString = function(string) {
  var buf = new Buffer(string, 'utf8');
  return [buf, new Buffer([0])];
}

exports.decodeUInt32 = function(array, index) {
  return array[index] | array[index + 1] << 8 | array[index + 2] << 16 | array[index + 3] << 24;
}

// Decode the int
exports.decodeUInt8 = function(array, index) {
  return array[index];
}

/**
 * Context insensitive type checks
 */

var toString = Object.prototype.toString;

var isObject = exports.isObject = function (arg) {
  return '[object Object]' == toString.call(arg)
}

exports.isArray = function (arg) {
  return Array.isArray(arg) ||
    'object' == typeof arg && '[object Array]' == toString.call(arg)
}

exports.isDate = function (arg) {
  return 'object' == typeof arg && '[object Date]' == toString.call(arg)
}

exports.isRegExp = function (arg) {
  return 'object' == typeof arg && '[object RegExp]' == toString.call(arg)
}

/**
 * Wrap a Mongo error document in an Error instance
 * @ignore
 * @api private
 */
var toError = function(error) {
  if (error instanceof Error) return error;

  var msg = error.err || error.errmsg || error.errMessage || error;
  var e = new Error(msg);
  e.name = 'MongoError';

  // Get all object keys
  var keys = typeof error == 'object'
    ? Object.keys(error)
    : [];

  for(var i = 0; i < keys.length; i++) {
    e[keys[i]] = error[keys[i]];
  }

  return e;
}
exports.toError = toError;

/**
 * Convert a single level object to an array
 * @ignore
 * @api private
 */
exports.objectToArray = function(object) {
  var list = [];

  for(var name in object) {
    list.push(object[name])
  }

  return list;
}

/**
 * Handle single command document return
 * @ignore
 * @api private
 */
exports.handleSingleCommandResultReturn = function(override_value_true, override_value_false, callback) {
  return function(err, result, connection) {
    if(callback == null) return;
    if(err && typeof callback == 'function') return callback(err, null);
    if(!result || !result.documents || result.documents.length == 0)
      if(typeof callback == 'function') return callback(toError("command failed to return results"), null)
    if(result && result.documents[0].ok == 1) {
      if(override_value_true) return callback(null, override_value_true)
      if(typeof callback == 'function') return callback(null, result.documents[0]);
    }

    // Return the error from the document
    if(typeof callback == 'function') return callback(toError(result.documents[0]), override_value_false);
  }
}

/**
 * Return correct processor
 * @ignore
 * @api private
 */
exports.processor = function() {
  // Set processor, setImmediate if 0.10 otherwise nextTick
  process.maxTickDepth = Infinity;
  // Only use nextTick
  return process.nextTick;
}

/**
 * Allow setting the socketTimeoutMS on all connections
 * to work around issues such as secondaries blocking due to compaction
 *
 * @ignore
 * @api private
 */
exports.setSocketTimeoutProperty = function(self, options) {
  Object.defineProperty(self, "socketTimeoutMS", {
      enumerable: true
    , get: function () { return options.socketTimeoutMS; }
    , set: function (value) {
      // Set the socket timeoutMS value
      options.socketTimeoutMS = value;

      // Get all the connections
      var connections = self.allRawConnections();
      for(var i = 0; i < connections.length; i++) {
        connections[i].socketTimeoutMS = value;
      }
    }
  });
}

/**
 * Determine if the server supports write commands
 *
 * @ignore
 * @api private
 */
exports.hasWriteCommands = function(connection) {
  return connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasWriteCommands;
}

/**
 * Fetch server capabilities
 *
 * @ignore
 * @api private
 */
exports.serverCapabilities = function(connection) {
  return connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasWriteCommands;
}

/**
 * Create index name based on field spec
 *
 * @ignore
 * @api private
 */
exports.parseIndexOptions = function(fieldOrSpec) {
  var fieldHash = {};
  var indexes = [];
  var keys;

  // Get all the fields accordingly
  if('string' == typeof fieldOrSpec) {
    // 'type'
    indexes.push(fieldOrSpec + '_' + 1);
    fieldHash[fieldOrSpec] = 1;
  } else if(Array.isArray(fieldOrSpec)) {
    fieldOrSpec.forEach(function(f) {
      if('string' == typeof f) {
        // [{location:'2d'}, 'type']
        indexes.push(f + '_' + 1);
        fieldHash[f] = 1;
      } else if(Array.isArray(f)) {
        // [['location', '2d'],['type', 1]]
        indexes.push(f[0] + '_' + (f[1] || 1));
        fieldHash[f[0]] = f[1] || 1;
      } else if(isObject(f)) {
        // [{location:'2d'}, {type:1}]
        keys = Object.keys(f);
        keys.forEach(function(k) {
          indexes.push(k + '_' + f[k]);
          fieldHash[k] = f[k];
        });
      } else {
        // undefined (ignore)
      }
    });
  } else if(isObject(fieldOrSpec)) {
    // {location:'2d', type:1}
    keys = Object.keys(fieldOrSpec);
    keys.forEach(function(key) {
      indexes.push(key + '_' + fieldOrSpec[key]);
      fieldHash[key] = fieldOrSpec[key];
    });
  }

  return {
    name: indexes.join("_"), keys: keys, fieldHash: fieldHash
  }
}

exports.decorateCommand = function(command, options, exclude) {
  for(var name in options) {
    if(exclude[name] == null) command[name] = options[name];
  }

  return command;
}

exports.shallowObjectCopy = function(object) {
  var c = {};
  for(var n in object) c[n] = object[n];
  return c;
}

<|endoftext|>


<commit_before>module.exports = function(options) {
    if (typeof options === 'string') {
        var browsers = options.split(",");
        options = {browsers: browsers};
    }
    return options;
};
<commit_msg>Update parse-options.js<commit_after>module.exports = function(options) {
    if (typeof options === 'string') {
        var browsers = options.split(/\s*,\s*/);
        options = {browsers: browsers};
    }
    return options;
};
<|endoftext|>


<commit_before>var _ = require('lodash');
var marked = require('marked');

// Utility function for splitting a list into groups
function splitBy(list, starter, ender) {
    var starts = 0;
    var ends = 0;
    var group = [];

    // Groups
    return _.reduce(list, function(groups, value) {
        // Ignore start and end delimiters in resulted groups
        if(starter(value)) {
            starts++;
        } else if(ender(value)) {
            ends++;
        }

        // Add current value to group
        group.push(value);

        // We've got a matching
        if(starts === ends && starts !== 0) {
            // Add group to end groups
            // (remove starter and ender token)
            groups.push(group.slice(1, -1));

            // Reset group
            group = [];
        }

        return groups;
    }, []);
}

function listSplit(nodes, start_type, end_type) {
    return splitBy(nodes, function(el) {
        return el.type === start_type;
    }, function(el) {
        return el.type === end_type;
    });
}

// Get the biggest list
// out of a list of marked nodes
function filterList(nodes) {
    return _.chain(nodes)
    .toArray()
    .rest(function(el) {
        // Get everything after list_start
        return el.type !== 'list_start';
    })
    .reverse()
    .rest(function(el) {
        // Get everything after list_end (remember we're reversed)
        return el.type !== 'list_end';
    })
    .reverse()
    .value().slice(1, -1);
}

// Parses an Article or Chapter title
// supports extracting links
function parseTitle(src, nums) {
    // Check if it's a link
    var matches = marked.InlineLexer.rules.link.exec(src);

    var level = nums.join('.');

    // Not a link, return plain text
    if(!matches) {
        return {
            title: src,
            level: level,
            path: null,
        };
    }

    return {
        title: matches[1],
        level: level,

        // Replace .md references with .html
        path: matches[2].replace(/\\/g, '/'),
    };
}

function parseChapter(nodes, nums) {
    // Convert single number to an array
    nums = _.isArray(nums) ? nums : [nums];

    return _.extend(parseTitle(_.first(nodes).text, nums), {
        articles: _.map(listSplit(filterList(nodes), 'list_item_start', 'list_item_end'), function(nodes, i) {
            return parseChapter(nodes, nums.concat(i + 1));
        })
    });
}

function defaultChapterList(chapterList) {
    var first = _.first(chapterList);

    if (first) {
        var chapter = parseChapter(first, [0]);

        // Already have README node, we're good to go
        if(chapter.path === 'README.md') {
            return chapterList;
        }
    }

    return [
        [ { type: 'text', text: '[Introduction](README.md)' } ]
    ].concat(chapterList);
}

function listGroups(src) {
    var nodes = marked.lexer(src);

    // Get out groups of lists
    return listSplit(
        filterList(nodes),
        'list_item_start', 'list_item_end'
    );
}

function parseSummary(src) {
    // Split out chapter sections
    var chapters = defaultChapterList(listGroups(src))
    .map(parseChapter);

    return {
        chapters: chapters
    };
}

function parseEntries (src) {
    return listGroups(src).map(parseChapter);
}

// Exports
module.exports = parseSummary;
module.exports.entries = parseEntries;
<commit_msg>Improve path normalization when parsing SUMMARY.md<commit_after>var _ = require('lodash');
var marked = require('marked');

// Utility function for splitting a list into groups
function splitBy(list, starter, ender) {
    var starts = 0;
    var ends = 0;
    var group = [];

    // Groups
    return _.reduce(list, function(groups, value) {
        // Ignore start and end delimiters in resulted groups
        if(starter(value)) {
            starts++;
        } else if(ender(value)) {
            ends++;
        }

        // Add current value to group
        group.push(value);

        // We've got a matching
        if(starts === ends && starts !== 0) {
            // Add group to end groups
            // (remove starter and ender token)
            groups.push(group.slice(1, -1));

            // Reset group
            group = [];
        }

        return groups;
    }, []);
}

function listSplit(nodes, start_type, end_type) {
    return splitBy(nodes, function(el) {
        return el.type === start_type;
    }, function(el) {
        return el.type === end_type;
    });
}

// Get the biggest list
// out of a list of marked nodes
function filterList(nodes) {
    return _.chain(nodes)
    .toArray()
    .rest(function(el) {
        // Get everything after list_start
        return el.type !== 'list_start';
    })
    .reverse()
    .rest(function(el) {
        // Get everything after list_end (remember we're reversed)
        return el.type !== 'list_end';
    })
    .reverse()
    .value().slice(1, -1);
}

// Parses an Article or Chapter title
// supports extracting links
function parseTitle(src, nums) {
    // Check if it's a link
    var matches = marked.InlineLexer.rules.link.exec(src);

    var level = nums.join('.');

    // Not a link, return plain text
    if(!matches) {
        return {
            title: src,
            level: level,
            path: null,
        };
    }

    return {
        title: matches[1],
        level: level,

        // Normalize path
        // 1. Convert Window's "\" to "/"
        // 2. Remove leading "/" if exists
        path: matches[2].replace(/\\/g, '/').replace(/^\/+/, ''),
    };
}

function parseChapter(nodes, nums) {
    // Convert single number to an array
    nums = _.isArray(nums) ? nums : [nums];

    return _.extend(parseTitle(_.first(nodes).text, nums), {
        articles: _.map(listSplit(filterList(nodes), 'list_item_start', 'list_item_end'), function(nodes, i) {
            return parseChapter(nodes, nums.concat(i + 1));
        })
    });
}

function defaultChapterList(chapterList) {
    var first = _.first(chapterList);

    if (first) {
        var chapter = parseChapter(first, [0]);

        // Already have README node, we're good to go
        if(chapter.path === 'README.md') {
            return chapterList;
        }
    }

    return [
        [ { type: 'text', text: '[Introduction](README.md)' } ]
    ].concat(chapterList);
}

function listGroups(src) {
    var nodes = marked.lexer(src);

    // Get out groups of lists
    return listSplit(
        filterList(nodes),
        'list_item_start', 'list_item_end'
    );
}

function parseSummary(src) {
    // Split out chapter sections
    var chapters = defaultChapterList(listGroups(src))
    .map(parseChapter);

    return {
        chapters: chapters
    };
}

function parseEntries (src) {
    return listGroups(src).map(parseChapter);
}

// Exports
module.exports = parseSummary;
module.exports.entries = parseEntries;
<|endoftext|>


<commit_before>var xmlstring = '\n\n<cas:serviceResponse xmlns:cas=\'http://www.yale.edu/tp/cas\'>\n\t<cas:authenticationSuccess>\n\t\t<cas:user>jmarca</cas:user>\n   \n\n\n<!-- Begin Ldap Attributes -->\n  \n  <cas:attributes>\n   \n  </cas:attributes>\n  \n<!-- End Ldap Attributes -->\n\t</cas:authenticationSuccess>\n</cas:serviceResponse>\n'

var xmlbadticketstring='<cas:serviceResponse xmlns:cas=\'http://www.yale.edu/tp/cas\'>\n\t<cas:authenticationFailure code=\'INVALID_TICKET\'>\n\t\tticket 'diediedie' not recognized\n\t</cas:authenticationFailure>\n</cas:serviceResponse>'

var libxmljs = require('libxmljs')

var saxparser = new libxmljs.SaxParser()
var usercharhandler=function(chars){
    console.log({'chars':chars})
    //req.session.name = user.text();
}
saxparser.on('startElementNS',function(elem, attrs, prefix, uri, namespaces) {
    console.log({'elem':elem
                ,'attrs':attrs
                ,'uri':uri
                ,'ns':namespaces})
    if(elem==='user'){
        console.log('user!')
        // valid user
        saxparser.on('characters',charhandler)
    }
});
saxparser.on('endElementNS',function(elem, attrs, prefix, uri, namespaces) {

    if(elem==='user'){
        console.log('turn off chars handler')
        // valid user
        saxparser.removeListener('characters',charhandler)
    }
})

saxparser.parseString(xmlstring)

saxparser.parseString(xmlbadticketstring)<commit_msg>little trial program is properly parsing cas attributes<commit_after>var xmlstring = '\n\n<cas:serviceResponse xmlns:cas=\'http://www.yale.edu/tp/cas\'>\n\t<cas:authenticationSuccess>\n\t\t<cas:user>jmarca</cas:user>\n   \n\n\n<!-- Begin Ldap Attributes -->\n  \n  <cas:attributes>\n   \n  </cas:attributes>\n  \n<!-- End Ldap Attributes -->\n\t</cas:authenticationSuccess>\n</cas:serviceResponse>\n'

var xmlbadticketstring='<cas:serviceResponse xmlns:cas=\'http://www.yale.edu/tp/cas\'>\n\t<cas:authenticationFailure code=\'INVALID_TICKET\'>\n\t\tticket 'diediedie' not recognized\n\t</cas:authenticationFailure>\n</cas:serviceResponse>'

var xmlattrs = '\n\n<cas:serviceResponse xmlns:cas=\'http://www.yale.edu/tp/cas\'>\n\t<cas:authenticationSuccess>\n\t\t<cas:user>jmarca</cas:user>\n   \n    \n     <mail>jmarca@translab.its.uci.edu</mail>\n    \n     <sn>Marca</sn>\n    \n     <cn>James Marca</cn>\n    \n     <givenName>James</givenName>\n    \n     <groups>[cn=admin,ou=groups,dc=ctmlabs,dc=org, cn=caltrans_d12_tmc,ou=groups,dc=ctmlabs,dc=org, cn=author,ou=groups,dc=ctmlabs,dc=org, cn=ctmlabs_staff,ou=groups,dc=ctmlabs,dc=org]</groups>\n    \n   \n\n\n<!-- Begin Ldap Attributes -->\n  \n  <cas:attributes>\n   \n    \n     <cas:mail>jmarca@translab.its.uci.edu</cas:mail>\n    \n     <cas:sn>Marca</cas:sn>\n    \n     <cas:cn>James Marca</cas:cn>\n    \n     <cas:givenName>James</cas:givenName>\n    \n     <cas:groups>[cn=admin,ou=groups,dc=ctmlabs,dc=org, cn=caltrans_d12_tmc,ou=groups,dc=ctmlabs,dc=org, cn=author,ou=groups,dc=ctmlabs,dc=org, cn=ctmlabs_staff,ou=groups,dc=ctmlabs,dc=org]</cas:groups>\n    \n   \n  </cas:attributes>\n  \n<!-- End Ldap Attributes -->\n\t</cas:authenticationSuccess>\n</cas:serviceResponse>\n'

var libxmljs = require('libxmljs')
var saxparser
var usercharhandler=function(chars){
    console.log({'userchars':chars})
    //req.session.name = user.text();
}
var attributes={}
var attrcharhandler=function(attrname){
    return function(chars){
        attributes[attrname]=chars
        console.log('capturing '+attrname+' '+chars)
    }
}
var attrhandler=function(e,a,p,u,n){
    console.log({'attrhandler':{'e':e,'u':u}})
    saxparser.once('characters',attrcharhandler(e))
}
function startHandler(elem, attrs, prefix, uri, namespaces) {
    console.log({'elem':elem
                ,'attrs':attrs
                ,'uri':uri
                ,'ns':namespaces})
    if(elem==='user'){
        console.log('user!')
        // valid user
        saxparser.on('characters',usercharhandler)
    }
    if(elem==='attributes'){
        console.log('attributes!')
        // valid user
        saxparser.on('startElementNS',attrhandler)
    }
}
function endHandler(elem, attrs, prefix, uri, namespaces) {

    if(elem==='user'){
        console.log('turn off chars handler')
        // valid user
        saxparser.removeListener('characters',usercharhandler)
    }
    if(elem==='attributes'){
        console.log('turn off attributes!')
        // valid user
        saxparser.removeListener('startElementNS',attrhandler)
    }
}

var async = require('async')
saxparser = new libxmljs.SaxParser()
saxparser.on('startElementNS',startHandler);
saxparser.on('endElementNS',endHandler)

async.forEach([xmlstring,xmlbadticketstring,xmlattrs]
          ,function(str,cb){
               console.log('next string')
               saxparser.removeAllListeners('endDocument')
               .on('endDocument',cb)
               saxparser.parseString(str)
           }
          ,function(e){
               console.log('done')
               if(attributes) console.log(attributes)
           });
<|endoftext|>


<commit_before>/* istanbul ignore next */(function() {
    var webpage = require("webpage"),
        system = require("system"),
        fs = require("fs"),
        webserver = require("webserver"),
        child_process = require("child_process");

    var config = JSON.parse(fs.read(system.args[1])),
        server = webserver.create(),
        pages = {},
        context = {};

    server.listen(config.phridge.port, function (req, res) {
        var pageIdMatch;

        if (req.url.indexOf(config.phridge.secret) === -1) {
            res.statusCode = 403;
            res.write("Forbidden");
            res.close();
            return;
        }

        if (pageIdMatch = /\/page\/([0-9]+)\?/.exec(req.url)) {
            runOnPage(pageIdMatch[1], req, res);
            return;
        }

        run(context, req, res);
    });

    function run(context, req, res) {
        var responseClosed = false;

        function resolve(val) {
            if (responseClosed) {
                throw new Error("Cannot resolve value: The response has already been closed. Have you called resolve/reject twice?");
            }
            res.statusCode = 200;
            res.write(JSON.stringify(val));
            res.close();
            responseClosed = true;
        }

        function reject(val) {
            if (responseClosed) {
                throw new Error("Cannot reject value: The response has already been closed. Have you called resolve/reject twice?");
            }
            res.statusCode = 400;
            res.write(JSON.stringify(val));
            res.close();
            responseClosed = true;
        }

        try {
            eval(req.post);
        } catch (err) {
            err.stack = err.stack.replace(/at :/g, "at phantomjs:");
            if (responseClosed) {
                system.stderr.writeLine(err.stack);
            } else {
                reject(err);
            }
        }
    }

    function runOnPage(pageId, request, response) {
        var page = pages[pageId];

        if (!page) {
            pages[pageId] = page = webpage.create();
        }

        run(page, request, response);
    }
})();<commit_msg>Removed unnecessary function wrapper<commit_after>var webpage = require("webpage"),
    system = require("system"),
    fs = require("fs"),
    webserver = require("webserver"),
    child_process = require("child_process");

var config = JSON.parse(fs.read(system.args[1])),
    server = webserver.create(),
    pages = {},
    context = {};

server.listen(config.phridge.port, function (req, res) {
    var pageIdMatch;

    if (req.url.indexOf(config.phridge.secret) === -1) {
        res.statusCode = 403;
        res.write("Forbidden");
        res.close();
        return;
    }

    if (pageIdMatch = /\/page\/([0-9]+)\?/.exec(req.url)) {
        runOnPage(pageIdMatch[1], req, res);
        return;
    }

    run(context, req, res);
});

function run(context, req, res) {
    var responseClosed = false;

    function resolve(val) {
        if (responseClosed) {
            throw new Error("Cannot resolve value: The response has already been closed. Have you called resolve/reject twice?");
        }
        res.statusCode = 200;
        res.write(JSON.stringify(val));
        res.close();
        responseClosed = true;
    }

    function reject(val) {
        if (responseClosed) {
            throw new Error("Cannot reject value: The response has already been closed. Have you called resolve/reject twice?");
        }
        res.statusCode = 400;
        res.write(JSON.stringify(val));
        res.close();
        responseClosed = true;
    }

    try {
        eval(req.post);
    } catch (err) {
        err.stack = err.stack.replace(/at :/g, "at phantomjs:");
        if (responseClosed) {
            system.stderr.writeLine(err.stack);
        } else {
            reject(err);
        }
    }
}

function runOnPage(pageId, request, response) {
    var page = pages[pageId];

    if (!page) {
        pages[pageId] = page = webpage.create();
    }

    run(page, request, response);
}<|endoftext|>


<commit_before>'use strict';

const EventEmitter = require('events').EventEmitter;
const path = require('path');
const requireIndex = require('requireindex');
const plugins = requireIndex(path.join(__dirname));
const version = require('../../package.json').version;
const Logger = require('js-logger');
const rndm = require('rndm');
var md5 = require('js-md5');

var zlib = require('zlib');

var World = require('../world');
var Command = require('../command');

module.exports.server = function(serv, options) {
  serv.pid = process.pid;
  serv.salt = rndm.base62(16);

  serv['online_players'] = 0;

  serv.log = Logger;
  serv.log.useDefaults();

  if(process.env.NODE_ENV == 'test') {
    serv.log.setLevel(serv.log.OFF);
  }

  serv.log.info('Starting dazed-sheep server version 0.30c (' + version + ')');

  serv.on('error', function(error) {
    serv.log.error('Oops! Something went wrong, ' + error);
  });

  serv.on('listening', function() {
    serv.log.info('Starting dazed-sheep server on *:' + serv._server.socketServer.address().port);
  });

  serv._server.on('login', (client) => {
    if(client.socket.listeners('end').length == 0) return;
    const player = new EventEmitter();
    player._client = client;
    player.commands = new Command({});

    Object.keys(plugins)
      .filter(pluginName => plugins[pluginName].player != undefined)
      .forEach(pluginName => plugins[pluginName].player(player, serv, options));

    serv.emit("newPlayer", player);
    player.emit('asap');
    player.login();
  });

  serv.heartbeat();
};

module.exports.player = function(player, serv, settings) {
  player.login = () => {
    var addr = player._client.socket.remoteAddress + ':' + player._client.socket.remotePort;

    player.verification_key = player._client.verification_key;
    player.id = serv.entityID;
    player.name = player._client.username;

    serv.log.info(player.name + '[/' + player._client.socket.remoteAddress + ':' + player._client.socket.remotePort + '] logged in with entity id ' + player.id);

    player._client.on('end', function() {
      serv.players.forEach(function(_player) {
        if(_player.id != player.id) {
          _player._client.write('despawn_player', {
            player_id: player.id,
          });
        }
      });
      const index = serv.players.indexOf(player);
      if (index > -1) {
        serv.players.splice(index, 1);
      }
      serv._writeAll('message', {
        player_id: player.id,
        message: '&e' + player.name + ' left the game'
      });
      serv.log.info(player.name + ' left the game');
      serv['online_players']--;
    });

    player._client.on('error', function(err) {
      serv.log.info(err.stack);
    });

    player._client.write('level_initialize', {});

    var compressedMap = zlib.gzipSync(serv.world.dump());

    for(var i = 0; i < compressedMap.length; i += 1024) {
      player._client.write('level_data_chunk', {
        chunk_data: compressedMap.slice(i, Math.min(i + 1024, compressedMap.length)),
        percent_complete: i == 0 ? 0 : Math.ceil(i / compressedMap.length * 100)
      });
    }

    player._client.write('level_finalize', {
      x_size: 256,
      y_size: 64,
      z_size: 256
    });

    if(settings['online-mode'] == true) {
      if(md5(serv.salt + player._client.username) == player.verification_key) {
        player.spawn();
      } else {
        player._client.write('disconnect_player', {
          disconnect_reason: 'Your username could not be verified!'
        });
        serv.log.info(player.name + ' couldn\'t be verified!');
      }
    } else {
      player.spawn();
    }
  };
};
<commit_msg>enforce player limit<commit_after>'use strict';

const EventEmitter = require('events').EventEmitter;
const path = require('path');
const requireIndex = require('requireindex');
const plugins = requireIndex(path.join(__dirname));
const version = require('../../package.json').version;
const Logger = require('js-logger');
const rndm = require('rndm');
var md5 = require('js-md5');

var zlib = require('zlib');

var World = require('../world');
var Command = require('../command');

module.exports.server = function(serv, options) {
  serv.pid = process.pid;
  serv.salt = rndm.base62(16);

  serv['online_players'] = 0;

  serv.log = Logger;
  serv.log.useDefaults();

  if(process.env.NODE_ENV == 'test') {
    serv.log.setLevel(serv.log.OFF);
  }

  serv.log.info('Starting dazed-sheep server version 0.30c (' + version + ')');

  serv.on('error', function(error) {
    serv.log.error('Oops! Something went wrong, ' + error);
  });

  serv.on('listening', function() {
    serv.log.info('Starting dazed-sheep server on *:' + serv._server.socketServer.address().port);
  });

  serv._server.on('login', (client) => {
    if(client.socket.listeners('end').length == 0) return;
    const player = new EventEmitter();
    player._client = client;
    player.commands = new Command({});

    Object.keys(plugins)
      .filter(pluginName => plugins[pluginName].player != undefined)
      .forEach(pluginName => plugins[pluginName].player(player, serv, options));

    serv.emit("newPlayer", player);
    player.emit('asap');
    player.login();
  });

  serv.heartbeat();
};

module.exports.player = function(player, serv, settings) {
  player.login = () => {
    var addr = player._client.socket.remoteAddress + ':' + player._client.socket.remotePort;

    player.verification_key = player._client.verification_key;
    player.id = serv.entityID;
    player.name = player._client.username;

    serv.log.info(player.name + '[/' + player._client.socket.remoteAddress + ':' + player._client.socket.remotePort + '] logged in with entity id ' + player.id);

    player._client.on('end', function() {
      serv.players.forEach(function(_player) {
        if(_player.id != player.id) {
          _player._client.write('despawn_player', {
            player_id: player.id,
          });
        }
      });
      const index = serv.players.indexOf(player);
      if (index > -1) {
        serv.players.splice(index, 1);
      }
      serv._writeAll('message', {
        player_id: player.id,
        message: '&e' + player.name + ' left the game'
      });
      serv.log.info(player.name + ' left the game');
      serv['online_players']--;
    });

    player._client.on('error', function(err) {
      serv.log.info(err.stack);
    });

    player._client.write('level_initialize', {});

    var compressedMap = zlib.gzipSync(serv.world.dump());

    for(var i = 0; i < compressedMap.length; i += 1024) {
      player._client.write('level_data_chunk', {
        chunk_data: compressedMap.slice(i, Math.min(i + 1024, compressedMap.length)),
        percent_complete: i == 0 ? 0 : Math.ceil(i / compressedMap.length * 100)
      });
    }

    player._client.write('level_finalize', {
      x_size: 256,
      y_size: 64,
      z_size: 256
    });

    if(settings['max-players'] < serv['online_players'] + 1) {
      player._client.write('disconnect_player', {
        disconnect_reason: 'The player limit has been reached, please try again later'
      });
    } else {
      if(settings['online-mode'] == true) {
        if(md5(serv.salt + player._client.username) == player.verification_key) {
          player.spawn();
        } else {
          player._client.write('disconnect_player', {
            disconnect_reason: 'Your username could not be verified!'
          });
          serv.log.info(player.name + ' couldn\'t be verified!');
        }
      } else {
        player.spawn();
      }
    }
  };
};
<|endoftext|>