<commit_before>function formatTime(num){
    var minute = '0' + String(Math.floor(num / 60));
    var second = '0' + String(num % 60);

    return minute.substr(-2) + ':' + second.substr(-2);
}

function count(current, maximum){
    if (current > maximum){
        return;
    }

    var timer = $('#timer');
    timer.text(formatTime(current));

    var timeoutId = window.setTimeout(count, 1000, current + 1, maximum);
    $('#stop').click('click', function(){
        window.clearTimeout(timeoutId);
    });
    if (current === maximum){
        timer.css('color', 'red');
        document.getElementById('finished').play();
    }
}

function resetTimer(){
    var timer = $('#timer');
    timer.text('00:00');
    timer.css('color', 'lime');
}

$(function(){
    $('#start').click(function(){
        resetTimer();
        var minute = Math.floor($('#minute').val());
        var second = Math.floor($('#second').val());
        count(0, minute * 60 + second);
    });
    $('#reset').click(function(){
        resetTimer();
    })
});
<commit_msg>タイムアップの1分前にも音を鳴らすようにした<commit_after>function formatTime(num){
    var minute = '0' + String(Math.floor(num / 60));
    var second = '0' + String(num % 60);

    return minute.substr(-2) + ':' + second.substr(-2);
}

function count(current, maximum){
    if (current > maximum){
        return;
    }

    var timer = $('#timer');
    timer.text(formatTime(current));

    var timeoutId = window.setTimeout(count, 1000, current + 1, maximum);
    $('#stop').click('click', function(){
        window.clearTimeout(timeoutId);
    });
    if (current === maximum){
        timer.css('color', 'red');
        document.getElementById('finished').play();
    }
    if (current === maximum - 60){
        document.getElementById('finished').play();
    }
}

function resetTimer(){
    var timer = $('#timer');
    timer.text('00:00');
    timer.css('color', 'lime');
}

$(function(){
    $('#start').click(function(){
        resetTimer();
        var minute = Math.floor($('#minute').val());
        var second = Math.floor($('#second').val());
        count(0, minute * 60 + second);
    });
    $('#reset').click(function(){
        resetTimer();
    })
});
<|endoftext|>


<commit_before>var TMT = TMT || {};

//Grid variables
var xloc;
var yloc;
var rows;
var cols;

var blocks = [];
var vehicles = [];

//Time Elapsed variables
var count;
var MAXTIME;
var text;

//Score text
var scoreText;

//emitter for the explosion for vehicle collisions
var emitter;

//Scale for the entire game
var theScale;

//title screen
TMT.Game = function () {};

TMT.Game.prototype = {
	//vehicle speed
	var trainSpeed;
	var planeSpeed;
	var boatSpeed;

	create: function () {

		//Game level modifier.
		this.adjustLevel(level);

        //background
        this.background = this.game.add.tileSprite(0, 0, this.game.world.width, this.game.world.height, 'gamebg');

        // Generate all the blocks
        this.generateBlocks();

		//adding the loading bar sprite
		this.progbar = this.game.add.sprite(xloc, this.game.height * 0.85, 'progress');
		this.progbar.scale.setTo((theScale*3)/400);

		//attempt at making vehicles group
		this.vehicles = this.game.add.group();
		this.vehicles.enableBody = true;
        this.generatePlane();
		this.generateBoat();
		this.generateTrain();

		//This will create text in the top left of the game screen.
		text = this.game.add.text(xloc/2, yloc/4, 'Time: ' + MAXTIME + '' , { fontSize: this.game.world.width/15+ 'px', fill: '#FFF' });
		count = MAXTIME;
        var counter= setInterval(timer, 1000);

		/*
			This will run a timer that will update the text in the top
			left of the game screen to reflect the time left in the
			timer. (Inside of create function)
		*/
		function timer(){
        	count--;
        	text.text = 'Time: ' + count;
        	if(count<=0){
            	text.text = 'Time\'s up!';
        	}
			this.vehicles.forEach.kill();
		}

		//Allows the game to access the explosion animation.
        emitter = this.game.add.emitter(0,0,10);
        emitter.makeParticles('fire');
        emitter.gravity = 200;

		//code snippet to test the gameEnd UI
		//this.gameEnd();
    },
    /*
		This will allow the game to dynamically adjust it's grid
		according to level. Level initially starts off at -1 but will
		be changed according to the level select.
	*/
	adjustLevel: function(level) {

		//Sets the dimensions of the game to the dimensions of the
		//"canvas" which is your entire game window.
		this.game.world.setBounds(0, 0, this.game.width, this.game.height);

		level = 1;
		if (level === -1) {
			MAXTIME = 20;
			theScale = 75;

			//set grid init position and grid elements
			xloc = this.game.world.width/2 - (theScale * 1.5);
			yloc = this.game.world.height / 3;
			rows = cols = 3;
		}
		if (level === 0) {
			MAXTIME = 30;
			theScale = 100;
			rows = 1;
			cols = 1;

			//set grid init position
			xloc = this.game.world.width/2 - (theScale * 0.5);
			yloc = this.game.world.height/2 - (theScale * 0.5);
		}
		if (level === 1) {
			MAXTIME = 20;
			theScale = 75;

			//set grid init position and grid elements
			xloc = this.game.world.width/2 - (theScale * 1.5);
			yloc = this.game.world.height / 3;
			rows = cols = 3;
		}

	},
	/*
		Create a plane. For now, only creates one plane as referenced
		by this.plane
	*/
    generatePlane: function () {
        //Display setting for the plane.
        this.plane = this.vehicles.create(xloc - 150, yloc + theScale, 'plane1', 2);
        this.plane.scale.setTo(theScale/100);
        this.plane.frame = 0;

		this.plane.life = 3;
		this.plane.dead = false;
		this.plane.moving = false;

		//add physics to the new plane.
        this.game.physics.arcade.enable(this.plane);
        this.plane.body.overlapWorldBounds = true;
		this.plane.body.width = this.plane.body.width / 2;
    	this.plane.body.height = this.plane.body.height / 2;
	},
    /*
		Create a boat. For now, only creates one boat as referenced by
		this.boat
	*/
    generateBoat: function () {
        //Display settings for the boat.
        this.boat = this.vehicles.create(xloc - 150, yloc, 'boat1', 2);
        this.boat.scale.setTo(theScale/100);
        this.boat.frame = 0;

		this.boat.life = 3;
		this.boat.dead = false;
		this.boat.moving = false;

        //add physics to the new boat.
        this.game.physics.arcade.enable(this.boat);
        this.boat.body.overlapWorldBounds = true;
		this.boat.body.width = this.boat.body.width / 2;
    	this.boat.body.height = this.boat.body.height / 2;
    },
    /*
		Create train. For now, only creates one train as referenced by
		this.train
	*/
    generateTrain: function () {
		//Display settings for the train.
        this.train = this.vehicles.create(xloc - 150, yloc + (theScale*2), 'train1', 2);
        this.train.scale.setTo(theScale/100);
        this.train.frame = 0;

		this.train.life = 3;
		this.train.dead = false;
		this.train.moving = false;

        //Add physics to the new train.
        this.game.physics.arcade.enable(this.train);
        this.train.body.overlapWorldBounds = true;
		this.train.body.width = this.train.body.width / 2;
    	this.train.body.height = this.train.body.height / 2;
    },

	enableMoving: function(vehicle) {
		vehicle.moving = true;
	},

    // Generate all blocks
    generateBlocks: function () {
        this.blocks = this.game.add.group();

        //enable physics in them
        this.blocks.enableBody = true;

        //phaser's random number generator
        var numBlocks = cols * rows;
        var current;

		var col = 1;
		var x = xloc;
		var y = yloc;
        for (var i = 0; i < numBlocks; i++) {
            //add sprite
            current = this.blocks.create(x, y, 'terrain');

			//x location of next tile is the next scaled tile.
            x += theScale;

			//If the number of current columns match the desired amount
			//of columns, switch the x back and move the y position.
			if (col++ === cols) {
                x = xloc;
                y += theScale;
				col = 1;
            }

			//Change the scale of the tile from 100px.
            current.scale.setTo(theScale / 100);

            //physics properties
            current.body.velocity.x = 0;
            current.body.velocity.y = 0;
            current.body.immovable = true;
            current.body.collideWorldBounds = true;

            //THIS IS WHERE YOU ENABLE MOUSE CLICKS!!!!
            current.inputEnabled = true;
            current.events.onInputDown.add(this.onDown, this);
            blocks[i] = current;

            //Initializes blank map
            blocks[i].frame = 3;
        }
        current = blocks[0];
    },

	/*
		Update function that will handle:
		1)time progress bar
		2)vehicle unmodified speed
		3)vehicle life points will be check within the overlap function
		4)vehicle overlap with tiles
	*/
	update: function() {
    	//method that will be later refined to show progress better.
		this.progressBar();

		//Sounds must be called inside of this function either directly
		//or with another function entirely (except create and preload)

		//Checks whether or not the vehicle has been "allowed to move."
		if(this.plane.moving)
			this.plane.body.velocity.x = this.game.width/10;
		if(this.boat.moving)
			this.boat.body.velocity.x = this.game.width/15;
		if(this.train.moving)
			this.train.body.velocity.x = this.game.width/12;

		//Overlap that allows all members of vehicles to interact with
		//tiles.
		this.game.physics.arcade.overlap(this.vehicles, this.blocks, this.playSound, this.checkTile, this);

    },
    /*
		Checks the life of all the vehicles to see whether or not they
		have recently died. Called by the update method.
	*/
	lifeCheck: function(vehicle) {
		//Life logic function
		if (vehicle.life <= 0) {
            if(!vehicle.dead)
                this.explosion(vehicle);
            vehicle.dead = true;
			vehicle.kill();
        }
	},

	/*
		Updates the progress bar that will represent the time remaining
		until the player wins the level.
	*/
    progressBar: function() {
		var percent = Math.floor(count / MAXTIME * 100);
		switch(percent) {
			case 100: this.progbar.frame = 10;
			break;
			case 90: this.progbar.frame = 9;
			break;
			case 80: this.progbar.frame = 8;
			break;
			case 70: this.progbar.frame = 7;
			break;
			case 60: this.progbar.frame = 6;
			break;
			case 50: this.progbar.frame = 5;
			break;
			case 40: this.progbar.frame = 4;
			break;
			case 30: this.progbar.frame = 3;
			break;
			case 20: this.progbar.frame = 2;
			break;
			case 10: this.progbar.frame = 1;
			break;
			case 0: this.progbar.frame = 0;
			break;
		}
	},

	/*
		This function is called by the game physics overlap.
        Takes a vehicle and a tile. Check to see if the vehicle matches
		the correct tile.
	*/
    checkTile: function (vehicle, tile) {
        if (vehicle.key === 'boat1'){
			if (tile.frame === 0) //boat travels over water
				return false;
			else
				return true;
		}
		else if (vehicle.key === 'plane1'){
			if (tile.frame === 1) //plane travels over air
				return false;
			else
				return true;
		}
		else if (vehicle.key === 'train1'){
			if (tile.frame === 2) //train travels over train tracks
				return false;
			else
				return true;
		}
	},
    /*
		This function allows the tiles to cycle between our
		spritesheet.
    */
	onDown: function (tile, pointer) {
        if (!this.train.moving){
			setTimeout(this.enableMoving(this.train), 300000000);
			setTimeout(this.enableMoving(this.plane), 300000);
			setTimeout(this.enableMoving(this.boat), 23400);
		}
		switchSound.play();
        if (tile.frame < 2)
            tile.frame++;
        else
            tile.frame = 0;
    },

	/*
		This function will always be called whenever ANY vehicle hits
		the wrong tile. Will check to see if the vehicle has died.
	*/
    playSound: function (vehicle, tile) {
        //right, down, left, up
		explosionSound.play();
		switch(vehicle.frame){
			case 0: //vehicle is going right
				vehicle.body.x = vehicle.body.x - 100;
				break;
			case 1: //vehicle is going down
				vehicle.body.y = vehicle.body.y - 100;
				break;
			case 2: //vehicle is going left
				vehicle.body.x = vehicle.body.x + 100;
				break;
			case 3: //vehicle is going up
				vehicle.body.y = vehicle.body.x + 100;
				break;
		}
		vehicle.life--;

		//Check to see if any vehicles have died recently.
		this.lifeCheck(vehicle);
    },
    /*
		Explosion graphic that will happen to whichever vehicle that
		reaches 0 life. Takes a vehicle as its parameter.
	*/
    explosion: function (vehicle) {
        emitter.x = vehicle.body.x;
        emitter.y = vehicle.body.y;

        //1) boolean for 'explode' (particles generate all at once)
        //2) particle lifespan (ms)
        //3) ignore
        //4) number of particles
        emitter.start(true, 1500, null, 8);
    },

	gameEnd: function() {
		/* Examples for tomorrow to use.

		startClickEvent: function () {
        	this.game.state.start('Game');
    	},
			this.startButton = this.game.add.button(this.game.width / 2, 400, 'startButton', this.startClickEvent, this);

		*/

		var menu = this.game.add.sprite(this.game.world.width /2 - 150, this.game.height * 0.4, 'continueUp');
		var retry = this.game.add.sprite(this.game.world.width /2 - 150, this.game.height * 0.4+105, 'backUp');
		var result = this.game.add.text(this.game.world.width /2 - 150, yloc*0.50, 'Result is PANTS' , { fontSize: this.game.world.width/10+ 'px', fill: '#F00' });
	}

};
<commit_msg>Level 1 is fully functional. Vehicles move based on their planeSpeed or whatever.<commit_after>var TMT = TMT || {};

