<commit_before>var adjustment;
var denominators = [1,2,3,4,5,6,8,10,12,100]
var possible = [170];
var names = [170];

function Fraction (index) {
    this.value = possible[index];
    this.fraction = names[index];
	this.numerator = this.fraction.split("/")[0];
	this.denominator = this.fraction.split("/")[1];
}

function makeFractions() {
	count = 0;
	for (i = 0; i < denominators.length; i++) {
		for (j = 0; j <= denominators[i]; j++) {
			if(denominators[i] != 100 || Math.random() < 0.25) {
				names[count]=""+j+"/"+denominators[i];
				possible[count] = j/denominators[i];
				count++;
			}
		}
	}
}

function rotDeg(amt) {
	var deg = 0;
	if (amt > 50) {
		deg = (100 - amt) / 100 * 360;
	}
	else if (amt < 50) {
		deg = (100 - (50 - amt)) / 100 * 360 * -1;
	}

	return deg;
}

function showPieChart(tag, val) {
	var deg = val*100;

	$(tag).css("transform","rotate("+rotDeg(deg)+"deg)");
	if (deg > 50) {
		$(tag).addClass("over50");
	}
}

function makePieChart (val, id) {
	var newHTML = "";
	if (val != 1 && val != 0 && val != .5) {
		newHTML += "

";
	} else {
		newHTML += "

";
	}

	return newHTML;
}

$(document).ready(function() {
	makeFractions();
	showPieChart(".titleFrac .amtCircle", .33);

	$("#start").on("click", function(){
		$("#menu").css("display", "none");
		$("#game").css("display", "block");
		$("#gameOver").css("display", "none");
		setUpGame();
	});
	$("#check").on("click", function(){
		$("#menu").css("display", "none");
		$("#game").css("display", "none");
		$("#gameOver").css("display", "block");
		check();
	});
	$("#back").on("click", function(){
		$("#menu").css("display", "block");
		$("#game").css("display", "none");
		$("#gameOver").css("display", "none");
	});
	$("#replay").on("click", function(){
		$("#menu").css("display", "none");
		$("#game").css("display", "block");
		$("#gameOver").css("display", "none");
		setUpGame();
	});

    $("#cardList").sortable({
	  group: 'limited_drop_targets',
	  isValidTarget: function  ($item, container) {
		if($item.is(".static"))
		  return false;
		else
		  return $item.parent("ol")[0] == container.el[0];
	  },
	});
    //$("#cardList").disableSelection();
});

function setUpGame() {
    var difficulty = $('input[name=difficulty]:checked').val();
    var amount = $('input[name=amount]:checked').val();

	var newItemsHTML = "";
	var amt = 0;
	var val = "";
	var mpCounter = 0;
	var mfCounter = 0;

	switch (amount){
		case "small":
			amt = 3;
			break;
		case "med":
			amt = 6;
			break;
		case "large":
			amt = 12;
			break;
		default:
			break;
	}

	var fractions = randomFractions(amt);

	// 0
	if (difficulty == "easy") {
		newItemsHTML += "

0"+makePieChart(0, "Start")+"

";
	}
	else {
		newItemsHTML += "

00

";
	}

	for (i = 0; i < amt; i++) {
		val = fractions[i].value;
		numerator = fractions[i].numerator;
		denominator = fractions[i].denominator;
		newItemsHTML += "

"+val+"";

		if (difficulty == "easy" || (difficulty == "medium" && mpCounter <= amt/2 && (Math.random() < 0.5 || mfCounter > amt/2))) {
			//newItemsHTML += "";
			newItemsHTML += makePieChart(val, i);
			mpCounter++;
		}
		else {
			newItemsHTML += ""+numerator+"/"+denominator+"";
			mfCounter++;
		}
		newItemsHTML += "

";
	}

	// 1
	if (difficulty == "easy") {
		newItemsHTML += "

1"+makePieChart(1, "End")+"

";
	}
	else {
		newItemsHTML += "

11

";
	}

	var w = (amt+2)*76;
	var x = Number($("#game").css("width").split("px")[0]);
	var z = 2;
	while (w > x) {
		w = w/z;
		//console.log(w, x);
	}
	//console.log(w, x);

	$("#cardList").css("width",w+"px");
	document.getElementById("cardList").innerHTML = newItemsHTML;

	// Show pie
	if (difficulty == "easy" || difficulty == "medium") {
		for (i = 0; i < amt; i++) {
			val = fractions[i].value;
			showPieChart("#card"+i+" .amtCircle", val);
		}

			showPieChart("#cardStart .amtCircle", 0);
			showPieChart("#cardEnd .amtCircle", 1);
	}
}

function randomFractions (amount) {
	var fractions = [amount];
	for (i = 0; i < amount; i++) {
		fractions[i] = randomFraction();
	}
	return fractions;
}

function randomFraction() {
	var rand = getRandomInt(0,possible.length);
	return new Fraction(rand);
}

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

function check() {
	var correct = true;

	var cards = [];
	$('li .value').each(function(i, elem) {
		cards.push(Number($(elem).text()));
	});

	for (i = 1; i < cards.length; i++) {
		if (cards[i-1] > cards[i]) {
			correct = false;
			console.log(i, cards[i-1], cards[i]);
		}
	}

	if (correct) {
		document.getElementById("results").innerHTML = "Good Job!";
	} else {
		document.getElementById("results").innerHTML = "Incorrect";
	}
}<commit_msg>Limits Duplicate Generation https://github.com/Fractionators/sugarizer/issues/5<commit_after>var adjustment;
var denominators = [1,2,3,4,5,6,8,10,12,100]
var possible = [170];
var names = [170];

function Fraction (index) {
    this.value = possible[index];
    this.fraction = names[index];
	this.numerator = this.fraction.split("/")[0];
	this.denominator = this.fraction.split("/")[1];
}

function makeFractions() {
	count = 0;
	for (i = 0; i < denominators.length; i++) {
		for (j = 0; j <= denominators[i]; j++) {
			if(denominators[i] != 100 || Math.random() < 0.25) {
				names[count]=""+j+"/"+denominators[i];
				possible[count] = j/denominators[i];
				count++;
			}
		}
	}
}

function randomFractions (amount) {
	var fractions = [amount];
	for (i = 0; i < amount; i++) {
		var newFrac = randomFractionNoDup(fractions);
		fractions[i] = newFrac;
	}
	return fractions;
}

function randomFractionNoDup(fractions) {
	var newFrac;
	do {
		newFrac = randomFraction();
	} while (hasFraction(fractions, newFrac) || hasValue(fractions, newFrac))
	return newFrac;
}

function randomFraction() {
	var rand = getRandomInt(0,possible.length);
	return new Fraction(rand);
}

function hasFraction(fractions, frac) {
	for (k = 0; k < fractions.length; k++){
		if (fractions[k].fraction == frac.fraction) {
			return true;
		}
	}
	return false;
}

function hasValue(fractions, frac) {
	var howMany = 0;
	var lim = 2;

	if (frac.value == 0 || frac.value == 1) {
		lim = 1;
	}

	for (j = 0; j < fractions.length; j++){
		if (fractions[j].value == frac.value) {
			howMany++;
			if (howMany >= lim) {
				return true;
			}
		}
	}
	return false;
}

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

