<commit_before>/*  Copyright (c) 2012 Sven "FuzzYspo0N" Bergström,
                  2013 Robert XD Hawkins

    written by : http://underscorediscovery.com
    written for : http://buildnewgames.com/real-time-multiplayer/

    modified for collective behavior experiments on Amazon Mechanical Turk

    MIT Licensed.
*/

/*
   THE FOLLOWING FUNCTIONS MAY NEED TO BE CHANGED
*/

// A window global for our game root variable.
var game = {};
// A window global for our id, which we can use to look ourselves up
var my_id = null;
// Keeps track of whether player is paying attention...
var visible;
var active_keys = [];
var speed_change = "none";

// what happens when you press 'left'?
left_turn = function() {
    var self = game.get_player(my_id);
    self.angle = (Number(self.angle) - 5) % 360;
    game.socket.send("a." + self.angle);
};

// what happens when you press 'left'?
right_turn = function() {
    var self = game.get_player(my_id);
    self.angle = (Number(self.angle) + 5) % 360;
    game.socket.send("a." + self.angle);
};

// Function that gets called client-side when server disconnects someone
client_ondisconnect = function(data) {
    // Redirect to exit survey
    console.log("server booted")
    var URL = '/forms/end.html?id=' + my_id;
    window.location.replace(URL);
};

/*
Note: If you add some new variable to your game that must be shared
  across server and client, add it both here and the server_send_update
  function in game.core.js to make sure it syncs

Explanation: This function is at the center of the problem of
  networking -- everybody has different INSTANCES of the game. The
  server has its own, and both players have theirs too. This can get
  confusing because the server will update a variable, and the variable
  of the same name won't change in the clients (because they have a
  different instance of it). To make sure everybody's on the same page,
  the server regularly sends news about its variables to the clients so
  that they can update their variables to reflect changes.
*/
client_onserverupdate_received = function(data){

    // Update client versions of variables with data received from
    // server_send_update function in game.core.js
    if(data.players) {
        _.map(_.zip(data.players, game.players),
            function(z){
                z[1].id = z[0].id
                if (z[0].player == null) {
                    z[1].player = null
                } else {
                    var s_player = z[0].player
                    var l_player = z[1].player
                    if(z[0].id != my_id | l_player.angle == null)
			l_player.angle = s_player.angle
                    l_player.curr_background = s_player.cbg
		    l_player.total_points = s_player.tot
                    l_player.pos = game.pos(s_player.pos)
                    l_player.speed = s_player.speed
                }
            })
    }

    game.condition = data.cond;
    game.draw_enabled = data.de;
    game.good2write = data.g2w;

};

// This is where clients parse socket.io messages from the server. If
// you want to add another event (labeled 'x', say), just add another
// case here, then call

//          this.instance.player_host.send("s.x. <data>")

// The corresponding function where the server parses messages from
// clients, look for "server_onMessage" in game.server.js.
client_onMessage = function(data) {

    var commands = data.split('.');
    var command = commands[0];
    var subcommand = commands[1] || null;
    var commanddata = commands[2] || null;

    switch(command) {
    case 's': //server message

        switch(subcommand) {
	case 'end' :
	    // Redirect to exit survey
	    console.log("received end message...")
	    var URL = '/forms/end.html?id=' + my_id;
	    window.location.replace(URL); break;
        case 'alert' : // Not in database, so you can't play...
            alert('You did not enter an ID');
            window.location.replace('http://nodejs.org'); break;
        case 'join' : //join a game requested
            var num_players = commanddata;
            client_onjoingame(num_players); break;
        case 'add_player' : // New player joined... Need to add them to our list.
            console.log("adding player" + commanddata)
            game.players.push({id: commanddata, player: new game_player(game)}); break;
        case 'begin_game' :
            game.hidden_enabled = true;
            client_newgame(); break;
        case 'blink' : //blink title
            flashTitle("GO!");  break;
        }
        break;
    }
};

// Restarts things on the client side. Necessary for iterated games.
client_newgame = function() {
    // Initiate countdown (with timeouts)
    game.get_player(my_id).angle = null;
    client_countdown();
};

client_countdown = function() {
    var player = game.get_player(my_id);
    player.message = 'Begin in 3...';
    setTimeout(function(){player.message = 'Begin in 2...';},
               1000);
    setTimeout(function(){player.message = 'Begin in 1...';},
               2000);
    setTimeout(function(){
        player.message = 'GO';
        game.start_time = new Date();},
	3000);
    setTimeout(function(){player.message = '';},
               4000);
}

client_update = function() {
    var player = game.get_player(my_id)
    //Clear the screen area
    game.ctx.clearRect(0,0,485,280);

    // Alter speeds
    if (speed_change != "none") {
        var self = game.get_player(my_id);
        self.speed = speed_change == "up" ? game.max_speed : game.min_speed;
        game.socket.send("s." + self.speed);
        speed_change = "none"
    }

    // Turn if key is still being held... Don't do anything if both are held
    if (active_keys.length < 2) {
        if(_.contains(active_keys, 'right')) right_turn();
        if(_.contains(active_keys, 'left')) left_turn() ;
    }

    // Draw visibility radius
    //if(player.pos) draw_visibility_radius(game, player)

    //Draw opponent next (but only those in radius)
    _.map(game.get_others(my_id), function(p){
	    //if(!game.hidden_enabled || game.distance_between(p.player.pos, player.pos) < game.visibility_radius)
            draw_player(game, p.player)
	    draw_label(game, p.player, "Player " + p.id.slice(0,4))
	})
	    //	else
	    //draw_other_dot(game, player, p.player)});

    // Draw points scoreboard
    $("#cumulative_bonus").html("Total pay so far: $" + (player.total_points).fixed(2));

    $("#curr_bonus").html("Current bonus: " + Math.floor(player.curr_background*100) + "%");

    // Draw time remaining
    var time_remaining = game.round_length - Math.floor((new Date() - game.start_time) / (1000 * 60))
    $("#time").html(game.good2write ? "Time remaining: " + time_remaining + " minutes" : "You are in the waiting room.");

    //And then we draw ourself so we're always in front
    if(player.pos) {
	draw_player(game, player)
	draw_label(game, player, "YOU");
    }

};

var percentColors = [
    { pct: 0.0, color: { r: 0xff, g: 0x00, b: 0 } },
    { pct: 0.5, color: { r: 0xff, g: 0xff, b: 0xff } },
    { pct: 1.0, color: { r: 0x00, g: 0xff, b: 0 } } ];

var getColorForPercentage = function(pct) {
    for (var i = 0; i < percentColors.length; i++) {
        if (pct <= percentColors[i].pct) {
            var lower = percentColors[i - 1] || { pct: 0.1, color: { r: 0x0, g: 0x00, b: 0 } };
            var upper = percentColors[i];
            var range = upper.pct - lower.pct;
            var rangePct = (pct - lower.pct) / range;
            var pctLower = 1 - rangePct;
            var pctUpper = rangePct;
            var color = {
                r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
                g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
                b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
            };
            return 'rgb(' + [color.r, color.g, color.b].join(',') + ')';
        }
    }
}

/*
  The following code should NOT need to be changed
*/

// When loading the page, we store references to our
// drawing canvases, and initiate a game instance.
window.onload = function(){
    //Create our game client instance.
    game = new game_core();

    //Connect to the socket.io server!
    client_connect_to_server(game);

    //Fetch the viewport
    game.viewport = document.getElementById('viewport');

    //Adjust its size
    game.viewport.width = game.world.width;
    game.viewport.height = game.world.height;

    // Keep track of which keys are being pressed
    KeyboardJS.on('left',
        function(){if(!_.contains(active_keys, 'left')) active_keys.push('left');},//if(_.contains(active_keys, 'left')) ;},
        function(){active_keys = _.without(active_keys, 'left');});//active_keys = _.without(active_keys, 'left');})
    KeyboardJS.on('right',
        function(){if(!_.contains(active_keys, 'right')) active_keys.push('right');},
        function(){active_keys = _.without(active_keys, 'right');})
    KeyboardJS.on('space',
        function(){speed_change = "up"},
        function(){speed_change = "down"})

    //Fetch the rendering contexts
    game.ctx = game.viewport.getContext('2d');

    //Set the draw style for the font
    game.ctx.font = '11px "Helvetica"';

    //Finally, start the loop
    game.update();
};

// Associates callback functions corresponding to different socket messages
client_connect_to_server = function(game) {
    //Store a local reference to our connection to the server
    game.socket = io.connect();

    //When we connect, we are not 'connected' until we have a server id
    //and are placed in a game by the server. The server sends us a message for that.
    game.socket.on('connect', function(){
//        game.state = 'connecting';
    }.bind(game));

    game.socket.on('ping', function(data){
	    game.socket.send('pong.' + data.sendTime + "." + data.tick_num)})
    //Sent when we are disconnected (network, server down, etc)
    game.socket.on('disconnect', client_ondisconnect.bind(game));
    //Sent each tick of the server simulation. This is our authoritive update
    game.socket.on('onserverupdate', client_onserverupdate_received);
    //Handle when we connect to the server, showing state and storing id's.
    game.socket.on('onconnected', client_onconnected.bind(game));
    //On message from the server, we parse the commands and send it to the handlers
    game.socket.on('message', client_onMessage.bind(game));
};

client_onconnected = function(data) {
    //The server responded that we are now in a game,
    //this lets us store the information about ourselves
    // so that we remember who we are.
    my_id = data.id;
    game.players[0].id = my_id;
    game.get_player(my_id).online = true;
};

client_onjoingame = function(num_players) {
    // Need client to know how many players there are, so they can set up the appropriate data structure
    _.map(_.range(num_players - 1), function(i){game.players.unshift({id: null, player: new game_player(game)})});
    // Set self color, leave others default white
    game.get_player(my_id).color = game.self_color;
    // Start 'em moving
    game.get_player(my_id).speed = game.min_speed;
};

// Automatically registers whether user has switched tabs...
(function() {
    document.hidden = hidden = "hidden";

    // Standards:
    if (hidden in document)
        document.addEventListener("visibilitychange", onchange);
    else if ((hidden = "mozHidden") in document)
        document.addEventListener("mozvisibilitychange", onchange);
    else if ((hidden = "webkitHidden") in document)
        document.addEventListener("webkitvisibilitychange", onchange);
    else if ((hidden = "msHidden") in document)
        document.addEventListener("msvisibilitychange", onchange);
    // IE 9 and lower:
    else if ('onfocusin' in document)
        document.onfocusin = document.onfocusout = onchange;
    // All others:
    else
        window.onpageshow = window.onpagehide = window.onfocus
             = window.onblur = onchange;
})();

function onchange (evt) {
    var v = 'visible', h = 'hidden',
    evtMap = {
        focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
    };
    evt = evt || window.event;
    if (evt.type in evtMap) {
        document.body.className = evtMap[evt.type];
    } else {
        document.body.className = evt.target.hidden ? "hidden" : "visible";
    }
    visible = document.body.className;
    game.socket.send("h." + document.body.className);
};

