<commit_before>Dice = new Meteor.Collection("dice");
if (Meteor.isClient) {
  Template.global = function () {
    return "works?";
  };

  Template.roller.greeting = function () {
    var dice = Dice.find({});
    var blurb = "";
    dice.fetch().forEach( function (die) {
      blurb = blurb + " " + die.value;
    });
    return blurb;
  };

  Template.roller.events({
    'click input': function () {
      Meteor.call('roll');
    }
  });

  Template.hello.greeting = function () {
    return "Welcome to aroma!";
  };

  Template.hello.events({
    'click input': function () {
      // template data, if any, is available in 'this'
      if (typeof console !== 'undefined')
        console.log("You pressed the button");
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    Dice.remove({});
    Meteor.call('turn');
  });
}

Meteor.methods({
  'turn': function () {
    if (Meteor.isServer) {
      Meteor.call('roll');
    }},
  'roll': function () {
    if (Meteor.isServer) {
      Dice.remove({});
      Dice.insert({value: Math.floor((Math.random() * 6) + 1)});
      Dice.insert({value: Math.floor((Math.random() * 6) + 1)});
      Dice.insert({value: Math.floor((Math.random() * 6) + 1)});
    }
  }
});
<commit_msg>Dies can be applied<commit_after>Dice = new Meteor.Collection("dice");
if (Meteor.isClient) {
  Template.global = function () {
    return "works?";
  };

  Template.roller.greeting = function () {
    var dice = Dice.find({});
    var blurb = "";
    dice.fetch().forEach( function (die) {
      blurb = blurb + " " + die.value + " " + die.applied;
    });
    return blurb;
  };

  Template.roller.events({
    'click input': function () {
      Meteor.call('roll');
    }
  });

  Template.hello.greeting = function () {
    return "Welcome to aroma!";
  };

  Template.hello.events({
    'click input': function () {
      // template data, if any, is available in 'this'
      if (typeof console !== 'undefined')
        console.log("You pressed the button");
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    Dice.remove({});
    Meteor.call('turn');
  });
}

Meteor.methods({
  'turn': function () {
    if (Meteor.isServer) {
      Meteor.call('roll');
    }},
  'roll': function () {
    if (Meteor.isServer) {
      Dice.remove({});
      Dice.insert(createDie());
      Dice.insert(createDie());
      Dice.insert(createDie());
    }
  }
});

createDie = function() {
  return {value: Math.floor((Math.random() * 6) + 1), applied: false};
}
<|endoftext|>


<commit_before>function MyArray() {
  this.array = [];
}

MyArray.prototype.add = function(data) {
  this.array.push(data);
};
MyArray.prototype.remove = function(data) {
  if(~this.array.indexOf(data)) {
    this.array.splice(this.array.indexOf(data), 1);
  }
};
MyArray.prototype.search = function(data) {
  if(~this.array.indexOf(data)) {
    return this.array.indexOf(data);
  } else {
    return null;
  }
};
MyArray.prototype.getAtIndex = function(index) {
  return this.array[index];
};
MyArray.prototype.length = function() {
  return this.array.length;
};
MyArray.prototype.print = function() {
  console.log(this.array.join(' '));
};

var array = new MyArray();
array.add(1);
array.add(2);
array.add(3);
array.add(4);
array.print(); // => 1 2 3 4
console.log('search 3 gives index 2:', array.search(3)); // => 2
console.log('getAtIndex 2 gives 3:', array.getAtIndex(2)); // => 3
console.log('length is 4:', array.length()); // => 4
array.remove(3);
array.print(); // => 1 2 4
<commit_msg>Updating Array.prototype.remove to remove duplicates<commit_after>function MyArray() {
  this.array = [];
}

MyArray.prototype.add = function(data) {
  this.array.push(data);
};
MyArray.prototype.remove = function(data) {
  this.array = this.array.filter(function(current) {
    return current !== data;
  });
};
MyArray.prototype.search = function(data) {

  var foundIndex = this.array.indexOf(data);
  if(~foundIndex) {
    return foundIndex;
  }

  return null;
};
MyArray.prototype.getAtIndex = function(index) {
  return this.array[index];
};
MyArray.prototype.length = function() {
  return this.array.length;
};
MyArray.prototype.print = function() {
  console.log(this.array.join(' '));
};

var array = new MyArray();
array.add(1);
array.add(2);
array.add(3);
array.add(4);
array.print(); // => 1 2 3 4
console.log('search 3 gives index 2:', array.search(3)); // => 2
console.log('getAtIndex 2 gives 3:', array.getAtIndex(2)); // => 3
console.log('length is 4:', array.length()); // => 4
array.remove(3);
array.print(); // => 1 2 4
array.add(5);
array.add(5);
array.print(); // => 1 2 4 5 5
array.remove(5);
array.print(); // => 1 2 4<|endoftext|>


<commit_before>// javascript-astar 0.3.0
// http://github.com/bgrins/javascript-astar
// Freely distributable under the MIT License.
// Implements the astar search algorithm in javascript using a Binary Heap.
// Includes Binary Heap (with modifications) from Marijn Haverbeke.
// http://eloquentjavascript.net/appendix2.html

(function(definition) {
    if(typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = definition();
    } else if(typeof define === 'function' && define.amd) {
        define([], definition);
    } else {
        var exports = definition();
        window.astar = exports.astar;
        window.Graph = exports.Graph;
    }
})(function() {

function pathTo(node){
    var curr = node,
        path = [];
    while(curr.parent) {
        path.push(curr);
        curr = curr.parent;
    }
    return path.reverse();
}

var astar = {
    init: function(graph) {
        for (var i = 0, len = graph.nodes.length; i < len; ++i) {
            var node = graph.nodes[i];
            node.f = 0;
            node.g = 0;
            node.h = 0;
            node.visited = false;
            node.closed = false;
            node.parent = null;
        }
    },
    heap: function() {
        return new BinaryHeap(function(node) {
            return node.f;
        });
    },

    // astar.search
    // supported options:
    // {
    //   heuristic: heuristic function to use
    //   closest: boolean specifying whether to return closest node if
    //            target is unreachable
    // }
    search: function(graph, start, end, options) {
        astar.init(graph);

        options = options || {};
        var heuristic = options.heuristic || astar.heuristics.manhattan,
            closest = options.closest || false;

        var openHeap = astar.heap(),
            closestNode = start; // set the start node to be the closest if required

        start.h = heuristic(start, end);

        openHeap.push(start);

        while(openHeap.size() > 0) {

            // Grab the lowest f(x) to process next.  Heap keeps this sorted for us.
            var currentNode = openHeap.pop();

            // End case -- result has been found, return the traced path.
            if(currentNode === end) {
                return pathTo(currentNode);
            }

            // Normal case -- move currentNode from open to closed, process each of its neighbors.
            currentNode.closed = true;

            // Find all neighbors for the current node.
            var neighbors = graph.neighbors(currentNode);

            for(var i = 0, il = neighbors.length; i < il; ++i) {
                var neighbor = neighbors[i];

                if(neighbor.closed || neighbor.isWall()) {
                    // Not a valid node to process, skip to next neighbor.
                    continue;
                }

                // The g score is the shortest distance from start to current node.
                // We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet.
                var gScore = currentNode.g + neighbor.getCost(currentNode),
                    beenVisited = neighbor.visited;

                if(!beenVisited || gScore < neighbor.g) {

                    // Found an optimal (so far) path to this node.  Take score for node to see how good it is.
                    neighbor.visited = true;
                    neighbor.parent = currentNode;
                    neighbor.h = neighbor.h || heuristic(neighbor, end);
                    neighbor.g = gScore;
                    neighbor.f = neighbor.g + neighbor.h;

                    if (closest) {
                        // If the neighbour is closer than the current closestNode or if it's equally close but has
                        // a cheaper path than the current closest node then it becomes the closest node
                        if (neighbor.h < closestNode.h || (neighbor.h === closestNode.h && neighbor.g < closestNode.g)) {
                            closestNode = neighbor;
                        }
                    }

                    if (!beenVisited) {
                        // Pushing to heap will put it in proper place based on the 'f' value.
                        openHeap.push(neighbor);
                    }
                    else {
                        // Already seen the node, but since it has been rescored we need to reorder it in the heap
                        openHeap.rescoreElement(neighbor);
                    }
                }
            }
        }

        if (closest) {
            return pathTo(closestNode);
        }

        // No result was found - empty array signifies failure to find path.
        return [];
    },
    // See list of heuristics: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
    heuristics: {
        manhattan: function(pos0, pos1) {
            var d1 = Math.abs (pos1.x - pos0.x);
            var d2 = Math.abs (pos1.y - pos0.y);
            return d1 + d2;
        },
        diagonal: function(pos0, pos1) {
            var D = 1;
            var D2 = Math.sqrt(2);
            var d1 = Math.abs (pos1.x - pos0.x);
            var d2 = Math.abs (pos1.y - pos0.y);
            return (D * (d1 + d2)) + ((D2 - (2 * D)) * Math.min(d1, d2));
        }
    }
};

/**
* A graph memory structure
* @param {Array} [gridIn] 2D array of input weights
* @param {bool} options
*               diagonal: Specifies whether diagonal moves are allowed
*/
function Graph(gridIn, options) {
    options = options || {};
    this.nodes = [];
    this.diagonal = !!options.diagonal;
    this.grid = [];
    for (var x = 0; x < gridIn.length; x++) {
        this.grid[x] = [];

        for (var y = 0, row = gridIn[x]; y < row.length; y++) {
            var node = new GridNode(x, y, row[y]);
            this.grid[x][y] = node;
            this.nodes.push(node);
        }
    }
}
Graph.prototype.neighbors = function(node) {
    var ret = [],
        x = node.x,
        y = node.y,
        grid = this.grid;

    // West
    if(grid[x-1] && grid[x-1][y]) {
        ret.push(grid[x-1][y]);
    }

    // East
    if(grid[x+1] && grid[x+1][y]) {
        ret.push(grid[x+1][y]);
    }

    // South
    if(grid[x] && grid[x][y-1]) {
        ret.push(grid[x][y-1]);
    }

    // North
    if(grid[x] && grid[x][y+1]) {
        ret.push(grid[x][y+1]);
    }

    if (this.diagonal) {
        // Southwest
        if(grid[x-1] && grid[x-1][y-1]) {
            ret.push(grid[x-1][y-1]);
        }

        // Southeast
        if(grid[x+1] && grid[x+1][y-1]) {
            ret.push(grid[x+1][y-1]);
        }

        // Northwest
        if(grid[x-1] && grid[x-1][y+1]) {
            ret.push(grid[x-1][y+1]);
        }

        // Northeast
        if(grid[x+1] && grid[x+1][y+1]) {
            ret.push(grid[x+1][y+1]);
        }
    }

    return ret;
};

Graph.prototype.toString = function() {
    var graphString = [],
        nodes = this.grid, // when using grid
        rowDebug, row, y, l;
    for (var x = 0, len = nodes.length; x < len; x++) {
        rowDebug = [];
        row = nodes[x];
        for (y = 0, l = row.length; y < l; y++) {
            rowDebug.push(row[y].weight);
        }
        graphString.push(rowDebug.join(" "));
    }
    return graphString.join("\n");
};

function GridNode(x, y, weight) {
    this.x = x;
    this.y = y;
    this.weight = weight;
}

GridNode.prototype.toString = function() {
    return "[" + this.x + " " + this.y + "]";
};

GridNode.prototype.getCost = function() {
    return this.weight;
};

GridNode.prototype.isWall = function() {
    return this.weight === 0;
};

function BinaryHeap(scoreFunction){
    this.content = [];
    this.scoreFunction = scoreFunction;
}

BinaryHeap.prototype = {
    push: function(element) {
        // Add the new element to the end of the array.
        this.content.push(element);

        // Allow it to sink down.
        this.sinkDown(this.content.length - 1);
    },
    pop: function() {
        // Store the first element so we can return it later.
        var result = this.content[0];
        // Get the element at the end of the array.
        var end = this.content.pop();
        // If there are any elements left, put the end element at the
        // start, and let it bubble up.
        if (this.content.length > 0) {
            this.content[0] = end;
            this.bubbleUp(0);
        }
        return result;
    },
    remove: function(node) {
        var i = this.content.indexOf(node);

        // When it is found, the process seen in 'pop' is repeated
        // to fill up the hole.
        var end = this.content.pop();

        if (i !== this.content.length - 1) {
            this.content[i] = end;

            if (this.scoreFunction(end) < this.scoreFunction(node)) {
                this.sinkDown(i);
            }
            else {
                this.bubbleUp(i);
            }
        }
    },
    size: function() {
        return this.content.length;
    },
    rescoreElement: function(node) {
        this.sinkDown(this.content.indexOf(node));
    },
    sinkDown: function(n) {
        // Fetch the element that has to be sunk.
        var element = this.content[n];

        // When at 0, an element can not sink any further.
        while (n > 0) {

            // Compute the parent element's index, and fetch it.
            var parentN = ((n + 1) >> 1) - 1,
                parent = this.content[parentN];
            // Swap the elements if the parent is greater.
            if (this.scoreFunction(element) < this.scoreFunction(parent)) {
                this.content[parentN] = element;
                this.content[n] = parent;
                // Update 'n' to continue at the new position.
                n = parentN;
            }
            // Found a parent that is less, no need to sink any further.
            else {
                break;
            }
        }
    },
    bubbleUp: function(n) {
        // Look up the target element and its score.
        var length = this.content.length,
            element = this.content[n],
            elemScore = this.scoreFunction(element);

        while(true) {
            // Compute the indices of the child elements.
            var child2N = (n + 1) << 1,
                child1N = child2N - 1;
            // This is used to store the new position of the element, if any.
            var swap = null,
                child1Score;
            // If the first child exists (is inside the array)...
            if (child1N < length) {
                // Look it up and compute its score.
                var child1 = this.content[child1N];
                child1Score = this.scoreFunction(child1);

                // If the score is less than our element's, we need to swap.
                if (child1Score < elemScore){
                    swap = child1N;
                }
            }

            // Do the same checks for the other child.
            if (child2N < length) {
                var child2 = this.content[child2N],
                    child2Score = this.scoreFunction(child2);
                if (child2Score < (swap === null ? elemScore : child1Score)) {
                    swap = child2N;
                }
            }

            // If the element needs to be moved, swap it, and continue.
            if (swap !== null) {
                this.content[n] = this.content[swap];
                this.content[swap] = element;
                n = swap;
            }
            // Otherwise, we are done.
            else {
                break;
            }
        }
    }
};

return {
    astar: astar,
    Graph: Graph
};

});
<commit_msg>Remove extra spaces<commit_after>// javascript-astar 0.3.0
// http://github.com/bgrins/javascript-astar
// Freely distributable under the MIT License.
// Implements the astar search algorithm in javascript using a Binary Heap.
// Includes Binary Heap (with modifications) from Marijn Haverbeke.
// http://eloquentjavascript.net/appendix2.html

(function(definition) {
    if(typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = definition();
    } else if(typeof define === 'function' && define.amd) {
        define([], definition);
    } else {
        var exports = definition();
        window.astar = exports.astar;
        window.Graph = exports.Graph;
    }
})(function() {

function pathTo(node){
    var curr = node,
        path = [];
    while(curr.parent) {
        path.push(curr);
        curr = curr.parent;
    }
    return path.reverse();
}

var astar = {
    init: function(graph) {
        for (var i = 0, len = graph.nodes.length; i < len; ++i) {
            var node = graph.nodes[i];
            node.f = 0;
            node.g = 0;
            node.h = 0;
            node.visited = false;
            node.closed = false;
            node.parent = null;
        }
    },
    heap: function() {
        return new BinaryHeap(function(node) {
            return node.f;
        });
    },

    // astar.search
    // supported options:
    // {
    //   heuristic: heuristic function to use
    //   closest: boolean specifying whether to return closest node if
    //            target is unreachable
    // }
    search: function(graph, start, end, options) {
        astar.init(graph);

        options = options || {};
        var heuristic = options.heuristic || astar.heuristics.manhattan,
            closest = options.closest || false;

        var openHeap = astar.heap(),
            closestNode = start; // set the start node to be the closest if required

        start.h = heuristic(start, end);

        openHeap.push(start);

        while(openHeap.size() > 0) {

            // Grab the lowest f(x) to process next.  Heap keeps this sorted for us.
            var currentNode = openHeap.pop();

            // End case -- result has been found, return the traced path.
            if(currentNode === end) {
                return pathTo(currentNode);
            }

            // Normal case -- move currentNode from open to closed, process each of its neighbors.
            currentNode.closed = true;

            // Find all neighbors for the current node.
            var neighbors = graph.neighbors(currentNode);

            for(var i = 0, il = neighbors.length; i < il; ++i) {
                var neighbor = neighbors[i];

                if(neighbor.closed || neighbor.isWall()) {
                    // Not a valid node to process, skip to next neighbor.
                    continue;
                }

                // The g score is the shortest distance from start to current node.
                // We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet.
                var gScore = currentNode.g + neighbor.getCost(currentNode),
                    beenVisited = neighbor.visited;

                if(!beenVisited || gScore < neighbor.g) {

                    // Found an optimal (so far) path to this node.  Take score for node to see how good it is.
                    neighbor.visited = true;
                    neighbor.parent = currentNode;
                    neighbor.h = neighbor.h || heuristic(neighbor, end);
                    neighbor.g = gScore;
                    neighbor.f = neighbor.g + neighbor.h;

                    if (closest) {
                        // If the neighbour is closer than the current closestNode or if it's equally close but has
                        // a cheaper path than the current closest node then it becomes the closest node
                        if (neighbor.h < closestNode.h || (neighbor.h === closestNode.h && neighbor.g < closestNode.g)) {
                            closestNode = neighbor;
                        }
                    }

                    if (!beenVisited) {
                        // Pushing to heap will put it in proper place based on the 'f' value.
                        openHeap.push(neighbor);
                    }
                    else {
                        // Already seen the node, but since it has been rescored we need to reorder it in the heap
                        openHeap.rescoreElement(neighbor);
                    }
                }
            }
        }

        if (closest) {
            return pathTo(closestNode);
        }

        // No result was found - empty array signifies failure to find path.
        return [];
    },
    // See list of heuristics: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
    heuristics: {
        manhattan: function(pos0, pos1) {
            var d1 = Math.abs(pos1.x - pos0.x);
            var d2 = Math.abs(pos1.y - pos0.y);
            return d1 + d2;
        },
        diagonal: function(pos0, pos1) {
            var D = 1;
            var D2 = Math.sqrt(2);
            var d1 = Math.abs(pos1.x - pos0.x);
            var d2 = Math.abs(pos1.y - pos0.y);
            return (D * (d1 + d2)) + ((D2 - (2 * D)) * Math.min(d1, d2));
        }
    }
};

/**
* A graph memory structure
* @param {Array} [gridIn] 2D array of input weights
* @param {bool} options
*               diagonal: Specifies whether diagonal moves are allowed
*/
function Graph(gridIn, options) {
    options = options || {};
    this.nodes = [];
    this.diagonal = !!options.diagonal;
    this.grid = [];
    for (var x = 0; x < gridIn.length; x++) {
        this.grid[x] = [];

        for (var y = 0, row = gridIn[x]; y < row.length; y++) {
            var node = new GridNode(x, y, row[y]);
            this.grid[x][y] = node;
            this.nodes.push(node);
        }
    }
}
Graph.prototype.neighbors = function(node) {
    var ret = [],
        x = node.x,
        y = node.y,
        grid = this.grid;

    // West
    if(grid[x-1] && grid[x-1][y]) {
        ret.push(grid[x-1][y]);
    }

    // East
    if(grid[x+1] && grid[x+1][y]) {
        ret.push(grid[x+1][y]);
    }

    // South
    if(grid[x] && grid[x][y-1]) {
        ret.push(grid[x][y-1]);
    }

    // North
    if(grid[x] && grid[x][y+1]) {
        ret.push(grid[x][y+1]);
    }

    if (this.diagonal) {
        // Southwest
        if(grid[x-1] && grid[x-1][y-1]) {
            ret.push(grid[x-1][y-1]);
        }

        // Southeast
        if(grid[x+1] && grid[x+1][y-1]) {
            ret.push(grid[x+1][y-1]);
        }

        // Northwest
        if(grid[x-1] && grid[x-1][y+1]) {
            ret.push(grid[x-1][y+1]);
        }

        // Northeast
        if(grid[x+1] && grid[x+1][y+1]) {
            ret.push(grid[x+1][y+1]);
        }
    }

    return ret;
};

Graph.prototype.toString = function() {
    var graphString = [],
        nodes = this.grid, // when using grid
        rowDebug, row, y, l;
    for (var x = 0, len = nodes.length; x < len; x++) {
        rowDebug = [];
        row = nodes[x];
        for (y = 0, l = row.length; y < l; y++) {
            rowDebug.push(row[y].weight);
        }
        graphString.push(rowDebug.join(" "));
    }
    return graphString.join("\n");
};

function GridNode(x, y, weight) {
    this.x = x;
    this.y = y;
    this.weight = weight;
}

GridNode.prototype.toString = function() {
    return "[" + this.x + " " + this.y + "]";
};

GridNode.prototype.getCost = function() {
    return this.weight;
};

GridNode.prototype.isWall = function() {
    return this.weight === 0;
};

function BinaryHeap(scoreFunction){
    this.content = [];
    this.scoreFunction = scoreFunction;
}

BinaryHeap.prototype = {
    push: function(element) {
        // Add the new element to the end of the array.
        this.content.push(element);

        // Allow it to sink down.
        this.sinkDown(this.content.length - 1);
    },
    pop: function() {
        // Store the first element so we can return it later.
        var result = this.content[0];
        // Get the element at the end of the array.
        var end = this.content.pop();
        // If there are any elements left, put the end element at the
        // start, and let it bubble up.
        if (this.content.length > 0) {
            this.content[0] = end;
            this.bubbleUp(0);
        }
        return result;
    },
    remove: function(node) {
        var i = this.content.indexOf(node);

        // When it is found, the process seen in 'pop' is repeated
        // to fill up the hole.
        var end = this.content.pop();

        if (i !== this.content.length - 1) {
            this.content[i] = end;

            if (this.scoreFunction(end) < this.scoreFunction(node)) {
                this.sinkDown(i);
            }
            else {
                this.bubbleUp(i);
            }
        }
    },
    size: function() {
        return this.content.length;
    },
    rescoreElement: function(node) {
        this.sinkDown(this.content.indexOf(node));
    },
    sinkDown: function(n) {
        // Fetch the element that has to be sunk.
        var element = this.content[n];

        // When at 0, an element can not sink any further.
        while (n > 0) {

            // Compute the parent element's index, and fetch it.
            var parentN = ((n + 1) >> 1) - 1,
                parent = this.content[parentN];
            // Swap the elements if the parent is greater.
            if (this.scoreFunction(element) < this.scoreFunction(parent)) {
                this.content[parentN] = element;
                this.content[n] = parent;
                // Update 'n' to continue at the new position.
                n = parentN;
            }
            // Found a parent that is less, no need to sink any further.
            else {
                break;
            }
        }
    },
    bubbleUp: function(n) {
        // Look up the target element and its score.
        var length = this.content.length,
            element = this.content[n],
            elemScore = this.scoreFunction(element);

        while(true) {
            // Compute the indices of the child elements.
            var child2N = (n + 1) << 1,
                child1N = child2N - 1;
            // This is used to store the new position of the element, if any.
            var swap = null,
                child1Score;
            // If the first child exists (is inside the array)...
            if (child1N < length) {
                // Look it up and compute its score.
                var child1 = this.content[child1N];
                child1Score = this.scoreFunction(child1);

                // If the score is less than our element's, we need to swap.
                if (child1Score < elemScore){
                    swap = child1N;
                }
            }

            // Do the same checks for the other child.
            if (child2N < length) {
                var child2 = this.content[child2N],
                    child2Score = this.scoreFunction(child2);
                if (child2Score < (swap === null ? elemScore : child1Score)) {
                    swap = child2N;
                }
            }

            // If the element needs to be moved, swap it, and continue.
            if (swap !== null) {
                this.content[n] = this.content[swap];
                this.content[swap] = element;
                n = swap;
            }
            // Otherwise, we are done.
            else {
                break;
            }
        }
    }
};

return {
    astar: astar,
    Graph: Graph
};

});
<|endoftext|>


<commit_before>//////////////////////////////////

//////   官方通用辅助代码 ////////

///////////////////////////////////

var RTCPeerConnection = null;
var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
var webrtcDetectedVersion = null;

function trace(text) {
    // This function is used for logging.
    if (text[text.length - 1] == '\n') {
        text = text.substring(0, text.length - 1);
    }
    console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

if (navigator.mozGetUserMedia) {
    console.log("这应该是 Firefox 浏览器");

    webrtcDetectedBrowser = "firefox";

    webrtcDetectedVersion =
             parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);

    // The RTCPeerConnection object.
    RTCPeerConnection = mozRTCPeerConnection;

    // The RTCSessionDescription object.
    RTCSessionDescription = mozRTCSessionDescription;

    // The RTCIceCandidate object.
    RTCIceCandidate = mozRTCIceCandidate;

    // Get UserMedia (only difference is the prefix).
    // Code from Adam Barth.
    getUserMedia = navigator.mozGetUserMedia.bind(navigator);

    // Creates iceServer from the url for FF.
    createIceServer = function (url, username, password) {
        var iceServer = null;
        var url_parts = url.split(':');
        if (url_parts[0].indexOf('stun') === 0) {
            // Create iceServer with stun url.
            iceServer = { 'url': url };
        } else if (url_parts[0].indexOf('turn') === 0) {
            if (webrtcDetectedVersion < 27) {
                // Create iceServer with turn url.
                // Ignore the transport parameter from TURN url for FF version <=27.
                var turn_url_parts = url.split("?");
                // Return null for createIceServer if transport=tcp.
                if (turn_url_parts[1].indexOf('transport=udp') === 0) {
                    iceServer = {
                        'url': turn_url_parts[0],
                        'credential': password,
                        'username': username
                    };
                }
            } else {
                // FF 27 and above supports transport parameters in TURN url,
                // So passing in the full url to create iceServer.
                iceServer = {
                    'url': url,
                    'credential': password,
                    'username': username
                };
            }
        }
        return iceServer;
    };

    // Attach a media stream to an element.
    attachMediaStream = function (element, stream) {
        console.log("Attaching media stream");
        element.mozSrcObject = stream;
        element.play();
    };

    reattachMediaStream = function (to, from) {
        console.log("Reattaching media stream");
        to.mozSrcObject = from.mozSrcObject;
        to.play();
    };

    // Fake get{Video,Audio}Tracks
    if (!MediaStream.prototype.getVideoTracks) {
        MediaStream.prototype.getVideoTracks = function () {
            return [];
        };
    }

    if (!MediaStream.prototype.getAudioTracks) {
        MediaStream.prototype.getAudioTracks = function () {
            return [];
        };
    }
} else if (navigator.webkitGetUserMedia) {
    console.log("这应该是 Chrome 浏览器");

    webrtcDetectedBrowser = "chrome";
    webrtcDetectedVersion =
           parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);

    // Creates iceServer from the url for Chrome.
    createIceServer = function (url, username, password) {
        var iceServer = null;
        var url_parts = url.split(':');
        if (url_parts[0].indexOf('stun') === 0) {
            // Create iceServer with stun url.
            iceServer = { 'url': url };
        } else if (url_parts[0].indexOf('turn') === 0) {
            // Chrome M28 & above uses below TURN format.
            iceServer = {
                'url': url,
                'credential': password,
                'username': username
            };
        }
        return iceServer;
    };

    // The RTCPeerConnection object.
    RTCPeerConnection = webkitRTCPeerConnection;

    // Get UserMedia (only difference is the prefix).
    // Code from Adam Barth.
    getUserMedia = navigator.webkitGetUserMedia.bind(navigator);

    // Attach a media stream to an element.
    attachMediaStream = function (element, stream) {
        if (typeof element.srcObject !== 'undefined') {
            element.srcObject = stream;
        } else if (typeof element.mozSrcObject !== 'undefined') {
            element.mozSrcObject = stream;
        } else if (typeof element.src !== 'undefined') {
            element.src = URL.createObjectURL(stream);
        } else {
            console.log('Error attaching stream to element.');
        }
    };

    reattachMediaStream = function (to, from) {
        to.src = from.src;
    };
} else {
    console.log("Browser does not appear to be WebRTC-capable");
}
<commit_msg>Google 官方通用辅助代码<commit_after>//////////////////////////////////
//////   官方通用辅助代码 ////////
///////////////////////////////////

var RTCPeerConnection = null;
var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
var webrtcDetectedVersion = null;

function trace(text) {
    // This function is used for logging.
    if (text[text.length - 1] == '\n') {
        text = text.substring(0, text.length - 1);
    }
    console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

if (navigator.mozGetUserMedia) {
    console.log("这应该是 Firefox 浏览器");

    webrtcDetectedBrowser = "firefox";

    webrtcDetectedVersion =
             parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);

    // The RTCPeerConnection object.
    RTCPeerConnection = mozRTCPeerConnection;

    // The RTCSessionDescription object.
    RTCSessionDescription = mozRTCSessionDescription;

    // The RTCIceCandidate object.
    RTCIceCandidate = mozRTCIceCandidate;

    // Get UserMedia (only difference is the prefix).
    // Code from Adam Barth.
    getUserMedia = navigator.mozGetUserMedia.bind(navigator);

    // Creates iceServer from the url for FF.
    createIceServer = function (url, username, password) {
        var iceServer = null;
        var url_parts = url.split(':');
        if (url_parts[0].indexOf('stun') === 0) {
            // Create iceServer with stun url.
            iceServer = { 'url': url };
        } else if (url_parts[0].indexOf('turn') === 0) {
            if (webrtcDetectedVersion < 27) {
                // Create iceServer with turn url.
                // Ignore the transport parameter from TURN url for FF version <=27.
                var turn_url_parts = url.split("?");
                // Return null for createIceServer if transport=tcp.
                if (turn_url_parts[1].indexOf('transport=udp') === 0) {
                    iceServer = {
                        'url': turn_url_parts[0],
                        'credential': password,
                        'username': username
                    };
                }
            } else {
                // FF 27 and above supports transport parameters in TURN url,
                // So passing in the full url to create iceServer.
                iceServer = {
                    'url': url,
                    'credential': password,
                    'username': username
                };
            }
        }
        return iceServer;
    };

    // Attach a media stream to an element.
    attachMediaStream = function (element, stream) {
        console.log("Attaching media stream");
        element.mozSrcObject = stream;
        element.play();
    };

    reattachMediaStream = function (to, from) {
        console.log("Reattaching media stream");
        to.mozSrcObject = from.mozSrcObject;
        to.play();
    };

    // Fake get{Video,Audio}Tracks
    if (!MediaStream.prototype.getVideoTracks) {
        MediaStream.prototype.getVideoTracks = function () {
            return [];
        };
    }

    if (!MediaStream.prototype.getAudioTracks) {
        MediaStream.prototype.getAudioTracks = function () {
            return [];
        };
    }
} else if (navigator.webkitGetUserMedia) {
    console.log("这应该是 Chrome 浏览器");

    webrtcDetectedBrowser = "chrome";
    webrtcDetectedVersion =
           parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);

    // Creates iceServer from the url for Chrome.
    createIceServer = function (url, username, password) {
        var iceServer = null;
        var url_parts = url.split(':');
        if (url_parts[0].indexOf('stun') === 0) {
            // Create iceServer with stun url.
            iceServer = { 'url': url };
        } else if (url_parts[0].indexOf('turn') === 0) {
            // Chrome M28 & above uses below TURN format.
            iceServer = {
                'url': url,
                'credential': password,
                'username': username
            };
        }
        return iceServer;
    };

    // The RTCPeerConnection object.
    RTCPeerConnection = webkitRTCPeerConnection;

    // Get UserMedia (only difference is the prefix).
    // Code from Adam Barth.
    getUserMedia = navigator.webkitGetUserMedia.bind(navigator);

    // Attach a media stream to an element.
    attachMediaStream = function (element, stream) {
        if (typeof element.srcObject !== 'undefined') {
            element.srcObject = stream;
        } else if (typeof element.mozSrcObject !== 'undefined') {
            element.mozSrcObject = stream;
        } else if (typeof element.src !== 'undefined') {
            element.src = URL.createObjectURL(stream);
        } else {
            console.log('Error attaching stream to element.');
        }
    };

    reattachMediaStream = function (to, from) {
        to.src = from.src;
    };
} else {
    console.log("Browser does not appear to be WebRTC-capable");
}
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter
var addpre = require('./range').addPrefix

