<commit_before>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<commit_msg>dev env<commit_after>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (process.env.NODE_ENV === 'development') {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
} else {
  var sequelize = new Sequelize(process.env.DATABASE_URL);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<|endoftext|>


<commit_before>import test from 'tape';
import WindowMock from './window-mock';
import {name} from '../package.json';

let windowMock = new WindowMock();

test(`${name}: Window`, (t) => {
  let tmp, tmpFunc;

  t.equal(windowMock._test, 'Window', 'should be a Window object');

  t.equal(typeof windowMock.applicationCache, 'object', 'applicationCache should be an object');

  t.equal(typeof windowMock.navigator, 'object', 'navigator should be an object');

  t.equal(typeof windowMock.location, 'object', 'location should be an object');

  t.equal(typeof windowMock.localStorage, 'object', 'localStorage should be an object');

  t.equal(typeof windowMock.document, 'object', 'document should be an object');

  tmpFunc = () => { tmp = true; };

  t.equal(typeof windowMock.setTimeout, 'function', 'setTimeout should be a function');
  tmp = false;
  windowMock.setTimeout(tmpFunc);
  t.equal(tmp, true, 'setTimeout should invoke callback');

  t.equal(typeof windowMock.requestAnimationFrame, 'function', 'requestAnimationFrame should be a function');
  tmp = false;
  windowMock.requestAnimationFrame(tmpFunc);
  t.equal(tmp, true, 'requestAnimationFrame should invoke callback');

  t.equal(typeof windowMock.btoa, 'function', 'btoa should be a function');

  t.equal(windowMock.btoa('x'), 'x', 'btoa should return');

  t.end();
});
<commit_msg>Cleanup<commit_after>import test from 'tape';
import WindowMock from './window-mock';
import {name} from '../package.json';

let windowMock = new WindowMock();

test(`${name}: Window`, (t) => {
  let
    tmp,
    tmpFunc = () => { tmp = true; };

  t.equal(windowMock._test, 'Window', 'should be a Window object');

  t.equal(typeof windowMock.applicationCache, 'object', 'applicationCache should be an object');

  t.equal(typeof windowMock.navigator, 'object', 'navigator should be an object');

  t.equal(typeof windowMock.location, 'object', 'location should be an object');

  t.equal(typeof windowMock.localStorage, 'object', 'localStorage should be an object');

  t.equal(typeof windowMock.document, 'object', 'document should be an object');

  t.equal(typeof windowMock.setTimeout, 'function', 'setTimeout should be a function');
  tmp = false;
  windowMock.setTimeout(tmpFunc);
  t.equal(tmp, true, 'setTimeout should invoke callback');

  t.equal(typeof windowMock.requestAnimationFrame, 'function', 'requestAnimationFrame should be a function');
  tmp = false;
  windowMock.requestAnimationFrame(tmpFunc);
  t.equal(tmp, true, 'requestAnimationFrame should invoke callback');

  t.equal(typeof windowMock.btoa, 'function', 'btoa should be a function');

  t.equal(windowMock.btoa('x'), 'x', 'btoa should return');

  t.end();
});
<|endoftext|>


<commit_before>import { Session } from 'meteor/session';

import { Contracts } from '/imports/api/contracts/Contracts';
import { createContract } from '/imports/startup/both/modules/Contract';

/**
* @param {string} contractId - contract where this ballot belongs to
* @param {object} ballot - ballot object
******/
const _setVote = (contractId, ballot) => {
  var candidateBallot = new Array();

  //see candidate ballots
  if (Session.get('candidateBallot') != undefined) {
   candidateBallot = Session.get('candidateBallot');
  }
  var multipleChoice = Session.get('contract').multipleChoice;

  //fate
  if (ballot.tick == undefined) { ballot.tick = true } else { ballot.tick = !ballot.tick };

  //add or update ballot in memory
  var update = false;
  for (i in candidateBallot) {
    if (!multipleChoice) {
      candidateBallot[i].ballot.tick = false;
    }
    if (candidateBallot[i].contractId == contractId) {
      if (candidateBallot[i].ballot._id == ballot._id) {
        candidateBallot[i].ballot = ballot
        update = true;
      }
    }
  }
  if (!update) {
    candidateBallot.push({
      contractId: contractId,
      ballot: ballot
    })
  }

  //save to session var
  Session.set('candidateBallot', candidateBallot);
  return ballot.tick;
}

/*****
* @param {string} contractId - contract where this ballot belongs to
* @param {object} ballotId - ballotId to check
******/
let _getVote = (contractId, ballotId) => {
  if (Session.get('rightToVote') == false && Session.get('contract').stage != STAGE_DRAFT) {
    //check if user already voted
    var ledger = Session.get('contract').wallet.ledger
    for (i in ledger) {
      if (ledger[i].entityId == Meteor.user()._id) {
        ballot = ledger[i].ballot;
        for (k in ballot) {
          if (ballot[k]._id == ballotId) {
            return true;
          }
        }
      }
    }
    return false;
  } else {
    //check user current vote
    var votes = Session.get('candidateBallot');
    for (i in votes) {
      if (votes[i].contractId == contractId && votes[i].ballot._id == ballotId) {
        return votes[i].ballot.tick;
      }
    }
  }
}

/****
* checks if at least one item from ballot has been checked for voting
****/
let _ballotReady = () => {
  var votes = Session.get('candidateBallot');
  for (i in votes) {
    if (votes[i].ballot.tick == true) {
      return true;
    }
  }
  return false;
}

/****
* keeps only boolean true values in ballot
* @param {object} ballot - ballot object
* @return {object} options - array with only ticked true ballot options
****/
let _purgeBallot = (options) => {
  var finalBallot = new Array();
  for (i in options) {
    if (options[i].ballot.tick == true) {
      finalBallot.push(options[i].ballot);
    }
  }
  return finalBallot;
}

/******
* shows the results of the current poll
* @param {object} contract - contract to check results on
* @return {array} results - array with a statistical object for every item in the ballot
*******/
let _showResults = (contract) => {
  var results = new Array();
  var ledger = contract.wallet.ledger;
  var ballot = contract.ballot;

  //add votes
  for (i in ledger) {
    if (ledger[i].ballot != undefined && ledger[i].ballot.length > 0) {
      quantity = (ledger[i].quantity / ledger[i].ballot.length);
      for (k in ledger[i].ballot) {
        results = _countVotes(results, ledger[i].ballot[k], quantity);
      }
    }
  }

  //get stats
  var totalvotes = 0;
  for (i in results) {
    totalvotes += results[i].votes;
  }

  //set percentage
  for (i in results) {
    ballotcount = results[i];
    ballotcount['percentage'] = ((ballotcount.votes * 100) / totalvotes);
    results[i] = ballotcount;
  }

  return results;
}

/******
* updates contract execution status based on final results
* @param {object} contract - contract to check results on
* @param {object} results - object with poll results
*********/
let _updateExecutionStatus = (contract, results) => {
  //check result
  var topvotes = 0;
  for (i in results) {
    if (results[i].votes > topvotes) {
      topvotes = results[i].votes;
      winner = results[i].mode;
    }
  }
  if (topvotes == 0) {
    winner = BALLOT_OPTION_MODE_NONE;
  }
  if (contract.stage == 'LIVE') {
    var contractId = contract._id;
    switch (winner) {
      case BALLOT_OPTION_MODE_AUTHORIZE:
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'APPROVED', stage : 'FINISH' }});
        break;
      case BALLOT_OPTION_MODE_REJECT:
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'REJECTED', stage : 'FINISH' }});
        break;
      case BALLOT_OPTION_MODE_FORK:
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'ALTERNATIVE', stage : 'FINISH' }});
        break;
      default:
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'VOID', stage: 'FINISH' }});
    }
  }
}

/******
* counts the votes in a given ballot
* @param {array} scoreboard - array with all ballots to do counting on
* @param {ballot} ballot - ballot to which compare existence in scoreboard
* @param {number} quantity - amount of votes to add
* @return {array} scoreboard - result board
*******/
let _countVotes = (scoreboard, ballot, quantity) => {
  for (i in scoreboard) {
    if (scoreboard[i]._id == ballot._id) {
      //add votes to exsting item
      scoreboard[i].votes += quantity;
      return scoreboard;
    }
  }
  //new item in ballot
  ballot['votes'] = quantity;
  scoreboard.push(ballot);
  return scoreboard;
}

/******
* generates a new contract that automatically goes as option in the ballot
*******/
let _forkContract = () => {
  if (Session.get('proposalURLStatus') == 'AVAILABLE') {
    var contract = createContract(convertToSlug(Session.get('newProposal')), Session.get('newProposal'))[0];
    if (contract) {
      if (_addChoiceToBallot(Session.get('contract')._id, contract._id)) {
        var contract = Contracts.findOne( { _id: Session.get('contract')._id }, {reactive: false});
        Session.set('dbContractBallot', contract.ballot );
        // LAI: where ProposalSearch comes from and what it is??
        ProposalSearch.search('');
        document.getElementById("searchInput").innerHTML = '';
        Session.set('proposalURLStatus', 'UNAVAILABLE');
        Session.set('createProposal', false);
        Session.set('emptyBallot', false);
        _verifyDraftFork(contract.ballot);
      }
    } else {
      Session.set('duplicateFork', true)
    }
  }
}

let _quickContract = (keyword) => {
  console.log('[createContract] new contract with keyword: ' + keyword);
  //Adds a new contract to db, returns created insert
  if (keyword != undefined || keyword != '') {
    var slug = convertToSlug(keyword);
  } else {
    var slug = convertToSlug('draft-' + Meteor.userId());
  }

  var creationDate = new Date;
  creationDate.setDate(creationDate.getDate() + 1);
  console.log('[createContract] new contract by user: ' + Meteor.userId());

  if (keyword != '') {
    //Creates new contract:
    console.log('[createContract] contract being created...');
    return Contracts.insert({ title: keyword });

  }
}

/******
* verifies if there's an option in the ballot that is still a draft
* @param {object} ballot - ballot to check
*******/
let _verifyDraftFork = (ballot) => {
  var draftFork = false;
  for (i in ballot) {
    choice = Contracts.findOne( { _id: ballot[i]._id });
    if (choice.stage == STAGE_DRAFT) {
      draftFork = true;
      break;
    }
  }
  Session.set('draftOptions', draftFork);
}

