<commit_before>define(function(require, exports, module) {
    require("converters/all");
    var BitArray = require("modules/multivalue/bitArray");
    var Base64 = require("modules/multivalue/base64");
    var Base64Url = require("modules/multivalue/base64url");
    var BigItnSjcl = require("modules/multivalue/bigIntSjcl");
    var Bytes = require("modules/multivalue/bytes");
    var DecBlocks = require("modules/multivalue/decBlocks");
    var Hex = require("modules/multivalue/hex");
    var Utf8String = require("modules/multivalue/utf8string");
    var X32WordArray = require("modules/multivalue/x32wordArray");
    var Bn = require("modules/sjcl/bn");

    var values = {
        BitArray: new BitArray([1400140393, 1852252269, 1702064993, 1734680881]),
        Base64: new Base64("U3RyaW5nIG1lc3NhZ2UhMQ=="),
        Base64Url: new Base64Url("U3RyaW5nIG1lc3NhZ2UhMQ"),
        BigItnSjcl: new BigItnSjcl(new Bn("0x537472696E67206D6573736167652131")),
        Bytes: new Bytes([83, 116, 114, 105, 110, 103, 32, 109, 101, 115, 115, 97, 103, 101, 33, 49]),
        DecBlocks: new DecBlocks("110930550633557961317610434596264288561"),
        Hex: new Hex("537472696E67206D6573736167652131"),
        Utf8String: new Utf8String("String message!1"),
        X32WordArray: new X32WordArray([1400140393, 1852252269, 1702064993, 1734680881], 16),
    }
    var types = {
        BitArray: BitArray,
        Base64: Base64,
        Base64Url: Base64Url,
        BigItnSjcl: BigItnSjcl,
        Bytes: Bytes,
        DecBlocks: DecBlocks,
        Hex: Hex,
        Utf8String: Utf8String,
        X32WordArray: X32WordArray,
    }

    function second(from, to)
    {
        it('to ' + to, function() {
            var result = values[from].as(types[to]);
            console.log(from, to, values[from], values[to], result)
            expect(result).be.instanceof(types[to]).with.property("value")
            expect(result.isEqualTo(values[to])).true;
        });

    }

    function first(from)
    {
        describe('converts ' + from, function() {
            for(var name in values)
            {
                second(from, name);
            }
        });
    }

    describe('Multivalue', function() {
        for(var name in values)
        {
            first(name);
        }
    });
});
<commit_msg>failing test<commit_after>define(function(require, exports, module) {
    require("converters/all");
    var BitArray = require("modules/multivalue/bitArray");
    var Base64 = require("modules/multivalue/base64");
    var Base64Url = require("modules/multivalue/base64url");
    var BigItnSjcl = require("modules/multivalue/bigIntSjcl");
    var Bytes = require("modules/multivalue/bytes");
    var DecBlocks = require("modules/multivalue/decBlocks");
    var Hex = require("modules/multivalue/hex");
    var Utf8String = require("modules/multivalue/utf8string");
    var X32WordArray = require("modules/multivalue/x32wordArray");
    var Bn = require("modules/sjcl/bn");

    var values = {
        BitArray: new BitArray([1400140393, 1852252269, 1702064993, 1734680881]),
        Base64: new Base64("U3RyaW5nIG1lc3NhZ2UhMQ=="),
        Base64Url: new Base64Url("U3RyaW5nIG1lc3NhZ2UhMQ"),
        BigItnSjcl: new BigItnSjcl(new Bn("0x537472696E67206D6573736167652131")),
        Bytes: new Bytes([83, 116, 114, 105, 110, 103, 32, 109, 101, 115, 115, 97, 103, 101, 33, 49]),
        DecBlocks: new DecBlocks("110930550633557961317610434596264288561"),
        Hex: new Hex("537472696E67206D6573736167652131"),
        Utf8String: new Utf8String("String message!1"),
        X32WordArray: new X32WordArray([1400140393, 1852252269, 1702064993, 1734680881], 16),
    }
    var types = {
        BitArray: BitArray,
        Base64: Base64,
        Base64Url: Base64Url,
        BigItnSjcl: BigItnSjcl,
        Bytes: Bytes,
        DecBlocks: DecBlocks,
        Hex: Hex,
        Utf8String: Utf8String,
        X32WordArray: X32WordArray,
    }

    function second(from, to)
    {
        it('to ' + to, function() {
            var result = values[from].as(types[to]);
            console.log(from, to, values[from], values[to], result)
            expect(result).be.instanceof(types[to]).with.property("value")
            expect(result.isEqualTo(values[to])).true;
        });

    }

    function first(from)
    {
        describe('converts ' + from, function() {
            for(var name in values)
            {
                second(from, name);
            }
        });
    }

    describe('Multivalue', function() {
        for(var name in values)
        {
            first(name);
        }
    });

    it("Bug from real world #1", function() {
        expect(new Bytes([8, 169, 157, 10, 239, 70, 62, 210, 33, 191, 147, 235, 135, 251, 83, 224]).as(BitArray).bitLength()).to.equals(128);
        expect(new Bytes([8, 169, 157, 10, 239, 70, 62, 210, 33, 191, 147, 235, 135, 251, 83, 224]).as(DecBlocks).as(Hex).as(BitArray).bitLength()).to.equals(128);
    });

});
<|endoftext|>


<commit_before>// This object allows the user to perform multiple calculations over multiple cores
//

// Example usage:
// ScriptName="SimulationToRun.js";
// CommonData=[InfoBlock];//All sims will have access to this information
// SimSpecificDataArray=[67, 33, 99, 55, 88];//can be an array of any type (including other classes). Uses array length to determine the number of simulations to run.
// NoCores=6;//The number of cores you want the simulation to run over
// SimulationObject=new MulticoreSim(ScriptName, CommonData, SimSpecificDataArray, NoCores); // getting it ready
// SimulationObject.Start(); // Start the simulations running

// Sample set up of SimulationToRun.js
// ----------------------------------------------------------
// importScripts("usefulscripts1.js", "usefulscripts2.js");//Scripts your function needs to use (note; only scripts in the same folder can be used)
//
// self.onmessage = function (e) {
// 		var SimNumber = e.data.SimNumber;
// 		var SimData = e.data.SimData;
// 		var CommonData = e.data.CommonData;
//
//		...//Where you do the calculations
//
//		Result.Value1=24;//Stores the results
//		Result.Value2=25;
//
//		self.postMessage({SimNumber: e.data.SimNumber, Result: Result});//All simulations should end with this line
//}

function MulticoreSim(ScriptName, CommonData, SimDataArray, NoCores){

	this.ScriptName=ScriptName;
	this.CommonData=CommonData;
	this.SimDataArray=SimDataArray;//an array of values or objects to be passed to the specified script
	this.NoCores=NoCores;
	this.Worker=[];//An array of workers
	this.NoSims=SimDataArray.length;

	this.CurrentlyRunning=false;
	this.Complete=false;
	this.NoSimsCurrentlyRunning=0;

	this.SimsStarted=0;
	this.SimsComplete=0;
	this.Result=[];

	this.UseSimProgressBar=false;
	this.SimProgressBarID="SimProgressBar";//To allow a progress bar to be installed into the page
	this.UseWithinSimProgressBar=false;
	this.WithinSimProgressBarID="WithinSimProgressBar";

}

MulticoreSim.prototype.Start=function() {

	//Check that nothing else is running
	if (this.CurrentlyRunning==true){
		console.log("Warning: worker currently running");
		return 0;
	};
	this.CurrentlyRunning=true;
	this.NoSimsCurrentlyRunning=0;
	this.Complete=false;

	// Set progress bar to zero
	if (this.UseSimProgressBar==true){
		document.getElementById(this.NoSimsCompleteProgressBarID).value=0;
	}

	//Create workers
	this.RampUpSims();
};

MulticoreSim.prototype.RampUpSims=function() {

	MoreSimsToRun=true;//flag to prevent continually trying to run more sims
	while (this.NoSimsCurrentlyRunning<this.NoCores &&  MoreSimsToRun==true){//there are spare cores available
		if (this.SimsStarted<this.NoSims){//if there are sims that have yet to be started
			SimID=this.SimsStarted++;//run this sim, increment by 1
			this.NoSimsCurrentlyRunning++;//indicate that another core has become used

			this.Worker= new Worker(this.ScriptName);

			var BoundMessage=MulticoreSimMessageHandler.bind(this);
			this.Worker.onmessage = BoundMessage;

			this.Worker.postMessage({ SimNumber: SimID, CommonData: this.CommonData, SimData: this.SimDataArray[SimID]});
		}
		else{ //there are no more sims to run
			MoreSimsToRun=false;
		}

	}

	//Determine if this is the last sim to complete
	if (this.SimsComplete>=this.NoSims){
		this.Complete=true;
		this.Terminate();//close all the workers
	}
}

MulticoreSimMessageHandler=function(e) {
	// There are 3 main message types that are handled
	// Messages to the StatusText (to be put somewhere on screen to indicate what is currently occurring)
	// Messages to the ProgressBar
	// Message to return result/indicate completeness

	// Messages to the StatusText
	if (typeof e.data.StatusText != 'undefined'){
		console.log(e.data.WorkerStatusText);
	}
	// Messages to the ProgressBar
	if (typeof e.data.ProgressBarValue != 'undefined'){
		if (this.UseSimProgressBar==true){
			document.getElementById(this.WithinSimProgressBarID).value=e.data.ProgressBarValue;
		}
	}
	if (typeof e.data.Result != 'undefined'){
		this.NoSimsCurrentlyRunning--;
		SimNumber=e.data.SimNumber;
		this.Result[SimNumber]=e.data.Result;//Store the results of the simulation
		this.SimsComplete++;

		this.RampUpSims();//Try to run more sims

		//Update the progress bar about completion
		if (this.UseSimProgressBar==true){
			document.getElementById(this.NoSimsCompleteProgressBarID).value=this.SimsComplete/this.NoSims;
		}
	}
};

MulticoreSim.prototype.Terminate=function() {//close down all workers
	this.Worker.terminate();
	this.CurrentlyRunning==false;
};

<commit_msg>Making comment about transferable objects<commit_after>// This object allows the user to perform multiple calculations over multiple cores
//

// Example usage:
// ScriptName="SimulationToRun.js";
// CommonData=[InfoBlock];//All sims will have access to this information
// SimSpecificDataArray=[67, 33, 99, 55, 88];//can be an array of any type (including other classes). Uses array length to determine the number of simulations to run.
// NoCores=6;//The number of cores you want the simulation to run over
// SimulationObject=new MulticoreSim(ScriptName, CommonData, SimSpecificDataArray, NoCores); // getting it ready
// SimulationObject.Start(); // Start the simulations running

// Sample set up of SimulationToRun.js
// ----------------------------------------------------------
// importScripts("usefulscripts1.js", "usefulscripts2.js");//Scripts your function needs to use (note; only scripts in the same folder can be used)
//
// self.onmessage = function (e) {
// 		var SimNumber = e.data.SimNumber;
// 		var SimData = e.data.SimData;
// 		var CommonData = e.data.CommonData;
//
//		...//Where you do the calculations
//
//		Result.Value1=24;//Stores the results
//		Result.Value2=25;
//
//		self.postMessage({SimNumber: e.data.SimNumber, Result: Result});//All simulations should end with this line
//}

// To use transferable objects http://stackoverflow.com/questions/16071211/using-transferable-objects-from-a-web-worker/16766758#16766758

