<commit_before>'use strict';

var babel = require('babel-core');
var babelDeps = require('babel-deps');
var BabelGlobalsFormatter = require('babel-globals-module-formatter');
var Concat = require('concat-with-sourcemaps');

function addUsedHelpers(concat, results) {
	var usedHelpers = getUsedExternalHelpers(results);
	concat.add('helpers.js', babel.buildExternalHelpers(usedHelpers, 'var'));
}

function compileToGlobals(files, options) {
	dependencies = {};
	visited = {};

	options = normalizeOptions(options);
	var results = babelDeps(files, options.babelOptions);
	var orderedResults = sortModules(results);

	var concat = new Concat(true, options.bundleFileName, '\n');
	initializeGlobalVar(concat, options);
	addUsedHelpers(concat, results);
	for (var i = 0; i < orderedResults.length; i++) {
		concat.add(orderedResults[i].path, orderedResults[i].babel.code, orderedResults[i].babel.map);
	}
	return concat;
}

function getUsedExternalHelpers(results) {
	var hasHelper = {};
	for (var i = 0; i < results.length; i++) {
		var currHelpers = results[i].babel.metadata.usedHelpers;
		for (var j = 0; j < currHelpers.length; j++) {
			hasHelper[currHelpers[j]] = true;
		}
	}
	return Object.keys(hasHelper);
}

function initializeGlobalVar(concat, options) {
	if (!options.skipGlobalVarInit) {
		concat.add('init.js', 'this.' + options.babelOptions._globalName + ' = {};');
	}
}

function normalizeOptions(options) {
	options = options || {};
	options.babelOptions = options.babelOptions || {};
	options.babelOptions.externalHelpers = true;
	options.babelOptions.metadataUsedHelpers = true;
	if (options.babelOptions.resolveModuleSource) {
		var originalFn = options.babelOptions.resolveModuleSource;
		options.babelOptions.resolveModuleSource = function(source, filename) {
			return resolveModuleSource(originalFn(source, filename), filename);
		};
	} else {
		options.babelOptions.resolveModuleSource = resolveModuleSource;
	}
	options.babelOptions.modules = BabelGlobalsFormatter;
	options.babelOptions._globalName = options.globalName || 'myGlobals';

	options.bundleFileName = options.bundleFileName || 'bundle.js';
	return options;
}

var dependencies = {};
var visited = {};
function resolveModuleSource(source, filename) {
	dependencies[filename] = dependencies[filename] || [];
	dependencies[filename].push(babelDeps.getFullPath(source, filename));
	return source;
}

function sortModules(results) {
	var orderedResultPaths = [];
	var pathToResults = {};
	for (var i = 0; i < results.length; i++) {
		pathToResults[results[i].path] = results[i];
		visit(results[i].path, orderedResultPaths);
	}

	var orderedResults = [];
	for (var j = 0; j < orderedResultPaths.length; j++) {
		orderedResults.push(pathToResults[orderedResultPaths[j]]);
	}
	return orderedResults;
}

function visit(filePath, orderedArr) {
	if (visited[filePath]) {
		return;
	}
	visited[filePath] = true;

	var deps = dependencies[filePath] || [];
	deps.forEach(function(dep) {
		visit(dep, orderedArr);
	});
	orderedArr.push(filePath);
}

module.exports = compileToGlobals;
<commit_msg>Adds babel external helpers as global as well<commit_after>'use strict';

var babel = require('babel-core');
var babelDeps = require('babel-deps');
var BabelGlobalsFormatter = require('babel-globals-module-formatter');
var Concat = require('concat-with-sourcemaps');

function addUsedHelpers(concat, results) {
	var usedHelpers = getUsedExternalHelpers(results);
	concat.add('helpers.js', babel.buildExternalHelpers(usedHelpers));
}

function compileToGlobals(files, options) {
	dependencies = {};
	visited = {};

	options = normalizeOptions(options);
	var results = babelDeps(files, options.babelOptions);
	var orderedResults = sortModules(results);

	var concat = new Concat(true, options.bundleFileName, '\n');
	initializeGlobalVar(concat, options);
	addUsedHelpers(concat, results);
	for (var i = 0; i < orderedResults.length; i++) {
		concat.add(orderedResults[i].path, orderedResults[i].babel.code, orderedResults[i].babel.map);
	}
	return concat;
}

function getUsedExternalHelpers(results) {
	var hasHelper = {};
	for (var i = 0; i < results.length; i++) {
		var currHelpers = results[i].babel.metadata.usedHelpers;
		for (var j = 0; j < currHelpers.length; j++) {
			hasHelper[currHelpers[j]] = true;
		}
	}
	return Object.keys(hasHelper);
}

function initializeGlobalVar(concat, options) {
	if (!options.skipGlobalVarInit) {
		concat.add('init.js', 'this.' + options.babelOptions._globalName + ' = {};');
	}
}

function normalizeOptions(options) {
	options = options || {};
	options.babelOptions = options.babelOptions || {};
	options.babelOptions.externalHelpers = true;
	options.babelOptions.metadataUsedHelpers = true;
	if (options.babelOptions.resolveModuleSource) {
		var originalFn = options.babelOptions.resolveModuleSource;
		options.babelOptions.resolveModuleSource = function(source, filename) {
			return resolveModuleSource(originalFn(source, filename), filename);
		};
	} else {
		options.babelOptions.resolveModuleSource = resolveModuleSource;
	}
	options.babelOptions.modules = BabelGlobalsFormatter;
	options.babelOptions._globalName = options.globalName || 'myGlobals';

	options.bundleFileName = options.bundleFileName || 'bundle.js';
	return options;
}

var dependencies = {};
var visited = {};
function resolveModuleSource(source, filename) {
	dependencies[filename] = dependencies[filename] || [];
	dependencies[filename].push(babelDeps.getFullPath(source, filename));
	return source;
}

function sortModules(results) {
	var orderedResultPaths = [];
	var pathToResults = {};
	for (var i = 0; i < results.length; i++) {
		pathToResults[results[i].path] = results[i];
		visit(results[i].path, orderedResultPaths);
	}

	var orderedResults = [];
	for (var j = 0; j < orderedResultPaths.length; j++) {
		orderedResults.push(pathToResults[orderedResultPaths[j]]);
	}
	return orderedResults;
}

function visit(filePath, orderedArr) {
	if (visited[filePath]) {
		return;
	}
	visited[filePath] = true;

	var deps = dependencies[filePath] || [];
	deps.forEach(function(dep) {
		visit(dep, orderedArr);
	});
	orderedArr.push(filePath);
}

module.exports = compileToGlobals;
<|endoftext|>


<commit_before>/**
* @fileoverview Interprets a given command and calls workspace controller_.functions.
* @author pandori@wisc.edu (Sahib Pandori)
* @author david.liang@wisc.edu (David Liang)
*/

'use strict';

goog.provide('SpeechBlocks.Interpreter');

goog.require('SpeechBlocks.Predecessor');
goog.require('SpeechBlocks.StatementInput')
goog.require('SpeechBlocks.Successor');
goog.require('SpeechBlocks.Translation');
goog.require('SpeechBlocks.ValueInput');
goog.require('goog.structs.Map');

/**
* Constructs an interpreter that takes actions as input and controls the Blockly Workspace.
* @param {!SpeechBlocks.Controller} controller_.The workspace controller_.
*/
SpeechBlocks.Interpreter = function(controller) {
  /** @private @const */
  this.controller_ = controller;
  /** @private */
  this.id_ = 1;
  /** @private */
  this.blockTypeMap_ = new goog.structs.Map();
  /**
  this.blockTypeMap_.set('if','controls_if');
  this.blockTypeMap_.set('comparison','logic_compare');
  this.blockTypeMap_.set('repeat','controls_repeat_ext');
  this.blockTypeMap_.set('number','math_number');
  this.blockTypeMap_.set('arithmetic','math_arithmetic');
  this.blockTypeMap_.set('text','text');
  this.blockTypeMap_.set('print','text_print');
  this.blockTypeMap_.set('set','variables_set');
  this.blockTypeMap_.set('variable','variables_get');
  */
  // temporary
  try {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", 'https://aravart.github.io/speech-blocks/grammar/blockTypeMap.txt', true);
    rawFile.onreadystatechange = function () {
      console.log('a');
      if(rawFile.readyState == 4) {
          console.log('b');
        if(rawFile.status == 200 || rawFile.status == 0) {
            console.log('c');
          var inputText = rawFile.responseText;
          inputText = inputText.split(/\r\n|\r|\n/g);
          for (var i = 0; i < inputText.length; i++) {
            var keyValuePair = inputText[i].split(":");
            console.log(keyValuePair[0]);
            console.log(keyValuePair[1]);
            this.blockTypeMap_.set(keyValuePair[0], keyValuePair[1]);
          }
          console.log(inputText);
        }
        rawFile.send();
      }
    }
    rawFile.onreadystatechange();
  } catch(err) { console.log(err.message); }
  console.log(this.blockTypeMap_.isEmpty());
  console.log(this.blockTypeMap_.getValues())
  console.log(this.blockTypeMap_.get('if'));
}

/**
* Interprets a given command by calling the corresponding action function.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.interpret = function(command) {
  switch (command.action) {
    case 'run': this.run(command); break;
    case 'add': this.addBlock(command); break;
    case 'move': this.moveBlock(command); break;
    case 'modify': this.modifyBlock(command); break;
    case 'delete': this.deleteBlock(command); break;
    default: console.log('Unsupported command');
  }
};

/**
* Compiles the Blockly code into JavaScript and runs it.
* @param {Object=} command Object with command specifics from the parser.
*/
SpeechBlocks.Interpreter.prototype.run = function(command) {
  Blockly.JavaScript.addReservedWords('code');
  var code = Blockly.JavaScript.workspaceToCode(this.controller_.workspace);
  eval(code);
};

/**
* Adds a specified block.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.addBlock = function(command) {
  var type = this.blockTypeMap_.get(command.type);
  if (type != null) { this.controller_.addBlock(type, (this.id_++).toString(), new SpeechBlocks.Translation(0,0)); }
};

/**
* @TODO Implement error checking
* Moves a specified block.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.moveBlock = function(command) {
  // ensure these fields are strings, so validity checking works properly
  command.block = command.block.toString();
  command.where.block = command.where.block.toString();
  if (this.isBlockIdValid(command.block)) {
    if (command.where == 'trash') {
      this.deleteBlock(command.block);
    } else {
      if (this.isBlockIdValid(command.where.block)) {
        switch (command.where.position) {
          // modify these so the 'where' field is right
          case 'after': this.controller_.moveBlock(command.block, new SpeechBlocks.Successor(command.where.block)); break;
          case 'before': this.controller_.moveBlock(command.block, new SpeechBlocks.Predecessor(command.where.block)); break;
          case 'lhs': case 'rhs': case 'to the right of':
          var inputList_ = this.controller_.getBlockValueInputs(command.where.block);
          if (inputList_.length < 1) { console.log('NO VALUE INPUTS FOR SPECIFIED BLOCK'); }
          else if (command.where.position == 'rhs' || command.where.position == 'to the right of') { this.controller_.moveBlock(command.block, new SpeechBlocks.ValueInput(command.where.block, inputList_[inputList_.length-1]));	}
          else { this.controller_.moveBlock(command.block, new SpeechBlocks.ValueInput(command.where.block, inputList_[0])); }
          case 'inside':
          var statementList_ = this.controller_.getBlockStatementInputs(command.where.block);
          if (statementList_.length < 1) { console.log('NO STATEMENT INPUTS FOR SPECIFIED BLOCK'); }
          else { this.controller_.moveBlock(command.block, new SpeechBlocks.StatementInput(command.where.block, statementList_[statementList_.length-1])); }
          break;
          default:
          console.log('Unsupported position');
        }
      }
    }
  }
  else {
    console.log('Invalid block Id');
  }
};

/**
* @TODO Implement each case of property
* Modifies a specified block.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.modifyBlock = function(command) {
  if (this.isBlockIdValid(command.block)) {
    switch(command.property) {
      case 'number':
      command.value = Number(command.value);
      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      case 'text':

      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      case 'comparison':

      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      case 'operation':

      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      case 'name':

      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      default:
      console.log('Unsupported property');
    }
    console.log('MODIFY NOT YET SUPPORTED');
  }
  else {
    console.log('Invalid block Id');
  }
};

/**
* Delete a specified block.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.deleteBlock = function(blockId) {
  if (this.isBlockIdValid(blockId)) { this.controller_.removeBlock(blockId); }
  else { console.log('Invalid block Id'); }
};

/**
* Checks to see if a block Id is valid.
* @param {!String=} blockId as string.
*/
SpeechBlocks.Interpreter.prototype.isBlockIdValid = function(blockRequestId) {
  return this.controller_.getAllBlockIds().contains(blockRequestId);
}
<commit_msg>File IO testing<commit_after>/**
* @fileoverview Interprets a given command and calls workspace controller_.functions.
* @author pandori@wisc.edu (Sahib Pandori)
* @author david.liang@wisc.edu (David Liang)
*/