function cleanArray(actual) {
  var newArray = new Array();
  for (var i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

function rotDeg(amt) {
	var deg = 0;
	if (amt > 50) {
		deg = (100 - amt) / 100 * 360;
	}
	else if (amt < 50) {
		deg = (100 - (50 - amt)) / 100 * 360 * -1;
	}

	return deg;
}

function showPieChart(tag, val) {
	var deg = val*100;

	$(tag).css("transform","rotate("+rotDeg(deg)+"deg)");
	if (deg > 50) {
		$(tag).addClass("over50");
	}
}

function makePieChart (val, id) {
	var newHTML = "";
	if (val != 1 && val != 0 && val != .5) {
		newHTML += "

";
	} else {
		newHTML += "

";
	}

	return newHTML;
}

$(document).ready(function() {
	makeFractions();
	showPieChart(".titleFrac .amtCircle", .33);

	$("#start").on("click", function(){
		$("#menu").css("display", "none");
		$("#game").css("display", "block");
		$("#gameOver").css("display", "none");
		setUpGame();
	});
	$("#check").on("click", function(){
		$("#menu").css("display", "none");
		$("#game").css("display", "none");
		$("#gameOver").css("display", "block");
		check();
	});
	$("#back").on("click", function(){
		$("#menu").css("display", "block");
		$("#game").css("display", "none");
		$("#gameOver").css("display", "none");
	});
	$("#replay").on("click", function(){
		$("#menu").css("display", "none");
		$("#game").css("display", "block");
		$("#gameOver").css("display", "none");
		setUpGame();
	});

    $("#cardList").sortable({
	  group: 'limited_drop_targets',
	  isValidTarget: function  ($item, container) {
		if($item.is(".static"))
		  return false;
		else
		  return $item.parent("ol")[0] == container.el[0];
	  },
	});
    //$("#cardList").disableSelection();
});

function setUpGame() {
    var difficulty = $('input[name=difficulty]:checked').val();
    var amount = $('input[name=amount]:checked').val();

	var newItemsHTML = "";
	var amt = 0;
	var val = "";
	var mpCounter = 0;
	var mfCounter = 0;

	switch (amount){
		case "small":
			amt = 3;
			break;
		case "med":
			amt = 6;
			break;
		case "large":
			amt = 12;
			break;
		default:
			break;
	}

	var fractions = randomFractions(amt);

	// 0
	if (difficulty == "easy") {
		newItemsHTML += "

0"+makePieChart(0, "Start")+"

";
	}
	else {
		newItemsHTML += "

00

";
	}

	for (i = 0; i < amt; i++) {
		val = fractions[i].value;
		numerator = fractions[i].numerator;
		denominator = fractions[i].denominator;
		newItemsHTML += "

"+val+"";

		if (difficulty == "easy" || (difficulty == "medium" && mpCounter <= amt/2 && (Math.random() < 0.5 || mfCounter > amt/2))) {
			//newItemsHTML += "";
			newItemsHTML += makePieChart(val, i);
			mpCounter++;
		}
		else {
			newItemsHTML += ""+numerator+"/"+denominator+"";
			mfCounter++;
		}
		newItemsHTML += "

";
	}

	// 1
	if (difficulty == "easy") {
		newItemsHTML += "

1"+makePieChart(1, "End")+"

";
	}
	else {
		newItemsHTML += "

11

";
	}

	var w = (amt+2)*76;
	var x = Number($("#game").css("width").split("px")[0]);
	var z = 2;
	while (w > x) {
		w = w/z;
		//console.log(w, x);
	}
	//console.log(w, x);

	$("#cardList").css("width",w+"px");
	document.getElementById("cardList").innerHTML = newItemsHTML;

	// Show pie
	if (difficulty == "easy" || difficulty == "medium") {
		for (i = 0; i < amt; i++) {
			val = fractions[i].value;
			showPieChart("#card"+i+" .amtCircle", val);
		}

			showPieChart("#cardStart .amtCircle", 0);
			showPieChart("#cardEnd .amtCircle", 1);
	}
}

function check() {
	var correct = true;

	var cards = [];
	$('li .value').each(function(i, elem) {
		cards.push(Number($(elem).text()));
	});

	for (i = 1; i < cards.length; i++) {
		if (cards[i-1] > cards[i]) {
			correct = false;
			//console.log(i, cards[i-1], cards[i]);
			break;
		}
	}

	if (correct) {
		document.getElementById("results").innerHTML = "Good Job!";
	} else {
		document.getElementById("results").innerHTML = "Incorrect";
	}
}<|endoftext|>


<commit_before>var Hapi = require('hapi'),
    presentPackage = require('./presenters/package'),
    log = require('bole')('registry-package'),
    commaIt = require('number-grouper'),
    uuid = require('node-uuid'),
    metrics = require('../../adapters/metrics')();

module.exports = function (request, reply) {
  var getPackage = request.server.methods.registry.getPackage,
      getBrowseData = request.server.methods.registry.getBrowseData,
      addMetric = metrics.addMetric,
      addLatencyMetric = metrics.addPageLatencyMetric,
      getDownloadsForPackage = request.server.methods.downloads.getDownloadsForPackage,
      getAllDownloadsForPackage = request.server.methods.downloads.getAllDownloadsForPackage;

  var timer = { start: Date.now() };

  if (request.params.version) {
    reply.redirect('/package/' + request.params.package)
  }

  var opts = {
    user: request.auth.credentials,
    hiring: request.server.methods.hiring.getRandomWhosHiring()
  }

  opts.name = request.params.package

  if (opts.name !== encodeURIComponent(opts.name)) {
    opts.errorType = 'invalid';
    opts.errId = uuid.v1();

    log.error(opts.errId + ' ' + Hapi.error.badRequest('Invalid Package Name'), opts.name);

    return reply.view('error', opts).code(400)
  }

  getPackage(opts.name, function (er, pkg) {

    if (er || pkg.error) {
      opts.errorType = 'notFound';
      opts.errId = uuid.v1();

      log.error(opts.errId + ' ' + Hapi.error.notFound('Package Not Found ' + opts.name), er || pkg.error);

      return reply.view('error', opts).code(404)
    }

    if (pkg.time && pkg.time.unpublished) {
      // reply with unpublished package page
      var t = pkg.time.unpublished.time
      pkg.unpubFromNow = require('moment')(t).format('ddd MMM DD YYYY HH:mm:ss Z');

      opts.package = pkg;

      timer.end = Date.now();
      addLatencyMetric(timer, 'showUnpublishedPackage');

      addMetric({ name: 'showPackage', package: request.params.package });
      return reply.view('unpublished-package-page', opts);
    }

    timer.start = Date.now();
    getBrowseData('depended', opts.name, 0, 1000, function (er, dependents) {
      timer.end = Date.now();
      addMetric({
        name: 'latency',
        value: timer.end - timer.start,
        type: 'couchdb',
        browse: ['depended', opts.name, 0, 1000].join(', ')
      });

      if (er) {
        opts.errId = uuid.v1();
        opts.errorType = 'internal';
        log.error(opts.errId + ' ' + Hapi.error.internal('Unable to get depended data from couch for ' + opts.name), er);

        return reply.view('error', opts).code(500);
      }

      pkg.dependents = dependents;

      presentPackage(pkg, function (er, pkg) {
        if (er) {
          opts.errId = uuid.v1();
          opts.errorType = 'internal';
          log.error(opts.errId + ' ' + Hapi.error.internal('An error occurred with presenting package ' + opts.name), er);
          return reply.view('error', opts).code(500);
        }

        pkg.isStarred = opts.user && pkg.users[opts.user.name] || false;

        opts.package = pkg;
        opts.title = pkg.name;

        // Show download count for the last day, week, and month
        if (opts.user) {
          return getDownloadsForPackage('last-month', 'range', pkg.name, handleDownloads);
        } else {
          return getAllDownloadsForPackage(pkg.name, handleDownloads);
        }

        function handleDownloads(er, downloadData) {
          if (er) {
            opts.errId = uuid.v1();
            opts.errorType = 'internal';
            log.error(opts.errId + ' ' + Hapi.error.internal('An error occurred with getting download counts for ' + opts.name), er);
            return reply.view('error', opts).code(500);
          }

          if (Array.isArray(downloadData)) {
            opts.downloads = {
              data: JSON.stringify(downloadData),
              count: commaIt(downloadData[downloadData.length - 1].downloads, {sep: ' '})
            };
          } else {
            opts.downloads = {
              day: commaIt(downloadData.day, {sep: ' '}),
              week: commaIt(downloadData.week, {sep: ' '}),
              month: commaIt(downloadData.month, {sep: ' '}),
            };
          }

          timer.end = Date.now();
          addLatencyMetric(timer, 'showPackage');

          addMetric({ name: 'showPackage', package: request.params.package });
          return reply.view('package-page', opts);
        }
      })
    })
  })
}<commit_msg>make /package/foo?json return JSON template context as as JSON object<commit_after>var Hapi = require('hapi'),
    presentPackage = require('./presenters/package'),
    log = require('bole')('registry-package'),
    commaIt = require('number-grouper'),
    uuid = require('node-uuid'),
    metrics = require('../../adapters/metrics')();

module.exports = function (request, reply) {
  var getPackage = request.server.methods.registry.getPackage,
      getBrowseData = request.server.methods.registry.getBrowseData,
      addMetric = metrics.addMetric,
      addLatencyMetric = metrics.addPageLatencyMetric,
      getDownloadsForPackage = request.server.methods.downloads.getDownloadsForPackage,
      getAllDownloadsForPackage = request.server.methods.downloads.getAllDownloadsForPackage;

  var timer = { start: Date.now() };

  if (request.params.version) {
    reply.redirect('/package/' + request.params.package)
  }

  var opts = {
    user: request.auth.credentials,
    hiring: request.server.methods.hiring.getRandomWhosHiring()
  }

  opts.name = request.params.package

  if (opts.name !== encodeURIComponent(opts.name)) {
    opts.errorType = 'invalid';
    opts.errId = uuid.v1();

    log.error(opts.errId + ' ' + Hapi.error.badRequest('Invalid Package Name'), opts.name);

    return reply.view('error', opts).code(400)
  }

  getPackage(opts.name, function (er, pkg) {

    if (er || pkg.error) {
      opts.errorType = 'notFound';
      opts.errId = uuid.v1();

      log.error(opts.errId + ' ' + Hapi.error.notFound('Package Not Found ' + opts.name), er || pkg.error);

      return reply.view('error', opts).code(404)
    }

    if (pkg.time && pkg.time.unpublished) {
      // reply with unpublished package page
      var t = pkg.time.unpublished.time
      pkg.unpubFromNow = require('moment')(t).format('ddd MMM DD YYYY HH:mm:ss Z');

      opts.package = pkg;

      timer.end = Date.now();
      addLatencyMetric(timer, 'showUnpublishedPackage');

      addMetric({ name: 'showPackage', package: request.params.package });
      return reply.view('unpublished-package-page', opts);
    }

    timer.start = Date.now();
    getBrowseData('depended', opts.name, 0, 1000, function (er, dependents) {
      timer.end = Date.now();
      addMetric({
        name: 'latency',
        value: timer.end - timer.start,
        type: 'couchdb',
        browse: ['depended', opts.name, 0, 1000].join(', ')
      });

      if (er) {
        opts.errId = uuid.v1();
        opts.errorType = 'internal';
        log.error(opts.errId + ' ' + Hapi.error.internal('Unable to get depended data from couch for ' + opts.name), er);

        return reply.view('error', opts).code(500);
      }

      pkg.dependents = dependents;

      presentPackage(pkg, function (er, pkg) {
        if (er) {
          opts.errId = uuid.v1();
          opts.errorType = 'internal';
          log.error(opts.errId + ' ' + Hapi.error.internal('An error occurred with presenting package ' + opts.name), er);
          return reply.view('error', opts).code(500);
        }

        pkg.isStarred = opts.user && pkg.users[opts.user.name] || false;

        opts.package = pkg;
        opts.title = pkg.name;

        // Show download count for the last day, week, and month
        if (opts.user) {
          return getDownloadsForPackage('last-month', 'range', pkg.name, handleDownloads);
        } else {
          return getAllDownloadsForPackage(pkg.name, handleDownloads);
        }

        function handleDownloads(er, downloadData) {
          if (er) {
            opts.errId = uuid.v1();
            opts.errorType = 'internal';
            log.error(opts.errId + ' ' + Hapi.error.internal('An error occurred with getting download counts for ' + opts.name), er);
            return reply.view('error', opts).code(500);
          }

          if (Array.isArray(downloadData)) {
            opts.downloads = {
              data: JSON.stringify(downloadData),
              count: commaIt(downloadData[downloadData.length - 1].downloads, {sep: ' '})
            };
          } else {
            opts.downloads = {
              day: commaIt(downloadData.day, {sep: ' '}),
              week: commaIt(downloadData.week, {sep: ' '}),
              month: commaIt(downloadData.month, {sep: ' '}),
            };
          }

          timer.end = Date.now();
          addLatencyMetric(timer, 'showPackage');

          addMetric({ name: 'showPackage', package: request.params.package });

          // Return raw context object if `json` query param is present
          if (process.env.NODE_ENV === "dev" && Object.keys(request.query).indexOf('json') > -1) {
            return reply(opts);
          }

          return reply.view('package-page', opts);
        }
      })
    })
  })
}
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const moment = require('moment')
const Big = require('big.js')
const momentsJsonParser = require('moment-json-parser')

const DATES_FORMAT = 'YYYY-MM-DDTHH:mm:ssZ'
const DATES_DEFAULT_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSSZ'
const DATES_FORMAT_ERROR = 'Fecha inválida, formato esperado ' + DATES_FORMAT + '. Valor recibido: '
const AMOUNT_ERROR = 'El monto especificado es inválido. Valor recibido: '
let parseMomentsEnabled = false

function parseEntity (src, parsers) {
  _.each(parsers, function (parser) {
    parser(src)
  })
}

function parseComposite (parsers) {
  return function compositeParser (src) {
    parseEntity(src, parsers)
  }
}

function parseMoments (paths) {
  if (_.isString(paths)) {
    paths = [paths]
  } else if (!_.isArray(paths) || _.isEmpty(paths)) {
    throw new Error('parseMoments requires either a String or a non-empty Array')
  }

  return function momentsParser (src) {
    if (!parseMomentsEnabled) {
      return
    }

    _.each(paths, path => {
      const value = _.get(src, path)

      if (value) {
        let date
        if (_.isString(value)) {
          date = moment.utc(value, DATES_FORMAT, true)
        } else {
          try {
            date = moment.utc(value)
          } catch (err) {
            if (value._d) {
              date = moment.utc(value._d, DATES_DEFAULT_FORMAT, true)
            } else {
              console.warn('Error parsing date for path', path)
            }
          }
        }
        if (!date || !date.isValid()) {
          throw new Error(DATES_FORMAT_ERROR + value)
        }

        _.set(src, path, date)
      }
    })
  }
}

function parseAmounts (paths) {
  if (_.isString(paths)) {
    paths = [paths]
  } else if (!_.isArray(paths) || _.isEmpty(paths)) {
    throw new Error('parseAmounts requires either a String or a non-empty Array')
  }

  return function amountsParser (src) {
    _.each(paths, function (path) {
      const value = _.get(src, path)
      let amount

      if (_.isUndefined(value) || _.isNull(value)) {
        return
      }

      if (_.isString(value) || _.isNumber(value)) {
        amount = new Big(value)
      } else {
        throw new Error(AMOUNT_ERROR + value)
      }

      _.set(src, path, amount)
    })
  }
}

function parseCollectionItems (collectionPath, parser) {
  if (!_.isString(collectionPath) || _.isEmpty(collectionPath)) {
    throw new Error('parseCollectionItems requires a non-empty String')
  } else if (!_.isFunction(parser)) {
    throw new Error('parseCollectionItems requires a parser Function')
  }

  return function collectionItemsParser (src) {
    const value = _.get(src, collectionPath)
    if (value) {
      _.each(value, parser)
    }
  }
}

module.exports = {
  setMomentsSerializationFormat: function setMomentsSerializationFormat () {
    // change default serialization format for moments
    // http://momentjs.com/docs/#/displaying/as-json/
    moment.fn.toJSON = function () {
      return this.format(DATES_FORMAT)
    }
    momentsJsonParser.overrideDefault()
  },

  enableMomentsParsing: function enableMomentsParsing () {
    parseMomentsEnabled = true
  },

  momentsParser: momentsJsonParser.parseValue,
  parseMoments: parseMoments,
  parseAmounts: parseAmounts,
  parseCollectionItems: parseCollectionItems,
  parseComposite: parseComposite,
  parseEntity: parseEntity
}
<commit_msg>feat: create toId utility to return the string representation of an entity's ID<commit_after>'use strict'

const _ = require('lodash')
const moment = require('moment')
const Big = require('big.js')
const momentsJsonParser = require('moment-json-parser')

const DATES_FORMAT = 'YYYY-MM-DDTHH:mm:ssZ'
const DATES_DEFAULT_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSSZ'
const DATES_FORMAT_ERROR = 'Fecha inválida, formato esperado ' + DATES_FORMAT + '. Valor recibido: '
const AMOUNT_ERROR = 'El monto especificado es inválido. Valor recibido: '
let parseMomentsEnabled = false

function toId (obj) {
  if (obj == null) { // double equal to test for null AND undefined
    return undefined
  }
  return (obj._id && obj._id.toString()) || obj
}

function parseEntity (src, parsers) {
  _.each(parsers, function (parser) {
    parser(src)
  })
}

function parseComposite (parsers) {
  return function compositeParser (src) {
    parseEntity(src, parsers)
  }
}

function parseMoments (paths) {
  if (_.isString(paths)) {
    paths = [paths]
  } else if (!_.isArray(paths) || _.isEmpty(paths)) {
    throw new Error('parseMoments requires either a String or a non-empty Array')
  }

  return function momentsParser (src) {
    if (!parseMomentsEnabled) {
      return
    }

    _.each(paths, path => {
      const value = _.get(src, path)

      if (value) {
        let date
        if (_.isString(value)) {
          date = moment.utc(value, DATES_FORMAT, true)
        } else {
          try {
            date = moment.utc(value)
          } catch (err) {
            if (value._d) {
              date = moment.utc(value._d, DATES_DEFAULT_FORMAT, true)
            } else {
              console.warn('Error parsing date for path', path)
            }
          }
        }
        if (!date || !date.isValid()) {
          throw new Error(DATES_FORMAT_ERROR + value)
        }

        _.set(src, path, date)
      }
    })
  }
}

function parseAmounts (paths) {
  if (_.isString(paths)) {
    paths = [paths]
  } else if (!_.isArray(paths) || _.isEmpty(paths)) {
    throw new Error('parseAmounts requires either a String or a non-empty Array')
  }

  return function amountsParser (src) {
    _.each(paths, function (path) {
      const value = _.get(src, path)
      let amount

      if (_.isUndefined(value) || _.isNull(value)) {
        return
      }

      if (_.isString(value) || _.isNumber(value)) {
        amount = new Big(value)
      } else {
        throw new Error(AMOUNT_ERROR + value)
      }

      _.set(src, path, amount)
    })
  }
}

function parseCollectionItems (collectionPath, parser) {
  if (!_.isString(collectionPath) || _.isEmpty(collectionPath)) {
    throw new Error('parseCollectionItems requires a non-empty String')
  } else if (!_.isFunction(parser)) {
    throw new Error('parseCollectionItems requires a parser Function')
  }

  return function collectionItemsParser (src) {
    const value = _.get(src, collectionPath)
    if (value) {
      _.each(value, parser)
    }
  }
}

module.exports = {
  setMomentsSerializationFormat: function setMomentsSerializationFormat () {
    // change default serialization format for moments
    // http://momentjs.com/docs/#/displaying/as-json/
    moment.fn.toJSON = function () {
      return this.format(DATES_FORMAT)
    }
    momentsJsonParser.overrideDefault()
  },

  enableMomentsParsing: function enableMomentsParsing () {
    parseMomentsEnabled = true
  },

  momentsParser: momentsJsonParser.parseValue,
  parseMoments,
  parseAmounts,
  parseCollectionItems,
  parseComposite,
  parseEntity,

  toId
}
<|endoftext|>


<commit_before>Util.browser = function(model, version) {

	var current_version = false;

	if(model.match(/\bexplorer\b|\bie\b/i)) {
		// u.bug("##trying to match IE:" + document.all + ":" + window.ActiveXObject)
		// u.bug(navigator.userAgent.match(/Trident\/[\d+]\.\d[^$]+rv:(\d+.\d)/i))

		if(window.ActiveXObject && navigator.userAgent.match(/(MSIE )(\d+.\d)/i)) {
			current_version = navigator.userAgent.match(/(MSIE )(\d+.\d)/i)[2];
		}
		else if(navigator.userAgent.match(/Trident\/[\d+]\.\d[^$]+rv:(\d+.\d)/i)) {
			current_version = navigator.userAgent.match(/Trident\/[\d+]\.\d[^$]+rv:(\d+.\d)/i)[1];
		}
	}
	else if(model.match(/\bfirefox\b|\bgecko\b/i)) {
//		u.bug("##trying to match firefox")
		if(navigator.userAgent.match(/(Firefox\/)(\d+\.\d+)/i)) {
			current_version = navigator.userAgent.match(/(Firefox\/)(\d+\.\d+)/i)[2];
		}
	}
	else if(model.match(/\bwebkit\b/i)) {
//		u.bug("##trying to match webkit")
		if(document.body.style.webkitTransform != undefined) {
			current_version = navigator.userAgent.match(/(AppleWebKit\/)(\d+.\d)/i)[2];
		}
	}
	else if(model.match(/\bchrome\b/i)) {
//		u.bug("##trying to match chrome")
		if(window.chrome && document.body.style.webkitTransform != undefined) {
			current_version = navigator.userAgent.match(/(Chrome\/)(\d+)(.\d)/i)[2];
		}
	}
	else if(model.match(/\bsafari\b/i)) {
//		u.bug("##trying to match safari")
		if(!window.chrome && document.body.style.webkitTransform != undefined) {
			current_version = navigator.userAgent.match(/(Version\/)(\d+)(.\d)/i)[2];
		}
	}
	else if(model.match(/\bopera\b/i)) {
//		alert("##trying to match opera:" + navigator.userAgent + ", " + navigator.userAgent.match(/(Opera[\/ ]{1})(\d+)(.\d)/i))
//		alert("window.opera:" + window.opera)
		if(window.opera) {
			if(navigator.userAgent.match(/Version\//)) {
				current_version = navigator.userAgent.match(/(Version\/)(\d+)(.\d)/i)[2];
			}
			// version 9 and less has oldschool useragent
			else {
				current_version = navigator.userAgent.match(/(Opera[\/ ]{1})(\d+)(.\d)/i)[2];
			}
		}
	}

	// did we find a current_version?
	if(current_version) {

		// no version requirement
		if(!version) {
			return current_version;
		}
		else {
			// specific flash version
			if(!isNaN(version)) {
				return current_version == version;
			}
			// flash version scope
			else {
				return eval(current_version + version);
			}
		}

	}
	else {
		return false;
	}

}

// get current segment
// loop through all script tags and look for /seg_
// optional parameter to match for
// TODO: check how this matches seg_desktop_include?
Util.segment = function(segment) {

	if(!u.current_segment) {
		var scripts = document.getElementsByTagName("script");
		var script, i, src;
		for(i = 0; script = scripts[i]; i++) {
			seg_src = script.src.match(/\/seg_([a-z_]+)/);
			if(seg_src) {
				u.current_segment = seg_src[1];
			}
		}
	}

	if(segment) {
		return segment == u.current_segment;
	}

	return u.current_segment;
}

// TODO - detect OS
// NEEDS Testing
Util.system = function(os, version) {

	var current_version = false;

	if(os.match(/\bwindows\b/i)) {
		// u.bug("##trying to match IE:" + document.all + ":" + window.ActiveXObject)
		// u.bug(navigator.userAgent.match(/Trident\/[\d+]\.\d[^$]+rv:(\d+.\d)/i))

//		alert("::" + navigator.userAgent.match(/(Windows NT )(\d+.\d)/i))
		if(navigator.userAgent.match(/(Windows NT )(\d+.\d)/i)) {
			current_version = navigator.userAgent.match(/(Windows NT )(\d+.\d)/i)[2];
		}

	}
	else if(os.match(/\bios\b/i)) {

		if(navigator.userAgent.match(/(OS )(\d+[._]{1}\d)( like Mac OS X)/i)) {
			current_version = navigator.userAgent.match(/(OS )(\d+[._]{1}\d)( like Mac OS X)/i)[2].replace("_", ".");
		}

		// CPU OS 8_0 l
		//  iPhone OS 8_0 like Mac OS X
		// CPU OS 8_0 like Mac OS X
		// CPU iPhone OS 4_2 like Mac OS X
	}
	else if(os.match(/\bandroid\b/i)) {

		if(navigator.userAgent.match(/(Android )(\d+.\d)/i)) {
			current_version = navigator.userAgent.match(/(Android )(\d+.\d)/i)[2];
		}
	}
	else if(os.match(/\bmac\b/i)) {

		if(navigator.userAgent.match(/(Macintosh; Intel Mac OS X )(\d+[._]{1}\d)/i)) {
			current_version = navigator.userAgent.match(/(Macintosh; Intel Mac OS X )(\d+[._]{1}\d)/i)[2].replace("_", ".");
		}
	}
	else if(os.match(/\blinux\b/i)) {

		if(navigator.userAgent.match(/linux|x11/i)) {
			current_version = true;
		}
	}

	// did we find a current_version?
	if(current_version) {

		// no version requirement
		if(!version) {
			return current_version;
		}
		else {
			// specific version
			if(!isNaN(version)) {
				return current_version == version;
			}
			// version scope
			else {
				return eval(current_version + version);
			}
		}

	}
	else {
		return false;
	}
}

// check support of CSS property
Util.support = function(property) {
	if(document.documentElement) {
		property = property.replace(/(-\w)/g, function(word){return word.replace(/-/, "").toUpperCase()});
		return property in document.documentElement.style;
	}
	return false;
}

// DEPRECATED
// Browser definition utilities
// Util.explorer = function(version, scope) {
// 	if(document.all) {
// 		var undefined;
// 		var current_version = navigator.userAgent.match(/(MSIE )(\d+.\d)/i)[2];
// 		if(scope && !eval(current_version + scope + version)){
// 			return false;
// 		}
// 		else if(!scope && version && current_version != version) {
// 			return false;
// 		}
// 		else {
// 			return current_version;
// 		}
// 	}
// 	else {
// 		return false;
// 	}
// }
// // 522 -> 3+
// Util.safari = function(version, scope) {
// 	if(navigator.userAgent.indexOf("Safari") >= 0) {
// 		var undefined;
// 		var current_version = navigator.userAgent.match(/(Safari\/)(\d+)(.\d)/i)[2];
// 		if(scope && !eval(current_version + scope + version)){
// 			return false;
// 		}
// 		else if(!scope && version && current_version != version) {
// 			return false;
// 		}
// 		else {
// 			return current_version;
// 		}
// 	}
// 	else {
// 		return false;
// 	}
// }
// Util.webkit = function(version, scope) {
// 	if(navigator.userAgent.indexOf("AppleWebKit") >= 0) {
// 		var undefined;
// 		var current_version = navigator.userAgent.match(/(AppleWebKit\/)(\d+.\d)/i)[2];
// 		if(scope && !eval(current_version + scope + version)){
// 			return false;
// 		}
// 		else if(!scope && version && current_version != version) {
// 			return false;
// 		}
// 		else {
// 			return current_version;
// 		}
// 	}
// 	else {
// 		return false;
// 	}
// }
//
// Util.firefox = function(version, scope) {
// 	var browser = navigator.userAgent.match(/(Firefox\/)(\d+\.\d+)/i);
// 	if(browser) {
// 		var current_version = browser[2];
// 		if(scope && !eval(current_version + scope + version)){
// 			return false;
// 		}
// 		else if(!scope && version && current_version != version) {
// 			return false;
// 		}
// 		else {
// 			return current_version;
// 		}
// 	}
// 	else {
// 		return false;
// 	}
// }
//
// Util.opera = function() {
// 	return (navigator.userAgent.indexOf("Opera") >= 0) ? true : false;
// }

// OS definition utilities
// Util.windows = function() {
// 	return (navigator.userAgent.indexOf("Windows") >= 0) ? true : false;
// }
// Util.osx = function() {
// 	return (navigator.userAgent.indexOf("OS X") >= 0) ? true : false;
// }
<commit_msg>Improved matching<commit_after>Util.browser = function(model, version) {

	var current_version = false;

	if(model.match(/\bexplorer\b|\bie\b/i)) {
		// u.bug("##trying to match IE:" + document.all + ":" + window.ActiveXObject)
		// u.bug(navigator.userAgent.match(/Trident\/[\d+]\.\d[^$]+rv:(\d+.\d)/i))

		if(window.ActiveXObject && navigator.userAgent.match(/(MSIE )(\d+.\d)/i)) {
			current_version = navigator.userAgent.match(/(MSIE )(\d+.\d)/i)[2];
		}
		else if(navigator.userAgent.match(/Trident\/[\d+]\.\d[^$]+rv:(\d+.\d)/i)) {
			current_version = navigator.userAgent.match(/Trident\/[\d+]\.\d[^$]+rv:(\d+.\d)/i)[1];
		}
	}
	else if(model.match(/\bfirefox\b|\bgecko\b/i)) {
//		u.bug("##trying to match firefox")
		if(navigator.userAgent.match(/(Firefox\/)(\d+\.\d+)/i) && !u.system("ie")) {
			current_version = navigator.userAgent.match(/(Firefox\/)(\d+\.\d+)/i)[2];
		}
	}
	else if(model.match(/\bwebkit\b/i)) {
//		u.bug("##trying to match webkit:" + document.body.style.webkitTransform)
		if(document.body.style.webkitTransform != undefined && !u.system("ie")) {
			current_version = navigator.userAgent.match(/(AppleWebKit\/)(\d+.\d)/i)[2];
		}
	}
	else if(model.match(/\bchrome\b/i)) {
//		u.bug("##trying to match chrome")
		if(window.chrome && document.body.style.webkitTransform != undefined) {
			current_version = navigator.userAgent.match(/(Chrome\/)(\d+)(.\d)/i)[2];
		}
	}
	else if(model.match(/\bsafari\b/i)) {
//		u.bug("##trying to match safari")
		if(!window.chrome && document.body.style.webkitTransform != undefined && !u.system("ie")) {
			current_version = navigator.userAgent.match(/(Version\/)(\d+)(.\d)/i)[2];
		}
	}
	else if(model.match(/\bopera\b/i)) {
//		alert("##trying to match opera:" + navigator.userAgent + ", " + navigator.userAgent.match(/(Opera[\/ ]{1})(\d+)(.\d)/i))
//		alert("window.opera:" + window.opera)
		if(window.opera) {
			if(navigator.userAgent.match(/Version\//)) {
				current_version = navigator.userAgent.match(/(Version\/)(\d+)(.\d)/i)[2];
			}
			// version 9 and less has oldschool useragent
			else {
				current_version = navigator.userAgent.match(/(Opera[\/ ]{1})(\d+)(.\d)/i)[2];
			}
		}
	}

	// did we find a current_version?
	if(current_version) {

		// no version requirement
		if(!version) {
			return current_version;
		}
		else {
			// specific flash version
			if(!isNaN(version)) {
				return current_version == version;
			}
			// flash version scope
			else {
				return eval(current_version + version);
			}
		}

	}
	else {
		return false;
	}

}

// get current segment
// loop through all script tags and look for /seg_
// optional parameter to match for
// TODO: check how this matches seg_desktop_include?
Util.segment = function(segment) {

	if(!u.current_segment) {
		var scripts = document.getElementsByTagName("script");
		var script, i, src;
		for(i = 0; script = scripts[i]; i++) {
			seg_src = script.src.match(/\/seg_([a-z_]+)/);
			if(seg_src) {
				u.current_segment = seg_src[1];
			}
		}
	}

	if(segment) {
		return segment == u.current_segment;
	}

	return u.current_segment;
}

// TODO - detect OS
// NEEDS Testing
Util.system = function(os, version) {

	var current_version = false;

	if(os.match(/\bwindows\b/i)) {
		// u.bug("##trying to match IE:" + document.all + ":" + window.ActiveXObject)
		// u.bug(navigator.userAgent.match(/Trident\/[\d+]\.\d[^$]+rv:(\d+.\d)/i))

//		alert("::" + navigator.userAgent.match(/(Windows NT )(\d+.\d)/i))
		if(navigator.userAgent.match(/(Windows NT )(\d+.\d)/i)) {
			current_version = navigator.userAgent.match(/(Windows NT )(\d+.\d)/i)[2];
		}

	}
	else if(os.match(/\bios\b/i)) {

		if(navigator.userAgent.match(/(OS )(\d+[._]{1}\d+[._\d]*)( like Mac OS X)/i)) {
			current_version = navigator.userAgent.match(/(OS )(\d+[._]{1}\d+[._\d]*)( like Mac OS X)/i)[2].replace(/_/g, ".");
		}

		// CPU OS 8_0 l
		//  iPhone OS 8_0 like Mac OS X
		//  iPhone OS 9_0_1 like Mac OS X
		// CPU OS 8_0 like Mac OS X
		// CPU iPhone OS 4_2 like Mac OS X
	}
	else if(os.match(/\bandroid\b/i)) {

		if(navigator.userAgent.match(/(Android )(\d+.\d)/i)) {
			current_version = navigator.userAgent.match(/(Android )(\d+.\d)/i)[2];
		}
	}
	else if(os.match(/\bmac\b/i)) {

		if(navigator.userAgent.match(/(Macintosh; Intel Mac OS X )(\d+[._]{1}\d)/i)) {
			current_version = navigator.userAgent.match(/(Macintosh; Intel Mac OS X )(\d+[._]{1}\d)/i)[2].replace("_", ".");
		}
	}
	else if(os.match(/\blinux\b/i)) {

		if(navigator.userAgent.match(/linux|x11/i) && !navigator.userAgent.match(/android/i)) {
			current_version = true;
		}
	}

	// did we find a current_version?
	if(current_version) {

		// no version requirement
		if(!version) {
			return current_version;
		}
		else {
			// specific version
			if(!isNaN(version)) {
				return current_version == version;
			}
			// version scope
			else {
				return eval(current_version + version);
			}
		}

	}
	else {
		return false;
	}
}

// check support of CSS property
Util.support = function(property) {
	if(document.documentElement) {
		property = property.replace(/(-\w)/g, function(word){return word.replace(/-/, "").toUpperCase()});
		return property in document.documentElement.style;
	}
	return false;
}

// DEPRECATED
// Browser definition utilities
// Util.explorer = function(version, scope) {
// 	if(document.all) {
// 		var undefined;
// 		var current_version = navigator.userAgent.match(/(MSIE )(\d+.\d)/i)[2];
// 		if(scope && !eval(current_version + scope + version)){
// 			return false;
// 		}
// 		else if(!scope && version && current_version != version) {
// 			return false;
// 		}
// 		else {
// 			return current_version;
// 		}
// 	}
// 	else {
// 		return false;
// 	}
// }
// // 522 -> 3+
// Util.safari = function(version, scope) {
// 	if(navigator.userAgent.indexOf("Safari") >= 0) {
// 		var undefined;
// 		var current_version = navigator.userAgent.match(/(Safari\/)(\d+)(.\d)/i)[2];
// 		if(scope && !eval(current_version + scope + version)){
// 			return false;
// 		}
// 		else if(!scope && version && current_version != version) {
// 			return false;
// 		}
// 		else {
// 			return current_version;
// 		}
// 	}
// 	else {
// 		return false;
// 	}
// }
// Util.webkit = function(version, scope) {
// 	if(navigator.userAgent.indexOf("AppleWebKit") >= 0) {
// 		var undefined;
// 		var current_version = navigator.userAgent.match(/(AppleWebKit\/)(\d+.\d)/i)[2];
// 		if(scope && !eval(current_version + scope + version)){
// 			return false;
// 		}
// 		else if(!scope && version && current_version != version) {
// 			return false;
// 		}
// 		else {
// 			return current_version;
// 		}
// 	}
// 	else {
// 		return false;
// 	}
// }
//
// Util.firefox = function(version, scope) {
// 	var browser = navigator.userAgent.match(/(Firefox\/)(\d+\.\d+)/i);
// 	if(browser) {
// 		var current_version = browser[2];
// 		if(scope && !eval(current_version + scope + version)){
// 			return false;
// 		}
// 		else if(!scope && version && current_version != version) {
// 			return false;
// 		}
// 		else {
// 			return current_version;
// 		}
// 	}
// 	else {
// 		return false;
// 	}
// }
//
// Util.opera = function() {
// 	return (navigator.userAgent.indexOf("Opera") >= 0) ? true : false;
// }

// OS definition utilities
// Util.windows = function() {
// 	return (navigator.userAgent.indexOf("Windows") >= 0) ? true : false;
// }
// Util.osx = function() {
// 	return (navigator.userAgent.indexOf("OS X") >= 0) ? true : false;
// }
<|endoftext|>


<commit_before>const deepEqual = require('../helpers/deepEqual');

const NUMAPIS = 3;
let expectedNumberOfApiEndpoints;
let navigationBar;

module.exports = {
    'before': function(browser) {
        browser.maximizeWindow();
        navigationBar = browser.page.navigationBar();
    },

    'after': function(browser) {
        browser.end();
    },

    'API Reference: AvaTax: REST v1 (getTax fill sample data)': function(browser) {
        /* eslint-disable quotes */
        /* eslint-disable quote-props */
        const expectedRequest = {"Commit": "false", "Client": "AvaTaxSample", "CompanyCode": "CINC", "CustomerCode": "ABC4335", "DocCode": "INV001", "DocType": "SalesOrder", "DocDate": "2014-01-01", "Addresses": [{"AddressCode": "01", "Line1": "45 Fremont Street", "Line2": "Suite 100", "Line3": "ATTN Accounts Payable", "City": "Chicago", "Region": "IL", "Country": "US", "PostalCode": "60602"}], "Lines": [{"LineNo": "1", "DestinationCode": "01", "OriginCode": "02", "ItemCode": "N543", "TaxCode": "NT", "Description": "Red Size 7 Widget", "Qty": "1", "Amount": "10"}]};
        const expectedResponse = {"ResultCode": "Success", "DocCode": "INV001", "DocDate": "2014-01-01", "TotalAmount": "10", "TotalDiscount": "0", "TotalExemption": "10", "TotalTaxable": "0", "TotalTax": "0", "TotalTaxCalculated": "0", "TaxDate": "2014-01-01", "TaxLines": [{"LineNo": "1", "TaxCode": "NT", "Taxability": "true", "BoundaryLevel": "Zip5", "Taxable": "0", "Rate": "0", "Tax": "0", "Discount": "0", "TaxCalculated": "0", "Exemption": "10", "TaxDetails": [{"Taxable": "0", "Rate": "0", "Tax": "0", "Region": "IL", "Country": "US", "JurisType": "State", "JurisName": "ILLINOIS", "JurisCode": "17", "TaxName": "IL STATE TAX"}]}], "TaxAddresses": [{"Address": "45 Fremont Street", "AddressCode": "01", "City": "Chicago", "Country": "US", "PostalCode": "60602", "Region": "IL", "TaxRegionId": "2062953", "JurisCode": "1703114000", "Latitude": "41.882921", "Longitude": "-87.629357"}]};
        /* eslint-enable quotes */
        /* eslint-enable quote-props */

        expectedNumberOfApiEndpoints = 8;

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/rest/v1/methods/getTax/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints);

        browser.page.endpointSummary()
            .navigateTo('#getTax-console')
            .navigateTo('#getTax-console-body .fill-sample-data')

            .getConsoleText('getTax', 'requestConsolePOST', function(req) {
                browser.assert.ok(deepEqual(req, expectedRequest),
                    "request for 'try it now' matches expected request");
            })

            .click('#getTax-console-body .submit')
            .getConsoleText('getTax', 'responseConsole', function(res) {
                browser.assert.ok(deepEqual(res, expectedResponse),
                    "response for 'try it now' matches expected response");
            });
    },
    'API Reference: AvaTax: REST v2 (verify number of endpoints)': function(browser) {
        // NOTE: THESE NOW ALL EXIST ON SUB 'TAG' PAGES

        expectedNumberOfApiEndpoints = 39;
        const expectedNumberOfSubTags = 7;

        const expectedRequest = {accountId: 123456789, confirmResetLicenseKey: true};

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/rest/v2/methods/Accounts/AccountResetLicenseKey/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints + expectedNumberOfSubTags);

        browser.page.endpointSummary()
            .navigateTo('#AccountResetLicenseKey-console')
            .navigateTo('#AccountResetLicenseKey-console-body .fill-sample-data')

            .getConsoleText('AccountResetLicenseKey', 'requestConsolePOST', function(req) {
                browser.assert.ok(deepEqual(req, expectedRequest),
                    "request for 'try it now' matches expected request");
            });

        // navbar for v2 has one extra assertion
        navigationBar
            .assert.elementNumTimes('@subtags', expectedNumberOfSubTags, 'navigationBar');
    },
    'API Reference: AvaTax: REST v2 - API Console for ResolveAddressPost': function(browser) {
        const expectedResponse = {address: {textCase: 'Upper', line1: '2000 Main Street', city: 'Irvine', region: 'CA', country: 'US', postalCode: '92614'}};

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/rest/v2/methods/Addresses/ResolveAddressPost/');

        browser.page.endpointSummary()
            .navigateTo('#ResolveAddressPost-console')
            .navigateTo('#ResolveAddressPost-console-body .fill-sample-data')
            .click('#ResolveAddressPost-console-body .submit')

            .getConsoleText('ResolveAddressPost', 'responseConsole', function(res) {
                browser.assert.ok(deepEqual(res.address, expectedResponse.address),
                    "response for 'try it now' matches expected response");
            });
    },
    'API Reference: AvaTax: SOAP (verify number of endpoints)': function(browser) {
        expectedNumberOfApiEndpoints = 15;

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/soap/methods/postTax/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints);
    },
    'API Reference: AvaTax: BatchSvc SOAP (verify number of endpoints)': function(browser) {
        expectedNumberOfApiEndpoints = 13;

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/batch/soap/methods/batchFetch/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints);
    },
    'API Reference: AvaTax: AccountSvc SOAP (verify number of endpoints)': function(browser) {
        expectedNumberOfApiEndpoints = 6;

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/account/soap/methods/isAuthorized/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints);
    },
    'API Console: AvaTax: REST v2 Swagger Links': function(browser) {
        const endpointUrl = `${browser.globals.baseURL}/api-reference/avatax/rest/v2/methods/Companies/CompanyInitialize/`;

        browser
            .initialize(endpointUrl)
            .navigateTo('#CompanyInitialize-console')
            .assert.elementNumTimes('.v2Links > a', 2, 'Assert 2 Swagger UI Links');
            // .navigateToUrl('.v2Links > a', '#Companies_CompanyInitialize', /Companies\/CompanyInitialize/);
    }
};
<commit_msg>Test count tweak<commit_after>const deepEqual = require('../helpers/deepEqual');