var errors = require('levelup/lib/errors')

function isFunction (f) {
  return 'function' === typeof f
}

function isString (s) {
  return 'string' === typeof s
}

function isObject (o) {
  return o && 'object' === typeof o
}

var version = require('./package.json').version

var sublevel = module.exports = function (nut, prefix, createStream, options) {
  var emitter = new EventEmitter()
  emitter.sublevels = {}

  emitter.version = version

  emitter.methods = {}
  prefix = prefix || []

  function errback (err) { if (err) emitter.emit('error', error)}

  createStream = createStream || function (e) { return e }

  function mergeOpts(opts) {
    var o = {}
    if(options)
      for(var k in options)
        if(options[k] != undefined)o[k] = options[k]
    if(opts)
      for(var k in opts)
        if(opts[k] != undefined) o[k] = opts[k]
    return o
  }

  emitter.put = function (key, value, opts, cb) {
    if('function' === typeof opts) cb = opts, opts = {}
    if(!cb) cb = errback

    nut.apply([{
      key: key, value: value,
      prefix: prefix.slice(), type: 'put'
    }], mergeOpts(opts), function (err) {
      if(!err) { emitter.emit('put', key, value); cb(null) }
      if(err) return cb(err)
    })
  }

  emitter.prefix = function () {
    return prefix.slice()
  }

  emitter.del = function (key, opts, cb) {
    if('function' === typeof opts) cb = opts, opts = {}
    if(!cb) cb = errback

    nut.apply([{
      key: key,
      prefix: prefix.slice(), type: 'del'
    }], mergeOpts(opts), function (err) {
      if(!err) { emitter.emit('del', key); cb(null) }
      if(err) return cb(err)
    })
  }

  emitter.batch = function (ops, opts, cb) {
    if('function' === typeof opts)
      cb = opts, opts = {}
    if(!cb) cb = errback

    ops = ops.map(function (op) {
      return {
        key:           op.key,
        value:         op.value,
        prefix:        op.prefix || prefix,
        keyEncoding:   op.keyEncoding,    // *
        valueEncoding: op.valueEncoding,  // * (TODO: encodings on sublevel)
      }
    })

    nut.apply(ops, mergeOpts(opts), function (err) {
      if(!err) { emitter.emit('batch', ops); cb(null) }
      if(err) return cb(err)
    })
  }

  emitter.get = function (key, opts, cb) {
    if('function' === typeof opts)
      cb = opts, opts = {}
    nut.get(key, prefix, mergeOpts(opts), function (err, value) {
      if(err) cb(new errors.NotFoundError('Key not found in database', err))
      else cb(null, value)
    })
  }

  emitter.sublevel = function (name, opts) {
    return emitter.sublevels[name] =
      emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts))
  }

  emitter.pre = function (key, hook) {
    if(isFunction(key)) return nut.pre([prefix], key)
    if(isString(key)) return nut.pre([prefix, key], hook)
    if(isObject(key)) return nut.pre(addpre(prefix, key), hook)

    throw new Error('not implemented yet')
  }

  emitter.post = function (key, hook) {
    if(isFunction(key)) return nut.post([prefix], key)
    if(isString(key))   return nut.post([prefix, key], hook)
    if(isObject(key))   return nut.post(addpre(prefix, key), hook)

    //TODO: handle ranges, needed for level-live-stream, etc.
    throw new Error('not implemented yet')
  }

  emitter.createReadStream = function (opts) {
    opts = mergeOpts(opts)
    opts.prefix = prefix
    var stream
    var it = nut.iterator(opts, function (err, it) {
      stream.setIterator(it)
    })

    stream = createStream(opts, nut.createDecoder(opts))
    if(it) stream.setIterator(it)

    return stream
  }

  emitter.createValueStream = function (opts) {
    opts = opts || {}
    opts.values = true
    opts.keys = false
    return emitter.createReadStream(opts)
  }

  emitter.createKeyStream = function (opts) {
    opts = opts || {}
    opts.values = false
    opts.keys = true
    return emitter.createReadStream(opts)
  }

  emitter.close = function (cb) {
    //TODO: deregister all hooks
    process.nextTick(cb || function () {})
  }

  return emitter
}
<commit_msg>s/error/err<commit_after>var EventEmitter = require('events').EventEmitter
var addpre = require('./range').addPrefix

