<commit_before>'use strict';

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

var port = 3000;

/** Layer 0 */
describe('routes', function() {

    before('starts server', function(done) {
        server.listen(port, done);
    });

    /** Layer 1 */
    describe('Message sending route', function() {

        it('client2 receives client1s msg', function(done) {
            server.workingUrl(done);
        });

        it('client1 receives MSG_ACK', function(done) {
            server.workingUrl(done);
        });

    }); // end `Message route` describe

    // describe('Delivery ACK route', function() {

    //     it('client1 receives DLVRY_ACK', function(done) {
    //         server.workingUrl(done);
    //     });

    // });

    // describe('Read ACK route', function() {

    //     it('client1 receives READ_ACK', function(done) {
    //         server.workingUrl(done);
    //     });

    // });

    // describe('Registered Contacts routes', function() {

    //     it('receives registered contacts', function(done) {
    //         server.workingUrl(done);
    //     });

    //     it('should store unregistered users', function(done) {
    //         server.workingUrl(done);
    //     });

    // });

    // describe('Forwards typing', function() {

    //     it('receives typing message', function(done) {
    //         server.workingUrl(done);
    //     });

    // });

    // describe('Profile changes', function() {

    //     it('updates name', function(done) {
    //         server.workingUrl(done);
    //     });

    //     it('updates dp', function(done) {
    //         server.workingUrl(done);
    //     });

    //     it('updates status', function(done) {
    //         server.workingUrl(done);
    //     });

    // });

    // describe('Online notification', function() {

    //     it('receives online message', function(done) {
    //         server.workingUrl(done);
    //     });

    // });

    after('close server', function() {
        server.close();
    });
});<commit_msg>clean up<commit_after>'use strict';

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

var port = 3000;

/** Layer 0 */
describe('routes', function() {

    before('starts server', function(done) {
        server.listen(port, done);
    });

    /** Layer 1 */
    describe('Message sending route', function() {

        it('client2 receives client1s msg', function(done) {
            server.workingUrl(done);
        });

        it('client1 receives MSG_ACK', function(done) {
            server.workingUrl(done);
        });

    }); // end `Message route` describe

    after('close server', function() {
        server.close();
    });
});<|endoftext|>


<commit_before>"use strict";

var assert     = require("assert"),
    util       = require("util"),
    simpleload = require("../index.js");

// mocha could be used
// the tests are really simple so let's not add any dependencies yet
// simpleload should be synchronous, as it is used for loading simple
// dependencies or modules at start

var startDate, endDate;

startDate = new Date();
util.log("Starting the tests.");

// use simpleload to load the specs
var loaded = simpleload(__dirname + "/specs", { suffix: "spec.js", as: "values" });
assert(loaded.length === 7);

endDate = new Date();
util.log("All tests passed, no failures. They took " + (endDate - startDate) + " ms to run.");<commit_msg>specs<commit_after>"use strict";

var assert     = require("assert"),
    util       = require("util"),
    simpleload = require("../index.js");

// mocha could be used
// the tests are really simple so let's not add any dependencies yet
// simpleload should be synchronous, as it is used for loading simple
// dependencies or modules at start

var startDate, endDate;

startDate = new Date();
util.log("Starting the tests.");

// use simpleload to load the specs
var specs = simpleload(__dirname + "/specs", { suffix: "spec.js", as: "values" });
assert(specs.length === 7);

endDate = new Date();
util.log("All tests passed, no failures. They took " + (endDate - startDate) + " ms to run.");<|endoftext|>


<commit_before>var should = require('should');
var fs = require('fs');
var URL = require('url');
var express = require('express');
var got = require('got');

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

describe("Sharpie middleware", function suite() {
	var app, server, port;
	before(function() {
		app = express();
		server = app.listen();
		port = server.address().port;
	});
	after(function() {
		if (server) server.close();
	});

	it("should pass through images with unsupported format", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image.ico').then(function(res) {
			should(res.statusCode).equal(200);
		});
	});

	it("should pass through unparsable svg", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/wrong.svg').then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql('<svg ="100" y="50"');
		});
	});

	it("should resize a jpeg image", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image.jpg?rs=w:50&q=75').then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body.length == 636);
			should(res.headers['content-type']).equal('image/jpeg');
		});
	});

	it("should not allow blacklisted domain", function() {
		app.get('/', sharpie({
			hostnames: function(hostname) {
				if (hostname == 'www.gravatar.com') return true;
				else return false;
			}
		}));

		return got('http://localhost:' + port, {query: {
			url: 'http://www.gravatar.com/avatar/0.jpg'
		}}).then(function(res) {
			should(res.statusCode).equal(200);
			should(res.headers['content-type']).equal('image/jpeg');
			return got('http://localhost:' + port, {query:{
				url: 'https://avatars0.githubusercontent.com/u/0'
			}}).catch(function(err) {
				return err;
			}).then(function(res) {
				should(res.statusCode).equal(403);
			});
		});
	});

	it("should append style tag to svg root element", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image-unboxed.svg', {query:{
			style: '*{fill:red;}'
		}}).then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql(`<svg version="1.0"><style type="text/css"><![CDATA[
*{fill:red;}
]]></style>`);
		});
	});

	it("should add preserveAspectRatio attribute to svg root element with a value of xMaxYMid", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image-boxed.svg', {query:{
			ratio: 'xMaxYMid'
		}}).then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql(`<svg
   xmlns="http://www.w3.org/2000/svg"
   version="1.0"
   height="6.7900095"
   width="30.449219"
   viewBox="0 0 30.449219 6.7900095" preserveAspectRatio="xMaxYMid">`);
		});
	});

	it("should add viewBox and preserveAspectRatio attributes to svg root element", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image.svg').then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql(`<svg x="100" y="50" width="200" height="400" version="1.0" viewBox="100 50 200 400" preserveAspectRatio="xMinYMin">`);
		});
	});

	it("should add viewBox and preserveAspectRatio attributes and style to svg root element", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image.svg', {query:{
			style: '*{fill:red;}'
		}}).then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql(`<svg x="100" y="50" width="200" height="400" version="1.0" viewBox="100 50 200 400" preserveAspectRatio="xMinYMin"><style type="text/css"><![CDATA[
*{fill:red;}
]]></style>`);
		});
	});

	it("should abort request and return 400 when not an image", function() {
		app.get('/file.txt', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				next();
			}
		}, function(req, res, next) {
			res.send('some text');
		});

		return got('http://localhost:' + port + '/file.txt').catch(function(err) {
			return err;
		}).then(function(res) {
			should(res.statusCode).equal(400);
		});
	});

	it("should pass errors gracefully", function() {
		app.get('/fail.jpg', function(req, res, next) {
			res.status(500);
			res.send('Fake server error');
		});
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image404.jpg?rs=w:50&q=75').catch(function(err) {
			return err;
		}).then(function(res) {
			should(res.statusCode).equal(404);
			return got('http://localhost:' + port + '/images/image500.jpg?rs=w:50&q=75');
		}).catch(function(err) {
			return err;
		}).then(function(res) {
			should(res.statusCode).equal(500);
			return got('http://localhost:' + port + '/fail.jpg?rs=w:50&q=75');
		}).catch(function(err) {
			return err;
		}).then(function(res) {
			should(res.statusCode).equal(500);
		});
	});
});

<commit_msg>And test error catching<commit_after>var should = require('should');
var fs = require('fs');
var URL = require('url');
var express = require('express');
var got = require('got');

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

describe("Sharpie middleware", function suite() {
	var app, server, port;
	before(function() {
		app = express();
		server = app.listen();
		port = server.address().port;
	});
	after(function() {
		if (server) server.close();
	});

	it("should pass through images with unsupported format", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image.ico').then(function(res) {
			should(res.statusCode).equal(200);
		});
	});

	it("should pass through unparsable svg", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/wrong.svg').then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql('<svg ="100" y="50"');
		});
	});

	it("should resize a jpeg image", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image.jpg?rs=w:50&q=75').then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body.length == 636);
			should(res.headers['content-type']).equal('image/jpeg');
		});
	});

	it("should not allow blacklisted domain", function() {
		app.get('/', sharpie({
			hostnames: function(hostname) {
				if (hostname == 'www.gravatar.com') return true;
				else return false;
			}
		}));

		return got('http://localhost:' + port, {query: {
			url: 'http://www.gravatar.com/avatar/0.jpg'
		}}).then(function(res) {
			should(res.statusCode).equal(200);
			should(res.headers['content-type']).equal('image/jpeg');
			return got('http://localhost:' + port, {query:{
				url: 'https://avatars0.githubusercontent.com/u/0'
			}}).catch(function(err) {
				return err;
			}).then(function(res) {
				should(res.statusCode).equal(403);
			});
		});
	});

	it("should append style tag to svg root element", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image-unboxed.svg', {query:{
			style: '*{fill:red;}'
		}}).then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql(`<svg version="1.0"><style type="text/css"><![CDATA[
*{fill:red;}
]]></style>`);
		});
	});

	it("should add preserveAspectRatio attribute to svg root element with a value of xMaxYMid", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image-boxed.svg', {query:{
			ratio: 'xMaxYMid'
		}}).then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql(`<svg
   xmlns="http://www.w3.org/2000/svg"
   version="1.0"
   height="6.7900095"
   width="30.449219"
   viewBox="0 0 30.449219 6.7900095" preserveAspectRatio="xMaxYMid">`);
		});
	});

	it("should add viewBox and preserveAspectRatio attributes to svg root element", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image.svg').then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql(`<svg x="100" y="50" width="200" height="400" version="1.0" viewBox="100 50 200 400" preserveAspectRatio="xMinYMin">`);
		});
	});

	it("should add viewBox and preserveAspectRatio attributes and style to svg root element", function() {
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image.svg', {query:{
			style: '*{fill:red;}'
		}}).then(function(res) {
			should(res.statusCode).equal(200);
			should(res.body).containEql(`<svg x="100" y="50" width="200" height="400" version="1.0" viewBox="100 50 200 400" preserveAspectRatio="xMinYMin"><style type="text/css"><![CDATA[
*{fill:red;}
]]></style>`);
		});
	});

	it("should abort request and return 400 when not an image", function() {
		app.get('/file.txt', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				next();
			}
		}, function(req, res, next) {
			res.send('some text');
		});

		return got('http://localhost:' + port + '/file.txt').catch(function(err) {
			return err;
		}).then(function(res) {
			should(res.statusCode).equal(400);
		});
	});

	it("should pass errors gracefully", function() {
		app.get('/fail.jpg', function(req, res, next) {
			res.status(500);
			res.send('Fake server error');
		});
		app.get('/images/*', function(req, res, next) {
			if (req.query.raw === undefined) {
				req.params.url = req.path + '?raw';
				sharpie()(req, res, next);
			} else {
				req.url = req.path.substring('/images'.length);
				next();
			}
		}, express.static(__dirname + '/images'));

		return got('http://localhost:' + port + '/images/image404.jpg?rs=w:50&q=75').catch(function(err) {
			return err;
		}).then(function(res) {
			should(res.statusCode).equal(404);
			return got('http://localhost:' + port + '/images/image500.jpg?rs=w:50&q=75');
		}).catch(function(err) {
			return err;
		}).then(function(res) {
			should(res.statusCode).equal(500);
			return got('http://localhost:' + port + '/fail.jpg?rs=w:50&q=75');
		}).catch(function(err) {
			return err;
		}).then(function(res) {
			should(res.statusCode).equal(500);
			return got('http://localhost:' + port + '/images/image.jpg?rs=w:123123123123&q=75');
		}).catch(function(res) {
			should(res.statusCode).equal(500);
		});
	});
});

