<commit_before>var twilio = require('twilio');
var request = require("request");
var constants = require('./../../constants');
var client = require('twilio')(constants.twilio_sid, constants.auth_token);
var restler = require('restler');
var colors = require('colors');

exports.help = function(req, res, next){
  console.log('[TEXT] SMS detected:'.green, req.body.Body.green);
  console.log('[TEXT] From:'.green,req.body.From.green);
  console.log('[TEXT] Body:'.green,req.body.Body.green);

  console.log('[TEXT] \'cmds\''.green);

  var tokens = req.body.Body.split(" ");

  if (tokens[0].toLowerCase() == 'cmds'){
    var body = 'Commands:\n'
        + 'cmds || Returns a list of available commands.\n'
        + 'reddit <subreddit> <amount> || Returns <amount> titles from <subreddit> subreddit. (Use \'front\' for homepage results)\n'
        + 'google <query> <amount> || Returns <amount> results from google search of <query>.\n'
        + 'TODO || Add more commands.';

    client.messages.create({
      to: req.body.From,
      from: constants.from_phone,
      body: body,
    });
  } else {
    next();
  }
}

exports.reddit = function(req, res, next){
  console.log('[TEXT] \'reddit\''.green);

  var tokens = req.body.Body.split(" ");
  if (tokens[0].toLowerCase() == 'reddit'){
    var subreddit = tokens[1];
    var amount = tokens[2];

    if (tokens[1] == 'front'){
      restler.get('http://reddit.com/.json').on('complete', function(reddit) {
        console.log('Reddit:', reddit);
        for(var i=0; i<amount; i++) {
          client.messages.create({
            to: req.body.From,
            from: constants.from_phone,
            body: reddit.data.children[i].data.title,
          });
        }
      });
    }else{
      restler.get('http://reddit.com/r/' + subreddit + '/.json').on('complete', function(reddit) {
        console.log('Reddit:', reddit);
        for(var i=0; i<amount; i++) {
          client.messages.create({
            to: request.body.From,
            from: constants.from_phone,
            body: reddit.data.children[i].data.title,
          });
        }
      });
    }
  } else {
    next();
  }
}

exports.gmap = function(req, res, next){
  console.log('[TEXT] \'gmap\''.green);
  var re = /gmap|gm (d|w|b|t) from (.+) to (.+)/;
  var body = req.body.Body;
  var pass = re.exec(body);
  if (pass){
    var type = pass[1];
    switch (type){
      case 'd':
        type = 'driving';
        break;
      case 'w':
        type = 'walking';
        break;
      case 'b':
        type = 'bicycling';
        break;
      case 't':
        type = 'transit';
        break;
    }
    var from = pass[2];
    var to = pass[3];
    console.log(from, to, type);
    request.post({
      uri: 'http://maps.googleapis.com/maps/api/directions/json',
      form: {
        origin: from,
        destination: to,
        mode: type,
      }
    }, function(error, response, body){
      if (error){
        console.log("There was an error:", error);
      } else {
        console.log("Request posted successfully!", body);
      }
    });
  } else{
    next();
  }
}

exports.google = function(req, res, next){
  console.log('[TEXT] \'google\''.green);

  var tokens = req.body.Body.split(" ");
  if (tokens[0].toLowerCase() == 'google'){
    var query = tokens.slice(1, -1).join(' ');
    var amount = tokens[tokens.length - 1];
    console.log('[DEBUG] Google', amount, 'results for', query);
    var body = 'Google ' + amount + ' results for ' + query;

    client.messages.create({
      to: req.body.From,
      from: constants.from_phone,
      body: body,
    });
  } else {
    next();
  }
}

exports.invalid = function(req, res){
  console.log('[TEXT] \'invalid\'');
  var body = 'Invalid input: ' + req.body.Body + '.\nPlease type \'cmds\' to get list of available commands.'
  client.messages.create({
    to: req.body.From,
    from: constants.from_phone,
    body: body,
  });
}
<commit_msg>wrong request type<commit_after>var twilio = require('twilio');
var request = require("request");
var constants = require('./../../constants');
var client = require('twilio')(constants.twilio_sid, constants.auth_token);
var restler = require('restler');
var colors = require('colors');

exports.help = function(req, res, next){
  console.log('[TEXT] SMS detected:'.green, req.body.Body.green);
  console.log('[TEXT] From:'.green,req.body.From.green);
  console.log('[TEXT] Body:'.green,req.body.Body.green);

  console.log('[TEXT] \'cmds\''.green);

  var tokens = req.body.Body.split(" ");

  if (tokens[0].toLowerCase() == 'cmds'){
    var body = 'Commands:\n'
        + 'cmds || Returns a list of available commands.\n'
        + 'reddit <subreddit> <amount> || Returns <amount> titles from <subreddit> subreddit. (Use \'front\' for homepage results)\n'
        + 'google <query> <amount> || Returns <amount> results from google search of <query>.\n'
        + 'TODO || Add more commands.';

    client.messages.create({
      to: req.body.From,
      from: constants.from_phone,
      body: body,
    });
  } else {
    next();
  }
}

exports.reddit = function(req, res, next){
  console.log('[TEXT] \'reddit\''.green);

  var tokens = req.body.Body.split(" ");
  if (tokens[0].toLowerCase() == 'reddit'){
    var subreddit = tokens[1];
    var amount = tokens[2];

    if (tokens[1] == 'front'){
      restler.get('http://reddit.com/.json').on('complete', function(reddit) {
        console.log('Reddit:', reddit);
        for(var i=0; i<amount; i++) {
          client.messages.create({
            to: req.body.From,
            from: constants.from_phone,
            body: reddit.data.children[i].data.title,
          });
        }
      });
    }else{
      restler.get('http://reddit.com/r/' + subreddit + '/.json').on('complete', function(reddit) {
        console.log('Reddit:', reddit);
        for(var i=0; i<amount; i++) {
          client.messages.create({
            to: request.body.From,
            from: constants.from_phone,
            body: reddit.data.children[i].data.title,
          });
        }
      });
    }
  } else {
    next();
  }
}

exports.gmap = function(req, res, next){
  console.log('[TEXT] \'gmap\''.green);
  var re = /gmap|gm (d|w|b|t) from (.+) to (.+)/;
  var body = req.body.Body;
  var pass = re.exec(body);
  if (pass){
    var type = pass[1];
    switch (type){
      case 'd':
        type = 'driving';
        break;
      case 'w':
        type = 'walking';
        break;
      case 'b':
        type = 'bicycling';
        break;
      case 't':
        type = 'transit';
        break;
    }
    var from = pass[2];
    var to = pass[3];
    console.log(from, to, type);
    request.get({
      uri: 'http://maps.googleapis.com/maps/api/directions/json',
      form: {
        origin: from,
        destination: to,
        mode: type,
      }
    }, function(error, response, body){
      if (error){
        console.log("There was an error:", error);
      } else {
        console.log("Request posted successfully!", body);
      }
    });
  } else{
    next();
  }
}

exports.google = function(req, res, next){
  console.log('[TEXT] \'google\''.green);

  var tokens = req.body.Body.split(" ");
  if (tokens[0].toLowerCase() == 'google'){
    var query = tokens.slice(1, -1).join(' ');
    var amount = tokens[tokens.length - 1];
    console.log('[DEBUG] Google', amount, 'results for', query);
    var body = 'Google ' + amount + ' results for ' + query;

    client.messages.create({
      to: req.body.From,
      from: constants.from_phone,
      body: body,
    });
  } else {
    next();
  }
}

exports.invalid = function(req, res){
  console.log('[TEXT] \'invalid\'');
  var body = 'Invalid input: ' + req.body.Body + '.\nPlease type \'cmds\' to get list of available commands.'
  client.messages.create({
    to: req.body.From,
    from: constants.from_phone,
    body: body,
  });
}
<|endoftext|>


<commit_before>import { defData } from './defaultData'

import * as v from '../../styles/variables'

class FrequenService {
  constructor () {
    this.storage = window.localStorage
    this.item = 'frequen'
    this.getData = this.getData.bind(this)
    this.setStorage = this.setStorage.bind(this)
  }

  getData () {
    let data

    // Check if there's storage access
    if (typeof Storage !== 'undefined') {
      // If we can access storage, check if there is data in storage.
      if (this.storage.getItem(this.item)) {
        // If there's data in storage, pull it
        data = JSON.parse(this.storage.getItem(this.item))
      } else {
        // If there's not data in storage, pull the default data
        data = defData
        // Store the default data in storage
        this.setStorage(data)
      }
    } else {
      // If we can't access storage, use the default data
      data = defData
    }

    return data
  }

  // Store the current data in storage
  setStorage (data) {
    if (typeof Storage !== 'undefined') {
      this.storage.setItem(this.item, JSON.stringify(data))
    }
  }