// Flashes title to notify user that game has started
(function () {

    var original = document.title;
    var timeout;

    window.flashTitle = function (newMsg, howManyTimes) {
        function step() {
            document.title = (document.title == original) ? newMsg : original;
            if (visible == "hidden") {
                timeout = setTimeout(step, 500);
            } else {
                document.title = original;
            }
        };
        cancelFlashTitle(timeout);
        step();
    };

window.cancelFlashTitle = function (timeout) {
    clearTimeout(timeout);
    document.title = original;
};

}());
<commit_msg>Modified location of landing page<commit_after>/*  Copyright (c) 2012 Sven "FuzzYspo0N" Bergström,
                  2013 Robert XD Hawkins

    written by : http://underscorediscovery.com
    written for : http://buildnewgames.com/real-time-multiplayer/

    modified for collective behavior experiments on Amazon Mechanical Turk

    MIT Licensed.
*/

/*
   THE FOLLOWING FUNCTIONS MAY NEED TO BE CHANGED
*/

// A window global for our game root variable.
var game = {};
// A window global for our id, which we can use to look ourselves up
var my_id = null;
// Keeps track of whether player is paying attention...
var visible;
var active_keys = [];
var speed_change = "none";

// what happens when you press 'left'?
left_turn = function() {
    var self = game.get_player(my_id);
    self.angle = (Number(self.angle) - 5) % 360;
    game.socket.send("a." + self.angle);
};

// what happens when you press 'left'?
right_turn = function() {
    var self = game.get_player(my_id);
    self.angle = (Number(self.angle) + 5) % 360;
    game.socket.send("a." + self.angle);
};

// Function that gets called client-side when server disconnects someone
client_ondisconnect = function(data) {
    // Redirect to exit survey
    console.log("server booted")
    var URL = 'http://projects.csail.mit.edu/ci/turk/forms/end.html?id=' + my_id;
    window.location.replace(URL);
};

/*
Note: If you add some new variable to your game that must be shared
  across server and client, add it both here and the server_send_update
  function in game.core.js to make sure it syncs

Explanation: This function is at the center of the problem of
  networking -- everybody has different INSTANCES of the game. The
  server has its own, and both players have theirs too. This can get
  confusing because the server will update a variable, and the variable
  of the same name won't change in the clients (because they have a
  different instance of it). To make sure everybody's on the same page,
  the server regularly sends news about its variables to the clients so
  that they can update their variables to reflect changes.
*/
client_onserverupdate_received = function(data){

    // Update client versions of variables with data received from
    // server_send_update function in game.core.js
    if(data.players) {
        _.map(_.zip(data.players, game.players),
            function(z){
                z[1].id = z[0].id
                if (z[0].player == null) {
                    z[1].player = null
                } else {
                    var s_player = z[0].player
                    var l_player = z[1].player
                    if(z[0].id != my_id | l_player.angle == null)
			l_player.angle = s_player.angle
                    l_player.curr_background = s_player.cbg
		    l_player.total_points = s_player.tot
                    l_player.pos = game.pos(s_player.pos)
                    l_player.speed = s_player.speed
                }
            })
    }

    game.condition = data.cond;
    game.draw_enabled = data.de;
    game.good2write = data.g2w;

};

// This is where clients parse socket.io messages from the server. If
// you want to add another event (labeled 'x', say), just add another
// case here, then call

//          this.instance.player_host.send("s.x. <data>")

// The corresponding function where the server parses messages from
// clients, look for "server_onMessage" in game.server.js.
client_onMessage = function(data) {

    var commands = data.split('.');
    var command = commands[0];
    var subcommand = commands[1] || null;
    var commanddata = commands[2] || null;

    switch(command) {
    case 's': //server message

        switch(subcommand) {
	case 'end' :
	    // Redirect to exit survey
	    console.log("received end message...")
	    var URL = 'http://projects.csail.mit.edu/ci/turk/forms/end.html?id=' + my_id;
	    window.location.replace(URL); break;
        case 'alert' : // Not in database, so you can't play...
            alert('You did not enter an ID');
            window.location.replace('http://nodejs.org'); break;
        case 'join' : //join a game requested
            var num_players = commanddata;
            client_onjoingame(num_players); break;
        case 'add_player' : // New player joined... Need to add them to our list.
            console.log("adding player" + commanddata)
            game.players.push({id: commanddata, player: new game_player(game)}); break;
        case 'begin_game' :
            game.hidden_enabled = true;
            client_newgame(); break;
        case 'blink' : //blink title
            flashTitle("GO!");  break;
        }
        break;
    }
};

// Restarts things on the client side. Necessary for iterated games.
client_newgame = function() {
    // Initiate countdown (with timeouts)
    game.get_player(my_id).angle = null;
    client_countdown();
};

client_countdown = function() {
    var player = game.get_player(my_id);
    player.message = 'Begin in 3...';
    setTimeout(function(){player.message = 'Begin in 2...';},
               1000);
    setTimeout(function(){player.message = 'Begin in 1...';},
               2000);
    setTimeout(function(){
        player.message = 'GO';
        game.start_time = new Date();},
	3000);
    setTimeout(function(){player.message = '';},
               4000);
}

client_update = function() {
    var player = game.get_player(my_id)
    //Clear the screen area
    game.ctx.clearRect(0,0,485,280);

    // Alter speeds
    if (speed_change != "none") {
        var self = game.get_player(my_id);
        self.speed = speed_change == "up" ? game.max_speed : game.min_speed;
        game.socket.send("s." + self.speed);
        speed_change = "none"
    }

    // Turn if key is still being held... Don't do anything if both are held
    if (active_keys.length < 2) {
        if(_.contains(active_keys, 'right')) right_turn();
        if(_.contains(active_keys, 'left')) left_turn() ;
    }

    // Draw visibility radius
    //if(player.pos) draw_visibility_radius(game, player)

    //Draw opponent next (but only those in radius)
    _.map(game.get_others(my_id), function(p){
	    //if(!game.hidden_enabled || game.distance_between(p.player.pos, player.pos) < game.visibility_radius)
            draw_player(game, p.player)
	    draw_label(game, p.player, "Player " + p.id.slice(0,4))
	})
	    //	else
	    //draw_other_dot(game, player, p.player)});

    // Draw points scoreboard
    $("#cumulative_bonus").html("Total pay so far: $" + (player.total_points).fixed(2));

    $("#curr_bonus").html("Current bonus: " + Math.floor(player.curr_background*100) + "%");

    // Draw time remaining
    var time_remaining = game.round_length - Math.floor((new Date() - game.start_time) / (1000 * 60))
    $("#time").html(game.good2write ? "Time remaining: " + time_remaining + " minutes" : "You are in the waiting room.");

    //And then we draw ourself so we're always in front
    if(player.pos) {
	draw_player(game, player)
	draw_label(game, player, "YOU");
    }

};

var percentColors = [
    { pct: 0.0, color: { r: 0xff, g: 0x00, b: 0 } },
    { pct: 0.5, color: { r: 0xff, g: 0xff, b: 0xff } },
    { pct: 1.0, color: { r: 0x00, g: 0xff, b: 0 } } ];

var getColorForPercentage = function(pct) {
    for (var i = 0; i < percentColors.length; i++) {
        if (pct <= percentColors[i].pct) {
            var lower = percentColors[i - 1] || { pct: 0.1, color: { r: 0x0, g: 0x00, b: 0 } };
            var upper = percentColors[i];
            var range = upper.pct - lower.pct;
            var rangePct = (pct - lower.pct) / range;
            var pctLower = 1 - rangePct;
            var pctUpper = rangePct;
            var color = {
                r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
                g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
                b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
            };
            return 'rgb(' + [color.r, color.g, color.b].join(',') + ')';
        }
    }
}

/*
  The following code should NOT need to be changed
*/

// When loading the page, we store references to our
// drawing canvases, and initiate a game instance.
window.onload = function(){
    //Create our game client instance.
    game = new game_core();

    //Connect to the socket.io server!
    client_connect_to_server(game);

    //Fetch the viewport
    game.viewport = document.getElementById('viewport');

    //Adjust its size
    game.viewport.width = game.world.width;
    game.viewport.height = game.world.height;

    // Keep track of which keys are being pressed
    KeyboardJS.on('left',
        function(){if(!_.contains(active_keys, 'left')) active_keys.push('left');},//if(_.contains(active_keys, 'left')) ;},
        function(){active_keys = _.without(active_keys, 'left');});//active_keys = _.without(active_keys, 'left');})
    KeyboardJS.on('right',
        function(){if(!_.contains(active_keys, 'right')) active_keys.push('right');},
        function(){active_keys = _.without(active_keys, 'right');})
    KeyboardJS.on('space',
        function(){speed_change = "up"},
        function(){speed_change = "down"})

    //Fetch the rendering contexts
    game.ctx = game.viewport.getContext('2d');

    //Set the draw style for the font
    game.ctx.font = '11px "Helvetica"';

    //Finally, start the loop
    game.update();
};

// Associates callback functions corresponding to different socket messages
client_connect_to_server = function(game) {
    //Store a local reference to our connection to the server
    game.socket = io.connect();

    //When we connect, we are not 'connected' until we have a server id
    //and are placed in a game by the server. The server sends us a message for that.
    game.socket.on('connect', function(){
//        game.state = 'connecting';
    }.bind(game));

    game.socket.on('ping', function(data){
	    game.socket.send('pong.' + data.sendTime + "." + data.tick_num)})
    //Sent when we are disconnected (network, server down, etc)
    game.socket.on('disconnect', client_ondisconnect.bind(game));
    //Sent each tick of the server simulation. This is our authoritive update
    game.socket.on('onserverupdate', client_onserverupdate_received);
    //Handle when we connect to the server, showing state and storing id's.
    game.socket.on('onconnected', client_onconnected.bind(game));
    //On message from the server, we parse the commands and send it to the handlers
    game.socket.on('message', client_onMessage.bind(game));
};

client_onconnected = function(data) {
    //The server responded that we are now in a game,
    //this lets us store the information about ourselves
    // so that we remember who we are.
    my_id = data.id;
    game.players[0].id = my_id;
    game.get_player(my_id).online = true;
};

client_onjoingame = function(num_players) {
    // Need client to know how many players there are, so they can set up the appropriate data structure
    _.map(_.range(num_players - 1), function(i){game.players.unshift({id: null, player: new game_player(game)})});
    // Set self color, leave others default white
    game.get_player(my_id).color = game.self_color;
    // Start 'em moving
    game.get_player(my_id).speed = game.min_speed;
};

// Automatically registers whether user has switched tabs...
(function() {
    document.hidden = hidden = "hidden";

    // Standards:
    if (hidden in document)
        document.addEventListener("visibilitychange", onchange);
    else if ((hidden = "mozHidden") in document)
        document.addEventListener("mozvisibilitychange", onchange);
    else if ((hidden = "webkitHidden") in document)
        document.addEventListener("webkitvisibilitychange", onchange);
    else if ((hidden = "msHidden") in document)
        document.addEventListener("msvisibilitychange", onchange);
    // IE 9 and lower:
    else if ('onfocusin' in document)
        document.onfocusin = document.onfocusout = onchange;
    // All others:
    else
        window.onpageshow = window.onpagehide = window.onfocus
             = window.onblur = onchange;
})();