function MulticoreSim(ScriptName, CommonData, SimDataArray, NoCores){

	this.ScriptName=ScriptName;
	this.CommonData=CommonData;
	this.SimDataArray=SimDataArray;//an array of values or objects to be passed to the specified script
	this.NoCores=NoCores;
	this.Worker=[];//An array of workers
	this.NoSims=SimDataArray.length;

	this.CurrentlyRunning=false;
	this.Complete=false;
	this.NoSimsCurrentlyRunning=0;

	this.SimsStarted=0;
	this.SimsComplete=0;
	this.Result=[];

	this.UseSimProgressBar=false;
	this.SimProgressBarID="SimProgressBar";//To allow a progress bar to be installed into the page
	this.UseWithinSimProgressBar=false;
	this.WithinSimProgressBarID="WithinSimProgressBar";

}

MulticoreSim.prototype.Start=function() {

	//Check that nothing else is running
	if (this.CurrentlyRunning==true){
		console.log("Warning: worker currently running");
		return 0;
	};
	this.CurrentlyRunning=true;
	this.NoSimsCurrentlyRunning=0;
	this.Complete=false;

	// Set progress bar to zero
	if (this.UseSimProgressBar==true){
		document.getElementById(this.NoSimsCompleteProgressBarID).value=0;
	}

	//Create workers
	this.RampUpSims();
};

MulticoreSim.prototype.RampUpSims=function() {

	MoreSimsToRun=true;//flag to prevent continually trying to run more sims
	while (this.NoSimsCurrentlyRunning<this.NoCores &&  MoreSimsToRun==true){//there are spare cores available
		if (this.SimsStarted<this.NoSims){//if there are sims that have yet to be started
			SimID=this.SimsStarted++;//run this sim, increment by 1
			this.NoSimsCurrentlyRunning++;//indicate that another core has become used

			this.Worker= new Worker(this.ScriptName);

			var BoundMessage=MulticoreSimMessageHandler.bind(this);
			this.Worker.onmessage = BoundMessage;

			this.Worker.postMessage({ SimNumber: SimID, CommonData: this.CommonData, SimData: this.SimDataArray[SimID]});
		}
		else{ //there are no more sims to run
			MoreSimsToRun=false;
		}

	}

	//Determine if this is the last sim to complete
	if (this.SimsComplete>=this.NoSims){
		this.Complete=true;
		this.Terminate();//close all the workers
	}
}

MulticoreSimMessageHandler=function(e) {
	// There are 3 main message types that are handled
	// Messages to the StatusText (to be put somewhere on screen to indicate what is currently occurring)
	// Messages to the ProgressBar
	// Message to return result/indicate completeness

	// Messages to the StatusText
	if (typeof e.data.StatusText != 'undefined'){
		console.log(e.data.WorkerStatusText);
	}
	// Messages to the ProgressBar
	if (typeof e.data.ProgressBarValue != 'undefined'){
		if (this.UseSimProgressBar==true){
			document.getElementById(this.WithinSimProgressBarID).value=e.data.ProgressBarValue;
		}
	}
	if (typeof e.data.Result != 'undefined'){
		this.NoSimsCurrentlyRunning--;
		SimNumber=e.data.SimNumber;
		this.Result[SimNumber]=e.data.Result;//Store the results of the simulation
		this.SimsComplete++;

		this.RampUpSims();//Try to run more sims

		//Update the progress bar about completion
		if (this.UseSimProgressBar==true){
			document.getElementById(this.NoSimsCompleteProgressBarID).value=this.SimsComplete/this.NoSims;
		}
	}
};

MulticoreSim.prototype.Terminate=function() {//close down all workers
	this.Worker.terminate();
	this.CurrentlyRunning==false;
};

<|endoftext|>


<commit_before>import { createStore, applyMiddleware, compose } from 'redux';
import { syncHistory } from 'react-router-redux';
import { browserHistory } from 'react-router';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
import createLogger from 'redux-logger';
import DevTools from '../containers/DevTools';
import * as actionTypes from '../actions';

const reduxRouterMiddleware = syncHistory(browserHistory);

const reduxLoggerOptions = {
	predicate(getState, action) {
		// Exclude these actions from being logged.
		const actionBlacklist = [
			actionTypes.TICK_TRIP_CLOCK
		];

		for (let actionType of actionBlacklist) {
			if (action.type === actionType) {
				return false;
			}
		}

		return true;
	}
};

export default function configureStore(initialState) {
	const store = createStore(
		rootReducer,
		initialState,
		compose(
			applyMiddleware(thunk, reduxRouterMiddleware, createLogger(reduxLoggerOptions)),
			DevTools.instrument()
		)
	);

	// Required for replaying actions from devtools to work.
	reduxRouterMiddleware.listenForReplays(store);

	if (module.hot) {
		// Enable Webpack hot module replacement for reducers.
		module.hot.accept('../reducers', () => {
			const nextRootReducer = require('../reducers').default;
			store.replaceReducer(nextRootReducer);
		});
	}

	return store;
}
<commit_msg>Integrate Redux devtools Chrome extension<commit_after>import { createStore, applyMiddleware, compose } from 'redux';
import { syncHistory } from 'react-router-redux';
import { browserHistory } from 'react-router';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
import createLogger from 'redux-logger';
import * as actionTypes from '../actions';

const reduxRouterMiddleware = syncHistory(browserHistory);

const reduxLoggerOptions = {
	predicate(getState, action) {
		// Exclude these actions from being logged.
		const actionBlacklist = [
			actionTypes.TICK_TRIP_CLOCK
		];

		for (let actionType of actionBlacklist) {
			if (action.type === actionType) {
				return false;
			}
		}

		return true;
	}
};

export default function configureStore(initialState) {
	const store = createStore(
		rootReducer,
		initialState,
		compose(
			applyMiddleware(thunk, reduxRouterMiddleware, createLogger(reduxLoggerOptions)),
			window.devToolsExtension ? window.devToolsExtension() : f => f
		)
	);

	// Required for replaying actions from devtools to work.
	reduxRouterMiddleware.listenForReplays(store);

	if (module.hot) {
		// Enable Webpack hot module replacement for reducers.
		module.hot.accept('../reducers', () => {
			const nextRootReducer = require('../reducers').default;
			store.replaceReducer(nextRootReducer);
		});
	}

	return store;
}
<|endoftext|>


<commit_before>/*
 * https://github.com/starzou
 *
 * Copyright (c) 2014 StarZou
 * Licensed under the MIT license.
 */

/**
 * @class 1
 * @description
 * @time 2015-01-30 20:21
 * @author StarZou
 **/
(function (window, document) {
    'use strict';
    console.log('jquery 研究...');

})(window, document);<commit_msg>jquery<commit_after>/*
 * https://github.com/starzou
 *
 * Copyright (c) 2014 StarZou
 * Licensed under the MIT license.
 */

/**
 * @class 1
 * @description
 * @time 2015-01-30 20:21
 * @author StarZou
 **/
(function (window, document) {
    'use strict';
    var title = 'jquery 研究...';
    console.log(title);

    var h1 = $('h1');
    console.log(h1);

})(window, document);<|endoftext|>


<commit_before>// Minify PNG, JPEG and GIF images
// grunt-contrib-imagemin: <https://github.com/gruntjs/grunt-contrib-imagemin>

'use strict';

var fs = require('fs');

module.exports = {

  // Distribution
  dist: {
    files: [{
      expand: true,
      cwd: '<%%= path.dist %>',
      dest: '<%%= path.dist %>',
      src: [
        '**/*.{png,jpg,gif<% if (cfg.svgo) { %>,svg<% } %>}'
      ],
      filter: function (filepath) {
        return fs.readFileSync(filepath).length > 0;
      }
    }]
  }

};
<commit_msg>Update comment in imagemin config<commit_after>// Minify images
// grunt-contrib-imagemin: <https://github.com/gruntjs/grunt-contrib-imagemin>

'use strict';

var fs = require('fs');

module.exports = {

  // Distribution
  dist: {
    files: [{
      expand: true,
      cwd: '<%%= path.dist %>',
      dest: '<%%= path.dist %>',
      src: [
        '**/*.{png,jpg,gif<% if (cfg.svgo) { %>,svg<% } %>}'
      ],
      filter: function (filepath) {
        return fs.readFileSync(filepath).length > 0;
      }
    }]
  }

};
<|endoftext|>


<commit_before>export const createFormattedDate = () => {
  const date = new Date()
  const days = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
  ]
  const months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ]

  return `${days[date.getDay()]} ${date.getDate()} ${
    months[date.getMonth()]
  }  ${date.getHours()}:${date.getMinutes()}`
}
<commit_msg>Alter datehelper to show correct time when date number is less than 10<commit_after>export const createFormattedDate = () => {
  const date = new Date()
  const days = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
  ]
  const months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ]

  const prefix = 0
  const hours = date.getHours()
  const minutes = date.getMinutes()

  return `${days[date.getDay()]} ${date.getDate()} ${
    months[date.getMonth()]
  }  ${hours < 9 ? `${prefix}${hours}` : hours}:${
    minutes < 9 ? `${prefix}${minutes}` : minutes
  }`
}
<|endoftext|>


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

//Shim for Promises
if (typeof Promise == "undefined") {Promise = require("promise");}

//Load in the API initialisers
var endpoints = {collector: require('../collector-api/collector.js')} //The collector API calls
//Visualiser API should go here too

var scope = {restify: require('restify') //API server
    , save: require('save') //Database interface
    , saveMongodb: require('save-mongodb')
    , chance: require('chance').Chance() //Salt generator
    , crypto: require('crypto') //Hasher
    , Db: require('mongodb').Db //MongoDB Database object
    , DbServer: require('mongodb').Server //MongoDB Server object
    , dryrun: false} //Initialise dryrun var

scope.server = scope.restify.createServer({ name: 'motion-logger-full-api'});
scope.portNum = 8080; // Default port for the API server

if (process.argv[2] == "--dryrun") {
    console.log();
    scope.dryrun = true;
} else {
    console.log();
    scope.dryrun = false;
}

var msgs = {dryrun: "Running in normal mode, all data will be saved to the specified DB!\nOpening database..."};
var promArr = [];
var helpshown = false;
for (var i = 2; i < process.argv.length; i++) {
    var arg = process.argv[i];
    if (i == 2 && (arg == "--help" || arg == "-help" || arg == "/h" || arg == "-h")) {
        console.log("Motion Logger Backend API\n\n" +
                    "--dryrun = Store values temporarily, don't store to a database\n"+
                    "--port [port] = Changes the port the server runs on, default is 8080\n" +
                    "-[endpoint initial] = Initialises the endpoints for that module.\n" +
                    "   i.e. -c would initialise the collector module\n" +
                    "--help = Display this help text");
        i = process.argv.length;
        helpshown = true;
    } else if (arg == "--dryrun") {
        msgs.dryrun = "Running in dry run mode, none of the data passed through the API will be saved!";
    } else if (arg == "--port") {
        var portNum = parseInt(process.argv[i+1]);
        if (!isNaN(portNum)) {
            scope.portNum = portNum;
            i++;
        }
    } else if (arg.substr(0,1) == "-") {
        //There are no other arguments other than to specify the endpoints. Loop through and find them.
        arg = arg.substr(1);
        for (var ep in endpoints) {
            if (arg.indexOf(ep.substr(0,1)) != -1) {
                promArr.push(endpoints[ep].init.call(scope));
                console.log("Intialising "+ep+" endpoints...");
                delete endpoints[ep];
            }
        }
    }
}

if (!helpshown) {
    for (var ep in endpoints) {
        console.log(ep + " endpoints are inactive.");
    }

    //When all the initialisation is done, start the server.
    Promise.all(promArr).then(startServer);
}

function startServer(errorReason) {
    if (typeof  errorReason == "string") {
        console.log("An error occurred during initialisation:\n"+errorReason);
    } else {
        console.log(msgs.dryrun);
        scope.server.listen(scope.portNum, function () {
            console.log('%s listening at %s', scope.server.name, scope.server.url)
        });
    }
};<commit_msg>Making the visualiser api endpoints available to the full api.<commit_after>#!/usr/bin/env node