var errors = require('levelup/lib/errors')

function isFunction (f) {
  return 'function' === typeof f
}

function isString (s) {
  return 'string' === typeof s
}

function isObject (o) {
  return o && 'object' === typeof o
}

var version = require('./package.json').version

var sublevel = module.exports = function (nut, prefix, createStream, options) {
  var emitter = new EventEmitter()
  emitter.sublevels = {}

  emitter.version = version

  emitter.methods = {}
  prefix = prefix || []

  function errback (err) { if (err) emitter.emit('error', err) }

  createStream = createStream || function (e) { return e }

  function mergeOpts(opts) {
    var o = {}
    if(options)
      for(var k in options)
        if(options[k] != undefined)o[k] = options[k]
    if(opts)
      for(var k in opts)
        if(opts[k] != undefined) o[k] = opts[k]
    return o
  }

  emitter.put = function (key, value, opts, cb) {
    if('function' === typeof opts) cb = opts, opts = {}
    if(!cb) cb = errback

    nut.apply([{
      key: key, value: value,
      prefix: prefix.slice(), type: 'put'
    }], mergeOpts(opts), function (err) {
      if(!err) { emitter.emit('put', key, value); cb(null) }
      if(err) return cb(err)
    })
  }

  emitter.prefix = function () {
    return prefix.slice()
  }

  emitter.del = function (key, opts, cb) {
    if('function' === typeof opts) cb = opts, opts = {}
    if(!cb) cb = errback

    nut.apply([{
      key: key,
      prefix: prefix.slice(), type: 'del'
    }], mergeOpts(opts), function (err) {
      if(!err) { emitter.emit('del', key); cb(null) }
      if(err) return cb(err)
    })
  }

  emitter.batch = function (ops, opts, cb) {
    if('function' === typeof opts)
      cb = opts, opts = {}
    if(!cb) cb = errback

    ops = ops.map(function (op) {
      return {
        key:           op.key,
        value:         op.value,
        prefix:        op.prefix || prefix,
        keyEncoding:   op.keyEncoding,    // *
        valueEncoding: op.valueEncoding,  // * (TODO: encodings on sublevel)
      }
    })

    nut.apply(ops, mergeOpts(opts), function (err) {
      if(!err) { emitter.emit('batch', ops); cb(null) }
      if(err) return cb(err)
    })
  }

  emitter.get = function (key, opts, cb) {
    if('function' === typeof opts)
      cb = opts, opts = {}
    nut.get(key, prefix, mergeOpts(opts), function (err, value) {
      if(err) cb(new errors.NotFoundError('Key not found in database', err))
      else cb(null, value)
    })
  }

  emitter.sublevel = function (name, opts) {
    return emitter.sublevels[name] =
      emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts))
  }

  emitter.pre = function (key, hook) {
    if(isFunction(key)) return nut.pre([prefix], key)
    if(isString(key)) return nut.pre([prefix, key], hook)
    if(isObject(key)) return nut.pre(addpre(prefix, key), hook)

    throw new Error('not implemented yet')
  }

  emitter.post = function (key, hook) {
    if(isFunction(key)) return nut.post([prefix], key)
    if(isString(key))   return nut.post([prefix, key], hook)
    if(isObject(key))   return nut.post(addpre(prefix, key), hook)

    //TODO: handle ranges, needed for level-live-stream, etc.
    throw new Error('not implemented yet')
  }

  emitter.createReadStream = function (opts) {
    opts = mergeOpts(opts)
    opts.prefix = prefix
    var stream
    var it = nut.iterator(opts, function (err, it) {
      stream.setIterator(it)
    })

    stream = createStream(opts, nut.createDecoder(opts))
    if(it) stream.setIterator(it)

    return stream
  }

  emitter.createValueStream = function (opts) {
    opts = opts || {}
    opts.values = true
    opts.keys = false
    return emitter.createReadStream(opts)
  }

  emitter.createKeyStream = function (opts) {
    opts = opts || {}
    opts.values = false
    opts.keys = true
    return emitter.createReadStream(opts)
  }

  emitter.close = function (cb) {
    //TODO: deregister all hooks
    process.nextTick(cb || function () {})
  }

  return emitter
}
<|endoftext|>