function onchange (evt) {
    var v = 'visible', h = 'hidden',
    evtMap = {
        focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
    };
    evt = evt || window.event;
    if (evt.type in evtMap) {
        document.body.className = evtMap[evt.type];
    } else {
        document.body.className = evt.target.hidden ? "hidden" : "visible";
    }
    visible = document.body.className;
    game.socket.send("h." + document.body.className);
};

// Flashes title to notify user that game has started
(function () {

    var original = document.title;
    var timeout;

    window.flashTitle = function (newMsg, howManyTimes) {
        function step() {
            document.title = (document.title == original) ? newMsg : original;
            if (visible == "hidden") {
                timeout = setTimeout(step, 500);
            } else {
                document.title = original;
            }
        };
        cancelFlashTitle(timeout);
        step();
    };

window.cancelFlashTitle = function (timeout) {
    clearTimeout(timeout);
    document.title = original;
};

}());
<|endoftext|>


<commit_before>"use strict";

var util = require("util");

function FlooUrl(owner, workspace, host, port) {
  this.owner = owner;
  this.workspace = workspace;
  this.host = host;
  this.port = port;
}

FlooUrl.prototype.toString = function () {
  let port = parseInt(this.port, 10);
  return util.format("https://%s:%s/%s/%s", this.host, port === 3448 ? "" : this.port, this.owner, this.workspace);
};

exports.FlooUrl = FlooUrl;
<commit_msg>fix floourl toString formating<commit_after>"use strict";

var util = require("util");

function FlooUrl(owner, workspace, host, port) {
  this.owner = owner;
  this.workspace = workspace;
  this.host = host;
  this.port = port;
}

FlooUrl.prototype.toString = function () {
  let port = parseInt(this.port, 10);
  return util.format("https://%s%s/%s/%s", this.host, port === 3448 ? "" : ":" + this.port, this.owner, this.workspace);
};

exports.FlooUrl = FlooUrl;
<|endoftext|>


<commit_before>var fs         = require('fs-extra');
var path       = require('path');
var _          = require('lodash');
var wrench     = require('wrench');
var glob       = require('glob');
var moment     = require('moment');
var handlebars = require('handlebars');
var pages      = require('./views/pages');
var navigation = require('./views/navigation');

require('./views/handlebars_helper');

var FILES = path.join(__dirname, '..', 'template', 'files');
var TEMPLATES = path.join(__dirname, '..', 'template', 'views');

function readIntro(introPath) {
  return require('fs').readFileSync(introPath).toString();
}

function readTemplate(filepath) {
  var source = fs.readFileSync(path.join(TEMPLATES, filepath));
  return handlebars.compile(source.toString());
}

function writeFile(templateName, pageName, outputFolder, viewModel) {
  var template = readTemplate(templateName);
  var filePath = path.join(outputFolder, pageName + '.html');
  var content = template(viewModel);
  fs.writeFileSync(filePath, content, 'utf-8');
}

function copyTemplateFiles(outputFolder) {
  wrench.copyDirSyncRecursive(FILES, outputFolder, {
    forceDelete: true,
    excludeHiddenUnix: true,
    preserveFiles: false
  });
}

function copyCustomFiles(fileSpecs, outputFolder) {
  var options = { nonull: false, sync: true, mark: true };
  _(fileSpecs).forEach(function(subFolder, pattern) {
    var files = glob(pattern, options);
    files.forEach(function(filePath) {
      if (filePath[filePath.length -1] !== '/') {
        var fileName = path.basename(filePath);
        var outputPath = path.join(outputFolder, subFolder, fileName);
        fs.copySync(filePath, outputPath);
      }
    });
  });
}

exports.write = function(samples, opts) {

  var intro = opts.intro ? readIntro(opts.intro) : '';
  var pagesModel = pages.create(samples.get());
  var navModel   = navigation.from(intro, pagesModel);

  copyTemplateFiles(opts.output);
  copyCustomFiles(opts.files, opts.output);

  var viewmodel = {
    generated: moment().format("MMMM Do YYYY, h:mm a"),
    title: opts.title,
    baseUrl: opts.baseUrl,
    navigation: navModel,
    styles: opts.styles
  }

  writeFile('index.hbs', 'index', opts.output, _.extend(viewmodel, {
    intro: intro
  }));

  pagesModel.forEach(function(page) {
    writeFile('pages.hbs', page.slug, opts.output, _.extend(viewmodel, page));
  });

};
<commit_msg>Fix when output folder is a nested folder (creates the whole hierarchy)<commit_after>var fs         = require('fs-extra');
var path       = require('path');
var _          = require('lodash');
var wrench     = require('wrench');
var glob       = require('glob');
var moment     = require('moment');
var handlebars = require('handlebars');
var pages      = require('./views/pages');
var navigation = require('./views/navigation');

require('./views/handlebars_helper');

var FILES = path.join(__dirname, '..', 'template', 'files');
var TEMPLATES = path.join(__dirname, '..', 'template', 'views');

function readIntro(introPath) {
  return require('fs').readFileSync(introPath).toString();
}

function readTemplate(filepath) {
  var source = fs.readFileSync(path.join(TEMPLATES, filepath));
  return handlebars.compile(source.toString());
}

function writeFile(templateName, pageName, outputFolder, viewModel) {
  var template = readTemplate(templateName);
  var filePath = path.join(outputFolder, pageName + '.html');
  var content = template(viewModel);
  fs.writeFileSync(filePath, content, 'utf-8');
}

function copyTemplateFiles(outputFolder) {
  wrench.copyDirSyncRecursive(FILES, outputFolder, {
    forceDelete: true,
    excludeHiddenUnix: true,
    preserveFiles: false
  });
}

function copyCustomFiles(fileSpecs, outputFolder) {
  var options = { nonull: false, sync: true, mark: true };
  _(fileSpecs).forEach(function(subFolder, pattern) {
    var files = glob(pattern, options);
    files.forEach(function(filePath) {
      if (filePath[filePath.length -1] !== '/') {
        var fileName = path.basename(filePath);
        var outputPath = path.join(outputFolder, subFolder, fileName);
        fs.copySync(filePath, outputPath);
      }
    });
  });
}

exports.write = function(samples, opts) {

  var intro = opts.intro ? readIntro(opts.intro) : '';
  var pagesModel = pages.create(samples.get());
  var navModel   = navigation.from(intro, pagesModel);

  fs.mkdirpSync(opts.output);
  copyTemplateFiles(opts.output);
  copyCustomFiles(opts.files, opts.output);

  var viewmodel = {
    generated: moment().format("MMMM Do YYYY, h:mm a"),
    title: opts.title,
    baseUrl: opts.baseUrl,
    navigation: navModel,
    styles: opts.styles
  }

  writeFile('index.hbs', 'index', opts.output, _.extend(viewmodel, {
    intro: intro
  }));

  pagesModel.forEach(function(page) {
    writeFile('pages.hbs', page.slug, opts.output, _.extend(viewmodel, page));
  });

};
<|endoftext|>


<commit_before>module.exports = function (creep) {
    var spawn = Game.spawns.Spawn1;
    var sources = creep.room.find(FIND_DROPPED_ENERGY);

    if (creep.energy < creep.energyCapacity) {
        if (!creep.pos.isNearTo(sources[0])) creep.moveTo(sources[0]);

        creep.pickup(sources[0]);
    }

    if (!sources[0] || creep.energy == creep.energyCapacity) {
        creep.moveTo(spawn);
        creep.transferEnergy(spawn);
    }
};
<commit_msg>Moved the runner's resting spot.<commit_after>module.exports = function (creep) {
    var spawn = Game.spawns.Spawn1;
    var sources = creep.room.find(FIND_DROPPED_ENERGY);

    if (creep.energy < creep.energyCapacity) {
        if (!creep.pos.isNearTo(sources[0])) creep.moveTo(sources[0]);

        creep.pickup(sources[0]);
    }

    if (creep.energy == creep.energyCapacity) {
        creep.moveTo(spawn);
        creep.transferEnergy(spawn);

        return;
    }

    creep.moveTo({x: 24, y: 28});
};
<|endoftext|>


<commit_before>(function() {
  // don't emit events from inside the previews themselves
  var qs = window.location.href.split('?');
  if (qs.length > 1 && qs[1].match('receiver')) { return; }

  var socket = io.connect(window.location.origin);

  Reveal.addEventListener( 'slidechanged', function( event ) {
    var nextindexh;
    var nextindexv;
    var slideElement = event.currentSlide;

    if (slideElement.nextElementSibling && slideElement.parentNode.nodeName == 'SECTION') {
      nextindexh = event.indexh;
      nextindexv = event.indexv + 1;
    } else {
      nextindexh = event.indexh + 1;
      nextindexv = 0;
    }

    var notes = slideElement.querySelector('aside.notes');
    var slideData = {
      notes : notes ? notes.innerHTML : '',
      indexh : event.indexh,
      indexv : event.indexv,
      nextindexh : nextindexh,
      nextindexv : nextindexv
    };

    socket.emit('slidechanged', slideData);
  } );
}());<commit_msg>broadcast socket id as part of slidedata<commit_after>(function() {
  // don't emit events from inside the previews themselves
  var qs = window.location.href.split('?');
  if (qs.length > 1 && qs[1].match('receiver')) { return; }

  var socket = io.connect(window.location.origin);
  var socketId = socket.socket.sessionid;
  console.log('View slide notes at ' + window.location.origin + '/_notes/' + socketId);

  Reveal.addEventListener( 'slidechanged', function( event ) {
    var nextindexh;
    var nextindexv;
    var slideElement = event.currentSlide;

    if (slideElement.nextElementSibling && slideElement.parentNode.nodeName == 'SECTION') {
      nextindexh = event.indexh;
      nextindexv = event.indexv + 1;
    } else {
      nextindexh = event.indexh + 1;
      nextindexv = 0;
    }

    var notes = slideElement.querySelector('aside.notes');
    var slideData = {
      notes : notes ? notes.innerHTML : '',
      indexh : event.indexh,
      indexv : event.indexv,
      nextindexh : nextindexh,
      nextindexv : nextindexv,
      socketId : socketId
    };

    socket.emit('slidechanged', slideData);
  } );
}());
<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    // Draw shapes.
    for(var shape in shapes){
        canvas_buffer.fillStyle = shapes[shape]['color'];
        canvas_buffer.fillRect(
          shapes[shape]['x'],
          shapes[shape]['y'],
          shapes[shape]['width'],
          shapes[shape]['height']
        );
    }

    // Draw time remaining.
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.fillText(
      'Time: ' + time + '/' + settings_settings['time-limit'],
      5,
      25
    );

    // Draw score.
    canvas_buffer.fillText(
      'Score: ' + score,
      5,
      55
    );
}

