<commit_before>import RSVP from 'rsvp';
import EventEmitter2 from 'eventemitter2';

const EM = EventEmitter2.EventEmitter2;

import flowUtil from './flow-util';

const exists         = flowUtil.exists;
const hasProperty    = flowUtil.hasProperty;
const mergeDict      = flowUtil.mergeDict;
const isSameEdge     = flowUtil.isSameEdge;
const isTerminalNode = flowUtil.isTerminalNode;
const getEntryNode   = flowUtil.getEntryNode;
const getNode        = flowUtil.getNode;

function initVariables(vars) {
  let dict = {};
  vars.forEach(
    (obj) => {
      var val;
      switch(obj.type) {
        case 'number':
          val = 0;
        break;
        case 'boolean':
          val = false;
        break;
        case 'string':
          val = '';
        break;
        default:
          throw new Error('xflox.initVariables : Unhandled type ' + obj.type);
      }
      dict[obj.name] = val;
    });
  return dict;

}

function initState(params) {
  let state = {};
  for (let key in params) {
    state[key] = params[key];
  }
  return state;
}

function getSelectedEdge(node, flow, state) {

  const resBranches = flow.branches.filter(
    (branch) =>
      branch.name === node.parameters.name &&
        branch.value === state[node.parameters.name]
  );

  if (resBranches.length > 1) {
    throw new Error('xflow.getNextNodeFromBranch : Multiple matching branches found');
  } else if (resBranches.length < 1) {
    throw new Error('xflow.getNextNodeFromBranch : No matching branches found');
  }

  const resEdges = flow.edges.filter(
    (edge) =>
      isSameEdge(edge, resBranches[0].branch)
  );

  if (resEdges.length > 1) {
    throw new Error('xflow.getNextNodeFromBranch : Multiple matching edges found');
  } else if (resEdges.length < 1) {
    throw new Error('xflow.getNextNodeFromBranch : No matching edges found');
  }

  return resEdges[0];
}

function getNextNode(node, flow, state) {
  // console.log('getNextNode ', JSON.stringify(node));
  const resEdges = flow.edges.filter(
    (edge) =>
      edge[0] === node.id
  );

  //
  // 1. Next node
  // 2. Next node from branch condition
  // 3. No next node
  //

  if (resEdges.length === 1) {
    return getNode(resEdges[0][1], flow.nodes);
  } else if (resEdges.length > 1) {
    return getNode(
      getSelectedEdge(node, flow, state)[1],
      flow.nodes,
      state
    );
  } else {
    return null;
  }

}

function getReturnValue(signature, state) {
  if (!!!state) {
    throw new Error('getReturnValue : NO STATE');
  }
  // console.log('getReturnValue : ', signature , ' // ' , state);
  return signature.map(
    (obj) => {
      let retObj = {};
      if (state[obj.name]) {
        retObj[obj.name] = state[obj.name];
      }
      return retObj;
    });
}

/**
 * XFlow class.
 * @class XFlow
 * @fires XFlow#start
 * @fires XFlow#end
 * @fires XFlow#nextStep
 */
class XFlow {

  /**
   * XFlow constructor
   * @constructor XFlow
   * @param {Object} flowJson
   * @param {Object} params
   */
  constructor(flowJson, params, dispatcher) {

    if (!!!flowJson) {
      throw new Error('XFlow : No valid flow data found');
    }

    params = params || {};

    if (!!!dispatcher) {
      throw new Error('XFlow : Initialized without a dispatcher');
    }

    /**
     * Flow ID
     * @member XFlow#id
     */
    this.id         = +(new Date());
    this.flow       = flowJson;
    this.dispatcher = dispatcher;
    this.state      = mergeDict(
      initState(params),
      initVariables(this.flow.variables)
    );

    this.emitter = new EM({
      wildcard : true
    });

  }

  emit(name, ...args) {
    this.emitter.emit.apply(
      this.emitter,
      [name, this.id].concat(...args)
    );
  }

  //
  // Sync methods
  //

  /**
   * Starts the flow
   * @method XFlow#start
   * @returns {Object} state
   */
  start() {
    this.emit('start');
    return this._runToCompletion(
      getEntryNode(this.flow.nodes)
    );
  }

  _runToCompletion(node) {

    while (!isTerminalNode(node)) {
      this.emit('nextStep', node.id);
      node = getNextNode(
        node,
        this.flow,
        this.state
      );
      this.state = this.dispatcher.processNode(node, this.state);
    }

    this.emit('end');
    return getReturnValue(
      this.flow.signature.out,
      this.state
    );

  }

  //
  // Async methods
  //

  /**
   * Start flow async
   * @method XFlow#startQ
   * @returns {Promise} Resolves the final state
   */
  startQ() {
    const defer = RSVP.defer();

    this.emit('start');

    try {
      this._runToCompletionQ(
        getEntryNode(this.flow.nodes)
      ).then(
        (state) => {
          this.emit('xflow.resolved', state);
          // console.log('startFlowQ: Resolved ', state);
          this.state = state;
          this.emit('end');
          defer.resolve(state);
        },
        (err) => {
          console.error('startFlowQ: Rejected ', err);
          defer.reject(err);
        }
      );
    } catch(e) {
      defer.reject(e.message);
    }

    return defer.promise;
  }

  _runToCompletionQ(node) {
    const defer = RSVP.defer();

    const nextStep = (node) => {
      this.emit('nextStep', node.id);
      node = getNextNode(
        node,
        this.flow,
        this.state
      );
      if (isTerminalNode(node)) {
        defer.resolve(
          getReturnValue(
            this.flow.signature.out,
            this.state
          ));
      } else {
        this.dispatcher.processNodeQ(node, this.state).then(
          (state) => {
            this.state = state;
            nextStep(node);
          },
          (err) => {
            console.error('runToCompletionQ.nextStep : error ', err);
            defer.reject('runToCompletionQ.nextStep : error ' + err);
          }
        );
      }
    };

    nextStep(node);

    return defer.promise;
  }
}

export default XFlow;
<commit_msg>Add nextStep/nextStepQ to XFlow<commit_after>import RSVP from 'rsvp';
import EventEmitter2 from 'eventemitter2';

const EM = EventEmitter2.EventEmitter2;

import flowUtil from './flow-util';

const exists         = flowUtil.exists;
const hasProperty    = flowUtil.hasProperty;
const mergeDict      = flowUtil.mergeDict;
const isSameEdge     = flowUtil.isSameEdge;
const isTerminalNode = flowUtil.isTerminalNode;
const getEntryNode   = flowUtil.getEntryNode;
const getNode        = flowUtil.getNode;

function initVariables(vars) {
  let dict = {};
  vars.forEach(
    (obj) => {
      let val;
      switch(obj.type) {
        case 'number':
          val = 0;
        break;
        case 'boolean':
          val = false;
        break;
        case 'string':
          val = '';
        break;
        default:
          throw new Error('xflox.initVariables : Unhandled type ' + obj.type);
      }
      dict[obj.name] = val;
    });
  return dict;

}

function initState(params) {
  let state = {};
  for (let key in params) {
    state[key] = params[key];
  }
  return state;
}

function getSelectedEdge(node, flow, state) {

  const resBranches = flow.branches.filter(
    (branch) =>
      branch.name === node.parameters.name &&
        branch.value === state[node.parameters.name]
  );

  if (resBranches.length > 1) {
    throw new Error('xflow.getNextNodeFromBranch : Multiple matching branches found');
  } else if (resBranches.length < 1) {
    throw new Error('xflow.getNextNodeFromBranch : No matching branches found');
  }

  const resEdges = flow.edges.filter(
    (edge) =>
      isSameEdge(edge, resBranches[0].branch)
  );

  if (resEdges.length > 1) {
    throw new Error('xflow.getNextNodeFromBranch : Multiple matching edges found');
  } else if (resEdges.length < 1) {
    throw new Error('xflow.getNextNodeFromBranch : No matching edges found');
  }

  return resEdges[0];
}

function getNextNode(node, flow, state) {
  // console.log('getNextNode ', JSON.stringify(node));
  const resEdges = flow.edges.filter(
    (edge) =>
      edge[0] === node.id
  );

  //
  // 1. Next node
  // 2. Next node from branch condition
  // 3. No next node
  //

  if (resEdges.length === 1) {
    return getNode(resEdges[0][1], flow.nodes);
  } else if (resEdges.length > 1) {
    return getNode(
      getSelectedEdge(node, flow, state)[1],
      flow.nodes,
      state
    );
  } else {
    return null;
  }

}

function getReturnValue(signature, state) {
  if (!!!state) {
    throw new Error('getReturnValue : NO STATE');
  }
  // console.log('getReturnValue : ', signature , ' // ' , state);
  return signature.map(
    (obj) => {
      let retObj = {};
      if (state[obj.name]) {
        retObj[obj.name] = state[obj.name];
      }
      return retObj;
    });
}

/**
 * XFlow class.
 * @class XFlow
 * @fires XFlow#start
 * @fires XFlow#end
 * @fires XFlow#nextStep
 */
class XFlow {

  /**
   * XFlow constructor
   * @constructor XFlow
   * @param {Object} flowJson
   * @param {Object} params
   */
  constructor(flowJson, params, dispatcher, id) {

    if (!!!flowJson) {
      throw new Error('XFlow : No valid flow data found');
    }

    params = params || {};

    if (!!!dispatcher) {
      throw new Error('XFlow : Initialized without a dispatcher');
    }

    /**
     * Flow ID
     * @member XFlow#id
     */
    this.id         = id || +(new Date());
    this.flow       = flowJson;
    this.dispatcher = dispatcher;

    this.state      = mergeDict(
      initState(params),
      initVariables(this.flow.variables)
    );

    this.emitter    = new EM({
      wildcard : true
    });

    this.activeNode = getEntryNode(this.flow.nodes);
    this.stepCount  = 0;

  }

  emit(name, ...args) {
    this.emitter.emit.apply(
      this.emitter,
      [name, this.id].concat(...args)
    );
  }

  //
  // Sync methods
  //

  /**
   * Starts the flow
   * @method XFlow#start
   * @returns {Object} state
   */
  start() {
    this.emit('start');

    while (!isTerminalNode(this.activeNode)) {
      this.emit('nextStep', this.activeNode.id);
      this.stepCount++;

      this.activeNode = getNextNode(
        this.activeNode,
        this.flow,
        this.state
      );

      this.state = this.dispatcher.processNode(
        this.activeNode,
        this.state
      );
    }

    this.emit('end');

    return getReturnValue(
      this.flow.signature.out,
      this.state
    );

  }

  nextStep() {
    this.emit('nextStep', this.activeNode.id);

    if (isTerminalNode(this.activeNode)) {

      this.emit('end');
      return false;

    } else {

      this.activeNode = getNextNode(
        this.activeNode,
        this.flow,
        this.state
      );

      this.stepCount++;

      this.state = this.dispatcher.processNode(
        this.activeNode,
        this.state
      );

      return true;
    }

  }

  nextStepQ() {
    const defer = RSVP.defer();

    this.emit('nextStep', this.activeNode.id);

    if (isTerminalNode(this.activeNode)) {

      this.emit('end');
      defer.resolve(false);

    } else {

      this.activeNode = getNextNode(
        this.activeNode,
        this.flow,
        this.state
      );

      this.stepCount++;

      this.dispatcher.processNodeQ(
        this.activeNode,
        this.state
      ).then(
        (state)=> {
          this.state = state;
          defer.resolve(true);
        },
        (err)=> {
          defer.reject(err);
        }
      );

    }
    return defer.promise;
  }

  returnValue() {
    return getReturnValue(
      this.flow.signature.out,
      this.state
    );
  }

  //
  // Async methods
  //