//Grid variables
var xloc;
var yloc;
var rows;
var cols;

//vehicle speed
var trainSpeed;
var planeSpeed;
var boatSpeed;

var blocks = [];
var vehicles = [];

//Time Elapsed variables
var count;
var MAXTIME;
var text;

//Score text
var scoreText;

//emitter for the explosion for vehicle collisions
var emitter;

//Scale for the entire game
var theScale;

//title screen
TMT.Game = function () {};

TMT.Game.prototype = {

	create: function () {

		//Game level modifier.
		this.adjustLevel(level);

        //background
        this.background = this.game.add.tileSprite(0, 0, this.game.world.width, this.game.world.height, 'gamebg');

        // Generate all the blocks
        this.generateBlocks();

		//adding the loading bar sprite
		this.progbar = this.game.add.sprite(xloc, this.game.height * 0.85, 'progress');
		this.progbar.scale.setTo((theScale*3)/400);

		//attempt at making vehicles group
		this.vehicles = this.game.add.group();
		this.vehicles.enableBody = true;
        this.generatePlane();
		this.generateBoat();
		this.generateTrain();

		//This will create text in the top left of the game screen.
		text = this.game.add.text(xloc/2, yloc/4, 'Time: ' + MAXTIME + '' , { fontSize: this.game.world.width/15+ 'px', fill: '#FFF' });
		count = MAXTIME;
        var counter= setInterval(timer, 1000);

		/*
			This will run a timer that will update the text in the top
			left of the game screen to reflect the time left in the
			timer. (Inside of create function)
		*/
		function timer(){
        	count--;
        	text.text = 'Time: ' + count;
        	if(count<=0){
            	text.text = 'Time\'s up!';
        	}
			this.vehicles.forEach.kill();
		}

		//Allows the game to access the explosion animation.
        emitter = this.game.add.emitter(0,0,10);
        emitter.makeParticles('fire');
        emitter.gravity = 200;

		//code snippet to test the gameEnd UI
		//this.gameEnd();
    },
    /*
		This will allow the game to dynamically adjust it's grid
		according to level. Level initially starts off at -1 but will
		be changed according to the level select.
	*/
	adjustLevel: function(level) {

		//Sets the dimensions of the game to the dimensions of the
		//"canvas" which is your entire game window.
		this.game.world.setBounds(0, 0, this.game.width, this.game.height);

		//level = 1;
		if (level === -1) {
			MAXTIME = 20;
			theScale = 75;

			//vehicle speed
			planeSpeed = this.game.width/10;
			boatSpeed = this.game.width/15;
			trainSpeed = this.game.width/12;

			//set grid init position and grid elements
			xloc = this.game.world.width/2 - (theScale * 1.5);
			yloc = this.game.world.height / 3;
			rows = cols = 3;
		}
		if (level === 0) {
			MAXTIME = 30;
			theScale = 100;
			rows = 1;
			cols = 1;

			//vehicle speed
			planeSpeed = this.game.width/10;
			boatSpeed = this.game.width/15;
			trainSpeed = this.game.width/12;

			//set grid init position
			xloc = this.game.world.width/2 - (theScale * 0.5);
			yloc = this.game.world.height/2 - (theScale * 0.5);
		}
		if (level === 1) {
			MAXTIME = 20;
			theScale = 75;

			//vehicle speed
			planeSpeed = this.game.width/10;
			boatSpeed = this.game.width/15;
			trainSpeed = this.game.width/12;

			//set grid init position and grid elements
			xloc = this.game.world.width/2 - (theScale * 1.5);
			yloc = this.game.world.height / 3;
			rows = cols = 3;
		}

	},
	/*
		Create a plane. For now, only creates one plane as referenced
		by this.plane
	*/
    generatePlane: function () {
        //Display setting for the plane.
        this.plane = this.vehicles.create(xloc - 150, yloc + theScale, 'plane1', 2);
        this.plane.scale.setTo(theScale/100);
        this.plane.frame = 0;

		this.plane.life = 3;
		this.plane.dead = false;
		this.plane.moving = false;

		//add physics to the new plane.
        this.game.physics.arcade.enable(this.plane);
        this.plane.body.overlapWorldBounds = true;
		this.plane.body.width = this.plane.body.width / 2;
    	this.plane.body.height = this.plane.body.height / 2;
	},
    /*
		Create a boat. For now, only creates one boat as referenced by
		this.boat
	*/
    generateBoat: function () {
        //Display settings for the boat.
        this.boat = this.vehicles.create(xloc - 150, yloc, 'boat1', 2);
        this.boat.scale.setTo(theScale/100);
        this.boat.frame = 0;

		this.boat.life = 3;
		this.boat.dead = false;
		this.boat.moving = false;

        //add physics to the new boat.
        this.game.physics.arcade.enable(this.boat);
        this.boat.body.overlapWorldBounds = true;
		this.boat.body.width = this.boat.body.width / 2;
    	this.boat.body.height = this.boat.body.height / 2;
    },
    /*
		Create train. For now, only creates one train as referenced by
		this.train
	*/
    generateTrain: function () {
		//Display settings for the train.
        this.train = this.vehicles.create(xloc - 150, yloc + (theScale*2), 'train1', 2);
        this.train.scale.setTo(theScale/100);
        this.train.frame = 0;

		this.train.life = 3;
		this.train.dead = false;
		this.train.moving = false;

        //Add physics to the new train.
        this.game.physics.arcade.enable(this.train);
        this.train.body.overlapWorldBounds = true;
		this.train.body.width = this.train.body.width / 2;
    	this.train.body.height = this.train.body.height / 2;
    },

	enableMoving: function(vehicle) {
		vehicle.moving = true;
	},

    // Generate all blocks
    generateBlocks: function () {
        this.blocks = this.game.add.group();

        //enable physics in them
        this.blocks.enableBody = true;

        //phaser's random number generator
        var numBlocks = cols * rows;
        var current;

		var col = 1;
		var x = xloc;
		var y = yloc;
        for (var i = 0; i < numBlocks; i++) {
            //add sprite
            current = this.blocks.create(x, y, 'terrain');

			//x location of next tile is the next scaled tile.
            x += theScale;

			//If the number of current columns match the desired amount
			//of columns, switch the x back and move the y position.
			if (col++ === cols) {
                x = xloc;
                y += theScale;
				col = 1;
            }

			//Change the scale of the tile from 100px.
            current.scale.setTo(theScale / 100);

            //physics properties
            current.body.velocity.x = 0;
            current.body.velocity.y = 0;
            current.body.immovable = true;
            current.body.collideWorldBounds = true;

            //THIS IS WHERE YOU ENABLE MOUSE CLICKS!!!!
            current.inputEnabled = true;
            current.events.onInputDown.add(this.onDown, this);
            blocks[i] = current;

            //Initializes blank map
            blocks[i].frame = 3;
        }
        current = blocks[0];
    },

	/*
		Update function that will handle:
		1)time progress bar
		2)vehicle unmodified speed
		3)vehicle life points will be check within the overlap function
		4)vehicle overlap with tiles
	*/
	update: function() {
    	//method that will be later refined to show progress better.
		this.progressBar();

		//Sounds must be called inside of this function either directly
		//or with another function entirely (except create and preload)

		//Checks whether or not the vehicle has been "allowed to move."
		if(this.plane.moving)
			this.plane.body.velocity.x = planeSpeed;
		if(this.boat.moving)
			this.boat.body.velocity.x = boatSpeed;
		if(this.train.moving)
			this.train.body.velocity.x = trainSpeed;

		//Overlap that allows all members of vehicles to interact with
		//tiles.
		this.game.physics.arcade.overlap(this.vehicles, this.blocks, this.playSound, this.checkTile, this);

    },
    /*
		Checks the life of all the vehicles to see whether or not they
		have recently died. Called by the update method.
	*/
	lifeCheck: function(vehicle) {
		//Life logic function
		if (vehicle.life <= 0) {
            if(!vehicle.dead)
                this.explosion(vehicle);
            vehicle.dead = true;
			vehicle.kill();
        }
	},

	/*
		Updates the progress bar that will represent the time remaining
		until the player wins the level.
	*/
    progressBar: function() {
		var percent = Math.floor(count / MAXTIME * 100);
		switch(percent) {
			case 100: this.progbar.frame = 10;
			break;
			case 90: this.progbar.frame = 9;
			break;
			case 80: this.progbar.frame = 8;
			break;
			case 70: this.progbar.frame = 7;
			break;
			case 60: this.progbar.frame = 6;
			break;
			case 50: this.progbar.frame = 5;
			break;
			case 40: this.progbar.frame = 4;
			break;
			case 30: this.progbar.frame = 3;
			break;
			case 20: this.progbar.frame = 2;
			break;
			case 10: this.progbar.frame = 1;
			break;
			case 0: this.progbar.frame = 0;
			break;
		}
	},

	/*
		This function is called by the game physics overlap.
        Takes a vehicle and a tile. Check to see if the vehicle matches
		the correct tile.
	*/
    checkTile: function (vehicle, tile) {
        if (vehicle.key === 'boat1'){
			if (tile.frame === 0) //boat travels over water
				return false;
			else
				return true;
		}
		else if (vehicle.key === 'plane1'){
			if (tile.frame === 1) //plane travels over air
				return false;
			else
				return true;
		}
		else if (vehicle.key === 'train1'){
			if (tile.frame === 2) //train travels over train tracks
				return false;
			else
				return true;
		}
	},
    /*
		This function allows the tiles to cycle between our
		spritesheet.
    */
	onDown: function (tile, pointer) {
        if (!this.train.moving){
			setTimeout(this.enableMoving(this.train), 300000000);
			setTimeout(this.enableMoving(this.plane), 300000);
			setTimeout(this.enableMoving(this.boat), 23400);
		}
		switchSound.play();
        if (tile.frame < 2)
            tile.frame++;
        else
            tile.frame = 0;
    },

	/*
		This function will always be called whenever ANY vehicle hits
		the wrong tile. Will check to see if the vehicle has died.
	*/
    playSound: function (vehicle, tile) {
        //right, down, left, up
		explosionSound.play();
		switch(vehicle.frame){
			case 0: //vehicle is going right
				vehicle.body.x = vehicle.body.x - 100;
				break;
			case 1: //vehicle is going down
				vehicle.body.y = vehicle.body.y - 100;
				break;
			case 2: //vehicle is going left
				vehicle.body.x = vehicle.body.x + 100;
				break;
			case 3: //vehicle is going up
				vehicle.body.y = vehicle.body.x + 100;
				break;
		}
		vehicle.life--;

		//Check to see if any vehicles have died recently.
		this.lifeCheck(vehicle);
    },
    /*
		Explosion graphic that will happen to whichever vehicle that
		reaches 0 life. Takes a vehicle as its parameter.
	*/
    explosion: function (vehicle) {
        emitter.x = vehicle.body.x;
        emitter.y = vehicle.body.y;

        //1) boolean for 'explode' (particles generate all at once)
        //2) particle lifespan (ms)
        //3) ignore
        //4) number of particles
        emitter.start(true, 1500, null, 8);
    },

	gameEnd: function() {
		/* Examples for tomorrow to use.

		startClickEvent: function () {
        	this.game.state.start('Game');
    	},
			this.startButton = this.game.add.button(this.game.width / 2, 400, 'startButton', this.startClickEvent, this);

		*/

		var menu = this.game.add.sprite(this.game.world.width /2 - 150, this.game.height * 0.4, 'continueUp');
		var retry = this.game.add.sprite(this.game.world.width /2 - 150, this.game.height * 0.4+105, 'backUp');
		var result = this.game.add.text(this.game.world.width /2 - 150, yloc*0.50, 'Result is PANTS' , { fontSize: this.game.world.width/10+ 'px', fill: '#F00' });
	}

};
<|endoftext|>