'use strict';

goog.provide('SpeechBlocks.Interpreter');

goog.require('SpeechBlocks.Predecessor');
goog.require('SpeechBlocks.StatementInput')
goog.require('SpeechBlocks.Successor');
goog.require('SpeechBlocks.Translation');
goog.require('SpeechBlocks.ValueInput');
goog.require('goog.structs.Map');

/**
* Constructs an interpreter that takes actions as input and controls the Blockly Workspace.
* @param {!SpeechBlocks.Controller} controller_.The workspace controller_.
*/
SpeechBlocks.Interpreter = function(controller) {
  /** @private @const */
  this.controller_ = controller;
  /** @private */
  this.id_ = 1;
  /** @private */
  this.blockTypeMap_ = new goog.structs.Map();
  /**
  this.blockTypeMap_.set('if','controls_if');
  this.blockTypeMap_.set('comparison','logic_compare');
  this.blockTypeMap_.set('repeat','controls_repeat_ext');
  this.blockTypeMap_.set('number','math_number');
  this.blockTypeMap_.set('arithmetic','math_arithmetic');
  this.blockTypeMap_.set('text','text');
  this.blockTypeMap_.set('print','text_print');
  this.blockTypeMap_.set('set','variables_set');
  this.blockTypeMap_.set('variable','variables_get');
  */
  // temporary
  try {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", 'https://aravart.github.io/speech-blocks/grammar/blockTypeMap.txt', true);
    rawFile.onreadystatechange = function () {
      console.log('rawFile.readyState');
      if(rawFile.readyState == 4) {
          console.log('b');
        if(rawFile.status == 200 || rawFile.status == 0) {
            console.log('c');
          var inputText = rawFile.responseText;
          inputText = inputText.split(/\r\n|\r|\n/g);
          for (var i = 0; i < inputText.length; i++) {
            var keyValuePair = inputText[i].split(":");
            console.log(keyValuePair[0]);
            console.log(keyValuePair[1]);
            this.blockTypeMap_.set(keyValuePair[0], keyValuePair[1]);
          }
          console.log(inputText);
        }
        rawFile.send();
      }
    }
    rawFile.onreadystatechange();
  } catch(err) { console.log(err.message); }
  console.log(this.blockTypeMap_.isEmpty());
  console.log(this.blockTypeMap_.getValues())
  console.log(this.blockTypeMap_.get('if'));
}

/**
* Interprets a given command by calling the corresponding action function.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.interpret = function(command) {
  switch (command.action) {
    case 'run': this.run(command); break;
    case 'add': this.addBlock(command); break;
    case 'move': this.moveBlock(command); break;
    case 'modify': this.modifyBlock(command); break;
    case 'delete': this.deleteBlock(command); break;
    default: console.log('Unsupported command');
  }
};

/**
* Compiles the Blockly code into JavaScript and runs it.
* @param {Object=} command Object with command specifics from the parser.
*/
SpeechBlocks.Interpreter.prototype.run = function(command) {
  Blockly.JavaScript.addReservedWords('code');
  var code = Blockly.JavaScript.workspaceToCode(this.controller_.workspace);
  eval(code);
};

/**
* Adds a specified block.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.addBlock = function(command) {
  var type = this.blockTypeMap_.get(command.type);
  if (type != null) { this.controller_.addBlock(type, (this.id_++).toString(), new SpeechBlocks.Translation(0,0)); }
};

/**
* @TODO Implement error checking
* Moves a specified block.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.moveBlock = function(command) {
  // ensure these fields are strings, so validity checking works properly
  command.block = command.block.toString();
  command.where.block = command.where.block.toString();
  if (this.isBlockIdValid(command.block)) {
    if (command.where == 'trash') {
      this.deleteBlock(command.block);
    } else {
      if (this.isBlockIdValid(command.where.block)) {
        switch (command.where.position) {
          // modify these so the 'where' field is right
          case 'after': this.controller_.moveBlock(command.block, new SpeechBlocks.Successor(command.where.block)); break;
          case 'before': this.controller_.moveBlock(command.block, new SpeechBlocks.Predecessor(command.where.block)); break;
          case 'lhs': case 'rhs': case 'to the right of':
          var inputList_ = this.controller_.getBlockValueInputs(command.where.block);
          if (inputList_.length < 1) { console.log('NO VALUE INPUTS FOR SPECIFIED BLOCK'); }
          else if (command.where.position == 'rhs' || command.where.position == 'to the right of') { this.controller_.moveBlock(command.block, new SpeechBlocks.ValueInput(command.where.block, inputList_[inputList_.length-1]));	}
          else { this.controller_.moveBlock(command.block, new SpeechBlocks.ValueInput(command.where.block, inputList_[0])); }
          case 'inside':
          var statementList_ = this.controller_.getBlockStatementInputs(command.where.block);
          if (statementList_.length < 1) { console.log('NO STATEMENT INPUTS FOR SPECIFIED BLOCK'); }
          else { this.controller_.moveBlock(command.block, new SpeechBlocks.StatementInput(command.where.block, statementList_[statementList_.length-1])); }
          break;
          default:
          console.log('Unsupported position');
        }
      }
    }
  }
  else {
    console.log('Invalid block Id');
  }
};

/**
* @TODO Implement each case of property
* Modifies a specified block.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.modifyBlock = function(command) {
  if (this.isBlockIdValid(command.block)) {
    switch(command.property) {
      case 'number':
      command.value = Number(command.value);
      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      case 'text':

      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      case 'comparison':

      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      case 'operation':

      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      case 'name':

      this.controller.setBlockField(command.block, fieldName, command.value);
      break;
      default:
      console.log('Unsupported property');
    }
    console.log('MODIFY NOT YET SUPPORTED');
  }
  else {
    console.log('Invalid block Id');
  }
};

/**
* Delete a specified block.
* @param {Object=} command Command object from parser.
*/
SpeechBlocks.Interpreter.prototype.deleteBlock = function(blockId) {
  if (this.isBlockIdValid(blockId)) { this.controller_.removeBlock(blockId); }
  else { console.log('Invalid block Id'); }
};

/**
* Checks to see if a block Id is valid.
* @param {!String=} blockId as string.
*/
SpeechBlocks.Interpreter.prototype.isBlockIdValid = function(blockRequestId) {
  return this.controller_.getAllBlockIds().contains(blockRequestId);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * This script gathers dates and payload names from the subreddit launch manifest,
 * fuzzy checks them against existing upcoming payload id's and updates the date if a
 * change is made in the wiki. The proper time zone is calculated from the launch site
 * id of the launch.
 */

const MongoClient = require('mongodb');
const moment = require('moment-timezone');
const cheerio = require('cheerio');
const request = require('request-promise-native');
const fuzz = require('fuzzball');

moment.suppressDeprecationWarnings = true;

let client;
let location;
let calculatedTimes;
let localTime;
let date;

const sites = [];
const payloads = [];
const promises = [];
const precision = [];

const hour = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}\s(\[[0-9]{2}:[0-9]{2}\]|[0-9]{2}:[0-9]{2})$/;
const day = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}$/;
const month = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})$/;
const year = /^[0-9]{4}$/;

(async () => {
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });

    const db = client.db('spacex-api');
    const col = db.collection('launch');

    const launches = await col.find({ upcoming: true }).toArray();

    // Collect site names for time zone and payload name for fuzzy check
    launches.forEach(launch => {
      // Add temp fix for last Iridium NEXT launch because we need fuzzy
      // search to return 100% substring match, else we get SSO-A and SSO-B changing
      // because of a slight difference.
      // NOTE: Will be removed after launch
      if (launch.rocket.second_stage.payloads[0].payload_id === 'Iridium NEXT 8') {
        payloads.push('Iridium 8');
      } else {
        payloads.push(launch.rocket.second_stage.payloads[0].payload_id);
      }
      sites.push(launch.launch_site.site_id);
    });

    // Grab subreddit wiki manifest
    const result = await request('https://www.reddit.com/r/spacex/wiki/launches/manifest');
    const $ = cheerio.load(result);

    // Grab entire row, clean date, and convert to valid UTC moment date
    const manifest = $('body > div.content > div > div > table:nth-child(6) > tbody').text();
    const manifest_row = manifest.split('\n').filter(v => v !== '');

    // Filter to collect manaifest dates
    const manifest_dates = manifest_row.filter((value, index) => {
      return index % 8 === 0;
    });

    // Filter to collect payload names
    const manifest_payloads = manifest_row.filter((value, index) => {
      return (index + 3) % 8 === 0;
    });

    payloads.forEach((payload, p_index) => {
      manifest_payloads.forEach((manifest_payload, m_index) => {
        if (fuzz.partial_ratio(payload, manifest_payload) === 100) {
          // Check and see if dates match a certain patten depending on the length of the
          // date given. This sets the amount of precision needed for the date.
          let mdate = manifest_dates[m_index];
          if (mdate.includes('Q')) {
            mdate = mdate.replace('Q', '');
            precision[m_index] = 'quarter';
          } else if (mdate.includes('H1')) {
            mdate = mdate.replace('H1', '1');
            precision[m_index] = 'half';
          } else if (mdate.includes('H2')) {
            mdate = mdate.replace('H2', '3');
            precision[m_index] = 'half';
          } else if (year.test(mdate)) {
            precision[m_index] = 'year';
          } else if (month.test(mdate)) {
            precision[m_index] = 'month';
          } else if (day.test(mdate)) {
            precision[m_index] = 'day';
          } else if (hour.test(mdate)) {
            precision[m_index] = 'hour';
          } else {
            precision[m_index] = 'hour';
          }

          location = sites[p_index];
          date = manifest_dates[m_index];

          console.log(date);
          console.log(`${payload} : ${manifest_payload}`);

          const stripped_time = `${date.replace('[', '').replace(']', '')} +0000`;
          const time = moment(stripped_time, ['YYYY MMM D HH:mm Z', 'YYYY MMM D Z', 'YYYY MMM Z', 'YYYY Q Z', 'YYYY Z']);
          const zone = moment.tz(time, 'UTC');

          // Set timezone based on launch location
          if (location === 'ccafs_slc_40' || location === 'ksc_lc_39a' || location === 'ccafs_lc_13') {
            localTime = time.tz('America/New_York').format();
          } else if (location === 'vafb_slc_4e' || location === 'vafb_slc_4w') {
            localTime = time.tz('America/Los_Angeles').format();
          } else {
            localTime = time.tz('America/Chicago').format();
          }

          // Build launch time objects to update
          calculatedTimes = {
            launch_date_unix: zone.unix(),
            launch_date_utc: zone.toISOString(),
            launch_date_local: localTime,
            is_tentative: true,
            tentative_max_precision: precision[m_index],
          };
          console.log(calculatedTimes);
          console.log('');

          // Another special case added for last Iridium launch
          // NOTE: Will be removed after launch
          if (payload === 'Iridium 8') {
            payload = 'Iridium NEXT 8';
          }

          promises.push(col.updateOne({ 'rocket.second_stage.payloads.payload_id': payload }, { $set: calculatedTimes }));
        }
      });
    });
    const output = await Promise.all(promises);
    output.forEach(doc => {
      console.log(`N: ${doc.result.n}`);
      console.log(`Modified: ${doc.result.nModified}`);
    });
  } catch (err) {
    console.log(err.stack);
  }

  if (client) {
    client.close();
  }
})();
<commit_msg>Added more comments to upcoming script<commit_after>#!/usr/bin/env node

