<commit_before>/*!
 * Created by Rajeshwar Patlolla https://github.com/rajeshwarpatlolla
 * Modified by Marko Marković <okram@civokram.com>
 */
"use strict";angular.module("ionic-datepicker",["ionic","ionic-datepicker.template"]).directive("ionicDatepicker",["$ionicPopup",function(e){return{restrict:"AE",replace:!0,scope:{value:"=",weekBeginsOnMonday:"=",min:"=",max:"="},link:function(t,a){var i=angular.copy(t.value)||new Date;t.highlightedDate=angular.copy(i),t.weekDays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],t.weekBeginsOnMonday&&t.weekDays.push(t.weekDays.shift());var n=["January","February","March","April","May","June","July","August","September","October","November","December"];t.calendarRows=new Array(6),t.calendarCols=new Array(7);var r=function(e){t.dayList=[];for(var a=new Date(e.getFullYear(),e.getMonth(),1).getDate(),i=new Date(e.getFullYear(),e.getMonth()+1,0).getDate(),r=a;i>=r;r++){var o=new Date(e.getFullYear(),e.getMonth(),r);t.dayList.push({date:o,day:o.getDate()})}a=t.dayList[0].date.getDay(),t.weekBeginsOnMonday&&a--;for(var d=0;a>d;d++)t.dayList.unshift(void 0);t.currentMonth=n[e.getMonth()],t.currentYear=e.getFullYear()};t.prevMonth=function(){var e=new Date(i.getFullYear(),i.getMonth(),0);void 0!==t.min&&e<t.min||(i.setMonth(i.getMonth()-1),r(i))},t.nextMonth=function(){var e=new Date(i.getFullYear(),i.getMonth()+1,1);void 0!==t.max&&e>t.max||(i.setMonth(i.getMonth()+1),r(i))},t.highlightDate=function(e){if("undefined"!=typeof e){if(void 0!==t.min&&e<t.min)return;if(void 0!==t.max&&e>t.max)return;t.highlightedDate=angular.copy(e),i=e,r(i)}},t.isValidDay=function(e,a){var i=t.dayList[7*e+a];return"undefined"!=typeof i},t.isSelected=function(e,a){if(t.isValidDay(e,a)){var i=t.dayList[7*e+a];return i.date.toDateString()===t.highlightedDate.toDateString()}return!1},t.isToday=function(e,a){return t.isValidDay(e,a)?t.dayList[7*e+a].date.toDateString()===(new Date).toDateString():!1},t.isDisabled=function(e,a){if(t.isValidDay(e,a)){if(t.dayList[7*e+a].date<t.min)return!0;if(t.dayList[7*e+a].date>t.max)return!0}return!1},a.on("click",function(){r(i),e.show({templateUrl:"ionic-datepicker.template.html",title:"Select a date",subTitle:"",scope:t,buttons:[{text:'',type:"button-clear"},{text:"Today",onTap:function(e){var a=new Date;return void 0!==t.min&&a<t.min?void e.preventDefault():void 0!==t.max&&a>t.max?void e.preventDefault():(t.highlightDate(a),void(t.value=a))}},{text:'',type:"button-positive",onTap:function(){t.highlightDate(t.highlightedDate),t.value=t.highlightedDate}}]})})}}}]),function(e){try{e=angular.module("ionic-datepicker.template")}catch(t){e=angular.module("ionic-datepicker.template",[])}e.run(["$templateCache",function(e){e.put("ionic-datepicker.template.html",'

<button class="col col-10 button-clear icon-left ion-chevron-left" ng-click=prevMonth()></button>
{{ currentMonth }} — {{ currentYear }}
<button class="col col-10 button-clear icon-right ion-chevron-right" ng-click=nextMonth()></button>

{{ weekDay | limitTo:1 }}

{{ dayList[$parent.$index * 7 + $index].day }}

')}])}();<commit_msg>Build the dist files<commit_after>/*!
 * Created by Rajeshwar Patlolla https://github.com/rajeshwarpatlolla
 * Modified by Marko Marković <okram@civokram.com>
 *
 * @version 1.0.0
 */
"use strict";angular.module("ionic-datepicker",["ionic","ionic-datepicker.template"]).directive("ionicDatepicker",["$ionicPopup",function(e){return{restrict:"AE",replace:!0,scope:{value:"=",weekBeginsOnMonday:"=",min:"=",max:"="},link:function(t,a){var i=angular.copy(t.value)||new Date;t.highlightedDate=angular.copy(i),t.weekDays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],t.weekBeginsOnMonday&&t.weekDays.push(t.weekDays.shift());var n=["January","February","March","April","May","June","July","August","September","October","November","December"];t.calendarRows=new Array(6),t.calendarCols=new Array(7);var r=function(e){t.dayList=[];for(var a=new Date(e.getFullYear(),e.getMonth(),1).getDate(),i=new Date(e.getFullYear(),e.getMonth()+1,0).getDate(),r=a;i>=r;r++){var o=new Date(e.getFullYear(),e.getMonth(),r);t.dayList.push({date:o,day:o.getDate()})}a=t.dayList[0].date.getDay(),t.weekBeginsOnMonday&&a--;for(var d=0;a>d;d++)t.dayList.unshift(void 0);t.currentMonth=n[e.getMonth()],t.currentYear=e.getFullYear()};t.prevMonth=function(){var e=new Date(i.getFullYear(),i.getMonth(),0);void 0!==t.min&&e<t.min||(i.setMonth(i.getMonth()-1),r(i))},t.nextMonth=function(){var e=new Date(i.getFullYear(),i.getMonth()+1,1);void 0!==t.max&&e>t.max||(i.setMonth(i.getMonth()+1),r(i))},t.highlightDate=function(e){if("undefined"!=typeof e){if(void 0!==t.min&&e<t.min)return;if(void 0!==t.max&&e>t.max)return;t.highlightedDate=angular.copy(e),i=e,r(i)}},t.isValidDay=function(e,a){var i=t.dayList[7*e+a];return"undefined"!=typeof i},t.isSelected=function(e,a){if(t.isValidDay(e,a)){var i=t.dayList[7*e+a];return i.date.toDateString()===t.highlightedDate.toDateString()}return!1},t.isToday=function(e,a){return t.isValidDay(e,a)?t.dayList[7*e+a].date.toDateString()===(new Date).toDateString():!1},t.isDisabled=function(e,a){if(t.isValidDay(e,a)){if(t.dayList[7*e+a].date<t.min)return!0;if(t.dayList[7*e+a].date>t.max)return!0}return!1},a.on("click",function(){r(i),e.show({templateUrl:"ionic-datepicker.template.html",title:"Select a date",subTitle:"",scope:t,buttons:[{text:'',type:"button-clear"},{text:"Today",onTap:function(e){var a=new Date;return void 0!==t.min&&a<t.min?void e.preventDefault():void 0!==t.max&&a>t.max?void e.preventDefault():(t.highlightDate(a),void(t.value=a))}},{text:'',type:"button-positive",onTap:function(){t.highlightDate(t.highlightedDate),t.value=t.highlightedDate}}]})})}}}]),function(e){try{e=angular.module("ionic-datepicker.template")}catch(t){e=angular.module("ionic-datepicker.template",[])}e.run(["$templateCache",function(e){e.put("ionic-datepicker.template.html",'

<button class="col col-10 button-clear icon-left ion-chevron-left" ng-click=prevMonth()></button>
{{ currentMonth }} — {{ currentYear }}
<button class="col col-10 button-clear icon-right ion-chevron-right" ng-click=nextMonth()></button>

{{ weekDay | limitTo:1 }}

{{ dayList[$parent.$index * 7 + $index].day }}

')}])}();<|endoftext|>


<commit_before>/** @constructor */
GameTitle.Preloader = function( game )
{
  this.preloader = null;

  this.soundList = [];
  this.numberOfDecodedSounds = 0;
};

GameTitle.Preloader.stateKey = "Preloader";

GameTitle.Preloader.prototype.init = function()
{

};

GameTitle.Preloader.prototype.preload = function()
{
  this.stage.backgroundColor = 0x111111;

  var preloaderWidth = ( this.game.width * 0.67 / 2.0 ) | 0;
  var preloaderHeight = 32;
  var bmd = this.game.add.bitmapData( preloaderWidth, preloaderHeight );
  bmd.ctx.fillStyle = "#999999";
  bmd.ctx.fillRect( 0, 0, preloaderWidth, preloaderHeight );

  this.preloader = this.game.add.sprite( 0, 0, bmd );
  this.preloader.anchor.setTo( 0.5, 0.5 );
  this.preloader.position.setTo( this.world.centerX,
                                 this.world.height - this.preloader.height * 2 );
  this.load.setPreloadSprite( this.preloader );

  this.load.audio( "bell2", "assets/sounds/bell2.wav" );
};

GameTitle.Preloader.prototype.create = function()
{
  this.stage.backgroundColor = 0x222222;

  this.numberOfDecodedSounds = 0;

  var bell2 = this.game.add.audio( "bell2" );
  this.soundList.push( bell2 );

  // Apply callback to decoding sounds.
  for( var i = 0; i < this.soundList.length; i++ )
  {
    this.soundList[i].onDecoded.add( this.soundDecoded, this );
  }

  this.sound.setDecodedCallback( this.soundList, this.allSoundsDecoded, this );
};

GameTitle.Preloader.prototype.soundDecoded = function( audio )
{
  // Start scaling the preloader sprite towards 200% for audio decoding.
  this.numberOfDecodedSounds++;
  this.preloader.scale.set( 1.0 + ( this.numberOfDecodedSounds / this.soundList.length ), 1.0 );
};

GameTitle.Preloader.prototype.allSoundsDecoded = function()
{
  this.start();
};

GameTitle.Preloader.prototype.start = function()
{
  // First see if the "state" URL parameter was specified.
  var stateKey = this.game.net.getQueryString( "state" );
  if( stateKey !== "" )
  {
    if( this.state.checkState( stateKey ) )
    {
      // Just straight to this state.
      this.state.start( stateKey );
      return;
    }
    else
    {
      console.warn( stateKey + " is not a valid state key." );
    }
  }

  // Proceed to main menu, as usual.
  this.state.start( GameTitle.MainMenu.stateKey );
};
<commit_msg>Fixed situation where URL state parameter was always considered as present when not.<commit_after>/** @constructor */
GameTitle.Preloader = function( game )
{
  this.preloader = null;

  this.soundList = [];
  this.numberOfDecodedSounds = 0;
};

GameTitle.Preloader.stateKey = "Preloader";

GameTitle.Preloader.prototype.init = function()
{

};

GameTitle.Preloader.prototype.preload = function()
{
  this.stage.backgroundColor = 0x111111;

  var preloaderWidth = ( this.game.width * 0.67 / 2.0 ) | 0;
  var preloaderHeight = 32;
  var bmd = this.game.add.bitmapData( preloaderWidth, preloaderHeight );
  bmd.ctx.fillStyle = "#999999";
  bmd.ctx.fillRect( 0, 0, preloaderWidth, preloaderHeight );

  this.preloader = this.game.add.sprite( 0, 0, bmd );
  this.preloader.anchor.setTo( 0.5, 0.5 );
  this.preloader.position.setTo( this.world.centerX,
                                 this.world.height - this.preloader.height * 2 );
  this.load.setPreloadSprite( this.preloader );

  this.load.audio( "bell2", "assets/sounds/bell2.wav" );
};

GameTitle.Preloader.prototype.create = function()
{
  this.stage.backgroundColor = 0x222222;

  this.numberOfDecodedSounds = 0;

  var bell2 = this.game.add.audio( "bell2" );
  this.soundList.push( bell2 );

  // Apply callback to decoding sounds.
  for( var i = 0; i < this.soundList.length; i++ )
  {
    this.soundList[i].onDecoded.add( this.soundDecoded, this );
  }

  this.sound.setDecodedCallback( this.soundList, this.allSoundsDecoded, this );
};

GameTitle.Preloader.prototype.soundDecoded = function( audio )
{
  // Start scaling the preloader sprite towards 200% for audio decoding.
  this.numberOfDecodedSounds++;
  this.preloader.scale.set( 1.0 + ( this.numberOfDecodedSounds / this.soundList.length ), 1.0 );
};

GameTitle.Preloader.prototype.allSoundsDecoded = function()
{
  this.start();
};

GameTitle.Preloader.prototype.start = function()
{
  // First see if the "state" URL parameter was specified.
  var stateKey = this.game.net.getQueryString( "state" );
  if( typeof stateKey === "string" && stateKey !== "" )
  {
    if( this.state.checkState( stateKey ) )
    {
      // Just straight to this state.
      this.state.start( stateKey );
      return;
    }
    else
    {
      console.warn( stateKey + " is not a valid state key." );
    }
  }

  // Proceed to main menu, as usual.
  this.state.start( GameTitle.MainMenu.stateKey );
};
<|endoftext|>


<commit_before>import R from "ramda";
import httpProxy from "http-proxy"; // See: https://github.com/nodejitsu/node-http-proxy
import log from "./log";
import Route from "./route";
import { isEmpty } from "./util";

// Create Proxy server and handle errors.
const proxy = httpProxy.createProxyServer();
proxy.on("error", (err) => {
  switch (err.code) {
    case "ECONNRESET":
      // Ignore this error:
      //    It is a bug in the `node-http-proxy` that is getting fixed.
      //    See issue: https://github.com/nodejitsu/node-http-proxy/issues/898
      break;
    default: log.error(`PROXY error:`, err);
  }
});

const formatRedirects = (items) => {
    const result = [];
    items.forEach((item, i) => {
        // Extract the "to" and "from" parts.
        const parts = item.split("=>");
        let from = parts[0] && parts[0].trim();
        let to = parts[1] && parts[1].trim();

        // Parse the values into route objects.
        if (!isEmpty(from) && !isEmpty(to)) {
          from = Route.parse(from);
          to = Route.parse(to);
        } else {
          log.warn(`The redirect '${ item }' is invalid. Must be in a format like '*/from => */to'.`)
        }

        // Store.
        result.push({ from, to });
    });
    return result;
  };

const findRedirect = (domain, path, redirects) => {
  if (!redirects) { return; }
  let result = R.find(item => item.from.match(domain, path), redirects);
  if (result) {
    // Ensure the redirection is not pointing to the current URL.
    // Note: This avoids a redirection loop getting started.
    if (result.to.match(domain, path)) {
      result = null;
    }
  }
  return result;
};

/**
 * Starts the gateway.
 *
 * @param options:
 *            - middleware:     The express middleware.
 *            - mainApi:        The main API.
 *            - gatewayPort:    The gateway port.
 *
*/
export default (settings = {}) => {
  const { middleware, mainApi, gatewayPort } = settings;
  const { manifest } = mainApi;

  const redirectUrl = (req, route) => {
        let { domain, path } = route;
        if (domain === "*") { domain = req.get("host").split(":")[0]; }
        if (path === "*") { path = "/"; }
        return `${ req.protocol }://${ domain }:${ gatewayPort }/${ path }`;
      };

  // Read in the redirect table from the manifest (if it exists).
  let redirects = manifest.current && manifest.current.redirect;
  if (redirects) {
    redirects = formatRedirects(redirects);
  }

  middleware.get("*", (req, res) => {
      // Setup initial conditions.
      const host = req.get("host");
      const domain = (host && host.split(":")[0]) || "*";
      const path = req.url;

      // Check if there is a redirect for the route.
      const redirect = findRedirect(domain, path, redirects);
      if (redirect) {

        // A redirection URL was found - send the browser to that address now.
        // HTTP 302: Found ("Moved Temporarily").
        const url = redirectUrl(req, redirect.to);
        res.redirect(302, url);

      } else {

        // Lookup the app.
        const app = mainApi.findAppFromRoute(domain, path);
        if (app) {

          // An app matches the current route. Proxy the request to it.
          const target = { host: "localhost", port: app.port };
          proxy.web(req, res, { target });

        } else {
          // No matching route.
          res.status(404).send({ message: "Route not found", domain, path });
        }
      }
    });
};
<commit_msg>Fix lint.<commit_after>import R from "ramda";
import httpProxy from "http-proxy"; // See: https://github.com/nodejitsu/node-http-proxy
import log from "./log";
import Route from "./route";
import { isEmpty } from "./util";

// Create Proxy server and handle errors.
const proxy = httpProxy.createProxyServer();
proxy.on("error", (err) => {
  switch (err.code) {
    case "ECONNRESET":
      // Ignore this error:
      //    It is a bug in the `node-http-proxy` that is getting fixed.
      //    See issue: https://github.com/nodejitsu/node-http-proxy/issues/898
      break;
    default: log.error(`PROXY error:`, err);
  }
});

const formatRedirects = (items) => {
    const result = [];
    items.forEach(item => {
        // Extract the "to" and "from" parts.
        const parts = item.split("=>");
        let from = parts[0] && parts[0].trim();
        let to = parts[1] && parts[1].trim();

        // Parse the values into route objects.
        if (!isEmpty(from) && !isEmpty(to)) {
          from = Route.parse(from);
          to = Route.parse(to);
        } else {
          log.warn(`The redirect '${ item }' is invalid. Must be in a format like '*/from => */to'.`);
        }

        // Store.
        result.push({ from, to });
    });
    return result;
  };

const findRedirect = (domain, path, redirects) => {
  if (redirects) {
    const redirect = R.find(item => item.from.match(domain, path), redirects);
    if (redirect && !redirect.to.match(domain, path)) {
      // NOTE: Ensure the redirection is not pointing to the current URL.
      //       This avoids a redirection loop getting started.
      return redirect;
    }
  }
};

/**
 * Starts the gateway.
 *
 * @param options:
 *            - middleware:     The express middleware.
 *            - mainApi:        The main API.
 *            - gatewayPort:    The gateway port.
 *
*/
export default (settings = {}) => {
  const { middleware, mainApi, gatewayPort } = settings;
  const { manifest } = mainApi;

  const redirectUrl = (req, route) => {
        let { domain, path } = route;
        if (domain === "*") { domain = req.get("host").split(":")[0]; }
        if (path === "*") { path = "/"; }
        return `${ req.protocol }://${ domain }:${ gatewayPort }/${ path }`;
      };

  // Read in the redirect table from the manifest (if it exists).
  let redirects = manifest.current && manifest.current.redirect;
  if (redirects) {
    redirects = formatRedirects(redirects);
  }

  middleware.get("*", (req, res) => {
      // Setup initial conditions.
      const host = req.get("host");
      const domain = (host && host.split(":")[0]) || "*";
      const path = req.url;

      // Check if there is a redirect for the route.
      const redirect = findRedirect(domain, path, redirects);
      if (redirect) {

        // A redirection URL was found - send the browser to that address now.
        // HTTP 302: Found ("Moved Temporarily").
        const url = redirectUrl(req, redirect.to);
        res.redirect(302, url);

      } else {

        // Lookup the app.
        const app = mainApi.findAppFromRoute(domain, path);
        if (app) {

          // An app matches the current route. Proxy the request to it.
          const target = { host: "localhost", port: app.port };
          proxy.web(req, res, { target });

        } else {
          // No matching route.
          res.status(404).send({ message: "Route not found", domain, path });
        }
      }
    });
};
<|endoftext|>


<commit_before>$(function(){
	$("#container").delegate("#loginform", "submit", function(){
		var credentials = $(this).serializeArray();
		var uri = $(this).attr("action");

		$.post(uri, credentials, function(data){
			if(data.success === true){
				ContentManager.onLoginLogout(data.redirect, 250);
			}
			else{
				$("#errorcontainer").hide().html('' + data.error + '').fadeIn(250);
				$("#app").effect("shake", { direction:"up", times:2, distance:2 }, 50);
			}
		});

		return false;
	});

	$("#container").delegate("#logout", "click", function(){
		var uri = $(this).attr("href");
     	$.get(uri, function(redirect) {
           	$("#header").slideUp(250, function(){
				$("#headerwrapper").slideUp(250, function() {
      				ContentManager.onLoginLogout(redirect, 0);
				});
			});
          });

     	return false;
	});
});<commit_msg>Touched up auth.js to conform to style guide.<commit_after>$(function() {
    $(document).on("submit", "#loginform", function() {
        var credentials = $(this).serializeArray();
        var uri = $(this).attr("action");
        $.post(uri, credentials, function(data) {
            if(data.success === true) {
                ContentManager.onLoginLogout(data.redirect, 250);
            } else {
                $("#errorcontainer").hide().html('' + data.error + '').fadeIn(250);
                $("#app").effect("shake", { direction:"up", times:2, distance:2 }, 50);
            }
        });

        return false;
    });

    $(document).on("click", "#logout", function() {
        var uri = $(this).attr("href");
        $.get(uri, function(redirect) {
            $("#header").slideUp(250, function() {
                $("#headerwrapper").slideUp(250, function() {
                    ContentManager.onLoginLogout(redirect, 0);
                });
            });
        });

        return false;
    });
});<|endoftext|>


<commit_before>d3.csv(
    //'https://raw.githubusercontent.com/RhoInc/viz-library/master/data/queries/queries.csv',
    '../../viz-library/data/dataCleaning/queries/queries.csv',
    function(error,data) {
        if (error)
            console.log(error);

        var settings = {
            filters: [{value_col: 'fieldname', multiple: true}],
        };
        var instance = queryOverview(
            '#container',
            settings
        );
        instance.init(data);
    }
);
<commit_msg>remove custom setting<commit_after>d3.csv(
    //'https://raw.githubusercontent.com/RhoInc/viz-library/master/data/queries/queries.csv',
    '../../viz-library/data/dataCleaning/queries/queries.csv',
    function(error,data) {
        if (error)
            console.log(error);

        var settings = {
        };
        var instance = queryOverview(
            '#container',
            settings
        );
        instance.init(data);
    }
);
<|endoftext|>


<commit_before>var NULL_ADDRESS = '0x0000000000000000000000000000000000000000';

function getTransactionError(func) {
  return Promise.resolve().then(func)
    .then(function(txid) {
      var tx = web3.eth.getTransaction(txid);
      var txr = web3.eth.getTransactionReceipt(txid);
      if (txr.gasUsed === tx.gas) throw new Error("all gas used");
    })
    .catch(function(err) {
      return err;
    });
}

contract("SpiceHours", function(accounts) {

  describe("test", function() {

    it("should not throw an error for owner", function() {
      var contract = SpiceHours.deployed();
      return getTransactionError(function() {
        return contract.test();
      }).then(function(err) {
        assert.isUndefined(err, "owner should have access");
      });
    });

    it("should throw an error for others", function() {
      var contract = SpiceHours.deployed();
      return getTransactionError(function() {
        return contract.test({from: accounts[1]});
      }).then(function(err) {
        assert.isDefined(err, "others should not have access");
      });
    });
  });
});
<commit_msg>Fix tests after contract change broke them.<commit_after>var NULL_ADDRESS = '0x0000000000000000000000000000000000000000';

function getTransactionError(func) {
  return Promise.resolve().then(func)
    .then(function(txid) {
      var tx = web3.eth.getTransaction(txid);
      var txr = web3.eth.getTransactionReceipt(txid);
      if (txr.gasUsed === tx.gas) throw new Error("all gas used");
    })
    .catch(function(err) {
      return err;
    });
}

contract("SpiceHours", function(accounts) {

  describe("balance", function() {

    it("should be zero in the beginning", function() {
      var contract = SpiceHours.deployed();
      return contract.balance.call(accounts[0]).then(function(balance) {
        assert.equal(balance.valueOf(), 0, "balance should be zero");
      });
    });
  });
});
<|endoftext|>


<commit_before>
var express = require('../')
  , request = require('./support/http');

describe('app.router', function(){
  it('should be .use()able', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.use(app.router);

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  it('should be auto .use()d on the first app.VERB() call', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  describe(':name', function(){
    it('should denote a capture group', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('tj', done);
    })

    it('should allow several capture groups', function(done){
      var app = express();

      app.get('/user/:user/:op', function(req, res){
        res.end(req.params.op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe(':name?', function(){
    it('should denote an optional capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('viewing tj', done);
    })

    it('should populate the capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })
})
<commit_msg>optional trailing slash<commit_after>
var express = require('../')
  , request = require('./support/http');

describe('app.router', function(){
  it('should be .use()able', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.use(app.router);

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  it('should be auto .use()d on the first app.VERB() call', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  describe('trailing slashes', function(){
    it('should be optional by default', function(done){
      var app = express();

      app.get('/user', function(req, res){
        res.end('tj');
      });

      request(app)
      .get('/user/')
      .expect('tj', done);
    })
  })

  describe(':name', function(){
    it('should denote a capture group', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('tj', done);
    })

    it('should allow several capture groups', function(done){
      var app = express();

      app.get('/user/:user/:op', function(req, res){
        res.end(req.params.op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe(':name?', function(){
    it('should denote an optional capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('viewing tj', done);
    })

    it('should populate the capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })
})
<|endoftext|>


<commit_before>var capitalize = require('../capitalize');

var chai = require('chai');
var expect = chai.expect;

describe('capitalize', function() {
	it('capitalizes single words', function() {
		expect(capitalize('express')).to.equal('Express');
		expect(capitalize('cats')).to.equal('Cats');
	});

	it('makes the rest of the string lowercase', function() {
		expect(capitalize('javaScript')).to.equal('Javascript');
	});

	it('leaves empty strings alone', function() {
		expect(capitalize('')).to.equal('');
	});

	it('leaves strings with no words alone', function() {
		expect(capitalize(' ')).to.equal(' ');
		expect(capitalize('123')).to.equal('123');
	});

	it('capitalizes multiple-word strings', function() {
		expect(capitalize('what is Express')).to.equal('What is express');
		expect(capitalize('i love lamp')).to.equal('I love lamp');
	});

	it('leaves already-capitalized words alone', function() {
		expect(capitalize('Express')).to.equal('Express');
		expect(capitalize('Evan')).to.equal('Evan');
		expect(capitalize('Catman')).to.equal('Catman');
	});

	it('capitalizes String objects without changing their values', function() {
		var str = new String('who is JavaScript?');
		expect(capitalize(str)).to.equal('Who is javascript?');
		expect(str.valueOf()).to.equal('who is JavaScript?');
	});
});
<commit_msg>Add test which checks if errors are handled<commit_after>var capitalize = require('../capitalize');

var chai = require('chai');
var expect = chai.expect;

describe('capitalize', function() {
	it('capitalizes single words', function() {
		expect(capitalize('express')).to.equal('Express');
		expect(capitalize('cats')).to.equal('Cats');
	});

	it('makes the rest of the string lowercase', function() {
		expect(capitalize('javaScript')).to.equal('Javascript');
	});

	it('leaves empty strings alone', function() {
		expect(capitalize('')).to.equal('');
	});

	it('leaves strings with no words alone', function() {
		expect(capitalize(' ')).to.equal(' ');
		expect(capitalize('123')).to.equal('123');
	});

	it('capitalizes multiple-word strings', function() {
		expect(capitalize('what is Express')).to.equal('What is express');
		expect(capitalize('i love lamp')).to.equal('I love lamp');
	});

	it('leaves already-capitalized words alone', function() {
		expect(capitalize('Express')).to.equal('Express');
		expect(capitalize('Evan')).to.equal('Evan');
		expect(capitalize('Catman')).to.equal('Catman');
	});

	it('capitalizes String objects without changing their values', function() {
		var str = new String('who is JavaScript?');
		expect(capitalize(str)).to.equal('Who is javascript?');
		expect(str.valueOf()).to.equal('who is JavaScript?');
	});

	it('throws an error if passed a number', function() {
		expect(function() { capitalize(123); }).to.throw(Error);
	});
});
<|endoftext|>


<commit_before>/* eslint-env mocha */

const assert = require('assert')
const crypto = require('crypto')
const albatross = require('../')

const id = crypto.randomBytes(4).toString('hex')
const ObjectID = albatross.ObjectID

describe('Collection', () => {
  let db, user, linusId

  before(async () => {
    db = albatross('mongodb://localhost/albatross-test')
    user = db.collection('user-' + id)
    await user.remove({})
  })

  beforeEach(async () => {
    linusId = new ObjectID()

    await user.insert({ name: 'Linus', _id: linusId })
    await user.insert({ name: 'Steve' })
    await user.insert({ name: 'Bob' })
  })

  afterEach(async () => {
    await user.remove({})
  })

  after(async () => {
    await db.close()
  })

  describe('#findById', () => {
    it('should find one record', async () => {
      const doc = await user.findById(linusId)
      assert.ok(doc)
      assert.strictEqual(doc.name, 'Linus')
    })

    it('should not match if string', async () => {
      const doc = await user.findById(linusId.toHexString())
      assert.strictEqual(doc, null)
    })
  })

  describe('#findOne', () => {
    it('should find one record', async () => {
      const doc = await user.findOne({ name: 'Linus' })
      assert.ok(doc)
      assert.strictEqual(doc.name, 'Linus')
    })

    it('should find only one record', async () => {
      const doc = await user.findOne({ name: { $ne: 'Linus' } })
      assert.ok(doc)
      assert.notStrictEqual(doc.name, 'Linus')
    })
  })

  describe('#find', () => {
    it('should find one record', async () => {
      const docs = await user.find({ name: 'Linus' })
      assert.ok(docs)
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 1)
      assert.strictEqual(docs[0].name, 'Linus')
    })

    it('should find multiple records', async () => {
      const docs = await user.find({ name: { $ne: 'Linus' } })
      assert.ok(docs)
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 2)
      assert.notStrictEqual(docs[0].name, 'Linus')
      assert.notStrictEqual(docs[1].name, 'Linus')
    })

    it('should find all records', async () => {
      const docs = await user.find({})
      assert.ok(docs)
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 3)
    })
  })

  describe('#count', () => {
    it('should count one record', async () => {
      const res = await user.count({ name: 'Linus' })
      assert.strictEqual(res, 1)
    })

    it('should count multiple records', async () => {
      const res = await user.count({ name: { $ne: 'Linus' } })
      assert.strictEqual(res, 2)
    })

    it('should count all records', async () => {
      const res = await user.count({})
      assert.strictEqual(res, 3)
    })
  })

  describe('#distinct', () => {
    it('should find one distinct names', async () => {
      const res = await user.distinct('name', { name: 'Linus' })
      assert.ok(Array.isArray(res))
      assert.strictEqual(res.length, 1)
      assert.strictEqual(res[0], 'Linus')
    })

    it('should find some distinct names', async () => {
      const res = await user.distinct('name', { name: { $ne: 'Linus' } })
      assert.ok(Array.isArray(res))
      assert.strictEqual(res.length, 2)
      assert.ok(res.includes('Steve'))
      assert.ok(res.includes('Bob'))
    })

    it('should find all distinct names', async () => {
      const res = await user.distinct('name')
      assert.ok(Array.isArray(res))
      assert.strictEqual(res.length, 3)
      assert.ok(res.includes('Linus'))
      assert.ok(res.includes('Steve'))
      assert.ok(res.includes('Bob'))
    })
  })

  describe('#insert', () => {
    it('should insert a single document', async () => {
      const doc = await user.insert({ test: 'foo' })
      assert.ok(doc)
      assert.strictEqual(doc.test, 'foo')
    })

    it('should insert multiple documents', async () => {
      const docs = await user.insert([{ test: 'foo' }, { test: 'bar' }])
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 2)
      assert.strictEqual(docs[0].test, 'foo')
      assert.strictEqual(docs[1].test, 'bar')
    })
  })

  describe('#update', () => {
    it('should update one record', async () => {
      const res = await user.update({ name: 'Linus' }, { $set: { year: 1992 } })
      assert.strictEqual(res, 1)

      const docs = await user.find({ name: 'Linus' })
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 1)
      assert.strictEqual(docs[0].name, 'Linus')
      assert.strictEqual(docs[0].year, 1992)
    })

    it('should update multiple records', async () => {
      const res = await user.update({ name: { $ne: 'Linus' } }, { $set: { famous: true } }, { multi: true })
      assert.strictEqual(res, 2)

      const docs = await user.find({ name: { $ne: 'Linus' } })
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 2)
      assert.strictEqual(docs[0].famous, true)
      assert.strictEqual(docs[1].famous, true)
    })

    it('should update all records', async () => {
      const res = await user.update({}, { $set: { planet: 'Earth' } }, { multi: true })
      assert.strictEqual(res, 3)

      const docs = await user.find({})
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 3)
      assert.strictEqual(docs[0].planet, 'Earth')
      assert.strictEqual(docs[1].planet, 'Earth')
      assert.strictEqual(docs[2].planet, 'Earth')
    })

    it('should only update one record', async () => {
      const res = await user.update({}, { $set: { planet: 'Earth' } })
      assert.strictEqual(res, 1)
    })

    it('should not accept single', () => {
      assert.throws(() => {
        user.update({}, { $set: { planet: 'Earth' } }, { single: true })
      })
    })
  })

  describe('#remove', () => {
    it('should remove one record', async () => {
      const res = await user.remove({ name: 'Linus' })
      assert.strictEqual(res, 1)

      const docs = await user.find({ name: 'Linus' })
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 0)
    })

    it('should remove multiple records', async () => {
      const res = await user.remove({ name: { $ne: 'Linus' } })
      assert.strictEqual(res, 2)

      const docs = await user.find({ name: { $ne: 'Linus' } })
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 0)
    })

    it('should remove all records', async () => {
      const res = await user.remove({})
      assert.strictEqual(res, 3)

      const docs = await user.find({})
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 0)
    })

    it('should only remove one record', async () => {
      const res = await user.remove({}, { single: true })
      assert.strictEqual(res, 1)
    })

    it('should not accept multi', () => {
      assert.throws(() => {
        user.remove({}, { multi: false })
      })
    })
  })
})
<commit_msg>🌹 Add tests for limit & sort<commit_after>/* eslint-env mocha */

const assert = require('assert')
const crypto = require('crypto')
const albatross = require('../')

const id = crypto.randomBytes(4).toString('hex')
const ObjectID = albatross.ObjectID

describe('Collection', () => {
  let db, user, linusId

  before(async () => {
    db = albatross('mongodb://localhost/albatross-test')
    user = db.collection('user-' + id)
    await user.remove({})
  })

  beforeEach(async () => {
    linusId = new ObjectID()

    await user.insert({ name: 'Linus', _id: linusId })
    await user.insert({ name: 'Steve' })
    await user.insert({ name: 'Bob' })
  })

  afterEach(async () => {
    await user.remove({})
  })

  after(async () => {
    await db.close()
  })

  describe('#findById', () => {
    it('should find one record', async () => {
      const doc = await user.findById(linusId)
      assert.ok(doc)
      assert.strictEqual(doc.name, 'Linus')
    })

    it('should not match if string', async () => {
      const doc = await user.findById(linusId.toHexString())
      assert.strictEqual(doc, null)
    })
  })

  describe('#findOne', () => {
    it('should find one record', async () => {
      const doc = await user.findOne({ name: 'Linus' })
      assert.ok(doc)
      assert.strictEqual(doc.name, 'Linus')
    })

    it('should find only one record', async () => {
      const doc = await user.findOne({ name: { $ne: 'Linus' } })
      assert.ok(doc)
      assert.notStrictEqual(doc.name, 'Linus')
    })
  })

  describe('#find', () => {
    it('should find one record', async () => {
      const docs = await user.find({ name: 'Linus' })
      assert.ok(docs)
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 1)
      assert.strictEqual(docs[0].name, 'Linus')
    })

    it('should find multiple records', async () => {
      const docs = await user.find({ name: { $ne: 'Linus' } })
      assert.ok(docs)
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 2)
      assert.notStrictEqual(docs[0].name, 'Linus')
      assert.notStrictEqual(docs[1].name, 'Linus')
    })

    it('should find all records', async () => {
      const docs = await user.find({})
      assert.ok(docs)
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 3)
    })

    it('should limit number of records', async () => {
      const docs = await user.find({}, { limit: 2 })
      assert.ok(docs)
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 2)
    })

    it('should sort records ascending', async () => {
      const docs = await user.find({}, { sort: { name: 1 } })
      assert.ok(docs)
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 3)
      assert.strictEqual(docs[0].name, 'Bob')
      assert.strictEqual(docs[1].name, 'Linus')
      assert.strictEqual(docs[2].name, 'Steve')
    })

    it('should sort records descending', async () => {
      const docs = await user.find({}, { sort: { name: -1 } })
      assert.ok(docs)
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 3)
      assert.strictEqual(docs[0].name, 'Steve')
      assert.strictEqual(docs[1].name, 'Linus')
      assert.strictEqual(docs[2].name, 'Bob')
    })
  })

  describe('#count', () => {
    it('should count one record', async () => {
      const res = await user.count({ name: 'Linus' })
      assert.strictEqual(res, 1)
    })

    it('should count multiple records', async () => {
      const res = await user.count({ name: { $ne: 'Linus' } })
      assert.strictEqual(res, 2)
    })

    it('should count all records', async () => {
      const res = await user.count({})
      assert.strictEqual(res, 3)
    })
  })

  describe('#distinct', () => {
    it('should find one distinct names', async () => {
      const res = await user.distinct('name', { name: 'Linus' })
      assert.ok(Array.isArray(res))
      assert.strictEqual(res.length, 1)
      assert.strictEqual(res[0], 'Linus')
    })

    it('should find some distinct names', async () => {
      const res = await user.distinct('name', { name: { $ne: 'Linus' } })
      assert.ok(Array.isArray(res))
      assert.strictEqual(res.length, 2)
      assert.ok(res.includes('Steve'))
      assert.ok(res.includes('Bob'))
    })

    it('should find all distinct names', async () => {
      const res = await user.distinct('name')
      assert.ok(Array.isArray(res))
      assert.strictEqual(res.length, 3)
      assert.ok(res.includes('Linus'))
      assert.ok(res.includes('Steve'))
      assert.ok(res.includes('Bob'))
    })
  })

  describe('#insert', () => {
    it('should insert a single document', async () => {
      const doc = await user.insert({ test: 'foo' })
      assert.ok(doc)
      assert.strictEqual(doc.test, 'foo')
    })

    it('should insert multiple documents', async () => {
      const docs = await user.insert([{ test: 'foo' }, { test: 'bar' }])
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 2)
      assert.strictEqual(docs[0].test, 'foo')
      assert.strictEqual(docs[1].test, 'bar')
    })
  })

  describe('#update', () => {
    it('should update one record', async () => {
      const res = await user.update({ name: 'Linus' }, { $set: { year: 1992 } })
      assert.strictEqual(res, 1)

      const docs = await user.find({ name: 'Linus' })
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 1)
      assert.strictEqual(docs[0].name, 'Linus')
      assert.strictEqual(docs[0].year, 1992)
    })

    it('should update multiple records', async () => {
      const res = await user.update({ name: { $ne: 'Linus' } }, { $set: { famous: true } }, { multi: true })
      assert.strictEqual(res, 2)

      const docs = await user.find({ name: { $ne: 'Linus' } })
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 2)
      assert.strictEqual(docs[0].famous, true)
      assert.strictEqual(docs[1].famous, true)
    })

    it('should update all records', async () => {
      const res = await user.update({}, { $set: { planet: 'Earth' } }, { multi: true })
      assert.strictEqual(res, 3)

      const docs = await user.find({})
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 3)
      assert.strictEqual(docs[0].planet, 'Earth')
      assert.strictEqual(docs[1].planet, 'Earth')
      assert.strictEqual(docs[2].planet, 'Earth')
    })

    it('should only update one record', async () => {
      const res = await user.update({}, { $set: { planet: 'Earth' } })
      assert.strictEqual(res, 1)
    })

    it('should not accept single', () => {
      assert.throws(() => {
        user.update({}, { $set: { planet: 'Earth' } }, { single: true })
      })
    })
  })

  describe('#remove', () => {
    it('should remove one record', async () => {
      const res = await user.remove({ name: 'Linus' })
      assert.strictEqual(res, 1)

      const docs = await user.find({ name: 'Linus' })
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 0)
    })

    it('should remove multiple records', async () => {
      const res = await user.remove({ name: { $ne: 'Linus' } })
      assert.strictEqual(res, 2)

      const docs = await user.find({ name: { $ne: 'Linus' } })
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 0)
    })

    it('should remove all records', async () => {
      const res = await user.remove({})
      assert.strictEqual(res, 3)

      const docs = await user.find({})
      assert.ok(Array.isArray(docs))
      assert.strictEqual(docs.length, 0)
    })

    it('should only remove one record', async () => {
      const res = await user.remove({}, { single: true })
      assert.strictEqual(res, 1)
    })

    it('should not accept multi', () => {
      assert.throws(() => {
        user.remove({}, { multi: false })
      })
    })
  })
})
<|endoftext|>


<commit_before>var assert = require('assert');
var h = require('./helpers');

suite('concurrent', function () {

  this.timeout(5000);

  setup(function () {
    process.chdir('./test');
  });

  teardown(function () {
    process.chdir('../');
  });

  test(' simple concurrent prerequisites 1', function (next) {
    h.exec('../bin/cli.js -q concurrent:simple1', function (out) {
      assert.equal('Started A\nStarted B\nFinished B\nFinished A', out);
      next();
    });
  });

  test(' simple concurrent prerequisites 2', function (next) {
    h.exec('../bin/cli.js -q concurrent:simple2', function (out) {
      assert.equal('Started C\nStarted D\nFinished C\nFinished D', out);
      next();
    });
  });

  test(' sequential concurrent prerequisites', function (next) {
    h.exec('../bin/cli.js -q concurrent:seqconcurrent', function (out) {
      assert.equal('Started A\nStarted B\nFinished B\nFinished A\nStarted C\nStarted D\nFinished C\nFinished D', out);
      next();
    });
  });

  test(' concurrent concurrent prerequisites', function (next) {
    h.exec('../bin/cli.js -q concurrent:concurrentconcurrent', function (out) {
      assert.equal('Started A\nStarted B\nStarted C\nStarted D\nFinished B\nFinished C\nFinished A\nFinished D', out);
      next();
    });
  });

  test(' concurrent prerequisites with subdependency', function (next) {
    h.exec('../bin/cli.js -q concurrent:subdep', function (out) {
      assert.equal('Started A\nFinished A\nStarted Ba\nFinished Ba', out);
      next();
    });
  });

  test(' failing in concurrent prerequisites', function (next) {
    h.exec('../bin/cli.js -q concurrent:Cfail', {breakOnError:false}, function (out) {
      assert.equal(1, out.code);
      next();
    });
  });

});
<commit_msg>More test cleanup<commit_after>let assert = require('assert');
let h = require('./helpers');
let exec = require('child_process').execSync;

suite('concurrent', function () {

  this.timeout(5000);

  setup(function () {
    process.chdir('./test');
  });

  teardown(function () {
    process.chdir('../');
  });

  test(' simple concurrent prerequisites 1', function () {
    let out = exec('../bin/cli.js -q concurrent:simple1').toString().trim()
    assert.equal('Started A\nStarted B\nFinished B\nFinished A', out);
  });

  test(' simple concurrent prerequisites 2', function () {
    let out = exec('../bin/cli.js -q concurrent:simple2').toString().trim()
    assert.equal('Started C\nStarted D\nFinished C\nFinished D', out);
  });

  test(' sequential concurrent prerequisites', function () {
    let out = exec('../bin/cli.js -q concurrent:seqconcurrent').toString().trim()
    assert.equal('Started A\nStarted B\nFinished B\nFinished A\nStarted C\nStarted D\nFinished C\nFinished D', out);
  });

  test(' concurrent concurrent prerequisites', function () {
    let out = exec('../bin/cli.js -q concurrent:concurrentconcurrent').toString().trim()
    assert.equal('Started A\nStarted B\nStarted C\nStarted D\nFinished B\nFinished C\nFinished A\nFinished D', out);
  });

  test(' concurrent prerequisites with subdependency', function () {
    let out = exec('../bin/cli.js -q concurrent:subdep').toString().trim()
    assert.equal('Started A\nFinished A\nStarted Ba\nFinished Ba', out);
  });

  test(' failing in concurrent prerequisites', function () {
    try {
      exec('../bin/cli.js -q concurrent:Cfail');
    }
    catch(err) {
      assert(err.message.indexOf('Command failed') > -1);
    }
  });

});
<|endoftext|>


<commit_before>import {createServer as httpServer} from 'http'
import {parse as parseURL} from 'url'
import {join as joinPath} from 'path'
import {stat} from 'fs'
import {transpile} from './index'

export default function service({base, lang, port}) {
	//var watched = []

	httpServer((req, res) => {

		if (req.method === 'GET') {
			let f = joinPath(base, parseURL(req.url).pathname)
			f = f.replace(/^\\\\([A-Z])\|/, '$1:')
			//if (watched.indexOf(path) >= 0)
			const send = (status, message) => {
				const s = message + ': ' + f + '\n'
				res.writeHead(status)
				res.end(s)
				if (status >= 400) console.error(s)
				else console.info(s)
			}

			stat(f, (err, stats) => {
				if (err) return send(404, err)
				if (!stats.isFile()) return send(404, 'path is not a file')

				const t0 = Date.now()
				try {
					lang.forEach(lang => transpile(f, f.replace(/\.jedi$/, '.' + lang), lang))
				} catch (e) {
					if (e.code === 'EACCES') return send(403, 'jedi probably cannot access directory')
					else return send(500, e.message)
				}
				const t1 = Date.now()
				send(200, 'transpiled in ' + (t1 - t0) + 'ms')
			})

			//transpiler.watch(loc.pathname)
		} else {
			res.writeHead(405)
			res.end()
		}

	}).listen(port)

	process.on('uncaughtException', err => {
		console.error(new Date().toISOString(), 'uncaught exception:', err)
		console.trace(err)
	})

}
<commit_msg>add version url for service<commit_after>import {createServer as httpServer} from 'http'
import {parse as parseURL} from 'url'
import {join as joinPath} from 'path'
import {stat} from 'fs'
import {transpile} from './index'
import pkg from '../package'

export default function service({base, lang, port}) {
	//var watched = []

	httpServer((req, res) => {

		if (req.method === 'GET') {
			if (req.url === '/--version') {
				res.writeHead(200)
				res.end(pkg.version)
				return
			}

			let f = joinPath(base, parseURL(req.url).pathname)
			f = f.replace(/^\\\\([A-Z])\|/, '$1:')
			//if (watched.indexOf(path) >= 0)
			const send = (status, message) => {
				const s = message + ': ' + f + '\n'
				res.writeHead(status)
				res.end(s)
				if (status >= 400) console.error(s)
				else console.info(s)
			}

			stat(f, (err, stats) => {
				if (err) return send(404, err)
				if (!stats.isFile()) return send(404, 'path is not a file')

				const t0 = Date.now()
				try {
					lang.forEach(lang => transpile(f, f.replace(/\.jedi$/, '.' + lang), lang))
				} catch (e) {
					if (e.code === 'EACCES') return send(403, 'jedi probably cannot access directory')
					else return send(500, e.message)
				}
				const t1 = Date.now()
				send(200, 'transpiled in ' + (t1 - t0) + 'ms')
			})

			//transpiler.watch(loc.pathname)
		} else {
			res.writeHead(405)
			res.end()
		}

	}).listen(port)

	process.on('uncaughtException', err => {
		console.error(new Date().toISOString(), 'uncaught exception:', err)
		console.trace(err)
	})

}
<|endoftext|>


<commit_before>'use strict';

var test = require('tape');
var stanza = require('../index');

test('Connect using WebSocket', function (t) {
    t.plan(1);

    var client = stanza.createClient({
        jid: 'anon@anon.lance.im',
        transport: 'websocket',
        wsURL: 'wss://lance.im:5281/xmpp-websocket'
    });

    client.on('session:started', function () {
        t.pass('Connected with WebSocket');
        client.disconnect();
    });

    client.connect();
});

test('Connect using BOSH', function (t) {
    t.plan(1);

    var client = stanza.createClient({
        jid: 'anon@anon.lance.im',
        transport: 'bosh',
        boshURL: 'https://lance.im:5281/http-bind'
    });

    client.on('session:started', function () {
        t.pass('Connected with BOSH');
        client.disconnect();
    });

    client.connect();
});
<commit_msg>Fix test connection URIs<commit_after>'use strict';

var test = require('tape');
var stanza = require('../index');

test('Connect using WebSocket', function (t) {
    t.plan(1);

    var client = stanza.createClient({
        jid: 'anon@anon.lance.im',
        transport: 'websocket',
        wsURL: 'wss://anon.lance.im/xmpp-websocket'
    });

    client.on('session:started', function () {
        t.pass('Connected with WebSocket');
        client.disconnect();
    });

    client.connect();
});

test('Connect using BOSH', function (t) {
    t.plan(1);

    var client = stanza.createClient({
        jid: 'anon@anon.lance.im',
        transport: 'bosh',
        boshURL: 'https://anon.lance.im/http-bind'
    });

    client.on('session:started', function () {
        t.pass('Connected with BOSH');
        client.disconnect();
    });

    client.connect();
});
<|endoftext|>


<commit_before>import { map } from 'lodash';
import makeDebug from 'debug';
import { Service as BaseService } from 'feathers-mongoose';
import { errorHandler } from 'feathers-mongoose/lib/error-handler';

const debug = makeDebug('mostly:feathers-mongoose:service');

const defaultOptions = {
  lean: true,
  paginate: {
    default: 10,
    max: 50
  }
};

// prevent accidental multiple operations
const assertMultiple = function(id, params, message) {
  if (!id) {
    if (params && params.query && (params.$multi || params.query.$multi)) {
      delete params.query.$multi;
    } else {
      throw new Error(message);
    }
  }
};

// transform the results
const transform = function(results) {
  let data = [].concat(results? results.data || results : []);
  data.forEach(item => {
    // item = Object.assign({}, item);
    // output id string instead of _id
    item.id = (item._id || item.id).toString();
    delete item._id;
    delete item.__v;
    // debug('transform item %j', item);
  });
  return results;
};

export class Service extends BaseService {
  constructor(options) {
    options = Object.assign({}, defaultOptions, options);
    super(options);

    delete options.Model;
    delete options.ModelName;

    this.options = options;
    this.name = options.name || 'mongoose-service';
  }

  setup(app) {
    this.app = app;
  }

  find(params) {
    params = params || { query: {} };
    // default behaviours for external call
    if (params.provider && params.query) {
      // fix id query as _ids
      if (params.query.id) {
        params.query._id = params.query.id;
        delete params.query.id;
      }
      // filter destroyed item by default
      if (!params.query.destroyedAt) {
        params.query.destroyedAt = null;
      }
      // default sort
      if (!params.query.$sort) {
        params.query.$sort = { createdAt: -1 };
      }
    }

    // allow extra params to be used only in after hook
    if (params.query && params.query.$after) {
      params.after = params.query.$after;
      delete params.query.$after;
    }

    // search by regex
    Object.keys(params.query || []).forEach(field => {
      if (params.query[field] && params.query[field].$like !== undefined && field.indexOf('$') === -1) {
        params.query[field] = { $regex: new RegExp(params.query[field].$like), $options: 'i' };
      }
    });

    const action = params.__action;

    if (!action || action === 'find') {
      debug('service %s find %j', this.name, params.query);
      return super.find(params).then(transform);
    }

    // TODO secure action call by find
    if (this[action]) {
      delete params.__action;
      return this._action(action, null, {}, params);
    }
    throw new Error("No such **get** action: " + action);
  }

  get(id, params) {
    if (id === 'null' || id === '0') id = null;
    params = params || { query: {} };

    let action = params.__action;

    // if id is null, try find the first one with params
    if (id === null && !action) action = 'first';

    if (!action || action === 'get') {
      debug('service %s get %j', this.name, id, params);
      return super.get(id, params).then(transform);
    }

    // TODO secure action call by get
    if (this[action]) {
      delete params.__action;
      return this._action(action, id, {}, params);
    }
    throw new Error("No such **get** action: " + action);
  }

  create(data, params) {
    params = params || { query: {} };
    // add support to create multiple objects
    if (Array.isArray(data)) {
      return Promise.all(data.map(current => this.create(current, params)));
    }
    return super.create(data, params).then(transform);
  }

  update(id, data, params) {
    if (id === 'null') id = null;
    params = params || {};
    assertMultiple(id, params, "Found null id, update must be called with $multi.");

    const action = params.__action;
    if (!action || action === 'update') {
      debug('service %s update %j', this.name, id, data, typeof data.parent);
      return super.update(id, data, params).then(transform);
    }

    if (this[action]) {
      delete params.__action;
      return this._action(action, id, data, params);
    } else {
      throw new Error("No such **put** action: " + action);
    }
  }

  patch(id, data, params) {
    if (id === 'null') id = null;
    params = params || {};
    assertMultiple(id, params, "Found null id, patch must be called with $multi.");

    const action = params.__action;
    if (!action || action === 'patch') {
      return super.patch(id, data, params).then(transform);
    }
    if (this[action]) {
      delete params.__action;
      debug('service %s patch %j', this.name, id);
      return this._action(action, id, data, params);
    } else {
      throw new Error("No such **patch** action: " + action);
    }
  }

  remove(id, params) {
    if (id === 'null') id = null;
    assertMultiple(id, params, "Found null id, remove must be called with $multi.");

    const action = params.__action;
    if (!action || action === 'remove') {
      if (params.query.$soft) {
        debug('service %s remove soft %j', this.name, id);
        delete params.query.$soft;
        return super.patch(id, { destroyedAt: new Date() }, params).then(transform);
      } else {
        debug('service %s remove %j', this.name, id);
        return super.remove(id, params).then(transform);
      }
    }

    if (action === 'restore') {
      delete params.__action;
      return this.restore(id, params);
    } else {
      throw new Error("No such **remove** action: " + action);
    }
  }

  _action(action, id, data, params) {
    debug(' => %s action %s with %j', this.name, action, id, data);
    // delete params.provider;
    let query = id? this.get(id, params) : Promise.resolve(null);
    return query.then(origin => {
      if (origin && origin.data) {
        origin = origin.data;
      }
      if (id && !origin) {
        throw new Error('Not found record ' + id + ' in ' + this.Model.modelName);
      }
      return this[action].call(this, id, data, params, origin);
    });
  }

  // some reserved actions

  upsert(data, params) {
    params = params || {};
    let query = params.query || data;  // default find by input data
    return this.Model.findOneAndUpdate(query,
        Object.assign({}, data), { upsert: true, new: true })
      .lean()
      .then(transform)
      .catch(errorHandler);
  }

  count(id, data, params) {
    params = params || id || { query: {} };
    params.query.$limit = 0;
    return super.find(params).then(result => result.total);
  }

  first(id, data, params) {
    params = params || id || { query: {} };
    params.query.$limit = 1;
    return this.find(params).then(results => {
      results = results.data || results;
      if (Array.isArray(results) && results.length > 0) {
        return results[0];
      } else {
        return results;
      }
    });
  }

  last(id, data, params) {
    params = params || id || { query: {} };
    return this.count(id, data, params).then(total => {
      params.query.$limit = 1;
      params.query.$skip = total - 1;
      return this.find(params).then(results => {
        results = results.data || results;
        if (Array.isArray(results) && results.length > 0) {
          return results[0];
        } else {
          return results;
        }
      });
    });
  }

  restore(id, data, params) {
    return super.patch(id, { destroyedAt: null }, params).then(transform);
  }
}

export default function init (options) {
  return new Service(options);
}

init.Service = Service;
init.transform = transform;
<commit_msg>Make params immutable<commit_after>import fp from 'lodash/fp';
import makeDebug from 'debug';
import { Service as BaseService } from 'feathers-mongoose';
import { errorHandler } from 'feathers-mongoose/lib/error-handler';

const debug = makeDebug('mostly:feathers-mongoose:service');

const defaultOptions = {
  lean: true,
  paginate: {
    default: 10,
    max: 50
  }
};

// prevent accidental multiple operations
const assertMultiple = function(id, params, message) {
  if (!id) {
    if (params && params.query && (params.$multi || params.query.$multi)) {
      delete params.query.$multi;
    } else {
      throw new Error(message);
    }
  }
};

// transform the results
const transform = function(results) {
  let data = [].concat(results? results.data || results : []);
  data.forEach(item => {
    // item = Object.assign({}, item);
    // output id string instead of _id
    item.id = (item._id || item.id).toString();
    delete item._id;
    delete item.__v;
    // debug('transform item %j', item);
  });
  return results;
};

const unsetOptions = fp.flow(
  fp.unset('Model'),
  fp.unset('ModelName')
);

export class Service extends BaseService {
  constructor(options) {
    options = Object.assign({}, defaultOptions, options);
    super(options);

    this.options = unsetOptions(options);
    this.name = options.name || 'mongoose-service';
  }

  setup(app) {
    this.app = app;
  }

  find(params) {
    params = params || { query: {} };
    // default behaviours for external call
    if (params.provider && params.query) {
      // fix id query as _ids
      if (params.query.id) {
        params.query._id = params.query.id;
        delete params.query.id;
      }
      // filter destroyed item by default
      if (!params.query.destroyedAt) {
        params.query.destroyedAt = null;
      }
      // default sort
      if (!params.query.$sort) {
        params.query.$sort = { createdAt: -1 };
      }
    }

    // search by regex
    Object.keys(params.query || []).forEach(field => {
      if (params.query[field] && params.query[field].$like !== undefined && field.indexOf('$') === -1) {
        params.query[field] = { $regex: new RegExp(params.query[field].$like), $options: 'i' };
      }
    });

    const action = params.__action;

    if (!action || action === 'find') {
      debug('service %s find %j', this.name, params.query);
      return super.find(params).then(transform);
    }

    // TODO secure action call by find
    if (this[action]) {
      params = fp.unset('__action', params);
      return this._action(action, null, {}, params);
    }
    throw new Error("No such **get** action: " + action);
  }

  get(id, params) {
    if (id === 'null' || id === '0') id = null;
    params = params || { query: {} };

    let action = params.__action;

    // if id is null, try find the first one with params
    if (id === null && !action) action = 'first';

    if (!action || action === 'get') {
      debug('service %s get %j', this.name, id, params);
      return super.get(id, params).then(transform);
    }

    // TODO secure action call by get
    if (this[action]) {
      params = fp.unset('__action', params);
      return this._action(action, id, {}, params);
    }
    throw new Error("No such **get** action: " + action);
  }

  create(data, params) {
    params = params || { query: {} };
    // add support to create multiple objects
    if (Array.isArray(data)) {
      return Promise.all(data.map(current => this.create(current, params)));
    }
    return super.create(data, params).then(transform);
  }

  update(id, data, params) {
    if (id === 'null') id = null;
    params = params || {};
    assertMultiple(id, params, "Found null id, update must be called with $multi.");

    const action = params.__action;
    if (!action || action === 'update') {
      debug('service %s update %j', this.name, id, data, typeof data.parent);
      return super.update(id, data, params).then(transform);
    }

    if (this[action]) {
      params = fp.unset('__action', params);
      return this._action(action, id, data, params);
    } else {
      throw new Error("No such **put** action: " + action);
    }
  }

  patch(id, data, params) {
    if (id === 'null') id = null;
    params = params || {};
    assertMultiple(id, params, "Found null id, patch must be called with $multi.");

    const action = params.__action;
    if (!action || action === 'patch') {
      return super.patch(id, data, params).then(transform);
    }
    if (this[action]) {
      debug('service %s patch %j', this.name, id);
      params = fp.unset('__action', params);
      return this._action(action, id, data, params);
    } else {
      throw new Error("No such **patch** action: " + action);
    }
  }

  remove(id, params) {
    if (id === 'null') id = null;
    assertMultiple(id, params, "Found null id, remove must be called with $multi.");

    const action = params.__action;
    if (!action || action === 'remove') {
      if (params.query.$soft) {
        debug('service %s remove soft %j', this.name, id);
        params = fp.unset('query.$soft', params);
        return super.patch(id, { destroyedAt: new Date() }, params).then(transform);
      } else {
        debug('service %s remove %j', this.name, id);
        return super.remove(id, params).then(transform);
      }
    }

    if (action === 'restore') {
      params = fp.unset('query.$soft')(params);
      return this.restore(id, params);
    } else {
      throw new Error("No such **remove** action: " + action);
    }
  }

  _action(action, id, data, params) {
    debug(' => %s action %s with %j', this.name, action, id, data);
    // delete params.provider;
    let query = id? this.get(id, params) : Promise.resolve(null);
    return query.then(origin => {
      if (origin && origin.data) {
        origin = origin.data;
      }
      if (id && !origin) {
        throw new Error('Not found record ' + id + ' in ' + this.Model.modelName);
      }
      return this[action].call(this, id, data, params, origin);
    });
  }

  // some reserved actions

  upsert(data, params) {
    params = params || {};
    let query = params.query || data;  // default find by input data
    return this.Model.findOneAndUpdate(query,
        Object.assign({}, data), { upsert: true, new: true })
      .lean()
      .then(transform)
      .catch(errorHandler);
  }

  count(id, data, params) {
    params = params || id || { query: {} };
    params.query.$limit = 0;
    return super.find(params).then(result => result.total);
  }

  first(id, data, params) {
    params = params || id || { query: {} };
    params.query.$limit = 1;
    return this.find(params).then(results => {
      results = results.data || results;
      if (Array.isArray(results) && results.length > 0) {
        return results[0];
      } else {
        return results;
      }
    });
  }

  last(id, data, params) {
    params = params || id || { query: {} };
    return this.count(id, data, params).then(total => {
      params.query.$limit = 1;
      params.query.$skip = total - 1;
      return this.find(params).then(results => {
        results = results.data || results;
        if (Array.isArray(results) && results.length > 0) {
          return results[0];
        } else {
          return results;
        }
      });
    });
  }

  restore(id, data, params) {
    return super.patch(id, { destroyedAt: null }, params).then(transform);
  }
}

export default function init (options) {
  return new Service(options);
}

init.Service = Service;
init.transform = transform;
<|endoftext|>


<commit_before>define(["Test", "Tone/core/Clock", "helper/Offline"],
	function (Test, Clock, Offline) {

	describe("Clock", function(){

		it ("can be created and disposed", function(){
			var clock = new Clock();
			clock.dispose();
			Test.wasDisposed(clock);
		});

		context("Get/Set values", function(){

			it ("can get and set the frequency", function(){
				var clock = new Clock(function(){}, 2);
				expect(clock.frequency.value).to.equal(2);
				clock.frequency.value = 0.2;
				expect(clock.frequency.value).to.be.closeTo(0.2, 0.001);
				clock.dispose();
			});

			it ("invokes the callback when started", function(done){
				var clock = new Clock(function(){
					clock.dispose();
					done();
				}, 10).start();
			});

			it ("can be constructed with an options object", function(done){
				var clock = new Clock({
					"callback" : function(){
						clock.dispose();
						done();
					},
					"frequency" : 8
				}).start();
				expect(clock.frequency.value).to.equal(8);
			});

			it ("can get and set it's values with the set/get", function(){
				var clock = new Clock();
				clock.set({
					"frequency" : 2
				});
				var gotValues = clock.get();
				expect(gotValues.frequency).to.equal(2);
				clock.dispose();
			});
		});

		context("State", function(){

			it ("correctly returns the scheduled play state", function(){
				return Offline(function(){
					var clock = new Clock();
					expect(clock.state).to.equal("stopped");
					clock.start(0).stop(0.2);
					expect(clock.state).to.equal("started");

					return function(sample, time){
						Test.whenBetween(time, 0, 0.2, function(){
							expect(clock.state).to.equal("started");
						});

						Test.whenBetween(time, 0.2, Infinity, function(){
							expect(clock.state).to.equal("stopped");
						});
					};
				}, 0.3);
			});

			it("can start, pause, and stop", function(){
				return Offline(function(){
					var clock = new Clock();
					expect(clock.state).to.equal("stopped");
					clock.start(0).pause(0.2).stop(0.4);
					expect(clock.state).to.equal("started");

					return function(sample, time){
						Test.whenBetween(time, 0, 0.2, function(){
							expect(clock.state).to.equal("started");
						});

						Test.whenBetween(time, 0.2, 0.4, function(){
							expect(clock.state).to.equal("paused");
						});

						Test.whenBetween(time, 0.4, Infinity, function(){
							expect(clock.state).to.equal("stopped");
						});
					};

				}, 0.5);
			});

			it("can schedule multiple start and stops", function(){
				return Offline(function(){
					var clock = new Clock();
					expect(clock.state).to.equal("stopped");
					clock.start(0).pause(0.1).stop(0.2).start(0.3).stop(0.4);
					expect(clock.state).to.equal("started");

					return function(sample, time){
						Test.whenBetween(time, 0.1, 0.2, function(){
							expect(clock.state).to.equal("paused");
						});
						Test.whenBetween(time, 0.2, 0.3, function(){
							expect(clock.state).to.equal("stopped");
						});
						Test.whenBetween(time, 0.3, 0.4, function(){
							expect(clock.state).to.equal("started");
						});
					};
				}, 0.5);
			});
		});

		context("Scheduling", function(){

			it ("passes a time to the callback", function(done){
				var clock = new Clock(function(time){
					expect(time).to.be.a.number;
					clock.dispose();
					done();
				}, 10).start();
			});

			it ("invokes the callback with a time great than now", function(done){
				var clock = new Clock(function(time){
					clock.dispose();
					expect(time).to.be.greaterThan(now);
					done();
				}, 10);
				var now = clock.now();
				var startTime = now + 0.1;
				clock.start(startTime);
			});

			it ("invokes the first callback at the given start time", function(done){
				var clock = new Clock(function(time){
					clock.dispose();
					expect(time).to.equal(startTime);
					done();
				}, 10);
				var startTime = clock.now() + 0.1;
				clock.start(startTime);
			});

			it ("can be scheduled to stop in the future", function(){
				var invokations = 0;
				return Offline(function(){
					new Clock(function(){
						invokations++;
					}, 0.5).start(0);
				}, 0.6).then(function(){
					expect(invokations).to.equal(1);
				});
			});

			it ("invokes the right number of callbacks given the duration", function(){
				var invokations = 0;
				return Offline(function(){
					new Clock(function(){
						invokations++;
					}, 10).start(0).stop(0.49);
				}, 0.6).then(function(){
					expect(invokations).to.equal(5);
				});
			});

			it ("can schedule the frequency of the clock", function(){
				var invokations = 0;
				return Offline(function(){
					var clock = new Clock(function(){
						invokations++;
					}, 2);
					clock.start(0).stop(1.1);
					clock.frequency.setValueAtTime(4, 0.5);
				}, 2).then(function(){
					expect(invokations).to.equal(4);
				});
			});
		});

		context("Ticks", function(){

			it ("has 0 ticks when first created", function(){
				var clock = new Clock();
				expect(clock.ticks).to.equal(0);
				clock.dispose();
			});

			it ("increments 1 tick per callback", function(){
				var ticks = 0;
				var clock;
				return Offline(function(){
					clock = new Clock(function(){
						ticks++;
					}, 0.05).start();
				}, 0.6).then(function(){
					expect(ticks).to.equal(clock.ticks);
				});
			});

			it ("resets ticks on stop", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20).start(0).stop(0.1);
					return function(time){
						Test.whenBetween(time, 0, 0.09, function(){
							expect(clock.ticks).to.be.greaterThan(0);
						});
						Test.whenBetween(time, 0.1, Infinity, function(){
							expect(clock.ticks).to.equal(0);
						});
					};
				}, 0.2);
			});

			it ("does not reset ticks on pause but stops incrementing", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20).start(0).pause(0.1);
					var pausedTicks = 0;
					return function(time){
						Test.whenBetween(time, 0, 0.1, function(){
							expect(clock.ticks).to.be.greaterThan(0);
							pausedTicks = clock.ticks;
						});
						Test.whenBetween(time, 0.1, Infinity, function(){
							expect(clock.ticks).to.equal(pausedTicks);
						});
					};
				}, 0.2);
			});

			it ("starts incrementing where it left off after pause", function(){

				return Offline(function(){
					var clock = new Clock(function(){}, 20).start(0).pause(0.1).start(0.2);

					var pausedTicks = 0;
					var tested = false;
					return function(time){
						Test.whenBetween(time, 0, 0.1, function(){
							expect(clock.ticks).to.be.greaterThan(0);
							pausedTicks = clock.ticks;
						});
						Test.whenBetween(time, 0.1, 0.19, function(){
							expect(clock.ticks).to.equal(pausedTicks);
						});
						Test.whenBetween(time, 0.2, Infinity, function(){
							if (!tested){
								tested = true;
								expect(clock.ticks).to.equal(pausedTicks + 1);
							}
						});
					};
				}, 0.3);
			});

			it ("can start with a tick offset", function(){
				return Offline(function(){
					var tested = false;
					var clock = new Clock(function(){
						if (!tested){
							tested = true;
							expect(clock.ticks).to.equal(4);
						}
					}, 10);
					expect(clock.ticks).to.equal(0);
					clock.start(0, 4);
				});
			});
		});

		context("Events", function(){

			it ("triggers the start event on start", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20);
					var startTime = 0.3;
					clock.on("start", function(time, offset){
						expect(time).to.be.closeTo(startTime, 0.05);
						expect(offset).to.equal(0);
					});
					clock.start(startTime);
				}, 0.4);
			});

			it ("triggers the start event with an offset", function(done){
				return Offline(function(){
					var clock = new Clock(function(){}, 20);
					var startTime = 0.3;
					clock.on("start", function(time, offset){
						expect(time).to.be.closeTo(startTime, 0.05);
						expect(offset).to.equal(2);
						clock.dispose();
						done();
					});
					clock.start(startTime, 2);
				}, 0.4);
			});

			it ("triggers stop event", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20);
					var stopTime = 0.3;
					clock.on("stop", function(time){
						expect(time).to.be.closeTo(stopTime, 0.05);
					});
					clock.start().stop(stopTime);
				});
			});

			it ("triggers pause stop event", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20);
					clock.on("pause", function(time){
						expect(time).to.be.closeTo(0.1, 0.05);
					}).on("stop", function(time){
						expect(time).to.be.closeTo(0.2, 0.05);
					});
					clock.start().pause(0.1).stop(0.2);
				});
			});
		});

	});
});<commit_msg>testing callback error throwing<commit_after>define(["Test", "Tone/core/Clock", "helper/Offline"],
	function (Test, Clock, Offline) {

	describe("Clock", function(){

		it ("can be created and disposed", function(){
			var clock = new Clock();
			clock.dispose();
			Test.wasDisposed(clock);
		});

		context("Get/Set values", function(){

			it ("can get and set the frequency", function(){
				var clock = new Clock(function(){}, 2);
				expect(clock.frequency.value).to.equal(2);
				clock.frequency.value = 0.2;
				expect(clock.frequency.value).to.be.closeTo(0.2, 0.001);
				clock.dispose();
			});

			it ("invokes the callback when started", function(done){
				var clock = new Clock(function(){
					clock.dispose();
					done();
				}, 10).start();
			});

			it ("can be constructed with an options object", function(done){
				var clock = new Clock({
					"callback" : function(){
						clock.dispose();
						done();
					},
					"frequency" : 8
				}).start();
				expect(clock.frequency.value).to.equal(8);
			});

			it ("can get and set it's values with the set/get", function(){
				var clock = new Clock();
				clock.set({
					"frequency" : 2
				});
				var gotValues = clock.get();
				expect(gotValues.frequency).to.equal(2);
				clock.dispose();
			});
		});

		context("State", function(){

			it ("correctly returns the scheduled play state", function(){
				return Offline(function(){
					var clock = new Clock();
					expect(clock.state).to.equal("stopped");
					clock.start(0).stop(0.2);
					expect(clock.state).to.equal("started");

					return function(sample, time){
						Test.whenBetween(time, 0, 0.2, function(){
							expect(clock.state).to.equal("started");
						});

						Test.whenBetween(time, 0.2, Infinity, function(){
							expect(clock.state).to.equal("stopped");
						});
					};
				}, 0.3);
			});

			it("can start, pause, and stop", function(){
				return Offline(function(){
					var clock = new Clock();
					expect(clock.state).to.equal("stopped");
					clock.start(0).pause(0.2).stop(0.4);
					expect(clock.state).to.equal("started");

					return function(sample, time){
						Test.whenBetween(time, 0, 0.2, function(){
							expect(clock.state).to.equal("started");
						});

						Test.whenBetween(time, 0.2, 0.4, function(){
							expect(clock.state).to.equal("paused");
						});

						Test.whenBetween(time, 0.4, Infinity, function(){
							expect(clock.state).to.equal("stopped");
						});
					};

				}, 0.5);
			});

			it("can schedule multiple start and stops", function(){
				return Offline(function(){
					var clock = new Clock();
					expect(clock.state).to.equal("stopped");
					clock.start(0).pause(0.1).stop(0.2).start(0.3).stop(0.4);
					expect(clock.state).to.equal("started");

					return function(sample, time){
						Test.whenBetween(time, 0.1, 0.2, function(){
							expect(clock.state).to.equal("paused");
						});
						Test.whenBetween(time, 0.2, 0.3, function(){
							expect(clock.state).to.equal("stopped");
						});
						Test.whenBetween(time, 0.3, 0.4, function(){
							expect(clock.state).to.equal("started");
						});
					};
				}, 0.5);
			});
		});

		context("Scheduling", function(){

			it ("passes a time to the callback", function(done){
				var clock = new Clock(function(time){
					expect(time).to.be.a.number;
					clock.dispose();
					done();
				}, 10).start();
			});

			it ("invokes the callback with a time great than now", function(done){
				var clock = new Clock(function(time){
					clock.dispose();
					expect(time).to.be.greaterThan(now);
					done();
				}, 10);
				var now = clock.now();
				var startTime = now + 0.1;
				clock.start(startTime);
			});

			it ("invokes the first callback at the given start time", function(done){
				var clock = new Clock(function(time){
					clock.dispose();
					expect(time).to.equal(startTime);
					done();
				}, 10);
				var startTime = clock.now() + 0.1;
				clock.start(startTime);
			});

			it ("can be scheduled to stop in the future", function(){
				var invokations = 0;
				return Offline(function(){
					new Clock(function(){
						invokations++;
					}, 0.5).start(0);
				}, 0.6).then(function(){
					expect(invokations).to.equal(1);
				});
			});

			it ("invokes the right number of callbacks given the duration", function(){
				var invokations = 0;
				return Offline(function(){
					new Clock(function(){
						invokations++;
					}, 10).start(0).stop(0.49);
				}, 0.6).then(function(){
					expect(invokations).to.equal(5);
				});
			});

			it ("can schedule the frequency of the clock", function(){
				var invokations = 0;
				return Offline(function(){
					var clock = new Clock(function(){
						invokations++;
					}, 2);
					clock.start(0).stop(1.1);
					clock.frequency.setValueAtTime(4, 0.5);
				}, 2).then(function(){
					expect(invokations).to.equal(4);
				});
			});
		});

		context("Ticks", function(){

			it ("has 0 ticks when first created", function(){
				var clock = new Clock();
				expect(clock.ticks).to.equal(0);
				clock.dispose();
			});

			it ("increments 1 tick per callback", function(){
				var ticks = 0;
				var clock;
				return Offline(function(){
					clock = new Clock(function(){
						ticks++;
					}, 0.05).start();
				}, 0.6).then(function(){
					expect(ticks).to.equal(clock.ticks);
				});
			});

			it ("resets ticks on stop", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20).start(0).stop(0.1);
					return function(time){
						Test.whenBetween(time, 0, 0.09, function(){
							expect(clock.ticks).to.be.greaterThan(0);
						});
						Test.whenBetween(time, 0.1, Infinity, function(){
							expect(clock.ticks).to.equal(0);
						});
					};
				}, 0.2);
			});

			it ("does not reset ticks on pause but stops incrementing", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20).start(0).pause(0.1);
					var pausedTicks = 0;
					return function(time){
						Test.whenBetween(time, 0, 0.1, function(){
							expect(clock.ticks).to.be.greaterThan(0);
							pausedTicks = clock.ticks;
						});
						Test.whenBetween(time, 0.1, Infinity, function(){
							expect(clock.ticks).to.equal(pausedTicks);
						});
					};
				}, 0.2);
			});

			it ("starts incrementing where it left off after pause", function(){

				return Offline(function(){
					var clock = new Clock(function(){}, 20).start(0).pause(0.1).start(0.2);

					var pausedTicks = 0;
					var tested = false;
					return function(time){
						Test.whenBetween(time, 0, 0.1, function(){
							expect(clock.ticks).to.be.greaterThan(0);
							pausedTicks = clock.ticks;
						});
						Test.whenBetween(time, 0.1, 0.19, function(){
							expect(clock.ticks).to.equal(pausedTicks);
						});
						Test.whenBetween(time, 0.2, Infinity, function(){
							if (!tested){
								tested = true;
								expect(clock.ticks).to.equal(pausedTicks + 1);
							}
						});
					};
				}, 0.3);
			});

			it ("can start with a tick offset", function(){
				return Offline(function(){
					var tested = false;
					var clock = new Clock(function(){
						if (!tested){
							tested = true;
							expect(clock.ticks).to.equal(4);
						}
					}, 10);
					expect(clock.ticks).to.equal(0);
					clock.start(0, 4);
				});
			});

			it ("recovers even when an error is thrown in the callback", function(done){
				try {
					Offline(function(){
						var clock = new Clock(function(time){
							throw new Error("error!");
						}, 10).start();
					}, 0.21);
				} catch(e){
					done();
				}
			});
		});

		context("Events", function(){

			it ("triggers the start event on start", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20);
					var startTime = 0.3;
					clock.on("start", function(time, offset){
						expect(time).to.be.closeTo(startTime, 0.05);
						expect(offset).to.equal(0);
					});
					clock.start(startTime);
				}, 0.4);
			});

			it ("triggers the start event with an offset", function(done){
				return Offline(function(){
					var clock = new Clock(function(){}, 20);
					var startTime = 0.3;
					clock.on("start", function(time, offset){
						expect(time).to.be.closeTo(startTime, 0.05);
						expect(offset).to.equal(2);
						clock.dispose();
						done();
					});
					clock.start(startTime, 2);
				}, 0.4);
			});

			it ("triggers stop event", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20);
					var stopTime = 0.3;
					clock.on("stop", function(time){
						expect(time).to.be.closeTo(stopTime, 0.05);
					});
					clock.start().stop(stopTime);
				});
			});

			it ("triggers pause stop event", function(){
				return Offline(function(){
					var clock = new Clock(function(){}, 20);
					clock.on("pause", function(time){
						expect(time).to.be.closeTo(0.1, 0.05);
					}).on("stop", function(time){
						expect(time).to.be.closeTo(0.2, 0.05);
					});
					clock.start().pause(0.1).stop(0.2);
				});
			});
		});

	});
});<|endoftext|>