function logic(){
    time = (time - .1).toFixed(1);

    if(time <= 0){
        window.clearInterval(canvas_interval);
    }
}

function randomize_shapes(){
    shapes.length = 0;

    if(settings_settings['red'] > 0){
        var loop_counter = settings_settings['red'] - 1;
        do{
            shapes.push({
              'color': '#f00',
              'height': random_integer({
                'max': 200,
              }) + 42,
              'score': -1,
              'width': random_integer({
                'max': 200,
              }) + 42,
              'x': random_integer({
                'max': canvas_width,
              }) - 21,
              'y': random_integer({
                'max': canvas_height,
              }) - 21,
            });
        }while(loop_counter--);
    }
    if(settings_settings['white'] > 0){
        var loop_counter = settings_settings['white'] - 1;
        do{
            shapes.push({
              'color': '#fff',
              'height': random_integer({
                'max': 99,
              }) + 20,
              'score': 1,
              'width': random_integer({
                'max': 99,
              }) + 20,
              'x': random_integer({
                'max': canvas_width,
              }) - 9,
              'y': random_integer({
                'max': canvas_height,
              }) - 9,
            });
        }while(loop_counter--);
    }

    shapes_length = shapes.length;

    if(time <= 0){
        canvas_draw();
    }
}

function resize_logic(){
    if(time > 0){
        randomize_shapes();

    }else{
        canvas_draw();
    }
}

function setmode_logic(newgame){
    shapes.length = 0;
    shapes_length = 0;

    // Main menu mode.
    if(canvas_mode === 0){
        document.body.innerHTML = '

Start New Game

'
          + '

<input disabled value=ESC>Main Menu
'
          + '<input id=restart-key maxlength=1>Restart

'
          + '
<input id=audio-volume max=1 min=0 step=0.01 type=range>Audio
'
          + '<input id=ms-per-frame>ms/Frame
'
          + '<input id=red>Red
'
          + '<input id=time-limit>Time Limit
'
          + '<input id=white>White
'
          + 'Reset Settings

';
        settings_update();

    // New game mode.
    }else{
        if(newgame){
            settings_save();

        }else{
            randomize_shapes();
        }

        score = 0;
        time = settings_settings['time-limit'];
    }
}

var mouse_x = 0;
var mouse_y = 0;
var score = 0;
var shapes = [];
var shapes_length = 0;
var time = 0;