<|endoftext|>


<commit_before>//https://wiki.saucelabs.com/display/DOCS/Test+Configuration+Options#TestConfigurationOptions-BrowserName
'use strict'
var assert = require("assert");
var webdriver = require("selenium-webdriver");
var URL = 'http://getfocus.io';
function createBrowser(browserName, url, context){
  return function createdBrowser(){
    if (process.env.SAUCE_USERNAME != undefined) {
      context.browser = new webdriver.Builder()
      .usingServer('http://'+ process.env.SAUCE_USERNAME+':'+process.env.SAUCE_ACCESS_KEY+'@ondemand.saucelabs.com:80/wd/hub')
      .withCapabilities({
        'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
        build: process.env.TRAVIS_BUILD_NUMBER,
        username: process.env.SAUCE_USERNAME,
        accessKey: process.env.SAUCE_ACCESS_KEY,
        browserName: browserName
      }).build();
    } else {
      context.browser = new webdriver.Builder()
      .withCapabilities({
        browserName: browserName
      }).build();
    }

    return context.browser.get(url);
  }
}
function quitBrowser(context){
    return function(){
      return context.browser.quit();
    }
}

function testTitle(done, context){
  var headline = context.browser.findElement(webdriver.By.css('h3'));
  headline.click();
  headline.getText().then(function(txt) {
    assert.equal(txt, "Les librairies FOCUS");
    done();
  });
}
/*
describe('testing chrome', () => {
  var ctx = {};
  beforeEach(() => createBrowser('chrome', URL, ctx));
  afterEach(() => quitBrowser(ctx));
  it('should handle clicking on a headline', done => testTitle(done, ctx));
});

describe('testing firefox', () => {
  var ctx = {};
  beforeEach(() => createBrowser('firefox', URL, ctx));
  afterEach(() => quitBrowser(ctx));
  it('should handle clicking on a headline', done => testTitle(done, ctx));
});

describe('testing internet explorer', () => {
  var ctx = {};
  beforeEach(() => createBrowser('internet explorer', URL, ctx));
  afterEach(() => quitBrowser(ctx));
  it('should handle clicking on a headline', done => testTitle(done, ctx));
});
*/

const testGenerator = browsers => {
  browsers.forEach(browserName => {
    describe(`testing javascript in ${browserName}`, () => {
            this.timeout(15 * 1000);
            beforeEach(() => {
              if (process.env.SAUCE_USERNAME != undefined) {
                 this.browser = new webdriver.Builder()
                 .usingServer('http://'+ process.env.SAUCE_USERNAME+':'+process.env.SAUCE_ACCESS_KEY+'@ondemand.saucelabs.com:80/wd/hub')
                 .withCapabilities({
                   'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
                   build: process.env.TRAVIS_BUILD_NUMBER,
                   username: process.env.SAUCE_USERNAME,
                   accessKey: process.env.SAUCE_ACCESS_KEY,
                   browserName: browserName
                 }).build();
               } else {
                 this.browser = new webdriver.Builder()
                 .withCapabilities({
                   browserName: browserName
                 }).build();
               }

              return this.browser.get("http://getfocus.io");
             });

           afterEach(() => this.browser.quit());

         it('should handle clicking on a headline', done => {
           const headline = this.browser.findElement(webdriver.By.css('h3'));
           headline.click();
           headline.getText().then(txt => {
             assert.equal(txt, "Les librairies FOCUS");
             done();
           });
         });
    });
  });
};

testGenerator(['chrome', 'firefox', 'internet explorer', 'iPhone', 'iPad']);
<commit_msg>Update simple.js<commit_after>//https://wiki.saucelabs.com/display/DOCS/Test+Configuration+Options#TestConfigurationOptions-BrowserName
'use strict'
var assert = require("assert");
var webdriver = require("selenium-webdriver");
var URL = 'http://getfocus.io';
function createBrowser(browserName, url, context){
  return function createdBrowser(){
    if (process.env.SAUCE_USERNAME != undefined) {
      context.browser = new webdriver.Builder()
      .usingServer('http://'+ process.env.SAUCE_USERNAME+':'+process.env.SAUCE_ACCESS_KEY+'@ondemand.saucelabs.com:80/wd/hub')
      .withCapabilities({
        'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
        build: process.env.TRAVIS_BUILD_NUMBER,
        username: process.env.SAUCE_USERNAME,
        accessKey: process.env.SAUCE_ACCESS_KEY,
        browserName: browserName
      }).build();
    } else {
      context.browser = new webdriver.Builder()
      .withCapabilities({
        browserName: browserName
      }).build();
    }

    return context.browser.get(url);
  }
}
function quitBrowser(context){
    return function(){
      return context.browser.quit();
    }
}

function testTitle(done, context){
  var headline = context.browser.findElement(webdriver.By.css('h3'));
  headline.click();
  headline.getText().then(function(txt) {
    assert.equal(txt, "Les librairies FOCUS");
    done();
  });
}
/*
describe('testing chrome', () => {
  var ctx = {};
  beforeEach(() => createBrowser('chrome', URL, ctx));
  afterEach(() => quitBrowser(ctx));
  it('should handle clicking on a headline', done => testTitle(done, ctx));
});

describe('testing firefox', () => {
  var ctx = {};
  beforeEach(() => createBrowser('firefox', URL, ctx));
  afterEach(() => quitBrowser(ctx));
  it('should handle clicking on a headline', done => testTitle(done, ctx));
});

describe('testing internet explorer', () => {
  var ctx = {};
  beforeEach(() => createBrowser('internet explorer', URL, ctx));
  afterEach(() => quitBrowser(ctx));
  it('should handle clicking on a headline', done => testTitle(done, ctx));
});
*/

const testGenerator = browsers => {
  browsers.forEach(browserName => {
    describe(`testing javascript in ${browserName}`, () => {

            beforeEach(() => {
              if (process.env.SAUCE_USERNAME != undefined) {
                 this.browser = new webdriver.Builder()
                 .usingServer('http://'+ process.env.SAUCE_USERNAME+':'+process.env.SAUCE_ACCESS_KEY+'@ondemand.saucelabs.com:80/wd/hub')
                 .withCapabilities({
                   'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
                   build: process.env.TRAVIS_BUILD_NUMBER,
                   username: process.env.SAUCE_USERNAME,
                   accessKey: process.env.SAUCE_ACCESS_KEY,
                   browserName: browserName
                 }).build();
               } else {
                 this.browser = new webdriver.Builder()
                 .withCapabilities({
                   browserName: browserName
                 }).build();
               }

              return this.browser.get("http://getfocus.io");
             });

           afterEach(() => this.browser.quit());

         it('should handle clicking on a headline', done => {
           const headline = this.browser.findElement(webdriver.By.css('h3'));
           headline.click();
           headline.getText().then(txt => {
             assert.equal(txt, "Les librairies FOCUS");
             done();
           });
         });
    });
  });
};

testGenerator(['chrome', 'firefox', 'internet explorer', 'iPhone', 'iPad']);
<|endoftext|>


<commit_before>test("toString", function() {
	assert_equal("foo", "foo".toString());
	assert_equal("", "".toString());
});

test("toString is not generic", function() {
	try {
		String.prototype.toString.call(123);
	} catch(e) {
		if(e instanceof TypeError) {
			assert(true);
			return;
		}
		assert(false, "exception not TypeError");
	}
	assert(false, "did not throw");
});

test("split", function() {
	assert("hello,world" == "hello world".split(" "));
	assert("this,is,a test" == "this is a test".split(" ", 3));
	assert("what" == "what".split("jjjj"));
	assert("w,h,a,t" == "what".split(""));
	assert("what" == "what".split());
});

test("slice", function() {
	assert_equal("hello", "hello".slice());
	assert_equal("llo", "hello".slice(2));
	assert_equal("el", "hello".slice(1,3));
	assert_equal("ell", "hello".slice(1,-1));
});

test("match", function() {
  assert("fo,ob,ar" == "foobar".match(/../g));
  assert("fo" == "foobar".match(/../));

  assert("fo,ob,ar" == "foobar".match(/.(.)/g));
  assert("fo,o" == "foobar".match(/.(.)/));
});

test("indexOf", function() {
  assert_equal(3, "foobar".indexOf("bar"));
  assert_equal(2, "bbaaaaa".indexOf("a"));
});

test("lastIndexOf", function() {
  assert_equal(3, "foobar".lastIndexOf("bar"));
  assert_equal(6, "bbaaaaa".lastIndexOf("a"));
});

test("enumerable properties", function() {
  var i = 0;
  var s = "hello";
  for(var x in s) {
    if(s.hasOwnProperty(x)) {
      i++;
    }
  }
  assert_equal(5, i);
});

test("charAt", function() {
  assert_equal("a", "abc".charAt(0));
  assert_equal("o", "zzo".charAt(2));
  assert_equal("", "what".charAt(-1));
  assert_equal("", "what".charAt(4));
});

test("[]", function() {
  assert_equal("a", "abc"[0]);
  assert_equal("o", "zzo"[2]);
  assert_equal(undefined, "what"[-1]);
  assert_equal(undefined, "what"[4]);
});

test("in", function() {
  assert(0 in "hi");
  assert(1 in "hi");
  assert(!(2 in "hi"));
  assert("length" in "hi");
  assert(!("foo" in "hi"));
});

test("charCodeAt", function() {
  assert_equal(97, "a".charCodeAt(0));
  assert_equal(111, "zzo".charCodeAt(2));
  assert(isNaN("what".charCodeAt(-1)));
  assert(isNaN("what".charCodeAt(4)));
});