<commit_before>import test from 'ava';
import DataStore from '../lib/data-store';
import sinon from 'sinon';

let clock;

test.before(() => {
    clock = sinon.useFakeTimers();
    clock.tick(10000);
});
test.after(() => {
    clock.restore();
});

test('constructor', (t) => {
    const CACHE_TIME = 3000;
    const fetcher = sinon.spy();
    const ds = new DataStore(fetcher, CACHE_TIME);

    t.is(ds.cacheTime, CACHE_TIME);
    t.false(fetcher.called);
    t.true(ds.lastUpdate < Date.now() - CACHE_TIME);
    t.is(ds.fetch, fetcher);
});

test('cache expired without any fetched data', (t) => {
    const fetcher = sinon.spy();
    const ds = new DataStore(fetcher);

    t.true(ds.cacheExpired);
});

test('get data without cache', async (t) => {
    const DATA = 'lorem ipsum';
    const fetcher = sinon.spy(() => Promise.resolve(DATA));

    const ds = new DataStore(fetcher);

    const p = await ds.getData();
    t.true(fetcher.calledOnce);
    t.is(fetcher.lastCall.args[0], undefined);
    t.is(p, DATA);
});

// These tests are serial since they rely on clock behaviour for cache invalidation.
test.serial('get data from cache', async (t) => {
    const DATA = 'lorem ipsum';
    const fetcher = sinon.spy(() => Promise.resolve(DATA));

    const ds = new DataStore(fetcher);

    const p = await ds.getData();
    t.true(fetcher.calledOnce);
    t.is(p, DATA);

    const q = await ds.getData();
    t.true(fetcher.calledOnce);
    t.is(q, DATA);
});