/******
* updates the ranking of an option in a ballot
* @param {string} contractId - contract
* @param {array} sortedBallotIDs - available options in this ballot
*******/
let _updateBallotRank = (contractId, sortedBallotIDs) => {
  var contract = Contracts.findOne({ _id: contractId });
  var ballot = contract.ballot;
  for (i in sortedBallotIDs) {
    for (k in ballot) {
      if (ballot[k]._id == sortedBallotIDs[i]) {
        ballot[k].rank = parseInt(i) + 1;
        break;
      }
    }
  }
  contract.ballot = ballot;
  _verifyDraftFork(ballot);
  Contracts.update({ _id: contractId }, { $set: { ballot: contract.ballot } });
}

/******
* removes an option froim a ballot
* @param {string} contractId - contract
* @param {string} forkId - choice id
*******/
let _removeFork = (contractId, forkId) => {
  Contracts.update({ _id: contractId}, { $pull: {
    ballot:
      { _id: forkId}
  }})
};

/******
* adds a choice to the ballot from an existing proposal
* @param {string} contractId - contract
* @param {string} forkId - choice id
* @return {boolean} value - succesfull add
*******/
let _addChoiceToBallot = (contractId, forkId) => {
  var dbContract = Contracts.findOne({ _id: forkId });
  if (dbContract != undefined) {
    if (checkDuplicate(Contracts.findOne(contractId, { ballot: { _id: dbContract._id } }).ballot, dbContract._id) == false) {
      var rankVal = parseInt(Contracts.findOne({ _id: contractId }).ballot.length) + 1;
      Contracts.update(contractId, { $push: {
        ballot:
          {
            _id: dbContract._id,
            mode: BALLOT_OPTION_MODE_FORK,
            url: dbContract.url,
            label: dbContract.title,
            rank: rankVal
          }
      }});
      Session.set('duplicateFork', false);
      if (Contracts.findOne({ _id: dbContract._id }).stage == STAGE_DRAFT) {
        Session.set('draftOptions', true);
      }
      Session.set('dbContractBallot', Contracts.findOne( { _id: contractId }, {reactive: false}).ballot );
      return true;
    } else {
      Session.set('duplicateFork', true);
      return false;
    }
  }
}

export const addChoiceToBallot = _addChoiceToBallot;
export const verifyDraftFork = _verifyDraftFork;
export const removeFork = _removeFork;
export const updateBallotRank = _updateBallotRank;
export const updateExecutionStatus = _updateExecutionStatus;
export const showResults = _showResults;
export const purgeBallot = _purgeBallot;
export const ballotReady = _ballotReady;
export const forkContract = _forkContract;
export const setVote = _setVote;
export const getVote = _getVote;
<commit_msg>rp const w value, add missed import func<commit_after>import { Session } from 'meteor/session';

import { Contracts } from '/imports/api/contracts/Contracts';
import { createContract } from '/imports/startup/both/modules/Contract';
import { checkDuplicate } from '/lib/utils';

/**
* @param {string} contractId - contract where this ballot belongs to
* @param {object} ballot - ballot object
******/
const _setVote = (contractId, ballot) => {
  var candidateBallot = new Array();

  //see candidate ballots
  if (Session.get('candidateBallot') != undefined) {
   candidateBallot = Session.get('candidateBallot');
  }
  var multipleChoice = Session.get('contract').multipleChoice;

  //fate
  if (ballot.tick == undefined) { ballot.tick = true } else { ballot.tick = !ballot.tick };

  //add or update ballot in memory
  var update = false;
  for (i in candidateBallot) {
    if (!multipleChoice) {
      candidateBallot[i].ballot.tick = false;
    }
    if (candidateBallot[i].contractId == contractId) {
      if (candidateBallot[i].ballot._id == ballot._id) {
        candidateBallot[i].ballot = ballot
        update = true;
      }
    }
  }
  if (!update) {
    candidateBallot.push({
      contractId: contractId,
      ballot: ballot
    })
  }

  //save to session var
  Session.set('candidateBallot', candidateBallot);
  return ballot.tick;
}

/*****
* @param {string} contractId - contract where this ballot belongs to
* @param {object} ballotId - ballotId to check
******/
let _getVote = (contractId, ballotId) => {
  if (Session.get('rightToVote') == false && Session.get('contract').stage != 'DRAFT') {
    //check if user already voted
    var ledger = Session.get('contract').wallet.ledger
    for (i in ledger) {
      if (ledger[i].entityId == Meteor.user()._id) {
        ballot = ledger[i].ballot;
        for (k in ballot) {
          if (ballot[k]._id == ballotId) {
            return true;
          }
        }
      }
    }
    return false;
  } else {
    //check user current vote
    var votes = Session.get('candidateBallot');
    for (i in votes) {
      if (votes[i].contractId == contractId && votes[i].ballot._id == ballotId) {
        return votes[i].ballot.tick;
      }
    }
  }
}

/****
* checks if at least one item from ballot has been checked for voting
****/
let _ballotReady = () => {
  var votes = Session.get('candidateBallot');
  for (i in votes) {
    if (votes[i].ballot.tick == true) {
      return true;
    }
  }
  return false;
}

/****
* keeps only boolean true values in ballot
* @param {object} ballot - ballot object
* @return {object} options - array with only ticked true ballot options
****/
let _purgeBallot = (options) => {
  var finalBallot = new Array();
  for (i in options) {
    if (options[i].ballot.tick == true) {
      finalBallot.push(options[i].ballot);
    }
  }
  return finalBallot;
}

/******
* shows the results of the current poll
* @param {object} contract - contract to check results on
* @return {array} results - array with a statistical object for every item in the ballot
*******/
let _showResults = (contract) => {
  var results = new Array();
  var ledger = contract.wallet.ledger;
  var ballot = contract.ballot;

  //add votes
  for (i in ledger) {
    if (ledger[i].ballot != undefined && ledger[i].ballot.length > 0) {
      quantity = (ledger[i].quantity / ledger[i].ballot.length);
      for (k in ledger[i].ballot) {
        results = _countVotes(results, ledger[i].ballot[k], quantity);
      }
    }
  }

  //get stats
  var totalvotes = 0;
  for (i in results) {
    totalvotes += results[i].votes;
  }

  //set percentage
  for (i in results) {
    ballotcount = results[i];
    ballotcount['percentage'] = ((ballotcount.votes * 100) / totalvotes);
    results[i] = ballotcount;
  }

  return results;
}

/******
* updates contract execution status based on final results
* @param {object} contract - contract to check results on
* @param {object} results - object with poll results
*********/
let _updateExecutionStatus = (contract, results) => {
  //check result
  var topvotes = 0;
  for (i in results) {
    if (results[i].votes > topvotes) {
      topvotes = results[i].votes;
      winner = results[i].mode;
    }
  }
  if (topvotes == 0) {
    winner = 'NONE';
  }
  if (contract.stage == 'LIVE') {
    var contractId = contract._id;
    switch (winner) {
      case 'AUTHORIZE':
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'APPROVED', stage : 'FINISH' }});
        break;
      case 'REJECT':
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'REJECTED', stage : 'FINISH' }});
        break;
      case 'FORK':
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'ALTERNATIVE', stage : 'FINISH' }});
        break;
      default:
        Contracts.update({ _id: contractId }, { $set: { executionStatus: 'VOID', stage: 'FINISH' }});
    }
  }
}

/******
* counts the votes in a given ballot
* @param {array} scoreboard - array with all ballots to do counting on
* @param {ballot} ballot - ballot to which compare existence in scoreboard
* @param {number} quantity - amount of votes to add
* @return {array} scoreboard - result board
*******/
let _countVotes = (scoreboard, ballot, quantity) => {
  for (i in scoreboard) {
    if (scoreboard[i]._id == ballot._id) {
      //add votes to exsting item
      scoreboard[i].votes += quantity;
      return scoreboard;
    }
  }
  //new item in ballot
  ballot['votes'] = quantity;
  scoreboard.push(ballot);
  return scoreboard;
}

/******
* generates a new contract that automatically goes as option in the ballot
*******/
let _forkContract = () => {
  if (Session.get('proposalURLStatus') == 'AVAILABLE') {
    var contract = createContract(convertToSlug(Session.get('newProposal')), Session.get('newProposal'))[0];
    if (contract) {
      if (_addChoiceToBallot(Session.get('contract')._id, contract._id)) {
        var contract = Contracts.findOne( { _id: Session.get('contract')._id }, {reactive: false});
        Session.set('dbContractBallot', contract.ballot );
        // LAI: where ProposalSearch comes from and what it is??
        ProposalSearch.search('');
        document.getElementById("searchInput").innerHTML = '';
        Session.set('proposalURLStatus', 'UNAVAILABLE');
        Session.set('createProposal', false);
        Session.set('emptyBallot', false);
        _verifyDraftFork(contract.ballot);
      }
    } else {
      Session.set('duplicateFork', true)
    }
  }
}

let _quickContract = (keyword) => {
  console.log('[createContract] new contract with keyword: ' + keyword);
  //Adds a new contract to db, returns created insert
  if (keyword != undefined || keyword != '') {
    var slug = convertToSlug(keyword);
  } else {
    var slug = convertToSlug('draft-' + Meteor.userId());
  }

  var creationDate = new Date;
  creationDate.setDate(creationDate.getDate() + 1);
  console.log('[createContract] new contract by user: ' + Meteor.userId());

  if (keyword != '') {
    //Creates new contract:
    console.log('[createContract] contract being created...');
    return Contracts.insert({ title: keyword });

  }
}

/******
* verifies if there's an option in the ballot that is still a draft
* @param {object} ballot - ballot to check
*******/
let _verifyDraftFork = (ballot) => {
  var draftFork = false;
  for (i in ballot) {
    choice = Contracts.findOne( { _id: ballot[i]._id });
    if (choice.stage == 'DRAFT') {
      draftFork = true;
      break;
    }
  }
  Session.set('draftOptions', draftFork);
}

/******
* updates the ranking of an option in a ballot
* @param {string} contractId - contract
* @param {array} sortedBallotIDs - available options in this ballot
*******/
let _updateBallotRank = (contractId, sortedBallotIDs) => {
  var contract = Contracts.findOne({ _id: contractId });
  var ballot = contract.ballot;
  for (i in sortedBallotIDs) {
    for (k in ballot) {
      if (ballot[k]._id == sortedBallotIDs[i]) {
        ballot[k].rank = parseInt(i) + 1;
        break;
      }
    }
  }
  contract.ballot = ballot;
  _verifyDraftFork(ballot);
  Contracts.update({ _id: contractId }, { $set: { ballot: contract.ballot } });
}

/******
* removes an option froim a ballot
* @param {string} contractId - contract
* @param {string} forkId - choice id
*******/
let _removeFork = (contractId, forkId) => {
  Contracts.update({ _id: contractId}, { $pull: {
    ballot:
      { _id: forkId}
  }})
};