  /**
   * Start flow async
   * @method XFlow#startQ
   * @returns {Promise} Resolves the final state
   */
  startQ() {
    const defer = RSVP.defer();

    this.emit('start');

    try {
      this._runToCompletionQ().then(
        (state) => {
          this.emit('xflow.resolved', state);
          // console.log('startFlowQ: Resolved ', state);
          this.state = state;
          this.emit('end');
          defer.resolve(state);
        },
        (err) => {
          console.error('startFlowQ: Rejected ', err);
          defer.reject(err);
        }
      );
    } catch(e) {
      defer.reject(e.message);
    }

    return defer.promise;
  }

  _runToCompletionQ() {
    const defer = RSVP.defer();

    const nextStep = () => {
      this.emit('nextStep', this.activeNode.id);
      this.stepCount++;

      this.activeNode = getNextNode(
        this.activeNode,
        this.flow,
        this.state
      );

      if (isTerminalNode(this.activeNode)) {
        defer.resolve(
          getReturnValue(
            this.flow.signature.out,
            this.state
          ));
      } else {
        this.dispatcher.processNodeQ(this.activeNode, this.state).then(
          (state) => {
            this.state = state;
            nextStep();
          },
          (err) => {
            console.error('runToCompletionQ.nextStep : error ', err);
            defer.reject('runToCompletionQ.nextStep : error ' + err);
          }
        );
      }
    };

    nextStep();

    return defer.promise;
  }

}

export default XFlow;
<|endoftext|>


<commit_before>/*
 * yatzy
 * https://github.com/sodper/yatzy-kata
 *
 * Copyright (c) 2014 Per Flitig
 * Licensed under the MIT license.
 */

'use strict';

// reduces to sum
var sum = function (previous, current) {
  return previous + current;
};

// creates a value filter function
var equal =  function(value) {
  return function (x) {
    return x === value;
  };
};

// creates a reduction function for multiples of die
var getMultiples = function(multiple) {
  return function(last, now, index, array) {
    if(array.filter(equal(now)).length === multiple) {
        last.push(now);
    }
    return last;
  };
};

/*
  commands
*/

var dieCommand = function(die) {
  return function(roll) {
    var filtered = roll.filter(equal(die));
    return filtered.reduce(sum, 0);
  };
};

var chanceCommand = function(roll) {
  return roll.reduce(sum, 0);
};

var yatzyCommand = function(roll) {
  return (roll.every(equal(roll[0]))) ? 50 : 0;
};

var pairCommand = function(roll) {
  var result = roll.reduce(function(last, now, index, array) {
    var filtered = array.filter(equal(now));
    return (filtered.length === 2 && now * 2 > last.score) ? { die: now, score: now * 2 } : last;
  }, { die: 0, score: 0 });
  return result.score;
};

var twoPairsCommand = function(roll) {
  var pairs = roll.reduce(getMultiples(2), []);

  return (pairs.length === 4) ? pairs.reduce(sum, 0) : 0;
};

var ofKindCommand = function(multiple) {
  return function(roll) {
    var threes = roll.reduce(getMultiples(multiple), []);
    return threes.reduce(sum, 0);
  };
};

var smallStraightCommand = function(roll) {
  for (var i=1; i<=5; i++) {
    if (roll.indexOf(i) == -1) {
      return 0;
    }
  }
  return roll.reduce(sum, 0);
};

var largeStraightCommand = function(roll) {
  for (var i=2; i<=6; i++) {
    if (roll.indexOf(i) == -1) {
      return 0;
    }
  }
  return roll.reduce(sum, 0);
};

// command object
var commands = {
  'ones': dieCommand(1),
  'twos': dieCommand(2),
  'threes': dieCommand(3),
  'fours': dieCommand(4),
  'fives': dieCommand(5),
  'chance': chanceCommand,
  'yatzy': yatzyCommand,
  'pair': pairCommand,
  'two pairs': twoPairsCommand,
  'three of a kind': ofKindCommand(3),
  'four of a kind': ofKindCommand(4),
  'small straight': smallStraightCommand,
  'large straight': largeStraightCommand,
};

exports.score = function(roll, category) {
  return commands[category](roll);
};
<commit_msg>Refactored commands for straight categories<commit_after>/*
 * yatzy
 * https://github.com/sodper/yatzy-kata
 *
 * Copyright (c) 2014 Per Flitig
 * Licensed under the MIT license.
 */

'use strict';

// reduces to sum
var sum = function (previous, current) {
  return previous + current;
};

// creates a value filter function
var equal =  function(value) {
  return function (x) {
    return x === value;
  };
};

// creates a reduction function for multiples of die
var getMultiples = function(multiple) {
  return function(last, now, index, array) {
    if(array.filter(equal(now)).length === multiple) {
        last.push(now);
    }
    return last;
  };
};

/*
  commands
*/

var dieCommand = function(die) {
  return function(roll) {
    var filtered = roll.filter(equal(die));
    return filtered.reduce(sum, 0);
  };
};

var chanceCommand = function(roll) {
  return roll.reduce(sum, 0);
};

var yatzyCommand = function(roll) {
  return (roll.every(equal(roll[0]))) ? 50 : 0;
};

var pairCommand = function(roll) {
  var result = roll.reduce(function(last, now, index, array) {
    var filtered = array.filter(equal(now));
    return (filtered.length === 2 && now * 2 > last.score) ? { die: now, score: now * 2 } : last;
  }, { die: 0, score: 0 });
  return result.score;
};

var twoPairsCommand = function(roll) {
  var pairs = roll.reduce(getMultiples(2), []);

  return (pairs.length === 4) ? pairs.reduce(sum, 0) : 0;
};

var ofKindCommand = function(multiple) {
  return function(roll) {
    var threes = roll.reduce(getMultiples(multiple), []);
    return threes.reduce(sum, 0);
  };
};

var straightCommand = function(type) {
  var limits = {
    'small': { start: 1, end: 5 },
    'large': { start: 2, end: 6 },
  };

  return function(roll) {
    for (var i = limits[type].start; i <= limits[type].end; i++) {
      if (roll.indexOf(i) == -1) {
        return 0;
      }
    }
    return roll.reduce(sum, 0);
  };
};

// command object
var commands = {
  'ones': dieCommand(1),
  'twos': dieCommand(2),
  'threes': dieCommand(3),
  'fours': dieCommand(4),
  'fives': dieCommand(5),
  'chance': chanceCommand,
  'yatzy': yatzyCommand,
  'pair': pairCommand,
  'two pairs': twoPairsCommand,
  'three of a kind': ofKindCommand(3),
  'four of a kind': ofKindCommand(4),
  'small straight': straightCommand('small'),
  'large straight': straightCommand('large'),
};

exports.score = function(roll, category) {
  return commands[category](roll);
};
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.makeTelegramDriver = makeTelegramDriver;

var _rx = require('rx');

var _rx2 = _interopRequireDefault(_rx);

var _ramda = require('ramda');

var _sources = require('./sources');

var _apiRequest = require('./api-request');

var _types = require('../types');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function makeEventsSelector(sources) {
  return function events(eventName) {
    var messageSources = {
      'message': sources.message.share()
    };

    var inlineQuerySources = {
      'inline_query': sources.inlineQuery.share(),
      'chosen_inline_result': sources.chosenInlineResult.share()
    };

    var callbackQuerySources = {
      'callback_query': sources.callbackQuery.share()
    };

    // return interface
    return _rx2.default.Observable.case(function () {
      return eventName;
    }, Object.assign({}, messageSources, inlineQuerySources, callbackQuerySources));
  };
}

var handleWebhook = function handleWebhook(token, request, action) {
  return request.mergeAll().filter(_types.WebhookResponse.is).map((0, _ramda.prop)('update')).do(function (x) {
    return console.log('webhook', x);
  }).subscribe(function (upd) {
    return action.onNext([upd]);
  }, function (err) {
    return console.error('request error: ', err);
  });
};

var handleRequest = function handleRequest(token, request) {
  return request.mergeAll().filter(_types.Request.is).flatMap(function (_ref) {
    var method = _ref.method;
    var query = _ref.options;
    return (0, _apiRequest.makeAPIRequest)({ token: token, method: method, query: query }).catch(_rx2.default.Observable.empty());
  }).subscribe(function (req) {
    return console.log('response: ', req);
  }, function (err) {
    return console.error('request error: ', err);
  });
};

function makeTelegramDriver(token) {
  var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

  var proxy = (0, _sources.makeUpdates)(token);
  var action = new _rx2.default.Subject();
  if (options.webhook) {
    proxy = (0, _sources.makeWebHook)(token, action);
  }

  var updates = proxy.doOnError(function (err) {
    return console.error('updates error: ', err);
  }).replay(null, 1);

  var sources = (0, _sources.makeSources)(updates);
  var disposable = updates.connect();

  return function telegramDriver(request) {
    // pass request
    if (options.webhook) {
      // handle webhook
      handleWebhook(token, request, action);
    }
    // handle request
    handleRequest(token, request);

    // return interface
    return {
      token: token,
      observable: updates,
      events: makeEventsSelector(sources),
      dispose: function dispose() {
        return disposable.dispose();
      }
    };
  };
}<commit_msg>update lib<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.makeTelegramDriver = makeTelegramDriver;

var _rx = require('rx');

var _rx2 = _interopRequireDefault(_rx);

var _ramda = require('ramda');

var _sources = require('./sources');

var _apiRequest = require('./api-request');

var _types = require('../types');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function makeEventsSelector(sources) {
  return function events(eventName) {
    var messageSources = {
      'message': sources.message.share()
    };

    var inlineQuerySources = {
      'inline_query': sources.inlineQuery.share(),
      'chosen_inline_result': sources.chosenInlineResult.share()
    };

    var callbackQuerySources = {
      'callback_query': sources.callbackQuery.share()
    };

    // return interface
    return _rx2.default.Observable.case(function () {
      return eventName;
    }, Object.assign({}, messageSources, inlineQuerySources, callbackQuerySources));
  };
}

var handleWebhook = function handleWebhook(token, request, action) {
  return request.mergeAll().filter(_types.WebhookResponse.is).map((0, _ramda.prop)('update')).subscribe(function (upd) {
    return action.onNext([upd]);
  }, function (err) {
    return console.error('request error: ', err);
  });
};

var handleRequest = function handleRequest(token, request) {
  return request.mergeAll().filter(_types.Request.is).flatMap(function (_ref) {
    var method = _ref.method;
    var query = _ref.options;
    return (0, _apiRequest.makeAPIRequest)({ token: token, method: method, query: query }).catch(_rx2.default.Observable.empty());
  }).subscribeOnError(function (err) {
    return console.error('request error: ', err);
  });
};

function makeTelegramDriver(token) {
  var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

  var proxy = (0, _sources.makeUpdates)(token);
  var action = new _rx2.default.Subject();
  if (options.webhook) {
    proxy = (0, _sources.makeWebHook)(token, action);
  }

  var updates = proxy.doOnError(function (err) {
    return console.error('updates error: ', err);
  }).replay(null, 1);

  var sources = (0, _sources.makeSources)(updates);
  var disposable = updates.connect();

  return function telegramDriver(request) {
    // pass request
    if (options.webhook) {
      // handle webhook
      handleWebhook(token, request, action);
    }
    // handle request
    handleRequest(token, request);

    // return interface
    return {
      token: token,
      observable: updates,
      events: makeEventsSelector(sources),
      dispose: function dispose() {
        return disposable.dispose();
      }
    };
  };
}<|endoftext|>