test("toUpperCase", function() {
  assert_equal("FOO", "foo".toUpperCase());
  assert_equal("FOO", "FoO".toUpperCase());
  assert_equal("", "".toUpperCase());
});

test("toLowerCase", function() {
  assert_equal("foo", "FOO".toLowerCase());
  assert_equal("foo", "FoO".toLowerCase());
  assert_equal("", "".toLowerCase());
});

test("fromCharCode", function() {
  assert_equal("", String.fromCharCode());
  assert_equal("a", String.fromCharCode(97));
  assert_equal("abcd", String.fromCharCode(97,98,99,100));
});

test("primitive value", function() {
  assert_equal("foobar", String(new String("foobar")));
  assert_equal("", String(new String("")));
});

test("escape codes", function() {
  assert_equal(-1, "\b".indexOf("b"));
  assert_equal(-1, "\n".indexOf("n"));
  assert_equal(-1, "\f".indexOf("f"));
  assert_equal(-1, "\v".indexOf("v"));
  assert_equal(-1, "\r".indexOf("r"));
  assert_equal(-1, "\t".indexOf("t"));
  assert_equal("hi", "h\
i");

  assert_equal(" ", "\x20");
  assert_equal(" ", "\u0020");
  assert_equal(" ", "\40");
});<commit_msg>string substring and comparison test<commit_after>test("toString", function() {
	assert_equal("foo", "foo".toString());
	assert_equal("", "".toString());
});

test("toString is not generic", function() {
	try {
		String.prototype.toString.call(123);
	} catch(e) {
		if(e instanceof TypeError) {
			assert(true);
			return;
		}
		assert(false, "exception not TypeError");
	}
	assert(false, "did not throw");
});

test("split", function() {
	assert("hello,world" == "hello world".split(" "));
	assert("this,is,a test" == "this is a test".split(" ", 3));
	assert("what" == "what".split("jjjj"));
	assert("w,h,a,t" == "what".split(""));
	assert("what" == "what".split());
});

test("slice", function() {
	assert_equal("hello", "hello".slice());
	assert_equal("llo", "hello".slice(2));
	assert_equal("el", "hello".slice(1,3));
	assert_equal("ell", "hello".slice(1,-1));
});

test("match", function() {
  assert("fo,ob,ar" == "foobar".match(/../g));
  assert("fo" == "foobar".match(/../));

  assert("fo,ob,ar" == "foobar".match(/.(.)/g));
  assert("fo,o" == "foobar".match(/.(.)/));
});

test("indexOf", function() {
  assert_equal(3, "foobar".indexOf("bar"));
  assert_equal(2, "bbaaaaa".indexOf("a"));
});

test("lastIndexOf", function() {
  assert_equal(3, "foobar".lastIndexOf("bar"));
  assert_equal(6, "bbaaaaa".lastIndexOf("a"));
});

test("enumerable properties", function() {
  var i = 0;
  var s = "hello";
  for(var x in s) {
    if(s.hasOwnProperty(x)) {
      i++;
    }
  }
  assert_equal(5, i);
});

test("charAt", function() {
  assert_equal("a", "abc".charAt(0));
  assert_equal("o", "zzo".charAt(2));
  assert_equal("", "what".charAt(-1));
  assert_equal("", "what".charAt(4));
});

test("[]", function() {
  assert_equal("a", "abc"[0]);
  assert_equal("o", "zzo"[2]);
  assert_equal(undefined, "what"[-1]);
  assert_equal(undefined, "what"[4]);
});

test("in", function() {
  assert(0 in "hi");
  assert(1 in "hi");
  assert(!(2 in "hi"));
  assert("length" in "hi");
  assert(!("foo" in "hi"));
});

test("charCodeAt", function() {
  assert_equal(97, "a".charCodeAt(0));
  assert_equal(111, "zzo".charCodeAt(2));
  assert(isNaN("what".charCodeAt(-1)));
  assert(isNaN("what".charCodeAt(4)));
});

test("toUpperCase", function() {
  assert_equal("FOO", "foo".toUpperCase());
  assert_equal("FOO", "FoO".toUpperCase());
  assert_equal("", "".toUpperCase());
});

test("toLowerCase", function() {
  assert_equal("foo", "FOO".toLowerCase());
  assert_equal("foo", "FoO".toLowerCase());
  assert_equal("", "".toLowerCase());
});

test("fromCharCode", function() {
  assert_equal("", String.fromCharCode());
  assert_equal("a", String.fromCharCode(97));
  assert_equal("abcd", String.fromCharCode(97,98,99,100));
});

test("primitive value", function() {
  assert_equal("foobar", String(new String("foobar")));
  assert_equal("", String(new String("")));
});

test("escape codes", function() {
  assert_equal(-1, "\b".indexOf("b"));
  assert_equal(-1, "\n".indexOf("n"));
  assert_equal(-1, "\f".indexOf("f"));
  assert_equal(-1, "\v".indexOf("v"));
  assert_equal(-1, "\r".indexOf("r"));
  assert_equal(-1, "\t".indexOf("t"));
  assert_equal("hi", "h\
i");

  assert_equal(" ", "\x20");
  assert_equal(" ", "\u0020");
  assert_equal(" ", "\40");
});

test("substring", function() {
    assert_equal("foobar", "foobar".substring());
    assert_equal("foobar", "foobar".substring(0, 6));
    assert_equal("ar", "foobar".substring(-2, 6));
    assert_equal("ob", "foobar".substring(2, 4));
    assert_equal("bar", "foobar".substring(3));
});

test("comparison", function() {
    assert("hello" > "a");
    assert("a" < "b");
    assert("a" <= "a");
    assert("A" < "a");
});<|endoftext|>


<commit_before>//Display the top bar: netid and course dropdown
var source = $("#page-top").html();
var template = Handlebars.compile(source);
$("#top_banner").html(template({
    netid: window.user.netid,
    quarter: firstLetterUppercase(window.term.quarter),
    year: window.term.year,
    sections: window.section_data
}));

//Listed for course dropdown selection change
$("#my_courses").change(function() {
    var index = $("select[name='my_courses'] option:selected").index();
    showCurrentCourseData(index);
    showHistoricDataSelectors(index);
    showHistoricCourseData(index, "All Quarters", "All Years");
});

var index = $("select[name='my_courses'] option:selected").index();
showCurrentCourseData(index);
showHistoricDataSelectors(index, "All Quarters", "All Years");
showHistoricCourseData(index, "All Quarters", "All Years");

//Display data about the currently selected course - called whenever selection changes
function showCurrentCourseData(index) {
    var current = $("#current-course-data").html();
    var currentTemplate = Handlebars.compile(current);
    $("#current-course-target").html(currentTemplate({
        current_median: window.section_data[index].current_median,
        current_num_registered: window.section_data[index].current_enrollment,
        current_capacity:window.section_data[index].limit_estimate_enrollment,
        current_repeat_students:3,
        concurrent_courses:window.section_data[index].concurrent_courses,
        current_majors:window.section_data[index].current_student_majors
    }));
}

//Populate the historic data selectors for the currently selected course
function showHistoricDataSelectors(index, quarter, year) {
    //Fix case of past quarters and create arrays without duplicate quarters/years
    var valid_quarters = [];
    var valid_years = [];
    var combined = [];//stores quarter + year so that when a quarter is selected, can only select years where the course was offered in that quarter & vice versa
    var past_offerings = window.section_data[index].past_offerings;
    for (var o in past_offerings) {
        past_offerings[o].quarter = firstLetterUppercase(past_offerings[o].quarter);
        if (combined.indexOf(past_offerings[o].quarter + past_offerings[o].year) == -1)
            combined.push(past_offerings[o].quarter + past_offerings[o].year);
        if (valid_quarters.indexOf(past_offerings[o].quarter) == -1)
            valid_quarters.push(past_offerings[o].quarter);
        if (valid_years.indexOf(past_offerings[o].year) == -1)
            valid_years.push(past_offerings[o].year);
    }
    //Remove any invalid combinations of quarter and year based on current selection
    if (quarter != "All Quarters") {
        var remove_years = [];
        for (var y in valid_years)
            if (combined.indexOf(quarter + valid_years[y]) == -1)
                remove_years.push(valid_years[y]);
        while (remove_years.length > 0) {
            valid_years.splice(valid_years.indexOf(remove_years[0]),1);
            remove_years.splice(0,1);
        }
    }
    if (year != "All Years") {
        var remove_quarters = [];
        for (var q in valid_quarters)
            if (combined.indexOf(valid_quarters[q] + year) == -1)
                remove_quarters.push(valid_quarters[q]);
        while (remove_quarters.length > 0) {
            valid_quarters.splice(valid_quarters.indexOf(remove_quarters[0]),1);
            remove_quarters.splice(0,1);
        }
    }

    //Load template
    var selectors = $("#historic-data-selectors").html();
    var selectorsTemplate = Handlebars.compile(selectors);
    $("#historic-selector-target").html(selectorsTemplate({
        past_quarters:prepOptions(quarter, valid_quarters, "All Quarters"), past_years:prepOptions(year, valid_years, "All Years")
    }));

    //Historic data selection
    $(".historic-filter").change(function() {
        console.log("selection change ");
        index = $("select[name='my_courses'] option:selected").index();
        var newQuarter = $("select[name='historic_filter_quarter'] option:selected").val();
        var newYear = $("select[name='historic_filter_year'] option:selected").val();
        showHistoricDataSelectors(index, newQuarter, newYear);
        showHistoricCourseData(index, newQuarter, newYear);
    });
}

//Prepares the handlebars variable for historic data selectors
function prepOptions(selected, valid, all) {
    options = [];
    //make sure All option gets pushed
    options.push({
        name: all,
        selected: (selected==all)? "selected":""
    });
    for (var v in valid) {
        options.push({
            name: valid[v],
            selected: (valid[v]==selected) ? "selected":""
        });
    }
    return options;
}

//Display data about the past offerings of selected course - called whenever selection changes
function showHistoricCourseData(index, quarter, year) {
    var past_offerings = window.section_data[index].past_offerings;
    for (var i = 0; i < past_offerings.length; i++)
        past_offerings[i].quarter = firstLetterUppercase(past_offerings[i].quarter);
    var historic = $("#historic-course-data").html();
    var historicTemplate = Handlebars.compile(historic);
    console.log("show historic data for " + quarter + " " + year);
    $("#historic-course-target").html(historicTemplate({
        common_majors:calculateCommon(index, quarter, year, "majors","major"),
        latest_majors:calculateCommon(index, quarter, year, "latest_majors","major"),
        common_courses:calculateCommon(index, quarter, year, "concurrent_courses","course"),
        selected_quarter:quarter,
        selected_year:year,
        instructors: getInstructors(index, quarter, year)
        //past_terms:window.section_data[index].past_offerings
    }));
}