/******
* adds a choice to the ballot from an existing proposal
* @param {string} contractId - contract
* @param {string} forkId - choice id
* @return {boolean} value - succesfull add
*******/
let _addChoiceToBallot = (contractId, forkId) => {
  var dbContract = Contracts.findOne({ _id: forkId });
  if (dbContract != undefined) {
    if(checkDuplicate(Contracts.findOne(contractId, { ballot: { _id: dbContract._id } }).ballot, dbContract._id) == false) {
      var rankVal = parseInt(Contracts.findOne({ _id: contractId }).ballot.length) + 1;
      Contracts.update(contractId, { $push: {
        ballot:
          {
            _id: dbContract._id,
            mode: 'FORK',
            url: dbContract.url,
            label: dbContract.title,
            rank: rankVal
          }
      }});
      Session.set('duplicateFork', false);
      if (Contracts.findOne({ _id: dbContract._id }).stage == 'DRAFT') {
        Session.set('draftOptions', true);
      }
      Session.set('dbContractBallot', Contracts.findOne( { _id: contractId }, {reactive: false}).ballot );
      return true;
    } else {
      Session.set('duplicateFork', true);
      return false;
    }
  }
}

export const addChoiceToBallot = _addChoiceToBallot;
export const verifyDraftFork = _verifyDraftFork;
export const removeFork = _removeFork;
export const updateBallotRank = _updateBallotRank;
export const updateExecutionStatus = _updateExecutionStatus;
export const showResults = _showResults;
export const purgeBallot = _purgeBallot;
export const ballotReady = _ballotReady;
export const forkContract = _forkContract;
export const setVote = _setVote;
export const getVote = _getVote;
<|endoftext|>


<commit_before>/**
 * Created by tigran on 7/20/15.
 */

require("./model");

var mongoose = require("mongoose")
    , Twitter = require('twitter-node-client').Twitter
    , async = require('async')
    , City = mongoose.model("City")
    , Country = mongoose.model("Country")
    , SocialPost = mongoose.model("SocialPost")
    , SocialUser = mongoose.model("SocialUser")
    , Token = mongoose.model("Token");

function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate());
};

Token.findOne({social: "twitter"}, function (err, twitter_keys) {
    var config = {
        "consumerKey": twitter_keys.token_data["consumer_key"],
        "consumerSecret": twitter_keys.token_data["consumer_secret"],
        "accessToken": twitter_keys.token_data["access_token"],
        "accessTokenSecret": twitter_keys.token_data["access_token_secret"]
    };
    var twitter = new Twitter(config);

    async.forever(function (next) {
        City.find({}, function (e, cities) {
            async.eachSeries(cities, function (city, cb) {
                var date = new Date();

                twitter.getSearch({
                    q: 'since:' + date.toMysqlFormat()
                    , geocode: city.latitude + "," + city.longitude + ",5000mi"
                    , count: 100
                    , result_type: "popular"
                }, function (err, response, body) {
                    console.log('ERROR [%s]', err);
                    setTimeout(function () {
                        cb();
                    }, 2500);
                }, function (data) {
                    if(typeof data !== 'object')
                    {
                        data = JSON.parse(data);
                    }
                    async.eachSeries(data["statuses"], function (post_data, next_post) {
                        SocialUser.findOne({user_id: post_data["user"]["id_str"]}, function (uerr, user) {
                            if(uerr)
                            {
                                console.log(err);
                                next_post(err);
                            }
                            else
                            {
                                var post_user;
                                var save_post_fn = function () {
                                    SocialPost.find({post_id: post_data["id_str"]}, function (perror, found_posts) {
                                        if (perror)
                                        {
                                            console.log(perror);
                                            next_post(perror);
                                        }
                                        else
                                        {
                                            if (found_posts.length > 0)
                                            {
                                                next_post();
                                            }
                                            else
                                            {
                                                var p = new SocialPost({
                                                    content: post_data["text"],
                                                    user: post_user._id,
                                                    post_id: post_data["id_str"],
                                                    url: post_user.url + "/" + post_data["id_str"]
                                                });
                                                p.save(function () {
                                                    console.log("------ " + p.url);
                                                    next_post();
                                                });
                                            }
                                        }
                                    });
                                };
                                if(user)
                                {
                                    post_user = user;
                                    save_post_fn();
                                }
                                else
                                {
                                    post_user = new SocialUser({
                                        user_id: post_data["user"]["id_str"],
                                        username: post_data["user"]["screen_name"],
                                        name: post_data["user"]["name"],
                                        photo: post_data["user"]["profile_image_url_https"],
                                        social_name: "twitter",
                                        url: "https://twitter.com/" + post_data["user"]["screen_name"]
                                    });
                                    post_user.save(function (save_error) {
                                        console.log("New User: " + post_user.url);
                                        if(save_error)
                                        {
                                            console.log(save_error);
                                            next_post(save_error);
                                        }
                                        else
                                        {
                                            save_post_fn();
                                        }
                                    });
                                }
                            }
                        });
                    }, function (ee) {
                        setTimeout(function () {
                            cb();
                        }, 2500);
                    });
                });
            }, function () {
                next();
            });
        });
    }, function () {

    });
});<commit_msg>printing error body<commit_after>/**
 * Created by tigran on 7/20/15.
 */

require("./model");

var mongoose = require("mongoose")
    , Twitter = require('twitter-node-client').Twitter
    , async = require('async')
    , City = mongoose.model("City")
    , Country = mongoose.model("Country")
    , SocialPost = mongoose.model("SocialPost")
    , SocialUser = mongoose.model("SocialUser")
    , Token = mongoose.model("Token");

function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate());
};

Token.findOne({social: "twitter"}, function (err, twitter_keys) {
    var config = {
        "consumerKey": twitter_keys.token_data["consumer_key"],
        "consumerSecret": twitter_keys.token_data["consumer_secret"],
        "accessToken": twitter_keys.token_data["access_token"],
        "accessTokenSecret": twitter_keys.token_data["access_token_secret"]
    };
    var twitter = new Twitter(config);

    async.forever(function (next) {
        City.find({}, function (e, cities) {
            async.eachSeries(cities, function (city, cb) {
                var date = new Date();

                twitter.getSearch({
                    q: 'since:' + date.toMysqlFormat()
                    , geocode: city.latitude + "," + city.longitude + ",5000mi"
                    , count: 100
                    , result_type: "popular"
                }, function (err, response, body) {
                    console.log('ERROR [%s]', body);
                    setTimeout(function () {
                        cb();
                    }, 2500);
                }, function (data) {
                    if(typeof data !== 'object')
                    {
                        data = JSON.parse(data);
                    }
                    async.eachSeries(data["statuses"], function (post_data, next_post) {
                        SocialUser.findOne({user_id: post_data["user"]["id_str"]}, function (uerr, user) {
                            if(uerr)
                            {
                                console.log(err);
                                next_post(err);
                            }
                            else
                            {
                                var post_user;
                                var save_post_fn = function () {
                                    SocialPost.find({post_id: post_data["id_str"]}, function (perror, found_posts) {
                                        if (perror)
                                        {
                                            console.log(perror);
                                            next_post(perror);
                                        }
                                        else
                                        {
                                            if (found_posts.length > 0)
                                            {
                                                next_post();
                                            }
                                            else
                                            {
                                                var p = new SocialPost({
                                                    content: post_data["text"],
                                                    user: post_user._id,
                                                    post_id: post_data["id_str"],
                                                    url: post_user.url + "/" + post_data["id_str"]
                                                });
                                                p.save(function () {
                                                    console.log("------ " + p.url);
                                                    next_post();
                                                });
                                            }
                                        }
                                    });
                                };
                                if(user)
                                {
                                    post_user = user;
                                    save_post_fn();
                                }
                                else
                                {
                                    post_user = new SocialUser({
                                        user_id: post_data["user"]["id_str"],
                                        username: post_data["user"]["screen_name"],
                                        name: post_data["user"]["name"],
                                        photo: post_data["user"]["profile_image_url_https"],
                                        social_name: "twitter",
                                        url: "https://twitter.com/" + post_data["user"]["screen_name"]
                                    });
                                    post_user.save(function (save_error) {
                                        console.log("New User: " + post_user.url);
                                        if(save_error)
                                        {
                                            console.log(save_error);
                                            next_post(save_error);
                                        }
                                        else
                                        {
                                            save_post_fn();
                                        }
                                    });
                                }
                            }
                        });
                    }, function (ee) {
                        setTimeout(function () {
                            cb();
                        }, 2500);
                    });
                });
            }, function () {
                next();
            });
        });
    }, function () {

    });
});<|endoftext|>


<commit_before>module('ExpandingTextareas', {
    setup: function() {
        this.$textarea = $('textarea.manual').expandingTextarea();
    }
});

test('Prevents initializing more than once', 1, function() {
    this.$textarea.expandingTextarea();
    equal(this.$textarea.parents('div.expandingText').length, 1,
        'Textarea has a single `div.expandingText` parent when `expandingTextarea()` called twice');
});

test('Ignores non-textarea elements', 1, function() {
    var $input = $('<input />').expandingTextarea();
    equal($input.parents().length, 0,
        'Non-textarea element not wrapped');
});

test('Returns the jQuery object', 1, function() {
    var $textarea = $('<textarea />');
    equal($textarea.expandingTextarea(), $textarea);
});

test('Wraps the textarea', function() {
    ok(this.$textarea.parent().is('div.expandingText'),
        'Textarea wrapped in `div.expandingText`');
});

test('Sets the textarea wrapper CSS', 1, function() {
    var $wrapper = this.$textarea.parent();
    equal($wrapper.css('position'), 'relative',
        'Textarea wrapper CSS `position` set to `relative`');
});

test('Ensures the clone is at least as tall as the textarea', 1, function() {
    var $textarea = $('<textarea rows="10" />').appendTo('#qunit-fixture');
    expected = $textarea.outerHeight(); // cache textarea height
    $textarea.expandingTextarea();
    equal($textarea.siblings('pre').outerHeight(), expected,
        'Textarea wrapper CSS `min-height` set to textarea outer height');
});

test('Creates a textarea clone', function() {
    var $pre = this.$textarea.siblings('pre');
    equal($pre.length, 1, 'Textarea has a `pre` sibling (clone)');
    equal($pre.find('div').length, 1, 'Textarea clone contains a div');
});

test('Sets the clone CSS `visibility` property', 1, function() {
    var $pre = this.$textarea.siblings('pre');
    equal($pre.css('visibility'), 'hidden',
        'Clone CSS `visibility` property set to `hidden`');
});

test('Sets clone CSS `white-space` property when `textarea[wrap]` is not "off"', 2, function() {
    ok(this.$textarea.attr('wrap') !== 'off');
    equal(this.$textarea.siblings('pre').css('white-space'), 'pre-wrap',
        'Clone CSS `white-space` property set to `pre-wrap`');
});