<commit_before>  var TAU = Math.PI*2;
  // min value to render a line.
  // it does not make sense to render a line of a width is not even visible
  var LINEWIDTH_MIN_VALUE = 0.05;

  function renderPoint(ctx, st) {
    ctx.fillStyle = st['marker-fill'];
    var pixel_size = st['marker-width'];

    // render a circle
    // TODO: fill and stroke order should depend on the order of the properties
    // in the cartocss.

    // fill
    ctx.beginPath();
    ctx.arc(0, 0, pixel_size, 0, TAU, true, true);
    ctx.closePath();

    if (st['marker-opacity'] !== undefined )  st['marker-fill-opacity'] = st['marker-line-opacity'] = st['marker-opacity'];

    if (st['marker-fill']) {
        ctx.globalAlpha = st['marker-fill-opacity'] >= 0? st['marker-fill-opacity']: 1;

      if (ctx.globalAlpha > 0) {
        ctx.fill();
      }
    }

    // stroke
    if (st['marker-line-color'] && st['marker-line-width'] && st['marker-line-width'] > LINEWIDTH_MIN_VALUE) {
      ctx.globalAlpha = st['marker-line-opacity'] >= 0? st['marker-line-opacity']: 1;
      if (st['marker-line-width'] !== undefined) {
        ctx.lineWidth = st['marker-line-width'];
      }
      ctx.strokeStyle = st['marker-line-color'];

      // do not render for alpha = 0
      if (ctx.globalAlpha > 0) {
        ctx.stroke();
      }
    }
  }

  function renderRectangle(ctx, st) {
    ctx.fillStyle = st['marker-fill'];
    var pixel_size = st['marker-width'];
    var w = pixel_size * 2;

    // fill
    if (st['marker-fill']) {
      if (st['marker-fill-opacity'] !== undefined || st['marker-opacity'] !== undefined) {
        ctx.globalAlpha = st['marker-fill-opacity'] || st['marker-opacity'];
      }
      ctx.fillRect(-pixel_size, -pixel_size, w, w)
    }

    // stroke
    ctx.globalAlpha = 1.0;
    if (st['marker-line-color'] && st['marker-line-width']) {
      if (st['marker-line-opacity']) {
        ctx.globalAlpha = st['marker-line-opacity'];
      }
      if (st['marker-line-width']) {
        ctx.lineWidth = st['marker-line-width'];
      }
      ctx.strokeStyle = st['marker-line-color'];

      // do not render for alpha = 0
      if (ctx.globalAlpha > 0) {
        ctx.strokeRect(-pixel_size, -pixel_size, w, w)
      }
    }
  }

  function renderSprite(ctx, img, st) {

    if(img.complete){
      if (st['marker-fill-opacity'] !== undefined || st['marker-opacity'] !== undefined) {
        ctx.globalAlpha = st['marker-fill-opacity'] || st['marker-opacity'];
      }
      ctx.drawImage(img, 0, 0, img.width, img.height);
    }
  }

module.exports = {
    renderPoint: renderPoint,
    renderSprite: renderSprite,
    renderRectangle: renderRectangle
};
<commit_msg>limits sprite radius to 255<commit_after>  var TAU = Math.PI*2;
  // min value to render a line.
  // it does not make sense to render a line of a width is not even visible
  var LINEWIDTH_MIN_VALUE = 0.05;

  function renderPoint(ctx, st) {
    ctx.fillStyle = st['marker-fill'];
    var pixel_size = st['marker-width'];

    // render a circle
    // TODO: fill and stroke order should depend on the order of the properties
    // in the cartocss.

    // fill
    ctx.beginPath();
    ctx.arc(0, 0, pixel_size, 0, TAU, true, true);
    ctx.closePath();

    if (st['marker-opacity'] !== undefined )  st['marker-fill-opacity'] = st['marker-line-opacity'] = st['marker-opacity'];

    if (st['marker-fill']) {
        ctx.globalAlpha = st['marker-fill-opacity'] >= 0? st['marker-fill-opacity']: 1;

      if (ctx.globalAlpha > 0) {
        ctx.fill();
      }
    }

    // stroke
    if (st['marker-line-color'] && st['marker-line-width'] && st['marker-line-width'] > LINEWIDTH_MIN_VALUE) {
      ctx.globalAlpha = st['marker-line-opacity'] >= 0? st['marker-line-opacity']: 1;
      if (st['marker-line-width'] !== undefined) {
        ctx.lineWidth = st['marker-line-width'];
      }
      ctx.strokeStyle = st['marker-line-color'];

      // do not render for alpha = 0
      if (ctx.globalAlpha > 0) {
        ctx.stroke();
      }
    }
  }

  function renderRectangle(ctx, st) {
    ctx.fillStyle = st['marker-fill'];
    var pixel_size = st['marker-width'];
    var w = pixel_size * 2;

    // fill
    if (st['marker-fill']) {
      if (st['marker-fill-opacity'] !== undefined || st['marker-opacity'] !== undefined) {
        ctx.globalAlpha = st['marker-fill-opacity'] || st['marker-opacity'];
      }
      ctx.fillRect(-pixel_size, -pixel_size, w, w)
    }

    // stroke
    ctx.globalAlpha = 1.0;
    if (st['marker-line-color'] && st['marker-line-width']) {
      if (st['marker-line-opacity']) {
        ctx.globalAlpha = st['marker-line-opacity'];
      }
      if (st['marker-line-width']) {
        ctx.lineWidth = st['marker-line-width'];
      }
      ctx.strokeStyle = st['marker-line-color'];

      // do not render for alpha = 0
      if (ctx.globalAlpha > 0) {
        ctx.strokeRect(-pixel_size, -pixel_size, w, w)
      }
    }
  }

  function renderSprite(ctx, img, st) {

    if(img.complete){
      if (st['marker-fill-opacity'] !== undefined || st['marker-opacity'] !== undefined) {
        ctx.globalAlpha = st['marker-fill-opacity'] || st['marker-opacity'];
      }
      var maxSpriteRadius = 255;
      ctx.drawImage(img, 0, 0, Math.min(img.width, maxSpriteRadius), Math.min(img.height, maxSpriteRadius));
    }
  }

module.exports = {
    renderPoint: renderPoint,
    renderSprite: renderSprite,
    renderRectangle: renderRectangle
};
<|endoftext|>


<commit_before>function Core(options) {
  this.options = options;
}

Core.prototype.hello = function() {

}

module.exports = Core;
<commit_msg>Add hello request<commit_after>var utils = require('./utils');

function Core(options) {
  this.options = options;
}

Core.prototype.hello = function(callback) {
  utils.request('GET', this.options.apiUrl + 'core/hello', this.options.apiKey, function(data) {
    return callback(data);
  });
}

module.exports = Core;
<|endoftext|>


<commit_before>
'use strict';

const config = require('../config');

const logger = require('../storage/logger');

const resetGamestate = require('./domain-utils/reset-gamestate');
const assignDealerButton = require('./domain-utils/assign-dealer-button');
const computeSmallBlind = require('./domain-utils/compute-small-blind');

// const payBlinds = require('./domain-utils/pay-blinds');
// const shuffleCards = require('./domain-utils/shuffle-cards');
// const assignCards = require('./domain-utils/assign-player-cards');
<commit_msg>draft setup-tasks<commit_after>
'use strict';

const config = require('../config');

const logger = require('../storage/logger');

const playerStatus = require('./domain/player-status');

const resetGamestate = require('./domain-utils/reset-gamestate');
const assignDealerButton = require('./domain-utils/assign-dealer-button');
const computeSmallBlind = require('./domain-utils/compute-small-blind');
const payAntes = require('./domain-utils/pay-antes');
const payBlinds = require('./domain-utils/pay-blinds');
const assignCards = require('./domain-utils/assign-cards');

exports = module.exports = function* setup(gs){

  resetGamestate(gs);

  logger.log('debug', 'Gamestate has been restored to hand initial condition.', { tag: gs.handUniqueId });

  // assign to the player in turn the dealer button
  // (only an active player can receive the button)
  assignDealerButton(gs);

  logger.log('debug', 'Dealer Button has been assigned (%d).', gs.dbIndex, { tag: gs.handUniqueId });

  // compute the small blind level for the current hand
  // big blinds is always the double
  computeSmallBlind(gs);

  logger.log('debug', 'Small Blind has been computed; its value is %d.', gs.sb, { tag: gs.handUniqueId });

  // make each active player pay the "ante"
  payAntes(gs);

  if (gs.ante){
    logger.log('debug', 'Players have pay the ante amount. Pot is %d.', gs.pot, { tag: gs.handUniqueId });
  }

  // make the players next to the dealer button
  // pay small/big blind amount
  payBlinds(gs);

  logger.log('debug', 'Blinds were payed. Pot is %d; Minimum amount to play is %d.', gs.pot, gs.callAmount, { tag: gs.handUniqueId });

  // assign two private cards to each active player
  assignCards(gs);

  const logMessage = gs.players.reduce(function(msg, player) {
    msg += player.status == playerStatus.active ?
      `${player.name} has ${player.cards.reduce(function(all, card){ all += `${card.rank}${card.type}, `; return all; }, '').trim().slice(0,-1)}. ` : `${player.name} is out. `;
    return msg;
  }, '');

  logger.log('debug', logMessage.trim(), { tag: gs.handUniqueId });

}
<|endoftext|>


<commit_before>var _ = require('underscore'),
    cssExplain = require('css-explain').cssExplain,
    cssRuleNameByType = {
        1: 'style',
        3: 'import',
        4: 'media',
        5: 'font-face',
        6: 'page',
        8: 'webkit-keyframes',
        9: 'webkit-keyframe'
    };

module.exports = function (queryObj, notepad) {
    notepad = notepad || {};
    notepad.css = notepad.css || {};
    notepad.css.numStyleDeclarationsByProperty = {};
    notepad.css.sumOfSelectorComplexity = 0;
    notepad.css.numStyleDeclarations = 0;
    var numCssRulesByType = notepad.css.numCssRulesByType = {},
        numStyleDeclarationsByPropertyName = notepad.css.numStyleDeclarationsByPropertyName = {};
    return function (assetGraph) {
        assetGraph.findAssets(_.extend({type: 'Css'}, queryObj)).forEach(function (cssAsset) {
            cssAsset.eachRuleInParseTree(function (cssRule) {
                var cssRuleName = cssRuleNameByType[cssRule.type];
                numCssRulesByType[cssRuleName] = (numCssRulesByType[cssRuleName] || 0) + 1;
                if (cssRuleName === 'style') {
                    var cssExplanation = cssExplain(cssRule.selectorText);
                    notepad.css.sumOfSelectorComplexity += cssExplanation.score;
                    notepad.css.numStyleDeclarations += cssRule.style.length;
                    for (var i = 0 ; i < cssRule.style.length ; i += 1) {
                        notepad.css.numStyleDeclarations += 1;
                        notepad.css.numStyleDeclarationsByProperty[cssRule.style[i]] = (notepad.css.numStyleDeclarationsByProperty[cssRule.style[i]] || 0) + 1;
                    }
                }
            });
        });
    };
};
<commit_msg>measureCssComplexity: Skip unloaded assets.<commit_after>var _ = require('underscore'),
    cssExplain = require('css-explain').cssExplain,
    cssRuleNameByType = {
        1: 'style',
        3: 'import',
        4: 'media',
        5: 'font-face',
        6: 'page',
        8: 'webkit-keyframes',
        9: 'webkit-keyframe'
    };

module.exports = function (queryObj, notepad) {
    notepad = notepad || {};
    notepad.css = notepad.css || {};
    notepad.css.numStyleDeclarationsByProperty = {};
    notepad.css.sumOfSelectorComplexity = 0;
    notepad.css.numStyleDeclarations = 0;
    var numCssRulesByType = notepad.css.numCssRulesByType = {},
        numStyleDeclarationsByPropertyName = notepad.css.numStyleDeclarationsByPropertyName = {};
    return function (assetGraph) {
        assetGraph.findAssets(_.extend({type: 'Css', isLoaded: true}, queryObj)).forEach(function (cssAsset) {
            cssAsset.eachRuleInParseTree(function (cssRule) {
                var cssRuleName = cssRuleNameByType[cssRule.type];
                numCssRulesByType[cssRuleName] = (numCssRulesByType[cssRuleName] || 0) + 1;
                if (cssRuleName === 'style') {
                    var cssExplanation = cssExplain(cssRule.selectorText);
                    notepad.css.sumOfSelectorComplexity += cssExplanation.score;
                    notepad.css.numStyleDeclarations += cssRule.style.length;
                    for (var i = 0 ; i < cssRule.style.length ; i += 1) {
                        notepad.css.numStyleDeclarations += 1;
                        notepad.css.numStyleDeclarationsByProperty[cssRule.style[i]] = (notepad.css.numStyleDeclarationsByProperty[cssRule.style[i]] || 0) + 1;
                    }
                }
            });
        });
    };
};
<|endoftext|>