  // Analyze the data
  analyze (data) {
    // Break the input into arrays and remove duplicates
    const splitBySlash = arr => {
      let newArr = Array.from(new Set(arr.split('/')))
      // Remove any blanks
      if (newArr.indexOf('') > -1) {
        newArr.splice(newArr.indexOf(''), 1)
      }
      return newArr
    }
    // Break each element in an array into a sub-array
    const makeSubArrays = arr => {
      let newArr = []
      arr.forEach(el => {
        newArr.push(el.split(','))
      })
      return newArr
    }
    const consonants = makeSubArrays(splitBySlash(data.consonants))
    const vowels = makeSubArrays(splitBySlash(data.vowels))

    // Flatten arrays and make sure there are no duplicates
    const flattenArrays = arr => Array.from(new Set([].concat(...arr)))
    // Distinguish upper/lower case if that option is selected
    const distinguishCase = arr => {
      let newArr = []
      console.log(data)
      if (!data.distinguishCase) {
        arr.forEach(el => newArr.push(el.toLowerCase()))
      } else {
        newArr = arr
      }
      console.log(newArr)
      return Array.from(new Set(newArr))
    }
    // And sort the flattened arrays by length so the longest segments are first
    const sortArrays = arr => {
      console.log(arr)
      return arr.sort((a, b) => b.length - a.length)
    }
    const consonantsFlat = sortArrays(
      distinguishCase(flattenArrays(consonants))
    )
    const vowelsFlat = sortArrays(distinguishCase(flattenArrays(vowels)))

    let rawResults = {}

    // Add each element in the flattened arrays to the results object and indicate which type they are
    const initResults = (arr, type) => {
      arr.forEach(el => {
        rawResults[el] = {}
        rawResults[el].count = 0
        rawResults[el].type = type
      })
    }
    initResults(consonantsFlat, 'consonant')
    initResults(vowelsFlat, 'vowel') // Currently, if an element appears in both consonants and vowels, its vowel instance will take precedence

    // Label which segments are allophones
    const labelAllophones = arr => {
      arr.forEach((elArr, i) => {
        if (elArr.length > 1) {
          elArr.forEach((el, j) => {
            if (j > 0) {
              rawResults[arr[i][j]].allophoneOf = arr[i][0]
            }
          })
        }
      })
    }
    labelAllophones(consonants)
    labelAllophones(vowels)

    // Build a single array and sort by segment length
    const fullArr = sortArrays(consonantsFlat.concat(vowelsFlat))

    // If not distinguishing case, convert the corpus to lowercase
    let corpus = data.distinguishCase ? data.corpus : data.corpus.toLowerCase()

    // For every instance of the segment in the text, increment the count and slice the instance out of the text
    const sliceAndCount = seg => {
      if (corpus.indexOf(seg) > -1) {
        rawResults[seg].count += 1
        corpus =
          corpus.slice(0, corpus.indexOf(seg)) +
          corpus.slice(corpus.indexOf(seg) + seg.length)
      }
    }

    // Loop through all segments counting and slicing all instances of each.
    fullArr.forEach(el => {
      while (corpus.indexOf(el) > -1) {
        sliceAndCount(el)
      }
    })

    // Find allophones and combine their counts
    for (let seg in rawResults) {
      if (rawResults.hasOwnProperty(seg)) {
        if (rawResults[seg].hasOwnProperty('allophoneOf')) {
          rawResults[rawResults[seg].allophoneOf].count += rawResults[seg].count
          delete rawResults[seg]
        }
      }
    }

    // Assemble the data
    const assembleData = filter => {
      // Add the results to a results array
      let resArr = []

      for (let seg in rawResults) {
        if (rawResults[seg].type === filter || filter === undefined) {
          resArr.push({
            segment: seg,
            count: rawResults[seg].count,
            type: rawResults[seg].type
          })
        }
      }

      // Sort by smallest count
      resArr.sort((a, b) => {
        return a.count - b.count
      })

      // Count the total number of counted segments
      let count = 0

      resArr.forEach(elObj => {
        count += elObj.count
      })

      return resArr.map((d, i) => ({
        x: (d.count / count) * 100,
        y: d.segment,
        count: d.count,
        type: d.type,
        i: i,
        color:
          d.type === 'consonant' ? v.blu.string() : v.blu.darken(0.2).string()
      }))
    }

    const results = {
      all: assembleData(),
      consonants: assembleData('consonant'),
      vowels: assembleData('vowel')
    }

    return results
  }
}

const frequenService = new FrequenService()

export default frequenService
<commit_msg>Remove console.log() calls<commit_after>import { defData } from './defaultData'

import * as v from '../../styles/variables'

class FrequenService {
  constructor () {
    this.storage = window.localStorage
    this.item = 'frequen'
    this.getData = this.getData.bind(this)
    this.setStorage = this.setStorage.bind(this)
  }

  getData () {
    let data

    // Check if there's storage access
    if (typeof Storage !== 'undefined') {
      // If we can access storage, check if there is data in storage.
      if (this.storage.getItem(this.item)) {
        // If there's data in storage, pull it
        data = JSON.parse(this.storage.getItem(this.item))
      } else {
        // If there's not data in storage, pull the default data
        data = defData
        // Store the default data in storage
        this.setStorage(data)
      }
    } else {
      // If we can't access storage, use the default data
      data = defData
    }

    return data
  }

  // Store the current data in storage
  setStorage (data) {
    if (typeof Storage !== 'undefined') {
      this.storage.setItem(this.item, JSON.stringify(data))
    }
  }

  // Analyze the data
  analyze (data) {
    // Break the input into arrays and remove duplicates
    const splitBySlash = arr => {
      let newArr = Array.from(new Set(arr.split('/')))
      // Remove any blanks
      if (newArr.indexOf('') > -1) {
        newArr.splice(newArr.indexOf(''), 1)
      }
      return newArr
    }
    // Break each element in an array into a sub-array
    const makeSubArrays = arr => {
      let newArr = []
      arr.forEach(el => {
        newArr.push(el.split(','))
      })
      return newArr
    }
    const consonants = makeSubArrays(splitBySlash(data.consonants))
    const vowels = makeSubArrays(splitBySlash(data.vowels))

    // Flatten arrays and make sure there are no duplicates
    const flattenArrays = arr => Array.from(new Set([].concat(...arr)))
    // Distinguish upper/lower case if that option is selected
    const distinguishCase = arr => {
      let newArr = []
      if (!data.distinguishCase) {
        arr.forEach(el => newArr.push(el.toLowerCase()))
      } else {
        newArr = arr
      }
      return Array.from(new Set(newArr))
    }
    // And sort the flattened arrays by length so the longest segments are first
    const sortArrays = arr => {
      return arr.sort((a, b) => b.length - a.length)
    }
    const consonantsFlat = sortArrays(
      distinguishCase(flattenArrays(consonants))
    )
    const vowelsFlat = sortArrays(distinguishCase(flattenArrays(vowels)))

    let rawResults = {}

    // Add each element in the flattened arrays to the results object and indicate which type they are
    const initResults = (arr, type) => {
      arr.forEach(el => {
        rawResults[el] = {}
        rawResults[el].count = 0
        rawResults[el].type = type
      })
    }
    initResults(consonantsFlat, 'consonant')
    initResults(vowelsFlat, 'vowel') // Currently, if an element appears in both consonants and vowels, its vowel instance will take precedence

    // Label which segments are allophones
    const labelAllophones = arr => {
      arr.forEach((elArr, i) => {
        if (elArr.length > 1) {
          elArr.forEach((el, j) => {
            if (j > 0) {
              rawResults[arr[i][j]].allophoneOf = arr[i][0]
            }
          })
        }
      })
    }
    labelAllophones(consonants)
    labelAllophones(vowels)

    // Build a single array and sort by segment length
    const fullArr = sortArrays(consonantsFlat.concat(vowelsFlat))

    // If not distinguishing case, convert the corpus to lowercase
    let corpus = data.distinguishCase ? data.corpus : data.corpus.toLowerCase()

    // For every instance of the segment in the text, increment the count and slice the instance out of the text
    const sliceAndCount = seg => {
      if (corpus.indexOf(seg) > -1) {
        rawResults[seg].count += 1
        corpus =
          corpus.slice(0, corpus.indexOf(seg)) +
          corpus.slice(corpus.indexOf(seg) + seg.length)
      }
    }

    // Loop through all segments counting and slicing all instances of each.
    fullArr.forEach(el => {
      while (corpus.indexOf(el) > -1) {
        sliceAndCount(el)
      }
    })

    // Find allophones and combine their counts
    for (let seg in rawResults) {
      if (rawResults.hasOwnProperty(seg)) {
        if (rawResults[seg].hasOwnProperty('allophoneOf')) {
          rawResults[rawResults[seg].allophoneOf].count += rawResults[seg].count
          delete rawResults[seg]
        }
      }
    }

    // Assemble the data
    const assembleData = filter => {
      // Add the results to a results array
      let resArr = []

      for (let seg in rawResults) {
        if (rawResults[seg].type === filter || filter === undefined) {
          resArr.push({
            segment: seg,
            count: rawResults[seg].count,
            type: rawResults[seg].type
          })
        }
      }

      // Sort by smallest count
      resArr.sort((a, b) => {
        return a.count - b.count
      })

      // Count the total number of counted segments
      let count = 0

      resArr.forEach(elObj => {
        count += elObj.count
      })

      return resArr.map((d, i) => ({
        x: (d.count / count) * 100,
        y: d.segment,
        count: d.count,
        type: d.type,
        i: i,
        color:
          d.type === 'consonant' ? v.blu.string() : v.blu.darken(0.2).string()
      }))
    }

    const results = {
      all: assembleData(),
      consonants: assembleData('consonant'),
      vowels: assembleData('vowel')
    }

    return results
  }
}

const frequenService = new FrequenService()

export default frequenService
<|endoftext|>


<commit_before>var should   = require('should');
var helper   = require('../support/spec_helper');
var ORM      = require('../../');