test('Sets the clone CSS `overflow-x` property when `textarea[wrap=off]`', 1, function() {
    var $textarea = $('<textarea wrap="off" />').expandingTextarea(),
        $pre = $textarea.siblings('pre');
    equal($pre.css('overflow-x'), 'scroll',
        'Clone CSS `overflow-x` property to `scroll`');
});

test('Copies the textarea CSS on to the clone', function() {
    var _this = this,
        $pre = this.$textarea.siblings('pre');

    var properties = [
        'lineHeight', 'textDecoration', 'letterSpacing',
        'fontSize', 'fontFamily', 'fontStyle',
        'fontWeight', 'textTransform', 'textAlign',
        'direction', 'wordSpacing', 'fontSizeAdjust',
        'wordWrap', 'word-break',
        'borderLeftWidth', 'borderRightWidth',
        'borderTopWidth','borderBottomWidth',
        'paddingLeft', 'paddingRight',
        'paddingTop','paddingBottom',
        'marginLeft', 'marginRight',
        'marginTop','marginBottom',
        'boxSizing', 'webkitBoxSizing', 'mozBoxSizing', 'msBoxSizing'];

    $.each(properties, function(i, property) {
        equal($pre.css(property), _this.$textarea.css(property),
            'Clone CSS `' + property + '` property equal to that of the textarea');
    });
});

test('Sets the textarea CSS', 3, function() {
    var style = this.$textarea[0].style;
    equal(style.position, 'absolute',
        'Textarea CSS `position` property set to `absolute`');
    equal(style.height, '100%',
        'Textarea CSS `height` property set to 100%');
    equal(style.resize, 'none',
      'Textarea CSS `resize` property set to `none`');
});

test('Updates the clone text on input', 1, function() {
    var text = 'Hello world!';
    this.$textarea.val(text).trigger('input');
    equal(this.$textarea.siblings('pre').find('div').text(), text+' ',
        'Clone’s `div` element updated with the textarea’s value (plus blank space)');
});

test('Invokes `options.resize` callback called on input', 1, function() {
    var $textarea = $('<textarea />').expandingTextarea({
        resize: function callback() {
            ok(true, '`options.resize` callback called');
        }
    });
    $textarea.trigger('input');
});

test('Destroy resets the textarea attributes', function() {
    var height = '100px',
        $textarea = $('<textarea style="height: '+ height +'" />').expandingTextarea();

    // Prevent false positives
    equal($textarea[0].style.height, '100%',
        'Textarea’s CSS `height` property set to 100% on init');

    $textarea.expandingTextarea('destroy');
    ok(!$textarea.hasClass('expanding-init'),
        'Init textarea class name removed on destroy');
    equal($textarea[0].style.height, height,
        'Textarea’s CSS `height` property reset to ' + height + ' on destroy');
    ok(!$textarea.data('expanding-styles'),
        '`expanding-styles` data removed on destroy');
});

test('Destroy removes the clone', 1, function() {
    this.$textarea.expandingTextarea('destroy');
    ok(!this.$textarea.siblings('pre').length,
        'Clone removed');
});

test('Destroy removes the textarea wrapper', 1, function() {
    this.$textarea.expandingTextarea('destroy');
    ok(!this.$textarea.parent().hasClass('expandingText'),
        'Textarea wrapper removed');
});
<commit_msg>Add tests to check dimensions of clone and wrapper<commit_after>module('ExpandingTextareas', {
    setup: function() {
        this.$textarea = $('textarea.manual').expandingTextarea();
    }
});

test('Prevents initializing more than once', 1, function() {
    this.$textarea.expandingTextarea();
    equal(this.$textarea.parents('div.expandingText').length, 1,
        'Textarea has a single `div.expandingText` parent when `expandingTextarea()` called twice');
});

test('Ignores non-textarea elements', 1, function() {
    var $input = $('<input />').expandingTextarea();
    equal($input.parents().length, 0,
        'Non-textarea element not wrapped');
});

test('Returns the jQuery object', 1, function() {
    var $textarea = $('<textarea />');
    equal($textarea.expandingTextarea(), $textarea);
});

test('Wraps the textarea', function() {
    ok(this.$textarea.parent().is('div.expandingText'),
        'Textarea wrapped in `div.expandingText`');
});

test('Sets the textarea wrapper CSS', 1, function() {
    var $wrapper = this.$textarea.parent();
    equal($wrapper.css('position'), 'relative',
        'Textarea wrapper CSS `position` set to `relative`');
});

test('Ensures the clone is at least as tall as the textarea', 1, function() {
    var $textarea = $('<textarea rows="10" />').appendTo('#qunit-fixture');
    expected = $textarea.outerHeight(); // cache textarea height
    $textarea.expandingTextarea();
    equal($textarea.siblings('pre').outerHeight(), expected,
        'Textarea wrapper CSS `min-height` set to textarea outer height');
});

test('Creates a textarea clone', function() {
    var $pre = this.$textarea.siblings('pre');
    equal($pre.length, 1, 'Textarea has a `pre` sibling (clone)');
    equal($pre.find('div').length, 1, 'Textarea clone contains a div');
});

test('Sets the clone CSS `visibility` property', 1, function() {
    var $pre = this.$textarea.siblings('pre');
    equal($pre.css('visibility'), 'hidden',
        'Clone CSS `visibility` property set to `hidden`');
});

test('Sets clone CSS `white-space` property when `textarea[wrap]` is not "off"', 2, function() {
    ok(this.$textarea.attr('wrap') !== 'off');
    equal(this.$textarea.siblings('pre').css('white-space'), 'pre-wrap',
        'Clone CSS `white-space` property set to `pre-wrap`');
});

test('Sets the clone CSS `overflow-x` property when `textarea[wrap=off]`', 1, function() {
    var $textarea = $('<textarea wrap="off" />').expandingTextarea(),
        $pre = $textarea.siblings('pre');
    equal($pre.css('overflow-x'), 'scroll',
        'Clone CSS `overflow-x` property to `scroll`');
});

test('Copies the textarea CSS on to the clone', function() {
    var _this = this,
        $pre = this.$textarea.siblings('pre');

    var properties = [
        'lineHeight', 'textDecoration', 'letterSpacing',
        'fontSize', 'fontFamily', 'fontStyle',
        'fontWeight', 'textTransform', 'textAlign',
        'direction', 'wordSpacing', 'fontSizeAdjust',
        'wordWrap', 'word-break',
        'borderLeftWidth', 'borderRightWidth',
        'borderTopWidth','borderBottomWidth',
        'paddingLeft', 'paddingRight',
        'paddingTop','paddingBottom',
        'marginLeft', 'marginRight',
        'marginTop','marginBottom',
        'boxSizing', 'webkitBoxSizing', 'mozBoxSizing', 'msBoxSizing'];

    $.each(properties, function(i, property) {
        equal($pre.css(property), _this.$textarea.css(property),
            'Clone CSS `' + property + '` property equal to that of the textarea');
    });
});

test('Sets the textarea CSS', 3, function() {
    var style = this.$textarea[0].style;
    equal(style.position, 'absolute',
        'Textarea CSS `position` property set to `absolute`');
    equal(style.height, '100%',
        'Textarea CSS `height` property set to 100%');
    equal(style.resize, 'none',
      'Textarea CSS `resize` property set to `none`');
});

test('Clone dimensions match those of the textarea', 2, function() {
    var $clone = this.$textarea.siblings('pre');
    equal(this.$textarea.outerHeight(true), $clone.outerHeight(true));
    equal(this.$textarea.outerWidth(true), $clone.outerWidth(true));
});

test('Updates the clone text on input', 1, function() {
    var text = 'Hello world!';
    this.$textarea.val(text).trigger('input');
    equal(this.$textarea.siblings('pre').find('div').text(), text+' ',
        'Clone’s `div` element updated with the textarea’s value (plus blank space)');
});

test('Clone and wrapper grow with textarea when long text inserted', 4, function() {
    var $clone = this.$textarea.siblings('pre'),
        $wrapper = this.$textarea.parent(),
        longText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
    for (var i = 0; i < 5; i++) {
        longText += longText + longText;
    }
    this.$textarea.val(longText).trigger('input');
    equal(this.$textarea.outerHeight(true), $clone.outerHeight(true));
    equal(this.$textarea.outerWidth(true), $clone.outerWidth(true));
    equal(this.$textarea.outerHeight(true), $wrapper.outerHeight());
    equal(this.$textarea.outerWidth(true), $wrapper.outerWidth());
});

test('Invokes `options.resize` callback called on input', 1, function() {
    var $textarea = $('<textarea />').expandingTextarea({
        resize: function callback() {
            ok(true, '`options.resize` callback called');
        }
    });
    $textarea.trigger('input');
});

test('Destroy resets the textarea attributes', function() {
    var height = '100px',
        $textarea = $('<textarea style="height: '+ height +'" />').expandingTextarea();

    // Prevent false positives
    equal($textarea[0].style.height, '100%',
        'Textarea’s CSS `height` property set to 100% on init');

    $textarea.expandingTextarea('destroy');
    ok(!$textarea.hasClass('expanding-init'),
        'Init textarea class name removed on destroy');
    equal($textarea[0].style.height, height,
        'Textarea’s CSS `height` property reset to ' + height + ' on destroy');
    ok(!$textarea.data('expanding-styles'),
        '`expanding-styles` data removed on destroy');
});

test('Destroy removes the clone', 1, function() {
    this.$textarea.expandingTextarea('destroy');
    ok(!this.$textarea.siblings('pre').length,
        'Clone removed');
});

test('Destroy removes the textarea wrapper', 1, function() {
    this.$textarea.expandingTextarea('destroy');
    ok(!this.$textarea.parent().hasClass('expandingText'),
        'Textarea wrapper removed');
});
<|endoftext|>


<commit_before>import React from 'react'
import sinon from 'sinon'
import test from 'tape'
import { mount } from 'enzyme'

import withControl from './withControl'

test('withControl creates a valid React element', assert => {
  const Rigged = withControl('base', { useStringRefs: true })(() => <div/>);
  const element = React.createElement(Rigged);
  assert.true(React.isValidElement(element));
  assert.end();
});

test('withControl throws a well-formed error when it does not have the correct context', assert => {
  class Base extends React.Component {
    render() {
      return <div/>;
    }
  }
  const Rigged = withControl('base', { useStringRefs: true })(Base);
  assert.throws(
    () => {
      mount(<Rigged/>, { context: {} });
    },
    /forgot to use an animatronics component/,
  );
  assert.end();
});