/**
 * This script gathers dates and payload names from the subreddit launch manifest,
 * fuzzy checks them against existing upcoming payload id's and updates the date if a
 * change is made in the wiki. The proper time zone is calculated from the launch site
 * id of the launch.
 *
 * Hopefully the format of the wiki does not change, but there's no real reason for it to change in the
 * forseeable future. If it does change
 */

const MongoClient = require('mongodb');
const moment = require('moment-timezone');
const cheerio = require('cheerio');
const request = require('request-promise-native');
const fuzz = require('fuzzball');

moment.suppressDeprecationWarnings = true;

let client;
let location;
let calculatedTimes;
let localTime;
let date;

const sites = [];
const payloads = [];
const promises = [];
const precision = [];

// RegEx expressions for matching dates in the wiki manifest
// Allows for long months or short months ex. September vs Sep
// Allows for time with or without brackets ex [23:45] vs 23:45
const hour = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}\s(\[[0-9]{2}:[0-9]{2}\]|[0-9]{2}:[0-9]{2})$/;
const day = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}$/;
const month = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})$/;
const year = /^[0-9]{4}$/;

(async () => {
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });

    const db = client.db('spacex-api');
    const col = db.collection('launch');

    const launches = await col.find({ upcoming: true }).toArray();

    // Collect site names for time zone and payload name for fuzzy check
    launches.forEach(launch => {
      // Add temp fix for last Iridium NEXT launch because we need fuzzy
      // search to return 100% substring match, else we get SSO-A and SSO-B changing
      // because of a slight difference.
      // NOTE: Will be removed after launch
      if (launch.rocket.second_stage.payloads[0].payload_id === 'Iridium NEXT 8') {
        payloads.push('Iridium 8');
      } else {
        payloads.push(launch.rocket.second_stage.payloads[0].payload_id);
      }
      sites.push(launch.launch_site.site_id);
    });

    // Grab subreddit wiki manifest
    const result = await request('https://www.reddit.com/r/spacex/wiki/launches/manifest');
    const $ = cheerio.load(result);

    // Grab entire row, clean date, and convert to valid UTC moment date
    const manifest = $('body > div.content > div > div > table:nth-child(6) > tbody').text();
    const manifest_row = manifest.split('\n').filter(v => v !== '');

    // Filter to collect manaifest dates
    const manifest_dates = manifest_row.filter((value, index) => {
      return index % 8 === 0;
    });

    // Filter to collect payload names
    const manifest_payloads = manifest_row.filter((value, index) => {
      return (index + 3) % 8 === 0;
    });

    payloads.forEach((payload, p_index) => {
      manifest_payloads.forEach((manifest_payload, m_index) => {
        if (fuzz.partial_ratio(payload, manifest_payload) === 100) {
          // Check and see if dates match a certain patten depending on the length of the
          // date given. This sets the amount of precision needed for the date.
          let mdate = manifest_dates[m_index];
          if (mdate.includes('Q')) {
            mdate = mdate.replace('Q', '');
            precision[m_index] = 'quarter';
          } else if (mdate.includes('H1')) {
            mdate = mdate.replace('H1', '1');
            precision[m_index] = 'half';
          } else if (mdate.includes('H2')) {
            mdate = mdate.replace('H2', '3');
            precision[m_index] = 'half';
          } else if (year.test(mdate)) {
            precision[m_index] = 'year';
          } else if (month.test(mdate)) {
            precision[m_index] = 'month';
          } else if (day.test(mdate)) {
            precision[m_index] = 'day';
          } else if (hour.test(mdate)) {
            precision[m_index] = 'hour';
          } else {
            console.log('Date did not match any of the existing regular expressions');
            process.exit(1);
          }

          // Store site_id for update query
          // Store manifest date for cleaning
          location = sites[p_index];
          date = manifest_dates[m_index];

          console.log(date);
          console.log(`${payload} : ${manifest_payload}`);

          // Strip brackets from time given, and tack on UTC time offset at the end for date parser
          const stripped_time = `${date.replace('[', '').replace(']', '')} +0000`;
          // Feed stripped time into all possible date formats in the wiki currently
          const time = moment(stripped_time, ['YYYY MMM D HH:mm Z', 'YYYY MMM D Z', 'YYYY MMM Z', 'YYYY Q Z', 'YYYY Z']);
          const zone = moment.tz(time, 'UTC');

          // Set timezone based on launch site id
          if (location === 'ccafs_slc_40' || location === 'ksc_lc_39a' || location === 'ccafs_lc_13') {
            localTime = time.tz('America/New_York').format();
          } else if (location === 'vafb_slc_4e' || location === 'vafb_slc_4w') {
            localTime = time.tz('America/Los_Angeles').format();
          } else {
            localTime = time.tz('America/Chicago').format();
          }

          // Build launch time objects to update
          calculatedTimes = {
            launch_date_unix: zone.unix(),
            launch_date_utc: zone.toISOString(),
            launch_date_local: localTime,
            is_tentative: true,
            tentative_max_precision: precision[m_index],
          };
          console.log(calculatedTimes);
          console.log('');

          // Another special case added for last Iridium launch
          // NOTE: Will be removed after launch
          if (payload === 'Iridium 8') {
            payload = 'Iridium NEXT 8';
          }

          // Add to array of promises to update all at once after the forEach functions finish
          promises.push(col.updateOne({ 'rocket.second_stage.payloads.payload_id': payload }, { $set: calculatedTimes }));
        }
      });
    });
    // Execute all our stored update promises
    const output = await Promise.all(promises);
    // Display if the document was found, and if it was modified or not
    output.forEach(doc => {
      console.log(`N: ${doc.result.n}`);
      console.log(`Modified: ${doc.result.nModified}`);
    });
  } catch (err) {
    console.log(err.stack);
  }

  if (client) {
    client.close();
  }
})();
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-chart', 'Integration | Component | sl chart', {
    integration: true
});