function getInstructors(index, quarter, year) {
    var all_quarters = "All Quarters";
    var all_years = "All Years";
    var past_offerings = window.section_data[index].past_offerings;
    var instructors = []
    for (var o = 0; o < past_offerings.length; o++) {
        if (quarterIsInRange(past_offerings[o], year, all_years, quarter, all_quarters)) {
            for (var i in past_offerings[o].instructors) {
                instructors.push({
                    quarter: past_offerings[o].quarter,
                    year: past_offerings[o].year,
                    display_name: past_offerings[o].instructors[i].display_name,
                    uw_email: past_offerings[o].instructors[i].uwnetid + "@uw.edu"
                });
            }
        }
    }
    return instructors;
}

//Calculates all of the common major/course lists based on historic selections
function calculateCommon(index, quarter, year, list_type, name_type) {
    var all_quarters = "All Quarters";
    var all_years = "All Years";
    var past_offerings = window.section_data[index].past_offerings;
    var obj = {};
    var total_students = 0;
    for (var o = 0; o < past_offerings.length; o++) {
        if (quarterIsInRange(past_offerings[o], year, all_years, quarter, all_quarters)) {
            var term_obj = past_offerings[o][list_type];
            for (var m = 0; m < term_obj.length; m++) {
                total_students += term_obj[m].number_students;
                if (obj.hasOwnProperty(term_obj[m][name_type]))
                    obj[term_obj[m][name_type]] += term_obj[m].number_students;
                else obj[term_obj[m][name_type]] = term_obj[m].number_students;
            }
        }
    }
    return sortObj(obj, total_students, name_type);
}

//check if past offering was in the range selected in the dropdowns
function quarterIsInRange(past_offering, year, all_years, quarter, all_quarters) {
    if ((past_offering.year == year && quarter == all_quarters) ||
        (year == all_years && past_offering.quarter == quarter) ||
        (year == all_years && quarter == all_quarters) ||
        (year != all_years && quarter != all_quarters)
       )
        return true;
    else return false;
}

//order majors/courses by number of students
function sortObj(arr, total_students, name_type) {
    var sorted = [];
    for (var i in arr) {
        if (name_type == "major")
            sorted.push({"major":i, "number_students":arr[i], "percent_students": ((arr[i]/total_students)*100).toFixed(2)});
        else
            sorted.push({"course":i, "number_students":arr[i], "percent_students": ((arr[i]/total_students)*100).toFixed(2)});
    }
    return reverseSortByNumStudents(sorted);
}

//sort array of objects by number_students value
function reverseSortByNumStudents(arr) {
    arr.sort(function(a, b) {
        return a.number_students - b.number_students;
    });
    return arr.reverse();
}

//Capitalize the first letter of a word
function firstLetterUppercase(word)
{
    return word.charAt(0).toUpperCase() + word.slice(1);
}<commit_msg>Fixed historic selectors take 2<commit_after>//Display the top bar: netid and course dropdown
var source = $("#page-top").html();
var template = Handlebars.compile(source);
$("#top_banner").html(template({
    netid: window.user.netid,
    quarter: firstLetterUppercase(window.term.quarter),
    year: window.term.year,
    sections: window.section_data
}));

//Listed for course dropdown selection change
$("#my_courses").change(function() {
    var index = $("select[name='my_courses'] option:selected").index();
    showCurrentCourseData(index);
    showHistoricDataSelectors(index, "All Quarters", "All Years");
    showHistoricCourseData(index, "All Quarters", "All Years");
});

var index = $("select[name='my_courses'] option:selected").index();
showCurrentCourseData(index);
showHistoricDataSelectors(index, "All Quarters", "All Years");
showHistoricCourseData(index, "All Quarters", "All Years");

//Display data about the currently selected course - called whenever selection changes
function showCurrentCourseData(index) {
    var current = $("#current-course-data").html();
    var currentTemplate = Handlebars.compile(current);
    $("#current-course-target").html(currentTemplate({
        current_median: window.section_data[index].current_median,
        current_num_registered: window.section_data[index].current_enrollment,
        current_capacity:window.section_data[index].limit_estimate_enrollment,
        current_repeat_students:3,
        concurrent_courses:window.section_data[index].concurrent_courses,
        current_majors:window.section_data[index].current_student_majors
    }));
}

//Populate the historic data selectors for the currently selected course
function showHistoricDataSelectors(index, quarter, year) {
    //Fix case of past quarters and create arrays without duplicate quarters/years
    var valid_quarters = [];
    var valid_years = [];
    var combined = [];//stores quarter + year so that when a quarter is selected, can only select years where the course was offered in that quarter & vice versa
    var past_offerings = window.section_data[index].past_offerings;
    for (var o in past_offerings) {
        past_offerings[o].quarter = firstLetterUppercase(past_offerings[o].quarter);
        if (combined.indexOf(past_offerings[o].quarter + past_offerings[o].year) == -1)
            combined.push(past_offerings[o].quarter + past_offerings[o].year);
        if (valid_quarters.indexOf(past_offerings[o].quarter) == -1)
            valid_quarters.push(past_offerings[o].quarter);
        if (valid_years.indexOf(past_offerings[o].year) == -1)
            valid_years.push(past_offerings[o].year);
    }
    //Remove any invalid combinations of quarter and year based on current selection
    if (quarter != "All Quarters") {
        var remove_years = [];
        for (var y in valid_years)
            if (combined.indexOf(quarter + valid_years[y]) == -1)
                remove_years.push(valid_years[y]);
        while (remove_years.length > 0) {
            valid_years.splice(valid_years.indexOf(remove_years[0]),1);
            remove_years.splice(0,1);
        }
    }
    if (year != "All Years") {
        var remove_quarters = [];
        for (var q in valid_quarters)
            if (combined.indexOf(valid_quarters[q] + year) == -1)
                remove_quarters.push(valid_quarters[q]);
        while (remove_quarters.length > 0) {
            valid_quarters.splice(valid_quarters.indexOf(remove_quarters[0]),1);
            remove_quarters.splice(0,1);
        }
    }

    //Load template
    var selectors = $("#historic-data-selectors").html();
    var selectorsTemplate = Handlebars.compile(selectors);
    $("#historic-selector-target").html(selectorsTemplate({
        past_quarters:prepOptions(quarter, valid_quarters, "All Quarters"), past_years:prepOptions(year, valid_years, "All Years")
    }));

    //Historic data selection
    $(".historic-filter").change(function() {
        console.log("selection change ");
        index = $("select[name='my_courses'] option:selected").index();
        var newQuarter = $("select[name='historic_filter_quarter'] option:selected").val();
        var newYear = $("select[name='historic_filter_year'] option:selected").val();
        showHistoricDataSelectors(index, newQuarter, newYear);
        showHistoricCourseData(index, newQuarter, newYear);
    });
}

//Prepares the handlebars variable for historic data selectors
function prepOptions(selected, valid, all) {
    options = [];
    //make sure All option gets pushed
    options.push({
        name: all,
        selected: (selected==all)? "selected":""
    });
    for (var v in valid) {
        options.push({
            name: valid[v],
            selected: (valid[v]==selected) ? "selected":""
        });
    }
    return options;
}

//Display data about the past offerings of selected course - called whenever selection changes
function showHistoricCourseData(index, quarter, year) {
    var past_offerings = window.section_data[index].past_offerings;
    for (var i = 0; i < past_offerings.length; i++)
        past_offerings[i].quarter = firstLetterUppercase(past_offerings[i].quarter);
    var historic = $("#historic-course-data").html();
    var historicTemplate = Handlebars.compile(historic);
    console.log("show historic data for " + quarter + " " + year);
    $("#historic-course-target").html(historicTemplate({
        common_majors:calculateCommon(index, quarter, year, "majors","major"),
        latest_majors:calculateCommon(index, quarter, year, "latest_majors","major"),
        common_courses:calculateCommon(index, quarter, year, "concurrent_courses","course"),
        selected_quarter:quarter,
        selected_year:year,
        instructors: getInstructors(index, quarter, year)
        //past_terms:window.section_data[index].past_offerings
    }));
}

function getInstructors(index, quarter, year) {
    var all_quarters = "All Quarters";
    var all_years = "All Years";
    var past_offerings = window.section_data[index].past_offerings;
    var instructors = []
    for (var o = 0; o < past_offerings.length; o++) {
        if (quarterIsInRange(past_offerings[o], year, all_years, quarter, all_quarters)) {
            for (var i in past_offerings[o].instructors) {
                instructors.push({
                    quarter: past_offerings[o].quarter,
                    year: past_offerings[o].year,
                    display_name: past_offerings[o].instructors[i].display_name,
                    uw_email: past_offerings[o].instructors[i].uwnetid + "@uw.edu"
                });
            }
        }
    }
    return instructors;
}

//Calculates all of the common major/course lists based on historic selections
function calculateCommon(index, quarter, year, list_type, name_type) {
    var all_quarters = "All Quarters";
    var all_years = "All Years";
    var past_offerings = window.section_data[index].past_offerings;
    var obj = {};
    var total_students = 0;
    for (var o = 0; o < past_offerings.length; o++) {
        if (quarterIsInRange(past_offerings[o], year, all_years, quarter, all_quarters)) {
            var term_obj = past_offerings[o][list_type];
            for (var m = 0; m < term_obj.length; m++) {
                total_students += term_obj[m].number_students;
                if (obj.hasOwnProperty(term_obj[m][name_type]))
                    obj[term_obj[m][name_type]] += term_obj[m].number_students;
                else obj[term_obj[m][name_type]] = term_obj[m].number_students;
            }
        }
    }
    return sortObj(obj, total_students, name_type);
}

//check if past offering was in the range selected in the dropdowns
function quarterIsInRange(past_offering, year, all_years, quarter, all_quarters) {
    if ((past_offering.year == year && quarter == all_quarters) ||
        (year == all_years && past_offering.quarter == quarter) ||
        (year == all_years && quarter == all_quarters) ||
        (year != all_years && quarter != all_quarters)
       )
        return true;
    else return false;
}