<commit_before>this.interval = null;
this.h = 0;
this.m = 0;
this.s = 0;

var start = function(sendMessageToParticipants){
  if(this.interval  && this.interval != null){
    stop();
  }
  this.interval = setInterval(function(){tick()},1000);
  if(sendMessageToParticipants == true){
    displayMessage(getLocalUser(), "started");
    sendMessage("started");
  }
};

var stop = function(sendMessageToParticipants){
  window.clearInterval(interval);
  if(sendMessageToParticipants == true){
   displayMessage(getLocalUser(), "stopped");
   sendMessage("stopped");
 }
};

var reset = function(sendMessageToParticipants){
 this.h = 0;
 this.m = 0;
 this.s = 0;

 displayTime();
 if(sendMessageToParticipants == true){
  displayMessage(getLocalUser(), "reset");
  sendMessage("reset");
}
};

var getLocalUser =function(){
  return gapi.hangout.getLocalParticipant();
};

var tick = function(){
  this.s += 1;
  if(this.s >= 60)
  {
    this.m += 1;
    this.s = 0;
  }

  if(this.m >= 60){
    this.h += 1;
    this.m = 0;
  }

  displayTime();
};

var displayTime = function(){
  html = "";
  html += getText(this.h)
  html += ":";

  html += getText(this.m)
  html += ":";

  html += getText(this.s)

  document.getElementById('timer').innerText = html;
};

var getText = function(n){
  var str  = "";
  if(n<10)
    str += "0";
  str += n;
  return str;
};

var sendMessage = function(msg){
  var message = {"action":msg,"hours":this.h, "minutes":this.m, "seconds":this.s};
  msg = JSON.stringify(msg);
  gapi.hangout.data.sendMessage(msg)
  console.log(msg);
};

var getUser = function(){
  return "user";
};

var init = function(){
 console.log('init called');
 gapi.hangout.onApiReady.add(
  function(eventObj) {
    if (eventObj.isApiReady) {
      try {
        gapi.hangout.data.onMessageReceived.add(
          function(msg){
           console.log('message received');
           var participant = gapi.hangout.getParticipantById(msg.senderId);
           var message = JSON.parse(msg.message);

           displayMessage(participant, message.action);

           this.h = message.hours;
           this.m = message.minutes;
           this.s = message.seconds;

           displayTime();
         });
        console.log('message handler registered');
      } catch (e) {
        console.log('init:ERROR');
        console.log(e);
      }
    }
  });
};

var displayMessage = function(participant, message){
  var messageArea =   document.getElementById('messageArea');
  messageArea.innerText = messageArea.innerHTML + "\n" + participant.person.displayName + " : " + message ;
  messageArea.scrollTop = messageArea.scrollTop + 50;
};

gadgets.util.registerOnLoadHandler(init);
console.log('script loaded'); <commit_msg>fixed js error<commit_after>this.interval = null;
this.h = 0;
this.m = 0;
this.s = 0;

var start = function(sendMessageToParticipants){
  if(this.interval  && this.interval != null){
    stop();
  }
  this.interval = setInterval(function(){tick()},1000);
  if(sendMessageToParticipants == true){
    displayMessage(getLocalUser(), "started");
    sendMessage("started");
  }
};

var stop = function(sendMessageToParticipants){
  window.clearInterval(interval);
  if(sendMessageToParticipants == true){
   displayMessage(getLocalUser(), "stopped");
   sendMessage("stopped");
 }
};

var reset = function(sendMessageToParticipants){
 this.h = 0;
 this.m = 0;
 this.s = 0;

 displayTime();
 if(sendMessageToParticipants == true){
  displayMessage(getLocalUser(), "reset");
  sendMessage("reset");
}
};

var getLocalUser =function(){
  return gapi.hangout.getLocalParticipant();
};

var tick = function(){
  this.s += 1;
  if(this.s >= 60)
  {
    this.m += 1;
    this.s = 0;
  }

  if(this.m >= 60){
    this.h += 1;
    this.m = 0;
  }

  displayTime();
};

var displayTime = function(){
  html = "";
  html += getText(this.h)
  html += ":";

  html += getText(this.m)
  html += ":";

  html += getText(this.s)

  document.getElementById('timer').innerText = html;
};

var getText = function(n){
  var str  = "";
  if(n<10)
    str += "0";
  str += n;
  return str;
};

var sendMessage = function(msg){
  var message = {"action":msg,"hours":this.h, "minutes":this.m, "seconds":this.s};
  msg = JSON.stringify(message);
  gapi.hangout.data.sendMessage(msg)
  console.log(msg);
};

var getUser = function(){
  return "user";
};

var init = function(){
 console.log('init called');
 gapi.hangout.onApiReady.add(
  function(eventObj) {
    if (eventObj.isApiReady) {
      try {
        gapi.hangout.data.onMessageReceived.add(
          function(msg){
           console.log('message received');
           var participant = gapi.hangout.getParticipantById(msg.senderId);
           var message = JSON.parse(msg.message);

           displayMessage(participant, message.action);

           this.h = message.hours;
           this.m = message.minutes;
           this.s = message.seconds;

           displayTime();
         });
        console.log('message handler registered');
      } catch (e) {
        console.log('init:ERROR');
        console.log(e);
      }
    }
  });
};

var displayMessage = function(participant, message){
  var messageArea =   document.getElementById('messageArea');
  messageArea.innerText = messageArea.innerHTML + "\n" + participant.person.displayName + " : " + message ;
  messageArea.scrollTop = messageArea.scrollTop + 50;
};

gadgets.util.registerOnLoadHandler(init);
console.log('script loaded'); <|endoftext|>


<commit_before>'use strict'

function micropubGet (qs) {
	let link = localStorage.getItem('micropub_link')
	return fetch(link.indexOf('?') === -1 ? link + '?' + qs : link + '&' + qs, {
		headers: {
			Accept: 'application/json',
			Authorization: 'Bearer ' + localStorage.getItem('access_token')
		}
	})
}

function micropubPost (obj) {
	return fetch(localStorage.getItem('micropub_link'), {
		method: 'post',
		headers: {
			Accept: 'application/json',
			'Content-Type': 'application/json',
			Authorization: 'Bearer ' + localStorage.getItem('access_token')
		},
		body: JSON.stringify(obj)
	})
}