<commit_before>/*
 *  © Chris How, Primesolid 2011
 *  All rights reserved.
 */

var $body, $input, $output, history = [], historyPosition = 0, currentLine, cwd, prompt = '$ ' ;

$(document).ready(function(){
    $body = $('body');
    $input = $('#input');
    $output = $('#output');

    $input.focus();
    $input.val(prompt);

    $input.on('keydown', function(e) {
        return handleKey(e);
    }).on('blur', function() {
        });

    $('html').on('click', function() {
        $input.focus();
    });
    $body.on('click', function(e) {
        e.stopPropagation();
    });

    $.ajaxPrefilter(function( options, _, jqXHR ) {
        if ( options.onreadystatechange ) {
            var xhrFactory = options.xhr;
            options.xhr = function() {
                var xhr = xhrFactory.apply( this, arguments );
                xhr.outputCount = 0;
                function handler() {
                    options.onreadystatechange( xhr, jqXHR );
                }
                if ( xhr.addEventListener ) {
                    xhr.addEventListener( "readystatechange", handler, false );
                } else {
                    setTimeout( function() {
                        var internal = xhr.onreadystatechange;
                        if ( internal ) {
                            xhr.onreadystatechange = function() {
                                handler();
                                internal.apply( this, arguments );
                            };
                        }
                    }, 0 );
                }
                return xhr;
            };
        }
    });

});

function handleKey(e) {
    log(e);
    if(e.keyCode === 13) {
        processLine();
        return false;
    } else if (e.keyCode == 38) { // up
        if(historyPosition == 0) {
            currentLine = $input.val();
        }
        if(historyPosition < history.length) {
            historyPosition += 1;
            $input.val(history[history.length - historyPosition]);
        }
        return false;
    } else if (e.keyCode == 40) { // down
        if(historyPosition > 1) {
            historyPosition -= 1;
            $input.val(history[history.length - historyPosition]);
        } else if (historyPosition == 1) {
            historyPosition -= 1;
            $input.val(currentLine);
        }
        return false;
    } else if (e.keyCode == 9) { // tab
        autoComplete();
        return false;
    } else if (e.keyCode == 8) { // delete
        if($input.val().length <= prompt.length) {
            return false;
        }
    } else if (e.keyCode == 67 && e.ctrlKey) { // ctrl-c
        write($input.val());
        $input.val(prompt);
    } else if (e.keyCode == 76 && e.ctrlKey) { // ctrl-l
        $output.html('');
    }

    return true;
}

function autoComplete() {
    var type;
    var originalInput = $input.val();
    var curInput = originalInput.substr(3).replace(/^\s+/,'');
    var stem = originalInput.substr(0, $input[0].selectionStart);
    if(curInput.indexOf(' ') == -1) {
        // complete command
        stem = stem.substr(stem.lastIndexOf(' ')+1);
        type = 'command'
    } else {
        // complete filename
        stem = stem.substr(stem.lastIndexOf(' ')+1);
        type = 'file'
    }
    log('stem: ' + stem);
    $.ajax({
        url: 'slave.php',
        data: {
            action: 'complete',
            type: type,
            stem: stem,
            nonce: NONCE
        },
        success: function(data) {
            handleAutocompleteResults(data, originalInput, curInput, stem);
        }
    });

}

function handleAutocompleteResults(data, originalInput, curInput, stem) {
    log(data);
    var i, len, j, currentMatch, datum, matchedAtLeastOneChar = false;
    if(data.length) {
        if(data.length == 1) {
            $input.val(originalInput.substr(0, $input[0].selectionStart - stem.length) + data[0] + originalInput.substr($input[0].selectionStart, originalInput.length));
        // TODO
        // set caret position
        } else {
            // mulitple possibilites.
            //            log(data);
            for(i = 0, len = data.length; i < len; i += 1) {
                datum = data[i];
                if(currentMatch) {
                    for(j = 0; j < currentMatch.length; j += 1) {
                        if(currentMatch.charAt(j) != datum.charAt(j)) {
                            currentMatch = currentMatch.substr(0, j);
                            break;
                        } else if(j > 1) {
                            matchedAtLeastOneChar = true;
                        }
                    }
                } else {
                    currentMatch = datum;
                }
            }
            if(matchedAtLeastOneChar) {
                $input.val(originalInput.substr(0, $input[0].selectionStart - stem.length) + currentMatch + originalInput.substr($input[0].selectionStart, originalInput.length));
            }
            write($input.val() + "\n");
            write(data.join(' ') + "\n");
            flash();
        }
    } else {
        flash();
    }

}