test('withControl registers the component when mounted', assert => {
  class Base extends React.Component {
    render() {
      return <div/>;
    }
  }
  const Rigged = withControl('base', { useStringRefs: true })(Base);
  const registerComponent = sinon.spy()
  const wrapper = mount(<Rigged/>, {
    context: {
      animatronics: {
        registerComponent,
        unregisterComponent: () => {},
      },
    },
  });
  assert.true(registerComponent.calledOnce);
  assert.end();
});

test('withControl unregisters the component when unmounted', assert => {
  class Base extends React.Component {
    render() {
      return <div/>;
    }
  }
  const Rigged = withControl('base', { useStringRefs: true })(Base);
  const unregisterComponent = sinon.spy()
  const wrapper = mount(<Rigged/>, {
    context: {
      animatronics: {
        registerComponent: () => {},
        unregisterComponent,
      },
    },
  });
  wrapper.unmount();
  assert.true(unregisterComponent.calledOnce);
  assert.end();
});

test('withControl sets the ref to the DOM node', assert => {
  class Base extends React.Component {
    render() {
      return <div/>;
    }
  }

  const Rigged = withControl('base', { useStringRefs: true })(Base);
  let actualDOMNode;

  const wrapper = mount(<Rigged/>, {
    context: {
      animatronics: {
        registerComponent: (componentName, domNode, styleUpdater) => {
          actualDOMNode = domNode;
        },
        unregisterComponent: () => {},
      },
    },
  });

  const expectedDOMNode = wrapper.find('div').getDOMNode();
  assert.equal(actualDOMNode, expectedDOMNode);
  assert.end();
});
<commit_msg>:art: [withControl] Renamed "Rigged" --> "Controlled" in test<commit_after>import React from 'react'
import sinon from 'sinon'
import test from 'tape'
import { mount } from 'enzyme'

import withControl from './withControl'

test('withControl creates a valid React element', assert => {
  const Controlled = withControl('base', { useStringRefs: true })(() => <div/>);
  const element = React.createElement(Controlled);
  assert.true(React.isValidElement(element));
  assert.end();
});

test('withControl throws a well-formed error when it does not have the correct context', assert => {
  class Base extends React.Component {
    render() {
      return <div/>;
    }
  }
  const Controlled = withControl('base', { useStringRefs: true })(Base);
  assert.throws(
    () => {
      mount(<Controlled/>, { context: {} });
    },
    /forgot to use an animatronics component/,
  );
  assert.end();
});

test('withControl registers the component when mounted', assert => {
  class Base extends React.Component {
    render() {
      return <div/>;
    }
  }
  const Controlled = withControl('base', { useStringRefs: true })(Base);
  const registerComponent = sinon.spy()
  const wrapper = mount(<Controlled/>, {
    context: {
      animatronics: {
        registerComponent,
        unregisterComponent: () => {},
      },
    },
  });
  assert.true(registerComponent.calledOnce);
  assert.end();
});

test('withControl unregisters the component when unmounted', assert => {
  class Base extends React.Component {
    render() {
      return <div/>;
    }
  }
  const Controlled = withControl('base', { useStringRefs: true })(Base);
  const unregisterComponent = sinon.spy()
  const wrapper = mount(<Controlled/>, {
    context: {
      animatronics: {
        registerComponent: () => {},
        unregisterComponent,
      },
    },
  });
  wrapper.unmount();
  assert.true(unregisterComponent.calledOnce);
  assert.end();
});

test('withControl sets the ref to the DOM node', assert => {
  class Base extends React.Component {
    render() {
      return <div/>;
    }
  }

  const Controlled = withControl('base', { useStringRefs: true })(Base);
  let actualDOMNode;

  const wrapper = mount(<Controlled/>, {
    context: {
      animatronics: {
        registerComponent: (componentName, domNode, styleUpdater) => {
          actualDOMNode = domNode;
        },
        unregisterComponent: () => {},
      },
    },
  });

  const expectedDOMNode = wrapper.find('div').getDOMNode();
  assert.equal(actualDOMNode, expectedDOMNode);
  assert.end();
});
<|endoftext|>


<commit_before>var spelling = function(dbot) {
    var dbot = dbot;
    var last = {};

    return {
        'listener': function(data, params) {
            var q = data.message.valMatch(/^\*\*?([\d\w\s]*)/, 2);
            var otherQ = data.message.valMatch(/^([\d\w\s]*): \*\*?([\d\w\s]*)/);
            if(q) {
                var correction = q[1];
                var candidates = last[data.channel][data.user].split(' ');
                var winner = false;
                var winnerDistance = 99999999; //urgh fix later

                for(var i=0;i<candidates.length;i++) {
                    var distance = String.prototype.distance(correction, candidates[i]);
                    if(distance < winnerDistance) {
                        winner = candidates[i];
                        winnerDistance = distance;
                    }
                }

                if(winnerDistance < 3) {
                    if(winner !== correction) {
                        var fix = last[data.channel][data.user].replace(winner, correction);
                        last[data.channel][data.user] = fix;
                        dbot.say(data.channel, data.user + ' meant: ' + fix);
                    }
                }
            } else if(otherQ) {
                if(last[data.channel].hasOwnProperty([otherQ[1]])) {
                    var correction = otherQ[2];
                    var candidates = last[data.channel][otherQ[1]].split(' ');
                    var winner = false;
                    var winnerDistance = 99999999; //urgh fix later

                    for(var i=0;i<candidates.length;i++) {
                        var distance = String.prototype.distance(correction, candidates[i]);
                        if(distance < winnerDistance) {
                            winner = candidates[i];
                            winnerDistance = distance;
                        }
                    }

                    if(winnerDistance < 3) {
                        if(winner !== correction) {
                            var fix = last[data.channel][otherQ[1]].replace(winner, correction);
                            last[data.channel][otherQ[1]] = fix;
                            dbot.say(data.channel, data.user + ' thinks ' + otherQ[1] + ' meant: ' + fix);
                        }
                    }
                }
            } else {
                 if(last.hasOwnProperty(data.channel)) {
                   last[data.channel][data.user] = data.message;
                } else {
                    last[data.channel] = { };
                    last[data.channel][data.user] = data.message;
                }
            }
        },

        'on': 'PRIVMSG'
    }
}

exports.fetch = function(dbot) {
    return spelling(dbot);
};
<commit_msg>valmatch correction<commit_after>var spelling = function(dbot) {
    var dbot = dbot;
    var last = {};

    return {
        'listener': function(data, params) {
            var q = data.message.valMatch(/^\*\*?([\d\w\s]*)/, 2);
            var otherQ = data.message.valMatch(/^([\d\w\s]*): \*\*?([\d\w\s]*)/, 3);
            if(q) {
                var correction = q[1];
                var candidates = last[data.channel][data.user].split(' ');
                var winner = false;
                var winnerDistance = 99999999; //urgh fix later

                for(var i=0;i<candidates.length;i++) {
                    var distance = String.prototype.distance(correction, candidates[i]);
                    if(distance < winnerDistance) {
                        winner = candidates[i];
                        winnerDistance = distance;
                    }
                }

                if(winnerDistance < 3) {
                    if(winner !== correction) {
                        var fix = last[data.channel][data.user].replace(winner, correction);
                        last[data.channel][data.user] = fix;
                        dbot.say(data.channel, data.user + ' meant: ' + fix);
                    }
                }
            } else if(otherQ) {
                if(last[data.channel].hasOwnProperty([otherQ[1]])) {
                    var correction = otherQ[2];
                    var candidates = last[data.channel][otherQ[1]].split(' ');
                    var winner = false;
                    var winnerDistance = 99999999; //urgh fix later

                    for(var i=0;i<candidates.length;i++) {
                        var distance = String.prototype.distance(correction, candidates[i]);
                        if(distance < winnerDistance) {
                            winner = candidates[i];
                            winnerDistance = distance;
                        }
                    }

                    if(winnerDistance < 3) {
                        if(winner !== correction) {
                            var fix = last[data.channel][otherQ[1]].replace(winner, correction);
                            last[data.channel][otherQ[1]] = fix;
                            dbot.say(data.channel, data.user + ' thinks ' + otherQ[1] + ' meant: ' + fix);
                        }
                    }
                }
            } else {
                 if(last.hasOwnProperty(data.channel)) {
                   last[data.channel][data.user] = data.message;
                } else {
                    last[data.channel] = { };
                    last[data.channel][data.user] = data.message;
                }
            }
        },

        'on': 'PRIVMSG'
    }
}

exports.fetch = function(dbot) {
    return spelling(dbot);
};
<|endoftext|>


<commit_before>import test from 'ava'
import fileUtils from '../src/fileUtils'

const testDir = `${__dirname}/fileutils-test`

test.before(async t => {
  await fileUtils.remove(testDir)
  const exists = await fileUtils.exists(testDir)
  t.false(exists)
})

test.after(async t => {
  await fileUtils.remove(testDir)
  const exists = await fileUtils.exists(testDir)
  t.false(exists)
})

test('should exists', async t => {
  const exists = await fileUtils.exists(testDir)
  t.false(exists)
})

test('should ensureDir', async t => {
  const dir = `${testDir}/foo/bar`
  let exists = await fileUtils.exists(dir)
  t.false(exists)

  await fileUtils.ensureDir(dir)
  exists = await fileUtils.exists(dir)
  t.true(exists)
})

test('should ensureFile', async t => {
  const file = `${testDir}/foo/a.txt`
  let exists = await fileUtils.exists(file)
  t.false(exists)

  await fileUtils.ensureFile(file)
  exists = await fileUtils.exists(file)
  t.true(exists)
})

test('should remove', async t => {
  const file = `${testDir}/foo/b.txt`
  await fileUtils.ensureFile(file)
  let exists = await fileUtils.exists(file)
  t.true(exists)

  await fileUtils.remove(file)
  exists = await fileUtils.exists(file)
  t.false(exists)
})

test('should readFile & writeFile', async t => {
  const file = `${testDir}/foo/c.txt`
  let exists = await fileUtils.exists(file)
  t.false(exists)

  await fileUtils.writeFile(file, '测试')
  exists = await fileUtils.exists(file)
  t.true(exists)

  const content = await fileUtils.readFile(file)
  t.is(content, '测试')
})

test('should searchFile', async t => {
  const filename = 'd.txt'
  const filePath = `${testDir}/${filename}`
  await fileUtils.ensureFile(filePath)

  let exists = await fileUtils.searchFile(filename, `${testDir}`)
  t.is(exists, filePath)

  exists = await fileUtils.searchFile(filename, `${testDir}/foo`)
  t.is(exists, filePath)

  exists = await fileUtils.searchFile(filename, `${testDir}/foo/`)
  t.is(exists, filePath)

  exists = await fileUtils.searchFile(filename, `${testDir}/foo//`)
  t.is(exists, filePath)
})
<commit_msg>test: improve fileUtils test<commit_after>import test from 'ava'
import fileUtils from '../src/fileUtils'