Polymer({
	is: 'micro-panel',

	properties: {
		selected: { type: Number, value: 0 },
		src: { type: String, value: "/" },
		editing: { type: Array, value: [] }
	},

	attached() {
		if (!(localStorage.getItem('access_token') && localStorage.getItem('micropub_link'))) {
			if (location.search.match(/code=/))
				this.authFinish()
			else
				this.showAuthDialog()
		}
		this.$.frame.addEventListener('load', load => {
			console.log(load)
			let style = load.target.contentDocument.createElement('style')
			style.innerHTML += '.h-entry { border: 2px solid blue; }'
			style.innerHTML += '.h-entry::before { content: "Edit"; background: blue; color: white; padding: 6px; display: block; cursor: pointer; }'
			load.target.contentDocument.body.appendChild(style)
			load.target.contentDocument.addEventListener('click', this.editClick.bind(this))
		})
	},

	editClick(e) {
		if (!e.target.classList.contains('h-entry')) return
		let entry = Microformats.get({ node: e.target, textFormat: 'normalised' }).items[0]
		let i = 0
		if (this.editing.find(editingEntry => {
			i += 1
			return ((editingEntry.properties || {}).uid || [1])[0] == ((entry.properties || {}).uid || [1])[0]
		})) {
			this.selected = 1 + i
			return
		}
		let frameUrl = this.$.frame.contentWindow.location.href
		let url = ((entry.properties || {}).url || [frameUrl])[0]
		if (frameUrl == url)
			return this.editStart(entry)
		micropubGet('q=source&url=' + encodeURIComponent(url))
		.then(resp => resp.json())
		.then(fullEntry => this.editStart(fullEntry))
		.catch(e => {
			console.log('Error when asking micropub for entry source', e)
			fetch(url)
			.then(resp => resp.text())
			.then(body => {
				let fullEntry = Microformats.get({ html: body, textFormat: 'normalised', filter: ['h-entry'] }).items[0]
				this.editStart(fullEntry)
			})
			.catch(e => {
				console.log('Error when fetching entry', e)
				this.editStart(entry)
			})
		})
	},

	editStart(entry) {
		this.push('editing', entry)
		this.selected = 1 + this.editing.length
	},

	deleteEntry(e) {
		if (!confirm('Are you sure you want to delete the entry?')) return
		let entry = e.model.item
		let url = ((entry.properties || {}).url || [null])[0]
		if (!url) return alert('Somehow, an entry with no URL! I have no idea how to delete that.')
		micropubPost({ 'mp-action': 'delete', url: url })
		.then(resp => {
			if (resp.status >= 300) throw new Error("Couldn't delete the entry! Response: " + resp.status)
			this.stopEditing(entry)
		})
		.catch(e => {
			console.log('Error when deleting entry', e)
			alert(e)
		})
	},

	saveEntry(e) {
		if (!confirm('Are you sure you want to save the entry?')) return
		let entry = e.model.item
		let url = ((entry.properties || {}).url || [null])[0]
		if (!url) return alert('Somehow, an entry with no URL! I have no idea how to save that.')
		micropubPost({ 'mp-action': 'update', url: url, replace: { properties: entry.properties } })
		.then(resp => {
			if (resp.status >= 300) throw new Error("Couldn't save the entry! Response: " + resp.status)
			this.stopEditing(entry)
		})
		.catch(e => {
			console.log('Error when saving entry', e)
			alert(e)
		})
	},

	stopEditing(entry) {
		this.splice('editing', this.editing.indexOf(entry), 1)
		this.$.frame.src = this.$.frame.src // reload
		this.selected = 0
	},

	showAuthDialog() {
		this.$['auth-url-input'].value = location.origin
		this.$['auth-dialog'].open()
	},

	authStart() {
		fetch(this.$['auth-url-input'].value)
		.then(resp => {
			let links = resp.headers.get('Link')
			let micropub_link = links.match(/<([^>]+)>;[^,]*rel="[^,]*micropub[^,]*"/)[1]
			let auth_link = links.match(/<([^>]+)>;[^,]*rel="[^,]*authorization_endpoint[^,]*"/)[1] || 'https://indieauth.com/auth'
			let token_link = links.match(/<([^>]+)>;[^,]*rel="[^,]*token_endpoint[^,]*"/)[1]
			let state = new Uint8Array(32)
			crypto.getRandomValues(state)
			state = state.join('')
			localStorage.setItem('micropub_link', micropub_link)
			localStorage.setItem('auth_link', auth_link)
			localStorage.setItem('token_link', token_link)
			localStorage.setItem('state', state)
			localStorage.setItem('redirect_uri', location.href)
			location.href = auth_link +
				'?me=' + encodeURIComponent(this.$['auth-url-input'].value) +
				'&client_id=' + encodeURIComponent(this.$['auth-url-input'].value) +
				'&redirect_uri=' + encodeURIComponent(location.href) +
				'&state=' + encodeURIComponent(state) +
				'&scope=post'
		})
	},

	authFinish() {
		let code = location.search.match(/code=([^&]+)/)[1]
		let me = location.search.match(/me=([^&]+)/)[1]
		fetch(localStorage.getItem('token_link'), {
			method: 'post',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
			body: 'code=' + code + '&me=' + me + '&client_id=' + me +
				'&redirect_uri=' + encodeURIComponent(localStorage.getItem('redirect_uri')) +
				'&state=' + encodeURIComponent(localStorage.getItem('state')) + '&scope=post'
		}).then(resp => {
			console.log(resp)
			return resp.text()
		}).then(body => {
			let token = body.match(/access_token=([^&]+)/)[1]
			if (!token) throw new Error('No access token in response')
			localStorage.setItem('access_token', token)
			localStorage.removeItem('auth_link')
			localStorage.removeItem('token_link')
			localStorage.removeItem('state')
			localStorage.removeItem('redirect_uri')
			history.replaceState({}, '', location.href.replace(/\?[^#]*/, ''))
		}).catch(e => {
			console.log(e)
			// TODO: show error to user
			this.authStart()
		})
	},

	showOpenUrl() {
		this.$['menu-button'].close()
		this.$['open-url-input'].value = this.$.frame.contentWindow.location.href
		this.$['open-url-dialog'].open()
	},

	openUrlClosed(e) {
		if (!e.detail.confirmed) return
		this.src = this.$['open-url-input'].value
		this.selected = 0
	},

	showAbout() {
		this.$['menu-button'].close()
		this.$['about-dialog'].open()
	}

})

<commit_msg>some refactoring<commit_after>'use strict'

function saveAuthParams (links) {
	let micropub_link = links.match(/<([^>]+)>;[^,]*rel="[^,]*micropub[^,]*"/)[1]
	let auth_link = links.match(/<([^>]+)>;[^,]*rel="[^,]*authorization_endpoint[^,]*"/)[1] || 'https://indieauth.com/auth'
	let token_link = links.match(/<([^>]+)>;[^,]*rel="[^,]*token_endpoint[^,]*"/)[1]
	localStorage.setItem('micropub_link', micropub_link)
	localStorage.setItem('auth_link', auth_link)
	localStorage.setItem('token_link', token_link)
	localStorage.setItem('redirect_uri', location.href)
}

function saveAndGetState () {
	let state = new Uint8Array(32)
	crypto.getRandomValues(state)
	state = state.join('')
	localStorage.setItem('state', state)
	return state
}

function setAccessToken (token) {
	localStorage.setItem('access_token', token)
	localStorage.removeItem('auth_link')
	localStorage.removeItem('token_link')
	localStorage.removeItem('state')
	localStorage.removeItem('redirect_uri')
	history.replaceState({}, '', location.href.replace(/\?[^#]*/, ''))
}

function micropubGet (qs) {
	let link = localStorage.getItem('micropub_link')
	return fetch(link.indexOf('?') === -1 ? link + '?' + qs : link + '&' + qs, {
		headers: {
			Accept: 'application/json',
			Authorization: 'Bearer ' + localStorage.getItem('access_token')
		}
	})
}

function micropubPost (obj) {
	return fetch(localStorage.getItem('micropub_link'), {
		method: 'post',
		headers: {
			Accept: 'application/json',
			'Content-Type': 'application/json',
			Authorization: 'Bearer ' + localStorage.getItem('access_token')
		},
		body: JSON.stringify(obj)
	})
}

Polymer({
	is: 'micro-panel',

	properties: {
		selected: { type: Number, value: 0 },
		src: { type: String, value: "/" },
		editing: { type: Array, value: [] }
	},

	attached() {
		if (!(localStorage.getItem('access_token') && localStorage.getItem('micropub_link'))) {
			if (location.search.match(/code=/))
				this.authFinish()
			else
				this.showAuthDialog()
		}
		this.$.frame.addEventListener('e', e => {
			console.log(e)
			let style = e.target.contentDocument.createElement('style')
			style.innerHTML += '.h-entry { border: 2px solid blue; }'
			style.innerHTML += '.h-entry::before { content: "Edit"; background: blue; color: white; padding: 6px; display: block; cursor: pointer; }'
			e.target.contentDocument.body.appendChild(style)
			e.target.contentDocument.addEventListener('click', this.editClick.bind(this))
		})
	},

	editClick(e) {
		if (!e.target.classList.contains('h-entry')) return
		let entry = Microformats.get({ node: e.target, textFormat: 'normalised' }).items[0]
		let i = 0
		if (this.editing.find(editingEntry => {
			i += 1
			return ((editingEntry.properties || {}).uid || [1])[0] == ((entry.properties || {}).uid || [1])[0]
		})) {
			this.selected = 1 + i
			return
		}
		let frameUrl = this.$.frame.contentWindow.location.href
		let url = ((entry.properties || {}).url || [frameUrl])[0]
		if (frameUrl == url)
			return this.editStart(entry)
		micropubGet('q=source&url=' + encodeURIComponent(url))
		.then(resp => resp.json())
		.then(fullEntry => this.editStart(fullEntry))
		.catch(e => {
			console.log('Error when asking micropub for entry source', e)
			fetch(url)
			.then(resp => resp.text())
			.then(body => {
				let fullEntry = Microformats.get({ html: body, textFormat: 'normalised', filter: ['h-entry'] }).items[0]
				this.editStart(fullEntry)
			})
			.catch(e => {
				console.log('Error when fetching entry', e)
				this.editStart(entry)
			})
		})
	},

	editStart(entry) {
		this.push('editing', entry)
		this.selected = 1 + this.editing.length
	},

	deleteEntry(e) {
		if (!confirm('Are you sure you want to delete the entry?')) return
		let entry = e.model.item
		let url = ((entry.properties || {}).url || [null])[0]
		if (!url) return alert('Somehow, an entry with no URL! I have no idea how to delete that.')
		micropubPost({ 'mp-action': 'delete', url: url })
		.then(resp => {
			if (resp.status >= 300) throw new Error("Couldn't delete the entry! Response: " + resp.status)
			this.editFinish(entry)
		})
		.catch(e => {
			console.log('Error when deleting entry', e)
			alert(e)
		})
	},

	saveEntry(e) {
		if (!confirm('Are you sure you want to save the entry?')) return
		let entry = e.model.item
		let url = ((entry.properties || {}).url || [null])[0]
		if (!url) return alert('Somehow, an entry with no URL! I have no idea how to save that.')
		micropubPost({ 'mp-action': 'update', url: url, replace: { properties: entry.properties } })
		.then(resp => {
			if (resp.status >= 300) throw new Error("Couldn't save the entry! Response: " + resp.status)
			this.editFinish(entry)
		})
		.catch(e => {
			console.log('Error when saving entry', e)
			alert(e)
		})
	},

	editFinish(entry) {
		this.splice('editing', this.editing.indexOf(entry), 1)
		this.$.frame.src = this.$.frame.src // reload
		this.selected = 0
	},

	showAuthDialog() {
		this.$['auth-url-input'].value = location.origin
		this.$['auth-dialog'].open()
	},

	authStart() {
		fetch(this.$['auth-url-input'].value)
		.then(resp => {
			let links = resp.headers.get('Link')
			saveAuthParams(links)
			let state = saveAndGetState()
			location.href = auth_link +
				'?me=' + encodeURIComponent(this.$['auth-url-input'].value) +
				'&client_id=' + encodeURIComponent(this.$['auth-url-input'].value) +
				'&redirect_uri=' + encodeURIComponent(location.href) +
				'&state=' + encodeURIComponent(state) +
				'&scope=post'
		})
	},

	authFinish() {
		let code = location.search.match(/code=([^&]+)/)[1]
		let me = location.search.match(/me=([^&]+)/)[1]
		fetch(localStorage.getItem('token_link'), {
			method: 'post',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
			body: 'code=' + code + '&me=' + me + '&client_id=' + me +
				'&redirect_uri=' + encodeURIComponent(localStorage.getItem('redirect_uri')) +
				'&state=' + encodeURIComponent(localStorage.getItem('state')) + '&scope=post'
		}).then(resp => {
			console.log(resp)
			return resp.text()
		}).then(body => {
			let token = body.match(/access_token=([^&]+)/)[1]
			if (!token) throw new Error('No access token in response')
			setAccessToken(token)
		}).catch(e => {
			console.log(e)
			alert('Could not get access token from the token endpoint.')
			this.authStart()
		})
	},

	showOpenUrl() {
		this.$['menu-button'].close()
		this.$['open-url-input'].value = this.$.frame.contentWindow.location.href
		this.$['open-url-dialog'].open()
	},

	openUrlClosed(e) {
		if (!e.detail.confirmed) return
		this.src = this.$['open-url-input'].value
		this.selected = 0
	},

	showAbout() {
		this.$['menu-button'].close()
		this.$['about-dialog'].open()
	}

})
<|endoftext|>


<commit_before>module.exports = (function () {

    var request = require('request');
    var token = null;
    var last_activity_date = null;

    function Tindr() {}

    /**
     * The Options object that is passed in to the requests
     * @param  {string} method Specifies wether it's a GET POST PUT or DELETE
     * @param  {string} path   the endpoint
     * @param  {object} data   object passed with the request
     * @return {Promise}
     */
    function configureOptions(method, path, data) {
        var options = {
            url: 'https://api.gotinder.com' + path,
            method: method,
            form: data,
            headers: {
                'Content-Type': 'application/json'
            }
        };

        if (token) {
            options.headers['X-Auth-Token'] = token;
        }

        return options;
    }

    /**
     * Here we make the acutual requests
     * @param  {string} method Method type (GET POST PUT DELETE)
     * @param  {string} path   endpoint
     * @param  {object} data   Pass in data with a POST request
     * @return {Promise}
     */
    function tinderRequest(method, path, data) {

        var options = configureOptions(method, path, data);

        return new Promise(function (resolve, reject) {
                return request(options, function (err, response, body) {
                    var data = null;

                    try {
                        data = JSON.parse(body);
                    } catch (err) {
                        return reject('Unable to parse body => ' + err);
                    }

                    if (!err && response.statusCode === 200) {
                        resolve(data);
                    } else {
                        reject(err || data);
                    }
                });
            })
            .then(function (data) {
                return data;
            })
            .catch(function (err) {
                return Promise.reject(err);
            })
    }

    /**
     * Setting up data for a GET request
     * @param  {path} the endpoint
     * @return {Promise}
     */
    function tinderGet(path) {
        return tinderRequest('GET', path, null);
    }

    /**
     * Setting up data for a POST request
     * @param  {path} the endpoint
     * @param  {data} if you want to pass data with the request
     * @return {Promise}
     */
    function tinderPost(path, data) {
        return tinderRequest('POST', path, data);
    }

    /**
     * A user needs to log in, in order to use the API
     * @param  {string} fb_token Facebook token
     * @param  {string} fb_id    Facebook id
     * @return {Promise}         Return a promise containing either data or error
     */
    Tindr.prototype.auth = function (fb_token, fb_id) {

        return tinderPost('/auth', {
                facebook_token: fb_token,
                facebook_id: fb_id
            })
            .then(function (data) {
                token = data.token;
                last_activity_date = data.create_date;

                return data;
            })
            .catch(function (err) {
                return Promise.reject(err);
            });
    };

    /**
     * Send a text message with token (needs to be done when the account is created)
     * @param  {number} phone_number The phone number you want the code to be sent to
     * @return {Promise}
     */
    Tindr.prototype.sendToken = function (phone_number) {
        return tinderPost('/sendtoken', {
            phone_number: phone_number
        });
    };

    /**
     * Get object containing info in regards to your own profile
     * @return {Promise}
     */
    Tindr.prototype.myProfile = function () {
        return tinderGet('/profile');
    };

    /**
     * Get profiles near your current location
     * @return {Promise}
     */
    Tindr.prototype.getRecommendations = function () {
        return tinderGet('/recs/core');
    }

    /**
     * Get groups near your current location
     * @return {Promise}
     */
    Tindr.prototype.getGroups = function () {
        return tinderGet('/recs/social');
    };

    /**
     * Like a person
     * @param  {string} user The profile you want to swipe right on
     * @return {Promise}
     */
    Tindr.prototype.like = function (user) {
        return tinderGet('/like/' + user);
    };

    /**
     * Pass on a user
     * @param  {string} user The user you want to left-swipe
     * @return {Promise}
     */
    Tindr.prototype.pass = function (user) {
        return tinderGet('/pass/' + user);
    };

    /**
     * Contains an object with info. People who liked you back,
     * the list over blocked people, last activity etc..
     * @return {Promise}
     */
    Tindr.prototype.update = function () {
        return tinderPost('/updates', {
            last_activity_date: last_activity_date
        });
    };

    /**
     * For updating your profile
     * @param  {object} profile An Object Containing the new changes
     * @return {Promise}
     */
    Tindr.prototype.updateProfile = function (profile) {
        if (typeof profile !== 'object') {
            return Promise.reject('Expected argument of type: Object');
        }

        return tinderPost('/profile', profile);
    };

    return new Tindr();

})();
<commit_msg>modified the tinderRequest<commit_after>module.exports = (function () {

    var request = require('request');
    var token = null;
    var last_activity_date = null;

    function Tindr() {}

    /**
     * The Options object that is passed in to the requests
     * @param  {string} method Specifies wether it's a GET POST PUT or DELETE
     * @param  {string} path   the endpoint
     * @param  {object} data   object passed with the request
     * @return {Promise}
     */
    function configureOptions(method, path, data) {
        var options = {
            url: 'https://api.gotinder.com' + path,
            method: method,
            form: data,
            headers: {
                'Content-Type': 'application/json'
            }
        };

        if (token) {
            options.headers['X-Auth-Token'] = token;
        }

        return options;
    }

    /**
     * Here we make the acutual requests
     * @param  {string} method Method type (GET POST PUT DELETE)
     * @param  {string} path   endpoint
     * @param  {object} data   Pass in data with a POST request
     * @return {Promise}
     */
    function tinderRequest(method, path, data) {

        var options = configureOptions(method, path, data);

        return new Promise(function (resolve, reject) {
            return request(options, function (err, response, body) {
                var data = null;

                try {
                    data = JSON.parse(body);
                } catch (err) {
                    return reject('Unable to parse body => ' + err);
                }

                if (!err && response.statusCode === 200) {
                    resolve(data);
                } else {
                    reject(err || data);
                }
            });
        });
    }

    /**
     * Setting up data for a GET request
     * @param  {path} the endpoint
     * @return {Promise}
     */
    function tinderGet(path) {
        return tinderRequest('GET', path, null);
    }

    /**
     * Setting up data for a POST request
     * @param  {path} the endpoint
     * @param  {data} if you want to pass data with the request
     * @return {Promise}
     */
    function tinderPost(path, data) {
        return tinderRequest('POST', path, data);
    }

    /**
     * A user needs to log in, in order to use the API
     * @param  {string} fb_token Facebook token
     * @param  {string} fb_id    Facebook id
     * @return {Promise}         Return a promise containing either data or error
     */
    Tindr.prototype.auth = function (fb_token, fb_id) {

        return tinderPost('/auth', {
                facebook_token: fb_token,
                facebook_id: fb_id
            })
            .then(function (data) {
                token = data.token;
                last_activity_date = data.create_date;

                return data;
            })
            .catch(function (err) {
                return Promise.reject(err);
            });
    };

    /**
     * Send a text message with token (needs to be done when the account is created)
     * @param  {number} phone_number The phone number you want the code to be sent to
     * @return {Promise}
     */
    Tindr.prototype.sendToken = function (phone_number) {
        return tinderPost('/sendtoken', {
            phone_number: phone_number
        });
    };

    /**
     * Get object containing info in regards to your own profile
     * @return {Promise}
     */
    Tindr.prototype.myProfile = function () {
        return tinderGet('/profile');
    };

    /**
     * Get profiles near your current location
     * @return {Promise}
     */
    Tindr.prototype.getRecommendations = function () {
        return tinderGet('/recs/core');
    }

    /**
     * Get groups near your current location
     * @return {Promise}
     */
    Tindr.prototype.getGroups = function () {
        return tinderGet('/recs/social');
    };

    /**
     * Like a person
     * @param  {string} user The profile you want to swipe right on
     * @return {Promise}
     */
    Tindr.prototype.like = function (user) {
        return tinderGet('/like/' + user);
    };

    /**
     * Pass on a user
     * @param  {string} user The user you want to left-swipe
     * @return {Promise}
     */
    Tindr.prototype.pass = function (user) {
        return tinderGet('/pass/' + user);
    };

    /**
     * Contains an object with info. People who liked you back,
     * the list over blocked people, last activity etc..
     * @return {Promise}
     */
    Tindr.prototype.update = function () {
        return tinderPost('/updates', {
            last_activity_date: last_activity_date
        });
    };

    /**
     * For updating your profile
     * @param  {object} profile An Object Containing the new changes
     * @return {Promise}
     */
    Tindr.prototype.updateProfile = function (profile) {
        if (typeof profile !== 'object') {
            return Promise.reject('Expected argument of type: Object');
        }

        return tinderPost('/profile', profile);
    };

    return new Tindr();

})();
<|endoftext|>


<commit_before>/// <reference path="../typings/tsd.d.ts" />
var express = require("express");
var router = express.Router();
var ad = require("../modules/Ad");
router.route("/ad").get(function (req, res) {
    console.log(req.query);
    ad.addAdLog(req.query).then(function (data) {
    });
}).post(function (req, res) {
    ad.getAdLogs().then(function (data) {
        return res.json(data);
    });
});
module.exports = router;
<commit_msg>完善 广告日志记录<commit_after>/// <reference path="../typings/tsd.d.ts" />
var express = require("express");
var router = express.Router();
var ad = require("../modules/Ad");
router.route("/ad").get(function (req, res) {
    ad.addAdLog(req.query).then(function (data) {
        res.sendStatus(200);
    });
}).post(function (req, res) {
    ad.getAdLogs().then(function (data) {
        return res.json(data);
    });
});
module.exports = router;
<|endoftext|>


<commit_before>'use strict';

var P = require('bluebird');
var preq = require('preq');
var domino = require('domino');
var sUtil = require('../lib/util');
var kafka = P.promisifyAll(require('kafka-node'));
var HighLevelProducer = kafka.HighLevelProducer;
var KeyedMessage = kafka.KeyedMessage;

var options = {
    connectionString: undefined, //"kafka-event-bus.services.eqiad.wmflabs:2181/kafka/kafka-event-bus",
    clientId: 0
};

var client = new kafka.Client(options.connectionString,
        options.clientId, options);
var producer = new HighLevelProducer(client);

producer.on('ready', console.log);

producer.on('error', console.log)

// shortcut
var HTTPError = sUtil.HTTPError;

/**
 * The main router object
 */
var router = sUtil.router();

/**
 * The main application object reported when this module is require()d
 */
var app;

var exampleSchema = {
	"title": "Example Schema",
	"type": "object",
	"properties": {
		"url": {
			"type": "string"
		},
		"type": {
			"type": "string"
		},
		"details": {
			"type": "string"
		}
	},
	"required": ["url", "name"]
};

var ajv = require('ajv')();
// add each validator
var validateMessage = ajv.compile(exampleSchema);

/**
 * PUT /topics/{name}
 * Create / update a topic. Accepts a JSON schema.
 */
router.put('/topics/:name', function(req, res) {
    producer.createTopics([req.params.name]);
    res.end(200);
});
/*
 * Expected layout
 * {
 *    topic: 'topicName',
 *    messages: ['message body'],// multi messages should be a array, single message can be just a string or a KeyedMessage instance
 *    // These might be best controlled by the proxy
 *    partition: 0, //default 0
 *    attributes: 2, // default: 0
 * }
 */

function validateMessages(topic, messages) {
    messages = messages.map(function(msg) {
        validateMessage(msg);
        return JSON.stringify(msg);
    });
    return {
        topic: topic,
        messages: messages,
        attributes: 2, // snappy compression
    };
}

/**
 * POST /topics/{name}/
 * Enqueue one or more events. Each event needs to conform to the JSON schema
 * associated with this topic.
 */
router.get('/topics/:name', function(req, res) {
    return P.try(function() {
        var message = validateMessages(req.params.name, req.body);
        return producer.sendAsync([message]);
    });
});

module.exports = function(appObj) {

    app = appObj;

    return {
        path: '/',
        api_version: 1,
        router: router
    };

};

<commit_msg>Fix responses<commit_after>'use strict';

var P = require('bluebird');
var preq = require('preq');
var domino = require('domino');
var sUtil = require('../lib/util');
var kafka = P.promisifyAll(require('kafka-node'));
var HighLevelProducer = kafka.HighLevelProducer;
var KeyedMessage = kafka.KeyedMessage;

var options = {
    connectionString: undefined, //"kafka-event-bus.services.eqiad.wmflabs:2181/kafka/kafka-event-bus",
    clientId: 0
};

var client = new kafka.Client(options.connectionString,
        options.clientId, options);
var producer = new HighLevelProducer(client);

producer.on('ready', console.log);

producer.on('error', console.log)

// shortcut
var HTTPError = sUtil.HTTPError;

/**
 * The main router object
 */
var router = sUtil.router();

/**
 * The main application object reported when this module is require()d
 */
var app;

var exampleSchema = {
	"title": "Example Schema",
	"type": "object",
	"properties": {
		"url": {
			"type": "string"
		},
		"type": {
			"type": "string"
		},
		"details": {
			"type": "string"
		}
	},
	"required": ["url", "name"]
};

var ajv = require('ajv')();
// add each validator
var validateMessage = ajv.compile(exampleSchema);

/**
 * PUT /topics/{name}
 * Create / update a topic. Accepts a JSON schema.
 */
router.put('/topics/:name', function(req, res) {
    producer.createTopics([req.params.name]);
    res.send('Topic created', 200);
});
/*
 * Expected layout
 * {
 *    topic: 'topicName',
 *    messages: ['message body'],// multi messages should be a array, single message can be just a string or a KeyedMessage instance
 *    // These might be best controlled by the proxy
 *    partition: 0, //default 0
 *    attributes: 2, // default: 0
 * }
 */

function validateMessages(topic, messages) {
    messages = messages.map(function(msg) {
        validateMessage(msg);
        return JSON.stringify(msg);
    });
    return {
        topic: topic,
        messages: messages,
        attributes: 2, // snappy compression
    };
}

/**
 * POST /topics/{name}/
 * Enqueue one or more events. Each event needs to conform to the JSON schema
 * associated with this topic.
 */
router.post('/topics/:name', function(req, res) {
    return P.try(function() {
        var message = validateMessages(req.params.name, req.body);
        return producer.sendAsync([message]);
    })
    .then(function(res) {
        res.send('Message enqueued', 200);
    });
});

module.exports = function(appObj) {

    app = appObj;

    return {
        path: '/',
        api_version: 1,
        router: router
    };

};

<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var users = {};
var numUsers = 0;
var rooms = ['Sports', 'TV', 'World News', 'Programming', 'Android', 'Apple'];
var roomJoinMsgs = ['Welcome to Sports', 'Welcome to TV', 'Welcome to Programming', 'Welcome to Android', 'Welcome to Apple']

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
	socket.emit('connection message', {
		message : "Welcome. Please enter a nickname."
	});

	socket.on('set username', function(msg){
		socket.username = msg.username;

		++numUsers;
		users[msg.username] = msg.username

		socket.emit('username set', {
			result : true
		})
	});

	socket.on('join room', function (msg){
		socket.roomNum = msg.roomNum;
		socket.join(rooms[socket.roomNum]);

		socket.emit('room join message', {
			message : roomJoinMsgs[socket.roomNum]
		});

		io.to(rooms[socket.roomNum]).emit('user joined', {
			message : socket.username
		});
	});

	socket.on('send message', function(msg){
		if (socket.username) {
			socket.broadcast.to(rooms[socket.roomNum]).emit('chat message', {
				message : msg.message,
				sender : socket.username
			});
		}
  	});

	socket.on('leave room', function(){
		var roomNum = socket.roomNum;
		socket.leave(rooms[socket.roomNum])
		socket.roomNum = undefined;

  		io.to(rooms[roomNum]).emit('user left', {
  			message : socket.username
  		});
	});

  	socket.on('disconnect', function(){
  		io.to(rooms[socket.roomNum]).emit('user left', {
  			message : socket.username
  		});
  	});
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
<commit_msg>change room implementation to return list of room objects<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var async = require('async');

var users = {};
var numUsers = 0;
var rooms = [{room : 'Sports', id : 0},
 {room : 'TV', id : 1},
 {room : 'World News', id : 2},
 {room : 'Programming', id : 3},
 {room : 'Android', id : 4},
 {room : 'Apple', id : 5}];

var roomJoinMsgs = ['Welcome to Sports', 'Welcome to TV', 'Welcome to World News', 'Welcome to Programming', 'Welcome to Android', 'Welcome to Apple']

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
	socket.emit('connection message', {
		message : "Welcome. Please enter a nickname."
	});

	socket.on('set username', function(msg){
		socket.username = msg.username;

		++numUsers;
		users[msg.username] = msg.username

		socket.emit('username set', {
			result : true,
			rooms : rooms
		})
	});

	socket.on('join room', function (msg){
		async.series([
			function(callback) {
				console.log(socket.roomNum);

				if (typeof socket.roomNum !== 'undefined') {
					socket.leave(socket.roomNum);

					io.to(socket.roomNum).emit('user left', {
  						message : socket.username
  					});

  					socket.roomNum = undefined;
				}

				callback();
			},
			function (callback) {
				socket.roomNum = msg.roomNum;
				socket.join(socket.roomNum);

				socket.emit('room join message', {
					message : roomJoinMsgs[socket.roomNum]
				});

				io.to(socket.roomNum).emit('user joined', {
					message : socket.username
				});

				callback()
			}
		]);
	});

	socket.on('send message', function(msg){
		if (socket.username) {
			socket.broadcast.to(socket.roomNum).emit('chat message', {
				message : msg.message,
				sender : socket.username
			});
		}
  	});

  	socket.on('disconnect', function(){
  		io.to(socket.roomNum).emit('user left', {
  			message : socket.username
  		});
  	});
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
<|endoftext|>


<commit_before>document.getElementById("id_logic_level_version").innerHTML="Business level version 2017.11.08.0";

var canvas = document.getElementById("id_canvas");
var context = canvas.getContext("2d");

window.addEventListener("touchstart", on_touch_start);

function on_touch_start(e)
{
    var touches = e.changedTouches;
    for (i = 0; i < e.changedTouches.length; i++){
        context.beginPath();
        context.arc(touches[i].pageX, touches[i].pageY, 10, 0, Math.PI);
        context.stroke();
    }

}<commit_msg>Canvas touchstart and added full circle, not just half<commit_after>document.getElementById("id_logic_level_version").innerHTML="Business level version 2017.11.08.2";

var canvas = document.getElementById("id_canvas");
var context = canvas.getContext("2d");

canvas.addEventListener("touchstart", on_touch_start);

function on_touch_start(e)
{
    var touches = e.changedTouches;
    for (i = 0; i < e.changedTouches.length; i++){
        context.beginPath();
        context.arc(touches[i].pageX, touches[i].pageY, 10, 0, 2 * Math.PI);
        context.stroke();
    }

}<|endoftext|>


<commit_before>const puppeteer = require('puppeteer')
let browser, page

const options = {
    args: [
        '--disable-accelerated-video',
        '--disable-gpu',
        '--disable-local-storage'
    ],
    headless: true,
    ignoreHTTPSErrors: true
}

async function enterFlightCities(origin, destination) {
    await page.waitFor('#s2id_origin .select2-choices')
    await page.click('#s2id_origin .select2-choices')
    await page.type('#s2id_autogen1', origin, { delay: 30 })

    await page.waitFor('#s2id_destination .select2-choices')
    await page.click('#s2id_destination .select2-choices')
    await page.type('#s2id_autogen2', destination, { delay: 30 })
}

async function enterFlightDates(departureDate, returnDate) {
    await page.type('#departure_date', departureDate, { delay: 30 })
    await page.type('#return_date', returnDate, { delay: 30 })
}

async function chooseEconomy() {
    // economy container button
    await page.waitFor(1)
    await page.waitFor('#offer-container-0-0 button')
    await page.click('#offer-container-0-0 button')

    // 'Economy Deal' button
    await page.waitFor(1)
    await page.waitFor('tr.flight-offers-comparison > td > table > tbody > tr:nth-child(13) > td:nth-child(2) > button')
    await page.click('tr.flight-offers-comparison > td > table > tbody > tr:nth-child(13) > td:nth-child(2) > button')
}

async function enterNumberOfPersonsAndSubmit(number) {
    await page.type('#adultNum', number, { delay: 50 })
    await page.click('#classes-submit button[type=submit]')
}

async function deleteAllCookiesFor(url) {
    let cookies = await page.cookies(url)
    await page.deleteCookie(...cookies)
}

async function trackThemDown() {
    try {
        console.log('Opening browser...')
        browser = await puppeteer.launch(options)

        console.log('Opening new page...')
        page = await browser.newPage()

        page.setViewport({ width: 1280, height: 720 })

        console.log(`Going to https://airserbia.com/en/`)
        await page.goto('https://airserbia.com/en/')

        await deleteAllCookiesFor('https://airserbia.com/en/')

        console.log('Entering flight origin and destination')
        await enterFlightCities('Belgrade', 'Rome')

        console.log('Entering dates')
        await enterFlightDates('05/04/2018', '09/04/2018')

        await enterNumberOfPersonsAndSubmit('2')

        // Wait for flight results
        console.log('Waiting for flights')
        await page.waitFor('.flights-table')

        console.log('Choose economy departure')
        await chooseEconomy()

        // Wait for submission of economy departure
        await page.waitFor('.dxp-selected-flight')

        console.log('Choose economy return')
        await chooseEconomy()

        // Wait for submission of economy return
        console.log('Waiting for total amount')
        await page.waitFor('.dxp-trip-total .total-amount-item')

        await deleteAllCookiesFor('https://booking.airserbia.com')

        return await page.evaluate(
            x => ({
                currency: document.querySelector('.total-amount-item .price .currency').textContent.trim(),
                amount: document.querySelector('.total-amount-item .price .amount .integer').textContent.trim()
            })
        )
    } finally {
        await page.close().catch(error => console.log(`Error closing page: ${error}.`))
        await browser.close()
    }
}

// trackThemDown()
//     .then(money => console.log(`${money.currency} ${money.amount}`))
//     .catch() // run it again
//     // store to db

module.exports = trackThemDown<commit_msg>add some waiting and no sandbox flag<commit_after>const puppeteer = require('puppeteer')
let browser, page

const options = {
    args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-accelerated-video',
        '--disable-gpu',
        '--disable-local-storage'
    ],
    headless: true,
    ignoreHTTPSErrors: true
}

async function enterFlightCities(origin, destination) {
    await page.waitFor('#s2id_origin .select2-choices')
    await page.click('#s2id_origin .select2-choices')
    await page.type('#s2id_autogen1', origin, { delay: 30 })

    await page.waitFor('#s2id_destination .select2-choices')
    await page.click('#s2id_destination .select2-choices')
    await page.type('#s2id_autogen2', destination, { delay: 30 })
}

async function enterFlightDates(departureDate, returnDate) {
    await page.type('#departure_date', departureDate, { delay: 30 })
    await page.type('#return_date', returnDate, { delay: 30 })
}

async function chooseEconomy() {
    // economy container button
    await page.waitFor(5)
    await page.waitFor('#offer-container-0-0 button')
    await page.click('#offer-container-0-0 button')

    // 'Economy Deal' button
    await page.waitFor(5)
    await page.waitFor('tr.flight-offers-comparison > td > table > tbody > tr:nth-child(13) > td:nth-child(2) > button')
    await page.click('tr.flight-offers-comparison > td > table > tbody > tr:nth-child(13) > td:nth-child(2) > button')
}

async function enterNumberOfPersonsAndSubmit(number) {
    await page.type('#adultNum', number, { delay: 50 })
    await page.click('#classes-submit button[type=submit]')
}

async function deleteAllCookiesFor(url) {
    let cookies = await page.cookies(url)
    await page.deleteCookie(...cookies)
}

async function trackThemDown() {
    try {
        console.log('Opening browser...')
        browser = await puppeteer.launch(options)

        console.log('Opening new page...')
        page = await browser.newPage()

        page.setViewport({ width: 1280, height: 720 })

        console.log(`Going to https://airserbia.com/en/`)
        await page.goto('https://airserbia.com/en/')

        await deleteAllCookiesFor('https://airserbia.com/en/')

        console.log('Entering flight origin and destination')
        await enterFlightCities('Belgrade', 'Rome')

        console.log('Entering dates')
        await enterFlightDates('05/04/2018', '09/04/2018')

        await enterNumberOfPersonsAndSubmit('2')

        // Wait for flight results
        console.log('Waiting for flights')
        await page.waitFor('.flights-table')

        console.log('Choose economy departure')
        await chooseEconomy()

        // Wait for submission of economy departure
        await page.waitFor('.dxp-selected-flight')

        console.log('Choose economy return')
        await chooseEconomy()

        // Wait for submission of economy return
        console.log('Waiting for total amount')
        await page.waitFor('.dxp-trip-total .total-amount-item')

        await deleteAllCookiesFor('https://booking.airserbia.com')

        return await page.evaluate(
            x => ({
                currency: document.querySelector('.total-amount-item .price .currency').textContent.trim(),
                amount: document.querySelector('.total-amount-item .price .amount .integer').textContent.trim()
            })
        )
    } finally {
        await page.close().catch(error => console.log(`Error closing page: ${error}.`))
        await browser.close()
    }
}

// trackThemDown()
//     .then(money => console.log(`${money.currency} ${money.amount}`))
//     .catch() // run it again
//     // store to db

module.exports = trackThemDown<|endoftext|>


<commit_before>/**
 * Created by arminhammer on 11/18/15.
 */
console.log('Loaded!');
var P = require('bluebird');

//var $ = jQuery= require('jquery');
//window.$ = $;
//var bootstrap = require('bootstrap');

//require('../node_modules/bootstrap/js/affix');
//require('../node_modules/bootstrap/js/scrollspy');

var m = require('mithril');
var _ = require('lodash');

//var ipcRenderer = P.promisifyAll(require('electron').ipcRenderer);

// In renderer process (web page).
var ipcRenderer = require('electron').ipcRenderer;
//console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"

var vpcs = m.prop([]);

var Resource = function(name, body) {
	var self = this;
	self.name = name;
	self.body = body;
	self.inTemplate = m.prop(false);
	self.toggleInTemplate = function(setting) {
		console.log('toggled ' + setting);
		self.inTemplate(setting);
	}
};

var resources = {
	Autoscaling: {
		AutoScalingGroups: [],
		LaunchConfigurations: [],
		LifecycleHooks: [],
		ScalingPolicys: [],
		ScheduledActions: []
	},
	EC2: {
		'CustomerGateway' : [],
		'DHCPOptions' : [],
		'EIP' : [],
		'EIPAssociation' : [],
		'Instance' : [],
		'InternetGateway' : [],
		'NetworkAcl' : [],
		'NetworkAclEntry' : [],
		'NetworkInterface' : [],
		'NetworkInterfaceAttachment' : [],
		'PlacementGroup' : [],
		'Route' : [],
		'RouteTable' : [],
		'SecurityGroup' : [],
		'SecurityGroupEgress' : [],
		'SecurityGroupIngress' : [],
		'SpotFleet' : [],
		'Subnet' : [],
		'SubnetNetworkAclAssociation' : [],
		'SubnetRouteTableAssociation' : [],
		'Volume' : [],
		'VolumeAttachment' : [],
		'VPC' : [],
		'VPCDHCPOptionsAssociation' : [],
		'VPCEndpoint' : [],
		'VPCGatewayAttachment' : [],
		'VPCPeeringConnection' : [],
		'VPNConnection' : [],
		'VPNConnectionRoute' : [],
		'VPNGateway' : [],
		'VPNGatewayRoutePropagation' : []
	}
	//vpcs: []
};

console.log('Resources before');
console.log(resources.vpcs);

ipcRenderer.on('vpc-reply', function(event, res) {
	m.startComputation();
	res.Vpcs.forEach(function(vpc) {
		resources.EC2.VPC.push(new Resource(vpc.VpcId, vpc));
	});
	m.endComputation();
});

ipcRenderer.send('vpc-request');

var ui = {
	controller: function() {
		this.resources = resources;
	},
	view: function(controller) {
		return m(".container", [
			m(".navbar.navbar-fixed-top", [
				m(".container", [
					m(".navbar-header", [
						m("a.navbar-brand[href='#']", "Bellerophon")
					])
				])
			]),
			m(".row.MainContent", [
				m("nav.col-xs-3.bs-docs-sidebar", [
					m("ul.nav.nav-stacked.fixed[id='sidebar']", [
						_.map(controller.resources, function(resource, key) {
							return m("li", [
								m("a[href='#" + key + "']", key),
								m("ul.nav.nav-stacked", [
									_.map(controller.resources[key], function(subResource, subKey) {
										return m("li", [m("a[href='#" + key + subKey + "']", subKey)])
									})
								])
							])
						})
						/*
						 m("li", [
						 m("a[href='#Autoscaling']", "Autoscaling"),
						 m("ul.nav.nav-stacked", [
						 m("li", [m("a[href='#AutoscalingAutoScalingGroup']", "AutoScalingGroup")]),
						 m("li", [m("a[href='#AutoscalingLaunchConfiguration']", "LaunchConfiguration")]),
						 m("li", [m("a[href='#AutoscalingLifecycleHook']", "LifecycleHook")]),
						 m("li", [m("a[href='#AutoscalingScalingPolicy']", "ScalingPolicy")]),
						 m("li", [m("a[href='#AutoscalingScheduledAction']", "ScheduledAction")])
						 ])
						 ]),
						 m("li", [
						 m("a[href='#VPC']", "EC2"),
						 m("ul.nav.nav-stacked", [
						 m("li", [m("a[href='#VPCSub1']", "Sub-Group 1")]),
						 m("li", [m("a[href='#VPCSub2']", "Sub-Group 2")])
						 ])
						 ])
						 */
					])
				]),
				m(".col-xs-9", [
					_.map(controller.resources, function(resource, key) {
						return m("section.group[id='" + key + "']", [
							m("h3", key),
							_.map(controller.resources[key], function(subResource, subKey) {
								return m(".subgroup[id='" + key + subKey + "']", [
									m("h4", subKey)
								])
							})
						])
					})
					/*
					 m("section.group[id='Autoscaling']", [
					 m("h3", "Autoscaling"),
					 m(".subgroup[id='AutoscalingAutoScalingGroup']", [
					 m("h4", "AutoScalingGroup")
					 ]),
					 m(".subgroup[id='AutoscalingLaunchConfiguration']", [
					 m("h4", "LaunchConfiguration")
					 ]),
					 m(".subgroup[id='AutoscalingLifecycleHook']", [
					 m("h4", "LifecycleHook")
					 ]),
					 m(".subgroup[id='AutoscalingScalingPolicy']", [
					 m("h4", "ScalingPolicy")
					 ]),
					 m(".subgroup[id='AutoscalingScheduledAction']", [
					 m("h4", "ScheduledAction")
					 ])
					 ]),
					 m("section.group[id='VPC']", [
					 m("h3", "EC2"),
					 m(".subgroup[id='VPCSub1']", [
					 m("h4", "Group A Sub 1")
					 ]),
					 m(".subgroup[id='VPCSub2']", [
					 m("h4", "Group A Sub 2")
					 ])
					 ])
					 */
				])
			]),
			"\n"
		])
		/*
		 return ('div', [
		 m('p', 'VPCs'),
		 m('div', [
		 controller.resources.vpcs.map(function(vpc) {
		 console.log(vpc.name);
		 console.log(vpc.inTemplate());
		 //console.log(vpc);
		 return m('div', [
		 m('p', [
		 m("input[type=checkbox]", { checked: vpc.inTemplate(), name: vpc.name, onclick: m.withAttr("checked", vpc.toggleInTemplate ) }),
		 vpc.name
		 ])
		 ])
		 })
		 ])
		 ])*/
	}
};

m.mount(document.body,ui);
<commit_msg>Autogeneration of the UI complete.<commit_after>/**
 * Created by arminhammer on 11/18/15.
 */
console.log('Loaded!');
var P = require('bluebird');

//var $ = jQuery= require('jquery');
//window.$ = $;
//var bootstrap = require('bootstrap');

//require('../node_modules/bootstrap/js/affix');
//require('../node_modules/bootstrap/js/scrollspy');

var m = require('mithril');
var _ = require('lodash');

//var ipcRenderer = P.promisifyAll(require('electron').ipcRenderer);

// In renderer process (web page).
var ipcRenderer = require('electron').ipcRenderer;
//console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"

var vpcs = m.prop([]);

var Resource = function(name, body) {
	var self = this;
	self.name = name;
	self.body = body;
	self.inTemplate = m.prop(false);
	self.toggleInTemplate = function(setting) {
		console.log('toggled ' + setting);
		self.inTemplate(setting);
	}
};

var resources = {
	Autoscaling: {
		AutoScalingGroup: [],
		LaunchConfiguration: [],
		LifecycleHook: [],
		ScalingPolicy: [],
		ScheduledAction: []
	},
	EC2: {
		/*
		CustomerGateway : [],
		DHCPOptions : [],
		EIP : [],
		EIPAssociation : [],
		Instance : [],
		InternetGateway : [],
		NetworkAcl : [],
		NetworkAclEntry : [],
		NetworkInterface : [],
		NetworkInterfaceAttachment : [],
		PlacementGroup : [],
		Route : [],
		RouteTable : [],
		*/
		SecurityGroup : [],
		/*
		SecurityGroupEgress : [],
		SecurityGroupIngress : [],
		SpotFleet : [],
		*/
		Subnet : [],
		/*
		SubnetNetworkAclAssociation : [],
		SubnetRouteTableAssociation : [],
		Volume : [],
		VolumeAttachment : [],
		*/
		VPC : []
		/*
		VPCDHCPOptionsAssociation : [],
		VPCEndpoint : [],
		VPCGatewayAttachment : [],
		VPCPeeringConnection : [],
		VPNConnection : [],
		VPNConnectionRoute : [],
		VPNGateway : [],
		VPNGatewayRoutePropagation : []
		*/
	}
	//vpcs: []
};

//console.log('Resources before');
//console.log(resources.vpcs);

ipcRenderer.on('vpc-reply', function(event, res) {
	m.startComputation();
	res.Vpcs.forEach(function(vpc) {
		resources.EC2.VPC.push(new Resource(vpc.VpcId, vpc));
	});
	m.endComputation();
	console.log('Added VPCs!');
	console.log(resources.EC2.VPC);
});

ipcRenderer.send('vpc-request');

var ui = {
	controller: function() {
		this.resources = resources;
	},
	view: function(controller) {
		return m(".container", [
			m(".navbar.navbar-fixed-top", [
				m(".container", [
					m(".navbar-header", [
						m("a.navbar-brand[href='#']", "Bellerophon")
					])
				])
			]),
			m(".row.MainContent", [
				m("nav.col-xs-3.bs-docs-sidebar", [
					m("ul.nav.nav-stacked.fixed[id='sidebar']", [
						_.map(controller.resources, function(resource, key) {
							return m("li", [
								m("a[href='#" + key + "']", key),
								m("ul.nav.nav-stacked", [
									_.map(controller.resources[key], function(subResource, subKey) {
										return m("li", [m("a[href='#" + key + subKey + "']", subKey)])
									})
								])
							])
						})
					])
				]),
				m(".col-xs-9", [
					_.map(controller.resources, function(group, key) {
						return m("section.group[id='" + key + "']", [
							m("h3", key),
							_.map(controller.resources[key], function(subResource, subKey) {
								return m(".subgroup[id='" + key + subKey + "']", [
									m("h4", subKey),
									_.map(controller.resources[key][subKey], function(resource) {
										return m('div', [
											m("input[type=checkbox]", { checked: resource.inTemplate(), name: resource.name, onclick: m.withAttr("checked", resource.toggleInTemplate ) }),
											resource.name
										])
									})
								])
							})
						])
					})
				])
			]),
			"\n"
		])
		/*
		 return ('div', [
		 m('p', 'VPCs'),
		 m('div', [
		 controller.resources.vpcs.map(function(vpc) {
		 console.log(vpc.name);
		 console.log(vpc.inTemplate());
		 //console.log(vpc);
		 return m('div', [
		 m('p', [
		 m("input[type=checkbox]", { checked: vpc.inTemplate(), name: vpc.name, onclick: m.withAttr("checked", vpc.toggleInTemplate ) }),
		 vpc.name
		 ])
		 ])
		 })
		 ])
		 ])*/
	}
};

m.mount(document.body,ui);
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var async = require('async');
var request = require('request');

module.exports = function(options){
  var seneca = this;
  var plugin = 'cd-users';
  var ENTITY_NS = 'sys/user';
  var so = seneca.options();

  seneca.add({role: plugin, cmd: 'load'}, cmd_load);
  seneca.add({role: plugin, cmd: 'list'}, cmd_list);
  seneca.add({role: plugin, cmd: 'register'}, cmd_register);
  seneca.add({role: plugin, cmd: 'promote'}, cmd_promote);
  seneca.add({role: plugin, cmd: 'get_users_by_emails'}, cmd_get_users_by_emails);
  seneca.add({role: plugin, cmd: 'update'}, cmd_update);
  seneca.add({role: plugin, cmd: 'get_init_user_types'}, cmd_get_init_user_types);
  seneca.add({role: plugin, cmd: 'is_champion'}, cmd_is_champion);

  function cmd_load(args, done) {
    var seneca = this;
    var id = args.id;
    var userEntity = seneca.make(ENTITY_NS);

    async.waterfall([
      function(done) {
        seneca.make(ENTITY_NS).load$({id: args.id}, done);
      },
      function(user, done) {
        return done(null, user.data$());
      }
    ], done);
  }

  function cmd_list(args, done){
    var seneca = this;

    async.waterfall([
      function(done) {
        seneca.make(ENTITY_NS).list$({ids: args.ids}, done);
      },
      function(users, done) {
        return done(null, _.map(users, function (user) {
          return user.data$();
        }));
      }
    ], done);
  }

  // We create an Account in Salesforce with the champion information and we also create a Lead.
  // The user.id is used for both Account and Leads.
  function updateSalesForce(user) {
    // ideally would be done in a workqueue
    process.nextTick(function() {
      if (process.env.SALESFORCE_ENABLED !== 'true') return;

      var account = {
        PlatformId__c: user.id,
        PlatformUrl__c: 'https://zen.coderdojo.com/dashboard/profile/' + user.id,
        Email__c: user.email,
        Name: user.name,
        //RecordTypeId: "0121100000051tU" // TODO - not working
      };

      seneca.act('role:cd-salesforce,cmd:save_account', {userId: user.id, account:account}, function (err, res){
        if (err) return seneca.log.error('Error creating Account in SalesForce!', err);
        seneca.log.info('Created Account in SalesForce', account, res);

        var lead = {
          PlatformId__c: user.id,
          PlatformUrl__c: 'https://zen.coderdojo.com/dashboard/profile/' + user.id,
          Email__c: user.email,
          LastName: user.name,
          //RecordTypeId: "0121100000051tU", // TODO - not working
          Company: '<n/a>',
          "ChampionAccount__c": res.id$
        };

        seneca.act('role:cd-salesforce,cmd:save_lead', {userId: user.id, lead:lead}, function (err, res){
          if (err) return seneca.log.error('Error creating Lead in SalesForce!', err);
          seneca.log.info('Created Lead in SalesForce', account, res);
        });
      });
    });
  }

  function cmd_register(args, done) {
    var isChampion = args.isChampion === true;
    delete args.isChampion;

    //Roles Available: basic-user, mentor, champion, cdf-admin
    var seneca = this;

    if(!args['g-recaptcha-response']){
      return done(new Error('Error with captcha'));
    }

    var secret = so['recaptcha_secret_key'];
    var captchaResponse = args['g-recaptcha-response'];

    var postData = {
      url: 'https://www.google.com/recaptcha/api/siteverify',
      form: {
        response: captchaResponse,
        secret: secret
      }
    };

    function verifyCaptcha(done){
      request.post(postData, function(err, response, body){
        if(err){
          return done(err);
        }

        body = JSON.parse(body);

        if(!body.success){
          return done(JSON.stringify(body['error-codes']));
        }

        return done(null, body.success);
      });
    }

    function registerUser(success, done){
      args = _.omit(args, ['g-recaptcha-response']);

      args.roles = ['basic-user'];
      args.mailingList = (args.mailingList) ? 1 : 0;
      seneca.act({role:'user', cmd:'register'}, args, function (err, registerResponse) {
        if(err) return done(err);
        if(!registerResponse.ok) return done(new Error(registerResponse.why));

        var user = registerResponse.user;
        //Create user profile based on initial user type.
        var userType = 'attendee-o13';
        if (user.initUserType) userType.name = user.initUserType.name;

        var profileData = {
          userId:user.id,
          email:user.email,
          userType: userType
        };
        seneca.act({role:'cd-profiles', cmd:'save', profile: profileData}, function (err, profile) {
          if(err) return done(err);
          if (registerResponse.ok === true && isChampion === true) updateSalesForce(registerResponse.user);
          done(null, registerResponse);
        });
      });
    }

    async.waterfall([
      verifyCaptcha,
      registerUser
    ], done);
  }

  function cmd_promote(args, done) {
    var seneca = this;
    var newRoles = args.roles;
    var userId = args.id;
    var userEntity = seneca.make$(ENTITY_NS);

    userEntity.load$(userId, function(err, response) {
      if(err) return done(err);
      var user = response;
      _.each(newRoles, function(newRole) {
        user.roles.push(newRole);
      });
      user.roles = _.uniq(user.roles);
      userEntity.save$(user, function(err, response) {
        if(err) return done(err);
        done(null, response);
      });
    });

  }

  function cmd_get_users_by_emails(args, done){
    var seneca = this, query = {};

    query.email = new RegExp(args.email, 'i');
    query.limit$ = query.limit$ ? query.limit$ : 10;

    seneca.make(ENTITY_NS).list$(query, function(err, users){
      if(err){
        return done(err);
      }

      users = _.map(users, function(user){
        return {email: user.email, id: user.id};
      });

      users = _.uniq(users, 'email');

      done(null, users);
    });
  }

  function cmd_update(args, done) {
    var seneca = this;
    var user = args.user;

    var userEntity = seneca.make(ENTITY_NS);

    userEntity.save$(user, done);
  }

  function cmd_get_init_user_types(args, done) {
    var seneca = this;
    //These types can be selected during registration on the platform.
    var initUserTypes = [
      {title: 'Youth Under 13', name: 'attendee-u13'},
      {title: 'Youth Over 13', name: 'attendee-o13'},
      {title: 'Parent/Guardian', name: 'parent-guardian'},
      {title: 'Mentor/Volunteer', name: 'mentor'},
      {title: 'Champion', name: 'champion'}
    ];
    done(null, initUserTypes);
  }

  /**
   * This function returns if true if a user is champion and it's dojos if any.
   */
  function cmd_is_champion(args, done){
    var seneca = this;

    seneca.make(ENTITY_NS).load$({id: args.id}, function(err, user) {
      if (err) {
        return done(err)
      }

      user = user.data$();

      var query = {
        query: {
          filtered: {
            query: {
              match_all: {}
            },
            filter: {
              bool: {
                must: [{
                  term: {userId: args.id}
                }]
              }
            }
          }
        }
      };

      seneca.act({
        role: 'cd-dojos',
        cmd: 'search',
        search: query,
        type: 'cd_dojoleads',
        user: user
      }, function (err, dojoLeads) {
        if (err) {
          return done(err)
        }

        if (dojoLeads.total > 0) {
          seneca.act({role: 'cd-dojos', cmd: 'my_dojos', user: user}, function (err, myDojos) {
            if (err) {
              return done(err)
            }

            return done(null, {
              isChampion: true,
              dojos: myDojos
            });
          });
        } else {
          return done(null, {isChampion: false});
        }
      });
    });
  }

  return {
    name: plugin
  };

};
<commit_msg>fix user type for profile when registering<commit_after>'use strict';

var _ = require('lodash');
var async = require('async');
var request = require('request');

module.exports = function(options){
  var seneca = this;
  var plugin = 'cd-users';
  var ENTITY_NS = 'sys/user';
  var so = seneca.options();

  seneca.add({role: plugin, cmd: 'load'}, cmd_load);
  seneca.add({role: plugin, cmd: 'list'}, cmd_list);
  seneca.add({role: plugin, cmd: 'register'}, cmd_register);
  seneca.add({role: plugin, cmd: 'promote'}, cmd_promote);
  seneca.add({role: plugin, cmd: 'get_users_by_emails'}, cmd_get_users_by_emails);
  seneca.add({role: plugin, cmd: 'update'}, cmd_update);
  seneca.add({role: plugin, cmd: 'get_init_user_types'}, cmd_get_init_user_types);
  seneca.add({role: plugin, cmd: 'is_champion'}, cmd_is_champion);

  function cmd_load(args, done) {
    var seneca = this;
    var id = args.id;
    var userEntity = seneca.make(ENTITY_NS);

    async.waterfall([
      function(done) {
        seneca.make(ENTITY_NS).load$({id: args.id}, done);
      },
      function(user, done) {
        return done(null, user.data$());
      }
    ], done);
  }

  function cmd_list(args, done){
    var seneca = this;

    async.waterfall([
      function(done) {
        seneca.make(ENTITY_NS).list$({ids: args.ids}, done);
      },
      function(users, done) {
        return done(null, _.map(users, function (user) {
          return user.data$();
        }));
      }
    ], done);
  }

  // We create an Account in Salesforce with the champion information and we also create a Lead.
  // The user.id is used for both Account and Leads.
  function updateSalesForce(user) {
    // ideally would be done in a workqueue
    process.nextTick(function() {
      if (process.env.SALESFORCE_ENABLED !== 'true') return;

      var account = {
        PlatformId__c: user.id,
        PlatformUrl__c: 'https://zen.coderdojo.com/dashboard/profile/' + user.id,
        Email__c: user.email,
        Name: user.name,
        //RecordTypeId: "0121100000051tU" // TODO - not working
      };

      seneca.act('role:cd-salesforce,cmd:save_account', {userId: user.id, account:account}, function (err, res){
        if (err) return seneca.log.error('Error creating Account in SalesForce!', err);
        seneca.log.info('Created Account in SalesForce', account, res);

        var lead = {
          PlatformId__c: user.id,
          PlatformUrl__c: 'https://zen.coderdojo.com/dashboard/profile/' + user.id,
          Email__c: user.email,
          LastName: user.name,
          //RecordTypeId: "0121100000051tU", // TODO - not working
          Company: '<n/a>',
          "ChampionAccount__c": res.id$
        };

        seneca.act('role:cd-salesforce,cmd:save_lead', {userId: user.id, lead:lead}, function (err, res){
          if (err) return seneca.log.error('Error creating Lead in SalesForce!', err);
          seneca.log.info('Created Lead in SalesForce', account, res);
        });
      });
    });
  }

  function cmd_register(args, done) {
    var isChampion = args.isChampion === true;
    delete args.isChampion;

    //Roles Available: basic-user, mentor, champion, cdf-admin
    var seneca = this;

    if(!args['g-recaptcha-response']){
      return done(new Error('Error with captcha'));
    }

    var secret = so['recaptcha_secret_key'];
    var captchaResponse = args['g-recaptcha-response'];

    var postData = {
      url: 'https://www.google.com/recaptcha/api/siteverify',
      form: {
        response: captchaResponse,
        secret: secret
      }
    };

    function verifyCaptcha(done){
      request.post(postData, function(err, response, body){
        if(err){
          return done(err);
        }

        body = JSON.parse(body);

        if(!body.success){
          return done(JSON.stringify(body['error-codes']));
        }

        return done(null, body.success);
      });
    }

    function registerUser(success, done){
      args = _.omit(args, ['g-recaptcha-response']);

      args.roles = ['basic-user'];
      args.mailingList = (args.mailingList) ? 1 : 0;
      seneca.act({role:'user', cmd:'register'}, args, function (err, registerResponse) {
        if(err) return done(err);
        if(!registerResponse.ok) return done(new Error(registerResponse.why));

        var user = registerResponse.user;
        //Create user profile based on initial user type.
        var userType = 'attendee-o13';
        if (user.initUserType) userType = user.initUserType.name;

        var profileData = {
          userId:user.id,
          email:user.email,
          userType: userType
        };
        seneca.act({role:'cd-profiles', cmd:'save', profile: profileData}, function (err, profile) {
          if(err) return done(err);
          if (registerResponse.ok === true && isChampion === true) updateSalesForce(registerResponse.user);
          done(null, registerResponse);
        });
      });
    }

    async.waterfall([
      verifyCaptcha,
      registerUser
    ], done);
  }

  function cmd_promote(args, done) {
    var seneca = this;
    var newRoles = args.roles;
    var userId = args.id;
    var userEntity = seneca.make$(ENTITY_NS);

    userEntity.load$(userId, function(err, response) {
      if(err) return done(err);
      var user = response;
      _.each(newRoles, function(newRole) {
        user.roles.push(newRole);
      });
      user.roles = _.uniq(user.roles);
      userEntity.save$(user, function(err, response) {
        if(err) return done(err);
        done(null, response);
      });
    });

  }

  function cmd_get_users_by_emails(args, done){
    var seneca = this, query = {};

    query.email = new RegExp(args.email, 'i');
    query.limit$ = query.limit$ ? query.limit$ : 10;

    seneca.make(ENTITY_NS).list$(query, function(err, users){
      if(err){
        return done(err);
      }

      users = _.map(users, function(user){
        return {email: user.email, id: user.id};
      });

      users = _.uniq(users, 'email');

      done(null, users);
    });
  }

  function cmd_update(args, done) {
    var seneca = this;
    var user = args.user;

    var userEntity = seneca.make(ENTITY_NS);

    userEntity.save$(user, done);
  }

  function cmd_get_init_user_types(args, done) {
    var seneca = this;
    //These types can be selected during registration on the platform.
    var initUserTypes = [
      {title: 'Youth Under 13', name: 'attendee-u13'},
      {title: 'Youth Over 13', name: 'attendee-o13'},
      {title: 'Parent/Guardian', name: 'parent-guardian'},
      {title: 'Mentor/Volunteer', name: 'mentor'},
      {title: 'Champion', name: 'champion'}
    ];
    done(null, initUserTypes);
  }

  /**
   * This function returns if true if a user is champion and it's dojos if any.
   */
  function cmd_is_champion(args, done){
    var seneca = this;

    seneca.make(ENTITY_NS).load$({id: args.id}, function(err, user) {
      if (err) {
        return done(err)
      }

      user = user.data$();

      var query = {
        query: {
          filtered: {
            query: {
              match_all: {}
            },
            filter: {
              bool: {
                must: [{
                  term: {userId: args.id}
                }]
              }
            }
          }
        }
      };

      seneca.act({
        role: 'cd-dojos',
        cmd: 'search',
        search: query,
        type: 'cd_dojoleads',
        user: user
      }, function (err, dojoLeads) {
        if (err) {
          return done(err)
        }

        if (dojoLeads.total > 0) {
          seneca.act({role: 'cd-dojos', cmd: 'my_dojos', user: user}, function (err, myDojos) {
            if (err) {
              return done(err)
            }

            return done(null, {
              isChampion: true,
              dojos: myDojos
            });
          });
        } else {
          return done(null, {isChampion: false});
        }
      });
    });
  }

  return {
    name: plugin
  };

};
<|endoftext|>