describe("Model.find() chaining", function() {
	var db = null;
	var Person = null;

	var setup = function () {
		return function (done) {
			Person = db.define("person", {
				name    : String,
				surname : String,
				age     : Number
			}, {
				cache : false
			});

			ORM.singleton.clear(); // clear cache

			return helper.dropSync(Person, function () {
				Person.create([{
					name    : "John",
					surname : "Doe",
					age     : 18
				}, {
					name    : "Jane",
					surname : "Doe",
					age     : 20
				}, {
					name    : "Jane",
					surname : "Dean",
					age     : 18
				}], done);
			});
		};
	};

	before(function (done) {
		helper.connect(function (connection) {
			db = connection;

			return done();
		});
	});

	after(function () {
		return db.close();
	});

	describe(".limit(N)", function () {
		before(setup());

		it("should limit results to N items", function (done) {
			Person.find().limit(2).run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 2);

				return done();
			});
		});
	});

	describe(".skip(N)", function () {
		before(setup());

		it("should skip the first N results", function (done) {
			Person.find().skip(2).order("age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 1);
				Number(instances[0].age).should.equal(20);

				return done();
			});
		});
	});

	describe(".offset(N)", function () {
		before(setup());

		it("should skip the first N results", function (done) {
			Person.find().offset(2).order("age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 1);
				Number(instances[0].age).should.equal(20);

				return done();
			});
		});
	});

	describe(".order('property')", function () {
		before(setup());

		it("should order by that property ascending", function (done) {
			Person.find().order("age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				Number(instances[0].age).should.equal(18);
				Number(instances[2].age).should.equal(20);

				return done();
			});
		});
	});

	describe(".order('-property')", function () {
		before(setup());

		it("should order by that property descending", function (done) {
			Person.find().order("-age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				Number(instances[0].age).should.equal(20);
				Number(instances[2].age).should.equal(18);

				return done();
			});
		});
	});

	describe(".order('property', 'Z')", function () {
		before(setup());

		it("should order by that property descending", function (done) {
			Person.find().order("age", "Z").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				Number(instances[0].age).should.equal(20);
				Number(instances[2].age).should.equal(18);

				return done();
			});
		});
	});

	describe(".only('property', ...)", function () {
		before(setup());

		it("should return only those properties, others null", function (done) {
			Person.find().only("age", "surname").order("-age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				instances[0].should.have.property("age");
				instances[0].should.have.property("surname", "Doe");
				instances[0].should.have.property("name", null);

				return done();
			});
		});
	});

	describe(".only('property1', ...)", function () {
		before(setup());

		it("should return only those properties, others null", function (done) {
			Person.find().only([ "age", "surname" ]).order("-age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				instances[0].should.have.property("age");
				instances[0].should.have.property("surname", "Doe");
				instances[0].should.have.property("name", null);

				return done();
			});
		});
	});

	describe(".count()", function () {
		before(setup());

		it("should return only the total number of results", function (done) {
			Person.find().count(function (err, count) {
				should.equal(err, null);
				count.should.equal(3);

				return done();
			});
		});
	});

	describe(".first()", function () {
		before(setup());

		it("should return only the first element", function (done) {
			Person.find().order("-age").first(function (err, JaneDoe) {
				should.equal(err, null);

				JaneDoe.name.should.equal("Jane");
				JaneDoe.surname.should.equal("Doe");
				Number(JaneDoe.age).should.equal(20);

				return done();
			});
		});

		it("should return null if not found", function (done) {
			Person.find({ name: "Jack" }).first(function (err, Jack) {
				should.equal(err, null);
				should.equal(Jack, null);

				return done();
			});
		});
	});

	describe(".last()", function () {
		before(setup());

		it("should return only the last element", function (done) {
			Person.find().order("age").last(function (err, JaneDoe) {
				should.equal(err, null);

				JaneDoe.name.should.equal("Jane");
				JaneDoe.surname.should.equal("Doe");
				Number(JaneDoe.age).should.equal(20);

				return done();
			});
		});

		it("should return null if not found", function (done) {
			Person.find({ name: "Jack" }).last(function (err, Jack) {
				should.equal(err, null);
				should.equal(Jack, null);

				return done();
			});
		});
	});

	describe(".find()", function () {
		before(setup());

		it("should not change find if no arguments", function (done) {
			Person.find().find().count(function (err, count) {
				should.equal(err, null);
				count.should.equal(3);

				return done();
			});
		});

		it("should restrict conditions if passed", function (done) {
			Person.find().find({ age: 18 }).count(function (err, count) {
				should.equal(err, null);
				count.should.equal(2);

				return done();
			});
		});

		it("should restrict conditions if passed and also be chainable", function (done) {
			Person.find().find({ age: 18 }).find({ name: "Jane" }).count(function (err, count) {
				should.equal(err, null);
				count.should.equal(1);

				return done();
			});
		});

		it("should return results if passed a callback as second argument", function (done) {
			Person.find().find({ age: 18 }, function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 2);

				return done();
			});
		});
	});

	describe(".each()", function () {
		before(setup());

		it("should return a ChainInstance", function (done) {
			var chain = Person.find().each();

			chain.filter.should.be.a("function");
			chain.sort.should.be.a("function");
			chain.count.should.be.a("function");

			return done();
		});
	});

	describe(".remove()", function () {
		before(setup());

		it("should have no problems if no results found", function (done) {
			Person.find({ age: 22 }).remove(function (err) {
				should.equal(err, null);

				Person.find().count(function (err, count) {
					should.equal(err, null);

					count.should.equal(3);

					return done();
				});
			});
		});

		it("should remove results and give feedback", function (done) {
			Person.find({ age: 20 }).remove(function (err) {
				should.equal(err, null);

				Person.find().count(function (err, count) {
					should.equal(err, null);

					count.should.equal(2);

					return done();
				});
			});
		});
	});

	describe(".each()", function () {
		before(setup());

		it("should return a ChainFind", function (done) {
			var chain = Person.find({ age: 22 }).each();

			chain.should.be.a("object");
			chain.filter.should.be.a("function");
			chain.sort.should.be.a("function");
			chain.count.should.be.a("function");
			chain.get.should.be.a("function");
			chain.save.should.be.a("function");

			return done();
		});

		describe(".count()", function () {
			it("should return the total filtered items", function (done) {
				Person.find().each().filter(function (person) {
					return (person.age > 18);
				}).count(function (count) {
					count.should.equal(1);

					return done();
				});
			});
		});

		describe(".sort()", function () {
			it("should return the items sorted using the sorted function", function (done) {
				Person.find().each().sort(function (first, second) {
					return (first.age < second.age);
				}).get(function (people) {
					should(Array.isArray(people));

					people.length.should.equal(3);
					people[0].age.should.equal(20);
					people[2].age.should.equal(18);

					return done();
				});
			});
		});
	});
});
<commit_msg>Updates ChainFind tests to avoid casting numbers<commit_after>var should   = require('should');
var helper   = require('../support/spec_helper');
var ORM      = require('../../');