const testDir = `${__dirname}/fileutils-test`

test.before(async () => {
  await fileUtils.remove(testDir)
})

test.after(async () => {
  await fileUtils.remove(testDir)
})

test('should exists', async t => {
  const exists = await fileUtils.exists(testDir)
  t.false(exists)
})

test('should ensureDir', async t => {
  const dir = `${testDir}/foo/bar`
  let exists = await fileUtils.exists(dir)
  t.false(exists)

  await fileUtils.ensureDir(dir)
  exists = await fileUtils.exists(dir)
  t.true(exists)
})

test('should ensureFile', async t => {
  const file = `${testDir}/foo/a.txt`
  let exists = await fileUtils.exists(file)
  t.false(exists)

  await fileUtils.ensureFile(file)
  exists = await fileUtils.exists(file)
  t.true(exists)
})

test('should remove', async t => {
  const file = `${testDir}/foo/b.txt`
  await fileUtils.ensureFile(file)
  let exists = await fileUtils.exists(file)
  t.true(exists)

  await fileUtils.remove(file)
  exists = await fileUtils.exists(file)
  t.false(exists)
})

test('should readFile & writeFile', async t => {
  const file = `${testDir}/foo/c.txt`
  let exists = await fileUtils.exists(file)
  t.false(exists)

  await fileUtils.writeFile(file, '测试')
  exists = await fileUtils.exists(file)
  t.true(exists)

  let content = await fileUtils.readFile(file)
  t.is(content, '测试')

  content = await fileUtils.readFile(file, 'base64')
  t.is(content, '5rWL6K+V')
})

test('should searchFile', async t => {
  const filename = 'd.txt'
  const filePath = `${testDir}/${filename}`
  await fileUtils.ensureFile(filePath)

  let result = await fileUtils.searchFile(filename, `${testDir}`)
  t.is(result, filePath)

  result = await fileUtils.searchFile(filename, `${testDir}/foo`)
  t.is(result, filePath)

  result = await fileUtils.searchFile(filename, `${testDir}/foo/`)
  t.is(result, filePath)

  result = await fileUtils.searchFile(filename, `${testDir}/foo//`)
  t.is(result, filePath)

  result = await fileUtils.searchFile(filename, `${testDir}/foo/bar`)
  t.is(result, filePath)

  result = await fileUtils.searchFile(filename, '/test')
  t.is(result, null)

  result = await fileUtils.searchFile('not-exists-file.txt')
  t.is(result, null)
})
<|endoftext|>


<commit_before>import React from 'react'
import test from 'tape'
import { shallow } from 'enzyme'

import withControl from './withControl'
import Control from './Control'

test.only('withControl', assert => {
  const Controlled = withControl('base', { useStringRefs: true })(() => <div/>);
  const wrapper = shallow(
    <Controlled/>,
    {
      context: {
        animatronics: {
          registerComponent: () => {},
          unregisterComponent: () => {},
        },
      }
    }
  );
  assert.true(wrapper.find(Control), 'contains the Control component');
  assert.end();
});
<commit_msg>:white_check_mark: [withControl] Remove .only<commit_after>import React from 'react'
import test from 'tape'
import { shallow } from 'enzyme'

import withControl from './withControl'
import Control from './Control'

test('withControl', assert => {
  const Controlled = withControl('base', { useStringRefs: true })(() => <div/>);
  const wrapper = shallow(
    <Controlled/>,
    {
      context: {
        animatronics: {
          registerComponent: () => {},
          unregisterComponent: () => {},
        },
      }
    }
  );
  assert.true(wrapper.find(Control), 'contains the Control component');
  assert.end();
});
<|endoftext|>


<commit_before>/*
 * grunt-serve
 * https://github.com/lud2k/grunt-serve
 *
 * Copyright (c) 2014 Ludovic Cabre
 * Licensed under the MIT license.
 */

'use strict';

var	childProcess = require("child_process"),
	fs = require('fs'),
	dot = require('dot'),
	paths = require('path'),
	contentTypes = require('../data/content_types.js'),
	jwt = require('jsonwebtoken'),
	express = require('express'),
	app = express(),
	server;
// requires

// load all template files
var loadTemplate = function(name) {
		return dot.template(fs.readFileSync(paths.join(__dirname, '..', 'pages', name)))
	},
	indexTmpl = loadTemplate('index.html'),
	notFoundTmpl = loadTemplate('not_found.html'),
	directoryTmpl = loadTemplate('directory.html'),
	errorTmpl = loadTemplate('error.html'),
	successTmpl = loadTemplate('success.html'),
	gruntErrorTmpl = loadTemplate('grunt_error.html'),
	missingTmpl = loadTemplate('missing.html'),
	unauthTmpl = loadTemplate('unauthorized.html');

/**
 * Definition of the exported method that will be called by Grunt on initialization.
 */
module.exports = function(grunt) {

	grunt.registerTask('_serve_selftest', 'Test grunt serve', function(){
		grunt.log.write('task testing successful');
	});

	//Aufrufen mit /task/serve_selfupdate:<url>
	grunt.registerTask('_serve_selfupdate', 'Updates the Repo and start serve again', function() {
		var options = this.options({
			localrepo: './',
			linkrepo: 'defaultLink'
		})
		if(options.linkrepo == ''){
			grunt.log.write('no link');
		} else{
			/*grunt.log.write('ich will mal was tolles machen \n');
			git().pull(function(err, update) {
				grunt.log.write('ich habe gepullt (: \n')
				if(update){
					grunt.log.write('ich habe ein update gemacht (: \n');
					//beende serve
					//process.exit(1);
				}
			});*/
			grunt.log.write('link: '+ options.link);
			grunt.log.write('local: '+ options.localrepo);
		}
	})
	// register serve task
	grunt.registerTask('serve', 'Starts a http server that can be called to run tasks.', function() {
		// control when the task should end
	    var done = this.async();

		// get options
		var options = this.options({
			port: 9000,
			keypath: './public.pem',
			silently: false,
			serve: {
				path: process.cwd()
			}
		});

		app.get ('/', function(req, res) {
			try{
				var cert = fs.readFileSync(options.keypath);
				var token = req.headers.webtoken;
				jwt.verify(token,cert,{algorithms: ['RS256']}, function(err, payload){
					if(err){
						err = {
							name: 'JsonWebTokenError',
							message: 'invalid signature'
						}
						render(res, 401, unauthTmpl, null, {info: 'unauthorized'}, options.port);
					} else{
						// forward request
						render(res, 200, indexTmpl, {
							host: req.headers.host,
							aliases: mapToArray(options.aliases, 'name'),
							files: filesInDirectory(grunt, options, '.'),
						}, {info: 'OK'}, options.port);
					}
				});
			} catch (e) {
				render(res, 500, errorTmpl, {
					error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
				}, {info: 'Error'}, options.port);
			}
		});

		app.get ('/task/:taskname', function(req, res) {
			try {
				var cert = fs.readFileSync(options.keypath);
				var token = req.headers.webtoken;
				jwt.verify(token,cert,{algorithms: ['RS256']}, function(err, payload){
					if(err){
						err = {
							name: 'JsonWebTokenError',
							message: 'invalid signature'
						}
						render(res, 401, unauthTmpl, null, {info: 'unauthorized'}, options.port);
					} else{
						var tasks = req.params.taskname.split(','),
						output = null;

						// run tasks
						executeTasks(req, res, grunt, options, tasks, output, null, options.port);
						return;
					}
				});
			} catch(e) {
				// show error
				render(res, 500, errorTmpl, {
					error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
				}, {info: 'Error'}, options.port);
			}
		});

		server = app.listen(options.port);

		// handle SIGINT signal properly
		process.on('SIGINT', function() {
			// terminate task
		    done();
		});
    	// a few messages
		grunt.log.write('Server is running on port '+options.port+'...\n');
		grunt.log.write('Press CTRL+C at any time to terminate it.\n');
	});
	grunt.registerTask('showTasks', 'show tasks', function(){
		displayTasks(grunt);
	});
}

/**
 * Handles all requests to the server.
 * Each call with trigger a call to the following function.
 */

/*
function handleRequest(request, response, grunt, options) {

	// is this url contains virtual root? If so, remove it
	if (options.virtualRoot) {
		if (path.indexOf(options.virtualRoot) === 0) {
			path = path.substr(options.virtualRoot.length);
		}
	}

	// does this path match an alias?
	var aliasName = path.substr(1);
	var aliases = options.aliases;
	if (aliases && aliases[aliasName]) {
		// get alias configuration
		var tasks = aliases[aliasName].tasks,
			output = aliases[aliasName].output,
			contentType = aliases[aliasName].contentType;

		if (!tasks) throw "No tasks were defined for alias: "+aliasName;

		// run tasks
		executeTasks(request, response, grunt, options, tasks, output, contentType);
		return;
	}
}
*/

function displayTasks(grunt){
	console.dir("start");
	var tasks = grunt.task._tasks;
	console.dir(tasks);
	for (var task in tasks) {

		console.dir(task);
		if(grunt.config.getRaw(grunt.task._tasks[task].name)){
			var config = grunt.config.getRaw(grunt.task._tasks[task].name);
			var targets = [];
			if (typeof config === 'object'){
				targets = Object.keys(config);
				console.dir(targets);
				//console.dir(grunt.config.get(grunt.task._tasks[task].name));
			}
		}
	}

}

/**
 * Runs Grunt to execute the given tasks.
 */
function executeTasks(request, response, grunt, options, tasks, output, contentType, port) {
	// execute tasks
	childProcess.exec('grunt '+tasks.join(' '), function(error, stdout, stderr) {
		try {
			// should we print the stdout?
			if (!options.silently) {
				// print stdout
				console.log(stdout);

				// print stderr (if any)
				if (stderr) {
					console.log(stderr);
				}
			}

			// any error? write logs and return
			if (stderr || error) {
			    render(response, 500, gruntErrorTmpl, {
			    	tasks: tasks,
			    	stdout: formatStdout(stdout),
			    	stderr: formatStdout(stderr)
			    }, {info: 'Error'}, port);
				return;
			}

		    // the the output stdout?
		    if (output == 'stdout' || !output) {
			    // write stdout
		    	render(response, 200, successTmpl, {
		    		output: formatStdout(stdout)
		    	}, {info: 'OK'}, port);

		    } else {
		    	// requested output file exists?
				if (grunt.file.exists(output)) {
					// write file
		    		write(response, 200, grunt, output, contentType);
				} else {
					// show file not found
				    render(response, 500, missingTmpl, {
				    	output: output
				    } , {info: 'Error'}, port);
				}
		    }
		} catch(e) {
			// show error
		    render(response, 500, errorTmpl, {
		    	error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
		    }, {info: 'Error'}, options.port);
		}
	});
}