window.onkeydown = function(e){
    if(canvas_mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // settings_settings['restart-key']: restart the current game.
    if(String.fromCharCode(key) === settings_settings['restart-key']){
        canvas_setmode(
          1,
          false
        );

    // ESC: return to main menu.
    }else if(key === 27){
        canvas_setmode(
          0,
          false
        );
    }
};

window.onload = function(){
    settings_init({
      'prefix': 'SpeedShape.htm-',
      'settings': {
        'audio-volume': 1,
        'ms-per-frame': 100,
        'red': 10,
        'restart-key': 'H',
        'time-limit': 30,
        'white': 1,
      },
    });
    audio_init();
    audio_create({
      'id': 'boop',
      'properties': {
        'duration': .1,
        'volume': .1,
      },
    });
    canvas_init();
};

window.onmousedown =
  window.ontouchstart = function(e){
    if(canvas_mode <= 0
      || time <= 0){
        return;
    }

    e.preventDefault();

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    for(var shape in shapes){
        shape = shapes_length - shape - 1;

        if(mouse_x <= shapes[shape]['x']
          || mouse_x >= shapes[shape]['x'] + shapes[shape]['width']
          || mouse_y <= shapes[shape]['y']
          || mouse_y >= shapes[shape]['y'] + shapes[shape]['height']){
            continue;
        }

        audio_start({
          'id': 'boop',
          'volume-multiplier': settings_settings['audio-volume'],
        });

        score += shapes[shape]['score'];
        randomize_shapes();
        break;
    }
};
<commit_msg>switched canvas.js to args<commit_after>'use strict';

function draw_logic(){
    // Draw shapes.
    for(var shape in shapes){
        canvas_buffer.fillStyle = shapes[shape]['color'];
        canvas_buffer.fillRect(
          shapes[shape]['x'],
          shapes[shape]['y'],
          shapes[shape]['width'],
          shapes[shape]['height']
        );
    }

    // Draw time remaining.
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.fillText(
      'Time: ' + time + '/' + settings_settings['time-limit'],
      5,
      25
    );

    // Draw score.
    canvas_buffer.fillText(
      'Score: ' + score,
      5,
      55
    );
}

function logic(){
    time = (time - .1).toFixed(1);

    if(time <= 0){
        window.clearInterval(canvas_interval);
    }
}

function randomize_shapes(){
    shapes.length = 0;

    if(settings_settings['red'] > 0){
        var loop_counter = settings_settings['red'] - 1;
        do{
            shapes.push({
              'color': '#f00',
              'height': random_integer({
                'max': 200,
              }) + 42,
              'score': -1,
              'width': random_integer({
                'max': 200,
              }) + 42,
              'x': random_integer({
                'max': canvas_width,
              }) - 21,
              'y': random_integer({
                'max': canvas_height,
              }) - 21,
            });
        }while(loop_counter--);
    }
    if(settings_settings['white'] > 0){
        var loop_counter = settings_settings['white'] - 1;
        do{
            shapes.push({
              'color': '#fff',
              'height': random_integer({
                'max': 99,
              }) + 20,
              'score': 1,
              'width': random_integer({
                'max': 99,
              }) + 20,
              'x': random_integer({
                'max': canvas_width,
              }) - 9,
              'y': random_integer({
                'max': canvas_height,
              }) - 9,
            });
        }while(loop_counter--);
    }

    shapes_length = shapes.length;

    if(time <= 0){
        canvas_draw();
    }
}

function resize_logic(){
    if(time > 0){
        randomize_shapes();

    }else{
        canvas_draw();
    }
}

function setmode_logic(newgame){
    shapes.length = 0;
    shapes_length = 0;

    // Main menu mode.
    if(canvas_mode === 0){
        document.body.innerHTML = '

Start New Game

'
          + '

<input disabled value=ESC>Main Menu
'
          + '<input id=restart-key maxlength=1>Restart

'
          + '
<input id=audio-volume max=1 min=0 step=0.01 type=range>Audio
'
          + '<input id=ms-per-frame>ms/Frame
'
          + '<input id=red>Red
'
          + '<input id=time-limit>Time Limit
'
          + '<input id=white>White
'
          + 'Reset Settings

';
        settings_update();

    // New game mode.
    }else{
        if(newgame){
            settings_save();

        }else{
            randomize_shapes();
        }

        score = 0;
        time = settings_settings['time-limit'];
    }
}

var mouse_x = 0;
var mouse_y = 0;
var score = 0;
var shapes = [];
var shapes_length = 0;
var time = 0;

window.onkeydown = function(e){
    if(canvas_mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // settings_settings['restart-key']: restart the current game.
    if(String.fromCharCode(key) === settings_settings['restart-key']){
        canvas_setmode({
          'mode': 1,
        });

    // ESC: return to main menu.
    }else if(key === 27){
        canvas_setmode({
          'mode': 0,
        });
    }
};

window.onload = function(){
    settings_init({
      'prefix': 'SpeedShape.htm-',
      'settings': {
        'audio-volume': 1,
        'ms-per-frame': 100,
        'red': 10,
        'restart-key': 'H',
        'time-limit': 30,
        'white': 1,
      },
    });
    audio_init();
    audio_create({
      'id': 'boop',
      'properties': {
        'duration': .1,
        'volume': .1,
      },
    });
    canvas_init();
};

window.onmousedown =
  window.ontouchstart = function(e){
    if(canvas_mode <= 0
      || time <= 0){
        return;
    }

    e.preventDefault();

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    for(var shape in shapes){
        shape = shapes_length - shape - 1;

        if(mouse_x <= shapes[shape]['x']
          || mouse_x >= shapes[shape]['x'] + shapes[shape]['width']
          || mouse_y <= shapes[shape]['y']
          || mouse_y >= shapes[shape]['y'] + shapes[shape]['height']){
            continue;
        }

        audio_start({
          'id': 'boop',
          'volume-multiplier': settings_settings['audio-volume'],
        });

        score += shapes[shape]['score'];
        randomize_shapes();
        break;
    }
};
<|endoftext|>


<commit_before>/*
 * forever.js: Top level include for the forever module
 *
 * (C) 2010 and Charlie Robbins
 * MIT LICENCE
 *
 */

var sys = require('sys'),
    fs = require('fs'),
    colors = require('colors'),
    path = require('path'),
    events = require('events'),
    exec = require('child_process').exec,
    spawn = require('child_process').spawn,
    daemon = require('daemon');

var forever = exports, config;

//
// function load ()
//   Initializes configuration for forever module
//
forever.load = function (options, callback) {
  var emitter = new events.EventEmitter();
  options = options || {};
  options.root    = options.root || path.join('/tmp', 'forever'),
  options.pidPath = options.pidPath || path.join(options.root, 'pids');
  config = options;

  // Create the two directories, ignoring errors
  fs.mkdir(config.root, 0755, function (err) {
    fs.mkdir(config.pidPath, 0755, function (err2) {
      if (callback) callback();
      emitter.emit('load');
    });
  });

  return emitter;
};

//
// function start (file, options)
//   Starts a script with forever
//   [file]:    Location of the node script to run.
//   [options]: Configuration for forever instance.
//
forever.start = function (file, options) {
  return new Forever(file, options).start();
};

//
// function startDaemon (file, options)
//   Starts a script with forever as a daemon
//   [file]:    Location of the node script to run.
//   [options]: Configuration for forever instance.
//
forever.startDaemon = function (file, options) {
  options.logFile = path.join(config.root, options.logFile || 'forever.log');
  options.pidFile = path.join(config.pidPath, options.pidFile);
  var runner = new Forever(file, options);

  fs.open(options.logFile, 'w+', function (err, fd) {
    try {
      var pid = daemon.start(fd);
      daemon.lock(options.pidFile);
      process.pid = pid;

      //
      // Remark: This should work, but the fd gets screwed up
      //         with the daemon process.
      //
      // process.on('exit', function () {
      //   fs.unlinkSync(options.pidFile);
      // });

      runner.start().save();
    }
    catch (ex) {
      runner.emit('error', ex);
    }
  });

  return runner;
};

//
// function stop (index)
//   Stops the process with the specified
//   index in the list of all processes
//
forever.stop = function (index, format) {
  var emitter = new events.EventEmitter(),
      processes = getAllProcesses(),
      proc = processes && processes[index];

  if (proc) {
    exec('kill ' + proc.foreverPid, function () {
      exec('kill ' + proc.pid, function () {
        if (format) proc = formatProcess(proc, index, '');
        emitter.emit('stop', proc);
      });
    });
  }
  else {
    process.nextTick(function () {
      emitter.emit('error', new Error('Cannot find forever process with index: ' + index));
    });
  }

  return emitter;
};

//
// function stopAll (format)
//   Stops all forever processes
//   [format]: Value indicating if we should format output
//
forever.stopAll = function (format) {
  var emitter = new events.EventEmitter(),
      processes = getAllProcesses() || [],
      pids = getAllPids(processes);

  if (format) {
    processes = forever.list(format, processes);
  }

  if (pids && processes) {
    var fPids = pids.map(function (pid) { return pid.foreverPid }).join(' '),
        cPids = pids.map(function (pid) { return pid.pid }).join(' ');

    exec('kill ' + fPids, function () {
      exec('kill ' + cPids, function () {
        emitter.emit('stopAll', processes);
      });
    });
  }
  else {
    process.nextTick(function () {
      emitter.emit('stopAll', null);
    });
  }

  return emitter;
};

//
// function list (format)
//   Returns the list of all process data managed by forever.
//   [format]: If set, will return a formatted string of data
//
forever.list = function (format, procs) {
  var formatted = [], procs = procs || getAllProcesses();
  if (!procs) return null;

  if (format) {
    var index = 0, maxLen = 0;
    // Iterate over the procs to see which has the longest options string
    procs.forEach(function (proc) {
      proc.length = [proc.file].concat(proc.options).join(' ').length;
      if (proc.length > maxLen) maxLen = proc.length;
    });

    procs.forEach(function (proc) {
      // Create padding string to keep output aligned
      var padding = new Array(maxLen - proc.length + 1).join(' ');
      formatted.push(formatProcess(proc, index, padding));
      index++;
    });
  }

  return format ? formatted.join('\n') : procs;
};

//
// function cleanUp ()
//   Utility function for removing excess pid and
//   config files used by forever.
//
forever.cleanUp = function () {
  var emitter = new events.EventEmitter(),
      processes = getAllProcesses();

  if (processes) {
    var checked = 0;
    processes.forEach(function (proc) {
      checkProcess(proc.pid, function (child) {
        checkProcess(proc.foreverPid, function (manager) {
          if (!child && !manager) {
            if (proc.pidFile) {
              fs.unlink(proc.pidFile, function () {
                // Ignore errors
              });
            }

            fs.unlink(path.join(config.pidPath, proc.foreverPid + '.fvr'), function () {
              // Ignore errors
            });
          }

          checked++;
          if (checked === processes.length) {
            emitter.emit('cleanUp');
          }
        });
      });
    });
  }
  else {
    process.nextTick(function () {
      emitter.emit('cleanUp');
    });
  }

  return emitter;
};

//
// function randomString (bits)
//   randomString returns a pseude-random ASCII string which contains at least
//   the specified number of bits of entropy the return value is a string of
//   length ⌈bits/6⌉ of characters from the base64 alphabet.
//
forever.randomString = function (bits) {
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
      rand, i, ret = '';

  //
  // in v8, Math.random() yields 32 pseudo-random bits (in spidermonkey it gives 53)
  //
  while (bits > 0) {
    rand = Math.floor(Math.random()*0x100000000) // 32-bit integer
    // base 64 means 6 bits per character, so we use the top 30 bits from rand to give 30/6=5 characters.
    for (i=26; i>0 && bits>0; i-=6, bits-=6) {
      ret+=chars[0x3F & rand >>> i];
    }
  }
  return ret;
};

//
// function checkProcess (pid, callback)
//   Utility function to check to see if a pid is running
//
function checkProcess (pid, callback) {
  exec('ps ' + pid + ' | grep -v PID', function (err, stdout, stderr) {
    if (err) return callback(false);
    callback(stdout.indexOf(pid) !== -1);
  });
};

//
// function formatProcess (index, padding)
//   Returns a formatted string for the process (proc) at
//   the specified index.
//   [proc]:    Process to format
//   [index]:   Index of the process in the set of all processes
//   [padding]: Padding to add to the formatted output
//
function formatProcess (proc, index, padding) {
  // Create an array of the output we can later join
  return ['  [' + index + ']', proc.file.green]
    .concat(proc.options.map(function (opt) { return opt.green }))
    .concat([padding + '[', proc.pid + ',', proc.foreverPid, ']'])
    .join(' ');
};

//
// function getAllProcess ()
//   Returns all data for processes managed by forever
//
function getAllProcesses () {
  var processes = [];
  try {
    var files = fs.readdirSync(config.pidPath);
    if (files.length === 0) {
      return null;
    }

    files = files.filter(function(file) { return /\.fvr$/.test(file) });
    files.forEach(function (file) {
      var child = JSON.parse(fs.readFileSync(path.join(config.pidPath, file)));
      processes.push(child);
    });

    return processes;
  }
  catch (ex) {
    // Ignore errors
    return null;
  }
};

//
// function getAllPids ()
//   Returns the set of all pids managed by forever.
//   e.x. [{ pid: 12345, foreverPid: 12346 }, ...]
//
function getAllPids (processes) {
  processes = processes || getAllProcesses();
  if (processes) {
    return processes.map(function (proc) {
      return {
        pid: proc.pid,
        foreverPid: proc.foreverPid
      }
    });
  }

  return null;
};

//
// Forever (file, options)
//   Creates a new instance of forever with specified params.
//   [file]:    Location of the node script to run.
//   [options]: Configuration for this instance.
//
var Forever = function (file, options) {
  events.EventEmitter.call(this);

  options.options.unshift(file);
  options.silent = options.silent || false;
  options.forever = options.forever || false;

  // If we should log stdout, open a file buffer
  if (options.outFile) {
    this.stdout = fs.createWriteStream(options.outFile, { flags: 'a+', encoding: 'utf8', mode: 0666 });
  }

  // If we should log stderr, open a file buffer
  if (options.errFile) {
    this.stderr = fs.createWriteStream(options.errFile, { flags: 'a+', encoding: 'utf8', mode: 0666 });
  }

  this.times = 0;
  this.options = options;
};

// Inherit from events.EventEmitter
sys.inherits(Forever, events.EventEmitter);

//
// function start ()
//   Start the process that this instance is configured for
//
Forever.prototype.start = function (restart) {
  var self = this;

  if (this.running && !restart) {
    process.nextTick(function () {
      self.emit('error', new Error('Cannot start process that is already running.'));
    });
  }

  var child = spawn('node', this.options.options);
  this.child = child;
  this.running = true;

  // Hook all stream data and process it
  function listenTo (stream) {
    child[stream].on('data', function (data) {
      // If we haven't been silenced, and we don't have a file stream
      // to output to write to the process stdout stream
      if (!self.options.silent && !self.options[stream]) {
        process.stdout.write(data);
      }

      // If we have been given an output file for the stream, write to it
      if (self.options[stream]) {
        self[stream].write(data);
      }

      self.emit(stream, data);
    });
  }

  // Listen to stdout and stderr
  listenTo('stdout');
  listenTo('stderr');

  child.on('exit', function (code) {
    self.log('Forever detected script exited with code: ' + code);
    self.times++;

    if (self.options.forever || self.times < self.options.max) {
      self.emit('restart', null, self);
      process.nextTick(function () {
        self.log('Forever restarting script for ' + self.times + ' time');
        self.start(true).save();
      });
    }
    else {
      this.running = false;

      // If had to write to an stdout file, close it
      if (self.options.stdout) {
        self.stdout.end();
      }

      // If had to write to an stderr file, close it
      if (self.options.stderr) {
        self.stderr.end();
      }

      self.emit('exit', null, self);
    }
  });

  return this;
};

//
// function save ()
//   Persists this instance of forever to disk.
//
Forever.prototype.save = function () {
  var self = this;
  if (!this.running) {
    process.nextTick(function () {
      self.emit('error', new Error('Cannot save Forever instance that is not running'));
    });
  }

  var childData = {
    pid: this.child.pid,
    foreverPid: process.pid,
    logFile: this.options.logFile,
    options: this.options.options.slice(1),
    file: this.options.options[0]
  };

  this.childData = childData;
  if (this.options.pidFile) {
    childData.pidFile = this.options.pidFile;
  }

  var childPath = path.join(config.pidPath, childData.foreverPid + '.fvr');
  fs.writeFile(childPath, JSON.stringify(childData), function (err) {
    if (err) self.emit('error', err);
  });

  //
  // Setup the forever process to listen to
  // SIGINT and SIGTERM events so that we can
  // clean up the *.pid file
  //
  // Remark: This should work, but the fd gets screwed up
  //         with the daemon process.
  //
  // process.on('SIGINT', function () {
  //   process.exit(0);
  // });
  //
  //process.on('SIGTERM', function () {
  //  process.exit(0);
  //});

  //process.on('exit', function () {
  //  fs.unlinkSync(childPath);
  //});

  return this;
};

//
// function log (message)
//   Utility function for logging forever actions
//
Forever.prototype.log = function (message) {
  if (!this.options.silent) {
    sys.puts(message);
  }
  return this;
};

//
// function stop ()
//   Stops this instance of forever
//
Forever.prototype.stop = function () {
  if (!this.child || !this.running) {
    var self = this;
    process.nextTick(function () {
      self.emit('error', new Error('Cannot stop process that is not running.'));
    });
  }
  else {
    this.child.kill();
    this.emit('stop', this.childData)
  }

  return this;
};

// Export the Forever object
forever.Forever = Forever;<commit_msg>"command" option to spawn() with, defaults to "node"<commit_after>/*
 * forever.js: Top level include for the forever module
 *
 * (C) 2010 and Charlie Robbins
 * MIT LICENCE
 *
 */

var sys = require('sys'),
    fs = require('fs'),
    colors = require('colors'),
    path = require('path'),
    events = require('events'),
    exec = require('child_process').exec,
    spawn = require('child_process').spawn,
    daemon = require('daemon');

var forever = exports, config;

//
// function load ()
//   Initializes configuration for forever module
//
forever.load = function (options, callback) {
  var emitter = new events.EventEmitter();
  options = options || {};
  options.root    = options.root || path.join('/tmp', 'forever'),
  options.pidPath = options.pidPath || path.join(options.root, 'pids');
  config = options;

  // Create the two directories, ignoring errors
  fs.mkdir(config.root, 0755, function (err) {
    fs.mkdir(config.pidPath, 0755, function (err2) {
      if (callback) callback();
      emitter.emit('load');
    });
  });

  return emitter;
};

//
// function start (file, options)
//   Starts a script with forever
//   [file]:    Location of the node script to run.
//   [options]: Configuration for forever instance.
//
forever.start = function (file, options) {
  return new Forever(file, options).start();
};

//
// function startDaemon (file, options)
//   Starts a script with forever as a daemon
//   [file]:    Location of the node script to run.
//   [options]: Configuration for forever instance.
//
forever.startDaemon = function (file, options) {
  options.logFile = path.join(config.root, options.logFile || 'forever.log');
  options.pidFile = path.join(config.pidPath, options.pidFile);
  var runner = new Forever(file, options);

  fs.open(options.logFile, 'w+', function (err, fd) {
    try {
      var pid = daemon.start(fd);
      daemon.lock(options.pidFile);
      process.pid = pid;

      //
      // Remark: This should work, but the fd gets screwed up
      //         with the daemon process.
      //
      // process.on('exit', function () {
      //   fs.unlinkSync(options.pidFile);
      // });

      runner.start().save();
    }
    catch (ex) {
      runner.emit('error', ex);
    }
  });

  return runner;
};

//
// function stop (index)
//   Stops the process with the specified
//   index in the list of all processes
//
forever.stop = function (index, format) {
  var emitter = new events.EventEmitter(),
      processes = getAllProcesses(),
      proc = processes && processes[index];

  if (proc) {
    exec('kill ' + proc.foreverPid, function () {
      exec('kill ' + proc.pid, function () {
        if (format) proc = formatProcess(proc, index, '');
        emitter.emit('stop', proc);
      });
    });
  }
  else {
    process.nextTick(function () {
      emitter.emit('error', new Error('Cannot find forever process with index: ' + index));
    });
  }

  return emitter;
};

//
// function stopAll (format)
//   Stops all forever processes
//   [format]: Value indicating if we should format output
//
forever.stopAll = function (format) {
  var emitter = new events.EventEmitter(),
      processes = getAllProcesses() || [],
      pids = getAllPids(processes);

  if (format) {
    processes = forever.list(format, processes);
  }

  if (pids && processes) {
    var fPids = pids.map(function (pid) { return pid.foreverPid }).join(' '),
        cPids = pids.map(function (pid) { return pid.pid }).join(' ');

    exec('kill ' + fPids, function () {
      exec('kill ' + cPids, function () {
        emitter.emit('stopAll', processes);
      });
    });
  }
  else {
    process.nextTick(function () {
      emitter.emit('stopAll', null);
    });
  }

  return emitter;
};

//
// function list (format)
//   Returns the list of all process data managed by forever.
//   [format]: If set, will return a formatted string of data
//
forever.list = function (format, procs) {
  var formatted = [], procs = procs || getAllProcesses();
  if (!procs) return null;

  if (format) {
    var index = 0, maxLen = 0;
    // Iterate over the procs to see which has the longest options string
    procs.forEach(function (proc) {
      proc.length = [proc.file].concat(proc.options).join(' ').length;
      if (proc.length > maxLen) maxLen = proc.length;
    });

    procs.forEach(function (proc) {
      // Create padding string to keep output aligned
      var padding = new Array(maxLen - proc.length + 1).join(' ');
      formatted.push(formatProcess(proc, index, padding));
      index++;
    });
  }

  return format ? formatted.join('\n') : procs;
};

//
// function cleanUp ()
//   Utility function for removing excess pid and
//   config files used by forever.
//
forever.cleanUp = function () {
  var emitter = new events.EventEmitter(),
      processes = getAllProcesses();

  if (processes) {
    var checked = 0;
    processes.forEach(function (proc) {
      checkProcess(proc.pid, function (child) {
        checkProcess(proc.foreverPid, function (manager) {
          if (!child && !manager) {
            if (proc.pidFile) {
              fs.unlink(proc.pidFile, function () {
                // Ignore errors
              });
            }

            fs.unlink(path.join(config.pidPath, proc.foreverPid + '.fvr'), function () {
              // Ignore errors
            });
          }

          checked++;
          if (checked === processes.length) {
            emitter.emit('cleanUp');
          }
        });
      });
    });
  }
  else {
    process.nextTick(function () {
      emitter.emit('cleanUp');
    });
  }

  return emitter;
};

//
// function randomString (bits)
//   randomString returns a pseude-random ASCII string which contains at least
//   the specified number of bits of entropy the return value is a string of
//   length ⌈bits/6⌉ of characters from the base64 alphabet.
//
forever.randomString = function (bits) {
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
      rand, i, ret = '';

  //
  // in v8, Math.random() yields 32 pseudo-random bits (in spidermonkey it gives 53)
  //
  while (bits > 0) {
    rand = Math.floor(Math.random()*0x100000000) // 32-bit integer
    // base 64 means 6 bits per character, so we use the top 30 bits from rand to give 30/6=5 characters.
    for (i=26; i>0 && bits>0; i-=6, bits-=6) {
      ret+=chars[0x3F & rand >>> i];
    }
  }
  return ret;
};

//
// function checkProcess (pid, callback)
//   Utility function to check to see if a pid is running
//
function checkProcess (pid, callback) {
  exec('ps ' + pid + ' | grep -v PID', function (err, stdout, stderr) {
    if (err) return callback(false);
    callback(stdout.indexOf(pid) !== -1);
  });
};

//
// function formatProcess (index, padding)
//   Returns a formatted string for the process (proc) at
//   the specified index.
//   [proc]:    Process to format
//   [index]:   Index of the process in the set of all processes
//   [padding]: Padding to add to the formatted output
//
function formatProcess (proc, index, padding) {
  // Create an array of the output we can later join
  return ['  [' + index + ']', proc.file.green]
    .concat(proc.options.map(function (opt) { return opt.green }))
    .concat([padding + '[', proc.pid + ',', proc.foreverPid, ']'])
    .join(' ');
};

//
// function getAllProcess ()
//   Returns all data for processes managed by forever
//
function getAllProcesses () {
  var processes = [];
  try {
    var files = fs.readdirSync(config.pidPath);
    if (files.length === 0) {
      return null;
    }

    files = files.filter(function(file) { return /\.fvr$/.test(file) });
    files.forEach(function (file) {
      var child = JSON.parse(fs.readFileSync(path.join(config.pidPath, file)));
      processes.push(child);
    });

    return processes;
  }
  catch (ex) {
    // Ignore errors
    return null;
  }
};

//
// function getAllPids ()
//   Returns the set of all pids managed by forever.
//   e.x. [{ pid: 12345, foreverPid: 12346 }, ...]
//
function getAllPids (processes) {
  processes = processes || getAllProcesses();
  if (processes) {
    return processes.map(function (proc) {
      return {
        pid: proc.pid,
        foreverPid: proc.foreverPid
      }
    });
  }

  return null;
};

//
// Forever (file, options)
//   Creates a new instance of forever with specified params.
//   [file]:    Location of the node script to run.
//   [options]: Configuration for this instance.
//
var Forever = function (file, options) {
  events.EventEmitter.call(this);

  options.options.unshift(file);
  options.silent = options.silent || false;
  options.forever = options.forever || false;
  options.command = options.command || 'node';

  // If we should log stdout, open a file buffer
  if (options.outFile) {
    this.stdout = fs.createWriteStream(options.outFile, { flags: 'a+', encoding: 'utf8', mode: 0666 });
  }

  // If we should log stderr, open a file buffer
  if (options.errFile) {
    this.stderr = fs.createWriteStream(options.errFile, { flags: 'a+', encoding: 'utf8', mode: 0666 });
  }

  this.times = 0;
  this.options = options;
};

// Inherit from events.EventEmitter
sys.inherits(Forever, events.EventEmitter);

//
// function start ()
//   Start the process that this instance is configured for
//
Forever.prototype.start = function (restart) {
  var self = this;

  if (this.running && !restart) {
    process.nextTick(function () {
      self.emit('error', new Error('Cannot start process that is already running.'));
    });
  }

  var child = spawn(this.options.command, this.options.options);
  this.child = child;
  this.running = true;

  // Hook all stream data and process it
  function listenTo (stream) {
    child[stream].on('data', function (data) {
      // If we haven't been silenced, and we don't have a file stream
      // to output to write to the process stdout stream
      if (!self.options.silent && !self.options[stream]) {
        process.stdout.write(data);
      }

      // If we have been given an output file for the stream, write to it
      if (self.options[stream]) {
        self[stream].write(data);
      }

      self.emit(stream, data);
    });
  }

  // Listen to stdout and stderr
  listenTo('stdout');
  listenTo('stderr');

  child.on('exit', function (code) {
    self.log('Forever detected script exited with code: ' + code);
    self.times++;

    if (self.options.forever || self.times < self.options.max) {
      self.emit('restart', null, self);
      process.nextTick(function () {
        self.log('Forever restarting script for ' + self.times + ' time');
        self.start(true).save();
      });
    }
    else {
      this.running = false;

      // If had to write to an stdout file, close it
      if (self.options.stdout) {
        self.stdout.end();
      }

      // If had to write to an stderr file, close it
      if (self.options.stderr) {
        self.stderr.end();
      }

      self.emit('exit', null, self);
    }
  });

  return this;
};

//
// function save ()
//   Persists this instance of forever to disk.
//
Forever.prototype.save = function () {
  var self = this;
  if (!this.running) {
    process.nextTick(function () {
      self.emit('error', new Error('Cannot save Forever instance that is not running'));
    });
  }

  var childData = {
    pid: this.child.pid,
    foreverPid: process.pid,
    logFile: this.options.logFile,
    options: this.options.options.slice(1),
    file: this.options.options[0]
  };

  this.childData = childData;
  if (this.options.pidFile) {
    childData.pidFile = this.options.pidFile;
  }

  var childPath = path.join(config.pidPath, childData.foreverPid + '.fvr');
  fs.writeFile(childPath, JSON.stringify(childData), function (err) {
    if (err) self.emit('error', err);
  });

  //
  // Setup the forever process to listen to
  // SIGINT and SIGTERM events so that we can
  // clean up the *.pid file
  //
  // Remark: This should work, but the fd gets screwed up
  //         with the daemon process.
  //
  // process.on('SIGINT', function () {
  //   process.exit(0);
  // });
  //
  //process.on('SIGTERM', function () {
  //  process.exit(0);
  //});

  //process.on('exit', function () {
  //  fs.unlinkSync(childPath);
  //});

  return this;
};

//
// function log (message)
//   Utility function for logging forever actions
//
Forever.prototype.log = function (message) {
  if (!this.options.silent) {
    sys.puts(message);
  }
  return this;
};

//
// function stop ()
//   Stops this instance of forever
//
Forever.prototype.stop = function () {
  if (!this.child || !this.running) {
    var self = this;
    process.nextTick(function () {
      self.emit('error', new Error('Cannot stop process that is not running.'));
    });
  }
  else {
    this.child.kill();
    this.emit('stop', this.childData)
  }

  return this;
};

// Export the Forever object
forever.Forever = Forever;
<|endoftext|>


<commit_before>'use strict';

module.exports = {
    'default': 'RFC3986',
    formatters: {
        RFC1738: function (value) {
            return String(value).replace(/%20/g, '+');
        },
        RFC3986: function (value) {
            return value;
        }
    },
    RFC1738: 'RFC1738',
    RFC3986: 'RFC3986'
};
<commit_msg>[Robustness] `formats`: cache `String#replace`<commit_after>'use strict';

var replace = String.prototype.replace;
var percentTwenties = /%20/g;

module.exports = {
    'default': 'RFC3986',
    formatters: {
        RFC1738: function (value) {
            return replace.call(value, percentTwenties, '+');
        },
        RFC3986: function (value) {
            return value;
        }
    },
    RFC1738: 'RFC1738',
    RFC3986: 'RFC3986'
};
<|endoftext|>


<commit_before>// Get retcode, score and status
function show_files() {
    var sub_uuid = getParameterByName('uuid');
    $("span#sub_uuid").text(sub_uuid);

    var find_files = function(data, status) {
        var array_length = data.files.length;
        var file_array = [];

        $.each(data.files, function(index, uuid) {
            file_get(function(data, status) {
                var f = {};

                var uuid = Object.keys(data)[0];
                var file_name = data[uuid].name;

                f.name = file_name;
                f.uuid = uuid;

                file_array.push(f);

                // Account for length of the array
                if (file_array.length === array_length) {
                    sort_files(file_array);
                }
            }, submit_error_callback, uuid);
        });
    };

    submission_get_files(find_files, submit_error_callback, sub_uuid);
}

function sort_files(file_array) {
    file_array.sort(function(x, y) {
        return x.name.localeCompare(y.name);
    });

    $.each(file_array, function(index, fle) {
        var url = file_get_uri(fle.uuid);
        $("#files_table").append("
" + fle.name + '	' + fle.uuid + "
");
    });

    console.log("Sorted Table");
}

// Taken from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
function getParameterByName(name, url) {
    if (!url) url = window.location.href;

    name = name.replace(/[\[\]]/g, "\\$&");

    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);

    if (!results) return null;
    if (!results[2]) return '';

    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function submit_error_callback(xhr, status, error) {
    // Log Error
    console.log("Status: " + status, ", Error: " + error);
}
<commit_msg>Revert to AJAX for downloads so authorization headers are passed.<commit_after>// Get retcode, score and status
function show_files() {
    var sub_uuid = getParameterByName('uuid');
    $("span#sub_uuid").text(sub_uuid);

    var find_files = function(data, status) {
        var array_length = data.files.length;
        var file_array = [];

        $.each(data.files, function(index, uuid) {
            file_get(function(data, status) {
                var f = {};

                var uuid = Object.keys(data)[0];
                var file_name = data[uuid].name;

                f.name = file_name;
                f.uuid = uuid;

                file_array.push(f);

                // Account for length of the array
                if (file_array.length === array_length) {
                    sort_files(file_array);
                }
            }, submit_error_callback, uuid);
        });
    };

    submission_get_files(find_files, submit_error_callback, sub_uuid);
}

function sort_files(file_array) {
    file_array.sort(function(x, y) {
        return x.name.localeCompare(y.name);
    });

    $.each(file_array, function(index, fle) {
        var url = file_get_uri(fle.uuid);
        $("#files_table").append("
" + fle.name + '	' + fle.uuid + "
");
    });

    console.log("Sorted Table");
}

// Taken from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
function getParameterByName(name, url) {
    if (!url) url = window.location.href;

    name = name.replace(/[\[\]]/g, "\\$&");

    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);

    if (!results) return null;
    if (!results[2]) return '';

    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function submit_error_callback(xhr, status, error) {
    // Log Error
    console.log("Status: " + status, ", Error: " + error);
}

$('#files_table').delegate('.auth-dl', 'click', function(event) {
    event.preventDefault();

    var uuid = $(this).data('uuid');
    var name = $(this).data('name');

    file_get_contents(function(data, status) {
        var blob = new Blob([data], { type: 'octet/stream' });
        var url = window.URL.createObjectURL(blob);

        var a = document.createElement('a');
        a.style = 'display: none';
        a.href = url;
        a.download = name;

        $(document.body).append(a);
        a.click();
        window.URL.revokeObjectURL(url);
    }, submit_error_callback, uuid);
});
<|endoftext|>


<commit_before>/**
 * http://en.wikipedia.org/wiki/YouTube#Quality_and_formats
 */
module.exports = {

  '5': {
    container: 'flv',
    resolution: '240p',
    encoding: 'Sorenson H.283',
    profile: null,
    bitrate: '0.25',
    audioEncoding: 'mp3',
    audioBitrate: 64,
  },

  '6': {
    container: 'flv',
    resolution: '270p',
    encoding: 'Sorenson H.263',
    profile: null,
    bitrate: '0.8',
    audioEncoding: 'mp3',
    audioBitrate: 64,
  },

  '13': {
    container: '3gp',
    resolution: null,
    encoding: 'MPEG-4 Visual',
    profile: null,
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: null,
  },

  '17': {
    container: '3gp',
    resolution: '144p',
    encoding: 'MPEG-4 Visual',
    profile: 'simple',
    bitrate: '0.05',
    audioEncoding: 'aac',
    audioBitrate: 24,
  },

  '18': {
    container: 'mp4',
    resolution: '360p',
    encoding: 'H.264',
    profile: 'baseline',
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '22': {
    container: 'mp4',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '2-3',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '34': {
    container: 'flv',
    resolution: '360p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '35': {
    container: 'flv',
    resolution: '480p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.8-1',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '36': {
    container: '3gp',
    resolution: '240p',
    encoding: 'MPEG-4 Visual',
    profile: 'simple',
    bitrate: '0.175',
    audioEncoding: 'aac',
    audioBitrate: 36,
  },

  '37': {
    container: 'mp4',
    resolution: '1080p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '3-5.9',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '38': {
    container: 'mp4',
    resolution: '3072p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '3.5-5',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '43': {
    container: 'webm',
    resolution: '360p',
    encoding: 'VP8',
    profile: null,
    bitrate: '0.5',
    audioEncoding: 'vorbis',
    audioBitrate: 128,
  },

  '44': {
    container: 'webm',
    resolution: '480p',
    encoding: 'VP8',
    profile: null,
    bitrate: '1',
    audioEncoding: 'vorbis',
    audioBitrate: 128,
  },

  '45': {
    container: 'webm',
    resolution: '720p',
    encoding: 'VP8',
    profile: null,
    bitrate: '2',
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  '46': {
    container: 'webm',
    resolution: '1080p',
    encoding: 'vp8',
    profile: null,
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  '82': {
    container: 'mp4',
    resolution: '360p',
    encoding: 'H.264',
    profile: '3d',
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '83': {
    container: 'mp4',
    resolution: '240p',
    encoding: 'H.264',
    profile: '3d',
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '84': {
    container: 'mp4',
    resolution: '720p',
    encoding: 'H.264',
    profile: '3d',
    bitrate: '2-3',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '85': {
    container: 'mp4',
    resolution: '1080p',
    encoding: 'H.264',
    profile: '3d',
    bitrate: '3-4',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '100': {
    container: 'webm',
    resolution: '360p',
    encoding: 'VP8',
    profile: '3d',
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 128,
  },

  '101': {
    container: 'webm',
    resolution: '360p',
    encoding: 'VP8',
    profile: '3d',
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  '102': {
    container: 'webm',
    resolution: '720p',
    encoding: 'VP8',
    profile: '3d',
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  // DASH (video only)
  '133': {
    container: 'mp4',
    resolution: '240p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.2-0.3',
    audioEncoding: null,
    audioBitrate: null,
  },

  '134': {
    container: 'mp4',
    resolution: '360p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.3-0.4',
    audioEncoding: null,
    audioBitrate: null,
  },

  '135': {
    container: 'mp4',
    resolution: '480p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.5-1',
    audioEncoding: null,
    audioBitrate: null,
  },

  '136': {
    container: 'mp4',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '1-1.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '137': {
    container: 'mp4',
    resolution: '1080p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '2-3',
    audioEncoding: null,
    audioBitrate: null,
  },

  '138': {
    container: 'mp4',
    resolution: '2160p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '13.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '160': {
    container: 'mp4',
    resolution: '144p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.1',
    audioEncoding: null,
    audioBitrate: null,
  },

  '242': {
    container: 'webm',
    resolution: '240p',
    encoding: 'VP9',
    profile: null,
    bitrate: '0.14',
    audioEncoding: null,
    audioBitrate: null,
  },

  '243': {
    container: 'webm',
    resolution: '360p',
    encoding: 'VP9',
    profile: null,
    bitrate: '0.26',
    audioEncoding: null,
    audioBitrate: null,
  },

  '244': {
    container: 'webm',
    resolution: '480p',
    encoding: 'VP9',
    profile: null,
    bitrate: '0.585',
    audioEncoding: null,
    audioBitrate: null,
  },

  '247': {
    container: 'webm',
    resolution: '720p',
    encoding: 'VP9',
    profile: null,
    bitrate: '1.184',
    audioEncoding: null,
    audioBitrate: null,
  },

  '248': {
    container: 'webm',
    resolution: '1080p',
    encoding: 'VP9',
    profile: null,
    bitrate: '1.895',
    audioEncoding: null,
    audioBitrate: null,
  },

  '264': {
    container: 'mp4',
    resolution: '1440p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '4-5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '266': {
    container: 'mp4',
    resolution: '2160p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '12.5-13.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '271': {
    container: 'webm',
    resolution: '1440p',
    encoding: 'VP9',
    profile: null,
    bitrate: '9',
    audioEncoding: null,
    audioBitrate: null,
  },

  '272': {
    container: 'webm',
    resolution: '2160p',
    encoding: 'VP9',
    profile: null,
    bitrate: '20',
    audioEncoding: null,
    audioBitrate: null,
  },

  '278': {
    container: 'webm',
    resolution: '144p',
    encoding: 'VP9',
    profile: null,
    bitrate: '0.08',
    audioEncoding: null,
    audioBitrate: null,
  },

  '298': {
    container: 'mp4',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '3-3.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '299': {
    container: 'mp4',
    resolution: '1080p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '5.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '302': {
    container: 'webm',
    resolution: '720p',
    encoding: 'VP9',
    profile: null,
    bitrate: '2.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '303': {
    container: 'webm',
    resolution: '1080p',
    encoding: 'VP9',
    profile: null,
    bitrate: '5',
    audioEncoding: null,
    audioBitrate: null,
  },

  // DASH (audio only)
  '139': {
    container: 'mp4',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 48,
  },

  '140': {
    container: 'mp4',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '141': {
    container: 'mp4',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 256,
  },

  '171': {
    container: 'webm',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 128,
  },

  '172': {
    container: 'webm',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  // Live streaming
  '92': {
    container: 'ts',
    resolution: '240p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.15-0.3',
    audioEncoding: 'aac',
    audioBitrate: 48,
  },

  '93': {
    container: 'ts',
    resolution: '480p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.5-1',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '94': {
    container: 'ts',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.8-1.25',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '95': {
    container: 'ts',
    resolution: '1080p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '1.5-3',
    audioEncoding: 'aac',
    audioBitrate: 256,
  },

  '96': {
    container: 'ts',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '2.5-6',
    audioEncoding: 'aac',
    audioBitrate: 256,
  },

  '120': {
    container: 'flv',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'Main@L3.1',
    bitrate: '2',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '127': {
    container: 'ts',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '128': {
    container: 'ts',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '132': {
    container: 'ts',
    resolution: '240p',
    encoding: 'H.264',
    profile: 'baseline',
    bitrate: '0.15-0.2',
    audioEncoding: 'aac',
    audioBitrate: 48,
  },

  '151': {
    container: 'ts',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'baseline',
    bitrate: '0.05',
    audioEncoding: 'aac',
    audioBitrate: 24,
  },

};
<commit_msg>add opus audio formats<commit_after>/**
 * http://en.wikipedia.org/wiki/YouTube#Quality_and_formats
 */
module.exports = {

  '5': {
    container: 'flv',
    resolution: '240p',
    encoding: 'Sorenson H.283',
    profile: null,
    bitrate: '0.25',
    audioEncoding: 'mp3',
    audioBitrate: 64,
  },

  '6': {
    container: 'flv',
    resolution: '270p',
    encoding: 'Sorenson H.263',
    profile: null,
    bitrate: '0.8',
    audioEncoding: 'mp3',
    audioBitrate: 64,
  },

  '13': {
    container: '3gp',
    resolution: null,
    encoding: 'MPEG-4 Visual',
    profile: null,
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: null,
  },

  '17': {
    container: '3gp',
    resolution: '144p',
    encoding: 'MPEG-4 Visual',
    profile: 'simple',
    bitrate: '0.05',
    audioEncoding: 'aac',
    audioBitrate: 24,
  },

  '18': {
    container: 'mp4',
    resolution: '360p',
    encoding: 'H.264',
    profile: 'baseline',
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '22': {
    container: 'mp4',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '2-3',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '34': {
    container: 'flv',
    resolution: '360p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '35': {
    container: 'flv',
    resolution: '480p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.8-1',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '36': {
    container: '3gp',
    resolution: '240p',
    encoding: 'MPEG-4 Visual',
    profile: 'simple',
    bitrate: '0.175',
    audioEncoding: 'aac',
    audioBitrate: 36,
  },

  '37': {
    container: 'mp4',
    resolution: '1080p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '3-5.9',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '38': {
    container: 'mp4',
    resolution: '3072p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '3.5-5',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '43': {
    container: 'webm',
    resolution: '360p',
    encoding: 'VP8',
    profile: null,
    bitrate: '0.5',
    audioEncoding: 'vorbis',
    audioBitrate: 128,
  },

  '44': {
    container: 'webm',
    resolution: '480p',
    encoding: 'VP8',
    profile: null,
    bitrate: '1',
    audioEncoding: 'vorbis',
    audioBitrate: 128,
  },

  '45': {
    container: 'webm',
    resolution: '720p',
    encoding: 'VP8',
    profile: null,
    bitrate: '2',
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  '46': {
    container: 'webm',
    resolution: '1080p',
    encoding: 'vp8',
    profile: null,
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  '82': {
    container: 'mp4',
    resolution: '360p',
    encoding: 'H.264',
    profile: '3d',
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '83': {
    container: 'mp4',
    resolution: '240p',
    encoding: 'H.264',
    profile: '3d',
    bitrate: '0.5',
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '84': {
    container: 'mp4',
    resolution: '720p',
    encoding: 'H.264',
    profile: '3d',
    bitrate: '2-3',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '85': {
    container: 'mp4',
    resolution: '1080p',
    encoding: 'H.264',
    profile: '3d',
    bitrate: '3-4',
    audioEncoding: 'aac',
    audioBitrate: 192,
  },

  '100': {
    container: 'webm',
    resolution: '360p',
    encoding: 'VP8',
    profile: '3d',
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 128,
  },

  '101': {
    container: 'webm',
    resolution: '360p',
    encoding: 'VP8',
    profile: '3d',
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  '102': {
    container: 'webm',
    resolution: '720p',
    encoding: 'VP8',
    profile: '3d',
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  // DASH (video only)
  '133': {
    container: 'mp4',
    resolution: '240p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.2-0.3',
    audioEncoding: null,
    audioBitrate: null,
  },

  '134': {
    container: 'mp4',
    resolution: '360p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.3-0.4',
    audioEncoding: null,
    audioBitrate: null,
  },

  '135': {
    container: 'mp4',
    resolution: '480p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.5-1',
    audioEncoding: null,
    audioBitrate: null,
  },

  '136': {
    container: 'mp4',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '1-1.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '137': {
    container: 'mp4',
    resolution: '1080p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '2-3',
    audioEncoding: null,
    audioBitrate: null,
  },

  '138': {
    container: 'mp4',
    resolution: '2160p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '13.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '160': {
    container: 'mp4',
    resolution: '144p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.1',
    audioEncoding: null,
    audioBitrate: null,
  },

  '242': {
    container: 'webm',
    resolution: '240p',
    encoding: 'VP9',
    profile: null,
    bitrate: '0.14',
    audioEncoding: null,
    audioBitrate: null,
  },

  '243': {
    container: 'webm',
    resolution: '360p',
    encoding: 'VP9',
    profile: null,
    bitrate: '0.26',
    audioEncoding: null,
    audioBitrate: null,
  },

  '244': {
    container: 'webm',
    resolution: '480p',
    encoding: 'VP9',
    profile: null,
    bitrate: '0.585',
    audioEncoding: null,
    audioBitrate: null,
  },

  '247': {
    container: 'webm',
    resolution: '720p',
    encoding: 'VP9',
    profile: null,
    bitrate: '1.184',
    audioEncoding: null,
    audioBitrate: null,
  },

  '248': {
    container: 'webm',
    resolution: '1080p',
    encoding: 'VP9',
    profile: null,
    bitrate: '1.895',
    audioEncoding: null,
    audioBitrate: null,
  },

  '264': {
    container: 'mp4',
    resolution: '1440p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '4-5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '266': {
    container: 'mp4',
    resolution: '2160p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '12.5-13.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '271': {
    container: 'webm',
    resolution: '1440p',
    encoding: 'VP9',
    profile: null,
    bitrate: '9',
    audioEncoding: null,
    audioBitrate: null,
  },

  '272': {
    container: 'webm',
    resolution: '2160p',
    encoding: 'VP9',
    profile: null,
    bitrate: '20',
    audioEncoding: null,
    audioBitrate: null,
  },

  '278': {
    container: 'webm',
    resolution: '144p',
    encoding: 'VP9',
    profile: null,
    bitrate: '0.08',
    audioEncoding: null,
    audioBitrate: null,
  },

  '298': {
    container: 'mp4',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '3-3.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '299': {
    container: 'mp4',
    resolution: '1080p',
    encoding: 'H.264',
    profile: 'high',
    bitrate: '5.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '302': {
    container: 'webm',
    resolution: '720p',
    encoding: 'VP9',
    profile: null,
    bitrate: '2.5',
    audioEncoding: null,
    audioBitrate: null,
  },

  '303': {
    container: 'webm',
    resolution: '1080p',
    encoding: 'VP9',
    profile: null,
    bitrate: '5',
    audioEncoding: null,
    audioBitrate: null,
  },

  // DASH (audio only)
  '139': {
    container: 'mp4',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 48,
  },

  '140': {
    container: 'mp4',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '141': {
    container: 'mp4',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 256,
  },

  '171': {
    container: 'webm',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 128,
  },

  '172': {
    container: 'webm',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'vorbis',
    audioBitrate: 192,
  },

  '249': {
    container: 'webm',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'opus',
    audioBitrate: 50,
  },
  '250': {
    container: 'webm',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'opus',
    audioBitrate: 70,
  },
  '251': {
    container: 'webm',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'opus',
    audioBitrate: 160,
  },

  // Live streaming
  '92': {
    container: 'ts',
    resolution: '240p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.15-0.3',
    audioEncoding: 'aac',
    audioBitrate: 48,
  },

  '93': {
    container: 'ts',
    resolution: '480p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.5-1',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '94': {
    container: 'ts',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '0.8-1.25',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '95': {
    container: 'ts',
    resolution: '1080p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '1.5-3',
    audioEncoding: 'aac',
    audioBitrate: 256,
  },

  '96': {
    container: 'ts',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'main',
    bitrate: '2.5-6',
    audioEncoding: 'aac',
    audioBitrate: 256,
  },

  '120': {
    container: 'flv',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'Main@L3.1',
    bitrate: '2',
    audioEncoding: 'aac',
    audioBitrate: 128,
  },

  '127': {
    container: 'ts',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '128': {
    container: 'ts',
    resolution: null,
    encoding: null,
    profile: null,
    bitrate: null,
    audioEncoding: 'aac',
    audioBitrate: 96,
  },

  '132': {
    container: 'ts',
    resolution: '240p',
    encoding: 'H.264',
    profile: 'baseline',
    bitrate: '0.15-0.2',
    audioEncoding: 'aac',
    audioBitrate: 48,
  },

  '151': {
    container: 'ts',
    resolution: '720p',
    encoding: 'H.264',
    profile: 'baseline',
    bitrate: '0.05',
    audioEncoding: 'aac',
    audioBitrate: 24,
  },

};
<|endoftext|>


<commit_before>function newDiffSuprressedDiv() {
  return $.parseHTML('
 Diff suppressed. Click to show. 0) {
      return false
    }

    var match_happened = false
    // Check if there is a match on some glob against the file name
    $(match_regexes).each(function(i, match_glob){
      var regex = new RegExp(match_glob)
      if ($(element).find('.file-header').attr("data-path").match(regex)) {
        match_happened = true
      }
    });

    return match_happened
  })

  file_diff_containers.each(function(i, element) {
    $(element).find("div.data.highlight").addClass("suppressed")
    $(element).after(newDiffSuprressedDiv())
  })
});<commit_msg>update<commit_after>function newDiffSuprressedDiv() {
  return $.parseHTML('
 Diff suppressed. 0) {
      return false
    }

    var match_happened = false
    // Check if there is a match on some glob against the file name
    $(match_regexes).each(function(i, match_glob){
      var regex = new RegExp(match_glob)
      if ($(element).find('.file-header').attr("data-path").match(regex)) {
        match_happened = true
      }
    });

    return match_happened
  })

  file_diff_containers.each(function(i, element) {
    $(element).find("div.data.highlight").addClass("suppressed")
    $(element).after(newDiffSuprressedDiv())
  })
});<|endoftext|>


<commit_before>'use strict';

function update_color(){
    var current_time = Math.floor(time_date_to_timestamp() / interval).toString();
    var hex = '#' + current_time.substr(current_time.length - 6);

    document.body.style.background = hex;
    document.getElementById('current-color').innerHTML = hex;
}

function repo_init(){
    update_color();
    window.setInterval(
      update_color,
      interval
    );
}

var interval = 100;
<commit_msg>added core_repo_init() usage<commit_after>'use strict';

function update_color(){
    var current_time = Math.floor(time_date_to_timestamp() / interval).toString();
    var hex = '#' + current_time.substr(current_time.length - 6);

    document.body.style.background = hex;
    document.getElementById('current-color').innerHTML = hex;
}

function repo_init(){
    core_repo_init({
      'title': 'TimeColors.htm',
    });

    update_color();
    window.setInterval(
      update_color,
      interval
    );
}

var interval = 100;
<|endoftext|>