function logout() {
    window.location = '?action=logout';
}

function flash() {
    $('html').addClass('inverse');
    setTimeout(function() {
        $('html').removeClass('inverse');
    }, 50);
}

function processLine() {
    var originalLine = $input.val();
    var line = originalLine;
    write(originalLine + "\n");

    if(line.indexOf(prompt) == 0) {
        line = line.substr(prompt.length);
    }

    if (line) {
        history.push(originalLine);
        if(line == 'clear') {
            $output.html('');
        } else if (line == 'logout') {
            logout();
            return;
//        } else if (line.indexOf('vi ') == 0) {
//            openEditor(line.substr(('vi ').length));
//            return;
        }
        $input.hide();
        $.ajax({
            url : 'slave.php',
            data: {
                cmd: line,
                nonce: NONCE
            },
            success: function(data) {
                $input.show();
                $input[0].selectionStart = $input.val().length;
                $body.scrollTop($body.height());
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert('Error: ' + textStatus);
                $input.show();
                $input[0].selectionStart = $input.val().length;
                $body.scrollTop($body.height());
            },
            onreadystatechange : function(myXhr, jqXhr){
                var chunk, len;
                if(myXhr.readyState === 3 || myXhr.readyState === 4) {
                    chunk = myXhr.responseText.substr(myXhr.outputCount);
                    len = chunk.length;
                    write(chunk);
                    myXhr.outputCount += len;
                }
            }
        });

    }

    $input.val(prompt);
}

function write(line) {
    var newEl = $('').text(line);
    $output.append(newEl);
    $body.scrollTop($body.height());
}

function log(what) {
    console.log(what);
}

function openEditor(file) {
    var editor = new Editor(file);
}