//order majors/courses by number of students
function sortObj(arr, total_students, name_type) {
    var sorted = [];
    for (var i in arr) {
        if (name_type == "major")
            sorted.push({"major":i, "number_students":arr[i], "percent_students": ((arr[i]/total_students)*100).toFixed(2)});
        else
            sorted.push({"course":i, "number_students":arr[i], "percent_students": ((arr[i]/total_students)*100).toFixed(2)});
    }
    return reverseSortByNumStudents(sorted);
}

//sort array of objects by number_students value
function reverseSortByNumStudents(arr) {
    arr.sort(function(a, b) {
        return a.number_students - b.number_students;
    });
    return arr.reverse();
}

//Capitalize the first letter of a word
function firstLetterUppercase(word)
{
    return word.charAt(0).toUpperCase() + word.slice(1);
}<|endoftext|>


<commit_before>// The expected number of bits of information from real science is
// -[1/7*lg(1/7) * 7]
// = 2.807 bits

// The expected number of bits of information from experimenting randomly on an adventurer is
// -[1/7*lg(1/7) + 2/7*lg(2/7) + 1/7*lg(1/7) + 3/7*lg(3/7)]
// = 1.842 bits

import React from 'react';
// import logo from './logo.svg';
import './App.css';

import _ from 'lodash'
import update from 'react-addons-update'

// This is what an Alchemical looks like:
// [1, 1, -1]

// Here are all of the Alchemicals:
var alchemicals = [
  [-1, +1, -1],
  [+1, -1, +1],
  [+1, -1, -1],
  [-1, +1, +1],
  [-1, -1, +1],
  [+1, +1, -1],
  [-1, -1, -1],
  [+1, +1, +1],
]

var ingredients = [
  "Mushroom",
  "Fern",
  "Toad",
  "Birdclaw",
  "Flower",
  "Mandrake",
  "Scorion",
  "Feather",
]

var potions = {
  "Red+":   [+1, 0, 0],
  "Red-":   [-1, 0, 0],
  "Green+": [0, +1, 0],
  "Green-": [0, -1, 0],
  "Blue+":  [0, 0, +1],
  "Blue-":  [0, 0, -1],
  "Soup":   [0, 0, 0],
}

var Fact = React.createClass({
  render: function() {
    return

      {this.props.index}: {JSON.stringify(this.props.item)}
      <button onClick={this.props.deleteFact} value={this.props.index}>Delete</button>

  }
});

var FactList = React.createClass({
  render: function() {
    return
{this.props.items.map((fact, factIndex) => <Fact key={factIndex} item={fact} index={factIndex} deleteFact={this.props.deleteFact}/>)}
;
  }
});

var Ingredient = React.createClass({
  render: function() {
    return
<input type="radio" name="ingredient" onChange={this.props.callback}/>{this.props.name}

  }
})

var Potion = React.createClass({
  render: function() {
    return
<input type="checkbox" name="potion" onChange={this.props.callback}/>{this.props.name}

  }
})

var SheetCell = React.createClass({
  render: function() {
    return {this.numWorlds()}
  },
  numWorlds: function() {
    var worlds = _.filter(this.props.worlds, _.bind(function(world) {
      return _.isEqual(world[this.props.ingredientIndex], this.props.alchemical)
    }, this))
    return worlds.length
  }
})

var SheetRow = React.createClass({
  render: function() {
    return
{ingredients.map((ingredient, index) => <SheetCell ingredientIndex={index} alchemical={this.props.alchemical} key={index} worlds={this.props.worlds}/>)}

  }
})

var AlchemistsSolverApp = React.createClass({
  getInitialState: function() {
    return {
      factlist: [],
      currentFact: this.makeNewFact(),
      worlds: permutator(alchemicals),
    }
  },
  makeNewFact: function() {
    return {
      ingredients: [0, 1],
      possibleResults: [false, false, false, false, false, false, false]
    }
  },
  handleSubmit: function(e) {
    e.preventDefault();
    this.setState({
      factlist: this.state.factlist.concat([this.state.currentFact]),
      worlds: _.filter(this.state.worlds, _.curry(check)(this.state.currentFact)),
    });
  },
  ingredientChange: function(ingredientIndex, ingredient) {
    var newIngredients = [];
    newIngredients[ingredientIndex] = ingredient;
    var newState = update(this.state,
      {currentFact: {ingredients: {$merge: newIngredients}}})
    this.setState(newState)
  },
  potionChange: function(potionIndex) {
    var newPossibleResults = [];
    newPossibleResults[potionIndex] = !this.state.currentFact.possibleResults[potionIndex];
    var newState = update(this.state,
      {currentFact: {possibleResults: {$merge: newPossibleResults}}})
    this.setState(newState)
  },
  render: function() {
    var self = this;
    return (

Alchemists Solver

        <FactList items={this.state.factlist} deleteFact={this.deleteFact}/>

        <form action="" style={{display: "inline-block"}}>
          {ingredients.map((name, index) => <Ingredient name={name} ingredientNumber={0} key={index} callback={function() {self.ingredientChange(0, index)}} />)}
        </form>

        <form action="" style={{display: "inline-block"}}>
          {ingredients.map((name, index) => <Ingredient name={name} ingredientNumber={1} key={index} callback={function() {self.ingredientChange(1, index)}} />)}
        </form>

        <form action="" style={{display: "inline-block"}}>
          {_.keys(potions).map((name, index) => <Potion name={name} key={index} callback={function() {self.potionChange(index)}} />)}
        </form>

        <form onSubmit={this.handleSubmit}>
          <button>{'Add Fact'}</button>
        </form>

{this.computeStuff()}

            {alchemicals.map((alchemical, index) => <SheetRow alchemical={alchemical} key={index} worlds={this.state.worlds}/>)}

    );
  },
  deleteFact: function(e) {
    var newFactList = removeAtIndex(this.state.factlist, parseInt(e.target.value, 10))
    var worlds = permutator(alchemicals)
    for (var factIndex in newFactList) {
      var fact = newFactList[factIndex]
      console.log(fact)
      worlds = _.filter(worlds, _.curry(check)(fact))
    }
    this.setState({factlist: newFactList, worlds: worlds})
  },
  computeStuff: function() {
    return this.state.worlds.length
  }
});

// non-mutating
function removeAtIndex(arr, index) {
  return _.filter(arr, function(val, idx) {return idx !== index})
}

var ColorMapping = {
  0: "red",
  1: "green",
  2: "blue",
};

// var SignMapping = {
//   -1: "minus",
//   0: "neutral",
//   1: "plus",
// };

// Alchemical -> Alchemical -> Potion
function mix(alchemicalA, alchemicalB) {
  var mean = _.zipWith(alchemicalA, alchemicalB, function(a,b){return (a+b)/2})
  for (var index = 0; index < 3; index++) {
    if (mean[(index+1) % 3] !== 0)
      mean[index] = 0
  }

  return mean
}

function check(fact, world) {
  var alchemicalA = world[fact.ingredients[0]]
  var alchemicalB = world[fact.ingredients[1]]
  var result = mix(alchemicalA, alchemicalB)
  var potionIndex = _.findIndex(_.values(potions), _.curry(_.isEqual)(result))
  return fact.possibleResults[potionIndex]
}

// http://stackoverflow.com/a/20871714/6036628
function permutator(inputArr) {
  var results = [];

  function permute(arr, memo) {
    var cur, memo = memo || [];

    for (var i = 0; i < arr.length; i++) {
      cur = arr.splice(i, 1);
      if (arr.length === 0) {
        results.push(memo.concat(cur));
      }
      permute(arr.slice(), memo.concat(cur));
      arr.splice(i, 0, cur[0]);
    }

    return results;
  }

  return permute(inputArr);
}

// ===== Unit tests =====

// Here is what a World looks like:
var exampleWorld = [
  [+1, -1, -1],
  [-1, +1, -1],
  [+1, -1, +1],
  [-1, +1, +1],
  [+1, +1, +1],
  [-1, -1, +1],
  [+1, +1, -1],
  [-1, -1, -1],
]

// This is what an Ingredient looks like:
var exampleIngredientA = 4
var exampleIngredientB = 5

// This is what a Potion looks like:
var examplePotionA = [0, 0, 1] // this is a blue+
var examplePotionB = [0, 0, 0] // this is soup

// This is what a Fact looks like:
// {
//   ingredients: [5, 7]
//   possibleResults: [true, false, false, false, false, false, true]
// }
// combining ingredient 5 and 7 make either a red+ or a soup
var exampleFact = {
  ingredients: [exampleIngredientA, exampleIngredientB],
  possibleResults: [examplePotionA, examplePotionB]
}

console.log(check(exampleFact, exampleWorld))

export default AlchemistsSolverApp;
<commit_msg>todo list<commit_after>//TODO change to percents
//TODO don't rerender on every click
//TODO add other views
//TODO add other fact types (periscope / beginner debunking)

// The expected number of bits of information from real science is
// -[1/7*lg(1/7) * 7]
// = 2.807 bits

// The expected number of bits of information from experimenting randomly on an adventurer is
// -[1/7*lg(1/7) + 2/7*lg(2/7) + 1/7*lg(1/7) + 3/7*lg(3/7)]
// = 1.842 bits

import React from 'react';
// import logo from './logo.svg';
import './App.css';

import _ from 'lodash'
import update from 'react-addons-update'

// This is what an Alchemical looks like:
// [1, 1, -1]

// Here are all of the Alchemicals:
var alchemicals = [
  [-1, +1, -1],
  [+1, -1, +1],
  [+1, -1, -1],
  [-1, +1, +1],
  [-1, -1, +1],
  [+1, +1, -1],
  [-1, -1, -1],
  [+1, +1, +1],
]

var ingredients = [
  "Mushroom",
  "Fern",
  "Toad",
  "Birdclaw",
  "Flower",
  "Mandrake",
  "Scorion",
  "Feather",
]

var potions = {
  "Red+":   [+1, 0, 0],
  "Red-":   [-1, 0, 0],
  "Green+": [0, +1, 0],
  "Green-": [0, -1, 0],
  "Blue+":  [0, 0, +1],
  "Blue-":  [0, 0, -1],
  "Soup":   [0, 0, 0],
}

var Fact = React.createClass({
  render: function() {
    return

      {this.props.index}: {JSON.stringify(this.props.item)}
      <button onClick={this.props.deleteFact} value={this.props.index}>Delete</button>

  }
});

var FactList = React.createClass({
  render: function() {
    return
{this.props.items.map((fact, factIndex) => <Fact key={factIndex} item={fact} index={factIndex} deleteFact={this.props.deleteFact}/>)}
;
  }
});

var Ingredient = React.createClass({
  render: function() {
    return
<input type="radio" name="ingredient" onChange={this.props.callback}/>{this.props.name}

  }
})