//Shim for Promises
if (typeof Promise == "undefined") {Promise = require("promise");}

//Load in the API initialisers
var endpoints = {collector: require('../collector-api/collector.js'), visualiser: require('../visualiser-api/visualiser.js')} //The collector API calls
//Visualiser API should go here too

var scope = {restify: require('restify') //API server
    , save: require('save') //Database interface
    , saveMongodb: require('save-mongodb')
    , chance: require('chance').Chance() //Salt generator
    , crypto: require('crypto') //Hasher
    , Db: require('mongodb').Db //MongoDB Database object
    , DbServer: require('mongodb').Server //MongoDB Server object
    , dryrun: false} //Initialise dryrun var

scope.server = scope.restify.createServer({ name: 'motion-logger-full-api'});
scope.portNum = 8080; // Default port for the API server

if (process.argv[2] == "--dryrun") {
    console.log();
    scope.dryrun = true;
} else {
    console.log();
    scope.dryrun = false;
}

var msgs = {dryrun: "Running in normal mode, all data will be saved to the specified DB!\nOpening database..."};
var promArr = [];
var helpshown = false;
for (var i = 2; i < process.argv.length; i++) {
    var arg = process.argv[i];
    if (i == 2 && (arg == "--help" || arg == "-help" || arg == "/h" || arg == "-h")) {
        console.log("Motion Logger Backend API\n\n" +
                    "--dryrun = Store values temporarily, don't store to a database\n"+
                    "--port [port] = Changes the port the server runs on, default is 8080\n" +
                    "-[endpoint initial] = Initialises the endpoints for that module.\n" +
                    "   i.e. -c would initialise the collector module\n" +
                    "--help = Display this help text");
        i = process.argv.length;
        helpshown = true;
    } else if (arg == "--dryrun") {
        msgs.dryrun = "Running in dry run mode, none of the data passed through the API will be saved!";
    } else if (arg == "--port") {
        var portNum = parseInt(process.argv[i+1]);
        if (!isNaN(portNum)) {
            scope.portNum = portNum;
            i++;
        }
    } else if (arg.substr(0,1) == "-") {
        //There are no other arguments other than to specify the endpoints. Loop through and find them.
        arg = arg.substr(1);
        for (var ep in endpoints) {
            if (arg.indexOf(ep.substr(0,1)) != -1) {
                promArr.push(endpoints[ep].init.call(scope));
                console.log("Intialising "+ep+" endpoints...");
                delete endpoints[ep];
            }
        }
    }
}

if (!helpshown) {
    for (var ep in endpoints) {
        console.log(ep + " endpoints are inactive.");
    }

    //When all the initialisation is done, start the server.
    Promise.all(promArr).then(startServer);
}

function startServer(errorReason) {
    if (typeof  errorReason == "string") {
        console.log("An error occurred during initialisation:\n"+errorReason);
    } else {
        console.log(msgs.dryrun);
        scope.server.listen(scope.portNum, function () {
            console.log('%s listening at %s', scope.server.name, scope.server.url)
        });
    }
};<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

const validateBoolOption = (name, value, defaultValue) => {
  if (typeof value === 'undefined') {
    value = defaultValue;
  }

  if (typeof value !== 'boolean') {
    throw new Error(`Preset react-app: '${name}' option must be a boolean.`);
  }

  return value;
};