/**
 * Renders a json response.
 */
function render(response, code, template, data, info, port) {
	var json = JSON.stringify({
		statusCode : code,
		text: info,
		link: "http://localhost/" + port
	})
	if (!response.headersSent) {
		response.writeHead(code, {"Content-Type": "application/json"});
	}
    response.end(json);
}

/**
 * Renders a html page and ends the request.
 */

/*
function render(response, code, template, data) {
	var json = JSON.stringify({
		statusCode : code,
		templ : template,
		text: "test123"
	})
	if (!response.headersSent) {
		response.writeHead(code, {"Content-Type": "application/json"});
	}
    response.end(json);
}

/**
 * Renders a html page and ends the request.
 */

/*
function render(response, code, template, data) {
	var html = template(data);
	if (!response.headersSent) {
	    response.writeHead(code, {"Content-Type": "text/html"});
	}
    response.end(html);
}
*/

/**
 * Writes a file's content to the output and ends the request.
 */
function write(response, code, grunt, file, contentType) {
	var data = fs.readFileSync(file);
	if (!response.headersSent) {
	    response.writeHead(200, headersForOutput(file, contentType));
	}
	response.end(data);
}

/**
 * Converts a map to an array adding the key to the value.
 */
function mapToArray(map, name) {
	var ret = [];
	for (var key in map) {
		map[key][name] = key;
		ret.push(map[key]);
	}
	return ret;
}

/**
 * Returns the list of files in the given directory.
 */
function filesInDirectory(grunt, options, path) {
	var ret = [],
		fullPath = paths.join(options.serve.path, path),
		files = fs.readdirSync(fullPath);

	// for each file
	for (var i=0; i<files.length; i++) {
		var file = files[i],
			stats = fs.statSync(paths.join(fullPath, file)),
			isDir = stats.isDirectory();

		// skip ., .. and hidden files
		if (file.charAt(0) == '.') continue;

		ret.push({
			path: path ? path + '/' + file : file,
			name: file,
			isDir: isDir
		});
	}

	return ret;
}

/**
 * Returns the headers that fits the best the output.
 * Will also add headers to prevent caching.
 */
function headersForOutput(path, contentType) {
	// disable caching
	var ret = {
		'Cache-Control': 'no-cache, no-store, must-revalidate',
		'Pragma': 'no-cache',
		'Expires': '0'
	}

	// try to auto detect the content type
	if (!contentType) {
		contentType = contentTypes(path);
		if (contentType) {
			ret['Content-Type'] = contentType;
		}
	}

	return ret;
}

/**
 * Converts Grunt's stdout into html.
 * (keeping the colors the same)
 */