test.serial('get data from expired cache', async (t) => {
    const DATA = 'lorem ipsum';
    const CACHE_TIME = 3000;
    const fetcher = sinon.spy(() => Promise.resolve(DATA));

    const ds = new DataStore(fetcher, CACHE_TIME);

    const p = await ds.getData();
    t.true(fetcher.calledOnce);
    t.is(p, DATA);

    clock.tick(CACHE_TIME + 1);

    const q = await ds.getData();
    t.true(fetcher.calledTwice);
    t.is(fetcher.lastCall.args[0], DATA);
    t.is(q, DATA);
});

test.serial('cache expired due to time', async (t) => {
    const CACHE_TIME = 3000;
    const fetcher = sinon.spy(() => Promise.resolve());
    const ds = new DataStore(fetcher, CACHE_TIME);

    await ds.getData();

    clock.tick(CACHE_TIME + 1);

    t.true(ds.cacheExpired);
});

test.serial('cache expired false', async (t) => {
    const fetcher = sinon.spy(() => Promise.resolve());
    const ds = new DataStore(fetcher);

    await ds.getData();

    t.false(ds.cacheExpired);
});

test('fetch callback only gets called once while loading data', async (t) => {
    let res;
    const fetcher = sinon.spy(() => {
        return new Promise((resolve) => {
            res = resolve;
        });
    });

    const ds = new DataStore(fetcher);

    const p = ds.getData();
    t.true(fetcher.calledOnce);
    t.is(typeof p.then, 'function');

    const q = ds.getData();
    t.true(fetcher.calledOnce);
    t.is(typeof q.then, 'function');

    res();
    await Promise.all([ p, q ]);

    t.true(fetcher.calledOnce);
});
<commit_msg>tests: Test rejecting datastore fetcher<commit_after>import test from 'ava';
import DataStore from '../lib/data-store';
import sinon from 'sinon';