module.exports = function(api, opts, env) {
  if (!opts) {
    opts = {};
  }

  var isEnvDevelopment = env === 'development';
  var isEnvProduction = env === 'production';
  var isEnvTest = env === 'test';
  var isFlowEnabled = validateBoolOption('flow', opts.flow, true);
  var areHelpersEnabled = validateBoolOption('helpers', opts.helpers, true);

  if (!isEnvDevelopment && !isEnvProduction && !isEnvTest) {
    throw new Error(
      'Using `babel-preset-react-app` requires that you specify `NODE_ENV` or ' +
        '`BABEL_ENV` environment variables. Valid values are "development", ' +
        '"test", and "production". Instead, received: ' +
        JSON.stringify(env) +
        '.'
    );
  }

  return {
    presets: [
      isEnvTest && [
        // ES features necessary for user's Node version
        require('@babel/preset-env').default,
        {
          targets: {
            node: 'current',
          },
        },
      ],
      (isEnvProduction || isEnvDevelopment) && [
        // Latest stable ECMAScript features
        require('@babel/preset-env').default,
        {
          // We want Create React App to be IE 9 compatible until React itself
          // no longer works with IE 9
          targets: {
            ie: 9,
          },
          // Users cannot override this behavior because this Babel
          // configuration is highly tuned for ES5 support
          ignoreBrowserslistConfig: true,
          // If users import all core-js they're probably not concerned with
          // bundle size. We shouldn't rely on magic to try and shrink it.
          useBuiltIns: false,
          // Do not transform modules to CJS
          modules: false,
        },
      ],
      [
        require('@babel/preset-react').default,
        {
          // Adds component stack to warning messages
          // Adds __self attribute to JSX which React will use for some warnings
          development: isEnvDevelopment || isEnvTest,
          // Will use the native built-in instead of trying to polyfill
          // behavior for any plugins that require one.
          useBuiltIns: true,
        },
      ],
      isFlowEnabled && [require('@babel/preset-flow').default],
    ].filter(Boolean),
    plugins: [
      // Experimental macros support. Will be documented after it's had some time
      // in the wild.
      require('babel-plugin-macros'),
      // Necessary to include regardless of the environment because
      // in practice some other transforms (such as object-rest-spread)
      // don't work without it: https://github.com/babel/babel/issues/7215
      require('@babel/plugin-transform-destructuring').default,
      // class { handleClick = () => { } }
      // Enable loose mode to use assignment instead of defineProperty
      // See discussion in https://github.com/facebook/create-react-app/issues/4263
      [
        require('@babel/plugin-proposal-class-properties').default,
        {
          loose: true,
        },
      ],
      // The following two plugins use Object.assign directly, instead of Babel's
      // extends helper. Note that this assumes `Object.assign` is available.
      // { ...todo, completed: true }
      [
        require('@babel/plugin-proposal-object-rest-spread').default,
        {
          useBuiltIns: true,
        },
      ],
      // Polyfills the runtime needed for async/await, generators, and friends
      // https://babeljs.io/docs/en/babel-plugin-transform-runtime
      [
        require('@babel/plugin-transform-runtime').default,
        {
          corejs: false,
          helpers: areHelpersEnabled,
          regenerator: true,
          // https://babeljs.io/docs/en/babel-plugin-transform-runtime#useesmodules
          // We should turn this on once the lowest version of Node LTS
          // supports ES Modules.
          useESModules: isEnvDevelopment || isEnvProduction,
        },
      ],
      isEnvProduction && [
        // Remove PropTypes from production build
        require('babel-plugin-transform-react-remove-prop-types').default,
        {
          removeImport: true,
        },
      ],
      // function* () { yield 42; yield 43; }
      !isEnvTest && [
        require('@babel/plugin-transform-regenerator').default,
        {
          // Async functions are converted to generators by @babel/preset-env
          async: false,
        },
      ],
      // Adds syntax support for import()
      require('@babel/plugin-syntax-dynamic-import').default,
      isEnvTest &&
        // Transform dynamic import to require
        require('babel-plugin-transform-dynamic-import').default,
    ].filter(Boolean),
  };
};
<commit_msg>Eliminate regenerator from preset-react-app plugins (#4630)<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

const validateBoolOption = (name, value, defaultValue) => {
  if (typeof value === 'undefined') {
    value = defaultValue;
  }

  if (typeof value !== 'boolean') {
    throw new Error(`Preset react-app: '${name}' option must be a boolean.`);
  }

  return value;
};

module.exports = function(api, opts, env) {
  if (!opts) {
    opts = {};
  }

  var isEnvDevelopment = env === 'development';
  var isEnvProduction = env === 'production';
  var isEnvTest = env === 'test';
  var isFlowEnabled = validateBoolOption('flow', opts.flow, true);
  var areHelpersEnabled = validateBoolOption('helpers', opts.helpers, true);

  if (!isEnvDevelopment && !isEnvProduction && !isEnvTest) {
    throw new Error(
      'Using `babel-preset-react-app` requires that you specify `NODE_ENV` or ' +
        '`BABEL_ENV` environment variables. Valid values are "development", ' +
        '"test", and "production". Instead, received: ' +
        JSON.stringify(env) +
        '.'
    );
  }

  return {
    presets: [
      isEnvTest && [
        // ES features necessary for user's Node version
        require('@babel/preset-env').default,
        {
          targets: {
            node: 'current',
          },
        },
      ],
      (isEnvProduction || isEnvDevelopment) && [
        // Latest stable ECMAScript features
        require('@babel/preset-env').default,
        {
          // We want Create React App to be IE 9 compatible until React itself
          // no longer works with IE 9
          targets: {
            ie: 9,
          },
          // Users cannot override this behavior because this Babel
          // configuration is highly tuned for ES5 support
          ignoreBrowserslistConfig: true,
          // If users import all core-js they're probably not concerned with
          // bundle size. We shouldn't rely on magic to try and shrink it.
          useBuiltIns: false,
          // Do not transform modules to CJS
          modules: false,
        },
      ],
      [
        require('@babel/preset-react').default,
        {
          // Adds component stack to warning messages
          // Adds __self attribute to JSX which React will use for some warnings
          development: isEnvDevelopment || isEnvTest,
          // Will use the native built-in instead of trying to polyfill
          // behavior for any plugins that require one.
          useBuiltIns: true,
        },
      ],
      isFlowEnabled && [require('@babel/preset-flow').default],
    ].filter(Boolean),
    plugins: [
      // Experimental macros support. Will be documented after it's had some time
      // in the wild.
      require('babel-plugin-macros'),
      // Necessary to include regardless of the environment because
      // in practice some other transforms (such as object-rest-spread)
      // don't work without it: https://github.com/babel/babel/issues/7215
      require('@babel/plugin-transform-destructuring').default,
      // class { handleClick = () => { } }
      // Enable loose mode to use assignment instead of defineProperty
      // See discussion in https://github.com/facebook/create-react-app/issues/4263
      [
        require('@babel/plugin-proposal-class-properties').default,
        {
          loose: true,
        },
      ],
      // The following two plugins use Object.assign directly, instead of Babel's
      // extends helper. Note that this assumes `Object.assign` is available.
      // { ...todo, completed: true }
      [
        require('@babel/plugin-proposal-object-rest-spread').default,
        {
          useBuiltIns: true,
        },
      ],
      // Polyfills the runtime needed for async/await, generators, and friends
      // https://babeljs.io/docs/en/babel-plugin-transform-runtime
      [
        require('@babel/plugin-transform-runtime').default,
        {
          corejs: false,
          helpers: areHelpersEnabled,
          regenerator: true,
          // https://babeljs.io/docs/en/babel-plugin-transform-runtime#useesmodules
          // We should turn this on once the lowest version of Node LTS
          // supports ES Modules.
          useESModules: isEnvDevelopment || isEnvProduction,
        },
      ],
      isEnvProduction && [
        // Remove PropTypes from production build
        require('babel-plugin-transform-react-remove-prop-types').default,
        {
          removeImport: true,
        },
      ],
      // Adds syntax support for import()
      require('@babel/plugin-syntax-dynamic-import').default,
      isEnvTest &&
        // Transform dynamic import to require
        require('babel-plugin-transform-dynamic-import').default,
    ].filter(Boolean),
  };
};
<|endoftext|>


<commit_before>'use strict';
const browserslist = require('browserslist');
const { compare, has } = require('./helpers');
const external = require('./external');

const aliases = new Map([
  ['and_chr', 'chrome'],
  ['and_ff', 'firefox'],
  ['ie_mob', 'ie'],
  ['ios_saf', 'ios'],
  ['op_mob', 'opera_mobile'],
]);

const validTargets = new Set([
  'android',
  'chrome',
  'edge',
  'electron',
  'firefox',
  'ie',
  'ios',
  'node',
  'opera',
  'opera_mobile',
  'phantom',
  'safari',
  'samsung',
]);

function browserslistEntries(targets) {
  return browserslist(targets).map(it => it.split(' '));
}

module.exports = function (targets) {
  let list;
  if (typeof targets == 'object' && !Array.isArray(targets)) {
    const { esmodules, browsers, node, ...rest } = targets;
    list = Object.entries(rest);
    if (esmodules) {
      list = list.concat(Object.entries(external.modules));
    }
    if (browsers) {
      list = list.concat(browserslistEntries(browsers));
    }
    if (node) {
      list.push(['node', node === 'current' ? process.versions.node : node]);
    }
  } else list = browserslistEntries(targets);

  const normalized = list.map(([engine, version]) => {
    if (has(browserslist.aliases, engine)) {
      engine = browserslist.aliases[engine];
    }
    if (aliases.has(engine)) {
      engine = aliases.get(engine);
    } else if (engine === 'android' && compare(version, '>', '4.4.4')) {
      engine = 'chrome';
    }
    return [engine, String(version)];
  }).filter(([engine]) => {
    return validTargets.has(engine);
  }).sort(([a], [b]) => {
    return a < b ? -1 : a > b ? 1 : 0;
  });

  const reducedByMinVersion = new Map();
  for (const [engine, version] of normalized) {
    if (!reducedByMinVersion.has(engine) || compare(version, '<=', reducedByMinVersion.get(engine))) {
      reducedByMinVersion.set(engine, version);
    }
  }

  return reducedByMinVersion;
};
<commit_msg>some stylistic changes<commit_after>'use strict';
const browserslist = require('browserslist');
const { compare, has } = require('./helpers');
const external = require('./external');

const aliases = new Map([
  ['and_chr', 'chrome'],
  ['and_ff', 'firefox'],
  ['ie_mob', 'ie'],
  ['ios_saf', 'ios'],
  ['op_mob', 'opera_mobile'],
]);

const validTargets = new Set([
  'android',
  'chrome',
  'edge',
  'electron',
  'firefox',
  'ie',
  'ios',
  'node',
  'opera',
  'opera_mobile',
  'phantom',
  'safari',
  'samsung',
]);

module.exports = function (targets) {
  if (typeof targets !== 'object' || Array.isArray(targets)) {
    targets = { browsers: targets };
  }

  const { browsers, esmodules, node, ...rest } = targets;
  const list = Object.entries(rest);

  if (browsers) {
    list.push(...browserslist(browsers).map(it => it.split(' ')));
  }
  if (esmodules) {
    list.push(...Object.entries(external.modules));
  }
  if (node) {
    list.push(['node', node === 'current' ? process.versions.node : node]);
  }

  const normalized = list.map(([engine, version]) => {
    if (has(browserslist.aliases, engine)) {
      engine = browserslist.aliases[engine];
    }
    if (aliases.has(engine)) {
      engine = aliases.get(engine);
    } else if (engine === 'android' && compare(version, '>', '4.4.4')) {
      engine = 'chrome';
    }
    return [engine, String(version)];
  }).filter(([engine]) => {
    return validTargets.has(engine);
  }).sort(([a], [b]) => {
    return a < b ? -1 : a > b ? 1 : 0;
  });

  const reducedByMinVersion = new Map();
  for (const [engine, version] of normalized) {
    if (!reducedByMinVersion.has(engine) || compare(version, '<=', reducedByMinVersion.get(engine))) {
      reducedByMinVersion.set(engine, version);
    }
  }

  return reducedByMinVersion;
};
<|endoftext|>


<commit_before>const TestCase = require("mocha/lib/test.js");
const Suite = require("mocha/lib/suite.js");
const Deployer = require("@truffle/deployer");
const compile = require("@truffle/compile-solidity/new");
const { shimContract } = require("@truffle/compile-solidity/legacy/shims");
const path = require("path");
const semver = require("semver");
const Native = require("@truffle/compile-solidity/compilerSupplier/loadingStrategies/Native");
const debug = require("debug")("lib:testing:soliditytest");

let SafeSend;

const SolidityTest = {
  async define(abstraction, dependencyPaths, runner, mocha) {
    const self = this;

    const suite = new Suite(abstraction.contract_name, {});
    suite.timeout(runner.BEFORE_TIMEOUT);

    // Set up our runner's needs first.
    suite.beforeAll("prepare suite", async function() {
      await runner.initialize.bind(runner)();
      await self.compileNewAbstractInterface.bind(this)(runner);
      await self.deployTestDependencies.bind(
        this
      )(abstraction, dependencyPaths, runner);
    });

    suite.beforeEach("before test", async function() {
      await runner.startTest(this);
    });

    // Function that checks transaction logs to see if a test failed.
    async function checkResultForFailure(result) {
      const logs = result.receipt.rawLogs;
      for (const log of logs) {
        const decodings = await runner.decoder.decodeLog(log);
        for (const decoding of decodings) {
          //check: is this a TestEvent?
          //note: we don't check the argument names
          if (
            decoding.abi.name === "TestEvent" &&
            decoding.arguments.length === 2 &&
            decoding.arguments[0].value.type.typeClass === "bool" &&
            decoding.arguments[0].indexed &&
            decoding.arguments[1].value.type.typeClass === "string" &&
            !decoding.arguments[1].indexed
          ) {
            //if so: did the test fail?
            if (!decoding.arguments[0].value.value.asBoolean) {
              //if so: extract the message
              let messageDecoding = decoding.arguments[1].value;
              let message;
              switch (messageDecoding.value.kind) {
                case "valid":
                  message = messageDecoding.value.asString;
                  break;
                case "malformed":
                  //use buffer to convert hex to string
                  //(this causes malformed UTF-8 to become U+FFFD)
                  message = Buffer.from(
                    messageDecoding.value.asHex.slice(2),
                    "hex"
                  ).toString();
              }
              throw new Error(message);
            }
          }
        }
      }
    }

    // Add functions from test file.
    for (const item of abstraction.abi) {
      if (item.type !== "function") {
        continue;
      }

      const hookTypes = ["beforeAll", "beforeEach", "afterAll", "afterEach"];
      for (const hookType of hookTypes) {
        if (item.name.startsWith(hookType)) {
          suite[hookType](item.name, async () => {
            let deployed = await abstraction.deployed();
            await checkResultForFailure(await deployed[item.name]());
          });
        }
      }

      if (item.name.startsWith("test")) {
        const test = new TestCase(item.name, async () => {
          let deployed = await abstraction.deployed();
          await checkResultForFailure(await deployed[item.name]());
        });

        test.timeout(runner.TEST_TIMEOUT);
        suite.addTest(test);
      }
    }

    suite.afterEach("after test", async function() {
      await runner.endTest(this);
    });

    mocha.suite.addSuite(suite);
  },

  async compileNewAbstractInterface(runner) {
    debug("compiling");
    const config = runner.config;
    const solcVersion = config.compilers.solc.version;
    if (solcVersion === "native") {
      solcVersion = new Native().load().version();
    }
    if (!solcVersion) {
      SafeSend = "NewSafeSend.sol";
    } else if (semver.lt(semver.coerce(solcVersion), "0.5.0")) {
      SafeSend = "OldSafeSend.sol";
    } else {
      SafeSend = "NewSafeSend.sol";
    }

    const { contracts } = await compile.with_dependencies(
      runner.config.with({
        paths: [
          path.join(__dirname, "Assert.sol"),
          path.join(__dirname, "AssertAddress.sol"),
          path.join(__dirname, "AssertAddressArray.sol"),
          path.join(__dirname, "AssertBalance.sol"),
          path.join(__dirname, "AssertBool.sol"),
          path.join(__dirname, "AssertBytes32.sol"),
          path.join(__dirname, "AssertBytes32Array.sol"),
          path.join(__dirname, "AssertGeneral.sol"),
          path.join(__dirname, "AssertInt.sol"),
          path.join(__dirname, "AssertIntArray.sol"),
          path.join(__dirname, "AssertString.sol"),
          path.join(__dirname, "AssertUint.sol"),
          path.join(__dirname, "AssertUintArray.sol"),
          "truffle/DeployedAddresses.sol", // generated by deployed.js
          path.join(__dirname, SafeSend)
        ],
        quiet: true
      })
    );

    // Set network values.
    for (let contract of contracts) {
      contract.network_id = config.network_id;
      contract.default_network = config.default_network;
    }

    await config.artifactor.saveAll(contracts.map(shimContract));
    debug("compiled");
  },

  async deployTestDependencies(abstraction, dependencyPaths, runner) {
    debug("deploying %s", abstraction.contract_name);
    const deployer = new Deployer(
      runner.config.with({
        logger: { log() {} }
      })
    );

    debug("starting deployer");
    await deployer.start();

    const testLibraries = [
      "Assert",
      "AssertAddress",
      "AssertAddressArray",
      "AssertBalance",
      "AssertBool",
      "AssertBytes32",
      "AssertBytes32Array",
      "AssertGeneral",
      "AssertInt",
      "AssertIntArray",
      "AssertString",
      "AssertUint",
      "AssertUintArray",
      "DeployedAddresses"
    ];

    const testAbstractions = testLibraries.map(name =>
      runner.config.resolver.require(`truffle/${name}.sol`)
    );

    SafeSend = runner.config.resolver.require(SafeSend);

    debug("deploying test libs");
    for (const testLib of testAbstractions) {
      await deployer.deploy(testLib);
      await deployer.link(testLib, abstraction);
    }

    debug("linking dependencies");
    for (const dependencyPath of dependencyPaths) {
      const dependency = runner.config.resolver.require(dependencyPath);

      if (dependency.isDeployed()) {
        await deployer.link(dependency, abstraction);
      }
    }

    debug("deploying contract");
    await deployer.deploy(abstraction);
    const deployed = await abstraction.deployed();
    let balance;
    if (deployed.initialBalance) {
      balance = await deployed.initialBalance.call();
    } else {
      balance = 0;
    }

    if (balance !== 0) {
      await deployer.deploy(SafeSend, deployed.address, {
        value: balance
      });
      const safeSend = await SafeSend.deployed();
      await safeSend.deliver();
    }

    debug("deployed %s", abstraction.contract_name);
  }
};

module.exports = SolidityTest;
<commit_msg>fix constant reassignment of solcVersion<commit_after>const TestCase = require("mocha/lib/test.js");
const Suite = require("mocha/lib/suite.js");
const Deployer = require("@truffle/deployer");
const compile = require("@truffle/compile-solidity/new");
const { shimContract } = require("@truffle/compile-solidity/legacy/shims");
const path = require("path");
const semver = require("semver");
const Native = require("@truffle/compile-solidity/compilerSupplier/loadingStrategies/Native");
const debug = require("debug")("lib:testing:soliditytest");

let SafeSend;

const SolidityTest = {
  async define(abstraction, dependencyPaths, runner, mocha) {
    const self = this;

    const suite = new Suite(abstraction.contract_name, {});
    suite.timeout(runner.BEFORE_TIMEOUT);

    // Set up our runner's needs first.
    suite.beforeAll("prepare suite", async function() {
      await runner.initialize.bind(runner)();
      await self.compileNewAbstractInterface.bind(this)(runner);
      await self.deployTestDependencies.bind(
        this
      )(abstraction, dependencyPaths, runner);
    });

    suite.beforeEach("before test", async function() {
      await runner.startTest(this);
    });

    // Function that checks transaction logs to see if a test failed.
    async function checkResultForFailure(result) {
      const logs = result.receipt.rawLogs;
      for (const log of logs) {
        const decodings = await runner.decoder.decodeLog(log);
        for (const decoding of decodings) {
          //check: is this a TestEvent?
          //note: we don't check the argument names
          if (
            decoding.abi.name === "TestEvent" &&
            decoding.arguments.length === 2 &&
            decoding.arguments[0].value.type.typeClass === "bool" &&
            decoding.arguments[0].indexed &&
            decoding.arguments[1].value.type.typeClass === "string" &&
            !decoding.arguments[1].indexed
          ) {
            //if so: did the test fail?
            if (!decoding.arguments[0].value.value.asBoolean) {
              //if so: extract the message
              let messageDecoding = decoding.arguments[1].value;
              let message;
              switch (messageDecoding.value.kind) {
                case "valid":
                  message = messageDecoding.value.asString;
                  break;
                case "malformed":
                  //use buffer to convert hex to string
                  //(this causes malformed UTF-8 to become U+FFFD)
                  message = Buffer.from(
                    messageDecoding.value.asHex.slice(2),
                    "hex"
                  ).toString();
              }
              throw new Error(message);
            }
          }
        }
      }
    }

    // Add functions from test file.
    for (const item of abstraction.abi) {
      if (item.type !== "function") {
        continue;
      }

      const hookTypes = ["beforeAll", "beforeEach", "afterAll", "afterEach"];
      for (const hookType of hookTypes) {
        if (item.name.startsWith(hookType)) {
          suite[hookType](item.name, async () => {
            let deployed = await abstraction.deployed();
            await checkResultForFailure(await deployed[item.name]());
          });
        }
      }

      if (item.name.startsWith("test")) {
        const test = new TestCase(item.name, async () => {
          let deployed = await abstraction.deployed();
          await checkResultForFailure(await deployed[item.name]());
        });

        test.timeout(runner.TEST_TIMEOUT);
        suite.addTest(test);
      }
    }

    suite.afterEach("after test", async function() {
      await runner.endTest(this);
    });

    mocha.suite.addSuite(suite);
  },

  async compileNewAbstractInterface(runner) {
    debug("compiling");
    const config = runner.config;
    let solcVersion = config.compilers.solc.version;
    if (solcVersion === "native") {
      solcVersion = new Native().load().version();
    }
    if (!solcVersion) {
      SafeSend = "NewSafeSend.sol";
    } else if (semver.lt(semver.coerce(solcVersion), "0.5.0")) {
      SafeSend = "OldSafeSend.sol";
    } else {
      SafeSend = "NewSafeSend.sol";
    }

    const { contracts } = await compile.with_dependencies(
      runner.config.with({
        paths: [
          path.join(__dirname, "Assert.sol"),
          path.join(__dirname, "AssertAddress.sol"),
          path.join(__dirname, "AssertAddressArray.sol"),
          path.join(__dirname, "AssertBalance.sol"),
          path.join(__dirname, "AssertBool.sol"),
          path.join(__dirname, "AssertBytes32.sol"),
          path.join(__dirname, "AssertBytes32Array.sol"),
          path.join(__dirname, "AssertGeneral.sol"),
          path.join(__dirname, "AssertInt.sol"),
          path.join(__dirname, "AssertIntArray.sol"),
          path.join(__dirname, "AssertString.sol"),
          path.join(__dirname, "AssertUint.sol"),
          path.join(__dirname, "AssertUintArray.sol"),
          "truffle/DeployedAddresses.sol", // generated by deployed.js
          path.join(__dirname, SafeSend)
        ],
        quiet: true
      })
    );

    // Set network values.
    for (let contract of contracts) {
      contract.network_id = config.network_id;
      contract.default_network = config.default_network;
    }

    await config.artifactor.saveAll(contracts.map(shimContract));
    debug("compiled");
  },

  async deployTestDependencies(abstraction, dependencyPaths, runner) {
    debug("deploying %s", abstraction.contract_name);
    const deployer = new Deployer(
      runner.config.with({
        logger: { log() {} }
      })
    );

    debug("starting deployer");
    await deployer.start();

    const testLibraries = [
      "Assert",
      "AssertAddress",
      "AssertAddressArray",
      "AssertBalance",
      "AssertBool",
      "AssertBytes32",
      "AssertBytes32Array",
      "AssertGeneral",
      "AssertInt",
      "AssertIntArray",
      "AssertString",
      "AssertUint",
      "AssertUintArray",
      "DeployedAddresses"
    ];

    const testAbstractions = testLibraries.map(name =>
      runner.config.resolver.require(`truffle/${name}.sol`)
    );

    SafeSend = runner.config.resolver.require(SafeSend);

    debug("deploying test libs");
    for (const testLib of testAbstractions) {
      await deployer.deploy(testLib);
      await deployer.link(testLib, abstraction);
    }

    debug("linking dependencies");
    for (const dependencyPath of dependencyPaths) {
      const dependency = runner.config.resolver.require(dependencyPath);

      if (dependency.isDeployed()) {
        await deployer.link(dependency, abstraction);
      }
    }

    debug("deploying contract");
    await deployer.deploy(abstraction);
    const deployed = await abstraction.deployed();
    let balance;
    if (deployed.initialBalance) {
      balance = await deployed.initialBalance.call();
    } else {
      balance = 0;
    }

    if (balance !== 0) {
      await deployer.deploy(SafeSend, deployed.address, {
        value: balance
      });
      const safeSend = await SafeSend.deployed();
      await safeSend.deliver();
    }

    debug("deployed %s", abstraction.contract_name);
  }
};

module.exports = SolidityTest;
<|endoftext|>


<commit_before>'use strict';

//Setting up route
angular.module('mean.users').config(['$meanStateProvider', '$httpProvider', 'jwtInterceptorProvider',
  function($meanStateProvider, $httpProvider, jwtInterceptorProvider) {

    jwtInterceptorProvider.tokenGetter = function() {
      return localStorage.getItem('JWT');
    };

    $httpProvider.interceptors.push('jwtInterceptor');

    // states for my app
    $meanStateProvider
      .state('auth', {
        url: '/auth',
        templateUrl: 'users/views/index.html'
      })
      .state('auth.login', {
        url: '/login',
        templateUrl: 'users/views/login.html',
        resolve: {
          loggedin: function(MeanUser) {
            return MeanUser.checkLoggedOut();
          }
        }
      })
      .state('auth.register', {
        url: '/register',
        templateUrl: 'users/views/register.html',
        resolve: {
          loggedin: function(MeanUser) {
            return MeanUser.checkLoggedOut();
          }
        }
      })
      .state('forgot-password', {
        url: '/forgot-password',
        templateUrl: 'users/views/forgot-password.html',
        resolve: {
          loggedin: function(MeanUser) {
            return MeanUser.checkLoggedOut();
          }
        }
      })
      .state('reset-password', {
        url: '/reset/:tokenId',
        templateUrl: 'users/views/reset-password.html',
        resolve: {
          loggedin: function(MeanUser) {
            return MeanUser.checkLoggedOut();
          }
        }
      });
  }
]);<commit_msg>Update auth.js<commit_after>'use strict';

//Setting up route
angular.module('mean.users').config(['$meanStateProvider', '$httpProvider', 'jwtInterceptorProvider',
  function($meanStateProvider, $httpProvider, jwtInterceptorProvider) {

    jwtInterceptorProvider.tokenGetter = function() {
      return localStorage.getItem('JWT');
    };

    $httpProvider.interceptors.push('jwtInterceptor');

    // states for my app
    $meanStateProvider
      .state('auth', {
        url: '/auth',
        abstract: true,
        templateUrl: 'users/views/index.html'
      })
      .state('auth.login', {
        url: '/login',
        templateUrl: 'users/views/login.html',
        resolve: {
          loggedin: function(MeanUser) {
            return MeanUser.checkLoggedOut();
          }
        }
      })
      .state('auth.register', {
        url: '/register',
        templateUrl: 'users/views/register.html',
        resolve: {
          loggedin: function(MeanUser) {
            return MeanUser.checkLoggedOut();
          }
        }
      })
      .state('forgot-password', {
        url: '/forgot-password',
        templateUrl: 'users/views/forgot-password.html',
        resolve: {
          loggedin: function(MeanUser) {
            return MeanUser.checkLoggedOut();
          }
        }
      })
      .state('reset-password', {
        url: '/reset/:tokenId',
        templateUrl: 'users/views/reset-password.html',
        resolve: {
          loggedin: function(MeanUser) {
            return MeanUser.checkLoggedOut();
          }
        }
      });
  }
]);
<|endoftext|>


<commit_before>var functions = require('firebase-functions')
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const genreSimScore = require('./genres');
const recentSongsSimScore = require('./recentTracks');
const topArtistsSimScore = require('./topArtists');
const topTrackSimScore = require('./topTracks');

exports.getMatches = functions.database.ref('/Users/{uid}/requestMatches')
  .onWrite(event=> {
    const userId = event.params.uid
    console.log('userId in getMatches', userId)

    return admin.database().ref('Users').once('value').then(snapshot => {

      const usersObj = snapshot.val()
      const userNames = Object.keys(usersObj).filter(name => name !== userId)

      const user1Obj = usersObj[userId]

      const user1TopArtists = user1Obj.topArtists.artists
      const user1TopTracks = user1Obj.topTracks.tracks
      const user1RecentSongs = user1Obj.recentSongs.songs

      userNames.forEach(user => {
        user2Obj = usersObj[user];

        let user2TopArtists
        let user2TopTracks
        let user2RecentSongs

        user2TopArtists =  (user2Obj.topArtists ? user2Obj.topArtists.artists : [])
        user2TopTracks =  (user2Obj.topTracks ? user2Obj.topTracks.tracks : [])
        user2RecentSongs =  (user2Obj.recentSongs ? user2Obj.recentSongs.songs : [])

        const genreScore = genreSimScore(user1TopArtists, user2TopArtists)
        const recentSongsScore = recentSongsSimScore(user1RecentSongs, user2RecentSongs)
        const artistsScore = topArtistsSimScore(user1TopArtists, user2TopArtists)
        const tracksScore = topTrackSimScore(user1TopTracks, user2TopTracks)

        const matchScore = (genreScore + recentSongsScore + artistsScore + tracksScore)/4

        console.log(`${user}'s match score: ${matchScore}`)
        console.log(`/Users/${userId}/matches/matchScores/${user}`)
        admin.database().ref(`/Users/${userId}/matches/matchScores/${user}`).set(matchScore)
        admin.database().ref(`/Users/${user}/matches/matchScores/${userId}`).set(matchScore)

      })

    }).catch(console.error)

  })
<commit_msg>add: other scores on click get matches<commit_after>var functions = require('firebase-functions')
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const genreSimScore = require('./genres');
const recentSongsSimScore = require('./recentTracks');
const topArtistsSimScore = require('./topArtists');
const topTrackSimScore = require('./topTracks');

exports.getMatches = functions.database.ref('/Users/{uid}/requestMatches')
  .onWrite(event=> {
    const userId = event.params.uid
    console.log('userId in getMatches', userId)

    return admin.database().ref('Users').once('value').then(snapshot => {

      const usersObj = snapshot.val()
      const userNames = Object.keys(usersObj).filter(name => name !== userId)

      const user1Obj = usersObj[userId]

      const user1TopArtists = user1Obj.topArtists.artists
      const user1TopTracks = user1Obj.topTracks.tracks
      const user1RecentSongs = user1Obj.recentSongs.songs

      userNames.forEach(user => {
        user2Obj = usersObj[user];

        let user2TopArtists
        let user2TopTracks
        let user2RecentSongs

        user2TopArtists =  (user2Obj.topArtists ? user2Obj.topArtists.artists : [])
        user2TopTracks =  (user2Obj.topTracks ? user2Obj.topTracks.tracks : [])
        user2RecentSongs =  (user2Obj.recentSongs ? user2Obj.recentSongs.songs : [])

        const genresScore = genreSimScore(user1TopArtists, user2TopArtists)
        const recentSongsScore = recentSongsSimScore(user1RecentSongs, user2RecentSongs)
        const artistsScore = topArtistsSimScore(user1TopArtists, user2TopArtists)
        const tracksScore = topTrackSimScore(user1TopTracks, user2TopTracks)

        const matchScore = (genresScore + recentSongsScore + artistsScore + tracksScore)/4

        console.log(`${user}'s match score: ${matchScore}`)
        console.log(`/Users/${userId}/matches/matchScores/${user}`)
        //masterscore
        admin.database().ref(`/Users/${userId}/matches/matchScores/${user}`).set(matchScore)
        admin.database().ref(`/Users/${user}/matches/matchScores/${userId}`).set(matchScore)
        //genrescore
        admin.database().ref(`/Users/${userId}/matches/genreScores/${user}`).set(genresScore)
        admin.database().ref(`/Users/${user}/matches/genreScores/${userId}`).set(genresScore)
        //recentSongsScore
        admin.database().ref(`/Users/${userId}/matches/recentSongsScores/${user}`).set(recentSongsScore)
        admin.database().ref(`/Users/${user}/matches/recentSongsScores/${userId}`).set(recentSongsScore)
        //artistscore
        admin.database().ref(`/Users/${userId}/matches/artistsScores/${user}`).set(artistsScore)
        admin.database().ref(`/Users/${user}/matches/artistsScores/${userId}`).set(artistsScore)
        //trackScore
        admin.database().ref(`/Users/${userId}/matches/tracksScores/${user}`).set(tracksScore)
        admin.database().ref(`/Users/${user}/matches/tracksScores/${userId}`).set(tracksScore)
      })

    }).catch(console.error)

  })
<|endoftext|>


<commit_before>'use strict';
/**
 * `list` type prompt
 */

var _ = require('lodash');
var chalk = require('chalk');
var cliCursor = require('cli-cursor');
var figures = require('figures');
var { map, takeUntil } = require('rxjs/operators');
var Base = require('./base');
var observe = require('../utils/events');
var Paginator = require('../utils/paginator');

class CheckboxPrompt extends Base {
  constructor(questions, rl, answers) {
    super(questions, rl, answers);

    if (!this.opt.choices) {
      this.throwParamError('choices');
    }

    if (_.isArray(this.opt.default)) {
      this.opt.choices.forEach(function(choice) {
        if (this.opt.default.indexOf(choice.value) >= 0) {
          choice.checked = true;
        }
      }, this);
    }

    this.pointer = 0;
    this.firstRender = true;

    // Make sure no default is set (so it won't be printed)
    this.opt.default = null;

    this.paginator = new Paginator(this.screen);
  }

  /**
   * Start the Inquiry session
   * @param  {Function} cb      Callback when prompt is done
   * @return {this}
   */

  _run(cb) {
    this.done = cb;

    var events = observe(this.rl);

    var validation = this.handleSubmitEvents(
      events.line.pipe(map(this.getCurrentValue.bind(this)))
    );
    validation.success.forEach(this.onEnd.bind(this));
    validation.error.forEach(this.onError.bind(this));

    events.normalizedUpKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onUpKey.bind(this));
    events.normalizedDownKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onDownKey.bind(this));
    events.numberKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onNumberKey.bind(this));
    events.spaceKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onSpaceKey.bind(this));
    events.aKey.pipe(takeUntil(validation.success)).forEach(this.onAllKey.bind(this));
    events.iKey.pipe(takeUntil(validation.success)).forEach(this.onInverseKey.bind(this));

    // Init the prompt
    cliCursor.hide();
    this.render();
    this.firstRender = false;

    return this;
  }

  /**
   * Render the prompt to screen
   * @return {CheckboxPrompt} self
   */

  render(error) {
    // Render question
    var message = this.getQuestion();
    var bottomContent = '';

    if (this.firstRender) {
      message +=
        '(Press ' +
        chalk.cyan.bold('<space>') +
        ' to select, ' +
        chalk.cyan.bold('<a>') +
        ' to toggle all, ' +
        chalk.cyan.bold('<i>') +
        ' to invert selection)';
    }

    // Render choices or answer depending on the state
    if (this.status === 'answered') {
      message += chalk.cyan(this.selection.join(', '));
    } else {
      var choicesStr = renderChoices(this.opt.choices, this.pointer);
      var indexPosition = this.opt.choices.indexOf(
        this.opt.choices.getChoice(this.pointer)
      );
      message +=
        '\n' + this.paginator.paginate(choicesStr, indexPosition, this.opt.pageSize);
    }

    if (error) {
      bottomContent = chalk.red('>> ') + error;
    }

    this.screen.render(message, bottomContent);
  }

  /**
   * When user press `enter` key
   */

  onEnd(state) {
    this.status = 'answered';

    // Rerender prompt (and clean subline error)
    this.render();

    this.screen.done();
    cliCursor.show();
    this.done(state.value);
  }

  onError(state) {
    this.render(state.isValid);
  }

  getCurrentValue() {
    var choices = this.opt.choices.filter(function(choice) {
      return Boolean(choice.checked) && !choice.disabled;
    });

    this.selection = _.map(choices, 'short');
    return _.map(choices, 'value');
  }

  onUpKey() {
    var len = this.opt.choices.realLength;
    this.pointer = this.pointer > 0 ? this.pointer - 1 : len - 1;
    this.render();
  }

  onDownKey() {
    var len = this.opt.choices.realLength;
    this.pointer = this.pointer < len - 1 ? this.pointer + 1 : 0;
    this.render();
  }

  onNumberKey(input) {
    if (input <= this.opt.choices.realLength) {
      this.pointer = input - 1;
      this.toggleChoice(this.pointer);
    }
    this.render();
  }

  onSpaceKey() {
    this.toggleChoice(this.pointer);
    this.render();
  }

  onAllKey() {
    var shouldBeChecked = Boolean(
      this.opt.choices.find(function(choice) {
        return choice.type !== 'separator' && !choice.checked;
      })
    );

    this.opt.choices.forEach(function(choice) {
      if (choice.type !== 'separator') {
        choice.checked = shouldBeChecked;
      }
    });

    this.render();
  }

  onInverseKey() {
    this.opt.choices.forEach(function(choice) {
      if (choice.type !== 'separator') {
        choice.checked = !choice.checked;
      }
    });

    this.render();
  }

  toggleChoice(index) {
    var item = this.opt.choices.getChoice(index);
    if (item !== undefined) {
      this.opt.choices.getChoice(index).checked = !item.checked;
    }
  }
}