function formatStdout(stdout) {
	var regex = /\x1B\[(\d+)m/g,
		opened = false,
		colors = {
			'0': '#000000',
			'30': '#000000',
			'31': '#CC0000',
			'32': '#00CC00',
			'33': '#CCCC00',
			'34': '#00CC00',
			'35': '#CC00CC',
			'36': '#00CCCC',
			'37': '#999999'
		},
		match;

	// replace all colors markers by html
	while ((match = regex.exec(stdout))) {
		var code = match[1]+'',
			start = stdout.substr(0, match.index),
			end = stdout.substr(match.index+3+code.length);

		if (code) {
			var colorEnd = opened ? '' : '',
				colorStart = '';
			stdout = start + colorEnd + colorStart + end;

		} else {
			stdout = start + end;
		}

		opened = true;
	}

	// replace all line return by the html equivalent
	return stdout.replace(/\n+/g, '
');
}
<commit_msg>edit JSON-response<commit_after>/*
 * grunt-serve
 * https://github.com/lud2k/grunt-serve
 *
 * Copyright (c) 2014 Ludovic Cabre
 * Licensed under the MIT license.
 */

'use strict';

var	childProcess = require("child_process"),
	fs = require('fs'),
	dot = require('dot'),
	paths = require('path'),
	contentTypes = require('../data/content_types.js'),
	jwt = require('jsonwebtoken'),
	express = require('express'),
	app = express(),
	server;
// requires

// load all template files
var loadTemplate = function(name) {
		return dot.template(fs.readFileSync(paths.join(__dirname, '..', 'pages', name)))
	},
	indexTmpl = loadTemplate('index.html'),
	notFoundTmpl = loadTemplate('not_found.html'),
	directoryTmpl = loadTemplate('directory.html'),
	errorTmpl = loadTemplate('error.html'),
	successTmpl = loadTemplate('success.html'),
	gruntErrorTmpl = loadTemplate('grunt_error.html'),
	missingTmpl = loadTemplate('missing.html'),
	unauthTmpl = loadTemplate('unauthorized.html');

/**
 * Definition of the exported method that will be called by Grunt on initialization.
 */
module.exports = function(grunt) {

	grunt.registerTask('_serve_selftest', 'Test grunt serve', function(){
		grunt.log.write('task testing successful');
	});

	//Aufrufen mit /task/serve_selfupdate:<url>
	grunt.registerTask('_serve_selfupdate', 'Updates the Repo and start serve again', function() {
		var options = this.options({
			localrepo: './',
			linkrepo: 'defaultLink'
		})
		if(options.linkrepo == ''){
			grunt.log.write('no link');
		} else{
			/*grunt.log.write('ich will mal was tolles machen \n');
			git().pull(function(err, update) {
				grunt.log.write('ich habe gepullt (: \n')
				if(update){
					grunt.log.write('ich habe ein update gemacht (: \n');
					//beende serve
					//process.exit(1);
				}
			});*/
			grunt.log.write('link: '+ options.link);
			grunt.log.write('local: '+ options.localrepo);
		}
	})
	// register serve task
	grunt.registerTask('serve', 'Starts a http server that can be called to run tasks.', function() {
		// control when the task should end
	    var done = this.async();

		// get options
		var options = this.options({
			port: 9000,
			keypath: './public.pem',
			silently: false,
			serve: {
				path: process.cwd()
			}
		});

		app.get ('/', function(req, res) {
			try{
				var cert = fs.readFileSync(options.keypath);
				var token = req.headers.webtoken;
				jwt.verify(token,cert,{algorithms: ['RS256']}, function(err, payload){
					if(err){
						err = {
							name: 'JsonWebTokenError',
							message: 'invalid signature'
						}
						render(res, 401, unauthTmpl, null, {info: 'unauthorized'}, options.port);
					} else{
						// forward request
						render(res, 200, indexTmpl, {
							host: req.headers.host,
							aliases: mapToArray(options.aliases, 'name'),
							files: filesInDirectory(grunt, options, '.'),
						}, {info: 'OK'}, options.port);
					}
				});
			} catch (e) {
				render(res, 500, errorTmpl, {
					error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
				}, {info: 'Error'}, options.port);
			}
		});

		app.get ('/task/:taskname', function(req, res) {
			try {
				var cert = fs.readFileSync(options.keypath);
				var token = req.headers.webtoken;
				jwt.verify(token,cert,{algorithms: ['RS256']}, function(err, payload){
					if(err){
						err = {
							name: 'JsonWebTokenError',
							message: 'invalid signature'
						}
						render(res, 401, unauthTmpl, null, {info: 'unauthorized'}, options.port);
					} else{
						var tasks = req.params.taskname.split(','),
						output = null;

						// run tasks
						executeTasks(req, res, grunt, options, tasks, output, null, options.port);
						return;
					}
				});
			} catch(e) {
				// show error
				render(res, 500, errorTmpl, {
					error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
				}, {info: 'Error'}, options.port);
			}
		});

		server = app.listen(options.port);

		// handle SIGINT signal properly
		process.on('SIGINT', function() {
			// terminate task
		    done();
		});
    	// a few messages
		grunt.log.write('Server is running on port '+options.port+'...\n');
		grunt.log.write('Press CTRL+C at any time to terminate it.\n');
	});
	grunt.registerTask('showTasks', 'show tasks', function(){
		displayTasks(grunt);
	});
}

/**
 * Handles all requests to the server.
 * Each call with trigger a call to the following function.
 */

/*
function handleRequest(request, response, grunt, options) {

	// is this url contains virtual root? If so, remove it
	if (options.virtualRoot) {
		if (path.indexOf(options.virtualRoot) === 0) {
			path = path.substr(options.virtualRoot.length);
		}
	}

	// does this path match an alias?
	var aliasName = path.substr(1);
	var aliases = options.aliases;
	if (aliases && aliases[aliasName]) {
		// get alias configuration
		var tasks = aliases[aliasName].tasks,
			output = aliases[aliasName].output,
			contentType = aliases[aliasName].contentType;

		if (!tasks) throw "No tasks were defined for alias: "+aliasName;

		// run tasks
		executeTasks(request, response, grunt, options, tasks, output, contentType);
		return;
	}
}
*/

function displayTasks(grunt){
	var tasks = grunt.task._tasks;
	console.dir(tasks);
	for (var task in tasks) {

		console.dir(task);
		if(grunt.config.getRaw(grunt.task._tasks[task].name)){
			var config = grunt.config.getRaw(grunt.task._tasks[task].name);
			var targets = [];
			if (typeof config === 'object'){
				targets = Object.keys(config);
				console.dir(targets);
				//console.dir(grunt.config.get(grunt.task._tasks[task].name));
			}
		}
	}
	return tasks;
}

/**
 * Runs Grunt to execute the given tasks.
 */
function executeTasks(request, response, grunt, options, tasks, output, contentType, port) {
	// execute tasks
	childProcess.exec('grunt '+tasks.join(' '), function(error, stdout, stderr) {
		try {
			// should we print the stdout?
			if (!options.silently) {
				// print stdout
				console.log(stdout);

				// print stderr (if any)
				if (stderr) {
					console.log(stderr);
				}
			}

			// any error? write logs and return
			if (stderr || error) {
			    render(response, 500, gruntErrorTmpl, {
			    	tasks: tasks,
			    	stdout: formatStdout(stdout),
			    	stderr: formatStdout(stderr)
			    }, {info: 'Error'}, port);
				return;
			}

		    // the the output stdout?
		    if (output == 'stdout' || !output) {
			    // write stdout
		    	render(response, 200, successTmpl, {
		    		output: formatStdout(stdout)
		    	}, {info: 'OK'}, port);

		    } else {
		    	// requested output file exists?
				if (grunt.file.exists(output)) {
					// write file
		    		write(response, 200, grunt, output, contentType);
				} else {
					// show file not found
				    render(response, 500, missingTmpl, {
				    	output: output
				    } , {info: 'Error'}, port);
				}
		    }
		} catch(e) {
			// show error
		    render(response, 500, errorTmpl, {
		    	error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
		    }, {info: 'Error'}, options.port);
		}
	});
}

/**
 * Renders a json response.
 */
function render(response, code, template, data, info, port) {
	var json = JSON.stringify({
		statusCode : code,
		text: info,
		link: "http://localhost/" + port,
		tasklist: displayTasks(grunt)
	})
	if (!response.headersSent) {
		response.writeHead(code, {"Content-Type": "application/json"});
	}
    response.end(json);
}

/**
 * Renders a html page and ends the request.
 */

/*
function render(response, code, template, data) {
	var json = JSON.stringify({
		statusCode : code,
		templ : template,
		text: "test123"
	})
	if (!response.headersSent) {
		response.writeHead(code, {"Content-Type": "application/json"});
	}
    response.end(json);
}

/**
 * Renders a html page and ends the request.
 */

/*
function render(response, code, template, data) {
	var html = template(data);
	if (!response.headersSent) {
	    response.writeHead(code, {"Content-Type": "text/html"});
	}
    response.end(html);
}
*/

/**
 * Writes a file's content to the output and ends the request.
 */
function write(response, code, grunt, file, contentType) {
	var data = fs.readFileSync(file);
	if (!response.headersSent) {
	    response.writeHead(200, headersForOutput(file, contentType));
	}
	response.end(data);
}

/**
 * Converts a map to an array adding the key to the value.
 */
function mapToArray(map, name) {
	var ret = [];
	for (var key in map) {
		map[key][name] = key;
		ret.push(map[key]);
	}
	return ret;
}

/**
 * Returns the list of files in the given directory.
 */
function filesInDirectory(grunt, options, path) {
	var ret = [],
		fullPath = paths.join(options.serve.path, path),
		files = fs.readdirSync(fullPath);

	// for each file
	for (var i=0; i<files.length; i++) {
		var file = files[i],
			stats = fs.statSync(paths.join(fullPath, file)),
			isDir = stats.isDirectory();

		// skip ., .. and hidden files
		if (file.charAt(0) == '.') continue;

		ret.push({
			path: path ? path + '/' + file : file,
			name: file,
			isDir: isDir
		});
	}

	return ret;
}

/**
 * Returns the headers that fits the best the output.
 * Will also add headers to prevent caching.
 */
function headersForOutput(path, contentType) {
	// disable caching
	var ret = {
		'Cache-Control': 'no-cache, no-store, must-revalidate',
		'Pragma': 'no-cache',
		'Expires': '0'
	}

	// try to auto detect the content type
	if (!contentType) {
		contentType = contentTypes(path);
		if (contentType) {
			ret['Content-Type'] = contentType;
		}
	}

	return ret;
}

/**
 * Converts Grunt's stdout into html.
 * (keeping the colors the same)
 */
function formatStdout(stdout) {
	var regex = /\x1B\[(\d+)m/g,
		opened = false,
		colors = {
			'0': '#000000',
			'30': '#000000',
			'31': '#CC0000',
			'32': '#00CC00',
			'33': '#CCCC00',
			'34': '#00CC00',
			'35': '#CC00CC',
			'36': '#00CCCC',
			'37': '#999999'
		},
		match;

	// replace all colors markers by html
	while ((match = regex.exec(stdout))) {
		var code = match[1]+'',
			start = stdout.substr(0, match.index),
			end = stdout.substr(match.index+3+code.length);

		if (code) {
			var colorEnd = opened ? '' : '',
				colorStart = '';
			stdout = start + colorEnd + colorStart + end;

		} else {
			stdout = start + end;
		}

		opened = true;
	}

	// replace all line return by the html equivalent
	return stdout.replace(/\n+/g, '
');
}
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/userdata/:organization/:product/:user', function (req, res, next) {
  res.redirect(['/portal#', 'userevents', req.params.organization, req.params.product, req.params.user].join('/'));
});

module.exports = router;
<commit_msg>update link<commit_after>var express = require('express');
var router = express.Router();

router.get('/userdata/:organization/:product/:user', function (req, res, next) {
  res.redirect(['/dashboard/#', 'userevents', req.params.organization, req.params.product, req.params.user].join('/'));
});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

var Task = require('wheelie/lib/models/task');

function config(globals) {
  // TODO: we should get these values from the plugins registry

  return {
    sass: globals.src + '/scss/**/*.{sass,scss}',
    assets: globals.src + '/assets/**',
    templates: globals.src + '/templates/**',
    jshint: [
      'gulpfile.js',
      globals.src + '/js/**/*.js'
    ]
  };
}

function run(gulp, config) {
  return function() {
    gulp.watch(config.sass, ['sass']);
    gulp.watch(config.assets, ['assets']);
    gulp.watch(config.templates, ['templates']);
    gulp.watch(config.jshint, ['jshint']);
  };
}

module.exports = new Task('watch', ['browser-sync', 'build'], run, config);
<commit_msg>added Handlebars watcher<commit_after>'use strict';

var Task = require('wheelie/lib/models/task');

function config(globals) {
  // TODO: we should get these values from the plugins registry

  return {
    sass: globals.src + '/scss/**/*.{sass,scss}',
    assets: globals.src + '/assets/**',
    templates: globals.src + '/templates/**',
    handlebars: globals.src + '/partials/**',
    jshint: [
      'gulpfile.js',
      globals.src + '/js/**/*.js'
    ]
  };
}

function run(gulp, config) {
  return function() {
    gulp.watch(config.sass, ['sass']);
    gulp.watch(config.assets, ['assets']);
    gulp.watch(config.templates, ['templates']);
    gulp.watch(config.handlebars, ['handlebars']);
    gulp.watch(config.jshint, ['jshint']);
  };
}

module.exports = new Task('watch', ['browser-sync', 'build'], run, config);
<|endoftext|>


<commit_before>'use strict';

var formatter = require('../lib/formatter'),
    should = require('should');

describe('formatter', function() {
    describe('formatter.header', function() {
        var header = 'my-file.js';

        it('is a function', function(done) {
            formatter.header.should.be.type('function');
            done();
        });

        it('should format a header', function(done) {
            formatter.header(header).should.be.exactly(header + ':');
            done();
        });
    });

    it('exists', function(done) {
        formatter.should.be.ok;
        done();
    });

    it('is a object', function(done) {
        formatter.should.be.type('object');
        done();
    });

    describe('formatter.line', function() {
        var givenString, expectedString;

        it('is a function', function(done) {
            formatter.line.should.be.type('function');
            done();
        });

        it('formats a string properly given a line number', function(done) {
            givenString = 'TODO: update client-side Session model to overwrite toJSON',
            expectedString = '  * [Line 8] [TODO] update client-side Session model to overwrite toJSON';

            formatter.line(givenString, 8).should.be.exactly(expectedString);

            done();
        });

        it('ignores code prefacing code', function(done) {
            givenString = '[1, 2, 3].forEach(function(number) { // TODO: declare new var & replace hard-coded',
            expectedString = '  * [Line 11] [TODO] declare new var & replace hard-coded';

            formatter.line(givenString, 11).should.be.exactly(expectedString);

            done();
        });
    });
});
<commit_msg>update formatter spec order"<commit_after>'use strict';

var formatter = require('../lib/formatter'),
    should = require('should');

describe('formatter', function() {
    it('exists', function(done) {
        formatter.should.be.ok;
        done();
    });

    it('is a object', function(done) {
        formatter.should.be.type('object');
        done();
    });

    describe('formatter.header', function() {
        var header = 'my-file.js';

        it('is a function', function(done) {
            formatter.header.should.be.type('function');
            done();
        });

        it('should format a header', function(done) {
            formatter.header(header).should.be.exactly(header + ':');
            done();
        });
    });

    describe('formatter.line', function() {
        var givenString, expectedString;

        it('is a function', function(done) {
            formatter.line.should.be.type('function');
            done();
        });

        it('formats a string properly given a line number', function(done) {
            givenString = 'TODO: update client-side Session model to overwrite toJSON',
            expectedString = '  * [Line 8] [TODO] update client-side Session model to overwrite toJSON';

            formatter.line(givenString, 8).should.be.exactly(expectedString);

            done();
        });

        it('ignores code prefacing code', function(done) {
            givenString = '[1, 2, 3].forEach(function(number) { // TODO: declare new var & replace hard-coded',
            expectedString = '  * [Line 11] [TODO] declare new var & replace hard-coded';

            formatter.line(givenString, 11).should.be.exactly(expectedString);

            done();
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var grunt = require('grunt');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.git_reset = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  default_options: function(test) {
    test.expect(1);

    var actual = grunt.file.read('tmp/default_options');
    var expected = grunt.file.read('test/expected/default_options');
    test.equal(actual, expected, 'should describe what the default behavior is.');

    test.done();
  },
  custom_options: function(test) {
    test.expect(1);

    var actual = grunt.file.read('tmp/custom_options');
    var expected = grunt.file.read('test/expected/custom_options');
    test.equal(actual, expected, 'should describe what the custom option(s) behavior is.');

    test.done();
  }
};
<commit_msg>Adds tests<commit_after>'use strict';

var grunt = require('grunt'),
    path  = require('path'),
    exec  = require('child_process').exec,
    execOptions = {
      cwd: path.join(__dirname, '..')
    };

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.git_reset = {
  setUp: function(done) {
    done();
  },
  bad_options: function(test) {
    test.expect(1);

    test.throws(
      exec('grunt git_reset:bad_options', execOptions),
      Error,
      'Running git_reset without path setting throws an error'
    );

    test.done();
  },
  good_options: function(test) {
    var file_exists,
        file_contents;

    test.expect(4);

    // delete file
    grunt.file.delete('test/fixtures/delete_this_file');
    file_exists = grunt.file.exists('test/fixtures/delete_this_file');
    test.ok(!file_exists, 'file is deleted to start out');

    // edit file
    grunt.file.write('test/fixtures/edit_this_file', 'changed');
    file_contents = grunt.file.read('test/fixtures/edit_this_file');
    test.equal(file_contents, 'changed', 'file is changed');

    exec('grunt git_reset:good_options', execOptions, function(error, stdout) {
      file_exists = grunt.file.exists('test/fixtures/delete_this_file');
      test.ok(file_exists, 'deleted file restored');

      file_contents = grunt.file.read('test/fixtures/edit_this_file');
      test.equal(file_contents, 'unchanged', 'file is unchanged');

      test.done();
    });
  }
};
<|endoftext|>