<commit_before>/*!
 * Universidad Industrial de Santander
 * Grupo de Desarrollo de Software Calumet
 * Realtime | Libraries | Rubi
 * Romel Pérez, prhone.blogspot.com
 * 2015
 **/

var rubi = require('mongoose');
var debug = require('debug')('libs:rubi');
var config = require('../config');

// -------------------------------------------------------------------------- //
// COLLECTIONS :: PORTAL //

// Usuarios.
var UsersSchema = rubi.Schema({
  _id: String,
  codEst: Number,
  codPos: Number,
  codProf: Number,
  active: Boolean,  // es un usuario activo
  admin: Boolean,  // es un administrador
  name: String,
  photo: String,
  ip: String,  // última ip conectada
  time: Date,  // último login
  devices: [{
    _id: String,  // socket
    agent: String  // el user-agent del navegador
  }]
}, {
  collection: 'users'
});
var UsersModel = rubi.model('users', UsersSchema);

// Mensajes.
var MessagesSchema = rubi.Schema({
  type: String,  // persistent | instant
  publishedBy: String,  // user id
  startDate: Date,  // mostrar desde cuando
  endDate: Date,  // hasta cuando
  message: String
}, {
  collection: 'messages'
});
var MessagesModel = rubi.model('messages', MessagesSchema);

// -------------------------------------------------------------------------- //
// COLLECTIONS :: AULACHAT //

// Classes.
var AC_ClassesSchema = rubi.Schema({
  subject: String,  // código de materia
  group: String,  // grupo
  guion: String,  // guión del aula
  teacher: String,
  students: [String],
  subgroups: [{
    _id: String,  // código del subgrupo del aula
    students: [String]  // estudiantes del subgrupo
  }]
}, {
  collection: 'ac_classes'
});
var AC_ClassesModel = rubi.model('ac_classes', AC_ClassesSchema);

// Rooms.
// NOTE: En el desarrollo de una versión futura, se tendrá la opción de crear
// salas de chat con otros usuarios de un aula, por lo tanto, esta estructura
// puede ser actualizada o en el peor caso, agregada una nueva.
var AC_RoomsSchema = rubi.Schema({
  _id: String,  // nombre de la sala: MATERIA_GRUPO(_SUBGRUPO)
  available: Boolean,  // si se puede chatear o no (en caso de exámen o quiz)
  teacher: {  // si hay profesor en la sala (en caso contrario, strings vacíos)
    _id: String,
    socket: String,  // identificador del socket de conexión
    state: String  // el estado: available | offline
  },
  students: [{  // los estudiantes de la sala
    _id: String,
    socket: String,  // identificador del socket de conexión
    state: String  // el estado: available | offline
  }],
  messages: [{
    _id: Date,  // datetime de publicación
    user: String,
    content: String  // contenido de la publicación
  }]
}, {
  collection: 'ac_rooms'
});
var AC_RoomsModel = rubi.model('ac_rooms', AC_RoomsSchema);

// -------------------------------------------------------------------------- //
// PUBLIC //

var controller = {

  // Mongoose.
  db: rubi,

  // Modelo de usuarios.
  users: UsersModel,

  // Modelo de mensajes.
  messages: MessagesModel,

  // Modelo de clases del aula.
  ac_classes: AC_ClassesModel,

  // Modelo de salas de chat del aula.
  ac_rooms: AC_RoomsModel,

  // Conectarse.
  connect: function (callback) {

    // Error al conectarse.
    rubi.connection.on('error', function (err) {
      callback(err);
      debug(err);
    });

    // Cuando esté conectado.
    rubi.connection.once('open', callback);

    // Conectarse a la db.
    rubi.connect('mongodb://'+ config.mongodb.host +':'+ config.mongodb.port
    + '/' + config.mongodb.db, {
      user: config.mongodb.user,
      pass: config.mongodb.pass,
      server: {socketOptions: {keepAlive: 1}},
      replset: {socketOptions: {keepAlive: 1}}
    });

    return this;
  },

  // Desconectarse.
  disconnect: function (callback) {
    rubi.disconnect(function (err) {
      if (err) {
        if (callback) callback(err);
        debug(err);
      } else {
        if (callback) callback();
      }
    });
    return this;
  }

};

// Hacer público el controlador.
module.exports = exports = controller;
<commit_msg>update: agregando propiedad type a a ac_rooms scheme<commit_after>/*!
 * Universidad Industrial de Santander
 * Grupo de Desarrollo de Software Calumet
 * Realtime | Libraries | Rubi
 * Romel Pérez, prhone.blogspot.com
 * 2015
 **/

var rubi = require('mongoose');
var debug = require('debug')('libs:rubi');
var config = require('../config');

// -------------------------------------------------------------------------- //
// COLLECTIONS :: PORTAL //

// Usuarios.
var UsersSchema = rubi.Schema({
  _id: String,
  codEst: Number,
  codPos: Number,
  codProf: Number,
  active: Boolean,  // es un usuario activo
  admin: Boolean,  // es un administrador
  name: String,
  photo: String,
  ip: String,  // última ip conectada
  time: Date,  // último login
  devices: [{
    _id: String,  // socket
    agent: String  // el user-agent del navegador
  }]
}, {
  collection: 'users'
});
var UsersModel = rubi.model('users', UsersSchema);

// Mensajes.
var MessagesSchema = rubi.Schema({
  type: String,  // persistent | instant
  publishedBy: String,  // user id
  startDate: Date,  // mostrar desde cuando
  endDate: Date,  // hasta cuando
  message: String
}, {
  collection: 'messages'
});
var MessagesModel = rubi.model('messages', MessagesSchema);

// -------------------------------------------------------------------------- //
// COLLECTIONS :: AULACHAT //

// Classes.
var AC_ClassesSchema = rubi.Schema({
  subject: String,  // código de materia
  group: String,  // grupo
  guion: String,  // guión del aula
  teacher: String,
  students: [String],
  subgroups: [{
    _id: String,  // código del subgrupo del aula
    students: [String]  // estudiantes del subgrupo
  }]
}, {
  collection: 'ac_classes'
});
var AC_ClassesModel = rubi.model('ac_classes', AC_ClassesSchema);

// Rooms.
// NOTE: En el desarrollo de una versión futura, se tendrá la opción de crear
// salas de chat con otros usuarios de un aula, por lo tanto, esta estructura
// puede ser actualizada o en el peor caso, agregada una nueva.
var AC_RoomsSchema = rubi.Schema({
  _id: String,  // nombre de la sala: MATERIA_GRUPO(_SUBGRUPO)
  type: String,  // tipo de sala: class | subgroup
  available: Boolean,  // si se puede chatear o no (en caso de exámen o quiz)
  teacher: {  // si hay profesor en la sala (en caso contrario, strings vacíos)
    _id: String,
    socket: String,  // identificador del socket de conexión
    state: String  // el estado: available | offline
  },
  students: [{  // los estudiantes de la sala
    _id: String,
    socket: String,  // identificador del socket de conexión
    state: String  // el estado: available | offline
  }],
  messages: [{
    _id: Date,  // datetime de publicación
    user: String,
    content: String  // contenido de la publicación
  }]
}, {
  collection: 'ac_rooms'
});
var AC_RoomsModel = rubi.model('ac_rooms', AC_RoomsSchema);

// -------------------------------------------------------------------------- //
// PUBLIC //

var controller = {

  // Mongoose.
  db: rubi,

  // Modelo de usuarios.
  users: UsersModel,

  // Modelo de mensajes.
  messages: MessagesModel,

  // Modelo de clases del aula.
  ac_classes: AC_ClassesModel,

  // Modelo de salas de chat del aula.
  ac_rooms: AC_RoomsModel,

  // Conectarse.
  connect: function (callback) {

    // Error al conectarse.
    rubi.connection.on('error', function (err) {
      callback(err);
      debug(err);
    });

    // Cuando esté conectado.
    rubi.connection.once('open', callback);

    // Conectarse a la db.
    rubi.connect('mongodb://'+ config.mongodb.host +':'+ config.mongodb.port
    + '/' + config.mongodb.db, {
      user: config.mongodb.user,
      pass: config.mongodb.pass,
      server: {socketOptions: {keepAlive: 1}},
      replset: {socketOptions: {keepAlive: 1}}
    });

    return this;
  },

  // Desconectarse.
  disconnect: function (callback) {
    rubi.disconnect(function (err) {
      if (err) {
        if (callback) callback(err);
        debug(err);
      } else {
        if (callback) callback();
      }
    });
    return this;
  }

};

// Hacer público el controlador.
module.exports = exports = controller;
<|endoftext|>


<commit_before>var watch = require('node-watch');
var hs = require('http-server');
var childProcess = require('child_process');
var bluebird = require('bluebird');
var mkdirp = bluebird.promisify(require('mkdirp'));
var fs = bluebird.promisifyAll(require('fs'));
var build = require('./build');
var PouchDB = require('pouchdb');
PouchDB.plugin(require('pouchdb-load'));

var promiseChain = Promise.resolve();

async function startPouchServer() {
  await mkdirp('db');

  var child = childProcess.spawn(
    '../node_modules/.bin/pouchdb-server',
    ['-p', '6984'], {
      cwd: 'db'
    }
  );
  child.stdout.on('data', function (data) {
    console.log(data.toString('utf-8'));
  });
  child.stderr.on('data', function (data) {
    console.error(data.toString('utf-8'));
  });
}

async function doIt() {

  startPouchServer();

  // wait for pouch server to start
  await new Promise(function (resolve) { setTimeout(resolve, 1000); });

  // dump monsters.txt
  var monstersDB = new PouchDB('http://localhost:6984/monsters');
  var monstersFullFatDB = new PouchDB('http://localhost:6984/monsters-fullfat');
  var descriptionsDB = new PouchDB('http://localhost:6984/descriptions');
  var evolutionsDB = new PouchDB('http://localhost:6984/evolutions');
  var typesDB = new PouchDB('http://localhost:6984/types');
  var movesDB = new PouchDB('http://localhost:6984/moves');
  var monsterMovesDB = new PouchDB('http://localhost:6984/monster-moves');
  var monstersSupplementalDB = new PouchDB('http://localhost:6984/monsters-supplemental');

  var loadPromises = [
    monstersDB.load(await fs.readFileAsync('src/assets/skim-monsters.txt', 'utf-8')),
    descriptionsDB.load(await fs.readFileAsync('src/assets/descriptions.txt', 'utf-8')),
    evolutionsDB.load(await fs.readFileAsync('src/assets/evolutions.txt', 'utf-8')),
    typesDB.load(await fs.readFileAsync('src/assets/types.txt', 'utf-8')),
    movesDB.load(await fs.readFileAsync('src/assets/moves.txt', 'utf-8')),
    monstersFullFatDB.load(await fs.readFileAsync('src/assets/monsters.txt', 'utf-8')),
    monsterMovesDB.load(await fs.readFileAsync('src/assets/monster-moves.txt', 'utf-8')),
    monstersSupplementalDB.load(await fs.readFileAsync('src/assets/monsters-supplemental.txt', 'utf-8'))
  ];

  // build with debug=true
  var buildPromise = build(true);

  // start up dev server
  var serverPromise = new Promise(function (resolve, reject) {
    hs.createServer({root: './www'}).listen(9000, function (err) {
      if (err) {
        return reject(err);
      }
      resolve();
    });
  });

  var allPromises = [...loadPromises, buildPromise, serverPromise];

  // do one at a time to avoid hammering pouchdb-server too hard
  for (var promise of allPromises) {
    await promise;
  }

  console.log('started dev server at http://127.0.0.1:9000');

  watch(__dirname + '/../src', () => {
    promiseChain = promiseChain.then(() => build(true));
  });
}

doIt().catch(err => console.error(err));