/**
 * Function for rendering checkbox choices
 * @param  {Number} pointer Position of the pointer
 * @return {String}         Rendered content
 */

function renderChoices(choices, pointer) {
  var output = '';
  var separatorOffset = 0;

  choices.forEach(function(choice, i) {
    if (choice.type === 'separator') {
      separatorOffset++;
      output += ' ' + choice + '\n';
      return;
    }

    if (choice.disabled) {
      separatorOffset++;
      output += ' - ' + choice.name;
      output += ' (' + (_.isString(choice.disabled) ? choice.disabled : 'Disabled') + ')';
    } else {
      var isSelected = i - separatorOffset === pointer;
      output += isSelected ? chalk.cyan(figures.pointer) : ' ';
      output += getCheckbox(choice.checked) + ' ' + choice.name;
    }

    output += '\n';
  });

  return output.replace(/\n$/, '');
}

/**
 * Get the checkbox
 * @param  {Boolean} checked - add a X or not to the checkbox
 * @return {String} Composited checkbox string
 */

function getCheckbox(checked) {
  return checked ? chalk.green(figures.radioOn) : figures.radioOff;
}

module.exports = CheckboxPrompt;
<commit_msg>Added highlight for selected line in checkbox (#716)<commit_after>'use strict';
/**
 * `list` type prompt
 */

var _ = require('lodash');
var chalk = require('chalk');
var cliCursor = require('cli-cursor');
var figures = require('figures');
var { map, takeUntil } = require('rxjs/operators');
var Base = require('./base');
var observe = require('../utils/events');
var Paginator = require('../utils/paginator');

class CheckboxPrompt extends Base {
  constructor(questions, rl, answers) {
    super(questions, rl, answers);

    if (!this.opt.choices) {
      this.throwParamError('choices');
    }

    if (_.isArray(this.opt.default)) {
      this.opt.choices.forEach(function(choice) {
        if (this.opt.default.indexOf(choice.value) >= 0) {
          choice.checked = true;
        }
      }, this);
    }

    this.pointer = 0;
    this.firstRender = true;

    // Make sure no default is set (so it won't be printed)
    this.opt.default = null;

    this.paginator = new Paginator(this.screen);
  }

  /**
   * Start the Inquiry session
   * @param  {Function} cb      Callback when prompt is done
   * @return {this}
   */

  _run(cb) {
    this.done = cb;

    var events = observe(this.rl);

    var validation = this.handleSubmitEvents(
      events.line.pipe(map(this.getCurrentValue.bind(this)))
    );
    validation.success.forEach(this.onEnd.bind(this));
    validation.error.forEach(this.onError.bind(this));

    events.normalizedUpKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onUpKey.bind(this));
    events.normalizedDownKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onDownKey.bind(this));
    events.numberKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onNumberKey.bind(this));
    events.spaceKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onSpaceKey.bind(this));
    events.aKey.pipe(takeUntil(validation.success)).forEach(this.onAllKey.bind(this));
    events.iKey.pipe(takeUntil(validation.success)).forEach(this.onInverseKey.bind(this));

    // Init the prompt
    cliCursor.hide();
    this.render();
    this.firstRender = false;

    return this;
  }

  /**
   * Render the prompt to screen
   * @return {CheckboxPrompt} self
   */

  render(error) {
    // Render question
    var message = this.getQuestion();
    var bottomContent = '';

    if (this.firstRender) {
      message +=
        '(Press ' +
        chalk.cyan.bold('<space>') +
        ' to select, ' +
        chalk.cyan.bold('<a>') +
        ' to toggle all, ' +
        chalk.cyan.bold('<i>') +
        ' to invert selection)';
    }

    // Render choices or answer depending on the state
    if (this.status === 'answered') {
      message += chalk.cyan(this.selection.join(', '));
    } else {
      var choicesStr = renderChoices(this.opt.choices, this.pointer);
      var indexPosition = this.opt.choices.indexOf(
        this.opt.choices.getChoice(this.pointer)
      );
      message +=
        '\n' + this.paginator.paginate(choicesStr, indexPosition, this.opt.pageSize);
    }

    if (error) {
      bottomContent = chalk.red('>> ') + error;
    }

    this.screen.render(message, bottomContent);
  }

  /**
   * When user press `enter` key
   */

  onEnd(state) {
    this.status = 'answered';

    // Rerender prompt (and clean subline error)
    this.render();

    this.screen.done();
    cliCursor.show();
    this.done(state.value);
  }

  onError(state) {
    this.render(state.isValid);
  }

  getCurrentValue() {
    var choices = this.opt.choices.filter(function(choice) {
      return Boolean(choice.checked) && !choice.disabled;
    });

    this.selection = _.map(choices, 'short');
    return _.map(choices, 'value');
  }

  onUpKey() {
    var len = this.opt.choices.realLength;
    this.pointer = this.pointer > 0 ? this.pointer - 1 : len - 1;
    this.render();
  }

  onDownKey() {
    var len = this.opt.choices.realLength;
    this.pointer = this.pointer < len - 1 ? this.pointer + 1 : 0;
    this.render();
  }

  onNumberKey(input) {
    if (input <= this.opt.choices.realLength) {
      this.pointer = input - 1;
      this.toggleChoice(this.pointer);
    }
    this.render();
  }

  onSpaceKey() {
    this.toggleChoice(this.pointer);
    this.render();
  }

  onAllKey() {
    var shouldBeChecked = Boolean(
      this.opt.choices.find(function(choice) {
        return choice.type !== 'separator' && !choice.checked;
      })
    );

    this.opt.choices.forEach(function(choice) {
      if (choice.type !== 'separator') {
        choice.checked = shouldBeChecked;
      }
    });

    this.render();
  }

  onInverseKey() {
    this.opt.choices.forEach(function(choice) {
      if (choice.type !== 'separator') {
        choice.checked = !choice.checked;
      }
    });

    this.render();
  }

  toggleChoice(index) {
    var item = this.opt.choices.getChoice(index);
    if (item !== undefined) {
      this.opt.choices.getChoice(index).checked = !item.checked;
    }
  }
}