var Potion = React.createClass({
  render: function() {
    return
<input type="checkbox" name="potion" onChange={this.props.callback}/>{this.props.name}

  }
})

var SheetCell = React.createClass({
  render: function() {
    return {this.numWorlds()}
  },
  numWorlds: function() {
    var worlds = _.filter(this.props.worlds, _.bind(function(world) {
      return _.isEqual(world[this.props.ingredientIndex], this.props.alchemical)
    }, this))
    return worlds.length
  }
})

var SheetRow = React.createClass({
  render: function() {
    return
{ingredients.map((ingredient, index) => <SheetCell ingredientIndex={index} alchemical={this.props.alchemical} key={index} worlds={this.props.worlds}/>)}

  }
})

var AlchemistsSolverApp = React.createClass({
  getInitialState: function() {
    return {
      factlist: [],
      currentFact: this.makeNewFact(),
      worlds: permutator(alchemicals),
    }
  },
  makeNewFact: function() {
    return {
      ingredients: [0, 1],
      possibleResults: [false, false, false, false, false, false, false]
    }
  },
  handleSubmit: function(e) {
    e.preventDefault();
    this.setState({
      factlist: this.state.factlist.concat([this.state.currentFact]),
      worlds: _.filter(this.state.worlds, _.curry(check)(this.state.currentFact)),
    });
  },
  ingredientChange: function(ingredientIndex, ingredient) {
    var newIngredients = [];
    newIngredients[ingredientIndex] = ingredient;
    var newState = update(this.state,
      {currentFact: {ingredients: {$merge: newIngredients}}})
    this.setState(newState)
  },
  potionChange: function(potionIndex) {
    var newPossibleResults = [];
    newPossibleResults[potionIndex] = !this.state.currentFact.possibleResults[potionIndex];
    var newState = update(this.state,
      {currentFact: {possibleResults: {$merge: newPossibleResults}}})
    this.setState(newState)
  },
  render: function() {
    var self = this;
    return (

Alchemists Solver

        <FactList items={this.state.factlist} deleteFact={this.deleteFact}/>

        <form action="" style={{display: "inline-block"}}>
          {ingredients.map((name, index) => <Ingredient name={name} ingredientNumber={0} key={index} callback={function() {self.ingredientChange(0, index)}} />)}
        </form>

        <form action="" style={{display: "inline-block"}}>
          {ingredients.map((name, index) => <Ingredient name={name} ingredientNumber={1} key={index} callback={function() {self.ingredientChange(1, index)}} />)}
        </form>

        <form action="" style={{display: "inline-block"}}>
          {_.keys(potions).map((name, index) => <Potion name={name} key={index} callback={function() {self.potionChange(index)}} />)}
        </form>

        <form onSubmit={this.handleSubmit}>
          <button>{'Add Fact'}</button>
        </form>

{this.computeStuff()}

            {alchemicals.map((alchemical, index) => <SheetRow alchemical={alchemical} key={index} worlds={this.state.worlds}/>)}

    );
  },
  deleteFact: function(e) {
    var newFactList = removeAtIndex(this.state.factlist, parseInt(e.target.value, 10))
    var worlds = permutator(alchemicals)
    for (var factIndex in newFactList) {
      var fact = newFactList[factIndex]
      console.log(fact)
      worlds = _.filter(worlds, _.curry(check)(fact))
    }
    this.setState({factlist: newFactList, worlds: worlds})
  },
  computeStuff: function() {
    return this.state.worlds.length
  }
});

// non-mutating
function removeAtIndex(arr, index) {
  return _.filter(arr, function(val, idx) {return idx !== index})
}

var ColorMapping = {
  0: "red",
  1: "green",
  2: "blue",
};

// var SignMapping = {
//   -1: "minus",
//   0: "neutral",
//   1: "plus",
// };

// Alchemical -> Alchemical -> Potion
function mix(alchemicalA, alchemicalB) {
  var mean = _.zipWith(alchemicalA, alchemicalB, function(a,b){return (a+b)/2})
  for (var index = 0; index < 3; index++) {
    if (mean[(index+1) % 3] !== 0)
      mean[index] = 0
  }

  return mean
}

function check(fact, world) {
  var alchemicalA = world[fact.ingredients[0]]
  var alchemicalB = world[fact.ingredients[1]]
  var result = mix(alchemicalA, alchemicalB)
  var potionIndex = _.findIndex(_.values(potions), _.curry(_.isEqual)(result))
  return fact.possibleResults[potionIndex]
}

// http://stackoverflow.com/a/20871714/6036628
function permutator(inputArr) {
  var results = [];

  function permute(arr, memo) {
    var cur, memo = memo || [];

    for (var i = 0; i < arr.length; i++) {
      cur = arr.splice(i, 1);
      if (arr.length === 0) {
        results.push(memo.concat(cur));
      }
      permute(arr.slice(), memo.concat(cur));
      arr.splice(i, 0, cur[0]);
    }

    return results;
  }

  return permute(inputArr);
}

// ===== Unit tests =====

// Here is what a World looks like:
var exampleWorld = [
  [+1, -1, -1],
  [-1, +1, -1],
  [+1, -1, +1],
  [-1, +1, +1],
  [+1, +1, +1],
  [-1, -1, +1],
  [+1, +1, -1],
  [-1, -1, -1],
]

// This is what an Ingredient looks like:
var exampleIngredientA = 4
var exampleIngredientB = 5

// This is what a Potion looks like:
var examplePotionA = [0, 0, 1] // this is a blue+
var examplePotionB = [0, 0, 0] // this is soup

// This is what a Fact looks like:
// {
//   ingredients: [5, 7]
//   possibleResults: [true, false, false, false, false, false, true]
// }
// combining ingredient 5 and 7 make either a red+ or a soup
var exampleFact = {
  ingredients: [exampleIngredientA, exampleIngredientB],
  possibleResults: [examplePotionA, examplePotionB]
}

console.log(check(exampleFact, exampleWorld))

export default AlchemistsSolverApp;
<|endoftext|>


<commit_before>var app = angular.module('app', [
        'ngResource',
        'ngRoute'
        ]);

app.factory('csrfReset', ['$q', '$injector', '$browser', function($q, $injector, $browser) {
    var csrfReset = {};

    csrfReset.responseError = function(response) {
        // When the CSRF token fails, we get back a new one in a cookie, retry
        // the request with the new token.
        if (response.status == 400 && typeof response.data.errors.csrf !== null) {
            var $http = $injector.get('$http');
            var httpConfig = response.config;

            // Get the new xsrfValue from the cookies
            var xsrfValue = $browser.cookies()[$http.defaults.xsrfCookieName];

            if (xsrfValue) {
                httpConfig.headers[$http.defaults.xsrfHeaderName] = xsrfValue;
            }

            // Return the new request
            return $http(httpConfig);
        }

        return $q.reject(response);
    };

    return csrfReset;
}]);

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token';
    $httpProvider.defaults.xsrfCookieName = 'CSRF-Token';
    $httpProvider.interceptors.push('csrfReset');
}]);

app.directive('serverError', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, element, attrs, ctrl) {
            element.on('input', function() {
                scope.$apply(
                    function() {
                        ctrl.$setValidity('server', true);
                    })
                }
            );
        }
    };
});

<commit_msg>Add some logging for the CSRF Reset<commit_after>var app = angular.module('app', [
        'ngResource',
        'ngRoute'
        ]);

app.factory('csrfReset', ['$q', '$injector', '$browser', '$log', function($q, $injector, $browser, $log) {
    var csrfReset = {};

    csrfReset.responseError = function(response) {
        // When the CSRF token fails, we get back a new one in a cookie, retry
        // the request with the new token.
        if (response.status == 400 && typeof response.data.errors.csrf !== null) {
            $log.debug('CSRF token was invalid, going to re-run request');
            var $http = $injector.get('$http');
            var httpConfig = response.config;

            // Get the new xsrfValue from the cookies
            var xsrfValue = $browser.cookies()[$http.defaults.xsrfCookieName];

            if (xsrfValue) {
                httpConfig.headers[$http.defaults.xsrfHeaderName] = xsrfValue;
            }

            // Return the new request
            return $http(httpConfig);
        }

        return $q.reject(response);
    };

    return csrfReset;
}]);

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token';
    $httpProvider.defaults.xsrfCookieName = 'CSRF-Token';
    $httpProvider.interceptors.push('csrfReset');
}]);

app.directive('serverError', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, element, attrs, ctrl) {
            element.on('input', function() {
                scope.$apply(
                    function() {
                        ctrl.$setValidity('server', true);
                    })
                }
            );
        }
    };
});

<|endoftext|>


<commit_before>// ==UserScript==
// @name         GitHub Utils
// @description  Something will go here...
// @version      0.3.1
// @updateURL    https://github.com/dracco1993/GitHubUtils/raw/master/githubutils.user.js
// @downloadURL  https://github.com/dracco1993/GitHubUtils/raw/master/githubutils.user.js
// @author       @dracco1993
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js
// @match        http://*.github.com/*/pulls*
// @match        https://*.github.com/*/pulls*
// @grant        none
// ==/UserScript==

// global variables
var username;
var urlMatcher = /(?:\/.+?){2}\/pulls/;

(function () {
  'use strict';
  init();

  document.addEventListener('pjax:end', function () {
    if (Array.isArray(window.location.pathname.match(urlMatcher))) {
      init();
    }
  });
}());

function init() {
  username = getUsername();

  $('.Box-row').each(function (k, v) {
    var temp = $(v).find('div.table-fixed > div > a')[0];

    $.ajax({
      url: temp.href,
      success: function (result) {
        var temp = $('<div/>').html(result).contents();
        getComments(temp);
      }
    });
  });
}

function getUsername() {
  return $('.dropdown-header .css-truncate-target').text();
}

function getComments(source) {
  var content = source.find('.js-comment-container');
  var prNumber = source.find('.gh-header-number').first().text().slice(1);
  var prDescription = content.slice(0, 1);
  var newComment = content.slice(-1, 1);
  var comments = content.slice(1, content.length - 1);
  var location = $('#issue_' + prNumber)[0];
  var timelineComments = source.find('.js-discussion .timeline-comment-wrapper');

  redify(location);

  if (comments.length > 0) {
    var lastComment = getLastComment(comments);
    var lastUserComment = getLastComment(comments, username);
    //var src = $(lastComment).find('.timeline-comment-avatar')[0].src;
    //addIcon(location, src, lastComment, prNumber);

    if (typeof (lastUserComment) !== 'undefined') {
      greenify(location);
    }
  } else {
    yellowify(location);
  }

  if (timelineComments.length > 0) {
    var lastUserCodeComment = getLastComment(timelineComments, username);
    if (typeof (lastUserCodeComment) !== 'undefined') {
      greenify(location);
    }
  }
}