let clock;

test.before(() => {
    clock = sinon.useFakeTimers();
    clock.tick(10000);
});
test.after(() => {
    clock.restore();
});

test('constructor', (t) => {
    const CACHE_TIME = 3000;
    const fetcher = sinon.spy();
    const ds = new DataStore(fetcher, CACHE_TIME);

    t.is(ds.cacheTime, CACHE_TIME);
    t.false(fetcher.called);
    t.true(ds.lastUpdate < Date.now() - CACHE_TIME);
    t.is(ds.fetch, fetcher);
});

test('cache expired without any fetched data', (t) => {
    const fetcher = sinon.spy();
    const ds = new DataStore(fetcher);

    t.true(ds.cacheExpired);
});

test('get data without cache', async (t) => {
    const DATA = 'lorem ipsum';
    const fetcher = sinon.spy(() => Promise.resolve(DATA));

    const ds = new DataStore(fetcher);

    const p = await ds.getData();
    t.true(fetcher.calledOnce);
    t.is(fetcher.lastCall.args[0], undefined);
    t.is(p, DATA);
});

// These tests are serial since they rely on clock behaviour for cache invalidation.
test.serial('get data from cache', async (t) => {
    const DATA = 'lorem ipsum';
    const fetcher = sinon.spy(() => Promise.resolve(DATA));

    const ds = new DataStore(fetcher);

    const p = await ds.getData();
    t.true(fetcher.calledOnce);
    t.is(p, DATA);

    const q = await ds.getData();
    t.true(fetcher.calledOnce);
    t.is(q, DATA);
});