/**
 * Function for rendering checkbox choices
 * @param  {Number} pointer Position of the pointer
 * @return {String}         Rendered content
 */

function renderChoices(choices, pointer) {
  var output = '';
  var separatorOffset = 0;

  choices.forEach(function(choice, i) {
    if (choice.type === 'separator') {
      separatorOffset++;
      output += ' ' + choice + '\n';
      return;
    }

    if (choice.disabled) {
      separatorOffset++;
      output += ' - ' + choice.name;
      output += ' (' + (_.isString(choice.disabled) ? choice.disabled : 'Disabled') + ')';
    } else {
      var line = getCheckbox(choice.checked) + ' ' + choice.name;
      if (i - separatorOffset === pointer) {
        output += chalk.cyan(figures.pointer + line);
      } else {
        output += ' ' + line;
      }
    }

    output += '\n';
  });

  return output.replace(/\n$/, '');
}

/**
 * Get the checkbox
 * @param  {Boolean} checked - add a X or not to the checkbox
 * @return {String} Composited checkbox string
 */

function getCheckbox(checked) {
  return checked ? chalk.green(figures.radioOn) : figures.radioOff;
}

module.exports = CheckboxPrompt;
<|endoftext|>


<commit_before>'use babel'

/* @flow */

declare module 'debugger' {