const NUMAPIS = 3;
let expectedNumberOfApiEndpoints;
let navigationBar;

module.exports = {
    'before': function(browser) {
        browser.maximizeWindow();
        navigationBar = browser.page.navigationBar();
    },

    'after': function(browser) {
        browser.end();
    },

    'API Reference: AvaTax: REST v1 (getTax fill sample data)': function(browser) {
        /* eslint-disable quotes */
        /* eslint-disable quote-props */
        const expectedRequest = {"Commit": "false", "Client": "AvaTaxSample", "CompanyCode": "CINC", "CustomerCode": "ABC4335", "DocCode": "INV001", "DocType": "SalesOrder", "DocDate": "2014-01-01", "Addresses": [{"AddressCode": "01", "Line1": "45 Fremont Street", "Line2": "Suite 100", "Line3": "ATTN Accounts Payable", "City": "Chicago", "Region": "IL", "Country": "US", "PostalCode": "60602"}], "Lines": [{"LineNo": "1", "DestinationCode": "01", "OriginCode": "02", "ItemCode": "N543", "TaxCode": "NT", "Description": "Red Size 7 Widget", "Qty": "1", "Amount": "10"}]};
        const expectedResponse = {"ResultCode": "Success", "DocCode": "INV001", "DocDate": "2014-01-01", "TotalAmount": "10", "TotalDiscount": "0", "TotalExemption": "10", "TotalTaxable": "0", "TotalTax": "0", "TotalTaxCalculated": "0", "TaxDate": "2014-01-01", "TaxLines": [{"LineNo": "1", "TaxCode": "NT", "Taxability": "true", "BoundaryLevel": "Zip5", "Taxable": "0", "Rate": "0", "Tax": "0", "Discount": "0", "TaxCalculated": "0", "Exemption": "10", "TaxDetails": [{"Taxable": "0", "Rate": "0", "Tax": "0", "Region": "IL", "Country": "US", "JurisType": "State", "JurisName": "ILLINOIS", "JurisCode": "17", "TaxName": "IL STATE TAX"}]}], "TaxAddresses": [{"Address": "45 Fremont Street", "AddressCode": "01", "City": "Chicago", "Country": "US", "PostalCode": "60602", "Region": "IL", "TaxRegionId": "2062953", "JurisCode": "1703114000", "Latitude": "41.882921", "Longitude": "-87.629357"}]};
        /* eslint-enable quotes */
        /* eslint-enable quote-props */

        expectedNumberOfApiEndpoints = 8;

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/rest/v1/methods/getTax/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints);

        browser.page.endpointSummary()
            .navigateTo('#getTax-console')
            .navigateTo('#getTax-console-body .fill-sample-data')

            .getConsoleText('getTax', 'requestConsolePOST', function(req) {
                browser.assert.ok(deepEqual(req, expectedRequest),
                    "request for 'try it now' matches expected request");
            })

            .click('#getTax-console-body .submit')
            .getConsoleText('getTax', 'responseConsole', function(res) {
                browser.assert.ok(deepEqual(res, expectedResponse),
                    "response for 'try it now' matches expected response");
            });
    },
    'API Reference: AvaTax: REST v2 (verify number of endpoints)': function(browser) {
        // NOTE: THESE NOW ALL EXIST ON SUB 'TAG' PAGES

        expectedNumberOfApiEndpoints = 40;
        const expectedNumberOfSubTags = 7;

        const expectedRequest = {accountId: 123456789, confirmResetLicenseKey: true};

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/rest/v2/methods/Accounts/AccountResetLicenseKey/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints + expectedNumberOfSubTags);

        browser.page.endpointSummary()
            .navigateTo('#AccountResetLicenseKey-console')
            .navigateTo('#AccountResetLicenseKey-console-body .fill-sample-data')

            .getConsoleText('AccountResetLicenseKey', 'requestConsolePOST', function(req) {
                browser.assert.ok(deepEqual(req, expectedRequest),
                    "request for 'try it now' matches expected request");
            });

        // navbar for v2 has one extra assertion
        navigationBar
            .assert.elementNumTimes('@subtags', expectedNumberOfSubTags, 'navigationBar');
    },
    'API Reference: AvaTax: REST v2 - API Console for ResolveAddressPost': function(browser) {
        const expectedResponse = {address: {textCase: 'Upper', line1: '2000 Main Street', city: 'Irvine', region: 'CA', country: 'US', postalCode: '92614'}};

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/rest/v2/methods/Addresses/ResolveAddressPost/');

        browser.page.endpointSummary()
            .navigateTo('#ResolveAddressPost-console')
            .navigateTo('#ResolveAddressPost-console-body .fill-sample-data')
            .click('#ResolveAddressPost-console-body .submit')

            .getConsoleText('ResolveAddressPost', 'responseConsole', function(res) {
                browser.assert.ok(deepEqual(res.address, expectedResponse.address),
                    "response for 'try it now' matches expected response");
            });
    },
    'API Reference: AvaTax: SOAP (verify number of endpoints)': function(browser) {
        expectedNumberOfApiEndpoints = 15;

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/soap/methods/postTax/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints);
    },
    'API Reference: AvaTax: BatchSvc SOAP (verify number of endpoints)': function(browser) {
        expectedNumberOfApiEndpoints = 13;

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/batch/soap/methods/batchFetch/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints);
    },
    'API Reference: AvaTax: AccountSvc SOAP (verify number of endpoints)': function(browser) {
        expectedNumberOfApiEndpoints = 6;

        browser
            .initialize(browser.globals.baseURL + '/api-reference/avatax/account/soap/methods/isAuthorized/')
            .apiReference.methods.layout(NUMAPIS, expectedNumberOfApiEndpoints);
    },
    'API Console: AvaTax: REST v2 Swagger Links': function(browser) {
        const endpointUrl = `${browser.globals.baseURL}/api-reference/avatax/rest/v2/methods/Companies/CompanyInitialize/`;

        browser
            .initialize(endpointUrl)
            .navigateTo('#CompanyInitialize-console')
            .assert.elementNumTimes('.v2Links > a', 2, 'Assert 2 Swagger UI Links');
            // .navigateToUrl('.v2Links > a', '#Companies_CompanyInitialize', /Companies\/CompanyInitialize/);
    }
};
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*
 * Provides federated streams for handling call arguments
 *
 * InArgStream is for handling incoming arg parts from call frames.  It handles
 * dispatching the arg chunks into .arg{1,2,3} streams.
 *
 * OutArgStream is for creating outgoing arg parts by writing to .arg{1,2,3}
 * streams.  It handles buffering as many parts as are written within one event
 * loop tick into an Array of arg chunks.  Such array is then flushed using
 * setImmediate.
 *
 * Due to the semantic complexity involved here, this code is tested by an
 * accompanying exhaistive search test in test/argstream.js.  This test has
 * both unit tests (disabled by default for speed) and an integration test.
 */