describe("Model.find() chaining", function() {
	var db = null;
	var Person = null;

	var setup = function () {
		return function (done) {
			Person = db.define("person", {
				name    : String,
				surname : String,
				age     : Number
			}, {
				cache : false
			});

			ORM.singleton.clear(); // clear cache

			return helper.dropSync(Person, function () {
				Person.create([{
					name    : "John",
					surname : "Doe",
					age     : 18
				}, {
					name    : "Jane",
					surname : "Doe",
					age     : 20
				}, {
					name    : "Jane",
					surname : "Dean",
					age     : 18
				}], done);
			});
		};
	};

	before(function (done) {
		helper.connect(function (connection) {
			db = connection;

			return done();
		});
	});

	after(function () {
		return db.close();
	});

	describe(".limit(N)", function () {
		before(setup());

		it("should limit results to N items", function (done) {
			Person.find().limit(2).run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 2);

				return done();
			});
		});
	});

	describe(".skip(N)", function () {
		before(setup());

		it("should skip the first N results", function (done) {
			Person.find().skip(2).order("age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 1);
				instances[0].age.should.equal(20);

				return done();
			});
		});
	});

	describe(".offset(N)", function () {
		before(setup());

		it("should skip the first N results", function (done) {
			Person.find().offset(2).order("age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 1);
				instances[0].age.should.equal(20);

				return done();
			});
		});
	});

	describe(".order('property')", function () {
		before(setup());

		it("should order by that property ascending", function (done) {
			Person.find().order("age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				instances[0].age.should.equal(18);
				instances[2].age.should.equal(20);

				return done();
			});
		});
	});

	describe(".order('-property')", function () {
		before(setup());

		it("should order by that property descending", function (done) {
			Person.find().order("-age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				instances[0].age.should.equal(20);
				instances[2].age.should.equal(18);

				return done();
			});
		});
	});

	describe(".order('property', 'Z')", function () {
		before(setup());

		it("should order by that property descending", function (done) {
			Person.find().order("age", "Z").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				instances[0].age.should.equal(20);
				instances[2].age.should.equal(18);

				return done();
			});
		});
	});

	describe(".only('property', ...)", function () {
		before(setup());

		it("should return only those properties, others null", function (done) {
			Person.find().only("age", "surname").order("-age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				instances[0].should.have.property("age");
				instances[0].should.have.property("surname", "Doe");
				instances[0].should.have.property("name", null);

				return done();
			});
		});
	});

	describe(".only('property1', ...)", function () {
		before(setup());

		it("should return only those properties, others null", function (done) {
			Person.find().only([ "age", "surname" ]).order("-age").run(function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 3);
				instances[0].should.have.property("age");
				instances[0].should.have.property("surname", "Doe");
				instances[0].should.have.property("name", null);

				return done();
			});
		});
	});

	describe(".count()", function () {
		before(setup());

		it("should return only the total number of results", function (done) {
			Person.find().count(function (err, count) {
				should.equal(err, null);
				count.should.equal(3);

				return done();
			});
		});
	});

	describe(".first()", function () {
		before(setup());

		it("should return only the first element", function (done) {
			Person.find().order("-age").first(function (err, JaneDoe) {
				should.equal(err, null);

				JaneDoe.name.should.equal("Jane");
				JaneDoe.surname.should.equal("Doe");
				JaneDoe.age.should.equal(20);

				return done();
			});
		});

		it("should return null if not found", function (done) {
			Person.find({ name: "Jack" }).first(function (err, Jack) {
				should.equal(err, null);
				should.equal(Jack, null);

				return done();
			});
		});
	});

	describe(".last()", function () {
		before(setup());

		it("should return only the last element", function (done) {
			Person.find().order("age").last(function (err, JaneDoe) {
				should.equal(err, null);

				JaneDoe.name.should.equal("Jane");
				JaneDoe.surname.should.equal("Doe");
				JaneDoe.age.should.equal(20);

				return done();
			});
		});

		it("should return null if not found", function (done) {
			Person.find({ name: "Jack" }).last(function (err, Jack) {
				should.equal(err, null);
				should.equal(Jack, null);

				return done();
			});
		});
	});

	describe(".find()", function () {
		before(setup());

		it("should not change find if no arguments", function (done) {
			Person.find().find().count(function (err, count) {
				should.equal(err, null);
				count.should.equal(3);

				return done();
			});
		});

		it("should restrict conditions if passed", function (done) {
			Person.find().find({ age: 18 }).count(function (err, count) {
				should.equal(err, null);
				count.should.equal(2);

				return done();
			});
		});

		it("should restrict conditions if passed and also be chainable", function (done) {
			Person.find().find({ age: 18 }).find({ name: "Jane" }).count(function (err, count) {
				should.equal(err, null);
				count.should.equal(1);

				return done();
			});
		});

		it("should return results if passed a callback as second argument", function (done) {
			Person.find().find({ age: 18 }, function (err, instances) {
				should.equal(err, null);
				instances.should.have.property("length", 2);

				return done();
			});
		});
	});

	describe(".each()", function () {
		before(setup());

		it("should return a ChainInstance", function (done) {
			var chain = Person.find().each();

			chain.filter.should.be.a("function");
			chain.sort.should.be.a("function");
			chain.count.should.be.a("function");

			return done();
		});
	});

	describe(".remove()", function () {
		before(setup());

		it("should have no problems if no results found", function (done) {
			Person.find({ age: 22 }).remove(function (err) {
				should.equal(err, null);

				Person.find().count(function (err, count) {
					should.equal(err, null);

					count.should.equal(3);

					return done();
				});
			});
		});

		it("should remove results and give feedback", function (done) {
			Person.find({ age: 20 }).remove(function (err) {
				should.equal(err, null);

				Person.find().count(function (err, count) {
					should.equal(err, null);

					count.should.equal(2);

					return done();
				});
			});
		});
	});

	describe(".each()", function () {
		before(setup());

		it("should return a ChainFind", function (done) {
			var chain = Person.find({ age: 22 }).each();

			chain.should.be.a("object");
			chain.filter.should.be.a("function");
			chain.sort.should.be.a("function");
			chain.count.should.be.a("function");
			chain.get.should.be.a("function");
			chain.save.should.be.a("function");

			return done();
		});

		describe(".count()", function () {
			it("should return the total filtered items", function (done) {
				Person.find().each().filter(function (person) {
					return (person.age > 18);
				}).count(function (count) {
					count.should.equal(1);

					return done();
				});
			});
		});

		describe(".sort()", function () {
			it("should return the items sorted using the sorted function", function (done) {
				Person.find().each().sort(function (first, second) {
					return (first.age < second.age);
				}).get(function (people) {
					should(Array.isArray(people));

					people.length.should.equal(3);
					people[0].age.should.equal(20);
					people[2].age.should.equal(18);

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


<commit_before>'use strict';

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

var fs = require('graceful-fs');
var del = require('del');
var File = require('vinyl');
var expect = require('expect');

var vfs = require('../');

function wipeOut() {
  this.timeout(20000);

  expect.restoreSpies();

  // Async del to get sort-of-fix for https://github.com/isaacs/rimraf/issues/72
  return del(path.join(__dirname, './out-fixtures/'));
}

var isWindows = (os.platform() === 'win32');

describe('.dest() with custom times', function() {
  beforeEach(wipeOut);
  afterEach(wipeOut);

  it('should not call futimes when no mtime is provided on the vinyl stat', function(done) {
    if (isWindows) {
      console.log('Changing the time of a directory errors in Windows.');
      console.log('Windows is treated as though it does not have permission to make this operation.');
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var earlier = Date.now() - 1000;

    var futimesSpy = expect.spyOn(fs, 'futimes').andCallThrough();

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {},
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(futimesSpy.calls.length).toEqual(0);
      expect(stats.atime.getTime()).toBeGreaterThan(earlier);
      expect(stats.mtime.getTime()).toBeGreaterThan(earlier);
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });

  it('should call futimes when an mtime is provided on the vinyl stat', function(done) {
    if (isWindows) {
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var expectedMtime = fs.lstatSync(inputPath).mtime;

    var futimesSpy = expect.spyOn(fs, 'futimes').andCallThrough();

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {
        mtime: expectedMtime,
      },
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(futimesSpy.calls.length).toEqual(1);
      expect(stats.mtime.getTime()).toEqual(expectedMtime.getTime());
      expect(expectedFile.stat.mtime).toEqual(expectedMtime);
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });

  it('should not call futimes when provided mtime on the vinyl stat is invalid', function(done) {
    if (isWindows) {
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var earlier = Date.now() - 1000;

    var futimesSpy = expect.spyOn(fs, 'futimes').andCallThrough();

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {
        mtime: new Date(undefined),
      },
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(futimesSpy.calls.length).toEqual(0);
      expect(stats.mtime.getTime()).toBeGreaterThan(earlier);
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });

  it('should call futimes when provided mtime on the vinyl stat is valid but provided atime is invalid', function(done) {
    if (isWindows) {
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var expectedMtime = fs.lstatSync(inputPath).mtime;
    var invalidAtime = new Date(undefined);

    var futimesSpy = expect.spyOn(fs, 'futimes').andCallThrough();

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {
        atime: invalidAtime,
        mtime: expectedMtime,
      },
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(futimesSpy.calls.length).toEqual(1);
      expect(stats.mtime.getTime()).toEqual(expectedMtime.getTime());
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });

  it('should write file atime and mtime using the vinyl stat', function(done) {
    if (isWindows) {
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var expectedAtime = fs.lstatSync(inputPath).atime;
    var expectedMtime = fs.lstatSync(inputPath).mtime;

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {
        atime: expectedAtime,
        mtime: expectedMtime,
      },
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(stats.atime.getTime()).toEqual(expectedAtime.getTime());
      expect(stats.mtime.getTime()).toEqual(expectedMtime.getTime());
      expect(expectedFile.stat.mtime).toEqual(expectedMtime);
      expect(expectedFile.stat.atime).toEqual(expectedAtime);
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });
});
<commit_msg>Fix: Increase offset in futimes test timestamps (#176)<commit_after>'use strict';

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

var fs = require('graceful-fs');
var del = require('del');
var File = require('vinyl');
var expect = require('expect');

var vfs = require('../');

function wipeOut() {
  this.timeout(20000);

  expect.restoreSpies();

  // Async del to get sort-of-fix for https://github.com/isaacs/rimraf/issues/72
  return del(path.join(__dirname, './out-fixtures/'));
}

var isWindows = (os.platform() === 'win32');

describe('.dest() with custom times', function() {
  beforeEach(wipeOut);
  afterEach(wipeOut);

  it('should not call futimes when no mtime is provided on the vinyl stat', function(done) {
    if (isWindows) {
      console.log('Changing the time of a directory errors in Windows.');
      console.log('Windows is treated as though it does not have permission to make this operation.');
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var earlier = Date.now() - 1001;

    var futimesSpy = expect.spyOn(fs, 'futimes').andCallThrough();

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {},
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(futimesSpy.calls.length).toEqual(0);
      expect(stats.atime.getTime()).toBeGreaterThan(earlier);
      expect(stats.mtime.getTime()).toBeGreaterThan(earlier);
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });

  it('should call futimes when an mtime is provided on the vinyl stat', function(done) {
    if (isWindows) {
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var expectedMtime = fs.lstatSync(inputPath).mtime;

    var futimesSpy = expect.spyOn(fs, 'futimes').andCallThrough();

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {
        mtime: expectedMtime,
      },
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(futimesSpy.calls.length).toEqual(1);
      expect(stats.mtime.getTime()).toEqual(expectedMtime.getTime());
      expect(expectedFile.stat.mtime).toEqual(expectedMtime);
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });

  it('should not call futimes when provided mtime on the vinyl stat is invalid', function(done) {
    if (isWindows) {
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var earlier = Date.now() - 1001;

    var futimesSpy = expect.spyOn(fs, 'futimes').andCallThrough();

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {
        mtime: new Date(undefined),
      },
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(futimesSpy.calls.length).toEqual(0);
      expect(stats.mtime.getTime()).toBeGreaterThan(earlier);
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });

  it('should call futimes when provided mtime on the vinyl stat is valid but provided atime is invalid', function(done) {
    if (isWindows) {
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var expectedMtime = fs.lstatSync(inputPath).mtime;
    var invalidAtime = new Date(undefined);

    var futimesSpy = expect.spyOn(fs, 'futimes').andCallThrough();

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {
        atime: invalidAtime,
        mtime: expectedMtime,
      },
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(futimesSpy.calls.length).toEqual(1);
      expect(stats.mtime.getTime()).toEqual(expectedMtime.getTime());
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });

  it('should write file atime and mtime using the vinyl stat', function(done) {
    if (isWindows) {
      this.skip();
      return;
    }

    var inputPath = path.join(__dirname, './fixtures/test.coffee');
    var inputBase = path.join(__dirname, './fixtures/');
    var expectedPath = path.join(__dirname, './out-fixtures/test.coffee');
    var expectedContents = fs.readFileSync(inputPath);
    var expectedAtime = fs.lstatSync(inputPath).atime;
    var expectedMtime = fs.lstatSync(inputPath).mtime;

    var expectedFile = new File({
      base: inputBase,
      cwd: __dirname,
      path: inputPath,
      contents: expectedContents,
      stat: {
        atime: expectedAtime,
        mtime: expectedMtime,
      },
    });

    var onEnd = function() {
      var stats = fs.lstatSync(expectedPath);

      expect(stats.atime.getTime()).toEqual(expectedAtime.getTime());
      expect(stats.mtime.getTime()).toEqual(expectedMtime.getTime());
      expect(expectedFile.stat.mtime).toEqual(expectedMtime);
      expect(expectedFile.stat.atime).toEqual(expectedAtime);
      done();
    };

    var stream = vfs.dest('./out-fixtures/', { cwd: __dirname });
    stream.on('end', onEnd);
    stream.write(expectedFile);
    stream.end();
  });
});
<|endoftext|>


<commit_before>"use strict";

module.exports = function (grunt) {
    configuration.selenium.forEach(function (browser) {
        grunt.registerTask(browser, [
            "connectIf",
            "exec:test" + browser.charAt(0).toUpperCase() + browser.substr(1) + "Verbose"
        ]);
    });
};
<commit_msg>Configuration structure update<commit_after>"use strict";

module.exports = function (grunt) {
    configuration.selenium.browsers.forEach(function (browser) {
        grunt.registerTask(browser, [
            "connectIf",
            "exec:test" + browser.charAt(0).toUpperCase() + browser.substr(1) + "Verbose"
        ]);
    });
};
<|endoftext|>


<commit_before>'use strict';

// Required args: id
// Optional args: properties
function audio_create(args){
    args['properties'] = args['properties'] || {};

    audio_audio[args['id']] = {};
    audio_audio[args['id']]['playing'] = false;

    for(var property in args['properties']){
        audio_audio[args['id']][property] = args['properties'][property];
    }

    audio_audio[args['id']]['connections'] = args['properties']['connections'] || [
      {
        'frequency': {
          'value': audio_audio[args['id']]['frequency'] || 100,
        },
        'label': 'Oscillator',
        'type': audio_audio[args['id']]['type'] || 'sine',
      },
      {
        'gain': {
          'value': args['properties']['volume'] || audio_volume,
        },
        'label': 'Gain',
      },
    ];

    audio_audio[args['id']]['connections'][0]['id'] = args['id'];
    audio_audio[args['id']]['connections'][0]['onended'] = function(){
        audio_onended({
          'this': this,
        });
    };
}

// Optional args: volume
function audio_init(args){
    args = args || {};
    args['volume'] = args['volume'] !== void 0
      ? args['volume']
      : audio_volume_default;

    audio_context = new window.AudioContext();
    audio_volume = args['volume'];
}

// Optional args: id, properties
function audio_node_create(args){
    args = args || {};
    args['id'] = args['id'] !== void 0
      ? args['id']
      : false;
    args['properties'] = args['properties'] || {};

    var source = audio_context['create' + args['properties']['label']](
      args['properties']['arg0'],
      args['properties']['arg1'],
      args['properties']['arg2']
    );

    for(var property in args['properties']){
        if(typeof args['properties'][property] === 'object'){
            for(var subproperty in args['properties'][property]){
                source[property][subproperty] = args['properties'][property][subproperty];
            }

        }else{
            source[property] = args['properties'][property];
        }
    }

    if(args['id'] === false){
        return source;
    }

    audio_sources[args['id']][args['properties']['label']] = source;
}

// Required args: this
function audio_onended(args){
    audio_audio[args['this'].id]['playing'] = false;

    if(audio_audio[args['this'].id]['repeat']){
        if(audio_audio[args['this'].id]['timeout'] <= 0){
            audio_start({
              'id': args['this'].id,
            });
f
        }else{
            window.setTimeout(
              'audio_start({id:"' + args['this'].id + '"});',
              audio_audio[args['this'].id]['duration'] * audio_audio[args['this'].id]['timeout']
            );
        }
    }

    delete audio_sources[args['this'].id];
}

// Required args: id
// Optional args: volume-multiplier
function audio_source_create(args){
    args['volume-multiplier'] = args['volume-multiplier'] !== void 0
      ? args['volume-multiplier']
      : 1;

    audio_sources[args['id']] = {
      'duration': audio_audio[args['id']]['duration'] || 0,
      'start': audio_audio[args['id']]['start'] || 0,
      'timeout': audio_audio[args['id']]['timeout'] || 1000,
    };

    // Create audio nodes.
    var connections_length = audio_audio[args['id']]['connections'].length;
    for(var i = 0; i < connections_length; i++){
        audio_node_create({
          'id': args['id'],
          'properties': audio_audio[args['id']]['connections'][i],
        });

        if(audio_audio[args['id']]['connections'][i]['label'] === 'Gain'){
            var volume = audio_audio[args['id']]['volume'] || audio_volume;
            audio_sources[args['id']]['Gain']['gain']['value'] =
              (audio_audio[args['id']]['volume'] || audio_volume)
                * args['volume-multiplier'];
        }
    }

    // Connect audio nodes.
    for(i = 0; i < connections_length - 1; i++){
        audio_sources[args['id']][audio_audio[args['id']]['connections'][i]['label']].connect(
          audio_sources[args['id']][audio_audio[args['id']]['connections'][i + 1]['label']]
        );
    }
    audio_sources[args['id']][audio_audio[args['id']]['connections'][connections_length - 1]['label']].connect(
      audio_context.destination
    );
}

// Required args: id
// Optional args: volume-multiplier
function audio_start(args){
    args['volume-multiplier'] = args['volume-multiplier'] !== void 0
      ? args['volume-multiplier']
      : audio_volume_multiplier;

    if(args['volume-multiplier'] === 0){
        return;
    }

    if(audio_audio[args['id']]['playing']){
        audio_stop({
          'id': args['id'],
        });
    }

    audio_source_create({
      'id': args['id'],
      'volume-multiplier': args['volume-multiplier'],
    });

    var startTime = audio_context.currentTime + audio_sources[args['id']]['start'];
    audio_audio[args['id']]['playing'] = true;
    audio_sources[args['id']][audio_audio[args['id']]['connections'][0]['label']].start(startTime);
    audio_stop({
      'id': args['id'],
      'when': startTime + audio_sources[args['id']]['duration'],
    });
}

// Required args: id
// Optional args: when
function audio_stop(args){
    args['when'] = args['when'] || void 0;

    audio_sources[args['id']][audio_audio[args['id']]['connections'][0]['label']].stop(args['when']);
}

function audio_stop_all(){
    for(var id in audio_sources){
        audio_stop({
          'id': id,
        });
    }
}

var audio_audio = {};
var audio_context = 0;
var audio_sources = {};
var audio_volume = 1;
var audio_volume_default = 1;
var audio_volume_multiplier = 1;
<commit_msg>added common core.js usage to common audio.js<commit_after>'use strict';

// Required args: id
// Optional args: properties
function audio_create(args){
    args = core_args({
      'args': args,
      'defaults': {
        'properties': {},
      },
    });

    audio_audio[args['id']] = {};
    audio_audio[args['id']]['playing'] = false;

    for(var property in args['properties']){
        audio_audio[args['id']][property] = args['properties'][property];
    }

    audio_audio[args['id']]['connections'] = args['properties']['connections'] || [
      {
        'frequency': {
          'value': audio_audio[args['id']]['frequency'] || 100,
        },
        'label': 'Oscillator',
        'type': audio_audio[args['id']]['type'] || 'sine',
      },
      {
        'gain': {
          'value': args['properties']['volume'] || audio_volume,
        },
        'label': 'Gain',
      },
    ];

    audio_audio[args['id']]['connections'][0]['id'] = args['id'];
    audio_audio[args['id']]['connections'][0]['onended'] = function(){
        audio_onended({
          'this': this,
        });
    };
}

// Optional args: volume
function audio_init(args){
    args = core_args({
      'args': args,
      'defaults': {
        'volume': audio_volume_default,
      },
    });

    audio_context = new window.AudioContext();
    audio_volume = args['volume'];
}

// Optional args: id, properties
function audio_node_create(args){
    args = core_args({
      'args': args,
      'defaults': {
        'id': false,
        'properties': {},
      },
    });

    var source = audio_context['create' + args['properties']['label']](
      args['properties']['arg0'],
      args['properties']['arg1'],
      args['properties']['arg2']
    );

    for(var property in args['properties']){
        if(core_args({
          'type': 'object',
          'var': args['properties'][property],
        })){
            for(var subproperty in args['properties'][property]){
                source[property][subproperty] = args['properties'][property][subproperty];
            }

        }else{
            source[property] = args['properties'][property];
        }
    }

    if(args['id'] === false){
        return source;
    }

    audio_sources[args['id']][args['properties']['label']] = source;
}

// Required args: this
function audio_onended(args){
    audio_audio[args['this'].id]['playing'] = false;

    if(audio_audio[args['this'].id]['repeat']){
        if(audio_audio[args['this'].id]['timeout'] <= 0){
            audio_start({
              'id': args['this'].id,
            });

        }else{
            window.setTimeout(
              'audio_start({id:"' + args['this'].id + '"});',
              audio_audio[args['this'].id]['duration'] * audio_audio[args['this'].id]['timeout']
            );
        }
    }

    delete audio_sources[args['this'].id];
}

// Required args: id
// Optional args: volume-multiplier
function audio_source_create(args){
    args = core_args({
      'args': args,
      'defaults': {
        'volume-multiplier': audio_volume_multiplier,
      },
    });

    audio_sources[args['id']] = {
      'duration': audio_audio[args['id']]['duration'] || 0,
      'start': audio_audio[args['id']]['start'] || 0,
      'timeout': audio_audio[args['id']]['timeout'] || 1000,
    };

    // Create audio nodes.
    var connections_length = audio_audio[args['id']]['connections'].length;
    for(var i = 0; i < connections_length; i++){
        audio_node_create({
          'id': args['id'],
          'properties': audio_audio[args['id']]['connections'][i],
        });

        if(audio_audio[args['id']]['connections'][i]['label'] === 'Gain'){
            var volume = audio_audio[args['id']]['volume'] || audio_volume;
            audio_sources[args['id']]['Gain']['gain']['value'] =
              (audio_audio[args['id']]['volume'] || audio_volume)
                * args['volume-multiplier'];
        }
    }

    // Connect audio nodes.
    for(i = 0; i < connections_length - 1; i++){
        audio_sources[args['id']][audio_audio[args['id']]['connections'][i]['label']].connect(
          audio_sources[args['id']][audio_audio[args['id']]['connections'][i + 1]['label']]
        );
    }
    audio_sources[args['id']][audio_audio[args['id']]['connections'][connections_length - 1]['label']].connect(
      audio_context.destination
    );
}

// Required args: id
// Optional args: volume-multiplier
function audio_start(args){
    args = core_args({
      'args': args,
      'defaults': {
        'volume-multiplier': audio_volume_multiplier,
      },
    });

    if(args['volume-multiplier'] === 0){
        return;
    }

    if(audio_audio[args['id']]['playing']){
        audio_stop({
          'id': args['id'],
        });
    }

    audio_source_create({
      'id': args['id'],
      'volume-multiplier': args['volume-multiplier'],
    });

    var startTime = audio_context.currentTime + audio_sources[args['id']]['start'];
    audio_audio[args['id']]['playing'] = true;
    audio_sources[args['id']][audio_audio[args['id']]['connections'][0]['label']].start(startTime);
    audio_stop({
      'id': args['id'],
      'when': startTime + audio_sources[args['id']]['duration'],
    });
}

// Required args: id
// Optional args: when
function audio_stop(args){
    args = core_args({
      'args': args,
      'defaults': {
        'when': void 0,
      },
    });

    audio_sources[args['id']][audio_audio[args['id']]['connections'][0]['label']].stop(args['when']);
}

function audio_stop_all(){
    for(var id in audio_sources){
        audio_stop({
          'id': id,
        });
    }
}

var audio_audio = {};
var audio_context = 0;
var audio_sources = {};
var audio_volume = 1;
var audio_volume_default = 1;
var audio_volume_multiplier = 1;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import TooltipProvider from 'interface/common/TooltipProvider';

import ITEMS from './ITEMS';
import getItemQualityLabel from './getItemQualityLabel';
import ItemIcon from './ItemIcon';

class ItemLink extends React.PureComponent {
  static propTypes = {
    id: PropTypes.number.isRequired,
    children: PropTypes.node,
    details: PropTypes.object,
    quality: PropTypes.number,
    icon: PropTypes.bool,
  };
  static defaultProps = {
    icon: true,
  };

  elem = null;

  componentDidMount() {
    this.componentDidUpdate();
  }
  componentDidUpdate() {
    TooltipProvider.refresh(this.elem);
  }

  render() {
    const { id, children, details, icon, ...others } = this.props;
    delete others.quality;

    let quality = this.props.quality;
    if (quality === undefined || quality === null) {
      quality = ITEMS[id] ? ITEMS[id].quality : 0;
    }

    return (
      <a
        href={TooltipProvider.item(id, details)}
        target="_blank"
        rel="noopener noreferrer"
        className={getItemQualityLabel(quality)}
        ref={elem => {
          this.elem = elem;
        }}
        {...others}
      >
        {icon && <ItemIcon id={id} noLink />}{' '}
        {children || ITEMS[id].name}
      </a>
    );
  }
}

export default ItemLink;
<commit_msg>When an item doesn't exist, give more info in the error<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import TooltipProvider from 'interface/common/TooltipProvider';

import ITEMS from './ITEMS';
import getItemQualityLabel from './getItemQualityLabel';
import ItemIcon from './ItemIcon';

class ItemLink extends React.PureComponent {
  static propTypes = {
    id: PropTypes.number.isRequired,
    children: PropTypes.node,
    details: PropTypes.object,
    quality: PropTypes.number,
    icon: PropTypes.bool,
  };
  static defaultProps = {
    icon: true,
  };

  elem = null;

  componentDidMount() {
    this.componentDidUpdate();
  }
  componentDidUpdate() {
    TooltipProvider.refresh(this.elem);
  }

  render() {
    const { id, children, details, icon, ...others } = this.props;
    delete others.quality;

    if (process.env.NODE_ENV === 'development' && !children && !ITEMS[id]) {
      throw new Error(`Unknown item: ${id}`);
    }

    let quality = this.props.quality;
    if (quality === undefined || quality === null) {
      quality = ITEMS[id] ? ITEMS[id].quality : 0;
    }

    return (
      <a
        href={TooltipProvider.item(id, details)}
        target="_blank"
        rel="noopener noreferrer"
        className={getItemQualityLabel(quality)}
        ref={elem => {
          this.elem = elem;
        }}
        {...others}
      >
        {icon && <ItemIcon id={id} noLink />}{' '}
        {children || ITEMS[id].name}
      </a>
    );
  }
}

export default ItemLink;
<|endoftext|>


<commit_before>/* jshint undef: true, strict:false, trailing:false, unused:false */
/* global require, exports, console, process, module, L, angular, _, jQuery */

angular
	.module('aditl', ['ng','indx','infinite-scroll','ngAnimate'])
	.directive('dayContainer', function() {
		return {
			restrict:'E',
			scope:{ day:'=' },
			templateUrl:'/apps/aditl/templates/day-container.html',
			controller:function($scope) {
				var prezero = function(n) {
					return n < 10 ? '0'+n : n;
				};
				$scope.simpleTime = function(d) {
					return prezero(d.getHours()) + ':' + prezero(d.getMinutes());
				};
				$scope.isHigh = function(v, range) {};
				$scope.isMedium = function(v, range) {};
				$scope.isLow = function(v, range) {};
				$scope.decodeThumb = function(th) {
					console.log('decodethumb >> ', th.length, _(th).isArray());
					return th && th.join('') || ''; // decodeURIComponent(th);
				};
			}
		};
	}).directive('locmap', function() {
		return {
			restrict:'E',
			replace:true,
			scope:{ location:'=' },
			template:'

',
			link:function(scope, element, attribute) {

				var lat = scope.location && scope.location.peek('latitude'), lon = scope.location && scope.location.peek('longitude');
				// console.log(' location >> ', scope.location, lat, lon);
				// console.log('', JSON.stringify(scope.location.attributes));
				scope.map = L.map(element[0]);

				element.attr('data-latitude', lat);
				element.attr('data-longitude', lon);
				element.attr('data-id', scope.location && scope.location.id);

				L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '' }).addTo(scope.map);

				if (lat && lon) {
					scope.map.setView([lat, lon], 18);
					L.marker([lat, lon]).addTo(scope.map);
				}
				// add a marker in the given location, attach some popup content to it and open the popup
				    // .bindPopup(scope.location.peek('name') ? scope.location.peek('name') : scope.location.id)
				    // .openPopup();
			},
			controller:function($scope) {
			}
		};
	}).controller('main', function($scope, client, utils, entities) {
		var u = utils;
		$scope.days = [];
		// $scope.locations = [];
		var box, all_locs = [];
		var sa = function(fn) { return u.safeApply($scope, fn); };
		var weekday=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
		var months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];

		var getBrowsingTopDocs = function(tstart,tend) {
			var d = u.deferred();
			entities.activities.getByActivityType(box,tstart,tend,['browse']).then(function(reads) {
				console.log('READS[', tstart, '-', tend, '] >> ', reads);
				var docsbyid = {};
				var timebydoc = {};
				reads.map(function(read) {
					var doc = read.peek('what'), tstart = read.peek('tstart'), tend = read.peek('tend');
					if (doc) {
						docsbyid[doc.id] = doc;
						timebydoc[doc.id] = (timebydoc[doc.id] ? timebydoc[doc.id] : 0) + (tend-tstart);
					}
				});
				var docids = _(timebydoc).keys();
				docids.sort(function(a,b) { return timebydoc[b] - timebydoc[a]; });
				d.resolve(docids.map(function(xx) { return docsbyid[xx]; }));
			});
			return d.promise();
		};

		var isToday = function(d) {
			var today = new Date();
			return d.getDate() == today.getDate() && d.getYear() == today.getYear() && d.getMonth() == today.getMonth();
		};

		var getNikeFuel  = function(tstart,tend) {
			var d = u.deferred();
			jQuery.when(
				entities.activities.getNikeStepsPerMin(box, tstart, tend),
				entities.activities.getNikeCaloriesPerMin(box, tstart, tend),
				entities.activities.getNikeFuelPerMin(box, tstart, tend)
			).then(function(steps, calories, fuel, stars) {
				// laura help me out here :)
				var totals = {};
				totals.steps = steps && steps.length && steps.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.calories = calories && calories.length && calories.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.fuel = fuel && fuel.length && fuel.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				// totals.stars = stars && stars.length && stars.reduce(function(x,y) { return x.peek('val') + y.peek('val'); }, 0);
				d.resolve(totals);
			}).fail(d.reject);
			return d.promise();
		};

		var getFitBitMetrics  = function(tstart,tend) {
			var d = u.deferred();
			jQuery.when(
				entities.activities.getFitbitStepsPerMin(box, tstart, tend),
				entities.activities.getFitbitCaloriesPerMin(box, tstart, tend),
				entities.activities.getFitbitDistancePerMin(box, tstart, tend),
				entities.activities.getFitbitFloorsPerMin(box, tstart, tend),
				entities.activities.getFitbitElevationPerMin(box, tstart, tend)
			).then(function(steps, calories, distance, floors, elevation) {
				// laura help me out here :)
				// console.log("FITBITS >> ", steps);
				var totals = {};
				totals.steps = steps && steps.length && steps.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.calories = calories && calories.length && calories.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.distance = distance && distance.length && distance.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.floors = floors && floors.length && floors.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.elevation = elevation && elevation.length && elevation.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				d.resolve(totals);
			}).fail(d.reject);
			return d.promise();
		};

		var makeSegment = function(tstart, tend, segname, location) {
			var seg = {
				tstart: tstart,
				tend: tend,
				name : segname,
				location : location,
				nike : {},
				fitbit : {},
				tweets : [],
				documents: []
			};

			return seg;
		};

		var populateSegment = function(seg) {
			var tstart = seg.tstart, tend = seg.tend;

			getBrowsingTopDocs(tstart,tend).then(function(topdocs) {
				sa(function() { seg.documents = topdocs.slice(0,10); });
			});

			// getNikeFuel(tstart,tend).then(function(total) {
			// 	sa(function() { seg.nike = total; });
			// }).fail(function(bail) { console.log('couldnt get fuel '); });

			// getFitBitMetrics(tstart,tend).then(function(total) {
			// 	sa(function() {  seg.fitbit = total; });
			// }).fail(function(bail) { console.log('couldnt get fitbit '); });

			// entities.documents.getMyTweets(box, tstart, tend).then(function(tweets){
			// 	console.log('TWEETS for the segment [', tstart, '-', tend, '] >> ', tweets);
			// 	sa(function() {  seg.tweets = tweets; });
			// });

		};

		var createDay = function(date) {
			if (!box) return;

			var dstart = new Date(date.valueOf()); dstart.setHours(0,0,0,0);
			var dend = new Date(date.valueOf()); dend.setHours(23,59,59,999);
			var todaystart = new Date(); todaystart.setHours(0,0,0,0);

			var day = {
				date:date,dstart:dstart,dend:dend,
				dow: weekday[dstart.getDay()].toLowerCase(),
				dom:dstart.getDate(),
				month:months[dstart.getMonth()].toLowerCase().slice(0,3),
				segments:[]
			};

			// segment the day by activity
			entities.activities.getByActivityType(	box, dstart, dend, ['walking','cycling','running','stay','transport'] ).then(
				function(acts) {
					var sorted = acts.concat();
					sorted = sorted.filter(function(x) {
						if (!(x.peek('tstart') || x.peek('tend'))) {
							console.error('something is messed with ', x);
						}
						return x.peek('tstart') !== undefined && x.peek('tend') !== undefined; });
					sorted.sort(function(x,y) { return x.peek('tstart').valueOf() - y.peek('tstart').valueOf(); });
					console.log('ACTIVITIES for day ', dstart, ' ~~ >> ', acts.length, sorted.length, sorted.map(function(act) { return act.id; }));

					// [act1]  [act2][act3]           [act4]

					var segments = [];

					_(sorted).map(function(ca, i) {
						var cstart = ca.peek('tstart');
						if (i !== 0) {
							var last_end = sorted[i-1].peek('tend');
							if (last_end.valueOf() > cstart.valueOf()) {
								cstart = new Date(last_end.valueOf())+ 1;
							}
							if (last_end.valueOf()-cstart.valueOf() > 60*1000) {
								sa(function() { segments.push(makeSegment(last_end,cstart)); });
							}
						}

						var newseg = makeSegment(ca.peek('tstart'),ca.peek('tend'), ca.peek('activity'), ca.peek('waypoints'));
						newseg.moves = {};
						newseg.moves.calories = ca.peek('calories');
						newseg.moves.steps = ca.peek('steps');
						newseg.moves.distance = ca.peek('distance');
						segments.push(newseg);
					});

					if (isToday(date)) {
						// console.log('today is true !! ', segments.length > 0);
						if (segments.length > 0) {
							var last_end = segments[segments.length-1].tend;
							var last_shouldbe = (new Date());
							segments[segments.length - 1].tend = last_shouldbe;
						}
					}

					sa(function() { day.segments = day.segments.concat(segments); });

					segments.map(function(x) { populateSegment(x); });

					// add a segment for now
					// var last_end = (sorted.length && sorted[sorted.length-1].peek('tend') || dstart);
					// var last_shouldbe = new Date(Math.min( (new Date()).valueOf(), dend.valueOf() ));
					// if (last_shouldbe.valueOf() - last_end.valueOf() > 60*1000) {
					// 	sa(function() {
					// 		// test
					// 		sorted[sorted.length-1].set({tend:last_shouldbe});
					// 		// day.segments.push(makeSegment(last_end, last_shouldbe));
					// 	});
					// }

					// // filter for activities that have at least 1 waypoint
					// acts = acts.filter(function(x) { return x.peek('waypoints'); });
					// console.log('got activities for day :: ', dstart, ' > ', acts.length, acts);

					// // filter out activities that are shorter than 1 minute
					// acts = acts.filter(function(x) { return x.peek('tend') - x.peek('tstart') > 60000; });

					// // now have activities that have at least one segment and that are at least 1 minute
					// acts.map(function(act) {
					// 	var newseg = makeSegment( act.peek('tstart'), act.peek('tend'), act.peek('activity'), act.peek('waypoints') );
					// 	console.log('made segment >> ', newseg);
					// 	sa(function() { day.segments.push(newseg);	});
					// });
				}).fail(function(bail) {
					console.error('error getting activities >> ', bail);
				});
			return day;
		};
		$scope.generatePast = function(start_date, num_days) {
			console.log('generatePast >> ', start_date);
			var i = 1;
			if (start_date === undefined) {
				start_date = new Date(new Date().valueOf() + i*24*3600*1000);
			}
			while (i <= num_days) {
				var date = new Date(start_date.valueOf() - i*24*3600*1000);
				var cd = createDay(date);
				if (cd) { $scope.days.push(cd); }
				i++;
			}
		};

		$scope.$watch('user + box', function() {
			if (!$scope.user) { console.log('no user :( '); return; }
			$scope.days = [];
			client.store.getBox($scope.box).then(function(_box) {
				window.box = _box;
				box = _box;
				// box.query({type:'location'}).then(function(things) {
				// 	u.safeApply($scope, function() {
				// 		all_locs = things.concat();
				// 		$scope.locations = things.slice(0,6);
				// 	});
				// }).fail(function(bail) { console.log('fail querying ', bail); });
				// $scope.genDay();
				u.safeApply($scope, function() { $scope.generatePast(undefined,10); });
			}).fail(function(bail) { console.error(bail); });
		});
		window._s = $scope;
		window.entities = entities;
	});<commit_msg>changed top docs<commit_after>/* jshint undef: true, strict:false, trailing:false, unused:false */
/* global require, exports, console, process, module, L, angular, _, jQuery */

angular
	.module('aditl', ['ng','indx','infinite-scroll','ngAnimate'])
	.directive('dayContainer', function() {
		return {
			restrict:'E',
			scope:{ day:'=' },
			templateUrl:'/apps/aditl/templates/day-container.html',
			controller:function($scope) {
				var prezero = function(n) {
					return n < 10 ? '0'+n : n;
				};
				$scope.simpleTime = function(d) {
					return prezero(d.getHours()) + ':' + prezero(d.getMinutes());
				};
				$scope.isHigh = function(v, range) {};
				$scope.isMedium = function(v, range) {};
				$scope.isLow = function(v, range) {};
				$scope.decodeThumb = function(th) {
					console.log('decodethumb >> ', th.length, _(th).isArray());
					return th && th.join('') || ''; // decodeURIComponent(th);
				};
			}
		};
	}).directive('locmap', function() {
		return {
			restrict:'E',
			replace:true,
			scope:{ location:'=' },
			template:'

',
			link:function(scope, element, attribute) {

				var lat = scope.location && scope.location.peek('latitude'), lon = scope.location && scope.location.peek('longitude');
				// console.log(' location >> ', scope.location, lat, lon);
				// console.log('', JSON.stringify(scope.location.attributes));
				scope.map = L.map(element[0]);

				element.attr('data-latitude', lat);
				element.attr('data-longitude', lon);
				element.attr('data-id', scope.location && scope.location.id);

				L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '' }).addTo(scope.map);

				if (lat && lon) {
					scope.map.setView([lat, lon], 18);
					L.marker([lat, lon]).addTo(scope.map);
				}
				// add a marker in the given location, attach some popup content to it and open the popup
				    // .bindPopup(scope.location.peek('name') ? scope.location.peek('name') : scope.location.id)
				    // .openPopup();
			},
			controller:function($scope) {
			}
		};
	}).controller('main', function($scope, client, utils, entities) {
		var u = utils;
		$scope.days = [];
		// $scope.locations = [];
		var box, all_locs = [];
		var sa = function(fn) { return u.safeApply($scope, fn); };
		var weekday=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
		var months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];

		var getBrowsingTopDocs = function(tstart,tend) {
			var d = u.deferred();
			entities.activities.getByActivityType(box,tstart,tend,['browse']).then(function(reads) {
				console.log('READS[', tstart, '-', tend, '] >> ', reads);
				var docsbyid = {};
				var timebydoc = {};
				reads.map(function(read) {
					var doc = read.peek('what'), tstart = read.peek('tstart'), tend = read.peek('tend');
					if (doc) {
						docsbyid[doc.id] = doc;
						timebydoc[doc.id] = (timebydoc[doc.id] ? timebydoc[doc.id] : 0) + (tend-tstart);
					}
				});
				var docids = _(timebydoc).keys();
				docids.sort(function(a,b) { return timebydoc[b] - timebydoc[a]; });
				d.resolve(docids.map(function(xx) { return docsbyid[xx]; }));
			});
			return d.promise();
		};

		var isToday = function(d) {
			var today = new Date();
			return d.getDate() == today.getDate() && d.getYear() == today.getYear() && d.getMonth() == today.getMonth();
		};

		var getNikeFuel  = function(tstart,tend) {
			var d = u.deferred();
			jQuery.when(
				entities.activities.getNikeStepsPerMin(box, tstart, tend),
				entities.activities.getNikeCaloriesPerMin(box, tstart, tend),
				entities.activities.getNikeFuelPerMin(box, tstart, tend)
			).then(function(steps, calories, fuel, stars) {
				// laura help me out here :)
				var totals = {};
				totals.steps = steps && steps.length && steps.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.calories = calories && calories.length && calories.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.fuel = fuel && fuel.length && fuel.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				// totals.stars = stars && stars.length && stars.reduce(function(x,y) { return x.peek('val') + y.peek('val'); }, 0);
				d.resolve(totals);
			}).fail(d.reject);
			return d.promise();
		};

		var getFitBitMetrics  = function(tstart,tend) {
			var d = u.deferred();
			jQuery.when(
				entities.activities.getFitbitStepsPerMin(box, tstart, tend),
				entities.activities.getFitbitCaloriesPerMin(box, tstart, tend),
				entities.activities.getFitbitDistancePerMin(box, tstart, tend),
				entities.activities.getFitbitFloorsPerMin(box, tstart, tend),
				entities.activities.getFitbitElevationPerMin(box, tstart, tend)
			).then(function(steps, calories, distance, floors, elevation) {
				// laura help me out here :)
				// console.log("FITBITS >> ", steps);
				var totals = {};
				totals.steps = steps && steps.length && steps.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.calories = calories && calories.length && calories.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.distance = distance && distance.length && distance.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.floors = floors && floors.length && floors.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				totals.elevation = elevation && elevation.length && elevation.reduce(function(x,y) { return x + parseFloat(y.peek('value')); }, 0);
				d.resolve(totals);
			}).fail(d.reject);
			return d.promise();
		};

		var makeSegment = function(tstart, tend, segname, location) {
			var seg = {
				tstart: tstart,
				tend: tend,
				name : segname,
				location : location,
				nike : {},
				fitbit : {},
				tweets : [],
				documents: []
			};

			return seg;
		};

		var populateSegment = function(seg) {
			var tstart = seg.tstart, tend = seg.tend;

			getBrowsingTopDocs(tstart,tend).then(function(topdocs) {
				sa(function() { seg.documents = topdocs.slice(0,20); });
			});

			// getNikeFuel(tstart,tend).then(function(total) {
			// 	sa(function() { seg.nike = total; });
			// }).fail(function(bail) { console.log('couldnt get fuel '); });

			// getFitBitMetrics(tstart,tend).then(function(total) {
			// 	sa(function() {  seg.fitbit = total; });
			// }).fail(function(bail) { console.log('couldnt get fitbit '); });

			// entities.documents.getMyTweets(box, tstart, tend).then(function(tweets){
			// 	console.log('TWEETS for the segment [', tstart, '-', tend, '] >> ', tweets);
			// 	sa(function() {  seg.tweets = tweets; });
			// });

		};

		var createDay = function(date) {
			if (!box) return;

			var dstart = new Date(date.valueOf()); dstart.setHours(0,0,0,0);
			var dend = new Date(date.valueOf()); dend.setHours(23,59,59,999);
			var todaystart = new Date(); todaystart.setHours(0,0,0,0);

			var day = {
				date:date,dstart:dstart,dend:dend,
				dow: weekday[dstart.getDay()].toLowerCase(),
				dom:dstart.getDate(),
				month:months[dstart.getMonth()].toLowerCase().slice(0,3),
				segments:[]
			};

			// segment the day by activity
			entities.activities.getByActivityType(	box, dstart, dend, ['walking','cycling','running','stay','transport'] ).then(
				function(acts) {
					var sorted = acts.concat();
					sorted = sorted.filter(function(x) {
						if (!(x.peek('tstart') || x.peek('tend'))) {
							console.error('something is messed with ', x);
						}
						return x.peek('tstart') !== undefined && x.peek('tend') !== undefined; });
					sorted.sort(function(x,y) { return x.peek('tstart').valueOf() - y.peek('tstart').valueOf(); });
					console.log('ACTIVITIES for day ', dstart, ' ~~ >> ', acts.length, sorted.length, sorted.map(function(act) { return act.id; }));

					// [act1]  [act2][act3]           [act4]

					var segments = [];

					_(sorted).map(function(ca, i) {
						var cstart = ca.peek('tstart');
						if (i !== 0) {
							var last_end = sorted[i-1].peek('tend');
							if (last_end.valueOf() > cstart.valueOf()) {
								cstart = new Date(last_end.valueOf())+ 1;
							}
							if (last_end.valueOf()-cstart.valueOf() > 60*1000) {
								sa(function() { segments.push(makeSegment(last_end,cstart)); });
							}
						}

						var newseg = makeSegment(ca.peek('tstart'),ca.peek('tend'), ca.peek('activity'), ca.peek('waypoints'));
						newseg.moves = {};
						newseg.moves.calories = ca.peek('calories');
						newseg.moves.steps = ca.peek('steps');
						newseg.moves.distance = ca.peek('distance');
						segments.push(newseg);
					});

					if (isToday(date)) {
						// console.log('today is true !! ', segments.length > 0);
						if (segments.length > 0) {
							var last_end = segments[segments.length-1].tend;
							var last_shouldbe = (new Date());
							segments[segments.length - 1].tend = last_shouldbe;
						}
					}

					sa(function() { day.segments = day.segments.concat(segments); });

					segments.map(function(x) { populateSegment(x); });

					// add a segment for now
					// var last_end = (sorted.length && sorted[sorted.length-1].peek('tend') || dstart);
					// var last_shouldbe = new Date(Math.min( (new Date()).valueOf(), dend.valueOf() ));
					// if (last_shouldbe.valueOf() - last_end.valueOf() > 60*1000) {
					// 	sa(function() {
					// 		// test
					// 		sorted[sorted.length-1].set({tend:last_shouldbe});
					// 		// day.segments.push(makeSegment(last_end, last_shouldbe));
					// 	});
					// }

					// // filter for activities that have at least 1 waypoint
					// acts = acts.filter(function(x) { return x.peek('waypoints'); });
					// console.log('got activities for day :: ', dstart, ' > ', acts.length, acts);

					// // filter out activities that are shorter than 1 minute
					// acts = acts.filter(function(x) { return x.peek('tend') - x.peek('tstart') > 60000; });

					// // now have activities that have at least one segment and that are at least 1 minute
					// acts.map(function(act) {
					// 	var newseg = makeSegment( act.peek('tstart'), act.peek('tend'), act.peek('activity'), act.peek('waypoints') );
					// 	console.log('made segment >> ', newseg);
					// 	sa(function() { day.segments.push(newseg);	});
					// });
				}).fail(function(bail) {
					console.error('error getting activities >> ', bail);
				});
			return day;
		};
		$scope.generatePast = function(start_date, num_days) {
			console.log('generatePast >> ', start_date);
			var i = 1;
			if (start_date === undefined) {
				start_date = new Date(new Date().valueOf() + i*24*3600*1000);
			}
			while (i <= num_days) {
				var date = new Date(start_date.valueOf() - i*24*3600*1000);
				var cd = createDay(date);
				if (cd) { $scope.days.push(cd); }
				i++;
			}
		};

		$scope.$watch('user + box', function() {
			if (!$scope.user) { console.log('no user :( '); return; }
			$scope.days = [];
			client.store.getBox($scope.box).then(function(_box) {
				window.box = _box;
				box = _box;
				// box.query({type:'location'}).then(function(things) {
				// 	u.safeApply($scope, function() {
				// 		all_locs = things.concat();
				// 		$scope.locations = things.slice(0,6);
				// 	});
				// }).fail(function(bail) { console.log('fail querying ', bail); });
				// $scope.genDay();
				u.safeApply($scope, function() { $scope.generatePast(undefined,10); });
			}).fail(function(bail) { console.error(bail); });
		});
		window._s = $scope;
		window.entities = entities;
	});<|endoftext|>


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

/* eslint-disable no-console */

'use strict';

const Benchmark   = require('benchmark');
const pica        = require('../')();
const filter_gen  = require('../lib/mm_resize/resize_filter_gen');
const resize_raw  = require('../lib/mm_resize/resize');

const sample = {
  width:  1024,
  height: 1024
};
sample.buffer    = new Uint8Array(sample.width * sample.height * 4);

/* eslint-disable new-cap */
Benchmark.Suite()

.add(`Resize of ${sample.width}x${sample.height}`, {
  defer: true,
  fn: function (defer) {
    pica.resizeBuffer({
      src:      sample.buffer,
      width:    sample.width,
      height:   sample.height,
      toWidth:  (sample.width * 0.15)|0,
      toHeight: (sample.height * 0.15)|0,
      filter:   'lanczos3'
    })
    .then(() => defer.resolve());
  }
})

.add(`Resize RAW of ${sample.width}x${sample.height}`, {
  fn: function () {
    resize_raw({
      src:      sample.buffer,
      width:    sample.width,
      height:   sample.height,
      toWidth:  (sample.width * 0.15)|0,
      toHeight: (sample.height * 0.15)|0
    });
  }
})

.add(`Unsharp of ${sample.width}x${sample.height}`, {
  fn: function () {
    pica.__mathlib.unsharp_mask(
      sample.buffer, sample.width, sample.height,
      80, 0.5, 4
    );
  }
})

.add(`Build filters for ${sample.width}x${sample.height}`, {
  fn: function () {
    filter_gen(
      3,
      sample.width,
      (sample.width * 0.15)|0,
      sample.width / ((sample.width * 0.15)|0),
      0.0
    );
    filter_gen(
      3,
      sample.height,
      (sample.height * 0.15)|0,
      sample.height / ((sample.height * 0.15)|0),
      0.0
    );
  }
})

.on('cycle', event => {
  console.log(`> ${event.target}`);
})

.run();
<commit_msg>Refactor benchmark<commit_after>#!/usr/bin/env node

/* eslint-disable no-console */

'use strict';

const Benchmark   = require('benchmark');
const filter_gen  = require('../lib/mm_resize/resize_filter_gen');
const resize_raw  = require('../lib/mm_resize/resize');

const pica_js     = require('../')([ 'js' ]);
const pica_wasm   = require('../')([ 'wasm' ]);

const SRC_WIDTH = 1024;
const SRC_HEIGHT = 1024;
const SCALE = 0.15;
const DST_WIDTH = (SRC_WIDTH * SCALE)|0;
const DST_HEIGHT = (SRC_HEIGHT * SCALE)|0;

const sample = new Uint8Array(SRC_WIDTH * SRC_HEIGHT * 4);
sample.fill(255);

/* eslint-disable new-cap */
Benchmark.Suite()

.add(`[js] resize ${SRC_WIDTH}x${SRC_HEIGHT} => ${DST_WIDTH}x${DST_HEIGHT}`, {
  defer: true,
  fn: function (defer) {
    pica_js.resizeBuffer({
      src:      sample,
      width:    SRC_WIDTH,
      height:   SRC_HEIGHT,
      toWidth:  DST_WIDTH,
      toHeight: DST_HEIGHT,
      filter:   'lanczos3'
    })
    .then(() => defer.resolve());
  }
})

.add(`[wasm] resize ${SRC_WIDTH}x${SRC_HEIGHT} => ${DST_WIDTH}x${DST_HEIGHT}`, {
  defer: true,
  fn: function (defer) {
    pica_wasm.resizeBuffer({
      src:      sample,
      width:    SRC_WIDTH,
      height:   SRC_HEIGHT,
      toWidth:  DST_WIDTH,
      toHeight: DST_HEIGHT,
      filter:   'lanczos3'
    })
    .then(() => defer.resolve());
  }
})

.add(`mm js resize ${SRC_WIDTH}x${SRC_HEIGHT} => ${DST_WIDTH}x${DST_HEIGHT}`, {
  fn: function () {
    resize_raw({
      src:      sample,
      width:    SRC_WIDTH,
      height:   SRC_HEIGHT,
      toWidth:  DST_WIDTH,
      toHeight: DST_HEIGHT
    });
  }
})

.add(`[js] unsharp ${SRC_WIDTH}x${SRC_HEIGHT}`, {
  fn: function () {
    pica_js.__mathlib.unsharp_mask(
      sample, SRC_WIDTH, SRC_HEIGHT,
      80, 0.5, 4
    );
  }
})

.add(`[wasm] unsharp ${SRC_WIDTH}x${SRC_HEIGHT}`, {
  fn: function () {
    pica_wasm.__mathlib.unsharp_mask(
      sample, SRC_WIDTH, SRC_HEIGHT,
      80, 0.5, 4
    );
  }
})

.add(`Build filters for ${SRC_WIDTH}x${SRC_HEIGHT}`, {
  fn: function () {
    filter_gen(
      'lanczos3',
      SRC_WIDTH,
      DST_WIDTH,
      SCALE,
      0.0
    );
    filter_gen(
      'lanczos3',
      SRC_HEIGHT,
      DST_HEIGHT,
      SCALE,
      0.0
    );
  }
})

.on('cycle', event => {
  console.log(`> ${event.target}`);
})

.run();
<|endoftext|>


<commit_before>const sqlite3 = require('sqlite3').verbose();

class SqlStore {
  constructor() {
    this.db = new sqlite3.Database('./db/baby-cycle');
  }

  add({type, time}) {
    const stmt = this.db.prepare("INSERT INTO event (event_type, event_time) VALUES (?, ?)");

    stmt.run(type, time);

    stmt.finalize();
  }

  get(cb) {
    this.db.each(`
      SELECT
        event_id,
        event_type,
        event_time
      FROM event
      ORDER BY event_time DESC
      LIMIT 1
    `, (err, {event_type: type, event_time: time, event_id: id}) => {

      cb({type, time, id})
    });
  }

  getAll(cb) {
    this.db.all(`
      SELECT
        event_id,
        event_type,
        event_time
      FROM event
      ORDER BY event_time ASC
    `, (err, rows) => {
      cb(rows.map(({event_type, event_time, event_id}) => ({id: event_id, type: event_type, time: event_time})));
    });
  }

  delete(event_id, cb) {
    this.db.run(`DELETE FROM event where event_id = ${event_id}`, (err) => {
      if (!err) {
        cb();
      }
    });
  }

}

module.exports = SqlStore;
<commit_msg>feat: make sql database configurable<commit_after>const sqlite3 = require('sqlite3').verbose();

class SqlStore {
  constructor() {
    if (process.env.SQL_DB) {
      this.db = new sqlite3.Database(process.env.SQL_DB);
    } else {
      this.db = new sqlite3.Database('./db/baby-cycle');
    }

  }

  add({type, time}) {
    const stmt = this.db.prepare("INSERT INTO event (event_type, event_time) VALUES (?, ?)");

    stmt.run(type, time);

    stmt.finalize();
  }

  get(cb) {
    this.db.each(`
      SELECT
        event_id,
        event_type,
        event_time
      FROM event
      ORDER BY event_time DESC
      LIMIT 1
    `, (err, {event_type: type, event_time: time, event_id: id}) => {

      cb({type, time, id})
    });
  }

  getAll(cb) {
    this.db.all(`
      SELECT
        event_id,
        event_type,
        event_time
      FROM event
      ORDER BY event_time ASC
    `, (err, rows) => {
      cb(rows.map(({event_type, event_time, event_id}) => ({id: event_id, type: event_type, time: event_time})));
    });
  }

  delete(event_id, cb) {
    this.db.run(`DELETE FROM event where event_id = ${event_id}`, (err) => {
      if (!err) {
        cb();
      }
    });
  }
}

module.exports = SqlStore;
<|endoftext|>