function addIcon(location, source, content, prNumber) {
  var temp = $(location).find('.lh-condensed')[0];
  var href = $(content).find("a[href^='#issuecomment']")[0];
  href = $(href).attr('href');
  var url = window.location.href.replace(/(pulls.*)/g, '');
  var link = $('<a>', {
    href: url + 'pull/' + prNumber + href
  });
  var image = link.append($('<img>', {
    src: source,
    width: 44
  }));
  $(temp).append(image);
}

function getLastComment(comments, tempuser) {
  if (typeof (tempuser) !== 'undefined') {
    // Username passed
    var lastComment;
    $.each(comments, function (i, comment) {
      if ($(comment).find('img')[0].alt.slice(1) === tempuser) {
        lastComment = comment;
      }
    });
    return lastComment;
  } else {
    // No username passed
    return comments[comments.length - 1];
  }
}

function setStyle(location, style) {
  $(location).css(style);
}

function redify(location) {
  setStyle(location, {
    'background-color': '#FFEC94'
  });
}

function yellowify(location) {
  setStyle(location, {
    'background-color': '#FFAEAE'
  });
}

function greenify(location) {
  setStyle(location, {
    'background-color': '#B0E57C'
  });
}
<commit_msg>Fix plugin loading issue<commit_after>// ==UserScript==
// @name         GitHub Utils
// @description  Something will go here...
// @version      0.4.0
// @updateURL    https://github.com/dracco1993/GitHubUtils/raw/master/githubutils.user.js
// @downloadURL  https://github.com/dracco1993/GitHubUtils/raw/master/githubutils.user.js
// @author       @dracco1993
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js
// @match        http://*.github.com/*
// @match        https://*.github.com/*
// @grant        none
// ==/UserScript==

// global variables
var username;
var urlMatcher = /(?:\/.+?){2}\/pulls/;

(function () {
  'use strict';
  if (Array.isArray(window.location.pathname.match(urlMatcher))) {
    init();
  }

  document.addEventListener('pjax:end', function () {
    if (Array.isArray(window.location.pathname.match(urlMatcher))) {
      init();
    }
  });
}());

function init() {
  username = getUsername();

  $('.Box-row').each(function (k, v) {
    var temp = $(v).find('div.table-fixed > div > a')[0];

    $.ajax({
      url: temp.href,
      success: function (result) {
        var temp = $('<div/>').html(result).contents();
        getComments(temp);
      }
    });
  });
}

function getUsername() {
  return $('.dropdown-header .css-truncate-target').text();
}

function getComments(source) {
  var content = source.find('.js-comment-container');
  var prNumber = source.find('.gh-header-number').first().text().slice(1);
  var prDescription = content.slice(0, 1);
  var newComment = content.slice(-1, 1);
  var comments = content.slice(1, content.length - 1);
  var location = $('#issue_' + prNumber)[0];
  var timelineComments = source.find('.js-discussion .timeline-comment-wrapper');

  redify(location);

  if (comments.length > 0) {
    var lastComment = getLastComment(comments);
    var lastUserComment = getLastComment(comments, username);
    //var src = $(lastComment).find('.timeline-comment-avatar')[0].src;
    //addIcon(location, src, lastComment, prNumber);

    if (typeof (lastUserComment) !== 'undefined') {
      greenify(location);
    }
  } else {
    yellowify(location);
  }

  if (timelineComments.length > 0) {
    var lastUserCodeComment = getLastComment(timelineComments, username);
    if (typeof (lastUserCodeComment) !== 'undefined') {
      greenify(location);
    }
  }
}

function addIcon(location, source, content, prNumber) {
  var temp = $(location).find('.lh-condensed')[0];
  var href = $(content).find("a[href^='#issuecomment']")[0];
  href = $(href).attr('href');
  var url = window.location.href.replace(/(pulls.*)/g, '');
  var link = $('<a>', {
    href: url + 'pull/' + prNumber + href
  });
  var image = link.append($('<img>', {
    src: source,
    width: 44
  }));
  $(temp).append(image);
}

function getLastComment(comments, tempuser) {
  if (typeof (tempuser) !== 'undefined') {
    // Username passed
    var lastComment;
    $.each(comments, function (i, comment) {
      if ($(comment).find('img')[0].alt.slice(1) === tempuser) {
        lastComment = comment;
      }
    });
    return lastComment;
  } else {
    // No username passed
    return comments[comments.length - 1];
  }
}

function setStyle(location, style) {
  $(location).css(style);
}

function redify(location) {
  setStyle(location, {
    'background-color': '#FFEC94'
  });
}

function yellowify(location) {
  setStyle(location, {
    'background-color': '#FFAEAE'
  });
}

function greenify(location) {
  setStyle(location, {
    'background-color': '#B0E57C'
  });
}
<|endoftext|>


<commit_before>exports.config = {
    seleniumAddress: 'http://192.168.2.130:4444/wd/hub',
    getPageTimeout: 600001,
    allScriptsTimeout: 5000001,
    framework: 'custom',
    // path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    capabilities: {
        'browserName': 'internet explorer',
    },

    // Spec patterns are relative to this directory.
    specs: [
        'test/e2e/features/e2e.feature'
    ],

    ignoreUncaughtExceptions: true,

    baseUrl: 'https://www.google.nl/',

    cucumberOpts: {
        require: ['test/e2e/features/step_definitions/*.js',
        'test/e2e/conf/env.js'],
        tags: '@checkApi',
        format: 'pretty',
        profile: false,
        'no-source': true
    },
    onPrepare: function () {
        global.chai = require('chai');
        var chaiAsPromised = require('chai-as-promised')
        chai.use(chaiAsPromised);
        global.expect = chai.expect;
    }
};
<commit_msg>Changed to Edge<commit_after>exports.config = {
    seleniumAddress: 'http://192.168.2.130:4444/wd/hub',
    getPageTimeout: 600001,
    allScriptsTimeout: 5000001,
    framework: 'custom',
    // path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    capabilities: {
        'browserName': 'MicrosoftEdge',
    },

    // Spec patterns are relative to this directory.
    specs: [
        'test/e2e/features/e2e.feature'
    ],

    ignoreUncaughtExceptions: true,

    baseUrl: 'https://www.google.nl/',

    cucumberOpts: {
        require: ['test/e2e/features/step_definitions/*.js',
        'test/e2e/conf/env.js'],
        tags: '@checkApi',
        format: 'pretty',
        profile: false,
        'no-source': true
    },
    onPrepare: function () {
        global.chai = require('chai');
        var chaiAsPromised = require('chai-as-promised')
        chai.use(chaiAsPromised);
        global.expect = chai.expect;
    }
};
<|endoftext|>


<commit_before>exports.config = {
    seleniumAddress: 'http://192.168.2.130:4444/wd/hub',
    getPageTimeout: 600001,
    allScriptsTimeout: 5000001,
    framework: 'custom',
    // path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    capabilities: {
        'browserName': 'MicrosoftEdge',
    },

    // Spec patterns are relative to this directory.
    specs: [
        'test/e2e/features/e2e.feature'
    ],

    ignoreUncaughtExceptions: true,

    baseUrl: 'https://www.google.nl/',

    cucumberOpts: {
        require: ['test/e2e/features/step_definitions/*.js',
        'test/e2e/conf/env.js'],
        tags: '@checkApi',
        format: 'pretty',
        profile: false,
        'no-source': true
    },
    onPrepare: function () {
        global.chai = require('chai');
        var chaiAsPromised = require('chai-as-promised')
        chai.use(chaiAsPromised);
        global.expect = chai.expect;
    }
};
<commit_msg>Changed back to Internet Exploder again<commit_after>exports.config = {
    seleniumAddress: 'http://192.168.2.130:4444/wd/hub',
    getPageTimeout: 600001,
    allScriptsTimeout: 5000001,
    framework: 'custom',
    // path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    capabilities: {
        'browserName': 'internet explorer',
    },

    // Spec patterns are relative to this directory.
    specs: [
        'test/e2e/features/e2e.feature'
    ],

    ignoreUncaughtExceptions: true,

    baseUrl: 'https://www.google.nl/',

    cucumberOpts: {
        require: ['test/e2e/features/step_definitions/*.js',
        'test/e2e/conf/env.js'],
        tags: '@checkApi',
        format: 'pretty',
        profile: false,
        'no-source': true
    },
    onPrepare: function () {
        global.chai = require('chai');
        var chaiAsPromised = require('chai-as-promised')
        chai.use(chaiAsPromised);
        global.expect = chai.expect;
    }
};
<|endoftext|>


<commit_before>"use strict";
// Log class

var config    = require('./config');
var plugins;
var connection;
var outbound;
var constants = require('./constants');
var util      = require('util');

var logger = exports;

logger.LOGDATA      = 9;
logger.LOGPROTOCOL  = 8;
logger.LOGDEBUG     = 7;
logger.LOGINFO      = 6;
logger.LOGNOTICE    = 5;
logger.LOGWARN      = 4;
logger.LOGERROR     = 3;
logger.LOGCRIT      = 2;
logger.LOGALERT     = 1;
logger.LOGEMERG     = 0;

var color_functions = {
    "DATA" : "green",
    "PROTOCOL" : "green",
    "DEBUG" : "grey",
    "INFO" : "cyan",
    "info" : "cyan",
    "NOTICE" : "blue",
    "WARN" : "red",
    "ERROR" : "red",
    "CRIT" : "red",
    "ALERT" : "red",
    "EMERG" : "red"
};

function colorize (color, str) {
    if (!util.inspect.colors[color]) return str;
    return '\u001b[' + util.inspect.colors[color][0] + 'm' + str +
              '\u001b[' + util.inspect.colors[color][1] + 'm';
}

var loglevel = logger.LOGWARN;

var deferred_logs = [];

logger.dump_logs = function (exit) {
    while (deferred_logs.length > 0) {
        var log_item = deferred_logs.shift();
        var color;
        if (color_functions) {
            color = color_functions[log_item.level];
        }
        if (color) {
            console.log(colorize(color,log_item.data));
        }
        else {
            console.log(log_item.data);
        }
    }
    if (exit) {
        process.exit(1);
    }
}