test( 'Defaults applied correctly', function( assert ) {
    this.set( 'testseries', [] );
    this.set( 'testoptions', {} );

    this.render( hbs`
        {{#sl-chart series=testseries options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.ok(
      this.$( '.sl-chart' ).hasClass( 'sl-chart' ),
      'has class sl-chart'
    );

    assert.ok(
      this.$( '.sl-chart' ).hasClass( 'panel' ),
      'has class panel'
    );

    assert.ok(
      this.$( '.sl-chart' ).hasClass( 'panel-default' ),
      'has class panel-default'
    );

    assert.ok(
      this.$( '.sl-chart' ).hasClass( 'sl-panel' ),
      'has class sl-panel'
    );
});

test( 'Loading state adds loading class', function( assert ) {
    this.set( 'testseries', [] );
    this.set( 'testoptions', {} );

    this.render( hbs`
        {{#sl-chart series=testseries isLoading=false options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.strictEqual(
        this.$( '.sl-chart' ).hasClass( 'sl-loading' ),
        false,
        'Default rendered component does not have "sl-loading" class'
    );

    this.render( hbs`
        {{#sl-chart series=testseries isLoading=true options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.strictEqual(
        this.$( '.sl-chart' ).hasClass( 'sl-loading' ),
        true,
        'Default rendered component does have "sl-loading" class'
    );
});

test( 'Title property is set', function( assert ) {
    this.set( 'testseries', [] );
    this.set( 'testoptions', {} );

    this.render( hbs`
        {{#sl-chart series=testseries options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.strictEqual(
        this.$( '.panel-heading' ).html(),
        undefined,
        'No chart title is rendered when title is not set'
    );

    this.render( hbs`
        {{#sl-chart title='Peak serve hours' series=testseries options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.equal(
        this.$( '.panel-heading' ).html(),
        'Peak serve hours',
        'Chart title is created with title value'
    );
});

test( 'Chart div uses the correct style', function( assert ) {
    this.set( 'testseries', [] );
    this.set( 'testoptions', {} );

    this.render( hbs`
        {{#sl-chart series=testseries options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.equal(
        this.$( 'div.chart' ).attr( 'style' ),
        'height: auto; width: auto;',
        'Chart div has automatic height and width'
    );

    this.render( hbs`
        {{#sl-chart series=testseries options=testoptions height=10 width=20}}
        {{/sl-chart}}
    ` );

    assert.equal(
        this.$( 'div.chart' ).attr( 'style' ),
        'height: 10; width: 20;',
        'Chart div has height 10 and width 20'
    );
});<commit_msg>closes https://github.com/softlayer/sl-ember-components/issues/722<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-chart', 'Integration | Component | sl chart', {
    integration: true
});

test( 'Defaults applied correctly', function( assert ) {
    this.set( 'testseries', [] );
    this.set( 'testoptions', {} );

    this.render( hbs`
        {{#sl-chart series=testseries options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.ok(
      this.$( '>:first-child' ).hasClass( 'sl-chart' ),
      'has class sl-chart'
    );

    assert.ok(
      this.$( '>:first-child' ).hasClass( 'panel' ),
      'has class panel'
    );

    assert.ok(
      this.$( '>:first-child' ).hasClass( 'panel-default' ),
      'has class panel-default'
    );

    assert.ok(
      this.$( '>:first-child' ).hasClass( 'sl-panel' ),
      'has class sl-panel'
    );
});

test( 'Loading state adds loading class', function( assert ) {
    this.set( 'testseries', [] );
    this.set( 'testoptions', {} );

    this.render( hbs`
        {{#sl-chart series=testseries isLoading=false options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'sl-loading' ),
        false,
        'Default rendered component does not have "sl-loading" class'
    );

    this.render( hbs`
        {{#sl-chart series=testseries isLoading=true options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).hasClass( 'sl-loading' ),
        true,
        'Default rendered component does have "sl-loading" class'
    );
});

test( 'Title property is set', function( assert ) {
    this.set( 'testseries', [] );
    this.set( 'testoptions', {} );

    this.render( hbs`
        {{#sl-chart series=testseries options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).find( '.panel-heading' ).html(),
        undefined,
        'No chart title is rendered when title is not set'
    );

    this.render( hbs`
        {{#sl-chart title='Peak serve hours' series=testseries options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.equal(
        this.$( '>:first-child' ).find( '.panel-heading' ).html(),
        'Peak serve hours',
        'Chart title is created with title value'
    );
});

test( 'Chart div uses the correct style', function( assert ) {
    this.set( 'testseries', [] );
    this.set( 'testoptions', {} );

    this.render( hbs`
        {{#sl-chart series=testseries options=testoptions}}
        {{/sl-chart}}
    ` );

    assert.equal(
        this.$( '>:first-child' ).find( 'div.chart' ).attr( 'style' ),
        'height: auto; width: auto;',
        'Chart div has automatic height and width'
    );

    this.render( hbs`
        {{#sl-chart series=testseries options=testoptions height=10 width=20}}
        {{/sl-chart}}
    ` );

    assert.equal(
        this.$( '>:first-child' ).find( 'div.chart' ).attr( 'style' ),
        'height: 10; width: 20;',
        'Chart div has height 10 and width 20'
    );
});<|endoftext|>


<commit_before>var should = require('should');
var util = require('should/lib/util');

/**
 * Assert given object is a Promise
 *
 * @name Promise
 * @memberOf Assertion
 * @category assertion promises
 * @module should-promised
 * @example
 *
 * promise.should.be.Promise;
 * (new Promise(function(resolve, reject) { resolve(10); })).should.be.a.Promise;
 * (10).should.not.be.a.Promise;
 */
should.Assertion.add('Promise', function() {
  this.params = {operator: 'to be promise'};

  var obj = this.obj;

  this.have.property('then')
    .which.is.a.Function
    .and.have.property('length')
    .which.is.above(1);

  this.obj = obj;
}, true);

/**
 * Assert given promise will be fulfilled
 *
 * @name fulfilled
 * @memberOf Assertion
 * @category assertion promises
 * @module should-promised
 * @returns {Promise}
 * @example
 * (new Promise(function(resolve, reject) { resolve(10); })).should.be.fulfilled;
 */
Object.defineProperty(should.Assertion.prototype, 'fulfilled', {
  get: function Assertion$fulfilled() {
    this.params = {operator: 'to be fulfilled'};

    this.obj.should.be.a.Promise;

    var that = this;
    return this.obj.then(function(value) {
      if(that.negate) {
        that.fail();
      }
      return value;
    }, function next$onError(err) {
      if(!that.negate) {
        that.fail();
      }
      return err;
    })
  }
});

/**
 * Assert given promise will be rejected
 *
 * @name rejected
 * @memberOf Assertion
 * @category assertion promises
 * @module should-promised
 * @returns {Promise}
 * @example
 * (new Promise(function(resolve, reject) { resolve(10); })).should.not.be.rejected;
 */
Object.defineProperty(should.Assertion.prototype, 'rejected', {
  get: function() {
    this.params = { operator: 'to be rejected'};

    this.obj.should.be.a.Promise;

    var that = this;
    return this.obj.then(function(value) {
      if(!that.negate) {
        that.fail();
      }
      return value;
    }, function next$onError(err) {
      if(that.negate) {
        that.fail();
      }
      return err;
    })
  }
});

/**
 * Assert given promise will be rejected with some sort of error. Arguments is the same for Assertion#throw
 *
 * @name rejectedWith
 * @memberOf Assertion
 * @category assertion promises
 * @module should-promised
 * @returns {Promise}
 * @example
 *
 * function failedPromise() {
 *   return new Promise(function(resolve, reject) {
 *     reject(new Error('boom'));
 *   })
 * }
 * failedPromise().should.be.rejectedWith(Error);
 * failedPromise().should.be.rejectedWith('boom');
 * failedPromise().should.be.rejectedWith(/boom/);
 * failedPromise().should.be.rejectedWith(Error, { message: 'boom' });
 * failedPromise().should.be.rejectedWith({ message: 'boom' });
 */
should.Assertion.prototype.rejectedWith = function(message, properties) {
  this.params = {operator: 'to be rejected'};

  this.obj.should.be.a.Promise;

  var that = this;
  return this.obj.then(function(value) {
    if(!that.negate) {
      that.fail();
    }
    return value;
  }, function next$onError(err) {
    if(that.negate) {
      that.fail();
    }

    var errorMatched = true, errorInfo = '';

    if('string' == typeof message) {
      errorMatched = message == err.message;
    } else if(message instanceof RegExp) {
      errorMatched = message.test(err.message);
    } else if('function' == typeof message) {
      errorMatched = err instanceof message;
    } else if(message != null && typeof message == 'object') {
      try {
        err.should.match(message);
      } catch(e) {
        if(e instanceof should.AssertionError) {
          errorInfo = ": " + e.message;
          errorMatched = false;
        } else {
          throw e;
        }
      }
    }

    if(!errorMatched) {
      if('string' == typeof message || message instanceof RegExp) {
        errorInfo = " with a message matching " + should.format(message) + ", but got '" + err.message + "'";
      } else if('function' == typeof message) {
        errorInfo = " of type " + util.functionName(message) + ", but got " + util.functionName(err.constructor);
      }
    } else if('function' == typeof message && properties) {
      try {
        err.should.match(properties);
      } catch(e) {
        if(e instanceof should.AssertionError) {
          errorInfo = ": " + e.message;
          errorMatched = false;
        } else {
          throw e;
        }
      }
    }

    that.params.operator += errorInfo;

    that.assert(errorMatched);

    return err;
  })
};

/**
 * Assert given object is promise and wrap it in PromisedAssertion, which has all properties of should.Assertion. That means you can chain as with usual Assertion.
 *
 * @name finally
 * @memberOf Assertion
 * @alias Assertion#eventually
 * @category assertion promises
 * @module should-promised
 * @returns {PromisedAssertion} Like should.Assertion, but .then this.obj in Assertion
 * @example
 *
 * (new Promise(function(resolve, reject) { resolve(10); })).should.be.eventually.equal(10);
 */
Object.defineProperty(should.Assertion.prototype, 'finally', {
  get: function() {
    this.obj.should.be.a.Promise;

    var that = this;

    return new PromisedAssertion(this.obj.then(function(obj) {
      var a = should(obj);

      a.negate = that.negate;
      a.anyOne = that.anyOne;

      return a;
    }));
  }
});

should.Assertion.alias('finally', 'eventually');

function PromisedAssertion(obj) {
  should.Assertion.apply(this, arguments);
}

function constructValueCall(name) {
  return function() {
    var args = arguments;
    this.obj = this.obj.then(function(a) {
      return a[name].apply(a, args);
    });

    return this;
  }
}

function constructGetCall(name) {
  return function() {
    this.obj = this.obj.then(function(a) {
      return a[name];
    });

    return this;
  }
}

for(var name in should.Assertion.prototype) {

  var desc = Object.getOwnPropertyDescriptor(should.Assertion.prototype, name);

  if(desc.get) {
    desc.get = constructGetCall(name);
  } else {
    desc.value = constructValueCall(name);
  }

  Object.defineProperty(PromisedAssertion.prototype, name, desc);
}

// delegate some methods of promises to internal promise
/**
 * Make PromisedAssertion to look like promise. Delegate resolve and reject to given promise.
 *
 * @name then
 * @memberOf PromisedAssertion
 * @category assertion promises
 * @module should-promised
 * @returns {Promise}
 */
PromisedAssertion.prototype.then = function(resolve, reject) {
  return this.obj.then(resolve, reject);
};<commit_msg>In Promise do not use current context<commit_after>var should = require('should');
var util = require('should/lib/util');

/**
 * Assert given object is a Promise
 *
 * @name Promise
 * @memberOf Assertion
 * @category assertion promises
 * @module should-promised
 * @example
 *
 * promise.should.be.Promise;
 * (new Promise(function(resolve, reject) { resolve(10); })).should.be.a.Promise;
 * (10).should.not.be.a.Promise;
 */
should.Assertion.add('Promise', function() {
  this.params = {operator: 'to be promise'};

  var obj = this.obj;

  obj.should.have.property('then')
    .which.is.a.Function
    .and.have.property('length')
    .which.is.above(1);
}, true);

/**
 * Assert given promise will be fulfilled
 *
 * @name fulfilled
 * @memberOf Assertion
 * @category assertion promises
 * @module should-promised
 * @returns {Promise}
 * @example
 * (new Promise(function(resolve, reject) { resolve(10); })).should.be.fulfilled;
 */
Object.defineProperty(should.Assertion.prototype, 'fulfilled', {
  get: function Assertion$fulfilled() {
    this.params = {operator: 'to be fulfilled'};

    this.obj.should.be.a.Promise;

    var that = this;
    return this.obj.then(function(value) {
      if(that.negate) {
        that.fail();
      }
      return value;
    }, function next$onError(err) {
      if(!that.negate) {
        that.fail();
      }
      return err;
    })
  }
});

/**
 * Assert given promise will be rejected
 *
 * @name rejected
 * @memberOf Assertion
 * @category assertion promises
 * @module should-promised
 * @returns {Promise}
 * @example
 * (new Promise(function(resolve, reject) { resolve(10); })).should.not.be.rejected;
 */
Object.defineProperty(should.Assertion.prototype, 'rejected', {
  get: function() {
    this.params = { operator: 'to be rejected'};

    this.obj.should.be.a.Promise;

    var that = this;
    return this.obj.then(function(value) {
      if(!that.negate) {
        that.fail();
      }
      return value;
    }, function next$onError(err) {
      if(that.negate) {
        that.fail();
      }
      return err;
    })
  }
});

/**
 * Assert given promise will be rejected with some sort of error. Arguments is the same for Assertion#throw
 *
 * @name rejectedWith
 * @memberOf Assertion
 * @category assertion promises
 * @module should-promised
 * @returns {Promise}
 * @example
 *
 * function failedPromise() {
 *   return new Promise(function(resolve, reject) {
 *     reject(new Error('boom'));
 *   })
 * }
 * failedPromise().should.be.rejectedWith(Error);
 * failedPromise().should.be.rejectedWith('boom');
 * failedPromise().should.be.rejectedWith(/boom/);
 * failedPromise().should.be.rejectedWith(Error, { message: 'boom' });
 * failedPromise().should.be.rejectedWith({ message: 'boom' });
 */
should.Assertion.prototype.rejectedWith = function(message, properties) {
  this.params = {operator: 'to be rejected'};

  this.obj.should.be.a.Promise;

  var that = this;
  return this.obj.then(function(value) {
    if(!that.negate) {
      that.fail();
    }
    return value;
  }, function next$onError(err) {
    if(that.negate) {
      that.fail();
    }

    var errorMatched = true, errorInfo = '';

    if('string' == typeof message) {
      errorMatched = message == err.message;
    } else if(message instanceof RegExp) {
      errorMatched = message.test(err.message);
    } else if('function' == typeof message) {
      errorMatched = err instanceof message;
    } else if(message != null && typeof message == 'object') {
      try {
        err.should.match(message);
      } catch(e) {
        if(e instanceof should.AssertionError) {
          errorInfo = ": " + e.message;
          errorMatched = false;
        } else {
          throw e;
        }
      }
    }

    if(!errorMatched) {
      if('string' == typeof message || message instanceof RegExp) {
        errorInfo = " with a message matching " + should.format(message) + ", but got '" + err.message + "'";
      } else if('function' == typeof message) {
        errorInfo = " of type " + util.functionName(message) + ", but got " + util.functionName(err.constructor);
      }
    } else if('function' == typeof message && properties) {
      try {
        err.should.match(properties);
      } catch(e) {
        if(e instanceof should.AssertionError) {
          errorInfo = ": " + e.message;
          errorMatched = false;
        } else {
          throw e;
        }
      }
    }

    that.params.operator += errorInfo;

    that.assert(errorMatched);

    return err;
  })
};

/**
 * Assert given object is promise and wrap it in PromisedAssertion, which has all properties of should.Assertion. That means you can chain as with usual Assertion.
 *
 * @name finally
 * @memberOf Assertion
 * @alias Assertion#eventually
 * @category assertion promises
 * @module should-promised
 * @returns {PromisedAssertion} Like should.Assertion, but .then this.obj in Assertion
 * @example
 *
 * (new Promise(function(resolve, reject) { resolve(10); })).should.be.eventually.equal(10);
 */
Object.defineProperty(should.Assertion.prototype, 'finally', {
  get: function() {
    this.obj.should.be.a.Promise;

    var that = this;

    return new PromisedAssertion(this.obj.then(function(obj) {
      var a = should(obj);

      a.negate = that.negate;
      a.anyOne = that.anyOne;

      return a;
    }));
  }
});

should.Assertion.alias('finally', 'eventually');

function PromisedAssertion(obj) {
  should.Assertion.apply(this, arguments);
}

function constructValueCall(name) {
  return function() {
    var args = arguments;
    this.obj = this.obj.then(function(a) {
      return a[name].apply(a, args);
    });

    return this;
  }
}

function constructGetCall(name) {
  return function() {
    this.obj = this.obj.then(function(a) {
      return a[name];
    });

    return this;
  }
}

for(var name in should.Assertion.prototype) {

  var desc = Object.getOwnPropertyDescriptor(should.Assertion.prototype, name);

  if(desc.get) {
    desc.get = constructGetCall(name);
  } else {
    desc.value = constructValueCall(name);
  }

  Object.defineProperty(PromisedAssertion.prototype, name, desc);
}

// delegate some methods of promises to internal promise
/**
 * Make PromisedAssertion to look like promise. Delegate resolve and reject to given promise.
 *
 * @name then
 * @memberOf PromisedAssertion
 * @category assertion promises
 * @module should-promised
 * @returns {Promise}
 */
PromisedAssertion.prototype.then = function(resolve, reject) {
  return this.obj.then(resolve, reject);
};<|endoftext|>


<commit_before>(function() {
  var util = require('util');
  var msgpack = require('msgpack-js');
  var uuid = require('uuid');
  var PROTOCOL_VERSION = 'ZSS:0.0';

  var Message = function(sid, sversion, verb, payload, headers, status){
    var self = this;

    self.identity = "id#" + uuid.v1();
    self.protocol = PROTOCOL_VERSION;
    self.type = "REQ";
    self.rid = uuid.v1();
    self.address = {
      sid: sid,
      sversion: sversion,
      verb: verb
    };
    self.headers = headers;
    self.status = status;
    self.payload = payload;

    self.toString = function(){
      var message = "********\nFRAME 0: %s\nFRAME 1: %s\nFRAME 2: %s\nFRAME 3: %s\nFRAME 4: %j\nFRAME 5: %j\nFRAME 6: %s\nFRAME 7: %j\n********";
      return util.format(message, self.identity, self.protocol, self.type, self.rid, self.address, self.headers, self.status, self.payload);
    };

    self.toFrames = function(){
      return Message.toFrames(self);
    };
  };

  Message.Type = {
    REQ: "REQ",
    REP: "REP"
  };

  Message.parse = function(frames){
    var msg = new Message();
    msg.identity = frames[0];
    msg.protocol = frames[1];
    msg.type = frames[2];
    msg.rid = frames[3];
    msg.address = msgpack.decode(frames[4]);
    msg.headers = msgpack.decode(frames[5]);
    msg.status = frames[6];
    msg.payload = msgpack.decode(frames[7]);
    return msg;
  };

  Message.toFrames = function(msg){
    var frames = [
      msg.identity,
      msg.protocol,
      msg.type,
      msg.rid,
      msgpack.encode(msg.address),
      msgpack.encode(msg.headers),
      msg.status,
      msgpack.encode(msg.payload)
    ];
    return frames;
  };

  module.exports = Message;
}());
<commit_msg>use message enumerator instead of harcoded string<commit_after>(function() {
  var util = require('util');
  var msgpack = require('msgpack-js');
  var uuid = require('uuid');
  var PROTOCOL_VERSION = 'ZSS:0.0';

  var Message = function(sid, sversion, verb, payload, headers, status){
    var self = this;

    self.identity = "id#" + uuid.v1();
    self.protocol = PROTOCOL_VERSION;
    self.type = Message.Type.REQ;
    self.rid = uuid.v1();
    self.address = {
      sid: sid,
      sversion: sversion,
      verb: verb
    };
    self.headers = headers;
    self.status = status;
    self.payload = payload;

    self.toString = function(){
      var message = "********\nFRAME 0: %s\nFRAME 1: %s\nFRAME 2: %s\nFRAME 3: %s\nFRAME 4: %j\nFRAME 5: %j\nFRAME 6: %s\nFRAME 7: %j\n********";
      return util.format(message, self.identity, self.protocol, self.type, self.rid, self.address, self.headers, self.status, self.payload);
    };

    self.toFrames = function(){
      return Message.toFrames(self);
    };
  };

  Message.Type = {
    REQ: "REQ",
    REP: "REP"
  };

  Message.parse = function(frames){
    var msg = new Message();
    msg.identity = frames[0];
    msg.protocol = frames[1];
    msg.type = frames[2];
    msg.rid = frames[3];
    msg.address = msgpack.decode(frames[4]);
    msg.headers = msgpack.decode(frames[5]);
    msg.status = frames[6];
    msg.payload = msgpack.decode(frames[7]);
    return msg;
  };

  Message.toFrames = function(msg){
    var frames = [
      msg.identity,
      msg.protocol,
      msg.type,
      msg.rid,
      msgpack.encode(msg.address),
      msgpack.encode(msg.headers),
      msg.status,
      msgpack.encode(msg.payload)
    ];
    return frames;
  };

  module.exports = Message;
}());
<|endoftext|>


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

};
<commit_msg>Step 4 - Extend our api using remote methods<commit_after>module.exports = function(CoffeeShop) {
  CoffeeShop.status = function(cb) {
    var currentDate = new Date();
    var currentHour = currentDate.getHours();
    var OPEN_HOUR = 6;
    var CLOSE_HOUR = 20;
    console.log('Current hour is ' + currentHour);
    var response;
    if (currentHour > OPEN_HOUR && currentHour < CLOSE_HOUR) {
      response = 'We are open for business.';
    } else {
      response = 'Sorry, we are closed. Open daily from 6am to 8pm.';
    }
    cb(null, response);
  };

  CoffeeShop.getName = function(shopId, cb) {
    CoffeeShop.findById( shopId, function (err, instance) {
      response = "Name of coffee shop is " + instance.name;
      cb(null, response);
      console.log(response);
    });
  }

  CoffeeShop.remoteMethod(
    'status',
    {
      http: {path: '/status', verb: 'get'},
      returns: {arg: 'status', type: 'string'}
    }
  );

  CoffeeShop.remoteMethod (
    'getName',
    {
      http: {path: '/getname', verb: 'get'},
      accepts: {arg: 'id', type: 'number', http: { source: 'query' } },
      returns: {arg: 'name', type: 'string'}
    }
  );
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2012 by Animatron.
 * All rights are reserved.
 *
 * Animatron player is licensed under the MIT License, see LICENSE.
 */

describe("structure", function() {

    it("should not allow to add the same element to a scene, but allow to add its clone", function() {
        var scene = new anm.Scene();
        var root1 = new anm.Element();
        var root2 = new anm.Element();
        var inner = new anm.Element();
        var test_elm = new anm.Element();
        var test_child = new anm.Element();
        test_elm.add(test_child);
        test_elm.setBand([2, 17]);
        root1.add(test_elm);
        root2.add(inner);
        inner.add(test_elm);
        scene.add(root1);

        try {
            scene.add(root2);
            this.fail('No exception was thrown');
        } catch(e) {
            expect(e.message).toBe(anm.Errors.S.ELEMENT_IS_REGISTERED); // TODO: include element name in error
        };

        try {
            inner.add(test_elm.clone());
            // should throw an exception because its child is already registered in scene
            this.fail('No exception was thrown');
        } catch(e) {
            expect(e.message).toBe(anm.Errors.S.ELEMENT_IS_REGISTERED); // TODO: include element name in error
        };

        try {
            inner.add(test_elm.clone());
            // should throw an exception because its child is already registered in scene
            this.fail('No exception was thrown');
        } catch(e) {
            expect(e.message).toBe(anm.Errors.S.ELEMENT_IS_REGISTERED); // TODO: include element name in error
        };

        test_elm.remove(test_child);
        try {
            inner.add(test_elm.clone());
        } catch(e) {
            this.fail('Should not throw any exception');
        }

    });

    it("should throw an exception when trying to remove the element that wasn't added to the scene", function() {
        var scene = new anm.Scene();
        var subj = new anm.Element();
        var some = new anm.Element();

        scene.add(some);

        try {
            scene.remove(subj);
            this.fail('No exception was thrown');
        } catch(e) {
            expect(e.message).toBe(anm.Errors.S.ELEMENT_IS_NOT_REGISTERED); // TODO: include element name in error
        }
    });

});<commit_msg>fix animation tests<commit_after>/*
 * Copyright (c) 2011-2012 by Animatron.
 * All rights are reserved.
 *
 * Animatron player is licensed under the MIT License, see LICENSE.
 */

describe("structure", function() {

    it("should not allow to add the same element to a scene, but allow to add its clone", function() {
        var scene = new anm.Scene();
        var root1 = new anm.Element();
        var root2 = new anm.Element();
        var inner = new anm.Element();
        var test_elm = new anm.Element();
        var test_child = new anm.Element();
        test_elm.add(test_child);
        test_elm.setBand([2, 17]);
        root1.add(test_elm);
        root2.add(inner);
        inner.add(test_elm);
        scene.add(root1);

        try {
            scene.add(root2);
            this.fail('No exception was thrown');
        } catch(e) {
            expect(e.message).toBe(anm.Errors.A.ELEMENT_IS_REGISTERED); // TODO: include element name in error
        };

        try {
            inner.add(test_elm.clone());
            // should throw an exception because its child is already registered in scene
            this.fail('No exception was thrown');
        } catch(e) {
            expect(e.message).toBe(anm.Errors.A.ELEMENT_IS_REGISTERED); // TODO: include element name in error
        };

        try {
            inner.add(test_elm.clone());
            // should throw an exception because its child is already registered in scene
            this.fail('No exception was thrown');
        } catch(e) {
            expect(e.message).toBe(anm.Errors.A.ELEMENT_IS_REGISTERED); // TODO: include element name in error
        };

        test_elm.remove(test_child);
        try {
            inner.add(test_elm.clone());
        } catch(e) {
            this.fail('Should not throw any exception');
        }

    });

    it("should throw an exception when trying to remove the element that wasn't added to the scene", function() {
        var scene = new anm.Scene();
        var subj = new anm.Element();
        var some = new anm.Element();

        scene.add(some);

        try {
            scene.remove(subj);
            this.fail('No exception was thrown');
        } catch(e) {
            expect(e.message).toBe(anm.Errors.A.ELEMENT_IS_NOT_REGISTERED); // TODO: include element name in error
        }
    });

});<|endoftext|>


<commit_before>/**
 * Base class for Client and Server classes. Contains basic methods like
 * request(), response(), onMessage(), onClose(),... Client and Server should
 * override them to have their basic logic.
 *
 * @author flatline
 */
const Observer = require('./../global/Observer');
//
// Basic events
//
const REQUEST  = 0;
const RESPONSE = 1;
const MSG      = 2;
const ERR      = 3;
const CLOSE    = 4;
const DESTROY  = 5;

const EVENTS   = {
    REQUEST,
    RESPONSE,
    MSG,
    ERR,
    CLOSE,
    DESTROY
};

class Connection extends Observer {
    constructor(eventAmount) {
        super(eventAmount);
        /**
         * {String} Reason why connection was closed. See onClose()
         * method for details.
         */
        this._closeReason = '';
        /**
         * {Boolean} Means that current client is connected to the server.
         * true - connected, false - disconnected.
         */
        this._active      = false;
    }

    get closeReason() {return this._closeReason}
    get active()      {return this._active}

    /**
     * Sends data to the client. First two parameters are required. All
     * other parameters depend of special request and will be send to
     * the client as an array.
     * @param {WebSocket} sock
     * @param {Number} type Request type (see Requests.TYPES)
     * @param {*} params Array of parameters
     * @return {Number} Unique request id
     * @abstract
     */
    request(sock, type, ...params) {this.fire(REQUEST, sock, type, ...params)}

    /**
     * Is user for answering on requests. May not be called if response
     * (response) don't needed.
     * @param {WebSocket} sock Socket where send the response
     * @param {Number} type Request type (see Requests.TYPES)
     * @param {Number} reqId Unique request id, returned by send() method
     * @param {Array} params Custom parameters to send
     * @abstract
     */
    response(sock, type, reqId, ...params) {this.fire(RESPONSE, sock, type, reqId, ...params)}

    /**
     * Is called every time if server/client sends us a request or response (response).
     * @param {WebSocket} sock Socket, received the message
     * @param {Event} event Message event. Data is in 'data' property
     * @abstract
     */
    onMessage(sock, event) {
        this.fire(MSG, sock, event);
    }

    /**
     * Is called on every error during web sockets work
     * @param {Event} event Error event
     * @abstract
     */
    onError(event) {
        this.fire(ERR, event);
    }

    /**
     * Connection has closed
     * @param {Event} event
     */
    onClose(event) {
        let reason = 'Unknown error';
        switch(event.code) {
            case 1000: reason = 'Normal closure';
                break;
            case 1001: reason = 'An endpoint is going away';
                break;
            case 1002: reason = 'An endpoint is terminating the connection due to a protocol error.';
                break;
            case 1003: reason = 'An endpoint is terminating the connection because it has received a type of data it cannot accept';
                break;
            case 1004: reason = 'Reserved. The specific meaning might be defined in the future.';
                break;
            case 1005: reason = 'No status code was actually present';
                break;
            case 1006: reason = 'The connection was closed abnormally';
                break;
            case 1007: reason = 'The endpoint is terminating the connection because a message was received that contained inconsistent data';
                break;
            case 1008: reason = 'The endpoint is terminating the connection because it received a message that violates its policy';
                break;
            case 1009: reason = 'The endpoint is terminating the connection because a data frame was received that is too large';
                break;
            case 1010: reason = 'The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn\'t.';
                break;
            case 1011: reason = 'The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.';
                break;
            case 1012: reason = 'The server is terminating the connection because it is restarting';
                break;
            case 1013: reason = 'The server is terminating the connection due to a temporary condition';
                break;
            case 1015: reason = 'The connection was closed due to a failure to perform a TLS handshake';
                break;
        }

        this._closeReason = reason;
        this.fire(CLOSE, event);
    }

    /**
     * Means that current Client or Server is active. Active means, that
     * it's ready to connect to server/Client. Should be called from parent
     * class (Client/Server)
     * @param {Boolean} active
     */
    onActive(active = true) {
        this._active = active;
    }

    /**
     * @destructor
     * @abstract
     */
    destroy() {
        this.fire(DESTROY);
        this._active = false;
    }
}

module.exports = {Connection, EVENTS};<commit_msg>added small comment. sync commit<commit_after>/**
 * Base class for Client and Server classes. Contains basic methods like
 * request(), response(), onMessage(), onClose(),... Client and Server should
 * override them to have their basic logic.
 *
 * @author flatline
 */
const Observer = require('./../global/Observer');
//
// Basic events
//
const REQUEST  = 0;
const RESPONSE = 1;
const MSG      = 2;
const ERR      = 3;
const CLOSE    = 4;
const DESTROY  = 5;

const EVENTS   = {
    REQUEST,
    RESPONSE,
    MSG,
    ERR,
    CLOSE,
    DESTROY
};

class Connection extends Observer {
    constructor(eventAmount) {
        super(eventAmount);
        /**
         * {String} Reason why connection was closed. See onClose()
         * method for details.
         */
        this._closeReason = '';
        /**
         * {Boolean} Means activeness of current Client/Server. Meaning of this
         * field may differ between children classes. For server it's running or
         * not. For client it's connected or not.
         */
        this._active      = false;
    }

    get closeReason() {return this._closeReason}
    get active()      {return this._active}

    /**
     * Sends data to the client. First two parameters are required. All
     * other parameters depend of special request and will be send to
     * the client as an array.
     * @param {WebSocket} sock
     * @param {Number} type Request type (see Requests.TYPES)
     * @param {*} params Array of parameters
     * @return {Number} Unique request id
     * @abstract
     */
    request(sock, type, ...params) {this.fire(REQUEST, sock, type, ...params)}

    /**
     * Is user for answering on requests. May not be called if response
     * (response) don't needed.
     * @param {WebSocket} sock Socket where send the response
     * @param {Number} type Request type (see Requests.TYPES)
     * @param {Number} reqId Unique request id, returned by send() method
     * @param {Array} params Custom parameters to send
     * @abstract
     */
    response(sock, type, reqId, ...params) {this.fire(RESPONSE, sock, type, reqId, ...params)}

    /**
     * Is called every time if server/client sends us a request or response (response).
     * @param {WebSocket} sock Socket, received the message
     * @param {Event} event Message event. Data is in 'data' property
     * @abstract
     */
    onMessage(sock, event) {
        this.fire(MSG, sock, event);
    }

    /**
     * Is called on every error during web sockets work
     * @param {Event} event Error event
     * @abstract
     */
    onError(event) {
        this.fire(ERR, event);
    }

    /**
     * Connection has closed
     * @param {Event} event
     */
    onClose(event) {
        let reason = 'Unknown error';
        switch(event.code) {
            case 1000: reason = 'Normal closure';
                break;
            case 1001: reason = 'An endpoint is going away';
                break;
            case 1002: reason = 'An endpoint is terminating the connection due to a protocol error.';
                break;
            case 1003: reason = 'An endpoint is terminating the connection because it has received a type of data it cannot accept';
                break;
            case 1004: reason = 'Reserved. The specific meaning might be defined in the future.';
                break;
            case 1005: reason = 'No status code was actually present';
                break;
            case 1006: reason = 'The connection was closed abnormally';
                break;
            case 1007: reason = 'The endpoint is terminating the connection because a message was received that contained inconsistent data';
                break;
            case 1008: reason = 'The endpoint is terminating the connection because it received a message that violates its policy';
                break;
            case 1009: reason = 'The endpoint is terminating the connection because a data frame was received that is too large';
                break;
            case 1010: reason = 'The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn\'t.';
                break;
            case 1011: reason = 'The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.';
                break;
            case 1012: reason = 'The server is terminating the connection because it is restarting';
                break;
            case 1013: reason = 'The server is terminating the connection due to a temporary condition';
                break;
            case 1015: reason = 'The connection was closed due to a failure to perform a TLS handshake';
                break;
        }

        this._closeReason = reason;
        this.fire(CLOSE, event);
    }

    /**
     * Means that current Client or Server is active. Active means, that
     * it's ready to connect to server/Client. Should be called from parent
     * class (Client/Server)
     * @param {Boolean} active
     */
    onActive(active = true) {
        this._active = active;
    }

    /**
     * @destructor
     * @abstract
     */
    destroy() {
        this.fire(DESTROY);
        this._active = false;
    }
}

module.exports = {Connection, EVENTS};<|endoftext|>


<commit_before>const jdb = require('node-json-db');
const db = new jdb("otc", true, true);
var orderid=0;
var sort_by = function(field, reverse, primer){

   var key = primer ?
       function(x) {return primer(x[field])} :
       function(x) {return x[field]};

   reverse = !reverse ? 1 : -1;

   return function (a, b) {
       return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
     }
}

module.exports = {
	cleanup:function(message) {
		try {
			var wtb = db.getData("/wtb");
			var wtb_arr = [];

			wtb.forEach(function(arr) {

				message.guild.fetchMember(arr['userid']).then(function(m) {
					console.log("User "+arr["username"]+" and ID "+arr["userid"]+" exists. Keeping order #"+arr["orderid"]);
					// 	wtb_arr.push(arr);
				}).catch((reason) => {
					console.log("No user here with "+arr["username"]+" and ID "+arr["userid"]+". Removing order #"+arr["orderid"]);
				});

			});
			// db.push("/wtb", wtb_arr);
		} catch(e) {

		};

		try {
			var wts = db.getData("/wts");
			var wts_arr = [];

			wts.forEach(function(arr) {

				message.guild.fetchMember(arr['userid']).then(function(m) {
					console.log("User "+arr["username"]+" and ID "+arr["userid"]+" exists. Keeping order #"+arr["orderid"]);
					// 	wts_arr.push(arr);
				}).catch((reason) => {
					console.log("No user here with "+arr["username"]+" and ID "+arr["userid"]+". Removing order #"+arr["orderid"]);
				});

			});
			// db.push("/wts", wts_arr);
		} catch(e) {

		};
	},
	wts:function(message, command) {
		var btc = command[1];
		var qrl = command[2];

		// Check if there's characters...
		if(!btc || !qrl) {
			message.channel.send("otc wts [btc/qrl] [qrl]")
			return;
		}
	    if(!/^[0-9\.]+$/.test(btc) || !/^[0-9\.]+$/.test(qrl)) {
	        message.channel.send("That's not a number I understand");
	        return;
	    }
		btc = parseFloat(btc);
		qrl = parseFloat(qrl);

		if(btc>1 || btc <= 0.000000001) {
			message.channel.send("BTC price per QRL is either too high or too low. Range 0.00000001 - 1");
			return;
		}
		if(qrl<=1) {
			message.channel.send("Can't sell less than 1 QRL at a time");
			return;
		}
		var total = btc*qrl;

		// Check if WTB is lower than WTS
		try {
			var wtb = db.getData("/wtb");
			var wtb_sorted = wtb.sort(sort_by('btc',true, parseFloat));

			if(wtb_sorted[0]['btc'] > btc - 0.00000001) {
				message.channel.send("Sorry, the WTS order must be higher than the *highest* WTB order at this time");
				return;
			}
		} catch(error) {

		};

		message.channel.send("Market WTS order at "+btc+" for "+qrl+" QRL for a total of ("+total+" BTC)");

		// Get orderid
		db.push('/orderid[]',{});
		orderid=db.getData("/orderid").length;

		db.push("/wts[]", {
			"orderid":orderid,
			"btc":btc,
			"qrl":qrl,
			"username":message.author.username,
			"userid":message.author.id
		}, true);

		this.market(message);
	},
	wtb:function(message, command) {
		var btc = command[1];
		var qrl = command[2];

		if(!btc || !qrl) {
			message.channel.send("otc wtb [btc/qrl] [qrl]")
			return;
		}
	    if(!/^[0-9\.]+$/.test(btc) || !/^[0-9\.]+$/.test(qrl)) {
	        message.channel.send("That's not a number I understand");
	        return;
	    }

		btc = parseFloat(btc);
		qrl = parseFloat(qrl);

		// check if there's characters...
		if(btc>1 || btc <= 0.000000001) {
			message.channel.send("BTC price per QRL is either too high or too low. Range 0.00000001 - 1");
			return;
		}
		if(qrl<=1) {
			message.channel.send("Can't buy less than 1 QRL at a time");
			return;
		}
		var total = btc*qrl;

		// Check if WTB is lower than WTS
		try {
			var wts = db.getData("/wts");
			var wts_sorted = wts.sort(sort_by('btc',false, parseFloat));

			if(parseFloat(wtb_sorted[0]['btc']) > parseFloat(btc - 0.00000001)) {
				message.channel.send("Sorry, the WTB order must be lower than the *lowest* WTS order at this time");
				return;
			}
		} catch(error) {

		};

		message.channel.send("Market WTB order at "+btc+" for "+qrl+" QRL for a total of ("+total+" BTC)");

			// Get orderid
		db.push('/orderid[]',{});
		orderid=db.getData("/orderid").length;

		db.push("/wtb[]", {
			"orderid":orderid,
			"btc":btc,
			"qrl":qrl,
			"username":message.author.username,
			"userid":message.author.id
		}, true);

		this.market(message);
	},
	clear:function(message, command) {

		try {
			var wtb = db.getData("/wtb");
			var wtb_arr = [];

			wtb.forEach(function(arr) {
				var orderid = parseInt(arr['orderid']);

				if(command[1]==orderid || command[1]==arr['btc']) {
					if(message.author.id==arr['userid']) {
						return;
					} else {
						message.channel.send("Please sir, deleting another person's order isn't nice.");
					}
				}

				wtb_arr.push(arr);
			});
			db.push("/wtb", wtb_arr);
		} catch(error) {

		}

		try {
			var wts = db.getData("/wts");
			var wts_arr = [];

			wts.forEach(function(arr) {
				var orderid = parseInt(arr['orderid']);

				if(command[1]==orderid || command[1]==arr['btc']) {
					if(message.author.id==arr['userid']) {
						return;
					} else {
						message.channel.send("Please sir, deleting another person's order isn't nice.");
					}
				}

				wts_arr.push(arr);
			});
			db.push("/wts", wts_arr);
		} catch(error) {

		}

		this.market(message,command);

	},
	clearall:function(message,command) {
		if(message.author.id == '356943957588049920') {
			db.delete("/");
			message.channel.send("Market deleted");
		} else {
			message.channel.send("Market not deleted");
		}

	},
	market:function(message, command) {
		var output = "";
		var total = 0;

		try {
			var wts = db.getData("/wts");
			var wts_sorted = wts.sort(sort_by('btc',true, parseFloat));

			if(wts.length>0) {

				output += "Market WTS (want to sell)```";
				wts_sorted.forEach(function(arr) {
					qrl = parseFloat(arr['qrl']);
					btc = parseFloat(arr['btc']);
					order = String(arr['orderid']);
					total= btc * qrl;
					output += order.padStart(3," ")+" ";
					output += btc.toFixed(8)+' btc/qrl';
					output += String(arr.qrl).padStart(6," ")+" qrl ";
					output += String(total.toFixed(8)).padStart(12," ")+" BTC "+arr.username+"\n";
				});
				output += "```";
			}
		} catch(error) {

		}

		try {
			var wtb = db.getData("/wtb");
			var wtb_sorted = wtb.sort(sort_by('btc',true, parseFloat));

			if(wtb.length>0) {
				output += "Market WTB (want to buy)```";
				wtb_sorted.forEach(function(arr) {
					qrl = parseFloat(arr.qrl);
					btc = parseFloat(arr.btc);
					order = String(arr.orderid);
					total= btc * qrl;
					output += order.padStart(3," ")+" ";
					output += btc.toFixed(8)+' btc/qrl';
					output += String(arr.qrl).padStart(6," ")+" qrl ";
					output += String(total.toFixed(8)).padStart(12," ")+" BTC "+arr.username+"\n";
				});
				output += "```";
			}
		} catch(error) {

		}

		if(output=="") {
			output = "No markets available";
		}
		message.channel.send(output);
	},
	escrow: function(message, command) {
		// If no command, print 'help'

		// otc escrow list

		// otc escrow order [btc_full] [qrl_full] [party_btc] [party_qrl]
		// ^ put in new escrow order

		// otc escrow recieved [order_number]
		// otc escrow review [order_number]
		// otc escrow status [order_number]
	},
	otc:async function(message, subcommand, config) {
		this.cleanup(message);
		var	command = subcommand.toLowerCase().split(' ');

		switch(command[0]) {
			case 'wts':
				this.wts(message, command);
			break;
			case 'wtb':
				this.wtb(message, command);
			break;
			case 'market':
				this.market(message, command);
			break;
			case 'clear':
				this.clear(message, command);
			break;
			case 'escrow':
				this.escrow(message, command);
			break;
			case 'clearall':
				this.clearall(message, command);
			break;
			default:
				message.channel.send("**Look at the market**\n`otc market`\n\n**Set a WTS (Want to Sell) order**\n`otc wts [btc/qrl] [qrl]`\n\n**Set a WTB (Want to Buy) order**\n`otc wtb [btc/qrl] [qrl]`\n\n**Remove an order**\n`otc clear [order number]`")

		}

	}
}<commit_msg>Deleting others orders<commit_after>const jdb = require('node-json-db');
const db = new jdb("otc", true, true);
var orderid=0;
var sort_by = function(field, reverse, primer){

   var key = primer ?
       function(x) {return primer(x[field])} :
       function(x) {return x[field]};

   reverse = !reverse ? 1 : -1;

   return function (a, b) {
       return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
     }
}

module.exports = {
	cleanup:function(message) {
		try {
			var wtb = db.getData("/wtb");
			var wtb_arr = [];

			wtb.forEach(function(arr) {

				message.guild.fetchMember(arr['userid']).then(function(m) {
					console.log("User "+arr["username"]+" and ID "+arr["userid"]+" exists. Keeping order #"+arr["orderid"]);
					// 	wtb_arr.push(arr);
				}).catch((reason) => {
					console.log("No user here with "+arr["username"]+" and ID "+arr["userid"]+". Removing order #"+arr["orderid"]);
				});

			});
			// db.push("/wtb", wtb_arr);
		} catch(e) {

		};

		try {
			var wts = db.getData("/wts");
			var wts_arr = [];

			wts.forEach(function(arr) {

				message.guild.fetchMember(arr['userid']).then(function(m) {
					console.log("User "+arr["username"]+" and ID "+arr["userid"]+" exists. Keeping order #"+arr["orderid"]);
					// 	wts_arr.push(arr);
				}).catch((reason) => {
					console.log("No user here with "+arr["username"]+" and ID "+arr["userid"]+". Removing order #"+arr["orderid"]);
				});

			});
			// db.push("/wts", wts_arr);
		} catch(e) {

		};
	},
	wts:function(message, command) {
		var btc = command[1];
		var qrl = command[2];

		// Check if there's characters...
		if(!btc || !qrl) {
			message.channel.send("otc wts [btc/qrl] [qrl]")
			return;
		}
	    if(!/^[0-9\.]+$/.test(btc) || !/^[0-9\.]+$/.test(qrl)) {
	        message.channel.send("That's not a number I understand");
	        return;
	    }
		btc = parseFloat(btc);
		qrl = parseFloat(qrl);

		if(btc>1 || btc <= 0.000000001) {
			message.channel.send("BTC price per QRL is either too high or too low. Range 0.00000001 - 1");
			return;
		}
		if(qrl<=1) {
			message.channel.send("Can't sell less than 1 QRL at a time");
			return;
		}
		var total = btc*qrl;

		// Check if WTB is lower than WTS
		try {
			var wtb = db.getData("/wtb");
			var wtb_sorted = wtb.sort(sort_by('btc',true, parseFloat));

			if(wtb_sorted[0]['btc'] > btc - 0.00000001) {
				message.channel.send("Sorry, the WTS order must be higher than the *highest* WTB order at this time");
				return;
			}
		} catch(error) {

		};

		message.channel.send("Market WTS order at "+btc+" for "+qrl+" QRL for a total of ("+total+" BTC)");

		// Get orderid
		db.push('/orderid[]',{});
		orderid=db.getData("/orderid").length;

		db.push("/wts[]", {
			"orderid":orderid,
			"btc":btc,
			"qrl":qrl,
			"username":message.author.username,
			"userid":message.author.id
		}, true);

		this.market(message);
	},
	wtb:function(message, command) {
		var btc = command[1];
		var qrl = command[2];

		if(!btc || !qrl) {
			message.channel.send("otc wtb [btc/qrl] [qrl]")
			return;
		}
	    if(!/^[0-9\.]+$/.test(btc) || !/^[0-9\.]+$/.test(qrl)) {
	        message.channel.send("That's not a number I understand");
	        return;
	    }

		btc = parseFloat(btc);
		qrl = parseFloat(qrl);

		// check if there's characters...
		if(btc>1 || btc <= 0.000000001) {
			message.channel.send("BTC price per QRL is either too high or too low. Range 0.00000001 - 1");
			return;
		}
		if(qrl<=1) {
			message.channel.send("Can't buy less than 1 QRL at a time");
			return;
		}
		var total = btc*qrl;

		// Check if WTB is lower than WTS
		try {
			var wts = db.getData("/wts");
			var wts_sorted = wts.sort(sort_by('btc',false, parseFloat));

			if(parseFloat(wtb_sorted[0]['btc']) > parseFloat(btc - 0.00000001)) {
				message.channel.send("Sorry, the WTB order must be lower than the *lowest* WTS order at this time");
				return;
			}
		} catch(error) {

		};

		message.channel.send("Market WTB order at "+btc+" for "+qrl+" QRL for a total of ("+total+" BTC)");

			// Get orderid
		db.push('/orderid[]',{});
		orderid=db.getData("/orderid").length;

		db.push("/wtb[]", {
			"orderid":orderid,
			"btc":btc,
			"qrl":qrl,
			"username":message.author.username,
			"userid":message.author.id
		}, true);

		this.market(message);
	},
	clear:function(message, command) {

		try {
			var wtb = db.getData("/wtb");
			var wtb_arr = [];

			wtb.forEach(function(arr) {
				var orderid = parseInt(arr['orderid']);

				if(command[1]==orderid || command[1]==arr['btc']) {
					if(message.author.id==arr['userid'] || message.author.id == '356943957588049920') {
						return;
					} else {
						message.channel.send("Please sir, deleting another person's order isn't nice.");
					}
				}

				wtb_arr.push(arr);
			});
			db.push("/wtb", wtb_arr);
		} catch(error) {

		}

		try {
			var wts = db.getData("/wts");
			var wts_arr = [];

			wts.forEach(function(arr) {
				var orderid = parseInt(arr['orderid']);

				if(command[1]==orderid || command[1]==arr['btc']) {
					if(message.author.id==arr['userid'] || message.author.id == '356943957588049920') {
						return;
					} else {
						message.channel.send("Please sir, deleting another person's order isn't nice.");
					}
				}

				wts_arr.push(arr);
			});
			db.push("/wts", wts_arr);
		} catch(error) {

		}

		this.market(message,command);

	},
	clearall:function(message,command) {
		if(message.author.id == '356943957588049920') {
			db.delete("/");
			message.channel.send("Market deleted");
		} else {
			message.channel.send("Market not deleted");
		}

	},
	market:function(message, command) {
		var output = "";
		var total = 0;

		try {
			var wts = db.getData("/wts");
			var wts_sorted = wts.sort(sort_by('btc',true, parseFloat));

			if(wts.length>0) {

				output += "Market WTS (want to sell)```";
				wts_sorted.forEach(function(arr) {
					qrl = parseFloat(arr['qrl']);
					btc = parseFloat(arr['btc']);
					order = String(arr['orderid']);
					total= btc * qrl;
					output += order.padStart(3," ")+" ";
					output += btc.toFixed(8)+' btc/qrl';
					output += String(arr.qrl).padStart(6," ")+" qrl ";
					output += String(total.toFixed(8)).padStart(12," ")+" BTC "+arr.username+"\n";
				});
				output += "```";
			}
		} catch(error) {

		}

		try {
			var wtb = db.getData("/wtb");
			var wtb_sorted = wtb.sort(sort_by('btc',true, parseFloat));

			if(wtb.length>0) {
				output += "Market WTB (want to buy)```";
				wtb_sorted.forEach(function(arr) {
					qrl = parseFloat(arr.qrl);
					btc = parseFloat(arr.btc);
					order = String(arr.orderid);
					total= btc * qrl;
					output += order.padStart(3," ")+" ";
					output += btc.toFixed(8)+' btc/qrl';
					output += String(arr.qrl).padStart(6," ")+" qrl ";
					output += String(total.toFixed(8)).padStart(12," ")+" BTC "+arr.username+"\n";
				});
				output += "```";
			}
		} catch(error) {

		}

		if(output=="") {
			output = "No markets available";
		}
		message.channel.send(output);
	},
	escrow: function(message, command) {
		// If no command, print 'help'

		// otc escrow list

		// otc escrow order [btc_full] [qrl_full] [party_btc] [party_qrl]
		// ^ put in new escrow order

		// otc escrow recieved [order_number]
		// otc escrow review [order_number]
		// otc escrow status [order_number]
	},
	otc:async function(message, subcommand, config) {
		this.cleanup(message);
		var	command = subcommand.toLowerCase().split(' ');

		switch(command[0]) {
			case 'wts':
				this.wts(message, command);
			break;
			case 'wtb':
				this.wtb(message, command);
			break;
			case 'market':
				this.market(message, command);
			break;
			case 'clear':
				this.clear(message, command);
			break;
			case 'escrow':
				this.escrow(message, command);
			break;
			case 'clearall':
				this.clearall(message, command);
			break;
			default:
				message.channel.send("**Look at the market**\n`otc market`\n\n**Set a WTS (Want to Sell) order**\n`otc wts [btc/qrl] [qrl]`\n\n**Set a WTB (Want to Buy) order**\n`otc wtb [btc/qrl] [qrl]`\n\n**Remove an order**\n`otc clear [order number]`")

		}

	}
}<|endoftext|>


<commit_before>var gulp = require('gulp'),
    Elixir = require('laravel-elixir'),
    htmlmin = require('gulp-htmlmin'),
    gulpif = require('gulp-if'),
    injectString = require('gulp-inject-string'),
    cssInline = require('gulp-inline-css'),
    prettify = require('gulp-prettify'),
    inky = require('inky'),
    lazypipe = require('lazypipe'),
    sass = require('node-sass'),
    siphon = require('siphon-media-query');

Elixir.config.email = {
    assets: {
        // Defines the path to the sass file.  This is a direct path and should not include wildcards.
        sass: Elixir.config.assetsPath + '/emails/sass/email.scss',

        // Defines the path to the email source files.
        templates: Elixir.config.assetsPath + '/emails/views/**/*.blade.php'
    },
    public: {
        // Defines the path to the folder containing the compiled email templates.
        views: Elixir.config.publicPath + '/views'
    }
};

Elixir.extend('processEmails', function(options) {
    var config = Elixir.config.email;
    new Elixir.Task('processEmails', function() {
        this.recordStep('Processing Emails');
        return gulp
            .src(config.assets.templates)
            .pipe(inky())
            .pipe(prettify({ indent_size: 2 }))
            .pipe(injectString.replace('->', '->'))
            .pipe(injectString.replace('=>', '=>'))
            .pipe(injectString.replace('"', '"'))
            .pipe(injectString.replace(''', '\''))
            .pipe(instyler())
            .pipe(minifier())
            .pipe(gulp.dest(config.public.views));
    })
    .watch(config.assets.templates);

    function instyler() {
        var sassResult = sass.renderSync({file: config.assets.sass}),
            css = sassResult.css.toString(),
            breakpointCss = siphon(css);

        var pipe = lazypipe()
            .pipe(
                cssInline,
                {
                    applyStyleTags: false,
                    removeStyleTags: true,
                    preserveMediaQueries: true,
                    removeLinkTags: false,
                    extraCss: css
                }
            )
            .pipe(
                injectString.replace,
                '<!-- <style> -->', '<style>' + breakpointCss + '</style>'
            );
        return pipe();
    }

    var minifier = lazypipe()
        .pipe(function () {
            return gulpif(Elixir.config.production, htmlmin({
                collapseWhitespace: true,
                minifyCSS: true
            }));
        });
});
<commit_msg>Removed redundant options variable<commit_after>var gulp = require('gulp'),
    Elixir = require('laravel-elixir'),
    htmlmin = require('gulp-htmlmin'),
    gulpif = require('gulp-if'),
    injectString = require('gulp-inject-string'),
    cssInline = require('gulp-inline-css'),
    prettify = require('gulp-prettify'),
    inky = require('inky'),
    lazypipe = require('lazypipe'),
    sass = require('node-sass'),
    siphon = require('siphon-media-query');

Elixir.config.email = {
    assets: {
        // Defines the path to the sass file.  This is a direct path and should not include wildcards.
        sass: Elixir.config.assetsPath + '/emails/sass/email.scss',

        // Defines the path to the email source files.
        templates: Elixir.config.assetsPath + '/emails/views/**/*.blade.php'
    },
    public: {
        // Defines the path to the folder containing the compiled email templates.
        views: Elixir.config.publicPath + '/views'
    }
};

Elixir.extend('processEmails', function() {
    var config = Elixir.config.email;
    new Elixir.Task('processEmails', function() {
        this.recordStep('Processing Emails');
        return gulp
            .src(config.assets.templates)
            .pipe(inky())
            .pipe(prettify({ indent_size: 2 }))
            .pipe(injectString.replace('->', '->'))
            .pipe(injectString.replace('=>', '=>'))
            .pipe(injectString.replace('"', '"'))
            .pipe(injectString.replace(''', '\''))
            .pipe(instyler())
            .pipe(minifier())
            .pipe(gulp.dest(config.public.views));
    })
    .watch(config.assets.templates);

    function instyler() {
        var sassResult = sass.renderSync({file: config.assets.sass}),
            css = sassResult.css.toString(),
            breakpointCss = siphon(css);

        var pipe = lazypipe()
            .pipe(
                cssInline,
                {
                    applyStyleTags: false,
                    removeStyleTags: true,
                    preserveMediaQueries: true,
                    removeLinkTags: false,
                    extraCss: css
                }
            )
            .pipe(
                injectString.replace,
                '<!-- <style> -->', '<style>' + breakpointCss + '</style>'
            );
        return pipe();
    }

    var minifier = lazypipe()
        .pipe(function () {
            return gulpif(Elixir.config.production, htmlmin({
                collapseWhitespace: true,
                minifyCSS: true
            }));
        });
});
<|endoftext|>


<commit_before>#! /usr/bin/env node

'use strict'

const cli = require('./cli')
const server = require('./server')
const pkg = require('./package.json')
const program = require('commander')

program
  .version(pkg.version)

program
  .command('start')
  .description('Start the Jackal server')
  .option('-c, --config-path [path]', 'Pass a path to a config file, default ./jackal.json')
  .option('-p, --port [port]', 'Port to run the server on, default 25863')
  .action(server)

program
  .command('send <jackalUrl> <contractsPath>')
  .option('-R, --reporter [reporter]', 'Reporter for output [json|spec|teamcity]')
  .option('--skip-missing-contract', 'Do not execute tests if the contracts file is missing')
  .description('Send the consumer\'s contracts in the specified file to the Jackal service')
  .action(cli.send)

program
  .command('run <jackalUrl> <providerName>')
  .option('-R, --reporter [reporter]', 'Reporter for output [json|spec|teamcity]')
  .option('-t, --test-url [testUrl]', 'Base url of the provider, defaults to the original URL specified by the consumer contract')
  .description('Runs the provider\'s contracts stored in the database of the Jackal service')
  .action(cli.run)

program
  .command('dump <jackalUrl>')
  .option('-R, --reporter [reporter]', 'Reporter for output [json|pretty]')
  .description('Dumps the database of the Jackal service')
  .action(cli.dump)

program
  .command('stats <jackalUrl>')
  .option('-C, --consumer [consumer]', 'Consumer to retrieve current statistics for')
  .option('-P, --provider [provider]', 'Provider to retrieve current statistics for')
  .option('-R, --reporter [reporter]', 'Reporter for output [json|pretty]')
  .description('Gets usage stats from the running Jackal service')
  .action(cli.stats)

program
  .parse(process.argv)

if (!process.argv.slice(2).length) {
  program.outputHelp()
}
<commit_msg>Removing port option from server cli command<commit_after>#! /usr/bin/env node

'use strict'

const cli = require('./cli')
const server = require('./server')
const pkg = require('./package.json')
const program = require('commander')

program
  .version(pkg.version)

program
  .command('start')
  .description('Start the Jackal server')
  .option('-c, --config-path [path]', 'Pass a path to a config file, default ./jackal.json')
  .action(server)

program
  .command('send <jackalUrl> <contractsPath>')
  .option('-R, --reporter [reporter]', 'Reporter for output [json|spec|teamcity]')
  .option('--skip-missing-contract', 'Do not execute tests if the contracts file is missing')
  .description('Send the consumer\'s contracts in the specified file to the Jackal service')
  .action(cli.send)

program
  .command('run <jackalUrl> <providerName>')
  .option('-R, --reporter [reporter]', 'Reporter for output [json|spec|teamcity]')
  .option('-t, --test-url [testUrl]', 'Base url of the provider, defaults to the original URL specified by the consumer contract')
  .description('Runs the provider\'s contracts stored in the database of the Jackal service')
  .action(cli.run)

program
  .command('dump <jackalUrl>')
  .option('-R, --reporter [reporter]', 'Reporter for output [json|pretty]')
  .description('Dumps the database of the Jackal service')
  .action(cli.dump)

program
  .command('stats <jackalUrl>')
  .option('-C, --consumer [consumer]', 'Consumer to retrieve current statistics for')
  .option('-P, --provider [provider]', 'Provider to retrieve current statistics for')
  .option('-R, --reporter [reporter]', 'Reporter for output [json|pretty]')
  .description('Gets usage stats from the running Jackal service')
  .action(cli.stats)

program
  .parse(process.argv)

if (!process.argv.slice(2).length) {
  program.outputHelp()
}
<|endoftext|>


<commit_before>'use strict';
const through = require('through2');

module.exports = pathCallback => {
	const stream = through.obj(function (file, encoding, callback) {
		this.paths.push(file.path);

		if (pathCallback) {
			(async () => {
				try {
					callback(null, await pathCallback(file.path));
				} catch (error) {
					callback(error);
				}
			})();
		} else {
			callback(null, file);
		}
	});

	stream.paths = [];

	return stream;
};
<commit_msg>Fix regression in v3 (#8)<commit_after>'use strict';
const through = require('through2');

module.exports = pathCallback => {
	const stream = through.obj(function (file, encoding, callback) {
		this.paths.push(file.path);

		if (pathCallback) {
			(async () => {
				try {
					await pathCallback(file.path);
					callback(null, file);
				} catch (error) {
					callback(error);
				}
			})();
		} else {
			callback(null, file);
		}
	});

	stream.paths = [];

	return stream;
};
<|endoftext|>