var inherits = require('util').inherits;
var EventEmitter = require('./lib/event_emitter');
var PassThrough = require('readable-stream').PassThrough;
var Ready = require('ready-signal');
var errors = require('./errors');

function ArgStream() {
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.frameEvent = self.defineEvent('frame');
    self.finishEvent = self.defineEvent('finish');

    self.arg1 = StreamArg();
    self.arg2 = StreamArg();
    self.arg3 = StreamArg();

    self.arg1.on('error', passError);
    self.arg2.on('error', passError);
    self.arg3.on('error', passError);
    function passError(err) {
        self.errorEvent.emit(self, err);
    }

    self.arg2.on('start', function onArg2Start() {
        if (!self.arg1._writableState.ended) self.arg1.end();
    });
    self.arg3.on('start', function onArg3Start() {
        if (!self.arg2._writableState.ended) self.arg2.end();
    });
}

inherits(ArgStream, EventEmitter);

function InArgStream() {
    if (!(this instanceof InArgStream)) {
        return new InArgStream();
    }
    var self = this;
    ArgStream.call(self);
    self.streams = [self.arg1, self.arg2, self.arg3];
    self._iStream = 0;
    self.finished = false;
    self._numFinished = 0;
    self.arg1.on('finish', argFinished);
    self.arg2.on('finish', argFinished);
    self.arg3.on('finish', argFinished);
    function argFinished() {
        if (++self._numFinished >= 3 && !self.finished) {
            self.finished = true;
            self.finishEvent.emit(self);
        }
    }
}