process.on('unhandledRejection', err => {
  console.error(err.stack);
});<commit_msg>(#22) - use abs path for pouchdb-server in `npm run serve`<commit_after>var watch = require('node-watch');
var hs = require('http-server');
var childProcess = require('child_process');
var bluebird = require('bluebird');
var mkdirp = bluebird.promisify(require('mkdirp'));
var fs = bluebird.promisifyAll(require('fs'));
var build = require('./build');
var PouchDB = require('pouchdb');
PouchDB.plugin(require('pouchdb-load'));

var promiseChain = Promise.resolve();

async function startPouchServer() {
  await mkdirp('db');

  var child = childProcess.spawn(
    __dirname + '/../node_modules/.bin/pouchdb-server',
    ['-p', '6984'], {
      cwd: 'db'
    }
  );
  child.stdout.on('data', function (data) {
    console.log(data.toString('utf-8'));
  });
  child.stderr.on('data', function (data) {
    console.error(data.toString('utf-8'));
  });
}

async function doIt() {

  startPouchServer();

  // wait for pouch server to start
  await new Promise(function (resolve) { setTimeout(resolve, 1000); });

  // dump monsters.txt
  var monstersDB = new PouchDB('http://localhost:6984/monsters');
  var monstersFullFatDB = new PouchDB('http://localhost:6984/monsters-fullfat');
  var descriptionsDB = new PouchDB('http://localhost:6984/descriptions');
  var evolutionsDB = new PouchDB('http://localhost:6984/evolutions');
  var typesDB = new PouchDB('http://localhost:6984/types');
  var movesDB = new PouchDB('http://localhost:6984/moves');
  var monsterMovesDB = new PouchDB('http://localhost:6984/monster-moves');
  var monstersSupplementalDB = new PouchDB('http://localhost:6984/monsters-supplemental');

  var loadPromises = [
    monstersDB.load(await fs.readFileAsync('src/assets/skim-monsters.txt', 'utf-8')),
    descriptionsDB.load(await fs.readFileAsync('src/assets/descriptions.txt', 'utf-8')),
    evolutionsDB.load(await fs.readFileAsync('src/assets/evolutions.txt', 'utf-8')),
    typesDB.load(await fs.readFileAsync('src/assets/types.txt', 'utf-8')),
    movesDB.load(await fs.readFileAsync('src/assets/moves.txt', 'utf-8')),
    monstersFullFatDB.load(await fs.readFileAsync('src/assets/monsters.txt', 'utf-8')),
    monsterMovesDB.load(await fs.readFileAsync('src/assets/monster-moves.txt', 'utf-8')),
    monstersSupplementalDB.load(await fs.readFileAsync('src/assets/monsters-supplemental.txt', 'utf-8'))
  ];

  // build with debug=true
  var buildPromise = build(true);

  // start up dev server
  var serverPromise = new Promise(function (resolve, reject) {
    hs.createServer({root: './www'}).listen(9000, function (err) {
      if (err) {
        return reject(err);
      }
      resolve();
    });
  });

  var allPromises = [...loadPromises, buildPromise, serverPromise];

  // do one at a time to avoid hammering pouchdb-server too hard
  for (var promise of allPromises) {
    await promise;
  }

  console.log('started dev server at http://127.0.0.1:9000');

  watch(__dirname + '/../src', () => {
    promiseChain = promiseChain.then(() => build(true));
  });
}

doIt().catch(err => console.error(err));

process.on('unhandledRejection', err => {
  console.error(err.stack);
});
<|endoftext|>


<commit_before>/** base namespace for all DOAJ-specific functions */
var doaj = {
    bitlyShortener : function(query, success_callback, error_callback) {

        function callbackWrapper(data) {
            success_callback(data.url);
        }

        function errorHandler() {
            alert("Sorry, we're unable to generate short urls at this time");
            error_callback();
        }

        var page = window.location.protocol + '//' + window.location.host + window.location.pathname;

        $.ajax({
            type: "POST",
            contentType: "application/json",
            dataType: "jsonp",
            url: "/service/shorten",
            data : JSON.stringify({page: page, query: query}),
            success: callbackWrapper,
            error: errorHandler
        });
    },

    journal_toc_id : function(journal) {
        // if e-issn is available, use that
        // if not, but a p-issn is available, use that
        // if neither ISSN is available, use the internal ID
        var ids = journal.bibjson.identifier;
        var pissns = [];
        var eissns = [];
        if (ids) {
            for (var i = 0; i < ids.length; i++) {
                if (ids[i].type === "pissn") {
                    pissns.push(ids[i].id)
                } else if (ids[i].type === "eissn") {
                    eissns.push(ids[i].id)
                }
            }
        }

        var toc_id = undefined;
        if (eissns.length > 0) { toc_id = eissns[0]; }
        if (!toc_id && pissns.length > 0) { toc_id = pissns[0]; }
        if (!toc_id) { toc_id = journal.id; }

        return toc_id;
    },

    monthmap : [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"
    ],

    licenceMap : {
        "CC BY" : ["/static/doaj/images/cc/by.png", "https://creativecommons.org/licenses/by/4.0/"],
        "CC BY-NC" : ["/static/doaj/images/cc/by-nc.png", "https://creativecommons.org/licenses/by-nc/4.0/"],
        "CC BY-NC-ND" : ["/static/doaj/images/cc/by-nc-nd.png", "https://creativecommons.org/licenses/by-nc-nd/4.0/"],
        "CC BY-NC-SA" : ["/static/doaj/images/cc/by-nc-sa.png", "https://creativecommons.org/licenses/by-nc-sa/4.0/"],
        "CC BY-ND" : ["/static/doaj/images/cc/by-nd.png", "https://creativecommons.org/licenses/by-nd/4.0/"],
        "CC BY-SA" : ["/static/doaj/images/cc/by-sa.png", "https://creativecommons.org/licenses/by-sa/4.0/"]
    },

    humanYearMonth : function(datestr) {
        var date = new Date(datestr);
        var monthnum = date.getUTCMonth();
        var year = date.getUTCFullYear();

        return doaj.monthmap[monthnum] + " " + String(year);
    },

    humanDate : function(datestr) {
        var date = new Date(datestr);
        var dom = date.getUTCDate();
        var monthnum = date.getUTCMonth();
        var year = date.getUTCFullYear();

        return String(dom) + " " + doaj.monthmap[monthnum] + " " + String(year);
    },

    humanDateTime : function(datestr) {
        var date = new Date(datestr);
        var dom = date.getUTCDate();
        var monthnum = date.getUTCMonth();
        var year = date.getUTCFullYear();
        var hour = date.getUTCHours();
        var minute = date.getUTCMinutes();

        if (String(hour).length === 1) {
            hour = "0" + String(hour);
        }

        if (String(minute).length === 1) {
            minute = "0" + String(minute);
        }

        return String(dom) + " " + doaj.monthmap[monthnum] + " " + String(year) + " at " + String(hour) + ":" + String(minute);
    },

    iso_datetime2date : function(isodate_str) {
        /* >>> '2003-04-03T00:00:00Z'.substring(0,10)
         * "2003-04-03"
         */
        return isodate_str.substring(0,10);
    },

    iso_datetime2date_and_time : function(isodate_str) {
        /* >>> "2013-12-13T22:35:42Z".replace('T',' ').replace('Z','')
         * "2013-12-13 22:35:42"
         */
        if (!isodate_str) { return "" }
        return isodate_str.replace('T',' ').replace('Z','')
    }
};

jQuery(document).ready(function() {
    $.noop(); // just a placeholder, delete when adding code here
});

function setCookieConsent(event) {
    event.preventDefault();
    $.ajax({
        type: "GET",
        url: "/cookie_consent",
        success: function() {
            $("#cookie-consent-banner").remove();
        },
        error : function() {
            alert("We weren't able to set your cookie consent preferences, please try again later.");
        }
    })
}<commit_msg>fix removal of cookie consent banner<commit_after>/** base namespace for all DOAJ-specific functions */
var doaj = {
    bitlyShortener : function(query, success_callback, error_callback) {

        function callbackWrapper(data) {
            success_callback(data.url);
        }

        function errorHandler() {
            alert("Sorry, we're unable to generate short urls at this time");
            error_callback();
        }

        var page = window.location.protocol + '//' + window.location.host + window.location.pathname;

        $.ajax({
            type: "POST",
            contentType: "application/json",
            dataType: "jsonp",
            url: "/service/shorten",
            data : JSON.stringify({page: page, query: query}),
            success: callbackWrapper,
            error: errorHandler
        });
    },

    journal_toc_id : function(journal) {
        // if e-issn is available, use that
        // if not, but a p-issn is available, use that
        // if neither ISSN is available, use the internal ID
        var ids = journal.bibjson.identifier;
        var pissns = [];
        var eissns = [];
        if (ids) {
            for (var i = 0; i < ids.length; i++) {
                if (ids[i].type === "pissn") {
                    pissns.push(ids[i].id)
                } else if (ids[i].type === "eissn") {
                    eissns.push(ids[i].id)
                }
            }
        }

        var toc_id = undefined;
        if (eissns.length > 0) { toc_id = eissns[0]; }
        if (!toc_id && pissns.length > 0) { toc_id = pissns[0]; }
        if (!toc_id) { toc_id = journal.id; }

        return toc_id;
    },

    monthmap : [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"
    ],

    licenceMap : {
        "CC BY" : ["/static/doaj/images/cc/by.png", "https://creativecommons.org/licenses/by/4.0/"],
        "CC BY-NC" : ["/static/doaj/images/cc/by-nc.png", "https://creativecommons.org/licenses/by-nc/4.0/"],
        "CC BY-NC-ND" : ["/static/doaj/images/cc/by-nc-nd.png", "https://creativecommons.org/licenses/by-nc-nd/4.0/"],
        "CC BY-NC-SA" : ["/static/doaj/images/cc/by-nc-sa.png", "https://creativecommons.org/licenses/by-nc-sa/4.0/"],
        "CC BY-ND" : ["/static/doaj/images/cc/by-nd.png", "https://creativecommons.org/licenses/by-nd/4.0/"],
        "CC BY-SA" : ["/static/doaj/images/cc/by-sa.png", "https://creativecommons.org/licenses/by-sa/4.0/"]
    },

    humanYearMonth : function(datestr) {
        var date = new Date(datestr);
        var monthnum = date.getUTCMonth();
        var year = date.getUTCFullYear();

        return doaj.monthmap[monthnum] + " " + String(year);
    },

    humanDate : function(datestr) {
        var date = new Date(datestr);
        var dom = date.getUTCDate();
        var monthnum = date.getUTCMonth();
        var year = date.getUTCFullYear();

        return String(dom) + " " + doaj.monthmap[monthnum] + " " + String(year);
    },

    humanDateTime : function(datestr) {
        var date = new Date(datestr);
        var dom = date.getUTCDate();
        var monthnum = date.getUTCMonth();
        var year = date.getUTCFullYear();
        var hour = date.getUTCHours();
        var minute = date.getUTCMinutes();

        if (String(hour).length === 1) {
            hour = "0" + String(hour);
        }

        if (String(minute).length === 1) {
            minute = "0" + String(minute);
        }

        return String(dom) + " " + doaj.monthmap[monthnum] + " " + String(year) + " at " + String(hour) + ":" + String(minute);
    },

    iso_datetime2date : function(isodate_str) {
        /* >>> '2003-04-03T00:00:00Z'.substring(0,10)
         * "2003-04-03"
         */
        return isodate_str.substring(0,10);
    },

    iso_datetime2date_and_time : function(isodate_str) {
        /* >>> "2013-12-13T22:35:42Z".replace('T',' ').replace('Z','')
         * "2013-12-13 22:35:42"
         */
        if (!isodate_str) { return "" }
        return isodate_str.replace('T',' ').replace('Z','')
    }
};

jQuery(document).ready(function() {
    $.noop(); // just a placeholder, delete when adding code here
});

function setCookieConsent(event) {
    event.preventDefault();
    $.ajax({
        type: "GET",
        url: "/cookie_consent",
        success: function() {
            $("#cookie-consent").remove();
        },
        error : function() {
            alert("We weren't able to set your cookie consent preferences, please try again later.");
        }
    })
}<|endoftext|>


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

/**
 * Module dependencies.
 */

var exec = require('child_process').exec;
var mustache = require('mustache');
var program = require('commander');
var assert = require('assert');
var mkdir = require('mkdirp');
var path = require('path');
var fs = require('fs');
var join = path.join;

/**
 * Options.
 */

var pkg = fs.readFileSync(__dirname + '/../package.json', 'utf-8');
var version = JSON.parse(pkg).version;
program.name = 'initialize';
program.version(version);

program.usage('<dirname>')
//program.option('-k, --keyword <tag>', 'add a keyword to package.json');
//program.option('-d, --description <sentence>', 'add a description');
program.parse(process.argv);

/**
 * Check for errors.
 */

var packageName = process.argv[2];
if (!packageName) throwErr('Please specify a package name. Type \'initialize -h\' to see all options.');

/**
 * Set config
 *
 * Provides us with the following value:
 *  - name
 *  - username
 *  - email
 *  - url
 *  - year
 *  - month
 *  - date
 */

console.log('');
console.log('configuration');
var pending = 1;
var config = {};

exec('npm whoami', function(err, name) {
  assert.ifError(err);
  config.name = name.replace(/(\n)/gm, '');
  console.log('  user: ' + config.name);
  if (!--pending) done(null);
});

function done() {
  getConfig();
  createDir();
  writeFiles();
  installDeps();
  initGit();
}

/**
 * Get configuration.
 */

function getConfig() {
  var date = new Date();
  var day = date.getDate();
  var month = date.getMonth();

  config.year = date.getFullYear();
  config.day = 2 == day.toString().length ? day : '0' + day;
  config.month = 2 == month.toString().length ? month : '0' + month;

  config.packageName = packageName;
  console.log('  packageName: ' + config.packageName);

  config.date = config.year + '-' + config.month + '-' + config.day;
  console.log('  date: ' + config.date);
}

/**
 * Create directory.
 */

function createDir() {
  mkdir.sync(packageName);
  process.chdir(packageName);
}

/**
 * Initialize git repo.
 */

function initGit() {
  exec('git init --quiet', function(err) {
    assert.ifError(err);
  });
}

/**
 * Write files.
 */

function writeFiles() {
  console.log('');
  console.log('files');
  write('./.editorconfig', fs.readFileSync(__dirname + '/../templates/editorconfig', 'utf-8'));
  write('./.eslintrc', fs.readFileSync(__dirname + '/../templates/eslintrc', 'utf-8'));
  write('./.gitignore', fs.readFileSync(__dirname + '/../templates/gitignore', 'utf-8'));
  write('./.travis.yml', fs.readFileSync(__dirname + '/../templates/travis.yml', 'utf-8'));
  write('./index.js', fs.readFileSync(__dirname + '/../templates/index.js', 'utf-8'));
  write('./LICENSE', fs.readFileSync(__dirname + '/../templates/LICENSE', 'utf-8'));
  write('./README.md', fs.readFileSync(__dirname + '/../templates/README.md', 'utf-8'));
  write('./package.json', fs.readFileSync(__dirname + '/../templates/package', 'utf-8'));
  write('./test.js', fs.readFileSync(__dirname + '/../templates/test.js', 'utf-8'));
}

/**
 * Install dependencies.
 */

function installDeps() {
  console.log('');
  console.log('dependencies');

  exec('npm i --save-dev tape', function(err) {
    console.log('  module: tape');
    assert.ifError(err);
  });

  exec('npm i --save-dev tape-spec', function(err) {
    console.log('  module: tap-spec');
    assert.ifError(err);
  });

  exec('npm i --save-dev eslint', function(err) {
    console.log('  module: eslint');
    assert.ifError(err);
  });

  exec('npm i --save-dev istanbul', function(err) {
    console.log('  module: istanbul');
    assert.ifError(err);
  });
}

/**
 * Echo str > path.
 *
 * @param {String} path
 * @param {String} str
 * @api private
 */

function write(path, str) {
  var mt = mustache.render(str, config);
  console.log('  file: ' + path.split('./')[1]);
  fs.writeFileSync(path, mt, {mode: 0666}, function(err) {
    if (err) throwErr(err);
    console.log('   \x1b[36mcreate\x1b[0m : ' + path);
  });
}

/**
 * Throw err.
 *
 * @param {Any} msg
 * @api private
 */

function throwErr(msg) {
  console.error(msg);
  process.exit(1);
}
<commit_msg>tap: fix<commit_after>#!/usr/bin/env node

/**
 * Module dependencies.
 */

var exec = require('child_process').exec;
var mustache = require('mustache');
var program = require('commander');
var assert = require('assert');
var mkdir = require('mkdirp');
var path = require('path');
var fs = require('fs');
var join = path.join;

/**
 * Options.
 */

var pkg = fs.readFileSync(__dirname + '/../package.json', 'utf-8');
var version = JSON.parse(pkg).version;
program.name = 'initialize';
program.version(version);

program.usage('<dirname>')
//program.option('-k, --keyword <tag>', 'add a keyword to package.json');
//program.option('-d, --description <sentence>', 'add a description');
program.parse(process.argv);

/**
 * Check for errors.
 */

var packageName = process.argv[2];
if (!packageName) throwErr('Please specify a package name. Type \'initialize -h\' to see all options.');

/**
 * Set config
 *
 * Provides us with the following value:
 *  - name
 *  - username
 *  - email
 *  - url
 *  - year
 *  - month
 *  - date
 */

console.log('');
console.log('configuration');
var pending = 1;
var config = {};

exec('npm whoami', function(err, name) {
  assert.ifError(err);
  config.name = name.replace(/(\n)/gm, '');
  console.log('  user: ' + config.name);
  if (!--pending) done(null);
});

function done() {
  getConfig();
  createDir();
  writeFiles();
  installDeps();
  initGit();
}

/**
 * Get configuration.
 */

function getConfig() {
  var date = new Date();
  var day = date.getDate();
  var month = date.getMonth();

  config.year = date.getFullYear();
  config.day = 2 == day.toString().length ? day : '0' + day;
  config.month = 2 == month.toString().length ? month : '0' + month;

  config.packageName = packageName;
  console.log('  packageName: ' + config.packageName);

  config.date = config.year + '-' + config.month + '-' + config.day;
  console.log('  date: ' + config.date);
}

/**
 * Create directory.
 */

function createDir() {
  mkdir.sync(packageName);
  process.chdir(packageName);
}

/**
 * Initialize git repo.
 */

function initGit() {
  exec('git init --quiet', function(err) {
    assert.ifError(err);
  });
}

/**
 * Write files.
 */

function writeFiles() {
  console.log('');
  console.log('files');
  write('./.editorconfig', fs.readFileSync(__dirname + '/../templates/editorconfig', 'utf-8'));
  write('./.eslintrc', fs.readFileSync(__dirname + '/../templates/eslintrc', 'utf-8'));
  write('./.gitignore', fs.readFileSync(__dirname + '/../templates/gitignore', 'utf-8'));
  write('./.travis.yml', fs.readFileSync(__dirname + '/../templates/travis.yml', 'utf-8'));
  write('./index.js', fs.readFileSync(__dirname + '/../templates/index.js', 'utf-8'));
  write('./LICENSE', fs.readFileSync(__dirname + '/../templates/LICENSE', 'utf-8'));
  write('./README.md', fs.readFileSync(__dirname + '/../templates/README.md', 'utf-8'));
  write('./package.json', fs.readFileSync(__dirname + '/../templates/package', 'utf-8'));
  write('./test.js', fs.readFileSync(__dirname + '/../templates/test.js', 'utf-8'));
}

/**
 * Install dependencies.
 */

function installDeps() {
  console.log('');
  console.log('dependencies');

  exec('npm i --save-dev tape', function(err) {
    console.log('  module: tape');
    assert.ifError(err);
  });

  exec('npm i --save-dev tap-spec', function(err) {
    console.log('  module: tap-spec');
    assert.ifError(err);
  });

  exec('npm i --save-dev eslint', function(err) {
    console.log('  module: eslint');
    assert.ifError(err);
  });

  exec('npm i --save-dev istanbul', function(err) {
    console.log('  module: istanbul');
    assert.ifError(err);
  });
}

/**
 * Echo str > path.
 *
 * @param {String} path
 * @param {String} str
 * @api private
 */

function write(path, str) {
  var mt = mustache.render(str, config);
  console.log('  file: ' + path.split('./')[1]);
  fs.writeFileSync(path, mt, {mode: 0666}, function(err) {
    if (err) throwErr(err);
    console.log('   \x1b[36mcreate\x1b[0m : ' + path);
  });
}

/**
 * Throw err.
 *
 * @param {Any} msg
 * @api private
 */

function throwErr(msg) {
  console.error(msg);
  process.exit(1);
}
<|endoftext|>


<commit_before>/* eslint-disable no-underscore-dangle */

const Mongo = require("mongodb").MongoClient;

let db;

const config = {
  moduleName: "mongo",
  enabled: true,
  dbName: "Komada",
  dbURL: "mongodb://localhost:27017/",
};

exports.init = async () => {
  try {
    db = await Mongo.connect(`${config.dbURL}${config.dbName}`);
  } catch (err) { console.log(err); }
};

const resolveQuery = query => (query instanceof Object ? query : { id: query });

// Collection Methods. Collections are implicitly created with document methods regardess.

/**
 * Create a collection within a DB. Options may be specfied, refer to MongoDB docs.
 * @param {string} name Name of the Collection to crate
 * @param {Object} [options] Object containing various options for the created Collection
 * @returns {Promise<Collection>} Returns a promise containing the created Collection.
 */
exports.createCollection = (name, options = {}) => db.createCollection(name, options);
exports.createTable = (...args) => this.createCollection(...args);
exports.hasTable = () => true;

/**
 * Drops a collection within a DB.
 * @param {string} name Name of the collection to drop.
 * @returns {Promise<boolean>}
 */
exports.dropCollection = name => db.dropCollection(name);
exports.deleteTable = (...args) => this.dropCollection(...args);

// Document Methods. Update requires MongoDB Update Operators. Be sure to refer to MongoDB documentation.
/**
 * Retrieves all Documents in a collection.
 * @param {string} collection Name of the Collection
 * @returns {Promise<Array>}
 */
exports.getAll = async (collection) => {
  const data = await db.collection(collection).find({}).toArray();
  for (let i = 0; i < data.length; i++) { delete data[i]._id; }
  return data;
};

/**
 * Retrieves a single Document from a Collection that matches a user determined ID
 * @param {string} collection Name of the Collection
 * @param {string} id ID of the document
 * @returns {Promise<?Object>}
 */
exports.get = (collection, id) => db.collection(collection).findOne(resolveQuery(id)); // eslint-disable-line quote-props

exports.has = async (...args) => {
  const results = await this.get(...args);
  if (!results) return false;
  return true;
};

exports.getRandom = async (...args) => {
  const results = await this.getAll(...args);
  return results[Math.floor(Math.random() * results.length)];
};

/**
 * Inserts a Document into a Collection using a user provided object.
 * @param {string} collection Name of the Collection
 * @param {(string|Object)} id ID of the document
 * @param {Object} docObj Document Object to insert
 * @returns {Promise}
 */
exports.insert = (collection, id, docObj) => db.collection(collection).insertOne(Object.assign(docObj, resolveQuery(id)));
exports.create = (...args) => this.insert(...args);
exports.set = (...args) => this.insert(...args);

/**
 * Deletes a Document from a Collection that matches a user determined ID *
 * @param {string} collection Name of the Collection
 * @param {string} id ID of the document
 * @returns {Promise<CommandResult>}
 */
exports.delete = (collection, id) => db.collection(collection).deleteOne(resolveQuery(id));

/**
 * Updates a Document using MongoDB Update Operators. *
 * @param {string} collection Name of the Collection
 * @param {Object} filter The Filter used to select the document to update
 * @param {Object} updateObj The update operations to be applied to the document
 */
exports.update = async (collection, filter, updateObj) => {
  const res = await this.get(collection, filter);
  await db.collection(collection).updateOne(resolveQuery(filter), Object.assign(res, updateObj));
};

/**
 * Replaces a Document with a new Document specified by the user *
 * @param {string} collection Name of the Collection
 * @param {Object} filter The Filter used to select the document to update
 * @param {Object} repDoc The Document that replaces the matching document
 * @returns {Promise<CommandResult>}
 */
exports.replace = (collection, filter, repDoc) => db.collection(collection).replaceOne(resolveQuery(filter), repDoc);

exports.eval = () => db;

exports.help = {
  name: "mongodb",
  type: "providers",
  description: "Allows use of MongoDB functionality throughout Komada.",
};

exports.conf = config;
exports.conf.requiredModules = ["mongodb"];
<commit_msg>Preperation for Mongo DB Driver 3.0.0<commit_after>/* eslint-disable no-underscore-dangle */

const Mongo = require("mongodb").MongoClient;

let db;

const config = {
  moduleName: "mongo",
  enabled: true,
  dbName: "Komada",
  dbURL: "mongodb://localhost:27017/",
};

exports.init = async () => {
  try {
    let client = await Mongo.connect(`${config.dbURL}${config.dbName}`);
    db = await client.db(config.dbName);
  } catch (err) { console.log(err); }
};

const resolveQuery = query => (query instanceof Object ? query : { id: query });

// Collection Methods. Collections are implicitly created with document methods regardess.

/**
 * Create a collection within a DB. Options may be specfied, refer to MongoDB docs.
 * @param {string} name Name of the Collection to crate
 * @param {Object} [options] Object containing various options for the created Collection
 * @returns {Promise<Collection>} Returns a promise containing the created Collection.
 */
exports.createCollection = (name, options = {}) => db.createCollection(name, options);
exports.createTable = (...args) => this.createCollection(...args);
exports.hasTable = () => true;

/**
 * Drops a collection within a DB.
 * @param {string} name Name of the collection to drop.
 * @returns {Promise<boolean>}
 */
exports.dropCollection = name => db.dropCollection(name);
exports.deleteTable = (...args) => this.dropCollection(...args);

// Document Methods. Update requires MongoDB Update Operators. Be sure to refer to MongoDB documentation.
/**
 * Retrieves all Documents in a collection.
 * @param {string} collection Name of the Collection
 * @returns {Promise<Array>}
 */
exports.getAll = async (collection) => {
  const data = await db.collection(collection).find({}).toArray();
  for (let i = 0; i < data.length; i++) { delete data[i]._id; }
  return data;
};

/**
 * Retrieves a single Document from a Collection that matches a user determined ID
 * @param {string} collection Name of the Collection
 * @param {string} id ID of the document
 * @returns {Promise<?Object>}
 */
exports.get = (collection, id) => db.collection(collection).findOne(resolveQuery(id)); // eslint-disable-line quote-props

exports.has = async (...args) => {
  const results = await this.get(...args);
  if (!results) return false;
  return true;
};

exports.getRandom = async (...args) => {
  const results = await this.getAll(...args);
  return results[Math.floor(Math.random() * results.length)];
};

/**
 * Inserts a Document into a Collection using a user provided object.
 * @param {string} collection Name of the Collection
 * @param {(string|Object)} id ID of the document
 * @param {Object} docObj Document Object to insert
 * @returns {Promise}
 */
exports.insert = (collection, id, docObj) => db.collection(collection).insertOne(Object.assign(docObj, resolveQuery(id)));
exports.create = (...args) => this.insert(...args);
exports.set = (...args) => this.insert(...args);

/**
 * Deletes a Document from a Collection that matches a user determined ID *
 * @param {string} collection Name of the Collection
 * @param {string} id ID of the document
 * @returns {Promise<CommandResult>}
 */
exports.delete = (collection, id) => db.collection(collection).deleteOne(resolveQuery(id));

/**
 * Updates a Document using MongoDB Update Operators. *
 * @param {string} collection Name of the Collection
 * @param {Object} filter The Filter used to select the document to update
 * @param {Object} updateObj The update operations to be applied to the document
 */
exports.update = async (collection, filter, updateObj) => {
  const res = await this.get(collection, filter);
  await db.collection(collection).updateOne(resolveQuery(filter), {$set: Object.assign(res, updateObj)});
};

/**
 * Replaces a Document with a new Document specified by the user *
 * @param {string} collection Name of the Collection
 * @param {Object} filter The Filter used to select the document to update
 * @param {Object} repDoc The Document that replaces the matching document
 * @returns {Promise<CommandResult>}
 */
exports.replace = (collection, filter, repDoc) => db.collection(collection).replaceOne(resolveQuery(filter), repDoc);

exports.eval = () => db;

exports.help = {
  name: "mongodb",
  type: "providers",
  description: "Allows use of MongoDB functionality throughout Komada.",
};

exports.conf = config;
exports.conf.requiredModules = ["mongodb"];
<|endoftext|>


<commit_before>(function(){
  var localStorageWrapper = function(name) {
    this.name = name;
    if(!localStorage.getItem(name)) {
      localStorage.setItem(name, "[]");
    }
  }

  localStorageWrapper.prototype.get = function(n) {
    if(n === undefined) {
      return JSON.parse(localStorage.getItem(this.name));
    } else {
      var data = JSON.parse(localStorage.getItem(this.name));
      return data[n];
    }

  }

  localStorageWrapper.prototype.search = function(searchTerm) {
    var wholeArray = JSON.parse(localStorage.getItem(this.name));
    for(var i in wholeArray) {
      if(wholeArray[i][searchTerm]) {
        return wholeArray[i][searchTerm];
      }
    }
    return null;
  }

  localStorageWrapper.prototype.set = function(data) {
    return localStorage.setItem(this.name, JSON.stringify(data));
  }

  localStorageWrapper.prototype.add = function(obj) {
    var data = this.get();
    data.push(obj);
    return this.set(data);
  }

  localStorageWrapper.prototype.remove = function(n) {
    var data = this.get();
    data.splice(n,n);
    return this.set(data);
  }

  localStorageWrapper.prototype.destroy = function() {
    delete localStorage[this.name]
  }

  cdb.admin.localStorage = localStorageWrapper;
}())
<commit_msg>fixed problem when there is no data for that key in local storage<commit_after>(function(){
  var localStorageWrapper = function(name) {
    this.name = name;
    if(!localStorage.getItem(name)) {
      localStorage.setItem(name, "[]");
    }
  }

  localStorageWrapper.prototype.get = function(n) {
    if(n === undefined) {
      return JSON.parse(localStorage.getItem(this.name));
    } else {
      var data = JSON.parse(localStorage.getItem(this.name));
      return data[n];
    }

  }

  localStorageWrapper.prototype.search = function(searchTerm) {
    var wholeArray = JSON.parse(localStorage.getItem(this.name));
    for(var i in wholeArray) {
      if(wholeArray[i][searchTerm]) {
        return wholeArray[i][searchTerm];
      }
    }
    return null;
  }

  localStorageWrapper.prototype.set = function(data) {
    return localStorage.setItem(this.name, JSON.stringify(data));
  }

  localStorageWrapper.prototype.add = function(obj) {
    var data = this.get();
    if(data) {
      data.push(obj);
      return this.set(data);
    }
  }

  localStorageWrapper.prototype.remove = function(n) {
    var data = this.get();
    data.splice(n,n);
    return this.set(data);
  }

  localStorageWrapper.prototype.destroy = function() {
    delete localStorage[this.name]
  }

  cdb.admin.localStorage = localStorageWrapper;
}())
<|endoftext|>


<commit_before>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Andrew Eisenberg - initial API and implementation
 ******************************************************************************/

// implements a zen coding plugin for scripted

/*jslint browser:true */
/*global define emmet prompt scripted */

define(["orion/textview/keyBinding", 'scripted/utils/textUtils', 'orion/editor/editorFeatures',
	'jquery', 'zen'],
	function(mKeyBinding, textUtils, editorFeatures, $) {
	function ZenEditorProxy(editor) {
		this.editor = editor;
	}

	var TAB_POS = "${0}";

	ZenEditorProxy.prototype = {
		init : function() {
			this.editorProxy = this.createProxy(this.editor);
			this.attach(this.editor);
		},
		createProxy: function(editor) {
			return emmet.exec(function(req, _) {
				var res = req('resources');
				var utils = req('utils');
				res.setVariable('indentation', textUtils.indent());
				utils.setNewline('\n');
				console.log("in editor proxy");
				return {
					setContext: function(context) {
						// TODO indentation not working
						var res = req('resources');
						var utils = req('utils');
						res.setVariable('indentation', textUtils.indent());
						utils.setNewline('\n');
					},

					/**
					 * Returns character indexes of selected text: object with start
					 * and end properties. If there's no selection, should return
					 * object with start and end properties referring
					 * to current caret position
					 * @return {Object}
					 * @example
					 * var selection = editor.getSelectionRange();
					 * alert(selection.start + ', ' + selection.end);
					 */
					getSelectionRange: function() {
						return {
							start: editor.getSelection().start,
							end: editor.getSelection().end
						};
					},

					/**
					 * Creates selection from start to end character
					 * indexes. If end is ommited, this method should place caret
					 * and start index
					 * @param {Number} start
					 * @param {Number} [end]
					 * @example
					 * editor.createSelection(10, 40);
					 *
					 * //move caret to 15th character
					 * editor.createSelection(15);
					 */
					createSelection: function(start, end) {
						editor.setSelection(start, end);
					},

					/**
					 * Returns current line's start and end indexes as object with start
					 * and end properties
					 * @return {Object}
					 * @example
					 * var range = editor.getCurrentLineRange();
					 * alert(range.start + ', ' + range.end);
					 */
					getCurrentLineRange: function() {
						var selStart = this.getCaretPos();
						var model = editor.getTextView().getModel();
						var line = model.getLineAtOffset(selStart);

						var result = {
							start: model.getLineStart(line),
							end: model.getLineEnd(line)
						};

						return result;
					},

					/**
					 * Returns current caret position
					 * @return {Number|null}
					 */
					getCaretPos: function() {
						var sel = this.getSelectionRange();
						return Math.min(sel.start, sel.end);
					},
					/**
					 * Set new caret position
					 * @param {Number} pos Caret position
					 */
					setCaretPos: function(pos) {
						this.createSelection(pos, pos);
					},

					/**
					 * Returns content of current line
					 * @return {String}
					 */
					getCurrentLine: function() {
						var range = this.getCurrentLineRange();
						return this.getContent().substring(range.start, range.end);
					},
					/**
					 * Replace editor's content or it's part (from start to
					 * end index). If value contains
					 * caret_placeholder, the editor will put caret into
					 * this position. If you skip start and end
					 * arguments, the whole target's content will be replaced with
					 * value.
					 *
					 * If you pass start argument only,
					 * the value will be placed at start string
					 * index of current content.
					 *
					 * If you pass start and end arguments,
					 * the corresponding substring of current target's content will be
					 * replaced with value.
					 * @param {String} value Content you want to paste
					 * @param {Number} [start] Start index of editor's content
					 * @param {Number} [end] End index of editor's content
					 * @param {Boolean} [no_indent] Do not auto indent value
					 */
					replaceContent: function(value, start, end, noIndent) {

						if (!noIndent) {
							var leading = textUtils.leadingWhitespace(editor.getTextView().getText(), start);
							var regex = new RegExp('\n', "g");
							value = value.replace(regex, "\n" + leading);
						}
						editor.getTextView().setText(value, start, end);

						var pos = value.indexOf(TAB_POS);
						if (pos !== -1) {
							var linkedMode = new editorFeatures.LinkedMode(editor);
							var linkedModeModel = { groups : [] };
							while (pos !== -1) {
								linkedModeModel.groups.push({
									positions : [{
										offset: pos + start,
										length: TAB_POS.length
									}]});
								pos = value.indexOf(TAB_POS, pos + TAB_POS.length);
							}
							linkedMode.enterLinkedMode(linkedModeModel);
						}
					},

					/**
					 * Returns editor's content
					 * @return {String}
					 */
					getContent: function() {
						return editor.getText();
					},

					getSyntax: function() {
						return editor.getContentType();
					},

					getProfileName: function() {
						return this.getSyntax();
					},

					// TODO uhhhh...we can do better
					prompt: function(title) {
						return prompt(title);
					},

					getSelection: function() {
						var sel = this.getSelectionRange();
						if (sel) {
							return editor.getText(sel.start, sel.end);
						}

						return '';
					},

					/**
					 * Returns current editor's file path
					 * @return {String}
					 * @since 0.65
					 */
					getFilePath: function() {
						return editor.getFilePath();
					}
				};
			});
		},

		runEmmetAction : function(name, args) {
			console.log("Running emmet action: " + name);
			try {
				return emmet.require('actions').run(name, [this.editorProxy]);
			} catch (e) {
				console.warn(e.message);
				console.warn(e.stack);
				return false;
			}
		},

		registerEmmetAction : function(name, key) {
			console.log("Registering emmet command " + name + " to " + key);
			this.editor.getTextView().setKeyBinding(new mKeyBinding.KeyBinding(key.toString(), /*command/ctrl*/ true, /*shift*/ true, /*alt*/ false), "Zen " + name);
			this.editor.getTextView().setAction("Zen " + name, function() {
				this.runEmmetAction(name);
				return false;
			}.bind(this));
		},

		attach : function(editor) {

			var i = 0;
			this.registerEmmetAction("expand_abbreviation", ++i);
			this.registerEmmetAction("match_pair_inward", ++i);
			this.registerEmmetAction("match_pair_outward", ++i);
			this.registerEmmetAction("matching_pair", ++i);
			this.registerEmmetAction("merge_lines", ++i);
			this.registerEmmetAction("remove_tag", ++i);
			this.registerEmmetAction("select_next_item", ++i);
			this.registerEmmetAction("select_previous_item", ++i);
			this.registerEmmetAction("split_join_tag", ++i);
		},

		detach : function() {
			$(document).on('paneDestroyed', function(event, pane) {
				if (pane.editor === this.editor) {

					this.editor = null;
					this.editorProxy = null;
				}
			});
		}
	};

	$(document).on('paneCreated', function(event, pane) {
		if (pane.editor) {
			var proxy = new ZenEditorProxy(pane.editor);
			proxy.init();
		}
	});
});<commit_msg>remove unnecessary console.log messages<commit_after>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Andrew Eisenberg - initial API and implementation
 ******************************************************************************/

// implements a zen coding plugin for scripted

/*jslint browser:true */
/*global define emmet prompt scripted */

define(["orion/textview/keyBinding", 'scripted/utils/textUtils', 'orion/editor/editorFeatures',
	'jquery', 'zen'],
	function(mKeyBinding, textUtils, editorFeatures, $) {
	function ZenEditorProxy(editor) {
		this.editor = editor;
	}

	var TAB_POS = "${0}";

	ZenEditorProxy.prototype = {
		init : function() {
			this.editorProxy = this.createProxy(this.editor);
			this.attach(this.editor);
		},
		createProxy: function(editor) {
			return emmet.exec(function(req, _) {
				// TODO shouldn't have to do this twice
				var res = req('resources');
				var utils = req('utils');
				res.setVariable('indentation', textUtils.indent());
				utils.setNewline('\n');
				return {
					setContext: function(context) {
						// TODO shouldn't have to do this twice
						var res = req('resources');
						var utils = req('utils');
						res.setVariable('indentation', textUtils.indent());
						utils.setNewline('\n');
					},

					/**
					 * Returns character indexes of selected text: object with start
					 * and end properties. If there's no selection, should return
					 * object with start and end properties referring
					 * to current caret position
					 * @return {Object}
					 * @example
					 * var selection = editor.getSelectionRange();
					 * alert(selection.start + ', ' + selection.end);
					 */
					getSelectionRange: function() {
						return {
							start: editor.getSelection().start,
							end: editor.getSelection().end
						};
					},

					/**
					 * Creates selection from start to end character
					 * indexes. If end is ommited, this method should place caret
					 * and start index
					 * @param {Number} start
					 * @param {Number} [end]
					 * @example
					 * editor.createSelection(10, 40);
					 *
					 * //move caret to 15th character
					 * editor.createSelection(15);
					 */
					createSelection: function(start, end) {
						editor.setSelection(start, end);
					},

					/**
					 * Returns current line's start and end indexes as object with start
					 * and end properties
					 * @return {Object}
					 * @example
					 * var range = editor.getCurrentLineRange();
					 * alert(range.start + ', ' + range.end);
					 */
					getCurrentLineRange: function() {
						var selStart = this.getCaretPos();
						var model = editor.getTextView().getModel();
						var line = model.getLineAtOffset(selStart);

						var result = {
							start: model.getLineStart(line),
							end: model.getLineEnd(line)
						};

						return result;
					},

					/**
					 * Returns current caret position
					 * @return {Number|null}
					 */
					getCaretPos: function() {
						var sel = this.getSelectionRange();
						return Math.min(sel.start, sel.end);
					},
					/**
					 * Set new caret position
					 * @param {Number} pos Caret position
					 */
					setCaretPos: function(pos) {
						this.createSelection(pos, pos);
					},

					/**
					 * Returns content of current line
					 * @return {String}
					 */
					getCurrentLine: function() {
						var range = this.getCurrentLineRange();
						return this.getContent().substring(range.start, range.end);
					},
					/**
					 * Replace editor's content or it's part (from start to
					 * end index). If value contains
					 * caret_placeholder, the editor will put caret into
					 * this position. If you skip start and end
					 * arguments, the whole target's content will be replaced with
					 * value.
					 *
					 * If you pass start argument only,
					 * the value will be placed at start string
					 * index of current content.
					 *
					 * If you pass start and end arguments,
					 * the corresponding substring of current target's content will be
					 * replaced with value.
					 * @param {String} value Content you want to paste
					 * @param {Number} [start] Start index of editor's content
					 * @param {Number} [end] End index of editor's content
					 * @param {Boolean} [no_indent] Do not auto indent value
					 */
					replaceContent: function(value, start, end, noIndent) {

						if (!noIndent) {
							var leading = textUtils.leadingWhitespace(editor.getTextView().getText(), start);
							var regex = new RegExp('\n', "g");
							value = value.replace(regex, "\n" + leading);
						}
						editor.getTextView().setText(value, start, end);

						var pos = value.indexOf(TAB_POS);
						if (pos !== -1) {
							var linkedMode = new editorFeatures.LinkedMode(editor);
							var linkedModeModel = { groups : [] };
							while (pos !== -1) {
								linkedModeModel.groups.push({
									positions : [{
										offset: pos + start,
										length: TAB_POS.length
									}]});
								pos = value.indexOf(TAB_POS, pos + TAB_POS.length);
							}
							linkedMode.enterLinkedMode(linkedModeModel);
						}
					},

					/**
					 * Returns editor's content
					 * @return {String}
					 */
					getContent: function() {
						return editor.getText();
					},

					getSyntax: function() {
						return editor.getContentType();
					},

					getProfileName: function() {
						return this.getSyntax();
					},

					// TODO uhhhh...we can do better
					prompt: function(title) {
						return prompt(title);
					},

					getSelection: function() {
						var sel = this.getSelectionRange();
						if (sel) {
							return editor.getText(sel.start, sel.end);
						}
						return '';
					},

					/**
					 * Returns current editor's file path
					 * @return {String}
					 * @since 0.65
					 */
					getFilePath: function() {
						return editor.getFilePath();
					}
				};
			});
		},

		runEmmetAction : function(name, args) {
			try {
				return emmet.require('actions').run(name, [this.editorProxy]);
			} catch (e) {
				console.warn(e.message);
				console.warn(e.stack);
				return false;
			}
		},

		registerEmmetAction : function(name, key) {
			this.editor.getTextView().setKeyBinding(new mKeyBinding.KeyBinding(key.toString(), /*command/ctrl*/ true, /*shift*/ true, /*alt*/ false), "Zen " + name);
			this.editor.getTextView().setAction("Zen " + name, function() {
				this.runEmmetAction(name);
				return false;
			}.bind(this));
		},

		attach : function(editor) {

			var i = 0;
			this.registerEmmetAction("expand_abbreviation", ++i);
			this.registerEmmetAction("match_pair_inward", ++i);
			this.registerEmmetAction("match_pair_outward", ++i);
			this.registerEmmetAction("matching_pair", ++i);
			this.registerEmmetAction("merge_lines", ++i);
			this.registerEmmetAction("remove_tag", ++i);
			this.registerEmmetAction("select_next_item", ++i);
			this.registerEmmetAction("select_previous_item", ++i);
			this.registerEmmetAction("split_join_tag", ++i);
		},

		detach : function() {
			$(document).on('paneDestroyed', function(event, pane) {
				if (pane.editor === this.editor) {

					this.editor = null;
					this.editorProxy = null;
				}
			});
		}
	};

	$(document).on('paneCreated', function(event, pane) {
		if (pane.editor) {
			var proxy = new ZenEditorProxy(pane.editor);
			proxy.init();
		}
	});
});<|endoftext|>


<commit_before>import auth from '../../../src/state/reducers/auth.reducers';
import { AUTH_RESPONSE, NOT_AUTHENTICATED } from '../../../src/state/actions/actionTypes';

describe('Authorisation reducer', () => {

  it('should return initial state', () => {
    expect(
      auth.authentication(undefined, {type: '', payload: {}})
    ).toEqual({});
  });

  it('should log user in when authentication success and store the token', () => {
    expect(
      auth.authentication({}, {type: AUTH_RESPONSE, payload: { loggedIn: true, message: '', token: 'TOKEN' }})
    ).toEqual({ loading: false, loggedIn: true, errorMessage: '', token: 'TOKEN' });
  });

  it('should not log user in when authentication failed and supply an error message', () => {
    expect(
      auth.authentication({}, {
        type: AUTH_RESPONSE,
        payload: new Error('Wrong username or password'),
        error: true
      })
    ).toEqual({ loading: false, loggedIn: undefined, errorMessage: 'Wrong username or password', token: undefined });
  });

  it('should turn authentication loggedIn to NOT logged in and auth token has been cleared if participant not authenticated', () => {
    expect(
      auth.authentication({}, {
        type: NOT_AUTHENTICATED
      })
    ).toEqual({ loading: false, loggedIn: false, token: null });
  });
});
<commit_msg>APEC-45 Fix test<commit_after>import auth from '../../../src/state/reducers/auth.reducers';
import { AUTH_SUCCESS, AUTH_FAILURE, NOT_AUTHENTICATED } from '../../../src/state/actions/actionTypes';

describe('Authorisation reducer', () => {

  it('should return initial state', () => {
    expect(
      auth.authentication(undefined, {type: '', payload: {}})
    ).toEqual({});
  });

  it('should log user in when authentication success and store the token', () => {
    expect(
      auth.authentication({}, {type: AUTH_SUCCESS, payload: 'TOKEN'})
    ).toEqual({ loading: false, loggedIn: true, token: 'TOKEN' });
  });

  it('should not log user in when authentication failed and supply an error message', () => {
    expect(
      auth.authentication({}, {
        type: AUTH_FAILURE,
        payload: 'Wrong username or password',
        error: true
      })
    ).toEqual({ loading: false, loggedIn: false, errorMessage: 'Wrong username or password' });
  });

  it('should turn authentication loggedIn to NOT logged in and auth token has been cleared if participant not authenticated', () => {
    expect(
      auth.authentication({}, {
        type: NOT_AUTHENTICATED
      })
    ).toEqual({});
  });
});
<|endoftext|>