  declare type FunctionBreakpoint = { function: string }
  declare type LineBreakpoint     = { filePath: string, bufferRow: number }
  declare type BreakpointLocation = LineBreakpoint | FunctionBreakpoint

  declare interface Breakpoint {
    location:        BreakpointLocation;
    enabled:         boolean;
    condition:       ?string;
    activeBufferRow: ?number;

    constructor(location: BreakpointLocation, condition?: string): void;

    getLocation(): BreakpointLocation;

    isEnabled(): bool;

    equals(other: Breakpoint): bool;
  }

  declare type BreakpointEventType  = 'inserted' | 'removed' | 'enabled' |
                                      'disabled' | 'moved' |
                                      'condition-added' | 'condition-removed'

  declare interface BreakpointEvent {
    type:       BreakpointEventType;
    breakpoint: Breakpoint;
    bufferRow:  ?number;

    constructor(
      type: BreakpointEventType, breakpoint: Breakpoint, bufferRow?: number): void;
  }

  declare type SessionEventType         = 'launched' | 'will-terminate' |
                                          'terminated' | 'resumed' | 'suspended'
  declare type SessionTerminationReason = 'normally' | 'interrupt'
  declare type SessionSuspensionReason  = 'breakpoint' | 'step'

  declare type ExecutionLine = { filePath: string, bufferRow: number }

  declare class SessionEvent {
    type:          SessionEventType;
    reason:        SessionTerminationReason | SessionSuspensionReason;
    executionLine: ExecutionLine;

    constructor(
      type:           SessionEventType,
      reason?:        SessionTerminationReason | SessionSuspensionReason,
      executionLine?: ExecutionLine): void;
  }

  declare interface EventDefs {
    BreakpointEvent: BreakpointEvent;
    SessionEvent: SessionEvent;
  }

  declare interface DebuggerTarget  {
    filePath: string,
    args: ?string[]
  }

  declare interface DebuggerProxy {

    onSessionEvent(callback: ((event: SessionEvent) => void)): Disposable;

    onBreakpointEvent(callback: ((event: BreakpointEvent) => void)): Disposable;
  }

  declare interface DebuggerRegistry {

    getDebuggerProxy(): DebuggerProxy;
  }

  declare type DebuggerController = {

    debuggerRegistry: DebuggerRegistry;
  }
}
<commit_msg>Expose more functions of DebuggerProxy in interface<commit_after>'use babel'

/* @flow */

declare module 'debugger' {

  declare type FunctionBreakpoint = { function: string }
  declare type LineBreakpoint     = { filePath: string, bufferRow: number }
  declare type BreakpointLocation = LineBreakpoint | FunctionBreakpoint

  declare interface Breakpoint {
    location:        BreakpointLocation;
    enabled:         boolean;
    condition:       ?string;
    activeBufferRow: ?number;

    constructor(location: BreakpointLocation, condition?: string): void;

    getLocation(): BreakpointLocation;

    isEnabled(): bool;

    equals(other: Breakpoint): bool;
  }

  declare type BreakpointEventType  = 'inserted' | 'removed' | 'enabled' |
                                      'disabled' | 'moved' |
                                      'condition-added' | 'condition-removed'

  declare interface BreakpointEvent {
    type:       BreakpointEventType;
    breakpoint: Breakpoint;
    bufferRow:  ?number;

    constructor(
      type: BreakpointEventType, breakpoint: Breakpoint, bufferRow?: number): void;
  }

  declare type SessionEventType         = 'launched' | 'will-terminate' |
                                          'terminated' | 'resumed' | 'suspended'
  declare type SessionTerminationReason = 'normally' | 'interrupt'
  declare type SessionSuspensionReason  = 'breakpoint' | 'step'

  declare type ExecutionLine = { filePath: string, bufferRow: number }

  declare class SessionEvent {
    type:          SessionEventType;
    reason:        SessionTerminationReason | SessionSuspensionReason;
    executionLine: ExecutionLine;

    constructor(
      type:           SessionEventType,
      reason?:        SessionTerminationReason | SessionSuspensionReason,
      executionLine?: ExecutionLine): void;
  }

  declare interface EventDefs {
    BreakpointEvent: BreakpointEvent;
    SessionEvent: SessionEvent;
  }

  declare interface DebuggerTarget  {
    filePath: string,
    args: ?string[]
  }

  declare interface DebuggerProxy {

    onSessionEvent(callback: ((event: SessionEvent) => void)): Disposable;

    onBreakpointEvent(callback: ((event: BreakpointEvent) => void)): Disposable;

    findBreakpoint(location: BreakpointLocation): ?Breakpoint;

    removeBreakpoint(breakpoint: Breakpoint): boolean;
  }

  declare interface DebuggerRegistry {

    getDebuggerProxy(): DebuggerProxy;
  }

  declare interface DebuggerController {

    debuggerRegistry: DebuggerRegistry;
  }
}
<|endoftext|>