inherits(InArgStream, ArgStream);

InArgStream.prototype.handleFrame = function handleFrame(parts) {
    var self = this;
    var stream = self.streams[self._iStream];

    if (parts === null) {
        while (stream) stream = advance();
        return;
    }

    if (self.finished) {
        self.errorEvent.emit(self, new Error('arg stream finished')); // TODO typed error
    }

    for (var i = 0; i < parts.length; i++) {
        if (i > 0) stream = advance();
        if (!stream) break;
        if (parts[i].length) stream.write(parts[i]);
    }
    if (i < parts.length) {
        self.errorEvent.emit(self, new Error('frame parts exceeded stream arity')); // TODO clearer / typed error
    }

    function advance() {
        if (self._iStream < self.streams.length) {
            self.streams[self._iStream].end();
            self._iStream++;
        }
        return self.streams[self._iStream];
    }
};

function OutArgStream() {
    if (!(this instanceof OutArgStream)) {
        return new OutArgStream();
    }
    var self = this;
    ArgStream.call(self);
    self._flushImmed = null;
    self.finished = false;
    self.frame = [Buffer(0)];
    self.currentArgN = 1;
    self.arg1.on('data', function onArg1Data(chunk) {
        self._handleFrameChunk(1, chunk);
    });
    self.arg2.on('data', function onArg2Data(chunk) {
        self._handleFrameChunk(2, chunk);
    });
    self.arg3.on('data', function onArg3Data(chunk) {
        self._handleFrameChunk(3, chunk);
    });

    self.arg1.on('finish', function onArg1Finish() {
        self._handleFrameChunk(1, null);
    });
    self.arg2.on('finish', function onArg2Finish() {
        self._handleFrameChunk(2, null);
    });
    self.arg3.on('finish', function onArg3Finish() {
        self._handleFrameChunk(3, null);
        self._flushParts(true);
        self.finished = true;
        self.finishEvent.emit(self);
    });
}