logger.log = function (level, data) {
    if (level === 'PROTOCOL') {
        data = data.replace(/\n/g, '\\n\n');
    }
    data = data.replace(/\r/g, '\\r')
               .replace(/\n$/, '');
    // todo - just buffer these up (defer) until plugins are loaded
    if (plugins && plugins.plugin_list) {
        while (deferred_logs.length > 0) {
            var log_item = deferred_logs.shift();
            plugins.run_hooks('log', logger, log_item);
        }
        plugins.run_hooks('log', logger, {
            'level' : level,
            'data'  : data
        });
    }
    else {
        deferred_logs.push({
            'level' : level,
            'data'  : data
        });
    }
}

logger.log_respond = function (retval, msg, data) {
    // any other return code is irrelevant
    if (retval === constants.cont) {
        var color;
        if (color_functions) {
            color = color_functions[data.level]
        }
        if (color) {
            return console.log(colorize(color,data.data));
        }
        else {
            return console.log(data.data);
        }
    }
};

logger._init_loglevel = function () {
    var self = this;
    var _loglevel = config.get('loglevel', 'value', function () {
        self._init_loglevel();
    });
    if (_loglevel) {
        var loglevel_num = parseInt(_loglevel);
        if (!loglevel_num || loglevel_num === NaN) {
            this.log('info', 'loglevel: ' + _loglevel.toUpperCase());
            loglevel = logger[_loglevel.toUpperCase()];
        }
        else {
            loglevel = loglevel_num;
        }
        if (!loglevel) {
            loglevel = logger.LOGWARN;
        }
    }
};

logger.would_log = function (level) {
    if (loglevel < level) return false;
    return true;
}

logger._init_loglevel();

var level, key;
for (key in logger) {
    if(logger.hasOwnProperty(key)) {
        if (key.match(/^LOG\w/)) {
            level = key.slice(3);
            logger[key.toLowerCase()] = (function(level, key) {
                return function() {
                    if (loglevel < logger[key])
                        return;
                    var levelstr = "[" + level + "]";
                    var str = "";
                    var uuidstr = "[-]";
                    var pluginstr = "[core]";
                    for (var i = 0; i < arguments.length; i++) {
                        var data = arguments[i];
                        if (typeof(data) === 'object') {
                            // if the object is a connection, we wish to add
                            // the connection id
                            if (data instanceof connection.Connection) {
                                uuidstr = "[" + data.uuid;
                                if (data.tran_count > 0) {
                                  uuidstr += "." + data.tran_count;
                                }
                                uuidstr += "]";
                            }
                            else if (data instanceof plugins.Plugin) {
                                pluginstr = "[" + data.name + "]";
                            }
                            else if (data instanceof outbound.HMailItem) {
                                pluginstr = "[outbound]";
                                if (data.todo && data.todo.uuid) {
                                    uuidstr = "[" + data.todo.uuid + "]";
                                }
                            }
                            else {
                                str += util.inspect(data);
                            }
                        }
                        else {
                            str += data;
                        }
                    }
                    logger.log(level, [levelstr, uuidstr, pluginstr, str].join(" "));
                }
            })(level, key);
        }
    }
}

// load these down here so it sees all the logger methods compiled above
plugins = require('./plugins');
connection = require('./connection');
outbound = require('./outbound');
<commit_msg>print color only if it is console, else normal text<commit_after>"use strict";
// Log class

var config    = require('./config');
var plugins;
var connection;
var outbound;
var constants = require('./constants');
var util      = require('util');
var tty = require('tty')

var logger = exports;

logger.LOGDATA      = 9;
logger.LOGPROTOCOL  = 8;
logger.LOGDEBUG     = 7;
logger.LOGINFO      = 6;
logger.LOGNOTICE    = 5;
logger.LOGWARN      = 4;
logger.LOGERROR     = 3;
logger.LOGCRIT      = 2;
logger.LOGALERT     = 1;
logger.LOGEMERG     = 0;

var color_functions = {
    "DATA" : "green",
    "PROTOCOL" : "green",
    "DEBUG" : "grey",
    "INFO" : "cyan",
    "info" : "cyan",
    "NOTICE" : "blue",
    "WARN" : "red",
    "ERROR" : "red",
    "CRIT" : "red",
    "ALERT" : "red",
    "EMERG" : "red"
};

function colorize (color, str) {
    if (!util.inspect.colors[color]) return str;
    return '\u001b[' + util.inspect.colors[color][0] + 'm' + str +
              '\u001b[' + util.inspect.colors[color][1] + 'm';
}

var loglevel = logger.LOGWARN;

var deferred_logs = [];

logger.dump_logs = function (exit) {
    while (deferred_logs.length > 0) {
        var log_item = deferred_logs.shift();
        var color;
        if (color_functions) {
            color = color_functions[log_item.level];
        }
        if (color && tty.isatty(process.stdout.fd)) {
            console.log(colorize(color,log_item.data));
        }
        else {
            console.log(log_item.data);
        }
    }
    if (exit) {
        process.exit(1);
    }
}

logger.log = function (level, data) {
    if (level === 'PROTOCOL') {
        data = data.replace(/\n/g, '\\n\n');
    }
    data = data.replace(/\r/g, '\\r')
               .replace(/\n$/, '');
    // todo - just buffer these up (defer) until plugins are loaded
    if (plugins && plugins.plugin_list) {
        while (deferred_logs.length > 0) {
            var log_item = deferred_logs.shift();
            plugins.run_hooks('log', logger, log_item);
        }
        plugins.run_hooks('log', logger, {
            'level' : level,
            'data'  : data
        });
    }
    else {
        deferred_logs.push({
            'level' : level,
            'data'  : data
        });
    }
}

logger.log_respond = function (retval, msg, data) {
    // any other return code is irrelevant
    if (retval === constants.cont) {
        var color;
        if (color_functions) {
            color = color_functions[data.level]
        }
        if (color && tty.isatty(process.stdout.fd)) {
            return console.log(colorize(color,data.data));
        }
        else {
            return console.log(data.data);
        }
    }
};

logger._init_loglevel = function () {
    var self = this;
    var _loglevel = config.get('loglevel', 'value', function () {
        self._init_loglevel();
    });
    if (_loglevel) {
        var loglevel_num = parseInt(_loglevel);
        if (!loglevel_num || loglevel_num === NaN) {
            this.log('info', 'loglevel: ' + _loglevel.toUpperCase());
            loglevel = logger[_loglevel.toUpperCase()];
        }
        else {
            loglevel = loglevel_num;
        }
        if (!loglevel) {
            loglevel = logger.LOGWARN;
        }
    }
};

logger.would_log = function (level) {
    if (loglevel < level) return false;
    return true;
}

logger._init_loglevel();

var level, key;
for (key in logger) {
    if(logger.hasOwnProperty(key)) {
        if (key.match(/^LOG\w/)) {
            level = key.slice(3);
            logger[key.toLowerCase()] = (function(level, key) {
                return function() {
                    if (loglevel < logger[key])
                        return;
                    var levelstr = "[" + level + "]";
                    var str = "";
                    var uuidstr = "[-]";
                    var pluginstr = "[core]";
                    for (var i = 0; i < arguments.length; i++) {
                        var data = arguments[i];
                        if (typeof(data) === 'object') {
                            // if the object is a connection, we wish to add
                            // the connection id
                            if (data instanceof connection.Connection) {
                                uuidstr = "[" + data.uuid;
                                if (data.tran_count > 0) {
                                  uuidstr += "." + data.tran_count;
                                }
                                uuidstr += "]";
                            }
                            else if (data instanceof plugins.Plugin) {
                                pluginstr = "[" + data.name + "]";
                            }
                            else if (data instanceof outbound.HMailItem) {
                                pluginstr = "[outbound]";
                                if (data.todo && data.todo.uuid) {
                                    uuidstr = "[" + data.todo.uuid + "]";
                                }
                            }
                            else {
                                str += util.inspect(data);
                            }
                        }
                        else {
                            str += data;
                        }
                    }
                    logger.log(level, [levelstr, uuidstr, pluginstr, str].join(" "));
                }
            })(level, key);
        }
    }
}

// load these down here so it sees all the logger methods compiled above
plugins = require('./plugins');
connection = require('./connection');
outbound = require('./outbound');
<|endoftext|>


<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var fs = require("fs");

function getTimeString() {
    var d = new Date();
    return d.toDateString() + " " + d.toTimeString().split(" ")[0];
}

var Logger = function(filename) {
    this.dead = false;
    this.filename = filename;
    this.writer = fs.createWriteStream(filename, {
        flags: "a",
        encoding: "utf-8"
    });
}

Logger.prototype.log = function () {
    if(this.dead) {
        Logger.errlog.log("WARNING: Attempted write to dead logger: ", this.filename);
        return;
    }
    var msg = "";
    for(var i in arguments)
        msg += arguments[i];
    var str = "[" + getTimeString() + "] " + msg + "\n";
    this.writer.write(str);
}

Logger.prototype.close = function () {
    this.writer.end("", null, function () {
        this.dead = true;
    });
}

var errlog = new Logger("error.log");
var syslog = new Logger("sys.log");
errlog.actualLog = errlog.log;
errlog.log = function(what) { console.log(what); this.actualLog(what); }
syslog.actualLog = syslog.log;
syslog.log = function(what) { console.log(what); this.actualLog(what); }

exports.Logger = Logger;
exports.errlog = errlog;
exports.syslog = syslog;
<commit_msg>Add close() check<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var fs = require("fs");

function getTimeString() {
    var d = new Date();
    return d.toDateString() + " " + d.toTimeString().split(" ")[0];
}

var Logger = function(filename) {
    this.dead = false;
    this.filename = filename;
    this.writer = fs.createWriteStream(filename, {
        flags: "a",
        encoding: "utf-8"
    });
}

Logger.prototype.log = function () {
    if(this.dead) {
        errlog.log("WARNING: Attempted write to dead logger: ", this.filename);
        return;
    }
    var msg = "";
    for(var i in arguments)
        msg += arguments[i];
    var str = "[" + getTimeString() + "] " + msg + "\n";
    this.writer.write(str);
}

Logger.prototype.close = function () {
    if(this.dead) {
        errlog.log("WARNING: Attempted closure on dead logger: ", this.filename);
        return;
    }
    this.writer.end("", null, function () {
        this.dead = true;
    });
}

var errlog = new Logger("error.log");
var syslog = new Logger("sys.log");
errlog.actualLog = errlog.log;
errlog.log = function(what) { console.log(what); this.actualLog(what); }
syslog.actualLog = syslog.log;
syslog.log = function(what) { console.log(what); this.actualLog(what); }

exports.Logger = Logger;
exports.errlog = errlog;
exports.syslog = syslog;
<|endoftext|>