<commit_before>var GameController = function(args) {
  this.keyStates = {
    up: false,
    down: false,
    left: false,
    right: false
  }
  this.pacMoveInterval = false;

  this.actorCanvas = args.actorCanvas;
  this.boardCanvas = args.boardCanvas;
  this.pelletCanvas = args.pelletCanvas;

  this.pac = new Actor({
    context: this.actorCanvas.context,
    startX: 113,
    startY: 212,
    name: "m",
    direction: "right"
  });
  this.blinky = new Ghost({
    context: this.actorCanvas.context,
    direction: "left",
    name: "b",
    startX: 112,
    startY: 116
  });
  this.inky = new Ghost({
    context: this.actorCanvas.context,
    direction: "up",
    mode: "house",
    name: "i",
    startX: 96,
    startY: 139
  });
  this.pinky = new Ghost({
    context: this.actorCanvas.context,
    direction: "right",
    mode: "exitting",
    name: "p",
    startX: 112,
    startY: 139
  });
  this.clyde = new Ghost({
    context: this.actorCanvas.context,
    direction: "down",
    mode: "house",
    name: "c",
    startX: 128,
    startY: 139
  });

  this.drawPellets();
  this.actorCanvas.renderPac(this.pac);

  addEventListener("keydown", this.handleKeyDown.bind(this));
  addEventListener("keyup", this.handleKeyUp.bind(this));

  setInterval(function() {
    this.moveGhost("b");
    this.moveGhost("i");
    this.moveGhost("p");
    this.moveGhost("c");
  }.bind(this), GHOST_MOVE_DELAY);

  setTimeout(function() {
    this.inky.setMode("exitting");
  }.bind(this), INKY_EXIT_DELAY);
  setTimeout(function() {
    this.clyde.setMode("exitting");
  }.bind(this), CLYDE_EXIT_DELAY);
}
GameController.prototype.drawPellets = function() {
  this.pelletCanvas.clearRect({
    x: 0,
    y: 0,
    w: BOARD_WIDTH,
    h: BOARD_HEIGHT
  });
  gameBoard.board.matrix.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      if(col == ".") {
        this.pelletCanvas.drawRect({
          x: (8 * cIndex) + 3,
          y: (8 * rIndex) + 27,
          w: 2,
          h: 2
        });
      }
      else if(col == "o") {
        this.pelletCanvas.drawCircle({
          x: (8 * cIndex) + 4,
          y: (8 * rIndex) + 28,
          rad: 4
        });
      }
      else if(col == "-") {
        this.pelletCanvas.drawRect({
          x: 8 * cIndex,
          y: (8 * rIndex) + 29,
          w: 8,
          h: 2
        });
      }
    });
  });
};
GameController.prototype.moveActor = function() {
  this.actorCanvas.clearRect(this.pac.getClearDimensions());
  var coords = {
    x: this.pac.x,
    y: this.pac.y
  }

  var newDirection = false;
  for(var prop in this.keyStates) {
    if(this.keyStates.hasOwnProperty(prop) && this.keyStates[prop]) {
      newDirection = prop;
      break;
    }
  }

  var collision;
  if(this.keyStates[this.pac.direction] === false && newDirection) {
    collision = gameBoard.detectCollision(coords, newDirection);
    if(collision != "door" && collision != "wall") {
      this.pac.direction = newDirection;
    }
  }

  collision = gameBoard.detectCollision(coords, this.pac.direction);
  if(collision == "wall" || collision == "door") {
    clearInterval(this.pacMoveInterval);
    this.pacMoveInterval = false;
  }
  else {
    this.pac.move();
  }
  this.pac.moveTowardCenter();

  this.actorCanvas.renderPac(this.pac);
};
GameController.prototype.moveGhost = function(name) {
  var ghost;
  switch(name) {
    case "b": ghost = "blinky"; break;
    case "i": ghost = "inky"; break;
    case "p": ghost = "pinky"; break;
    case "c": ghost = "clyde"; break;
  }
  this.actorCanvas.clearRect(this[ghost].getClearDimensions());

  if(this[ghost].movementMode == "house") {
    if(this[ghost].y + 8 >= HOUSE_BOTTOM || this[ghost].y - 5 <= HOUSE_TOP) {
      this[ghost].direction = oppositeDirection(this[ghost].direction);
    }
  }
  else if(this[ghost].movementMode == "exitting") {
    this[ghost].exitHouse();
  }
  else if(this[ghost].isCentered()) {
    this[ghost].setNextDirection();
  }

  this[ghost].move();
  this.actorCanvas.renderGhost(this[ghost]);
};
GameController.prototype.handleKeyDown = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    if(this.keyStates[keyPressed] === false) {
      this.keyStates[keyPressed] = true;
      if(this.pacMoveInterval === false) {
        this.pacMoveInterval = setInterval(this.moveActor.bind(this), this.pac.speed);
      }
    }
  }
};
GameController.prototype.handleKeyUp = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    this.keyStates[keyPressed] = false;
  }
};
GameController.prototype.setNextDirection = function(ghost) {
  var currentTile = {
    x: Math.floor(this[ghost].x / 8),
    y: Math.floor(this[ghost].y / 8) - 3
  }
  var adjacentTiles = gameBoard.getAdjacentTiles({
    x: this[ghost].x,
    y: this[ghost].y
  });
  adjacentTiles[oppositeDirection(this[ghost].direction)] = undefined;

  var emptyTiles = gameBoard.getEmptyTiles(adjacentTiles);
  var nextTile = gameBoard.getClosestTile({
    tiles: emptyTiles,
    target: this[ghost].targetTile
  });

  if(nextTile.x < currentTile.x) {
    this[ghost].direction = "left";
  }
  else if(nextTile.x > currentTile.x) {
    this[ghost].direction = "right";
  }
  else if(nextTile.y < currentTile.y) {
    this[ghost].direction = "up";
  }
  else if(nextTile.y > currentTile.y) {
    this[ghost].direction = "down";
  }
};
<commit_msg>Update GameController.moveGhost to use own function setNextDirection<commit_after>var GameController = function(args) {
  this.keyStates = {
    up: false,
    down: false,
    left: false,
    right: false
  }
  this.pacMoveInterval = false;

  this.actorCanvas = args.actorCanvas;
  this.boardCanvas = args.boardCanvas;
  this.pelletCanvas = args.pelletCanvas;

  this.pac = new Actor({
    context: this.actorCanvas.context,
    startX: 113,
    startY: 212,
    name: "m",
    direction: "right"
  });
  this.blinky = new Ghost({
    context: this.actorCanvas.context,
    direction: "left",
    name: "b",
    startX: 112,
    startY: 116
  });
  this.inky = new Ghost({
    context: this.actorCanvas.context,
    direction: "up",
    mode: "house",
    name: "i",
    startX: 96,
    startY: 139
  });
  this.pinky = new Ghost({
    context: this.actorCanvas.context,
    direction: "right",
    mode: "exitting",
    name: "p",
    startX: 112,
    startY: 139
  });
  this.clyde = new Ghost({
    context: this.actorCanvas.context,
    direction: "down",
    mode: "house",
    name: "c",
    startX: 128,
    startY: 139
  });

  this.drawPellets();
  this.actorCanvas.renderPac(this.pac);

  addEventListener("keydown", this.handleKeyDown.bind(this));
  addEventListener("keyup", this.handleKeyUp.bind(this));

  setInterval(function() {
    this.moveGhost("b");
    this.moveGhost("i");
    this.moveGhost("p");
    this.moveGhost("c");
  }.bind(this), GHOST_MOVE_DELAY);

  setTimeout(function() {
    this.inky.setMode("exitting");
  }.bind(this), INKY_EXIT_DELAY);
  setTimeout(function() {
    this.clyde.setMode("exitting");
  }.bind(this), CLYDE_EXIT_DELAY);
}
GameController.prototype.drawPellets = function() {
  this.pelletCanvas.clearRect({
    x: 0,
    y: 0,
    w: BOARD_WIDTH,
    h: BOARD_HEIGHT
  });
  gameBoard.board.matrix.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      if(col == ".") {
        this.pelletCanvas.drawRect({
          x: (8 * cIndex) + 3,
          y: (8 * rIndex) + 27,
          w: 2,
          h: 2
        });
      }
      else if(col == "o") {
        this.pelletCanvas.drawCircle({
          x: (8 * cIndex) + 4,
          y: (8 * rIndex) + 28,
          rad: 4
        });
      }
      else if(col == "-") {
        this.pelletCanvas.drawRect({
          x: 8 * cIndex,
          y: (8 * rIndex) + 29,
          w: 8,
          h: 2
        });
      }
    });
  });
};
GameController.prototype.moveActor = function() {
  this.actorCanvas.clearRect(this.pac.getClearDimensions());
  var coords = {
    x: this.pac.x,
    y: this.pac.y
  }

  var newDirection = false;
  for(var prop in this.keyStates) {
    if(this.keyStates.hasOwnProperty(prop) && this.keyStates[prop]) {
      newDirection = prop;
      break;
    }
  }

  var collision;
  if(this.keyStates[this.pac.direction] === false && newDirection) {
    collision = gameBoard.detectCollision(coords, newDirection);
    if(collision != "door" && collision != "wall") {
      this.pac.direction = newDirection;
    }
  }

  collision = gameBoard.detectCollision(coords, this.pac.direction);
  if(collision == "wall" || collision == "door") {
    clearInterval(this.pacMoveInterval);
    this.pacMoveInterval = false;
  }
  else {
    this.pac.move();
  }
  this.pac.moveTowardCenter();

  this.actorCanvas.renderPac(this.pac);
};
GameController.prototype.moveGhost = function(name) {
  var ghost;
  switch(name) {
    case "b": ghost = "blinky"; break;
    case "i": ghost = "inky"; break;
    case "p": ghost = "pinky"; break;
    case "c": ghost = "clyde"; break;
  }
  this.actorCanvas.clearRect(this[ghost].getClearDimensions());

  if(this[ghost].movementMode == "house") {
    if(this[ghost].y + 8 >= HOUSE_BOTTOM || this[ghost].y - 5 <= HOUSE_TOP) {
      this[ghost].direction = oppositeDirection(this[ghost].direction);
    }
  }
  else if(this[ghost].movementMode == "exitting") {
    this[ghost].exitHouse();
  }
  else if(this[ghost].isCentered()) {
    this.setNextDirection(ghost);
  }

  this[ghost].move();
  this.actorCanvas.renderGhost(this[ghost]);
};
GameController.prototype.handleKeyDown = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    if(this.keyStates[keyPressed] === false) {
      this.keyStates[keyPressed] = true;
      if(this.pacMoveInterval === false) {
        this.pacMoveInterval = setInterval(this.moveActor.bind(this), this.pac.speed);
      }
    }
  }
};
GameController.prototype.handleKeyUp = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    this.keyStates[keyPressed] = false;
  }
};
GameController.prototype.setNextDirection = function(ghost) {
  var currentTile = {
    x: Math.floor(this[ghost].x / 8),
    y: Math.floor(this[ghost].y / 8) - 3
  }
  var adjacentTiles = gameBoard.getAdjacentTiles({
    x: this[ghost].x,
    y: this[ghost].y
  });
  adjacentTiles[oppositeDirection(this[ghost].direction)] = undefined;

  var emptyTiles = gameBoard.getEmptyTiles(adjacentTiles);
  var nextTile = gameBoard.getClosestTile({
    tiles: emptyTiles,
    target: this[ghost].targetTile
  });

  if(nextTile.x < currentTile.x) {
    this[ghost].direction = "left";
  }
  else if(nextTile.x > currentTile.x) {
    this[ghost].direction = "right";
  }
  else if(nextTile.y < currentTile.y) {
    this[ghost].direction = "up";
  }
  else if(nextTile.y > currentTile.y) {
    this[ghost].direction = "down";
  }
};
<|endoftext|>


<commit_before>(function() {
	"use strict";

	// Logger provides logging to the browser’s console, and sending log
	// messages to a server for debugging purposes.
	function Logger(allowSubmissions, submissionUrl) {
		// allowSubmissions indicates whether log messages can be sent to a
		// server for debugging. If set to false, no submissions can be sent,
		// even if the debug, error, info and log methods are called with
		// submit=true.
		this.allowSubmissions = !!allowSubmissions;

		// submissionUrl is the URL to which log messages are sent as a POST
		// request.
		this.submissionUrl = submissionUrl || "";
	}

	Logger.prototype.debug = function(args, submit) {
		this.log(args, submit, Logger.LogTypeDebug);
	};

	Logger.prototype.error = function(args, submit) {
		this.log(args, submit, Logger.LogTypeError);
	};

	Logger.prototype.info = function(args, submit) {
		this.log(args, submit, Logger.LogTypeInfo);
	};

	Logger.prototype.log = function(args, submit, logType) {
		if (window.console) {
			switch (logType) {
				case Logger.LogTypeDebug:
					console.debug(args);
					break;
				case Logger.LogTypeError:
					console.error(args);
					break;
				case Logger.LogTypeInfo:
					console.info(args);
					break;
				default:
					console.log(args);
			}
		}

		if (this.allowSubmissions && submit) {
			this.submit(logType, sprinkles.String.format(args));
		}
	};

	// submit sends a log messages to a server.
	Logger.prototype.submit = function(logType, report) {
		var report = String(logType).toUpperCase() + ": " + String(report);

		var request = new XMLHttpRequest();
		request.onerror = this.error("Logger: Sending %s report failed.", logType);
		request.onload = function(event) {
			if (event.target.status !== 200) {
				request.onerror(event);
				return;
			}
		};
		request.open("POST", this.submissionUrl)
		request.send(report);
	};

	// Log types.
	Logger.LogTypeDebug = "debug";
	Logger.LogTypeError = "error";
	Logger.LogTypeInfo  = "info";

	sprinkles.Logger = Logger;
})();
<commit_msg>Fixed handling of arguments in sprinkles.Logger.<commit_after>(function() {
	"use strict";

	// Logger provides logging to the browser’s console, and sending log
	// messages to a server for debugging purposes.
	function Logger(allowSubmissions, submissionUrl) {
		// allowSubmissions indicates whether log messages can be sent to a
		// server for debugging. If set to false, no submissions can be sent,
		// even if the debug, error, info and log methods are called with
		// submit=true.
		this.allowSubmissions = !!allowSubmissions;

		// submissionUrl is the URL to which log messages are sent as a POST
		// request.
		this.submissionUrl = submissionUrl || "";
	}

	Logger.prototype.debug = function(args, submit) {
		this.log(args, submit, Logger.LogTypeDebug);
	};

	Logger.prototype.error = function(args, submit) {
		this.log(args, submit, Logger.LogTypeError);
	};

	Logger.prototype.info = function(args, submit) {
		this.log(args, submit, Logger.LogTypeInfo);
	};

	Logger.prototype.warn = function(args, submit) {
		this.log(args, submit, Logger.LogTypeWarning);
	};

	Logger.prototype.log = function(args, submit, logType) {
		var console = window.console;
		if (console) {
			switch (logType) {
				case Logger.LogTypeDebug:
					console.debug.apply(console, args);
					break;
				case Logger.LogTypeError:
					console.error.apply(console, args);
					break;
				case Logger.LogTypeInfo:
					console.info.apply(console, args);
					break;
				case Logger.LogTypeWarning:
					console.warn.apply(console, args);
					break;
				default:
					console.log.apply(console, args);
			}
		}

		if (this.allowSubmissions && submit) {
			this.submit(logType, sprinkles.String.format(args));
		}
	};

	// submit sends a log messages to a server.
	Logger.prototype.submit = function(logType, report) {
		var report = String(logType).toUpperCase() + ": " + String(report);

		var request = new XMLHttpRequest();
		request.onerror = this.error("Logger: Sending %s report failed.", logType);
		request.onload = function(event) {
			if (event.target.status !== 200) {
				request.onerror(event);
				return;
			}
		};
		request.open("POST", this.submissionUrl)
		request.send(report);
	};

	// Log types.
	Logger.LogTypeDebug   = "debug";
	Logger.LogTypeError   = "error";
	Logger.LogTypeInfo    = "info";
	Logger.LogTypeWarning = "warning";

	sprinkles.Logger = Logger;
})();
<|endoftext|>