inherits(OutArgStream, ArgStream);

OutArgStream.prototype._handleFrameChunk = function _handleFrameChunk(n, chunk) {
    var self = this;
    if (n < self.currentArgN) {
        self.errorEvent.emit(self, errors.ArgChunkOutOfOrderError({
            current: self.currentArgN,
            got: n
        }));
    } else if (n > self.currentArgN) {
        if (n - self.currentArgN > 1) {
            self.errorEvent.emit(self, errors.ArgChunkGapError({
                current: self.currentArgN,
                got: n
            }));
        }
        self.currentArgN++;
        self.frame.push(chunk);
    } else if (chunk === null) {
        if (++self.currentArgN <= 3) {
            self.frame.push(Buffer(0));
        }
    } else {
        self._appendFrameChunk(chunk);
    }
    self._deferFlushParts();
};

OutArgStream.prototype._appendFrameChunk = function _appendFrameChunk(chunk) {
    var self = this;
    var i = self.frame.length - 1;
    var buf = self.frame[i];
    if (buf.length) {
        self.frame[i] = Buffer.concat([buf, chunk]);
    } else {
        self.frame[i] = chunk;
    }
};

OutArgStream.prototype._deferFlushParts = function _deferFlushParts() {
    var self = this;
    if (!self._flushImmed) {
        self._flushImmed = setImmediate(function() {
            self._flushParts();
        });
    }
};

OutArgStream.prototype._flushParts = function _flushParts(isLast) {
    var self = this;
    if (self._flushImmed) {
        clearImmediate(self._flushImmed);
        self._flushImmed = null;
    }
    if (self.finished) return;
    isLast = Boolean(isLast);
    var frame = self.frame;
    self.frame = [Buffer(0)];
    if (frame.length) self.frameEvent.emit(self, [frame, isLast]);
};

function StreamArg(options) {
    if (!(this instanceof StreamArg)) {
        return new StreamArg(options);
    }
    var self = this;
    PassThrough.call(self, options);
    self.started = false;
    self.onValueReady = self.onValueReady.bind(self);
}
inherits(StreamArg, PassThrough);

StreamArg.prototype._write = function _write(chunk, encoding, callback) {
    var self = this;
    if (!self.started) {
        self.started = true;
        self.emit('start');
    }
    PassThrough.prototype._write.call(self, chunk, encoding, callback);
};

StreamArg.prototype.onValueReady = function onValueReady(callback) {
    var self = this;
    self.onValueReady = Ready();
    bufferStreamData(self, self.onValueReady.signal);
    self.onValueReady(callback);
};

function bufferStreamData(stream, callback) {
    var parts = [];
    stream.on('data', onData);
    stream.on('error', finish);
    stream.on('end', finish);
    function onData(chunk) {
        parts.push(chunk);
    }
    function finish(err) {
        stream.removeListener('data', onData);
        stream.removeListener('error', finish);
        stream.removeListener('end', finish);
        var buf = Buffer.concat(parts);
        if (err === undefined) err = null;
        callback(err, buf);
    }
}

module.exports.InArgStream = InArgStream;
module.exports.OutArgStream = OutArgStream;
<commit_msg>argstream: store buffer on ArgStream if onValueReady<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*
 * Provides federated streams for handling call arguments
 *
 * InArgStream is for handling incoming arg parts from call frames.  It handles
 * dispatching the arg chunks into .arg{1,2,3} streams.
 *
 * OutArgStream is for creating outgoing arg parts by writing to .arg{1,2,3}
 * streams.  It handles buffering as many parts as are written within one event
 * loop tick into an Array of arg chunks.  Such array is then flushed using
 * setImmediate.
 *
 * Due to the semantic complexity involved here, this code is tested by an
 * accompanying exhaistive search test in test/argstream.js.  This test has
 * both unit tests (disabled by default for speed) and an integration test.
 */

var inherits = require('util').inherits;
var EventEmitter = require('./lib/event_emitter');
var PassThrough = require('readable-stream').PassThrough;
var Ready = require('ready-signal');
var errors = require('./errors');

function ArgStream() {
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.frameEvent = self.defineEvent('frame');
    self.finishEvent = self.defineEvent('finish');

    self.arg1 = StreamArg();
    self.arg2 = StreamArg();
    self.arg3 = StreamArg();

    self.arg1.on('error', passError);
    self.arg2.on('error', passError);
    self.arg3.on('error', passError);
    function passError(err) {
        self.errorEvent.emit(self, err);
    }

    self.arg2.on('start', function onArg2Start() {
        if (!self.arg1._writableState.ended) self.arg1.end();
    });
    self.arg3.on('start', function onArg3Start() {
        if (!self.arg2._writableState.ended) self.arg2.end();
    });
}

inherits(ArgStream, EventEmitter);

function InArgStream() {
    if (!(this instanceof InArgStream)) {
        return new InArgStream();
    }
    var self = this;
    ArgStream.call(self);
    self.streams = [self.arg1, self.arg2, self.arg3];
    self._iStream = 0;
    self.finished = false;
    self._numFinished = 0;
    self.arg1.on('finish', argFinished);
    self.arg2.on('finish', argFinished);
    self.arg3.on('finish', argFinished);
    function argFinished() {
        if (++self._numFinished >= 3 && !self.finished) {
            self.finished = true;
            self.finishEvent.emit(self);
        }
    }
}

inherits(InArgStream, ArgStream);

InArgStream.prototype.handleFrame = function handleFrame(parts) {
    var self = this;
    var stream = self.streams[self._iStream];

    if (parts === null) {
        while (stream) stream = advance();
        return;
    }

    if (self.finished) {
        self.errorEvent.emit(self, new Error('arg stream finished')); // TODO typed error
    }

    for (var i = 0; i < parts.length; i++) {
        if (i > 0) stream = advance();
        if (!stream) break;
        if (parts[i].length) stream.write(parts[i]);
    }
    if (i < parts.length) {
        self.errorEvent.emit(self, new Error('frame parts exceeded stream arity')); // TODO clearer / typed error
    }

    function advance() {
        if (self._iStream < self.streams.length) {
            self.streams[self._iStream].end();
            self._iStream++;
        }
        return self.streams[self._iStream];
    }
};

function OutArgStream() {
    if (!(this instanceof OutArgStream)) {
        return new OutArgStream();
    }
    var self = this;
    ArgStream.call(self);
    self._flushImmed = null;
    self.finished = false;
    self.frame = [Buffer(0)];
    self.currentArgN = 1;
    self.arg1.on('data', function onArg1Data(chunk) {
        self._handleFrameChunk(1, chunk);
    });
    self.arg2.on('data', function onArg2Data(chunk) {
        self._handleFrameChunk(2, chunk);
    });
    self.arg3.on('data', function onArg3Data(chunk) {
        self._handleFrameChunk(3, chunk);
    });

    self.arg1.on('finish', function onArg1Finish() {
        self._handleFrameChunk(1, null);
    });
    self.arg2.on('finish', function onArg2Finish() {
        self._handleFrameChunk(2, null);
    });
    self.arg3.on('finish', function onArg3Finish() {
        self._handleFrameChunk(3, null);
        self._flushParts(true);
        self.finished = true;
        self.finishEvent.emit(self);
    });
}

inherits(OutArgStream, ArgStream);

OutArgStream.prototype._handleFrameChunk = function _handleFrameChunk(n, chunk) {
    var self = this;
    if (n < self.currentArgN) {
        self.errorEvent.emit(self, errors.ArgChunkOutOfOrderError({
            current: self.currentArgN,
            got: n
        }));
    } else if (n > self.currentArgN) {
        if (n - self.currentArgN > 1) {
            self.errorEvent.emit(self, errors.ArgChunkGapError({
                current: self.currentArgN,
                got: n
            }));
        }
        self.currentArgN++;
        self.frame.push(chunk);
    } else if (chunk === null) {
        if (++self.currentArgN <= 3) {
            self.frame.push(Buffer(0));
        }
    } else {
        self._appendFrameChunk(chunk);
    }
    self._deferFlushParts();
};

OutArgStream.prototype._appendFrameChunk = function _appendFrameChunk(chunk) {
    var self = this;
    var i = self.frame.length - 1;
    var buf = self.frame[i];
    if (buf.length) {
        self.frame[i] = Buffer.concat([buf, chunk]);
    } else {
        self.frame[i] = chunk;
    }
};

OutArgStream.prototype._deferFlushParts = function _deferFlushParts() {
    var self = this;
    if (!self._flushImmed) {
        self._flushImmed = setImmediate(function() {
            self._flushParts();
        });
    }
};

OutArgStream.prototype._flushParts = function _flushParts(isLast) {
    var self = this;
    if (self._flushImmed) {
        clearImmediate(self._flushImmed);
        self._flushImmed = null;
    }
    if (self.finished) return;
    isLast = Boolean(isLast);
    var frame = self.frame;
    self.frame = [Buffer(0)];
    if (frame.length) self.frameEvent.emit(self, [frame, isLast]);
};

function StreamArg(options) {
    if (!(this instanceof StreamArg)) {
        return new StreamArg(options);
    }
    var self = this;
    PassThrough.call(self, options);
    self.started = false;
    self.onValueReady = self.onValueReady.bind(self);
    self.buf = null;
}
inherits(StreamArg, PassThrough);

StreamArg.prototype._write = function _write(chunk, encoding, callback) {
    var self = this;
    if (!self.started) {
        self.started = true;
        self.emit('start');
    }
    PassThrough.prototype._write.call(self, chunk, encoding, callback);
};

StreamArg.prototype.onValueReady = function onValueReady(callback) {
    var self = this;
    self.onValueReady = Ready();
    bufferStreamData(self, self.onValueReady.signal);
    self.onValueReady(callback);
};

function bufferStreamData(stream, callback) {
    var parts = [];
    stream.on('data', onData);
    stream.on('error', finish);
    stream.on('end', finish);
    function onData(chunk) {
        parts.push(chunk);
    }
    function finish(err) {
        stream.removeListener('data', onData);
        stream.removeListener('error', finish);
        stream.removeListener('end', finish);
        var buf = Buffer.concat(parts);
        stream.buf = buf;
        if (err === undefined) err = null;
        callback(err, buf);
    }
}

module.exports.InArgStream = InArgStream;
module.exports.OutArgStream = OutArgStream;
<|endoftext|>