test.serial('get data from expired cache', async (t) => {
    const DATA = 'lorem ipsum';
    const CACHE_TIME = 3000;
    const fetcher = sinon.spy(() => Promise.resolve(DATA));

    const ds = new DataStore(fetcher, CACHE_TIME);

    const p = await ds.getData();
    t.true(fetcher.calledOnce);
    t.is(p, DATA);

    clock.tick(CACHE_TIME + 1);

    const q = await ds.getData();
    t.true(fetcher.calledTwice);
    t.is(fetcher.lastCall.args[0], DATA);
    t.is(q, DATA);
});

test.serial('cache expired due to time', async (t) => {
    const CACHE_TIME = 3000;
    const fetcher = sinon.spy(() => Promise.resolve());
    const ds = new DataStore(fetcher, CACHE_TIME);

    await ds.getData();

    clock.tick(CACHE_TIME + 1);

    t.true(ds.cacheExpired);
});

test.serial('cache expired false', async (t) => {
    const fetcher = sinon.spy(() => Promise.resolve());
    const ds = new DataStore(fetcher);

    await ds.getData();

    t.false(ds.cacheExpired);
});

test('fetch callback only gets called once while loading data', async (t) => {
    let res;
    const fetcher = sinon.spy(() => {
        return new Promise((resolve) => {
            res = resolve;
        });
    });

    const ds = new DataStore(fetcher);

    const p = ds.getData();
    t.true(fetcher.calledOnce);
    t.is(typeof p.then, 'function');

    const q = ds.getData();
    t.true(fetcher.calledOnce);
    t.is(typeof q.then, 'function');

    res();
    await Promise.all([ p, q ]);

    t.true(fetcher.calledOnce);
});

test('Throwing fetcher aborts current loading', async (t) => {
    const fetcher = sinon.stub();
    fetcher.rejects();

    const ds = new DataStore(fetcher);

    await t.throws(ds.getData());
    t.true(fetcher.calledOnce);

    fetcher.resolves();

    await t.notThrows(ds.getData());
    t.true(fetcher.calledTwice);
});
<|endoftext|>