function Editor(file) {
    var $editor = $('#editor');
    $editor.fadeIn('fast');

    //    alert(file);
    var $links = $("
[ Cancel ]   [ Save ]
");
    $editor.find('#editor_links').append($links);
    $('#editor_cancel').bind('click', function(){
        $editor.fadeOut('fast');
    });
}<commit_msg>Fixes suggested by jslint<commit_after>/*
 *  © Chris How, Primesolid 2011
 *  All rights reserved.
 */

/* JSLint setup */
/*global $, JSTarget, alert, History, console, NONCE */
/* browser white */

(function() {
    "use strict";
    var $body, $input, $output, history = [], historyPosition = 0, currentLine, cwd, prompt = '$ ' ;

    function write(line) {
        var newEl = $('').text(line);
        $output.append(newEl);
        $body.scrollTop($body.height());
    }

    function flash() {
        $('html').addClass('inverse');
        setTimeout(function() {
            $('html').removeClass('inverse');
        }, 50);
    }

    function handleAutocompleteResults(data, originalInput, curInput, stem) {
        console.log(data);
        var i, len, j, currentMatch, datum, matchedAtLeastOneChar = false, caretPosition;
        if(data.length) {
            if(data.length === 1) {
                caretPosition = (originalInput.substr(0, $input[0].selectionStart - stem.length) + data[0]).length;
                $input.val(originalInput.substr(0, $input[0].selectionStart - stem.length) + data[0] + originalInput.substr($input[0].selectionStart, originalInput.length));
                // set caret position
                $input[0].selectionStart = $input[0].selectionEnd = caretPosition;

            } else {
                // mulitple possibilites.
                for(i = 0, len = data.length; i < len; i += 1) {
                    datum = data[i];
                    if(currentMatch) {
                        for(j = 0; j < currentMatch.length; j += 1) {
                            if(currentMatch.charAt(j) !== datum.charAt(j)) {
                                currentMatch = currentMatch.substr(0, j);
                                break;
                            } else if(j > 1) {
                                matchedAtLeastOneChar = true;
                            }
                        }
                    } else {
                        currentMatch = datum;
                    }
                }
                if(matchedAtLeastOneChar) {
                    $input.val(originalInput.substr(0, $input[0].selectionStart - stem.length) + currentMatch + originalInput.substr($input[0].selectionStart, originalInput.length));
                }
                write($input.val() + "\n");
                write(data.join(' ') + "\n");
                flash();
            }
        } else {
            flash();
        }

    }

    function autoComplete() {
        var type;
        var originalInput = $input.val();
        var curInput = originalInput.substr(3).replace(/^\s+/,'');
        var stem = originalInput.substr(0, $input[0].selectionStart);
        if(curInput.indexOf(' ') === -1) {
            // complete command
            stem = stem.substr(stem.lastIndexOf(' ')+1);
            type = 'command';
        } else {
            // complete filename
            stem = stem.substr(stem.lastIndexOf(' ')+1);
            type = 'file';
        }
        console.log('stem: ' + stem);
        $.ajax({
            url: 'slave.php',
            data: {
                action: 'complete',
                type: type,
                stem: stem,
                nonce: NONCE
            },
            success: function(data) {
                handleAutocompleteResults(data, originalInput, curInput, stem);
            }
        });

    }

    function logout() {
        window.location = '?action=logout';
    }

    function processLine() {
        var originalLine = $input.val();
        var line = originalLine;
        write(originalLine + "\n");

        if(line.indexOf(prompt) === 0) {
            line = line.substr(prompt.length);
        }

        if (line) {
            history.push(originalLine);
            if(line === 'clear') {
                $output.html('');
            } else if (line === 'logout') {
                logout();
                return;
            //        } else if (line.indexOf('vi ') == 0) {
            //            openEditor(line.substr(('vi ').length));
            //            return;
            }
            $input.hide();
            $.ajax({
                url : 'slave.php',
                data: {
                    cmd: line,
                    nonce: NONCE
                },
                success: function(data) {
                    $input.show();
                    $input[0].selectionStart = $input.val().length;
                    $body.scrollTop($body.height());
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert('Error: ' + textStatus);
                    $input.show();
                    $input[0].selectionStart = $input.val().length;
                    $body.scrollTop($body.height());
                },
                onreadystatechange : function(myXhr, jqXhr){
                    var chunk, len;
                    if(myXhr.readyState === 3 || myXhr.readyState === 4) {
                        chunk = myXhr.responseText.substr(myXhr.outputCount);
                        len = chunk.length;
                        write(chunk);
                        myXhr.outputCount += len;
                    }
                }
            });

        }

        $input.val(prompt);
    }

    function handleKey(e) {
        if(e.keyCode === 13) {
            processLine();
            return false;
        } else if (e.keyCode === 38) { // up
            if(historyPosition === 0) {
                currentLine = $input.val();
            }
            if(historyPosition < history.length) {
                historyPosition += 1;
                $input.val(history[history.length - historyPosition]);
            }
            return false;
        } else if (e.keyCode === 40) { // down
            if(historyPosition > 1) {
                historyPosition -= 1;
                $input.val(history[history.length - historyPosition]);
            } else if (historyPosition === 1) {
                historyPosition -= 1;
                $input.val(currentLine);
            }
            return false;
        } else if (e.keyCode === 9) { // tab
            autoComplete();
            return false;
        } else if (e.keyCode === 8) { // delete
            if($input.val().length <= prompt.length) {
                return false;
            }
        } else if (e.keyCode === 67 && e.ctrlKey) { // ctrl-c
            write($input.val());
            $input.val(prompt);
        } else if (e.keyCode === 76 && e.ctrlKey) { // ctrl-l
            $output.html('');
        }

        return true;
    }

    function Editor(file) {
        var $editor = $('#editor');
        $editor.fadeIn('fast');

        //    alert(file);
        var $links = $("
[ Cancel ]   [ Save ]
");
        $editor.find('#editor_links').append($links);
        $('#editor_cancel').bind('click', function(){
            $editor.fadeOut('fast');
        });
    }

    function openEditor(file) {
        var editor = new Editor(file);
    }

    // and off we go...
    $(document).ready(function(){
        $body = $('body');
        $input = $('#input');
        $output = $('#output');

        $input.focus();
        $input.val(prompt);

        $input.on('keydown', function(e) {
            return handleKey(e);
        }).on('blur', function() {
            });

        $('html').on('click', function() {
            $input.focus();
        });
        $body.on('click', function(e) {
            e.stopPropagation();
        });

        $.ajaxPrefilter(function( options, junk, jqXHR ) {
            if ( options.onreadystatechange ) {
                var xhrFactory = options.xhr;
                options.xhr = function() {
                    var xhr = xhrFactory.apply( this, arguments );
                    xhr.outputCount = 0;
                    function handler() {
                        options.onreadystatechange( xhr, jqXHR );
                    }
                    if ( xhr.addEventListener ) {
                        xhr.addEventListener( "readystatechange", handler, false );
                    } else {
                        setTimeout( function() {
                            var internal = xhr.onreadystatechange;
                            if ( internal ) {
                                xhr.onreadystatechange = function() {
                                    handler();
                                    internal.apply( this, arguments );
                                };
                            }
                        }, 0 );
                    }
                    return xhr;
                };
            }
        });

    });

}());<|endoftext|>


<commit_before>function Player() {
  this.x = Math.random() * width | 0;
  this.y = Math.random() * height| 0;

  // Image h/w
  this.h = this.w = 48;

  this.dx = 0;
  this.dy = 0;

  this.turnSpeed = 0.001;
  this.thrust = 0.1;
  this.angle = 0;
  this.exploded = false;

  this.img = new Image();
  this.img.src = 'http://retroships.com/generate.png?&size=4&cB=300&seed=' + name;
}

inherits(Player, CanvasItem);

Player.prototype.update = function () {
  if (keys[32]) {
    if (thisPlayer.exploded) {
      thisPlayer.reset();
    } else {
      thisPlayer.fire();
    }
  }
  if (keys[90]) {
    thisPlayer.explode();
  }
  // Turns
  if (keys[39]) {
    this.angle += this.turnSpeed * -1;
  }

  if (keys[37]) {
    this.angle += this.turnSpeed * 1;
  }

  // Math stuff to determine direction
  var radians = this.angle / Math.PI * 180;

  // Adjust speeds for player input
  if (keys[38]) {
    this.dx -= Math.sin(radians) * this.thrust;
    this.dy -= Math.cos(radians) * this.thrust;
  }
  if (keys[40]) {
    this.dx += Math.sin(radians) * this.thrust;
    this.dy += Math.cos(radians) * this.thrust;
  }
  // Actually make changes
  this.x += this.dx;
  this.y += this.dy;

  // Check for wraparound
  if (this.x < 0) {
    this.x = width;
  } else if (this.x > width) {
    this.x = 0;
  }
  if (this.y < 0) {
    this.y = height;
  } else if (this.y > height) {
    this.y = 0;
  }

  // There's totally friction in space.
  this.dx *= 0.98;
  this.dy *= 0.98;
};
Player.prototype.destroyed = function () {
  return this.exploded;
};
Player.prototype.explode = function () {
  if (!this.exploded) {
    this.exploded = true;
    socket.emit('exploded', {name: name});
    boom(this.x, this.y, this.dx, this.dy);
  }
};
Player.prototype.fire = function () {
  var radians = (this.angle + 0.055) * (180/Math.PI);

  var xx = this.x + (this.w/2 * Math.cos(-(this.angle + 0.0275) * (180/Math.PI)));
  var yy = this.y + (this.w/2 * Math.sin(-(this.angle + 0.0275) * (180/Math.PI)));

  var r = this.w/2;
  playerBullets.create({
    x: xx,
    y: yy,
    dx: Math.sin(radians) * 10,
    dy: Math.cos(radians) * 10,
    c: 'rgba(0,24,234,1)',
    r: 7,
    decay: 0.04
  });
}

function FBPlayer (params) {
  this.x = params.x;
  this.y = params.y;
  this.angle = params.angle;

  this.name = params.name;

  this.h = 55;
  this.w = 50;

  this.connected = true;
  this.exploded = false;

  this.img = new Image();
  this.img.src = 'http://retroships.com/generate.png?&size=4&seed=' + this.name;

  this.lastUpdated = new Date();
};

inherits(FBPlayer, CanvasItem);

FBPlayer.prototype.update = function () {
  if (playerBullets.colliding(this.x, this.y)) {
    socket.emit('exploded', {name: this.name});
  }
  if (this.firing && !this.exploded) {
    this.fire();
  }
};
FBPlayer.prototype.destroyed = function () {
  return !this.connected
};

FBPlayer.prototype.render = Player.prototype.render = function () {
  if (this.exploded) { return; }
  context.save();
  context.translate(this.x, this.y);
  context.rotate(-(this.angle + 0.055) * (180/Math.PI));
  context.drawImage(this.img, -this.w/2, -this.h/2);
  context.restore();
};
FBPlayer.prototype.reset = Player.prototype.reset = function (params) {
  if (!this.exploded) { return; }
  // Crummy workaround
  if (!params) {
    // We're a player
    socket.emit('reset', {name: name});
  }
  this.constructor(params);
};
FBPlayer.prototype.fire = function () {
  var radians = (this.angle + 0.055) * (180/Math.PI);

  var xx = this.x + (this.w/2 * Math.cos(-(this.angle + 0.0275) * (180/Math.PI)));
  var yy = this.y + (this.w/2 * Math.sin(-(this.angle + 0.0275) * (180/Math.PI)));

  var r = this.w/2;
  particles.create({
    x: xx,
    y: yy,
    dx: Math.sin(radians) * 10,
    dy: Math.cos(radians) * 10,
    c: 'rgba(287,3,24,1)',
    r: 7,
    decay: 0.04
  });
};<commit_msg>shrunk the game a bit<commit_after>function Player() {
  this.x = Math.random() * width | 0;
  this.y = Math.random() * height| 0;

  // Image h/w
  this.h = this.w = 36;

  this.dx = 0;
  this.dy = 0;

  this.turnSpeed = 0.001;
  this.thrust = 0.1;
  this.angle = 0;
  this.exploded = false;

  this.img = new Image();
  this.img.src = 'http://retroships.com/generate.png?&size=3&cB=300&seed=' + name;
}

inherits(Player, CanvasItem);

Player.prototype.update = function () {
  if (keys[32]) {
    if (thisPlayer.exploded) {
      thisPlayer.reset();
    } else {
      thisPlayer.fire();
    }
  }
  if (keys[90]) {
    thisPlayer.explode();
  }
  // Turns
  if (keys[39]) {
    this.angle += this.turnSpeed * -1;
  }

  if (keys[37]) {
    this.angle += this.turnSpeed * 1;
  }

  // Math stuff to determine direction
  var radians = this.angle / Math.PI * 180;

  // Adjust speeds for player input
  if (keys[38]) {
    this.dx -= Math.sin(radians) * this.thrust;
    this.dy -= Math.cos(radians) * this.thrust;
  }
  if (keys[40]) {
    this.dx += Math.sin(radians) * this.thrust;
    this.dy += Math.cos(radians) * this.thrust;
  }
  // Actually make changes
  this.x += this.dx;
  this.y += this.dy;

  // Check for wraparound
  if (this.x < 0) {
    this.x = width;
  } else if (this.x > width) {
    this.x = 0;
  }
  if (this.y < 0) {
    this.y = height;
  } else if (this.y > height) {
    this.y = 0;
  }

  // There's totally friction in space.
  this.dx *= 0.98;
  this.dy *= 0.98;
};
Player.prototype.destroyed = function () {
  return this.exploded;
};
Player.prototype.explode = function () {
  if (!this.exploded) {
    this.exploded = true;
    socket.emit('exploded', {name: name});
    boom(this.x, this.y, this.dx, this.dy);
  }
};
Player.prototype.fire = function () {
  var radians = (this.angle + 0.055) * (180/Math.PI);

  var xx = this.x + (this.w/2 * Math.cos(-(this.angle + 0.0275) * (180/Math.PI)));
  var yy = this.y + (this.w/2 * Math.sin(-(this.angle + 0.0275) * (180/Math.PI)));

  var r = this.w/2;
  playerBullets.create({
    x: xx,
    y: yy,
    dx: Math.sin(radians) * 10,
    dy: Math.cos(radians) * 10,
    c: 'rgba(0,24,234,1)',
    r: 7,
    decay: 0.06
  });
}

function FBPlayer (params) {
  this.x = params.x;
  this.y = params.y;
  this.angle = params.angle;

  this.name = params.name;

  this.h = this.w = 36;

  this.connected = true;
  this.exploded = false;

  this.img = new Image();
  this.img.src = 'http://retroships.com/generate.png?&size=3&seed=' + this.name;

  this.lastUpdated = new Date();
};

inherits(FBPlayer, CanvasItem);

FBPlayer.prototype.update = function () {
  if (playerBullets.colliding(this.x, this.y)) {
    socket.emit('exploded', {name: this.name});
  }
  if (this.firing && !this.exploded) {
    this.fire();
  }
};
FBPlayer.prototype.destroyed = function () {
  return !this.connected
};

FBPlayer.prototype.render = Player.prototype.render = function () {
  if (this.exploded) { return; }
  context.save();
  context.translate(this.x, this.y);
  context.rotate(-(this.angle + 0.055) * (180/Math.PI));
  context.drawImage(this.img, -this.w/2, -this.h/2);
  context.restore();
};
FBPlayer.prototype.reset = Player.prototype.reset = function (params) {
  if (!this.exploded) { return; }
  // Crummy workaround
  if (!params) {
    // We're a player
    socket.emit('reset', {name: name});
  }
  this.constructor(params);
};
FBPlayer.prototype.fire = function () {
  var radians = (this.angle + 0.055) * (180/Math.PI);

  var xx = this.x + (this.w/2 * Math.cos(-(this.angle + 0.0275) * (180/Math.PI)));
  var yy = this.y + (this.w/2 * Math.sin(-(this.angle + 0.0275) * (180/Math.PI)));

  var r = this.w/2;
  particles.create({
    x: xx,
    y: yy,
    dx: Math.sin(radians) * 10,
    dy: Math.cos(radians) * 10,
    c: 'rgba(287,3,24,1)',
    r: 7,
    decay: 0.06
  });
};<|endoftext|>


<commit_before>var http = require('http');
var phantom = require('node-phantom-simple');

var processing = false;
var requests = [];

// Request the current page and send back as png
// Then process next request in queue if there is one
var processRequest = function(req, res){
	if(req && res){
		processing = true;
		phantom.create(function(err,ph) {
			return ph.createPage(function(err, page) {
				page.set('viewportSize', {
					width: 1024,
					height: 1024
				});
				return page.open(req.url.slice(1), function(err, status) {
					console.log('status: ', status, err);
					//Wait for a bit for AJAX content to load on the page. Better solution?
					setTimeout(function() {
						page.renderBase64("PNG", function(error, result){
							var imageBuffer = new Buffer(result, 'base64');
							res.writeHead(200, {
								'Content-Type': 'image/png',
								'Content-Length': imageBuffer.length});
							res.end(imageBuffer);
							ph.exit()
							processRequest.apply(null, requests.shift());
						});
					}, 1000);
				});
			}, {parameters: {'ignore-ssl-errors': 'yes'}});
		});
	} else {
		processing = false;
	}
};

// Process the incoming request if not already processing
// Else put into queue
http.createServer(function (req, res) {
	if(!processing){
		processRequest(req, res);
	} else if (requests.length > 10) {
		requests = [];
		processRequest(req, res);
	} else {
		requests.push([req, res]);
	}
}).listen(process.env.PORT || 1337, function(){
	console.log('running');
});
<commit_msg>remove console.log of page load errors<commit_after>var http = require('http');
var phantom = require('node-phantom-simple');

var processing = false;
var requests = [];

// Request the current page and send back as png
// Then process next request in queue if there is one
var processRequest = function(req, res){
	if(req && res){
		processing = true;
		phantom.create(function(err,ph) {
			return ph.createPage(function(err, page) {
				page.set('viewportSize', {
					width: 1024,
					height: 1024
				});
				return page.open(req.url.slice(1), function(err, status) {
					//Wait for a bit for AJAX content to load on the page. Better solution?
					setTimeout(function() {
						page.renderBase64("PNG", function(error, result){
							var imageBuffer = new Buffer(result, 'base64');
							res.writeHead(200, {
								'Content-Type': 'image/png',
								'Content-Length': imageBuffer.length});
							res.end(imageBuffer);
							ph.exit()
							processRequest.apply(null, requests.shift());
						});
					}, 1000);
				});
			}, {parameters: {'ignore-ssl-errors': 'yes'}});
		});
	} else {
		processing = false;
	}
};

// Process the incoming request if not already processing
// Else put into queue
http.createServer(function (req, res) {
	if(!processing){
		processRequest(req, res);
	} else if (requests.length > 10) {
		requests = [];
		processRequest(req, res);
	} else {
		requests.push([req, res]);
	}
}).listen(process.env.PORT || 1337, function(){
	console.log('running');
});
<|endoftext|>


<commit_before>// Configs
S.cfga({
        "defaultToCurrentScreen" : true,
        "secondsBetweenRepeat" : 0.5,
        "checkDefaultsOnLoad" : true,
        "focusCheckWidthMax" : 3000,
        "orderScreensLeftToRight" : true
});

// Operations
var full = S.op("move", {
        "x" : "screenOriginX",
        "y" : "screenOriginY",
        "width" : "screenSizeX",
        "height" : "screenSizeY"
});
var topRight = S.op("corner", {
        "direction" : "top-right",
        "width" : "screenSizeX/2",
        "height" : "screenSizeY/2"
});
var bottomRight = S.op("corner", {
        "direction" : "bottom-right",
        "width" : "screenSizeX/2",
        "height" : "screenSizeY/2"
});
var bottomLeft = S.op("corner", {
        "direction" : "bottom-left",
        "width" : "screenSizeX/2",
        "height" : "screenSizeY/2"
});
var topLeft = S.op("corner", {
        "direction" : "top-left",
        "width" : "screenSizeX/2",
        "height" : "screenSizeY/2"
});

var restrict = function(rect, visible) {
        // S.log("[SLATE] before restrict; rect: " + JSON.stringify(rect) + "; visible: " + JSON.stringify(visible));
        if (rect.width > visible.width) {
                rect.width = visible.width;
                // S.log("[SLATE] too wide; new width: " + rect.width);
        }
        if (rect.height > visible.height) {
                rect.height = visible.height;
                // S.log("[SLATE] too high; new height: " + rect.height);
        }
        if (rect.x < visible.x) {
                rect.x = visible.x;
                // S.log("[SLATE] nudge right; new x: " + rect.x);
        }
        if (rect.y < visible.y) {
                rect.y = visible.y;
                // S.log("[SLATE] nudge down; new y: " + rect.y);
        }
        if (rect.x + rect.width > visible.x + visible.width) {
                rect.x = (visible.x + visible.width) - rect.width;
                // S.log("[SLATE] nudge left; new x: " + rect.x);
        }
        if (rect.y + rect.height > visible.y + visible.height) {
                rect.y = (visible.y + visible.height) - rect.height;
                // S.log("[SLATE] nudge up; new y: " + rect.y);
        }
        return {"x":rect.x, "y":rect.y, "width":rect.width, "height": rect.height};
};

var whichEdge = function(window, visible) {
        var snapTolerance = 5;
        var result = '';
        var rect = window.rect();
        // snapTop takes priority over snapBottom
        if (rect.y <= visible.y + snapTolerance) {
                result = 'top';
        } else if (rect.y + rect.height + snapTolerance >= visible.y + visible.height) {
                result = 'bottom';
        }
        // snapLeft takes priority over snapRight
        if (rect.x <= visible.x + snapTolerance) {
                result += 'left';
        } else if (rect.x + rect.width + snapTolerance >= visible.x + visible.width) {
                result += 'right';
        }
        // S.log("[SLATE] whichEdge: " + result + "; rect: " + JSON.stringify(rect) + "; visible: " + JSON.stringify(visible));
        return result; // top|topleft|topright|bottom|bottomleft|bottomright|left|right
};

var snap = function(window, visible, edge) {
        if (edge !== '') {
                var rect = window.rect();
                if (edge.indexOf("top") != -1) {
                        rect.y = visible.y;
                }
                if (edge.indexOf("left") != -1) {
                        rect.x = visible.x;
                }
                if (edge.indexOf("bottom") != -1) {
                        rect.y = (visible.y + visible.height) - rect.height;
                }
                if (edge.indexOf("right") != -1) {
                        rect.x = (visible.x + visible.width) - rect.width;
                }
                window.doop("move", rect);
        }
};

var flubber = function(op) {
        return function(window) {
                var visible = S.screen().visibleRect();
                var edge = whichEdge(window, visible);
                var rect = window.rect();
                switch (op) {
                case "grow":
                        rect.width = Math.round(rect.width * 1.1);
                        rect.height = Math.round(rect.height * 1.1);
                        break;
                case "shrink":
                        rect.width = Math.round(rect.width * 0.9);
                        rect.height = Math.round(rect.height * 0.9);
                        break;
                default:
                        S.log("[SLATE] cannot perform unknown operation: " + op);
                        return;
                }
                // NOTE: some windows have discrete sizes; for best
                // adherence to edges, need to resize, then snap.
                window.doop("move", restrict(rect, visible);
                snap(window, visible, edge);
        };
};

// Bind All. NOTE: some of these may *not* work if you have not
// removed the expose/spaces/mission control bindings.
S.bnda({
        "1:alt" : flubber("grow"),
        "2:alt" : flubber("shrink"),

        // resize top left corner
        "right:ctrl" : S.op("resize", { "width" : "-10%", "height" : "+0", "anchor" : "bottom-right" }),
        "left:ctrl" : S.op("resize", { "width" : "+10%", "height" : "+0", "anchor" : "bottom-right" }),
        "up:ctrl" : S.op("resize", { "width" : "+0", "height" : "+10%", "anchor" : "bottom-right" }),
        "down:ctrl" : S.op("resize", { "width" : "+0", "height" : "-10%", "anchor" : "bottom-right" }),
        // resize bottom right corner
        "up:alt" : S.op("resize", { "width" : "+0", "height" : "-10%" }),
        "down:alt" : S.op("resize", { "width" : "+0", "height" : "+10%" }),
        "left:alt" : S.op("resize", { "width" : "-10%", "height" : "+0" }),
        "right:alt" : S.op("resize", { "width" : "+10%", "height" : "+0" }),
        // move entire window
        "right:ctrl;alt" : S.op("nudge", { "x" : "+10%", "y" : "+0" }),
        "left:ctrl;alt" : S.op("nudge", { "x" : "-10%", "y" : "+0" }),
        "up:ctrl;alt" : S.op("nudge", { "x" : "+0", "y" : "-10%" }),
        "down:ctrl;alt" : S.op("nudge", { "x" : "+0", "y" : "+10%" }),
        // shove window to edge
        "right:ctrl;shift" : S.op("push", { "direction" : "right", "style" : "bar-resize:screenSizeX/2" }),
        "left:ctrl;shift" : S.op("push", { "direction" : "left", "style" : "bar-resize:screenSizeX/2" }),
        "up:ctrl;shift" : S.op("push", { "direction" : "up", "style" : "bar-resize:screenSizeY/2" }),
        "down:ctrl;shift" : S.op("push", { "direction" : "down", "style" : "bar-resize:screenSizeY/2" }),
        // shove window to corner
        "u:shift;ctrl;cmd" : topLeft,
        "i:shift;ctrl;cmd" : topRight,
        "j:shift;ctrl;cmd" : full, // all corners ;)
        "n:shift;ctrl;cmd" : bottomLeft,
        "m:shift;ctrl;cmd" : bottomRight,
        // change which window is in focus
        "right:cmd" : S.op("focus", { "direction" : "right" }),
        "left:cmd" : S.op("focus", { "direction" : "left" }),
        "up:cmd" : S.op("focus", { "direction" : "up" }),
        "down:cmd" : S.op("focus", { "direction" : "down" }),
        // Window Hints
        "esc:cmd" : S.op("hint"),
        // Grid
        "esc:ctrl" : S.op("grid")
});

// Log that we're done configuring
S.log("[SLATE] -------------- Finished Loading Config --------------");
<commit_msg>config loads rather than bails due to syntax error<commit_after>// Configs
S.cfga({
        "defaultToCurrentScreen" : true,
        "secondsBetweenRepeat" : 0.5,
        "checkDefaultsOnLoad" : true,
        "focusCheckWidthMax" : 3000,
        "orderScreensLeftToRight" : true
});

// Operations
var full = S.op("move", {
        "x" : "screenOriginX",
        "y" : "screenOriginY",
        "width" : "screenSizeX",
        "height" : "screenSizeY"
});
var topRight = S.op("corner", {
        "direction" : "top-right",
        "width" : "screenSizeX/2",
        "height" : "screenSizeY/2"
});
var bottomRight = S.op("corner", {
        "direction" : "bottom-right",
        "width" : "screenSizeX/2",
        "height" : "screenSizeY/2"
});
var bottomLeft = S.op("corner", {
        "direction" : "bottom-left",
        "width" : "screenSizeX/2",
        "height" : "screenSizeY/2"
});
var topLeft = S.op("corner", {
        "direction" : "top-left",
        "width" : "screenSizeX/2",
        "height" : "screenSizeY/2"
});

var restrict = function(rect, visible) {
        // S.log("[SLATE] before restrict; rect: " + JSON.stringify(rect) + "; visible: " + JSON.stringify(visible));
        if (rect.width > visible.width) {
                rect.width = visible.width;
                // S.log("[SLATE] too wide; new width: " + rect.width);
        }
        if (rect.height > visible.height) {
                rect.height = visible.height;
                // S.log("[SLATE] too high; new height: " + rect.height);
        }
        if (rect.x < visible.x) {
                rect.x = visible.x;
                // S.log("[SLATE] nudge right; new x: " + rect.x);
        }
        if (rect.y < visible.y) {
                rect.y = visible.y;
                // S.log("[SLATE] nudge down; new y: " + rect.y);
        }
        if (rect.x + rect.width > visible.x + visible.width) {
                rect.x = (visible.x + visible.width) - rect.width;
                // S.log("[SLATE] nudge left; new x: " + rect.x);
        }
        if (rect.y + rect.height > visible.y + visible.height) {
                rect.y = (visible.y + visible.height) - rect.height;
                // S.log("[SLATE] nudge up; new y: " + rect.y);
        }
        return {"x":rect.x, "y":rect.y, "width":rect.width, "height": rect.height};
};

var whichEdge = function(window, visible) {
        var snapTolerance = 5;
        var result = '';
        var rect = window.rect();
        // snapTop takes priority over snapBottom
        if (rect.y <= visible.y + snapTolerance) {
                result = 'top';
        } else if (rect.y + rect.height + snapTolerance >= visible.y + visible.height) {
                result = 'bottom';
        }
        // snapLeft takes priority over snapRight
        if (rect.x <= visible.x + snapTolerance) {
                result += 'left';
        } else if (rect.x + rect.width + snapTolerance >= visible.x + visible.width) {
                result += 'right';
        }
        // S.log("[SLATE] whichEdge: " + result + "; rect: " + JSON.stringify(rect) + "; visible: " + JSON.stringify(visible));
        return result; // top|topleft|topright|bottom|bottomleft|bottomright|left|right
};

var snap = function(window, visible, edge) {
        if (edge !== '') {
                var rect = window.rect();
                if (edge.indexOf("top") != -1) {
                        rect.y = visible.y;
                }
                if (edge.indexOf("left") != -1) {
                        rect.x = visible.x;
                }
                if (edge.indexOf("bottom") != -1) {
                        rect.y = (visible.y + visible.height) - rect.height;
                }
                if (edge.indexOf("right") != -1) {
                        rect.x = (visible.x + visible.width) - rect.width;
                }
                window.doop("move", rect);
        }
};

var flubber = function(op) {
        return function(window) {
                var visible = S.screen().visibleRect();
                var edge = whichEdge(window, visible);
                var rect = window.rect();
                switch (op) {
                case "grow":
                        rect.width = Math.round(rect.width * 1.1);
                        rect.height = Math.round(rect.height * 1.1);
                        break;
                case "shrink":
                        rect.width = Math.round(rect.width * 0.9);
                        rect.height = Math.round(rect.height * 0.9);
                        break;
                default:
                        S.log("[SLATE] cannot perform unknown operation: " + op);
                        return;
                }
                // NOTE: some windows have discrete sizes; for best
                // adherence to edges, need to resize, then snap.
                window.doop("move", restrict(rect, visible));
                snap(window, visible, edge);
        };
};

// Bind All. NOTE: some of these may *not* work if you have not
// removed the expose/spaces/mission control bindings.
S.bnda({
        "1:alt" : flubber("grow"),
        "2:alt" : flubber("shrink"),

        // resize top left corner
        "right:ctrl" : S.op("resize", { "width" : "-10%", "height" : "+0", "anchor" : "bottom-right" }),
        "left:ctrl" : S.op("resize", { "width" : "+10%", "height" : "+0", "anchor" : "bottom-right" }),
        "up:ctrl" : S.op("resize", { "width" : "+0", "height" : "+10%", "anchor" : "bottom-right" }),
        "down:ctrl" : S.op("resize", { "width" : "+0", "height" : "-10%", "anchor" : "bottom-right" }),
        // resize bottom right corner
        "up:alt" : S.op("resize", { "width" : "+0", "height" : "-10%" }),
        "down:alt" : S.op("resize", { "width" : "+0", "height" : "+10%" }),
        "left:alt" : S.op("resize", { "width" : "-10%", "height" : "+0" }),
        "right:alt" : S.op("resize", { "width" : "+10%", "height" : "+0" }),
        // move entire window
        "right:ctrl;alt" : S.op("nudge", { "x" : "+10%", "y" : "+0" }),
        "left:ctrl;alt" : S.op("nudge", { "x" : "-10%", "y" : "+0" }),
        "up:ctrl;alt" : S.op("nudge", { "x" : "+0", "y" : "-10%" }),
        "down:ctrl;alt" : S.op("nudge", { "x" : "+0", "y" : "+10%" }),
        // shove window to edge
        "right:ctrl;shift" : S.op("push", { "direction" : "right", "style" : "bar-resize:screenSizeX/2" }),
        "left:ctrl;shift" : S.op("push", { "direction" : "left", "style" : "bar-resize:screenSizeX/2" }),
        "up:ctrl;shift" : S.op("push", { "direction" : "up", "style" : "bar-resize:screenSizeY/2" }),
        "down:ctrl;shift" : S.op("push", { "direction" : "down", "style" : "bar-resize:screenSizeY/2" }),
        // shove window to corner
        "u:shift;ctrl;cmd" : topLeft,
        "i:shift;ctrl;cmd" : topRight,
        "j:shift;ctrl;cmd" : full, // all corners ;)
        "n:shift;ctrl;cmd" : bottomLeft,
        "m:shift;ctrl;cmd" : bottomRight,
        // change which window is in focus
        "right:cmd" : S.op("focus", { "direction" : "right" }),
        "left:cmd" : S.op("focus", { "direction" : "left" }),
        "up:cmd" : S.op("focus", { "direction" : "up" }),
        "down:cmd" : S.op("focus", { "direction" : "down" }),
        // Window Hints
        "esc:cmd" : S.op("hint"),
        // Grid
        "esc:ctrl" : S.op("grid")
});

// Log that we're done configuring
S.log("[SLATE] -------------- Finished Loading Config --------------");
<|endoftext|>


<commit_before>var io = require('socket.io-client'),
    config = require('./config/config'),
    socket = io.connect(config.socketio.client.uri)
;

var status = {
  name : 'raspberry one'
};

// Connected to master
socket.on('connect', function() {
  console.log('connection established.');

  // Send current status to the master
  socket.emit('/status', status);
});

socket.on('disconnect', function() {
  console.log('disconnect');
});

socket.on('error', function(err) {
  console.log(err);
});

socket.on('reconnect', function(count) {
  console.log('reconnected', count);
});

socket.on('reconnecting', function(count) {
 console.log('reconnecting', count);
});

socket.on('reconnect_error', function(err) {
  console.log(err);
});<commit_msg>Improved console.log and default value for "status.name".<commit_after>var io = require('socket.io-client'),
    config = require('./config/config'),
    socket = io.connect(config.socketio.client.uri)
;

var status = {
  name : 'slave'
};

// Connected to master
socket.on('connect', function() {
  console.log('Connection to '+config.socketio.client.uri+' established.');

  // Send current status to the master
  socket.emit('/status', status);
});

socket.on('disconnect', function() {
  console.log('disconnect');
});

socket.on('error', function(err) {
  console.log(err);
});

socket.on('reconnect', function(count) {
  console.log('reconnected', count);
});

socket.on('reconnecting', function(count) {
 console.log('reconnecting', count);
});

socket.on('reconnect_error', function(err) {
  console.log(err);
});<|endoftext|>


<commit_before>'use strict';

var reAnsi        = require('ansi-regex')
  , stringifiable = require('es5-ext/object/validate-stringifiable-value')
  , length        = require('./get-stripped-length')
  , sgr           = require('./lib/sgr');

var Token = function Token(token) {
	this.token = token;
};

var tokenize = function (str) {
	var match = reAnsi().exec(str);

	if (!match) {
		return [ str ];
	}

	var index = match.index
	  , head, prehead, tail;

	if (index === 0) {
		head = match[0];
		tail = str.slice(head.length);

		return [ new Token(head) ].concat(tokenize(tail));
	}

	prehead = str.slice(0, index);
	head = match[0];
	tail = str.slice(index + head.length);

	return [ prehead, new Token(head) ].concat(tokenize(tail));
};

var isChunkInSlice = function (chunk, index, begin, end) {
	var endIndex = chunk.length + index;

	if (begin > endIndex) return false;
	if (end < index) return false;
	return true;
};

var sliceSeq = function (seq, begin, end) {
	var sliced = seq.reduce(function (state, chunk) {
		var index = state.index;

		if (!(chunk instanceof Token)) {
			var nextChunk = '';

			if (isChunkInSlice(chunk, index, begin, end)) {
				var relBegin = Math.max(begin - index, 0)
				  , relEnd   = Math.min(end - index, chunk.length);

				nextChunk = chunk.slice(relBegin, relEnd);
			}

			state.seq.push(nextChunk);
			state.index = index + chunk.length;
		} else {
			var code = sgr.extractCode(chunk.token);

			if (index <= begin) {
				if (code in sgr.openers) {
					sgr.openStyle(state.preOpeners, code);
				}
				if (code in sgr.closers) {
					sgr.closeStyle(state.preOpeners, code);
				}
			} else if (index < end) {
				if (code in sgr.openers) {
					sgr.openStyle(state.inOpeners, code);
					state.seq.push(chunk);
				} else if (code in sgr.closers) {
					state.inClosers.push(code);
					state.seq.push(chunk);
				}
			}
		}

		return state;
	}, {
		index: 0,
		seq: [],

		// preOpeners -> [ mod ]
		// preOpeners must be prepended to the slice if they wasn't closed til the end of it
		// preOpeners must be closed if they wasn't closed til the end of the slice
		preOpeners: [],

		// inOpeners  -> [ mod ]
		// inOpeners already in the slice and must not be prepended to the slice
		// inOpeners must be closed if they wasn't closed til the end of the slice
		inOpeners:  [], // opener CSI inside slice

		// inClosers -> [ code ]
		// closer CSIs for determining which pre/in-Openers must be closed
		inClosers:  []
	});

	sliced.seq = [].concat(
		sgr.prepend(sliced.preOpeners),
		sliced.seq,
		sgr.complete([].concat(sliced.preOpeners, sliced.inOpeners), sliced.inClosers)
	);

	return sliced.seq;
};

module.exports = function (str, begin, end) {
	var seq, len;

	str = stringifiable(str);
	len = length(str);

	if (begin == null) {
		begin = 0;
	}
	if (end == null) {
		end = len;
	}
	if (begin < 0) {
		begin = len + begin;
	}
	if (end < 0) {
		end = len + end;
	}

	seq = tokenize(str);
	seq = sliceSeq(seq, begin, end);
	return seq.map(function (chunk) {
		if (chunk instanceof Token) {
			return chunk.token;
		}

		return chunk;
	}).join('');
};
<commit_msg>Improve slice arguments handling<commit_after>'use strict';

var reAnsi        = require('ansi-regex')
  , stringifiable = require('es5-ext/object/validate-stringifiable-value')
  , length        = require('./get-stripped-length')
  , sgr           = require('./lib/sgr')

  , max = Math.max;

var Token = function Token(token) {
	this.token = token;
};

var tokenize = function (str) {
	var match = reAnsi().exec(str);

	if (!match) {
		return [ str ];
	}

	var index = match.index
	  , head, prehead, tail;

	if (index === 0) {
		head = match[0];
		tail = str.slice(head.length);

		return [ new Token(head) ].concat(tokenize(tail));
	}

	prehead = str.slice(0, index);
	head = match[0];
	tail = str.slice(index + head.length);

	return [ prehead, new Token(head) ].concat(tokenize(tail));
};

var isChunkInSlice = function (chunk, index, begin, end) {
	var endIndex = chunk.length + index;

	if (begin > endIndex) return false;
	if (end < index) return false;
	return true;
};

var sliceSeq = function (seq, begin, end) {
	var sliced = seq.reduce(function (state, chunk) {
		var index = state.index;

		if (!(chunk instanceof Token)) {
			var nextChunk = '';

			if (isChunkInSlice(chunk, index, begin, end)) {
				var relBegin = Math.max(begin - index, 0)
				  , relEnd   = Math.min(end - index, chunk.length);

				nextChunk = chunk.slice(relBegin, relEnd);
			}

			state.seq.push(nextChunk);
			state.index = index + chunk.length;
		} else {
			var code = sgr.extractCode(chunk.token);

			if (index <= begin) {
				if (code in sgr.openers) {
					sgr.openStyle(state.preOpeners, code);
				}
				if (code in sgr.closers) {
					sgr.closeStyle(state.preOpeners, code);
				}
			} else if (index < end) {
				if (code in sgr.openers) {
					sgr.openStyle(state.inOpeners, code);
					state.seq.push(chunk);
				} else if (code in sgr.closers) {
					state.inClosers.push(code);
					state.seq.push(chunk);
				}
			}
		}

		return state;
	}, {
		index: 0,
		seq: [],

		// preOpeners -> [ mod ]
		// preOpeners must be prepended to the slice if they wasn't closed til the end of it
		// preOpeners must be closed if they wasn't closed til the end of the slice
		preOpeners: [],

		// inOpeners  -> [ mod ]
		// inOpeners already in the slice and must not be prepended to the slice
		// inOpeners must be closed if they wasn't closed til the end of the slice
		inOpeners:  [], // opener CSI inside slice

		// inClosers -> [ code ]
		// closer CSIs for determining which pre/in-Openers must be closed
		inClosers:  []
	});

	sliced.seq = [].concat(
		sgr.prepend(sliced.preOpeners),
		sliced.seq,
		sgr.complete([].concat(sliced.preOpeners, sliced.inOpeners), sliced.inClosers)
	);

	return sliced.seq;
};

module.exports = function (str/*, begin, end*/) {
	var seq, begin = Number(arguments[1]), end = Number(arguments[2]), len;

	str = stringifiable(str);
	len = length(str);

	if (isNaN(begin)) {
		begin = 0;
	}
	if (isNaN(end)) {
		end = len;
	}
	if (begin < 0) {
		begin = max(len + begin, 0);
	}
	if (end < 0) {
		end = max(len + end, 0);
	}

	seq = tokenize(str);
	seq = sliceSeq(seq, begin, end);
	return seq.map(function (chunk) {
		if (chunk instanceof Token) {
			return chunk.token;
		}

		return chunk;
	}).join('');
};
<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', function() {
  var canvas = document.querySelector('#screen');
  var context =  canvas.getContext('2d');

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }

  resizeCanvas();
});
<commit_msg>Create gameloop for snake<commit_after>document.addEventListener('DOMContentLoaded', function() {
  var canvas = document.querySelector('#screen');
  var context =  canvas.getContext('2d');

  window.addEventListener('resize', resizeCanvas, false);

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    drawSnake();
  }

  resizeCanvas();

  if (window.requestAnimationFrame !== null) {
    var recursiveAnim = function() {
      mainloop();
      window.requestAnimationFrame(recursiveAnim);
    };

    window.requestAnimationFrame(recursiveAnim);
  } else {
    setInterval(mainloop, 1000.0 / 60.0);
  }

  var point = 0;
  function mainloop() {
    updateSnake();
    drawSnake();
  }

  function updateSnake() {
    if (point >= canvas.width || point >= canvas.height) {
      point = 0;
    } else {
      point++;
    }
  }

  function drawSnake() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillRect(point, point, 10, 10);
  }
});
<|endoftext|>