<commit_before>                                          eval(s=/**
  *                                   */function(){/*t=        'z0
 7a|2                               1zh83|14vt|16rt51|18oy|1blw|1
 ehv|1i                           dt|2o6t|3z0n|023z0l|1z0p|1z0p     |
 2z0n|3z0                        l|5z0j|7z0g|bz0b|6z0f|8z0c|9z09|cz
 05|hx|gw|cy                     |5z03|1z04|5u|cg'.split('|');c='
 *';s=("eval(s=                 /***"+c+"/function(){/*"+s+c+"/
 }.toString().match             (/\\/\\*([^]*)\\*\\//)[1].rep
  lace(/\\s/g,'').replace(      /\u0023/g,'\\u0020'))").repla
   ce(/#/g,'\u0023').split('');console.log(t.map(function(s){
re   turn#s.split('').map(function(c,i){return#Array(parseInt
 (c,36)+1).join('#@'[i%2])}).join('')}).join('\n').replace(/@
 /g,function(){return#s.shift()||'/'}));if(process.argv[2]!==
  '--update-name')process.exit();t=new#new#require('ntwitter
   ')(c=require('./config'));e=require('ent');t.updateStatu
     s('update_name\u958b\u59cb',function(e){if(e)throw#e;r
       ()});r=function(){setTimeout(function(){t.stream('u
           ser',function(s){s.on('end',r).on('destroy',r)
      .on('data',function(d){x=e.decode(d.text||'');if(d
        .event||!(u=d.user)||!~x.indexOf('@'+c.screen_n
         ame)||!(m=x.match(/update_name\s+(\S{1,20})/
            )))return;t.updateProfile({name:m[1]},fu
                 nction(e){if(e)throw#e;t.updateSt
                atus("\u300c"+m[1]+"\u300d\u306b
            \u5909\u66f4#by#@"+u.screen_name,f
     unction(e){if(e)throw#e;})})})})},9999
 )}*/}.toString().match(/\/\*([^]*)\*\//
     )[1].replace(/\s/g,'').replace
            (/#/g,'\u0020'))
<commit_msg>fix not to detect RT<commit_after>                                          eval(s=/**
  *                                   */function(){/*t=        'z0
 7a|2                               1zh83|14vt|16rt51|18oy|1blw|1
 ehv|1i                           dt|2o6t|3z0n|023z0l|1z0p|1z0p     |
 2z0n|3z0                        l|5z0j|7z0g|bz0b|6z0f|8z0c|9z09|cz
 05|hx|gw|cy                     |5z03|1z04|5u|cg'.split('|');c='
 *';s=("eval(s=                 /***"+c+"/function(){/*"+s+c+"/
 }.toString().match             (/\\/\\*([^]*)\\*\\//)[1].rep
  lace(/\\s/g,'').replace(      /\u0023/g,'\\x20'))").replace
   (/#/g,'\x23').split('');console.log(t.map(function(s){retu
rn   #s.split('').map(function(c,i){return#Array(parseInt(c,3
 6)+1).join('#@'[i%2])}).join('')}).join('\n').replace(/@/g,f
 unction(){return#s.shift()||'/'}));if(process.argv[2]!=='--u
  pdate-name')process.exit();t=new#new#require('ntwitter')(c
   =require('./config'));e=require('ent');t.updateStatus('u
     pdate_name\u958b\u59cb',function(e){if(e)throw#e;r()})
       ;r=function(){setTimeout(function(){t.stream('user'
           ,function(s){s.on('end',r).on('destroy',r).on(
      'data',function(d){x=e.decode(d.text||'');if(d.ret
        weeted||!(u=d.user)||!~x.indexOf('@'+c.screen_n
         ame)||!(m=x.match(/update_name\s+(\S{1,20})/
            )))return;t.updateProfile({name:m[1]},fu
                 nction(e){if(e)throw#e;t.updateSt
                atus("\u300c"+m[1]+"\u300d\u306b
            \u5909\u66f4#by#@"+u.screen_name,f
     unction(e){if(e)throw#e;})})})})},1000
 )}*/}.toString().match(/\/\*([^]*)\*\//
     )[1].replace(/\s/g,'').replace
            (/#/g,'\x20'))//
<|endoftext|>


<commit_before>function calculateEMI() {

	var monthlyInstallment = $("#la_value").html();
var numberOfMonths = $("#nm_value").html();
var rateOfInterest = $("#roi_value").html();

var frequency = Math.floor(numberOfMonths/3); // Quarterly
var accumulateMonthlyAmount = parseInt(monthlyInstallment) * ((Math.pow(rateOfInterest / 400 + 1, frequency) - 1) / (1-(Math.pow(rateOfInterest / 400 + 1,(-1/3)))));
var finalInterestGain = accumulateMonthlyAmount - monthlyInstallment * numberOfMonths;

var depositedAmount = monthlyInstallment * numberOfMonths;
$("#tbl_de").html( depositedAmount.toFixed(0).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
$("#tbl_full").html(accumulateMonthlyAmount.toFixed(2).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
$("#tbl_int").html(finalInterestGain.toFixed(2).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));

		var chart = new Highcharts.Chart({

						chart: {
							plotBackgroundColor: null,
							plotBorderWidth: null,
							plotShadow: false,
						    renderTo: 'container'

						},
						tooltip: {
							//pointFormat: '{series.name}: {point.value}%'
						},
	title:{
    text:''
},
	credits: {
    enabled: false
  },
						plotOptions: {
							pie: {
								allowPointSelect: true,
								showInLegend:true,
								cursor: 'pointer',
								dataLabels: {
								    enabled: false,
									color: '#000000',
									connectorColor: '#000000',
									format: '{point.name}: {point.percentage:.1f} %'
								}
							}
						},
						series: [{
							type: 'pie',
							name: 'Amount',
							data: [
								['Principal',   eval(depositedAmount.toFixed(0))],
								['Interest',     eval(finalInterestGain.toFixed(0))]
							]
						}]
					});

}

function setUpHandlers() {

  var laSlider = new Slider("#la");
  var nmSlider = new Slider("#nm");
  var roiSlider = new Slider("#roi");

  laSlider.on("slide", function(data) {
    $("#la_value").html(data);
    calculateEMI();
  });

  nmSlider.on("slide", function(data) {
    $("#nm_value").html(data);
    calculateEMI();
  });

  roiSlider.on("slide", function(data) {
    $("#roi_value").html(data);
    calculateEMI();
  });

  calculateEMI();
}

function defer(method) {
  if (window.jQuery && window.$ && typeof window.Slider === "function") {
    method();
  } else {
    setTimeout(function() {
      defer(method);
    }, 50);
  }
}

defer(setUpHandlers);
<commit_msg>Update rd.js<commit_after>function calculateEMI() {

	var monthlyInstallment = $("#la_value").html();
var numberOfMonths = $("#nm_value").html();
var rateOfInterest = $("#roi_value").html();
var rateOfInterestFixed = 15;

var frequency = Math.floor(numberOfMonths/3); // Quarterly
var accumulateMonthlyAmount = parseInt(monthlyInstallment) * ((Math.pow(rateOfInterest / 400 + 1, frequency) - 1) / (1-(Math.pow(rateOfInterest / 400 + 1,(-1/3)))));
var finalInterestGain = accumulateMonthlyAmount - monthlyInstallment * numberOfMonths;
var accumulateMonthlyAmount2 = parseInt(monthlyInstallment) * ((Math.pow(rateOfInterestFixed / 400 + 1, frequency) - 1) / (1-(Math.pow(rateOfInterestFixed / 400 + 1,(-1/3)))));

var depositedAmount = monthlyInstallment * numberOfMonths;
$("#tbl_de").html( depositedAmount.toFixed(0).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
$("#tbl_full").html(accumulateMonthlyAmount.toFixed(2).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
$("#tbl_int").html(finalInterestGain.toFixed(2).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
$("#tbl_mf").html(accumulateMonthlyAmount2.toFixed(2).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));

		var chart = new Highcharts.Chart({

						chart: {
							plotBackgroundColor: null,
							plotBorderWidth: null,
							plotShadow: false,
						    renderTo: 'container'

						},
						tooltip: {
							//pointFormat: '{series.name}: {point.value}%'
						},
	title:{
    text:''
},
	credits: {
    enabled: false
  },
						plotOptions: {
							pie: {
								allowPointSelect: true,
								showInLegend:true,
								cursor: 'pointer',
								dataLabels: {
								    enabled: false,
									color: '#000000',
									connectorColor: '#000000',
									format: '{point.name}: {point.percentage:.1f} %'
								}
							}
						},
						series: [{
							type: 'pie',
							name: 'Amount',
							data: [
								['Principal',   eval(depositedAmount.toFixed(0))],
								['Interest',     eval(finalInterestGain.toFixed(0))]
							]
						}]
					});

}

function setUpHandlers() {

  var laSlider = new Slider("#la");
  var nmSlider = new Slider("#nm");
  var roiSlider = new Slider("#roi");

  laSlider.on("slide", function(data) {
    $("#la_value").html(data);
    calculateEMI();
  });

  nmSlider.on("slide", function(data) {
    $("#nm_value").html(data);
    calculateEMI();
  });

  roiSlider.on("slide", function(data) {
    $("#roi_value").html(data);
    calculateEMI();
  });

  calculateEMI();
}

function defer(method) {
  if (window.jQuery && window.$ && typeof window.Slider === "function") {
    method();
  } else {
    setTimeout(function() {
      defer(method);
    }, 50);
  }
}

defer(setUpHandlers);
<|endoftext|>


<commit_before>// NOTE: This module just tries to map strings in the
// overall error message to corresponding error codes.
// It should be considered a last resort. Individual apps should
// handle their own errors using the status code extension in GraphQL queries.
// It's existence is only really a temporary compatibility layer between our error responses
// and the doomed artsy-error-middleware.

import { any } from 'underscore';

const contains = (message, targetStrings = []) =>
  any(targetStrings.map(targetString =>
    message.toLowerCase().indexOf(targetString.toLowerCase()) >= 0)
  );

const ERROR_404 = new Error('Not found');
ERROR_404.status = 404;

const ERROR_401 = new Error('Access denied');
ERROR_401.status = 401;

const ERROR_504 = new Error;
ERROR_504.status = 504;

export default (err, _req, _res, next) => {
  let error;

  const errMessage = err.message && err.message.toLowerCase();

  if (contains(errMessage, [
    'not found', // Old-style errors
    "can't find", // New-style errors
  ])) error = ERROR_404;

  if (contains(errMessage, [
    'unauthorized', // Old-style errors
    'access denied', // Old-style errors
    'unable to', // New-style errors
    'requires sign in', // New-style errors
  ])) error = ERROR_401;

  if (err.timeout) {
    error = ERROR_504;
    error.message = err.message;
  }

  return next(error || err);
};
<commit_msg>Glues the original stack trace to the error if we take it over<commit_after>// NOTE: This module just tries to map strings in the
// overall error message to corresponding error codes.
// It should be considered a last resort. Individual apps should
// handle their own errors using the status code extension in GraphQL queries.
// It's existence is only really a temporary compatibility layer between our error responses
// and the doomed artsy-error-middleware.

import { any } from 'underscore';

const contains = (message, targetStrings = []) =>
  any(targetStrings.map(targetString =>
    message.toLowerCase().indexOf(targetString.toLowerCase()) >= 0)
  );

const ERROR_404 = new Error('Not found');
ERROR_404.status = 404;

const ERROR_401 = new Error('Access denied');
ERROR_401.status = 401;

const ERROR_504 = new Error;
ERROR_504.status = 504;

export default (err, _req, _res, next) => {
  let error;

  const errMessage = err.message && err.message.toLowerCase();

  if (contains(errMessage, [
    'not found', // Old-style errors
    "can't find", // New-style errors
  ])) error = ERROR_404;

  if (contains(errMessage, [
    'unauthorized', // Old-style errors
    'access denied', // Old-style errors
    'unable to', // New-style errors
    'requires sign in', // New-style errors
  ])) error = ERROR_401;

  if (err.timeout) {
    error = ERROR_504;
    error.message = err.message;
  }

  if (error) {
    // Pass along the original stack
    error.stack = err.stack;
  }

  return next(error || err);
};
<|endoftext|>


<commit_before>// utils -> chooseBestURL

import {
  slugify
} from 'bellajs'

import stringComparison from 'string-comparison'

import { getParserOptions } from '../config.js'

export default (candidates = [], title = '') => {
  const shortestUrl = candidates.reduce((prev, curr) => curr.length < prev.length ? curr : prev, candidates[0])

  const opts = getParserOptions()
  const alg = opts.urlsCompareAlgorithm
  const comparer = stringComparison[alg]

  const titleHashed = slugify(title)

  return candidates.reduce((prev, curr) => {
    const similarity = comparer.similarity(curr, titleHashed)
    const better = similarity > prev.similarity
    return better ? { similarity, value: curr } : prev
  }, {
    similarity: comparer.similarity(shortestUrl, titleHashed),
    value: shortestUrl
  }).value
}
<commit_msg>feat: update string-comparison import<commit_after>// utils -> chooseBestURL

import {
  slugify
} from 'bellajs'

import * as stringComparison from 'string-comparison'

import { getParserOptions } from '../config.js'

export default (candidates = [], title = '') => {
  const shortestUrl = candidates.reduce((prev, curr) => curr.length < prev.length ? curr : prev, candidates[0])

  const opts = getParserOptions()
  const alg = opts.urlsCompareAlgorithm
  const comparer = stringComparison[alg]

  const titleHashed = slugify(title)

  return candidates.reduce((prev, curr) => {
    const similarity = comparer.similarity(curr, titleHashed)
    const better = similarity > prev.similarity
    return better ? { similarity, value: curr } : prev
  }, {
    similarity: comparer.similarity(shortestUrl, titleHashed),
    value: shortestUrl
  }).value
}
<|endoftext|>


<commit_before>// js handling for activities.
$(document).ready(function(){

    function getLoadingHtml(){
        return '

Loading...

';
    }

    /**
     * This is for activities handling.
     *
     * Required data attributes:
     *
     *  - data-ajax="activities"
     *
     * Usage:
     *
     *
...

     */
    $('.activities-container').on('click', '.activity .delete-activity form button',  function(e){
        var $frm = $(this).closest('form'),
            form_data = $frm.serialize();

        e.preventDefault();

        $.post($frm.attr('action'), form_data, function(resp_text, success_fail, resp){
            if (resp.status == 200){
                $frm.closest('.activity-container').remove();
            } else if (window.console && window.console.log) {
                window.console.log('There was an error deleting the activity.');
            }
        });

    }).on('click', '.activities-paging .has-more', function(e){
        e.preventDefault();

        var $this = $(this),
            url = $this.attr('href');

        $this.replaceWith(getLoadingHtml());

        $.get(url, function(data){
            $('.activities-paging').remove();
            $('ul.activities:last').after(data);
        });

    }).on('click', 'ul.activity-type a', function(e){
        e.preventDefault();

        var $this = $(this),
            $parentType = $this.closest('.activity-type'),
            $parent = $this.closest('.activities-container'),
            $activitiesContainer = $parent.find('.activities:first'),
            $linkContainer = $this.closest('li'),
            url = $this.attr('href');

        if ($linkContainer.is('.active')) {
            // This is already active, nothing to do.
            return false;
        }

        $this.blur();
        $parentType.find('li').removeClass('active');
        $linkContainer.addClass('active');

        $parent.find('.activities-paging').remove();
        $activitiesContainer.append('
' + getLoadingHtml() + '
');

        $.get(url, function(data){
            $activitiesContainer.html(data);
        });

    }).on('focus', 'form.comment-form textarea', function(e){
        e.preventDefault();
        var $this = $(this);

        if ($this.data('origHeight') == undefined){
            $this.data('origHeight', $this.css('height'));
        }

        $this.css('height', '75px');

    }).on('blur', 'form.comment-form textarea', function(e) {
        var $this = $(this);

        if ($.trim($this.val()) == ''){
            $this.css('height', $this.data('origHeight'));
        }

    }).on('submit', 'form.comment-form', function(e){
        e.preventDefault();
        var $this = $(this),
            $activitiesContainer = $this.closest('.activities-container')
            $textField = $this.find('textarea[name="text"]'),
            formData = $this.serialize(),
            text = $.trim($textField.val());

        if (!text) {
            // No text in the comment.  Nothing to do.
            return false;
        }

        $.post($this.attr('action'), formData, function(resp_text, success_fail, resp){
            var $activities = $activitiesContainer.find('.activities:first');

            if (resp.status == 200 || resp.status == 202) {
                $activities.find('.no-activities-found').remove();
                $activities.prepend(resp_text.activity);
                $textField.val('');
                $textField.blur();
            } else if (window.console && window.console.log) {
                window.console.log('There was an error adding the comment.');
            }
        });

    }).on('submit', 'form.comment-reply-form', function(e){

        e.preventDefault();

        var $this = $(this),
            form_data = $this.serialize(),
            activity_id = $this.find('input[name="pid"]').val(),
            text = $.trim($this.find('input[name="text"]').val());

        if (!text) {
            // No text in the comment.  Nothing to do.
            return false;
        }

        $.post($this.attr('action'), form_data, function(resp_text, success_fail, resp){

            if (resp.status == 200 || resp.status == 202){
                $('#n-' + activity_id).replaceWith(resp_text.activity);
            } else if (window.console && window.console.log) {
                window.console.log('There was an error adding the activity reply.');
            }
        });

    }).on('submit', 'form.delete-activity', function(e){

        e.preventDefault();
        var $this = $(this),
            form_data = $this.serialize(),
            activity_id = $this.find('input[name="nid"]').val();

        $.post($this.attr('action'), form_data, function(resp_text, success_fail, resp){

            if (resp.status == 200){
                $('#n-' + activity_id).remove();
            } else if (window.console && window.console.log) {
                window.console.log('There was an error deleting the activity.');
            }
        });
    });

});
<commit_msg>js syntax fix.<commit_after>// js handling for activities.
$(document).ready(function(){

    function getLoadingHtml(){
        return '

Loading...

';
    }

    /**
     * This is for activities handling.
     *
     * Required data attributes:
     *
     *  - data-ajax="activities"
     *
     * Usage:
     *
     *
...

     */
    $('.activities-container').on('click', '.activity .delete-activity form button',  function(e){
        var $frm = $(this).closest('form'),
            form_data = $frm.serialize();

        e.preventDefault();

        $.post($frm.attr('action'), form_data, function(resp_text, success_fail, resp){
            if (resp.status == 200){
                $frm.closest('.activity-container').remove();
            } else if (window.console && window.console.log) {
                window.console.log('There was an error deleting the activity.');
            }
        });

    }).on('click', '.activities-paging .has-more', function(e){
        e.preventDefault();

        var $this = $(this),
            url = $this.attr('href');

        $this.replaceWith(getLoadingHtml());

        $.get(url, function(data){
            $('.activities-paging').remove();
            $('ul.activities:last').after(data);
        });

    }).on('click', 'ul.activity-type a', function(e){
        e.preventDefault();

        var $this = $(this),
            $parentType = $this.closest('.activity-type'),
            $parent = $this.closest('.activities-container'),
            $activitiesContainer = $parent.find('.activities:first'),
            $linkContainer = $this.closest('li'),
            url = $this.attr('href');

        if ($linkContainer.is('.active')) {
            // This is already active, nothing to do.
            return false;
        }

        $this.blur();
        $parentType.find('li').removeClass('active');
        $linkContainer.addClass('active');

        $parent.find('.activities-paging').remove();
        $activitiesContainer.append('
' + getLoadingHtml() + '
');

        $.get(url, function(data){
            $activitiesContainer.html(data);
        });

    }).on('focus', 'form.comment-form textarea', function(e){
        e.preventDefault();
        var $this = $(this);

        if ($this.data('origHeight') === undefined){
            $this.data('origHeight', $this.css('height'));
        }

        $this.css('height', '75px');

    }).on('blur', 'form.comment-form textarea', function(e) {
        var $this = $(this);

        if ($.trim($this.val()) == ''){
            $this.css('height', $this.data('origHeight'));
        }

    }).on('submit', 'form.comment-form', function(e){
        e.preventDefault();
        var $this = $(this),
            $activitiesContainer = $this.closest('.activities-container')
            $textField = $this.find('textarea[name="text"]'),
            formData = $this.serialize(),
            text = $.trim($textField.val());

        if (!text) {
            // No text in the comment.  Nothing to do.
            return false;
        }

        $.post($this.attr('action'), formData, function(resp_text, success_fail, resp){
            var $activities = $activitiesContainer.find('.activities:first');

            if (resp.status == 200 || resp.status == 202) {
                $activities.find('.no-activities-found').remove();
                $activities.prepend(resp_text.activity);
                $textField.val('');
                $textField.blur();
            } else if (window.console && window.console.log) {
                window.console.log('There was an error adding the comment.');
            }
        });

    }).on('submit', 'form.comment-reply-form', function(e){

        e.preventDefault();

        var $this = $(this),
            form_data = $this.serialize(),
            activity_id = $this.find('input[name="pid"]').val(),
            text = $.trim($this.find('input[name="text"]').val());

        if (!text) {
            // No text in the comment.  Nothing to do.
            return false;
        }

        $.post($this.attr('action'), form_data, function(resp_text, success_fail, resp){

            if (resp.status == 200 || resp.status == 202){
                $('#n-' + activity_id).replaceWith(resp_text.activity);
            } else if (window.console && window.console.log) {
                window.console.log('There was an error adding the activity reply.');
            }
        });

    }).on('submit', 'form.delete-activity', function(e){

        e.preventDefault();
        var $this = $(this),
            form_data = $this.serialize(),
            activity_id = $this.find('input[name="nid"]').val();

        $.post($this.attr('action'), form_data, function(resp_text, success_fail, resp){

            if (resp.status == 200){
                $('#n-' + activity_id).remove();
            } else if (window.console && window.console.log) {
                window.console.log('There was an error deleting the activity.');
            }
        });
    });

});
<|endoftext|>


<commit_before>var Q = require('q');
var mongoose = require('mongoose');

/**
 * Connect to MongoDB Database.
 *
 * @param {String} db
 */

exports.connect = function(db) {
    if (!db) db = 'mongodb://localhost:27017/ps';
    var url = process.env.MONGODB || db;
    mongoose.connect(url);
    mongoose.connection.on('error', function() {
        console.error('MongoDB Connection Error. Make sure MongoDB is running.');
    });
};

var userSchema = new mongoose.Schema({
    name: { type: String, lowercase: true, unique: true },
    money: { type: Number, default: 0 },
    symbol: String,
    seen: Date,
    cards: Array
});

var User = exports.userModel = mongoose.model('user', userSchema);

exports.User = {
    /**
     * Promise wrapper for User.findOne.
     *
     * @param {Object} query
     * @return {Promise}
     */
    findOne: function(query) {
        var deferred = Q.defer();
        User.findOne(query, function(err, result) {
            if (err) return deferred.reject(new Error(err));
            deferred.resolve(result);
        });
        return deferred.promise;
    },
    /**
     * Promise wrapper for User.find.
     *
     * @param {Object} query
     * @return {Promise}
     */
    find: function(query) {
        var deferred = Q.defer();
        User.find(query, function(err, result) {
            if (err) return deferred.reject(new Error(err));
            deferred.resolve(result);
        });
        return deferred.promise;
    }
};<commit_msg>Add marketplace schema<commit_after>var Q = require('q');
var mongoose = require('mongoose');

/**
 * Connect to MongoDB Database.
 *
 * @param {String} db
 */

exports.connect = function(db) {
    if (!db) db = 'mongodb://localhost:27017/ps';
    var url = process.env.MONGODB || db;
    mongoose.connect(url);
    mongoose.connection.on('error', function() {
        console.error('MongoDB Connection Error. Make sure MongoDB is running.');
    });
};

var userSchema = new mongoose.Schema({
    name: { type: String, lowercase: true, unique: true },
    money: { type: Number, default: 0 },
    symbol: String,
    seen: Date,
    cards: Array
});

var User = exports.userModel = mongoose.model('user', userSchema);

var marketplaceSchema = new mongoose.Schema({
    cid: { type: String, unique: true},
    card: String,
    name: String,
    rarity: String,
    points: Number,
    owner: String,
    price: Number
});

export.MarketPlace = mongoose.model('marketplace', marketplaceSchema);

exports.User = {
    /**
     * Promise wrapper for User.findOne.
     *
     * @param {Object} query
     * @return {Promise}
     */
    findOne: function(query) {
        var deferred = Q.defer();
        User.findOne(query, function(err, result) {
            if (err) return deferred.reject(new Error(err));
            deferred.resolve(result);
        });
        return deferred.promise;
    },
    /**
     * Promise wrapper for User.find.
     *
     * @param {Object} query
     * @return {Promise}
     */
    find: function(query) {
        var deferred = Q.defer();
        User.find(query, function(err, result) {
            if (err) return deferred.reject(new Error(err));
            deferred.resolve(result);
        });
        return deferred.promise;
    }
};<|endoftext|>