<commit_before>// Bind and Events dependencies
var Bind = require("github/jillix/bind")
  , Events = require("github/jillix/events")
  ;

/**
 *  Mono module for jxMaps application
 */
module.exports = function(config) {

    // get module
    var self = this;

    // call events
    Events.call(self, config);

    // binds
    config.binds = config.binds || [];
    config.options = Object (config.options);
    config.options.ui = Object (config.options.ui);

    // run the binds
    for (var i = 0; i < config.binds.length; ++i) {
        Bind.call(self, config.binds[i]);
    }

    // set config in self
    self.config = config;
    self._maps = {};

    // ui
    self._$ = {
        map: $(self.config.options.ui.map)
      , waiter: $(self.config.options.ui.map)
      , error: $(self.config.options.ui.map)
    }

    // crud operations
    var operations = ["create", "read", "update", "delete"];

    // generate client methods
    for (var i = 0; i < operations.length; ++i) {
        (function (op) {
            self[op] = function (options, callback) {
                self.link (op, { data: options }, callback);
            };
        })(operations[i]);
    }

    /**
     *  mono-maps#embed
     *  Gets the map to embed from database
     *
     *  Arguments
     *    options: an object containing:
     *      - mapId: the map id
     *    callback: the callback function
     * */
    self.embed = function (options, callback) {

        // update ui
        self._$.map.hide();
        self._$.waiter.show();

        // default value for callback
        callback = callback || function () {};

        // call server operation
        self.link ("embed", { data: options}, function (err, mapData) {

            // handle error
            if (err) {

                // update UI
                self._$.waiter.fadeOut();
                self._$.error.fadeIn().text(err);

                return callback (err);
            }

            // cache map in _maps
            self._maps[mapData._id] = mapData;

            // get google maps script
            $.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=__initializeMap");
        });
    }

    /**
     *  This is a global function that will be called after loading the
     *  Google library.
     *
     * */
    window.__initializeMap = function (mapData) {

        // no map data
        if (!mapData) {
            for (var mapId in self._maps) {
                __initializeMap (self._maps[mapId]);
            }
            return;
        }

        // get map element
        var mapEl = self._$.map[0];
        if (!mapEl) {
            return console.error ("No map element found.");
        }

        // map options
        var mapOptions = {
            center: new google.maps.LatLng (
                mapData.options.center.lat
              , mapData.options.center.lng
            )
          , zoom: mapData.options.zoom
          , mapTypeId: google.maps.MapTypeId[mapData.options.type]
        };

        // save google maps instance in _gmap
        self._gmap = new google.maps.Map(mapEl, mapOptions)

        // default value for markers
        var markers = mapData.markers = mapData.markers || []
          , allMarkers = []
          ;

        // each marker
        for (var i = 0; i < markers.length; ++i) {

            (function (cMarker) {

                // icon exists
                if (cMarker.icon) {

                    cMarker.icon = new google.maps.MarkerImage(
                        cMarker.icon.path
                      , new google.maps.Size (
                            cMarker.icon.size.w
                          , cMarker.icon.size.h
                        )
                      , new google.maps.Point (
                            cMarker.icon.origin.x
                          , cMarker.icon.origin.y
                        )
                      , new google.maps.Point (
                            cMarker.icon.anchor.x
                          , cMarker.icon.anchor.y
                        )
                    );
                }

                // create google marker
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(cMarker.position.lat, cMarker.position.lng)
                  , map: self._gmap
                  , title: cMarker.title || ""
                  , icon: cMarker.icon || undefined
                  , visible: cMarker.visible
                });

                // infowin exists
                if (cMarker.infowin) {
                    cMarker.infowin = new google.maps.InfoWindow({
                        content: cMarker.infowin.content
                    });
                }

                // push the new marker
                allMarkers.push (marker);

                // add click event for info window
                google.maps.event.addListener(marker, "click", function() {
                    if (!cMarker.infowin) return;
                    cMarker.infowin.open(self._gmap, marker);
                });
            })(markers[i]);
        }

        // marker clusterer
        self._gmarkerClusterer = new MarkerClusterer(self._gmap);

        // update ui
        self._$.map.fadeIn();
        self._$.waiter.fadeOut();
    };

    // we are on the embed page
    if (location.pathname + location.search + location.hash === self.config.options.embedPage) {

        // get the map id
        var mapId = Utils.queryString ("mapId");

        // no map id
        if (!mapId) {
            self._$.map.hide();
            self._$.waiter.hide();
            self._$.error.text("Missing mapId.");
        }

        // call embed method
        self.embed ({mapId: mapId});
    }

    // emit ready
    self.emit("ready", self);
};
<commit_msg>Added automaticallyEmbed option<commit_after>// Bind and Events dependencies
var Bind = require("github/jillix/bind")
  , Events = require("github/jillix/events")
  ;

/**
 *  Mono module for jxMaps application
 */
module.exports = function(config) {

    // get module
    var self = this;

    // call events
    Events.call(self, config);

    // binds
    config.binds = config.binds || [];
    config.options = Object (config.options);
    config.options.ui = Object (config.options.ui);

    // run the binds
    for (var i = 0; i < config.binds.length; ++i) {
        Bind.call(self, config.binds[i]);
    }

    // set config in self
    self.config = config;
    self._maps = {};

    // ui
    self._$ = {
        map: $(self.config.options.ui.map)
      , waiter: $(self.config.options.ui.map)
      , error: $(self.config.options.ui.map)
    }

    // crud operations
    var operations = ["create", "read", "update", "delete"];

    // generate client methods
    for (var i = 0; i < operations.length; ++i) {
        (function (op) {
            self[op] = function (options, callback) {
                self.link (op, { data: options }, callback);
            };
        })(operations[i]);
    }

    /**
     *  mono-maps#embed
     *  Gets the map to embed from database
     *
     *  Arguments
     *    options: an object containing:
     *      - mapId: the map id
     *    callback: the callback function
     * */
    self.embed = function (options, callback) {

        // update ui
        self._$.map.hide();
        self._$.waiter.show();

        // default value for callback
        callback = callback || function () {};

        // call server operation
        self.link ("embed", { data: options}, function (err, mapData) {

            // handle error
            if (err) {

                // update UI
                self._$.waiter.fadeOut();
                self._$.error.fadeIn().text(err);

                return callback (err);
            }

            // cache map in _maps
            self._maps[mapData._id] = mapData;

            // get google maps script
            $.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=__initializeMap");
        });
    }

    /**
     *  This is a global function that will be called after loading the
     *  Google library.
     *
     * */
    window.__initializeMap = function (mapData) {

        // no map data
        if (!mapData) {
            for (var mapId in self._maps) {
                __initializeMap (self._maps[mapId]);
            }
            return;
        }

        // get map element
        var mapEl = self._$.map[0];
        if (!mapEl) {
            return console.error ("No map element found.");
        }

        // map options
        var mapOptions = {
            center: new google.maps.LatLng (
                mapData.options.center.lat
              , mapData.options.center.lng
            )
          , zoom: mapData.options.zoom
          , mapTypeId: google.maps.MapTypeId[mapData.options.type]
        };

        // save google maps instance in _gmap
        self._gmap = new google.maps.Map(mapEl, mapOptions)

        // default value for markers
        var markers = mapData.markers = mapData.markers || []
          , allMarkers = []
          ;

        // each marker
        for (var i = 0; i < markers.length; ++i) {

            (function (cMarker) {

                // icon exists
                if (cMarker.icon) {

                    cMarker.icon = new google.maps.MarkerImage(
                        cMarker.icon.path
                      , new google.maps.Size (
                            cMarker.icon.size.w
                          , cMarker.icon.size.h
                        )
                      , new google.maps.Point (
                            cMarker.icon.origin.x
                          , cMarker.icon.origin.y
                        )
                      , new google.maps.Point (
                            cMarker.icon.anchor.x
                          , cMarker.icon.anchor.y
                        )
                    );
                }

                // create google marker
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(cMarker.position.lat, cMarker.position.lng)
                  , map: self._gmap
                  , title: cMarker.title || ""
                  , icon: cMarker.icon || undefined
                  , visible: cMarker.visible
                });

                // infowin exists
                if (cMarker.infowin) {
                    cMarker.infowin = new google.maps.InfoWindow({
                        content: cMarker.infowin.content
                    });
                }

                // push the new marker
                allMarkers.push (marker);

                // add click event for info window
                google.maps.event.addListener(marker, "click", function() {
                    if (!cMarker.infowin) return;
                    cMarker.infowin.open(self._gmap, marker);
                });
            })(markers[i]);
        }

        // marker clusterer
        self._gmarkerClusterer = new MarkerClusterer(self._gmap);

        // update ui
        self._$.map.fadeIn();
        self._$.waiter.fadeOut();
    };

    // we are on the embed page
    if (
        location.pathname + location.search + location.hash === self.config.options.embedPage
        && self.config.options.automaticallyEmbed !== false
    ) {

        // get the map id
        var mapId = Utils.queryString ("mapId");

        // no map id
        if (!mapId) {
            self._$.map.hide();
            self._$.waiter.hide();
            self._$.error.text("Missing mapId.");
        }

        // call embed method
        self.embed ({mapId: mapId});
    }

    // emit ready
    self.emit("ready", self);
};
<|endoftext|>


<commit_before>/*
 * Contains objects related to the game world in Battles. This includes areas,
 * dungeons, dungeon branches etc.
 */

var RG = require('./rg.js');

const Stairs = RG.Element.Stairs;

RG.World = {};

/* Branch, as name suggests, is a branch of dungeon. A branch is linear
 * progression of connected levels (usually with increasing difficulty).
 * Branch can have
 * entry points to other branches (or out of the dungeon). */
RG.World.Branch = function(name) {

    var _name = name;
    this.getName = function() {return _name;};

    var _levels = [];

    var _stairsDown = [];
    var _stairsUp = [];
    var _stairsOther = [];

    var _numCount = 1;

    var _dungeon = null;

    this.setDungeon = function(dungeon) {_dungeon = dungeon;};
    this.getDungeon = function() {return _dungeon;};

    this.getLevels = function() {return _levels;};
    this.getStairsUp = function() {return _stairsUp;};
    this.getStairsDown = function() {return _stairsDown;};

    /* Stairs leading to other branches.*/
    this.getStairsOther = function() {return _stairsOther;};

    /* Returns entrance/exit for the branch.*/
    this.getEntrance = function() {
        return _stairsUp[0];
    };

    /* Connects entrance to a stairs.*/
    this.connectEntrance = function(stairs) {
        if (_stairsUp.length > 0) {
            _stairsUp[0].setTargetStairs(stairs);
        }
        else {
            RG.err('World.Branch', 'connectEntrance',
                'No stairs for connection exist. Call connectLevels() first.');
        }
    };

    /* Connects specified level to the given stairs (Usually external to this
     * branch.*/
    this.connectLevelToStairs = function(nLevel, stairs) {
        var level = _levels[nLevel];
        var otherBranchLevel = stairs.getSrcLevel();

        if (!RG.isNullOrUndef([otherBranchLevel])) {
            var down = !stairs.isDown();
            var newStairs = new RG.Element.Stairs(down,
                level, otherBranchLevel);
            var cell = level.getFreeRandCell();
            level.addStairs(newStairs, cell.getX(), cell.getY());
            newStairs.setTargetStairs(stairs);
            _stairsOther.push(newStairs);
        }
        else {
            RG.err('World.Branch', 'connectLevelToStairs',
                'Stairs must be first connected to other level.');
        }
    };

    this.hasLevel = function(level) {
        var index = _levels.indexOf(level);
        return index >= 0;
    };

    this.addLevel = function(level) {
        if (!this.hasLevel(level)) {
            level.setLevelNumber(_numCount++);
            _levels.push(level);
        }
        else {
            RG.err('World.Branch', 'addLevel',
                'Trying to add existing level. ');
        }
    };

    /* Connects the added levels together.*/
    this.connectLevels = function() {
        var nLevels = _levels.length;
        for (let nl = 0; nl < nLevels; nl++) {
            var src = _levels[nl];
            var stairCell = null;

            // Create stairs down
            if (nl < nLevels - 1) {
                var targetDown = _levels[nl + 1];
                var stairsDown = new RG.Element.Stairs(true, src, targetDown);
                stairCell = src.getFreeRandCell();
                src.addStairs(stairsDown, stairCell.getX(), stairCell.getY());
                _stairsDown.push(stairsDown);
            }

            // Create stairs up
            if (nl >= 0) {
                var targetUp = _levels[nl - 1];
                var stairsUp = new RG.Element.Stairs(false, src, targetUp);
                stairCell = src.getFreeRandCell();
                src.addStairs(stairsUp, stairCell.getX(), stairCell.getY());
                _stairsUp.push(stairsUp);
            }
        }

        // Finally connect the stairs together
        for (let nl = 0; nl < nLevels; nl++) {
            if (nl < nLevels - 1) {
                _stairsDown[nl].setTargetStairs(_stairsUp[nl + 1]);
            }

            // Don't connect first stairs up
            if (nl > 0) {
                _stairsUp[nl].setTargetStairs(_stairsDown[nl - 1]);
            }
        }
    };

};

/* Dungeons is a collection of branches.*/
RG.World.Dungeon = function(name) {

    var _name = name;
    this.getName = function() {return _name;};

    var _branches = [];

    /* Returns true if the dungeon has given branch.*/
    this.hasBranch = function(branch) {
        var index = _branches.indexOf(branch);
        return index >= 0;
    };

    this.addBranch = function(branch) {
        if (!this.hasBranch(branch)) {
            _branches.push(branch);
            branch.setDungeon(this);
            return true;
        }
        return false;
    };

    this.getLevels = function() {
        var res = [];
        for (var i = 0; i < _branches.length; i++) {
            res = res.concat(_branches[i].getLevels());
        }
        return res;
    };

    /* Returns all entrances/exits for the dungeon.*/
    this.getEntrances = function() {
        var res = [];
        for (var i = 0; i < _branches.length; i++) {
            res.push(_branches[i].getEntrance());
        }
        return res;
    };

    /* Connects two branches b1 and b2 together from specified levels l1 and l2.
     * */
    this.connectBranches = function(b1, b2, l1, l2) {
        if (this.hasBranch(b1) && this.hasBranch(b2)) {
            var down = true;
            if (l1 > l2) {down = false;}
            var stairs = new RG.Element.Stairs(down);
            var b2Levels = b2.getLevels();
            if (l2 < b2Levels.length) {
                var cell = b2Levels[l2].getFreeRandCell();
                b2Levels[l2].addStairs(stairs, cell.getX(), cell.getY());
                b1.connectLevelToStairs(l1, stairs);
            }
            else {
                RG.err('World.Dungeon', 'connectBranches',
                    'Level ' + l2 + " doesn't exist in branch " + b2.getName());
            }
        }
        else {
            RG.err('World.Dungeon', 'connectBranches',
                'Branches must be added to dungeon before connection.');
        }
    };

};

/* Area-tile is a level which has entry/exit points on a number of edges.*/
RG.World.AreaTile = function(x, y, area) {

    var _tileX = x;
    var _tileY = y;
    var _area = area;

    this.cols = null;
    this.rows = null;

    var _level = null;

    /* Sets the level for this tile.*/
    this.setLevel = function(level) {
        _level = level;
        this.cols = _level.getMap().cols;
        this.rows = _level.getMap().rows;
    };

    this.getLevel = function() {return _level;};

    this.getLevel = function() {return _level;};
    this.getTileX = function() {return _tileX;};
    this.getTileY = function() {return _tileY;};

    /* Returns true for edge tiles.*/
    this.isEdge = function() {
        if (this.isNorthEdge()) {return true;}
        if (this.isSouthEdge()) {return true;}
        if (this.isWestEdge()) {return true;}
        if (this.isEastEdge()) {return true;}
        return false;
    };

    this.isNorthEdge = function() {return _tileY === 0;};
    this.isSouthEdge = function() {return _tileY === (_area.getMaxY() - 1);};
    this.isWestEdge = function() {return _tileX === 0;};
    this.isEastEdge = function() {return _tileY === (_area.getMaxY() - 1);};

    /* Connect this tile to east and south tiles */
    this.connect = function(eastTile, southTile) {
        var lastX = this.cols - 1;
        var lastY = this.rows - 1;

        // Connect to east tile
        if (!RG.isNullOrUndef([eastTile])) {
            var levelEast = eastTile.getLevel();
            const map = _level.getMap();
            var mapEast = levelEast.getMap();

            for (var y = 1; y <= lastY - 1; y++) {
                const cell = map.getCell(lastX, y);
                var cellEast = mapEast.getCell(0, y);

                if (cell.isFree() && cellEast.isFree()) {
                    const stairs = new Stairs(true, _level, levelEast);
                    var stairsEast = new Stairs(false, levelEast, _level);
                    _level.addStairs(stairs, lastX, y);
                    levelEast.addStairs(stairsEast, 0, y);
                }
            }

        }

        // Connect to south tile
        if (!RG.isNullOrUndef([southTile])) {
            var levelSouth = southTile.getLevel();
            const map = _level.getMap();
            var mapSouth = levelSouth.getMap();

            for (var x = 1; x <= lastX - 1; x++) {
                const cell = map.getCell(x, lastY);
                var cellSouth = mapSouth.getCell(x, 0);

                if (cell.isFree() && cellSouth.isFree()) {
                    const stairs = new Stairs(true, _level, levelSouth);
                    var stairsSouth = new Stairs(false, levelSouth, _level);
                    _level.addStairs(stairs, x, lastY);
                    levelSouth.addStairs(stairsSouth, x, 0);
                }
            }
        }
    };
};

/* Area is N x M area of tiles, with no linear progression like in dungeons.
 * Moving between tiles of areas happens by travelling to the edges of a tile.
 * Each tile is a level with special edge tiles.
 * */
RG.World.Area = function(name, maxX, maxY) {

    var _name = name;
    this.getName = function() {return _name;};

    var _maxX = maxX;
    var _maxY = maxY;

    this.getMaxX = () => (_maxX);
    this.getMaxY = () => (_maxY);
    const _tiles = [];

    this._init = function() {
        // Create the tiles
        for (let x = 0; x < _maxX; x++) {
            const tileColumn = [];
            for (let y = 0; y < _maxY; y++) {
                const newTile = new RG.World.AreaTile(x, y, this);
                const level = RG.FACT.createLevel('ruins', 30, 30, {});
                newTile.setLevel(level);
                tileColumn.push(newTile);
            }
            _tiles.push(tileColumn);
        }

        // Connect the tiles
        for (let x = 0; x < _maxX; x++) {
            for (let y = 0; y < _maxY; y++) {
                if (x < _maxX - 1 && y < _maxY - 1) {
                    _tiles[x][y].connect(_tiles[x + 1][y], _tiles[x][y + 1]);
                }
                else if (x < _maxX - 1) {
                    _tiles[x][y].connect(_tiles[x + 1][y], null);
                }
                else if (y < _maxY - 1) {
                    _tiles[x][y].connect(null, _tiles[x][y + 1]);
                }
            }
        }
    };

    this._init();

    this.getMaxX = function() {return _maxX;};
    this.getMaxY = function() {return _maxY;};

    this.getLevels = function() {
        var res = [];
        for (let x = 0; x < _tiles.length; x++) {
            for (let y = 0; y < _tiles[x].length; y++) {
                res.push(_tiles[x][y].getLevel());
            }
        }
        return res;
    };

    this.getTiles = function() {
        return _tiles;
    };

};

/* Factory object for creating worlds and features. */
RG.World.Factory = function() {

    this.createArea = function(conf) {
        const area = new RG.World.Area('testArea', 4, 4);
    };

    this.createDungeon = function(conf) {
        console.log(conf);
    };

};

/* Largest place structure. Contains a number of area and dungeons. */
RG.World.World = function(conf) {

    if (RG.isNullOrUndef([conf])) {
        RG.err('World.World', '', 'No configuration given.');
        return;
    }

    var _fact = new RG.World.Factory();

    var _areas = [];
    var _dungeons = [];

    var nAreas = conf.nAreas;
    var nDungeons = conf.nDungeons;

    for (var i = 0; i < nAreas; i++) {
        var area = _fact.createArea(conf);
        _areas.push(area);
    }

    for (var j = 0; j < nDungeons; j++) {
        var dungeon = _fact.createDungeon(conf);
        _dungeons.push(dungeon);
    }

    // Connect areas and dungeons

};

module.exports = RG.World;
<commit_msg>Added missing setTargetStairs for connecting the tiles together.<commit_after>/*
 * Contains objects related to the game world in Battles. This includes areas,
 * dungeons, dungeon branches etc.
 */

var RG = require('./rg.js');

const Stairs = RG.Element.Stairs;

RG.World = {};

/* Branch, as name suggests, is a branch of dungeon. A branch is linear
 * progression of connected levels (usually with increasing difficulty).
 * Branch can have
 * entry points to other branches (or out of the dungeon). */
RG.World.Branch = function(name) {

    var _name = name;
    this.getName = function() {return _name;};

    var _levels = [];

    var _stairsDown = [];
    var _stairsUp = [];
    var _stairsOther = [];

    var _numCount = 1;

    var _dungeon = null;

    this.setDungeon = function(dungeon) {_dungeon = dungeon;};
    this.getDungeon = function() {return _dungeon;};

    this.getLevels = function() {return _levels;};
    this.getStairsUp = function() {return _stairsUp;};
    this.getStairsDown = function() {return _stairsDown;};

    /* Stairs leading to other branches.*/
    this.getStairsOther = function() {return _stairsOther;};

    /* Returns entrance/exit for the branch.*/
    this.getEntrance = function() {
        return _stairsUp[0];
    };

    /* Connects entrance to a stairs.*/
    this.connectEntrance = function(stairs) {
        if (_stairsUp.length > 0) {
            _stairsUp[0].setTargetStairs(stairs);
        }
        else {
            RG.err('World.Branch', 'connectEntrance',
                'No stairs for connection exist. Call connectLevels() first.');
        }
    };

    /* Connects specified level to the given stairs (Usually external to this
     * branch.*/
    this.connectLevelToStairs = function(nLevel, stairs) {
        var level = _levels[nLevel];
        var otherBranchLevel = stairs.getSrcLevel();

        if (!RG.isNullOrUndef([otherBranchLevel])) {
            var down = !stairs.isDown();
            var newStairs = new RG.Element.Stairs(down,
                level, otherBranchLevel);
            var cell = level.getFreeRandCell();
            level.addStairs(newStairs, cell.getX(), cell.getY());
            newStairs.setTargetStairs(stairs);
            _stairsOther.push(newStairs);
        }
        else {
            RG.err('World.Branch', 'connectLevelToStairs',
                'Stairs must be first connected to other level.');
        }
    };

    this.hasLevel = function(level) {
        var index = _levels.indexOf(level);
        return index >= 0;
    };

    this.addLevel = function(level) {
        if (!this.hasLevel(level)) {
            level.setLevelNumber(_numCount++);
            _levels.push(level);
        }
        else {
            RG.err('World.Branch', 'addLevel',
                'Trying to add existing level. ');
        }
    };

    /* Connects the added levels together.*/
    this.connectLevels = function() {
        var nLevels = _levels.length;
        for (let nl = 0; nl < nLevels; nl++) {
            var src = _levels[nl];
            var stairCell = null;

            // Create stairs down
            if (nl < nLevels - 1) {
                var targetDown = _levels[nl + 1];
                var stairsDown = new RG.Element.Stairs(true, src, targetDown);
                stairCell = src.getFreeRandCell();
                src.addStairs(stairsDown, stairCell.getX(), stairCell.getY());
                _stairsDown.push(stairsDown);
            }

            // Create stairs up
            if (nl >= 0) {
                var targetUp = _levels[nl - 1];
                var stairsUp = new RG.Element.Stairs(false, src, targetUp);
                stairCell = src.getFreeRandCell();
                src.addStairs(stairsUp, stairCell.getX(), stairCell.getY());
                _stairsUp.push(stairsUp);
            }
        }

        // Finally connect the stairs together
        for (let nl = 0; nl < nLevels; nl++) {
            if (nl < nLevels - 1) {
                _stairsDown[nl].setTargetStairs(_stairsUp[nl + 1]);
            }

            // Don't connect first stairs up
            if (nl > 0) {
                _stairsUp[nl].setTargetStairs(_stairsDown[nl - 1]);
            }
        }
    };

};

/* Dungeons is a collection of branches.*/
RG.World.Dungeon = function(name) {

    var _name = name;
    this.getName = function() {return _name;};

    var _branches = [];

    /* Returns true if the dungeon has given branch.*/
    this.hasBranch = function(branch) {
        var index = _branches.indexOf(branch);
        return index >= 0;
    };

    this.addBranch = function(branch) {
        if (!this.hasBranch(branch)) {
            _branches.push(branch);
            branch.setDungeon(this);
            return true;
        }
        return false;
    };

    this.getLevels = function() {
        var res = [];
        for (var i = 0; i < _branches.length; i++) {
            res = res.concat(_branches[i].getLevels());
        }
        return res;
    };

    /* Returns all entrances/exits for the dungeon.*/
    this.getEntrances = function() {
        var res = [];
        for (var i = 0; i < _branches.length; i++) {
            res.push(_branches[i].getEntrance());
        }
        return res;
    };

    /* Connects two branches b1 and b2 together from specified levels l1 and l2.
     * */
    this.connectBranches = function(b1, b2, l1, l2) {
        if (this.hasBranch(b1) && this.hasBranch(b2)) {
            var down = true;
            if (l1 > l2) {down = false;}
            var stairs = new RG.Element.Stairs(down);
            var b2Levels = b2.getLevels();
            if (l2 < b2Levels.length) {
                var cell = b2Levels[l2].getFreeRandCell();
                b2Levels[l2].addStairs(stairs, cell.getX(), cell.getY());
                b1.connectLevelToStairs(l1, stairs);
            }
            else {
                RG.err('World.Dungeon', 'connectBranches',
                    'Level ' + l2 + " doesn't exist in branch " + b2.getName());
            }
        }
        else {
            RG.err('World.Dungeon', 'connectBranches',
                'Branches must be added to dungeon before connection.');
        }
    };

};

/* Area-tile is a level which has entry/exit points on a number of edges.*/
RG.World.AreaTile = function(x, y, area) {

    var _tileX = x;
    var _tileY = y;
    var _area = area;

    this.cols = null;
    this.rows = null;

    var _level = null;

    /* Sets the level for this tile.*/
    this.setLevel = function(level) {
        _level = level;
        this.cols = _level.getMap().cols;
        this.rows = _level.getMap().rows;
    };

    this.getLevel = function() {return _level;};

    this.getLevel = function() {return _level;};
    this.getTileX = function() {return _tileX;};
    this.getTileY = function() {return _tileY;};

    /* Returns true for edge tiles.*/
    this.isEdge = function() {
        if (this.isNorthEdge()) {return true;}
        if (this.isSouthEdge()) {return true;}
        if (this.isWestEdge()) {return true;}
        if (this.isEastEdge()) {return true;}
        return false;
    };

    this.isNorthEdge = function() {return _tileY === 0;};
    this.isSouthEdge = function() {return _tileY === (_area.getMaxY() - 1);};
    this.isWestEdge = function() {return _tileX === 0;};
    this.isEastEdge = function() {return _tileY === (_area.getMaxY() - 1);};

    /* Connect this tile to east and south tiles */
    this.connect = function(eastTile, southTile) {
        var lastX = this.cols - 1;
        var lastY = this.rows - 1;

        // Connect to east tile
        if (!RG.isNullOrUndef([eastTile])) {
            var levelEast = eastTile.getLevel();
            const map = _level.getMap();
            var mapEast = levelEast.getMap();

            for (var y = 1; y <= lastY - 1; y++) {
                const cell = map.getCell(lastX, y);
                var cellEast = mapEast.getCell(0, y);

                if (cell.isFree() && cellEast.isFree()) {
                    const stairs = new Stairs(true, _level, levelEast);
                    var stairsEast = new Stairs(false, levelEast, _level);
                    stairs.setTargetStairs(stairsEast);
                    stairsEast.setTargetStairs(stairs);

                    _level.addStairs(stairs, lastX, y);
                    levelEast.addStairs(stairsEast, 0, y);
                }
            }

        }

        // Connect to south tile
        if (!RG.isNullOrUndef([southTile])) {
            var levelSouth = southTile.getLevel();
            const map = _level.getMap();
            var mapSouth = levelSouth.getMap();

            for (var x = 1; x <= lastX - 1; x++) {
                const cell = map.getCell(x, lastY);
                var cellSouth = mapSouth.getCell(x, 0);

                if (cell.isFree() && cellSouth.isFree()) {
                    const stairs = new Stairs(true, _level, levelSouth);
                    var stairsSouth = new Stairs(false, levelSouth, _level);
                    stairs.setTargetStairs(stairsSouth);
                    stairsSouth.setTargetStairs(stairs);
                    _level.addStairs(stairs, x, lastY);
                    levelSouth.addStairs(stairsSouth, x, 0);
                }
            }
        }
    };
};

/* Area is N x M area of tiles, with no linear progression like in dungeons.
 * Moving between tiles of areas happens by travelling to the edges of a tile.
 * Each tile is a level with special edge tiles.
 * */
RG.World.Area = function(name, maxX, maxY) {

    var _name = name;
    this.getName = function() {return _name;};

    var _maxX = maxX;
    var _maxY = maxY;

    this.getMaxX = () => (_maxX);
    this.getMaxY = () => (_maxY);
    const _tiles = [];

    this._init = function() {
        // Create the tiles
        for (let x = 0; x < _maxX; x++) {
            const tileColumn = [];
            for (let y = 0; y < _maxY; y++) {
                const newTile = new RG.World.AreaTile(x, y, this);
                const level = RG.FACT.createLevel('ruins', 30, 30, {});
                newTile.setLevel(level);
                tileColumn.push(newTile);
            }
            _tiles.push(tileColumn);
        }

        // Connect the tiles
        for (let x = 0; x < _maxX; x++) {
            for (let y = 0; y < _maxY; y++) {
                if (x < _maxX - 1 && y < _maxY - 1) {
                    _tiles[x][y].connect(_tiles[x + 1][y], _tiles[x][y + 1]);
                }
                else if (x < _maxX - 1) {
                    _tiles[x][y].connect(_tiles[x + 1][y], null);
                }
                else if (y < _maxY - 1) {
                    _tiles[x][y].connect(null, _tiles[x][y + 1]);
                }
            }
        }
    };

    this._init();

    this.getMaxX = function() {return _maxX;};
    this.getMaxY = function() {return _maxY;};

    this.getLevels = function() {
        var res = [];
        for (let x = 0; x < _tiles.length; x++) {
            for (let y = 0; y < _tiles[x].length; y++) {
                res.push(_tiles[x][y].getLevel());
            }
        }
        return res;
    };

    this.getTiles = function() {
        return _tiles;
    };

};

/* Factory object for creating worlds and features. */
RG.World.Factory = function() {

    this.createArea = function(conf) {
        const area = new RG.World.Area('testArea', 4, 4);
    };

    this.createDungeon = function(conf) {
        console.log(conf);
    };

};

/* Largest place structure. Contains a number of area and dungeons. */
RG.World.World = function(conf) {

    if (RG.isNullOrUndef([conf])) {
        RG.err('World.World', '', 'No configuration given.');
        return;
    }

    var _fact = new RG.World.Factory();

    var _areas = [];
    var _dungeons = [];

    var nAreas = conf.nAreas;
    var nDungeons = conf.nDungeons;

    for (var i = 0; i < nAreas; i++) {
        var area = _fact.createArea(conf);
        _areas.push(area);
    }

    for (var j = 0; j < nDungeons; j++) {
        var dungeon = _fact.createDungeon(conf);
        _dungeons.push(dungeon);
    }

    // Connect areas and dungeons

};

module.exports = RG.World;
<|endoftext|>


<commit_before>var geojsonRandom = require('geojson-random'),
    geojsonExtent = require('geojson-extent'),
    http = require('http');
// var $ = require('jquery'),
//     XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
// $.support.cors = true;

module.exports.clear = function(context) {
    context.data.clear();
};

module.exports.random = function(context, count, type) {
    context.data.mergeFeatures(geojsonRandom(count, type).features, 'meta');
};

module.exports.bboxify = function(context) {
    context.data.set({ map: geojsonExtent.bboxify(context.data.get('map')) });
};

module.exports.otpify = function(context) {
    // context.data.set({ map: otpify(context.data.get('map')) });
    var features = context.data.get('map').features;
    console.log(features);
    $.each(features, function(i, feature){
      if (feature.geometry.type === 'Point'){
        feature.properties.url = 'http://opentrip.atlantaregion.com/otp-leaflet-client/?module=planner&fromPlace='+feature.geometry.coordinates[1]+','+feature.geometry.coordinates[0]+'&toPlace='+features[features.length - 1].geometry.coordinates[1]+','+features[features.length - 1].geometry.coordinates[0]+'&mode=TRANSIT%2CWALK&maxWalkDistance=3218.688&arriveBy=false&showIntermediateStops=false&itinIndex=0';
      }
    });
    context.data.set({});
};
var request = require('request');
var getJsonFromJsonP = function (url, callback) {
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var jsonpData = body;
    var json;
    //if you don't know for sure that you are getting jsonp, then i'd do something like this
    try
    {
       json = JSON.parse(jsonpData);
    }
    catch(e)
    {
        var startPos = jsonpData.indexOf('({');
        var endPos = jsonpData.indexOf('})');
        var jsonString = jsonpData.substring(startPos+1, endPos+1);
        json = JSON.parse(jsonString);
    }
    callback(null, json);
  } else {
    callback(error);
  }
})
}
module.exports.isochrones = function(context) {
	console.log(context.data.get('map'));
  var map = context.data.get('map')
  // var features = map.features;
  var isochrones = [];
  var geojson;
  var features = [];
  var geoLayer;
	var options = {
	  host: 'opentrip.atlantaregion.com',
	  // port: 80,
	  path: '/otp-rest-servlet/ws/plan?&fromPlace=33.87725673930016%2C-84.46014404296875&toPlace=33.74946419232578%2C-84.38873291015625&time=1%3A13pm&date=03-21-2014&mode=TRANSIT%2CWALK&maxWalkDistance=750&arriveBy=false&showIntermediateStops=false&itinIndex=0&callback=?',
	  // headers: {'dataType': 'jsonp'}
	};
  console.log(context)
    $.each(map.features, function(i, feature){
      var url = 'http://opentrip.atlantaregion.com' + '/otp-rest-servlet/ws/isochrone?algorithm%20=accSampling&fromPlace='+ feature.geometry.coordinates[1] + ',' + feature.geometry.coordinates[0]+'&date=2014/06/16&time=12:00:00&maxWalkDistance=1000&mode=WALK,TRANSIT&cutoffSec=1800';
      $.ajax({
          url: url,
          type: "GET",
          dataType: "jsonp",
          success: function( data ) {
            geojson = data;
            features.push(geojson.features);
            // geoLayer = L.geoJson(geojson, {

            //   style: function (feature) {
            //     switch (feature.properties.Time) {
            //             case 1800: return {fillColor: "#ff0000", fillOpacity: 0.1, weight: 0};
            //             // case 3600:   return {fillColor: "#0000ff", weight: 0};
            //         }
            //   },

            //   // onEachFeature: onEachFeature,

            //   pointToLayer: function (feature, latlng) {
            //     return L.circleMarker(latlng, {
            //       radius: 8,
            //       fillColor: "#ff7800",
            //       color: "#000",
            //       weight: 1,
            //       opacity: 1,
            //       fillOpacity: 0.8
            //     });
            //   }
            // }).addTo(window.api.map);

            console.log(data)
            context.data.mergeFeatures(geojson.features, 'map');
          }
      });
      // if (i === map.features.length -1){
      //   console.log(features)
      //   context.data.mergeFeatures(features, 'map');
      // }
    });

};<commit_msg>commented out adding to dataset<commit_after>var geojsonRandom = require('geojson-random'),
    geojsonExtent = require('geojson-extent'),
    http = require('http');
// var $ = require('jquery'),
//     XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
// $.support.cors = true;

module.exports.clear = function(context) {
    context.data.clear();
};

module.exports.random = function(context, count, type) {
    context.data.mergeFeatures(geojsonRandom(count, type).features, 'meta');
};

module.exports.bboxify = function(context) {
    context.data.set({ map: geojsonExtent.bboxify(context.data.get('map')) });
};

module.exports.otpify = function(context) {
    // context.data.set({ map: otpify(context.data.get('map')) });
    var features = context.data.get('map').features;
    console.log(features);
    $.each(features, function(i, feature){
      if (feature.geometry.type === 'Point'){
        feature.properties.url = 'http://opentrip.atlantaregion.com/otp-leaflet-client/?module=planner&fromPlace='+feature.geometry.coordinates[1]+','+feature.geometry.coordinates[0]+'&toPlace='+features[features.length - 1].geometry.coordinates[1]+','+features[features.length - 1].geometry.coordinates[0]+'&mode=TRANSIT%2CWALK&maxWalkDistance=3218.688&arriveBy=false&showIntermediateStops=false&itinIndex=0';
      }
    });
    context.data.set({});
};
var request = require('request');
var getJsonFromJsonP = function (url, callback) {
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var jsonpData = body;
    var json;
    //if you don't know for sure that you are getting jsonp, then i'd do something like this
    try
    {
       json = JSON.parse(jsonpData);
    }
    catch(e)
    {
        var startPos = jsonpData.indexOf('({');
        var endPos = jsonpData.indexOf('})');
        var jsonString = jsonpData.substring(startPos+1, endPos+1);
        json = JSON.parse(jsonString);
    }
    callback(null, json);
  } else {
    callback(error);
  }
})
}
module.exports.isochrones = function(context) {
	console.log(context.data.get('map'));
  var map = context.data.get('map')
  // var features = map.features;
  var isochrones = [];
  var geojson;
  var features = [];
  var geoLayer;
	var options = {
	  host: 'opentrip.atlantaregion.com',
	  // port: 80,
	  path: '/otp-rest-servlet/ws/plan?&fromPlace=33.87725673930016%2C-84.46014404296875&toPlace=33.74946419232578%2C-84.38873291015625&time=1%3A13pm&date=03-21-2014&mode=TRANSIT%2CWALK&maxWalkDistance=750&arriveBy=false&showIntermediateStops=false&itinIndex=0&callback=?',
	  // headers: {'dataType': 'jsonp'}
	};
  console.log(context)
    $.each(map.features, function(i, feature){
      var url = 'http://opentrip.atlantaregion.com' + '/otp-rest-servlet/ws/isochrone?algorithm%20=accSampling&fromPlace='+ feature.geometry.coordinates[1] + ',' + feature.geometry.coordinates[0]+'&date=2014/06/16&time=12:00:00&maxWalkDistance=1000&mode=WALK,TRANSIT&cutoffSec=1800';
      $.ajax({
          url: url,
          type: "GET",
          dataType: "jsonp",
          success: function( data ) {
            geojson = data;
            features.push(geojson.features);
            geoLayer = L.geoJson(geojson, {

              style: function (feature) {
                switch (feature.properties.Time) {
                        case 1800: return {fillColor: "#ff0000", fillOpacity: 0.1, weight: 0};
                        // case 3600:   return {fillColor: "#0000ff", weight: 0};
                    }
              },

              // onEachFeature: onEachFeature,

              pointToLayer: function (feature, latlng) {
                return L.circleMarker(latlng, {
                  radius: 8,
                  fillColor: "#ff7800",
                  color: "#000",
                  weight: 1,
                  opacity: 1,
                  fillOpacity: 0.8
                });
              }
            }).addTo(window.api.map);

            console.log(data)

            // adds data into dataset
            // context.data.mergeFeatures(geojson.features, 'map');
          }
      });
    });

};<|endoftext|>


<commit_before>// Given a collection of distinct numbers, return all possible permutations.

// For example,
// [1,2,3] have the following permutations:
// [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

// Logic
// create a result array to push our permutations in and return
// create a get getPermutations function that takes in an array, and our input
  // create a base case, if input array is empty push copy of current array into result
  // if input array is not empty, loop through input array
  // else
    // create a copy of our input array for our next input
    // push the item of the inputArr that the for loop is on, into the currentArr
    // splice the index of the nextInput array
    // run the getPermutations function on the current array and nextInput array
    // pop last array in current array

  // run get permutations function on an empty arr and nums or our input
  // return result

var permute = function(nums) { // 144ms runtime
    var result = [];
    //nums are distinct numbers.
    function getPermutations (currentArray, inputArr) {
        var inputLength = inputArr.length;
        if ( inputLength < 1 ) {
            result.push( currentArray.slice() ); //Here we must do a copy. Because an array is an object,
                                                // every time we're passing its reference into a new function.
        } else {
            for ( var i = 0; i < inputLength; i++) {
                var nextInput = inputArr.slice(); //Same reason, array is object, copy is needed.
                currentArray.push( inputArr[i] );
                nextInput.splice( i, 1 );
                getPermutations ( currentArray, nextInput );
                currentArray.pop();
            }
        }
    }
    getPermutations( [], nums );
    return result;
};

// ------------------------------------
// Backtracking

var permute = function( nums, l=0, result=[] ){ // 122ms runtime
    if( l >= nums.length ){
        var arr = nums.slice();
        result.push( arr );
    } else {
        for ( var i = l; i < nums.length; i++ ){
            var temp = nums[l]; // swap
            nums[l] = nums[i];
            nums[i] = temp;
            permute( nums, l+1, result );
            temp = nums[l]; // swap back
            nums[l] = nums[i];
            nums[i] = temp;
        }
    }
    return result;
};
console.log(perme)

// ----------------------------------------------------------

function swap (nums, index1, index2) {
  var temp = nums[index1];
  nums[index1] = nums[index2];
  nums[index2] = temp;
  return nums;
}

var permute = function( nums, startIndex=0, endIndex=nums.length-1) {
  if (startIndex === endIndex) {
     console.log(nums);
  } else {
        for (var i = startIndex; i <= endIndex; i++) {
          swap(nums, startIndex, i );
          permute(nums, startIndex + 1, endIndex);
          swap(nums, i, startIndex); // backtrack
        }
  }
}; // output is console.log

<commit_msg>syntax<commit_after>// Given a collection of distinct numbers, return all possible permutations.

// For example,
// [1,2,3] have the following permutations:
// [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

// Logic
// create a result array to push our permutations in and return
// create a get getPermutations function that takes in an array, and our input
  // create a base case, if input array is empty push copy of current array into result
  // if input array is not empty, loop through input array
  // else
    // create a copy of our input array for our next input
    // push the item of the inputArr that the for loop is on, into the currentArr
    // splice the index of the nextInput array
    // run the getPermutations function on the current array and nextInput array
    // pop last array in current array

  // run get permutations function on an empty arr and nums or our input
  // return result

var permute = function(nums) { // 144ms runtime
    var result = [];
    //nums are distinct numbers.
    function getPermutations(currentArray, inputArr) {
        var inputLength = inputArr.length;
        if ( inputLength < 1 ) {
            result.push( currentArray.slice() ); //Here we must do a copy. Because an array is an object,
                                                // every time we're passing its reference into a new function.
        } else {
            for ( var i = 0; i < inputLength; i++) {
                var nextInput = inputArr.slice(); //Same reason, array is object, copy is needed.
                currentArray.push( inputArr[i] );
                nextInput.splice( i, 1 );
                getPermutations( currentArray, nextInput );
                currentArray.pop();
            }
        }
    }
    getPermutations( [], nums );
    return result;
};

// ------------------------------------
// Backtracking

var permute = function( nums, l=0, result=[] ){ // 122ms runtime
    if( l >= nums.length ){
        var arr = nums.slice();
        result.push( arr );
    } else {
        for ( var i = l; i < nums.length; i++ ){
            var temp = nums[l]; // swap
            nums[l] = nums[i];
            nums[i] = temp;
            permute( nums, l+1, result );
            temp = nums[l]; // swap back
            nums[l] = nums[i];
            nums[i] = temp;
        }
    }
    return result;
};
console.log(perme)

// ----------------------------------------------------------

function swap (nums, index1, index2) {
  var temp = nums[index1];
  nums[index1] = nums[index2];
  nums[index2] = temp;
  return nums;
}

var permute = function( nums, startIndex=0, endIndex=nums.length-1) {
  if (startIndex === endIndex) {
     console.log(nums);
  } else {
        for (var i = startIndex; i <= endIndex; i++) {
          swap(nums, startIndex, i );
          permute(nums, startIndex + 1, endIndex);
          swap(nums, i, startIndex); // backtrack
        }
  }
}; // output is console.log

<|endoftext|>


<commit_before>var parsers = require('./parsers'),
    zlib = require('zlib'),
    utils = require('./utils'),
    parseUrl = require('url').parse,
    uuid = require('node-uuid'),
    http = {http: require('http'), https: require('https')};

module.exports.version = '0.2.0-dev';

var Client = function Client(dsn, options) {
    options = options || {};
    this.dsn = utils.parseDSN(dsn);
    this.name = options.name || require('os').hostname();
    this.site = options.site;
    this.root = options.root || process.cwd();
    if(!process.env.NODE_ENV || !(process.env.NODE_ENV == 'production' || process.env.NODE_ENV == 'test')) {
        console.log('Warning: Sentry logging is disabled, please set NODE_ENV=production');
        this._enabled = false;
    } else {
        this._enabled = true;
    }
}, _ = Client.prototype;

module.exports.Client = Client;

_.getIdent =
_.get_ident = function getIdent(result) {
    return result.id+'$'+result.checksum;
};

_.process = function process(kwargs) {
    var event_id = uuid().replace(/-/g, ''),
        checksum;

    kwargs['modules'] = utils.getModules();
    kwargs['server_name'] = kwargs['server_name'] || this.name;
    kwargs['extra'] = kwargs['extra'] || {};

    if(!kwargs['checksum']){
        checksum = kwargs['checksum'] = utils.constructChecksum(kwargs);
    } else {
        checksum = kwargs['checksum'];
    }

    kwargs['event_id'] = event_id;
    kwargs['timestamp'] = new Date().toISOString().split('.')[0];
    kwargs['project'] = this.dsn.project_id;
    kwargs['site'] = kwargs['site'] || this.site;

    // this will happen asynchronously. We don't care about it's response.
    this._enabled && this.send(kwargs);

    return {'id': event_id, 'checksum': checksum};
};

_.sendRemote = function sendRemote(message, headers, cb) {
    var self = this;
    var options = {
        host: self.dsn.host,
        path: self.dsn.path + '/api/store/',
        headers: headers,
        method: 'POST'
    }, req = http[self.dsn.protocol].request(options, function(res){
        res.setEncoding('utf8');
        res.on('data', function(data) {
            // don't care!
        });
    });
    req.on('error', function(e){
        // do we care?
    });
    req.end(message);
};

_.send = function send(kwargs) {
    var self = this;
    zlib.deflate(JSON.stringify(kwargs), function(err, buff) {
        var message = buff.toString('base64'),
            timestamp = new Date().getTime(),
            signature = utils.getSignature(self.dsn.private_key, message, timestamp),
            headers = {
                'X-Sentry-Auth': utils.getAuthHeader(signature, timestamp, self.dsn.public_key, self.dsn.project_id),
                'Content-Type': 'application/octet-stream',
                'Content-Length': message.length
            };

        self.sendRemote(message, headers);
    });
};

_.createFromText =
_.create_from_text = function createFromText(message, kwargs, cb) {
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    var result = this.process(parsers.parseText(message, kwargs));
    cb && cb(result);
    return result;
};

_.createFromError =
_.create_from_exception =
_.create_from_error = function createFromError(err, kwargs, cb) {
    var self = this;
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    parsers.parseError(err, kwargs, function(kw) {
        var result = self.process(kw);
        cb && cb(result);
    });
};

_.createFromQuery =
_.create_from_query = function createFromQuery(query, engine, kwargs, cb) {
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    var result = this.process(parsers.parseQuery(query, engine, kwargs));
    cb && cb(result);
    return result;
};

_.patchGlobal = function patchGlobal() {
    module.exports.patchGlobal(this);
};

module.exports.patchGlobal =
module.exports.patch_global = function patchGlobal(client) {
    var util = require('util');
    client = (client instanceof Client) ? client : new Client(client);
    process.on('uncaughtException', function(err) {
        client.createFromError(err, function(result) {
            util.log('uncaughtException: '+client.get_ident(result));
        });
    });
};
<commit_msg>Add node.js version to the "extra" key.<commit_after>var parsers = require('./parsers'),
    zlib = require('zlib'),
    utils = require('./utils'),
    parseUrl = require('url').parse,
    uuid = require('node-uuid'),
    http = {http: require('http'), https: require('https')};

module.exports.version = '0.2.0-dev';

var Client = function Client(dsn, options) {
    options = options || {};
    this.dsn = utils.parseDSN(dsn);
    this.name = options.name || require('os').hostname();
    this.site = options.site;
    this.root = options.root || process.cwd();
    if(!process.env.NODE_ENV || !(process.env.NODE_ENV == 'production' || process.env.NODE_ENV == 'test')) {
        console.log('Warning: Sentry logging is disabled, please set NODE_ENV=production');
        this._enabled = false;
    } else {
        this._enabled = true;
    }
}, _ = Client.prototype;

module.exports.Client = Client;

_.getIdent =
_.get_ident = function getIdent(result) {
    return result.id+'$'+result.checksum;
};

_.process = function process(kwargs) {
    var event_id = uuid().replace(/-/g, ''),
        checksum;

    kwargs['modules'] = utils.getModules();
    kwargs['server_name'] = kwargs['server_name'] || this.name;
    kwargs['extra'] = kwargs['extra'] || {};
    kwargs['extra']['node'] = process.version;

    if(!kwargs['checksum']){
        checksum = kwargs['checksum'] = utils.constructChecksum(kwargs);
    } else {
        checksum = kwargs['checksum'];
    }

    kwargs['event_id'] = event_id;
    kwargs['timestamp'] = new Date().toISOString().split('.')[0];
    kwargs['project'] = this.dsn.project_id;
    kwargs['site'] = kwargs['site'] || this.site;

    // this will happen asynchronously. We don't care about it's response.
    this._enabled && this.send(kwargs);

    return {'id': event_id, 'checksum': checksum};
};

_.sendRemote = function sendRemote(message, headers, cb) {
    var self = this;
    var options = {
        host: self.dsn.host,
        path: self.dsn.path + '/api/store/',
        headers: headers,
        method: 'POST'
    }, req = http[self.dsn.protocol].request(options, function(res){
        res.setEncoding('utf8');
        res.on('data', function(data) {
            // don't care!
        });
    });
    req.on('error', function(e){
        // do we care?
    });
    req.end(message);
};

_.send = function send(kwargs) {
    var self = this;
    zlib.deflate(JSON.stringify(kwargs), function(err, buff) {
        var message = buff.toString('base64'),
            timestamp = new Date().getTime(),
            signature = utils.getSignature(self.dsn.private_key, message, timestamp),
            headers = {
                'X-Sentry-Auth': utils.getAuthHeader(signature, timestamp, self.dsn.public_key, self.dsn.project_id),
                'Content-Type': 'application/octet-stream',
                'Content-Length': message.length
            };

        self.sendRemote(message, headers);
    });
};

_.createFromText =
_.create_from_text = function createFromText(message, kwargs, cb) {
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    var result = this.process(parsers.parseText(message, kwargs));
    cb && cb(result);
    return result;
};

_.createFromError =
_.create_from_exception =
_.create_from_error = function createFromError(err, kwargs, cb) {
    var self = this;
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    parsers.parseError(err, kwargs, function(kw) {
        var result = self.process(kw);
        cb && cb(result);
    });
};

_.createFromQuery =
_.create_from_query = function createFromQuery(query, engine, kwargs, cb) {
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    var result = this.process(parsers.parseQuery(query, engine, kwargs));
    cb && cb(result);
    return result;
};

_.patchGlobal = function patchGlobal() {
    module.exports.patchGlobal(this);
};

module.exports.patchGlobal =
module.exports.patch_global = function patchGlobal(client) {
    var util = require('util');
    client = (client instanceof Client) ? client : new Client(client);
    process.on('uncaughtException', function(err) {
        client.createFromError(err, function(result) {
            util.log('uncaughtException: '+client.get_ident(result));
        });
    });
};
<|endoftext|>


<commit_before>
// CREDIT
// http://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string

// URL.createObjectURL
window.URL = window.URL || window.webkitURL;

// Dependencies
// var co        = require('co');
var Promise   = require('promise-polyfill');
var setAsap   = require('setasap');
    Promise._setImmediateFn(setAsap);

var estupendoWrapper = function estupendoWrapper(){

    var fn /* @@@ */;

    // Register message handler
    onmessage = function(msg){

        // Return module source
        postMessage(fn.apply({}, msg.data));

        // Terminate the worker
        close();
    };
};

var buildBlob = function(blob){
    "use strict";

    try {
        return new window.Blob([blob], {type: 'application/javascript'});
    } catch (e) {

        // Backwards-compatibility
        window.BlobBuilder = window.BlobBuilder
            || window.WebKitBlobBuilder
            || window.MozBlobBuilder;

        // Blob setup
        blob = new window.BlobBuilder();
        blob.append(response);
        blob = blob.getBlob();

        return blob;
    }
};

var buildWorkerSrc = function(fnSrc){
    "use strict";

    // Setup
    var workerSrc = [];
    var wrapSrc = estupendoWrapper.toString()
        .replace("fn /* @@@ */", "fn = " + fnSrc);
        // .replace('onmessage = null;', 'onmessage = ' + fnSrc.slice(0, -1))
        // .replace('/* @@@ DO NOT REMOVE*/', '};');

    workerSrc.push("// Estupendo Web Worker\n");
    workerSrc.push("(");
    workerSrc.push(wrapSrc);
    workerSrc.push(")();");

    // console.log(workerSrc.join(''));

    return workerSrc.join('');
};

module.exports = function(fnSrc, args){
    "use strict";

    // Setup
    var timeout = 7000;

    // Launch worker
    var workerSrc  = buildWorkerSrc(fnSrc);
    var workerBlob = buildBlob(workerSrc);
    var worker     = new Worker(window.URL.createObjectURL(workerBlob));

    // Args must be an array
    args = (Array.isArray(args))? args : [args];

    // Return a promise
    return new Promise(function(resolve, reject){

        // Register message handler
        worker.onmessage = resolve;

        // XXX
        // console.log('riww args', args);

        // SEnd params to worker
        worker.postMessage(args);

        // Setup timeout
        setTimeout(function(){
            var error = new Error('riww ERROR: Async request worker timed out', arguments);
            worker.terminate();
            reject(error);
        }, timeout);
    });
};<commit_msg>refactor<commit_after><|endoftext|>


<commit_before>var http          = require("http");
var path          = require("path");
var paperboy      = require("paperboy");
var B             = require("buster-core");
var testServer    = require("./middleware");
var cli           = require("buster-cli");
var DOCUMENT_ROOT = path.join(__dirname, "../public");

function servePublicFiles(documentRoot, req, res) {
    paperboy
        .deliver(documentRoot, req, res)
        .addHeader("Expires", 300)
        .error(function(statCode, msg) {
            res.writeHead(statCode, { "Content-Type": "text/plain" });
            res.end("Error " + statCode);
        })
        .otherwise(function(err) {
            res.writeHead(404, { "Content-Type": "text/plain" });
            res.end("Error 404: File not found");
        });
}

module.exports = {
    create: function (stdout, stderr, options) {
        options = options || {};

        var c = cli.create(options);
        var logger = c.createLogger(stdout, stderr);

        c.addHelpOption(options.missionStatement, options.description);

        return B.extend(B.create(this), {
            cli: c,
            logger: logger,
            documentRoot: options.documentRoot || DOCUMENT_ROOT,
            templateRoot: options.templateRoot,
            name: options.name,
            binary: options.binary,
            unexpectedErrorMessage: options.unexpectedErrorMessage,
            phantom: options.phantom || require('phantom')
        });
    },

    run: function (args, callback) {
        callback = callback || function () {};

        this.loadOptions();
        this.cli.parseArgs(args, function (err, options) {
            if (this.cli.loggedHelp) {
                return callback();
            }

            try {
                var port = options["--port"].value;
                var binding = options["--binding"].value;
                var server = this.createServer(port, binding);
                process.nextTick(function () {
                    var serverUrl = "http://localhost:" + port;

                    callback(null, server);

                    this.logger.log(this.binary + " running on " + serverUrl);

                    if(options['--capture-headless'].isSet) {
                        this.captureHeadlessBrowser(serverUrl)

                    }
                }.bind(this));
            } catch (e) {
                this.handleError(e);
                callback(e);
            }
        }.bind(this));
    },

    createServer: function (port, binding) {
        var middleware, documentRoot = this.documentRoot;
        var httpServer = http.createServer(function (req, res) {
            if (middleware.respond(req, res)) { return; }
            servePublicFiles(documentRoot, req, res);
        });
        httpServer.on("error", B.bind(this, "handleError"));
        httpServer.listen(port, binding);
        middleware = testServer.create(httpServer, {
            logger: this.logger,
            templateRoot: this.templateRoot,
            name: this.name
        });
        return httpServer;
    },

    captureHeadlessBrowser: function(serverUrl) {
        var self = this;

        this.logger.log('Starting headless browser...');

        phantom.create(function(ph) {
            ph.createPage(function(page) {
                page.open(serverUrl + '/capture');
                self.logger.log('Browser was captured.');
            });
        });
    },

    loadOptions: function () {
        this.cli.opt(["-p", "--port"], {
            description: "The port to run the server on",
            defaultValue: 1111,
            validators: [this.cli.validators.integer()],
            transform: function (value) { return parseInt(value, 10); }
        });

        this.cli.opt(["-b", "--binding"], {
            description: "The address to bind the server to",
            hasValue: true
        });

        this.cli.opt(['-c', '--capture-headless'], {
            description: "Captures a headless webkit browser after the server was started."
        });
    },

    handleError: function (err) {
        if (/EADDRINUSE/.test(err.message)) {
            this.cli.err("Address already in use. Pick another " +
                         "port with -p/--port to start " + this.binary);
        } else {
            this.cli.err(this.unexpectedErrorMessage + err.stack);
        }
    }
};
<commit_msg>extracted capture logic<commit_after>var http          = require("http");
var path          = require("path");
var paperboy      = require("paperboy");
var B             = require("buster-core");
var testServer    = require("./middleware");
var cli           = require("buster-cli");
var DOCUMENT_ROOT = path.join(__dirname, "../public");

function servePublicFiles(documentRoot, req, res) {
    paperboy
        .deliver(documentRoot, req, res)
        .addHeader("Expires", 300)
        .error(function(statCode, msg) {
            res.writeHead(statCode, { "Content-Type": "text/plain" });
            res.end("Error " + statCode);
        })
        .otherwise(function(err) {
            res.writeHead(404, { "Content-Type": "text/plain" });
            res.end("Error 404: File not found");
        });
}

module.exports = {
    create: function (stdout, stderr, options) {
        options = options || {};

        var c = cli.create(options);
        var logger = c.createLogger(stdout, stderr);

        c.addHelpOption(options.missionStatement, options.description);

        return B.extend(B.create(this), {
            cli: c,
            logger: logger,
            documentRoot: options.documentRoot || DOCUMENT_ROOT,
            templateRoot: options.templateRoot,
            name: options.name,
            binary: options.binary,
            unexpectedErrorMessage: options.unexpectedErrorMessage,
            phantom: options.phantom || require('phantom')
        });
    },

    run: function (args, callback) {
        callback = callback || function () {};

        this.loadOptions();
        this.cli.parseArgs(args, function (err, options) {
            if (this.cli.loggedHelp) {
                return callback();
            }

            try {
                var port = options["--port"].value;
                var binding = options["--binding"].value;
                var server = this.createServer(port, binding);

                process.nextTick(function () {
                    var serverUrl = "http://localhost:" + port;

                    if(options['--capture-headless'].isSet) {
                        this.captureHeadlessBrowser(serverUrl);
                    }

                    callback(null, server);

                    this.logger.log(this.binary + " running on " + serverUrl);
                }.bind(this));
            } catch (e) {
                this.handleError(e);
                callback(e);
            }
        }.bind(this));
    },

    createServer: function (port, binding) {
        var middleware, documentRoot = this.documentRoot;
        var httpServer = http.createServer(function (req, res) {
            if (middleware.respond(req, res)) { return; }
            servePublicFiles(documentRoot, req, res);
        });
        httpServer.on("error", B.bind(this, "handleError"));
        httpServer.listen(port, binding);
        middleware = testServer.create(httpServer, {
            logger: this.logger,
            templateRoot: this.templateRoot,
            name: this.name
        });
        return httpServer;
    },

    captureHeadlessBrowser: function(serverUrl) {
        var self = this;

        this.logger.log('Starting headless browser...');
        this.phantom.create(function(ph) {
            ph.createPage(function(page) {
                page.open(serverUrl + '/capture');
                self.logger.log('Browser was captured.');
            });
        });
    },

    loadOptions: function () {
        this.cli.opt(["-p", "--port"], {
            description: "The port to run the server on",
            defaultValue: 1111,
            validators: [this.cli.validators.integer()],
            transform: function (value) { return parseInt(value, 10); }
        });

        this.cli.opt(["-b", "--binding"], {
            description: "The address to bind the server to",
            hasValue: true
        });

        this.cli.opt(['-c', '--capture-headless'], {
            description: "Captures a headless webkit browser after the server was started."
        });
    },

    handleError: function (err) {
        if (/EADDRINUSE/.test(err.message)) {
            this.cli.err("Address already in use. Pick another " +
                         "port with -p/--port to start " + this.binary);
        } else {
            this.cli.err(this.unexpectedErrorMessage + err.stack);
        }
    }
};
<|endoftext|>


<commit_before>import assign from 'lodash.assign';
import omit from 'lodash.omit';

import * as actions from 'src/actions';
import PaginatorError from 'src/paginator-error';

export const errors = Object.freeze({
  calculateOffsetNoLimit: 'Can\'t calculate offsets without a limit',
  calculatePageNoLimit: 'Can\'t calculate pages without a limit'
});

const defaultOptions = {
  limitQueryParam: 'limit',
  offsetQueryParam: 'offset'
};

export class LimitOffsetQueryHandler {
  constructor(options) {
    this._excessParams = null;
    this._limit = null;
    this.setOptions(options);
  }

  makeParams(page) {
    const opts = this._options;
    const queryParams = assign({}, this._excessParams);

    queryParams[opts.limitQueryParam] = this._limit;
    queryParams[opts.offsetQueryParam] = this._calculateOffset(page);

    return queryParams;
  }

  resolvePage(queryParams) {
    const result = this._parse(queryParams);

    if (!this._limit) {
      this._limit = result.limit;
    }

    return this._calculatePage(result.offset);
  }

  setParams(queryParams) {
    const result = this._parse(queryParams);
    this._excessParams = result.excess;
    this._limit = result.limit;

    return this;
  }

  onResponse(response) {
    const result = actions.parseResponse(response);

    if (!this._limit) {
      this._limit = result.limit;
    }
  }

  setOptions(options) {
    this._options = assign({}, defaultOptions, options);

    return this;
  }

  _parse(queryParams) {
    const {limitQueryParam, offsetQueryParam} = this._options;
    const defaults = {
      limit: null,
      offset: 0
    };
    const result = assign({}, defaults);

    if (queryParams.hasOwnProperty(limitQueryParam)) {
      result.limit = queryParams[limitQueryParam];
    }
    if (queryParams.hasOwnProperty(offsetQueryParam)) {
      result.offset = queryParams[offsetQueryParam];
    }

    result.excess = this._getExcess(queryParams);

    return result;
  }

  _getExcess(queryParams) {
    const opts = this._options;
    const paginationProperties = [
      opts.limitQueryParam,
      opts.offsetQueryParam
    ];

    return omit(queryParams, paginationProperties);
  }

  _calculateOffset(page) {
    const limit = this._limit;

    if (page === 1) {
      return 0;
    }
    if (!limit) {
      throw new PaginatorError(errors.calculateOffsetNoLimit);
    }

    return limit * page - limit;
  }

  _calculatePage(offset) {
    const limit = this._limit;

    if (offset === 0) {
      return 1;
    }
    if (!limit) {
      throw new PaginatorError(errors.calculatePageNoLimit);
    }

    return (offset + limit) / limit;
  }
}

export default LimitOffsetQueryHandler;
<commit_msg>Simplify resolvePage to a single purpose<commit_after>import assign from 'lodash.assign';
import omit from 'lodash.omit';

import * as actions from 'src/actions';
import PaginatorError from 'src/paginator-error';

export const errors = Object.freeze({
  calculateOffsetNoLimit: 'Can\'t calculate offsets without a limit',
  calculatePageNoLimit: 'Can\'t calculate pages without a limit'
});

const defaultOptions = {
  limitQueryParam: 'limit',
  offsetQueryParam: 'offset'
};

export class LimitOffsetQueryHandler {
  constructor(options) {
    this._excessParams = null;
    this._limit = null;
    this.setOptions(options);
  }

  makeParams(page) {
    const opts = this._options;
    const queryParams = assign({}, this._excessParams);

    queryParams[opts.limitQueryParam] = this._limit;
    queryParams[opts.offsetQueryParam] = this._calculateOffset(page);

    return queryParams;
  }

  resolvePage(queryParams) {
    const {offset, limit} = this._parse(queryParams);

    if (offset === 0) {
      return 1;
    }
    if (!limit) {
      throw new PaginatorError(errors.calculatePageNoLimit);
    }

    return (offset + limit) / limit;
  }

  setParams(queryParams) {
    const result = this._parse(queryParams);
    this._excessParams = result.excess;
    this._limit = result.limit;

    return this;
  }

  onResponse(response) {
    const result = actions.parseResponse(response);

    if (!this._limit) {
      this._limit = result.limit;
    }
  }

  setOptions(options) {
    this._options = assign({}, defaultOptions, options);

    return this;
  }

  _parse(queryParams) {
    const {limitQueryParam, offsetQueryParam} = this._options;
    const defaults = {
      limit: null,
      offset: 0
    };
    const result = assign({}, defaults);

    if (queryParams.hasOwnProperty(limitQueryParam)) {
      result.limit = queryParams[limitQueryParam];
    }
    if (queryParams.hasOwnProperty(offsetQueryParam)) {
      result.offset = queryParams[offsetQueryParam];
    }

    result.excess = this._getExcess(queryParams);

    return result;
  }

  _getExcess(queryParams) {
    const opts = this._options;
    const paginationProperties = [
      opts.limitQueryParam,
      opts.offsetQueryParam
    ];

    return omit(queryParams, paginationProperties);
  }

  _calculateOffset(page) {
    const limit = this._limit;

    if (page === 1) {
      return 0;
    }
    if (!limit) {
      throw new PaginatorError(errors.calculateOffsetNoLimit);
    }

    return limit * page - limit;
  }
}

export default LimitOffsetQueryHandler;
<|endoftext|>


<commit_before>/*!
 * jQuery Modal
 * Copyright (c) 2014 CreativeDream
 * Website http://creativedream.net/plugins
 * Version: 1.0 (07-01-2014)
 * Requires: jQuery v1.7.1 or later
*/
function modal(e){return $.cModal(e)}(function(e){e.cModal=function(t){var n={type:"default",title:"title",text:null,buttons:[{text:"OK",val:true,onClick:function(e){return true}}],center:true,autoclose:false,callback:null,onShow:null,closeClick:true,theme:"default",background:"rgba(0,0,0,0.5)",zIndex:1050,buttonText:{ok:"OK",yes:"Yes",no:"No",cancel:"Cancel"},template:'

',_classes:{box:".modal-box",title:".modal-title",content:".modal-text",buttons:".modal-buttons",closebtn:".modal-close-btn"}},t=e.extend({},n,t),r,i=e("
").hide();mBox=t._classes.box,template=i.append(t.template),that={init:function(){e("#modal-window").remove();i.css({position:"fixed",width:"100%",height:"100%",top:"0",left:"0","z-index":t.zIndex,overflow:"auto"});that._modalShow();that._modalConent();t.onShow!=null?t.onShow(template):null;i.on("click","a.modal-btn",function(t){that._modalBtn(e(this))}).on("click",t._classes.closebtn,function(e){that._modalHide()}).click(function(e){if(t.closeClick){if(e.target.id=="modal-window"){that._modalHide()}}});e(window).keyup(function(e){if(e.keyCode==13){that._modalBtn(i.find(t._classes.buttons+" a.modal-btn:first-child"))}if(e.keyCode==27){that._modalHide()}})},_modalShow:function(){e("body").css("overflow","hidden").append(template)},_modalHide:function(n){r=typeof r=="undefined"?false:r;if(!n){i.fadeOut(200,function(){t.callback!=null?t.callback(r):null;e(this).remove();e("body").css("overflow","auto")});topPercent=100*parseFloat(e(mBox).css("top"))/parseFloat(e(mBox).parent().css("height"));e(mBox).animate({top:topPercent+5+"%"},"fast")}else{setTimeout(function(){i.fadeOut(300,function(){t.callback!=null?t.callback(r):null;e(this).remove();e("body").css("overflow","auto")});topPercent=100*parseFloat(e(mBox).css("top"))/parseFloat(e(mBox).parent().css("height"));e(mBox).animate({top:topPercent+5+"%"},"fast")},n)}},_modalConent:function(){_title=t._classes.title;_content=t._classes.content;_buttons=t._classes.buttons;_buttonsText=t.buttonText;_types=["alert","confirm","prompt"];if(t.theme&&t.theme!=null&&t.theme!="default"){e(mBox).addClass("modal-theme-"+t.theme)}if(t.background&&t.background!=null){i.css("background-color",t.background)}if(t.title||t.title!=null){e(_title).prepend(t.title);if(e.inArray(t.type,_types)==-1){e(_title).addClass(t.type)}}else{e(_title).remove()}t.type=="prompt"?t.text+='<input type="text" name="modal-prompt-input" class="modal-prompt-input" />':"";e(_content).html(t.text);if(t.buttons||t.buttons!=null){buttons="";switch(t.type){case"alert":buttons=''+_buttonsText.ok+"";break;case"confirm":buttons=''+_buttonsText.yes+''+_buttonsText.no+"";break;case"prompt":buttons=''+_buttonsText.ok+''+_buttonsText.cancel+"";break;default:if(t.buttons.length>0&&e.isArray(t.buttons)){e.each(t.buttons,function(e,t){addClass=t["addClass"]&&typeof t["addClass"]!="undefined"?" "+t["addClass"]:"";buttons+=''+t["text"]+""})}else{buttons+=''+_buttonsText.ok+""}}e(_buttons).html(buttons)}else{e(_buttons).remove()}i.fadeIn(200);that._position();if(t.autoclose){time=t.buttons||t.buttons!=null?e(_content).text().length*32:900;that._modalHide(time<900?900:time)}},_position:function(){if(t.center){data={top:50,left:50,marginTop:-e(mBox).outerHeight()/2,marginLeft:-e(mBox).outerWidth()/2};if(e(window).height()<e(mBox).outerHeight()){data.top=1;data.marginTop=0}e(mBox).css({top:data.top-5+"%",left:data.left+"%","margin-top":data.marginTop,"margin-left":data.marginLeft}).animate({top:data.top+"%"},"fast")}else{data={top:10,left:50,marginTop:0,marginLeft:-e(mBox).outerWidth()/2};e(mBox).css({top:data.top-5+"%",left:data.left+"%","margin-top":data.marginTop,"margin-left":data.marginLeft}).animate({top:data.top+"%"},"fast")}},_modalBtn:function(n){var s=false,o=t.type,u=n.index(),a=t.buttons[u];if(e.inArray(o,["alert","confirm","prompt"])>-1){s=u==0?true:false;if(o=="prompt"){s=s&&i.find("input.modal-prompt-input").size()>0&&i.find("input.modal-prompt-input").val().length!=0?i.find("input.modal-prompt-input").val():false}that._modalHide()}else{s=a&&a["val"]?a["val"]:true;if(!a["onClick"]||a["onClick"]({val:s,bObj:n,bOpts:a,modal:template})){that._modalHide()}}r=s}};that.init();return true}})(jQuery);
<commit_msg>Update jquery.modal.min.js<commit_after>/*!
 * jQuery Modal
 * Copyright (c) 2014 CreativeDream
 * Website http://creativedream.net/plugins
 * Version: 1.2 (20-10-2014)
 * Requires: jQuery v1.7.1 or later
*/
function modal(e){return $.cModal(e)}(function(e){e.cModal=function(t){var n={type:"default",title:null,text:null,size:"normal",buttons:[{text:"OK",val:true,onClick:function(e){return true}}],center:true,autoclose:false,callback:null,onShow:null,closeClick:true,closable:true,theme:"default",background:"rgba(0,0,0,0.5)",zIndex:1050,buttonText:{ok:"OK",yes:"Yes",cancel:"Cancel"},template:'

',_classes:{box:".modal-box",title:".modal-title",content:".modal-text",buttons:".modal-buttons",closebtn:".modal-close-btn"}},t=e.extend({},n,t),r,i=e("
").hide(),s=t._classes.box,o=i.append(t.template),u={init:function(){e("#modal-window").remove();i.css({position:"fixed",width:"100%",height:"100%",top:"0",left:"0","z-index":t.zIndex,overflow:"auto"});i.find(t._classes.box).css({position:"absolute"});u._modalShow();u._modalConent();t.onShow!=null?t.onShow({getModal:function(){return i},getTitle:function(){return i.find(t._classes.title)},getContet:function(){return i.find(t._classes.content)},setTitle:function(e){i.find(t._classes.title+" h3").html(e);return true},setContent:function(e){i.find(t._classes.content).html(e);return true},setClosable:function(e){if(e===false){t.closable=false}else{t.closable=true}return true}}):null;i.on("click","a.modal-btn",function(t){u._modalBtn(e(this))}).on("click",t._classes.closebtn,function(e){u._modalHide()}).click(function(e){if(t.closeClick){if(e.target.id=="modal-window"){u._modalHide()}}});e(window).bind("keyup",u._keyUpF);i.bind("DOMSubtreeModified",u._position)},_keyUpF:function(e){switch(e.keyCode){case 13:if($("input:not(.modal-prompt-input),textarea").is(":focus")){return false}u._modalBtn(i.find(t._classes.buttons+" a.modal-btn"+(typeof u.btnForEKey!=="undefined"&&i.find(t._classes.buttons+" a.modal-btn:eq("+u.btnForEKey+")").size()>0?":eq("+u.btnForEKey+")":":last-child")));break;case 27:u._modalHide();break}},_modalShow:function(){e("body").css({overflow:"hidden",width:e("body").innerWidth()}).append(o)},_modalHide:function(n){if(t.closable===false){return false}r=typeof r=="undefined"?false:r;var o=function(){i.fadeOut(200,function(){t.callback!=null?t.callback(r):null;e(this).remove();e("body").css({overflow:"",width:""})});var n=100*parseFloat(e(s).css("top"))/parseFloat(e(s).parent().css("height"));e(s).animate({top:n+5+"%"},"fast")};if(!n){o()}else{setTimeout(function(){o()},n)}e(window).unbind("keyup",u._keyUpF)},_modalConent:function(){var n=t._classes.title,r=t._classes.content,o=t._classes.buttons,a=t.buttonText,f=["alert","confirm","prompt"];if(t.size&&t.theme!=null&&t.theme!="normal"){e(s).addClass("modal-size-"+t.size)}if(t.theme&&t.theme!=null&&t.theme!="default"){e(s).addClass(t.theme)}if(t.background&&t.background!=null){i.css("background-color",t.background)}if(t.title||t.title!=null){e(n).prepend("
"+t.title+"
");if(e.inArray(t.type,f)==-1&&t.type!="default"){e(n).addClass("modal-title-"+t.type)}}else{e(n).remove()}t.type=="prompt"?t.text+='<input type="text" name="modal-prompt-input" class="modal-prompt-input" autofocus="on" />':"";e(r).html(t.text);if(t.buttons||t.buttons!=null){var l="";switch(t.type){case"alert":l=''+a.ok+"";break;case"confirm":l=''+a.cancel+''+a.yes+"";break;case"prompt":l=''+a.cancel+''+a.ok+"";break;default:if(t.buttons.length>0&&e.isArray(t.buttons)){e.each(t.buttons,function(e,t){var n=t["addClass"]&&typeof t["addClass"]!="undefined"?" "+t["addClass"]:"";l+=''+t["text"]+"";if(t["eKey"]){u.btnForEKey=e}})}else{l+=''+a.ok+""}}e(o).html(l)}else{e(o).remove()}i.fadeIn(200);u._position();if(t.autoclose){time=t.buttons||t.buttons!=null?e(r).text().length*32:900;u._modalHide(time<900?900:time)}},_position:function(){var n=null;if(t.center){n={top:50,left:50,marginTop:-e(s).outerHeight()/2,marginLeft:-e(s).outerWidth()/2};if(e(window).height()<e(s).outerHeight()){n.top=1;n.marginTop=0}e(s).css({top:n.top-5+"%",left:n.left+"%","margin-top":n.marginTop,"margin-left":n.marginLeft}).animate({top:n.top+"%"},"fast")}else{n={top:10,left:50,marginTop:0,marginLeft:-e(s).outerWidth()/2};e(s).css({top:n.top-5+"%",left:n.left+"%","margin-top":n.marginTop,"margin-left":n.marginLeft}).animate({top:n.top+"%"},"fast")}},_modalBtn:function(n){var s=false,o=t.type,a=n.index(),f=t.buttons[a];if(e.inArray(o,["alert","confirm","prompt"])>-1){s=a==1?true:false;if(o=="prompt"){s=s&&i.find("input.modal-prompt-input").size()>0&&i.find("input.modal-prompt-input").val().length!=0?i.find("input.modal-prompt-input").val():false}u._modalHide()}else{if(n.hasClass("btn-disabled")){return false}s=f&&f["val"]?f["val"]:true;if(!f["onClick"]||f["onClick"]({val:s,bObj:n,bOpts:f,getModal:function(){return i},getTitle:function(){return i.find(t._classes.title)},getContet:function(){return i.find(t._classes.content)},setTitle:function(e){i.find(t._classes.title+" h3").html(e);return true},setContent:function(e){i.find(t._classes.content).html(e);return true},setClosable:function(e){if(e===false){t.closable=false}else{t.closable=true}return true}})){u._modalHide()}}r=s}};u.init();return true}})(jQuery);
<|endoftext|>


<commit_before>var Stream = require('stream').Stream;

require('http').OutgoingMessage.prototype.hijack = function (cb) {
    var writeHead = this.writeHead,
        write = this.write,
        end = this.end,
        originalResponse = this,
        hijacking = true,
        originalHasEnded = false,
        hijackedResponse = new Stream();

    Stream.call(hijackedResponse);

    originalResponse.on('drain', function () {
        hijackedResponse.emit('drain');
    });

    hijackedResponse.readable = hijackedResponse.writable = true;

    hijackedResponse.write = function (chunk, encoding) {
        return write.call(originalResponse, chunk, encoding);
    };

    hijackedResponse.end = function (chunk, encoding) {
        if (chunk) {
            write.call(originalResponse, chunk, encoding);
        }
        end.call(originalResponse);
    };

    hijackedResponse.__defineGetter__('statusCode', function () {
        return originalResponse.statusCode;
    });

    hijackedResponse.__defineSetter__('statusCode', function (statusCode) {
        originalResponse.statusCode = statusCode;
    });

    hijackedResponse.__proto__ = originalResponse;

    this.writeHead = function (statusCode, headers) {
        if (statusCode) {
            this.statusCode = statusCode;
        }
        if (headers) {
            for (var headerName in headers) {
                this.setHeader(headerName, headers[headerName]);
            }
        }
        this.writeHead = writeHead;
        cb(null, hijackedResponse);
    };

    // Wait for the original response to end, then make the original res.write and res.end work again
    hijackedResponse.unhijack = function (restoreOriginal, cb) {
        if (typeof restoreOriginal === 'function') {
            cb = restoreOriginal;
            restoreOriginal = false;
        }
        if (restoreOriginal) {
            hijacking = false;
        }
        if (originalHasEnded) {
            process.nextTick(function () {
                hijacking = false;
                if (cb) {
                    cb(null, originalResponse);
                }
            });
        } else {
            hijackedResponse.once('originalend', function () {
                hijacking = false;
                if (cb) {
                    cb(null, originalResponse);
                }
            });
        }
    };

    this.write = function (chunk, encoding) {
        if (!this.headerSent && this.writeHead !== writeHead) this._implicitHeader();
        if (hijacking) {
            hijackedResponse.emit('data', chunk, encoding);
        } else {
            return write.call(this, chunk, encoding);
        }
    };

    this.end = function (chunk, encoding) {
        if (chunk) {
            this.write(chunk, encoding);
        } else if (!this.headerSent && this.writeHead !== writeHead) {
            this._implicitHeader();
        }
        hijackedResponse.emit('originalend');
        originalHasEnded = true;
        if (hijacking) {
            // Prevent .pipe from cleaning up too soon:
            process.nextTick(function () {
                hijackedResponse.emit('end');
            });
        } else {
            end.call(this);
        }
    };
};
<commit_msg>Delay the emission of 'drain' events to the next tick. Fixes stack overflow errors with certain pipe constructs.<commit_after>var Stream = require('stream').Stream;

require('http').OutgoingMessage.prototype.hijack = function (cb) {
    var writeHead = this.writeHead,
        write = this.write,
        end = this.end,
        originalResponse = this,
        hijacking = true,
        originalHasEnded = false,
        hijackedResponse = new Stream();

    Stream.call(hijackedResponse);

    originalResponse.on('drain', function () {
        process.nextTick(function () {
            hijackedResponse.emit('drain');
        });
    });

    hijackedResponse.readable = hijackedResponse.writable = true;

    hijackedResponse.write = function (chunk, encoding) {
        return write.call(originalResponse, chunk, encoding);
    };

    hijackedResponse.end = function (chunk, encoding) {
        if (chunk) {
            write.call(originalResponse, chunk, encoding);
        }
        end.call(originalResponse);
    };

    hijackedResponse.__defineGetter__('statusCode', function () {
        return originalResponse.statusCode;
    });

    hijackedResponse.__defineSetter__('statusCode', function (statusCode) {
        originalResponse.statusCode = statusCode;
    });

    hijackedResponse.__proto__ = originalResponse;

    this.writeHead = function (statusCode, headers) {
        if (statusCode) {
            this.statusCode = statusCode;
        }
        if (headers) {
            for (var headerName in headers) {
                this.setHeader(headerName, headers[headerName]);
            }
        }
        this.writeHead = writeHead;
        cb(null, hijackedResponse);
    };

    // Wait for the original response to end, then make the original res.write and res.end work again
    hijackedResponse.unhijack = function (restoreOriginal, cb) {
        if (typeof restoreOriginal === 'function') {
            cb = restoreOriginal;
            restoreOriginal = false;
        }
        if (restoreOriginal) {
            hijacking = false;
        }
        if (originalHasEnded) {
            process.nextTick(function () {
                hijacking = false;
                if (cb) {
                    cb(null, originalResponse);
                }
            });
        } else {
            hijackedResponse.once('originalend', function () {
                hijacking = false;
                if (cb) {
                    cb(null, originalResponse);
                }
            });
        }
    };

    this.write = function (chunk, encoding) {
        if (!this.headerSent && this.writeHead !== writeHead) this._implicitHeader();
        if (hijacking) {
            hijackedResponse.emit('data', chunk, encoding);
        } else {
            return write.call(this, chunk, encoding);
        }
    };

    this.end = function (chunk, encoding) {
        if (chunk) {
            this.write(chunk, encoding);
        } else if (!this.headerSent && this.writeHead !== writeHead) {
            this._implicitHeader();
        }
        hijackedResponse.emit('originalend');
        originalHasEnded = true;
        if (hijacking) {
            // Prevent .pipe from cleaning up too soon:
            process.nextTick(function () {
                hijackedResponse.emit('end');
            });
        } else {
            end.call(this);
        }
    };
};
<|endoftext|>


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

'use strict';

// description: get an attribute for a project
// arguments: <project> <attribute>

var storage = require('../lib/storage.js');
var utilities = require('../lib/utilities.js');

var program = utilities.programDefaults('get', '<project> <attribute>');

program.option('-p, --porcelain', 'Get the value in a machine-readable way');

program.parse(process.argv);

storage.setup(function () {
  if (program.args.length !== 2) {
    console.error('Please specify a project and attribute.');

    process.exit(1);
  }

  var name = program.args[0];
  var attribute = program.args[1];

  var project = storage.getProjectOrDie(name);

  if (attribute === 'directory') {
    project.directory = utilities.expand(project.directory);
  }

  if (program.porcelain) {
    console.log(project[attribute] || '');
  } else {
    console.log('%s:%s: "%s"', project.name, attribute,
                project[attribute] || '');
  }
});
<commit_msg>get: only setup storage if needed<commit_after>#!/usr/bin/env node

'use strict';

// description: get an attribute for a project
// arguments: <project> <attribute>

var storage = require('../lib/storage.js');
var utilities = require('../lib/utilities.js');

var program = utilities.programDefaults('get', '<project> <attribute>');

program.option('-p, --porcelain', 'Get the value in a machine-readable way');

program.parse(process.argv);

if (program.args.length !== 2) {
  console.error('Please specify a project and attribute.');

  process.exit(1);
}

storage.setup(function () {
  var name = program.args[0];
  var attribute = program.args[1];

  var project = storage.getProjectOrDie(name);

  if (attribute === 'directory') {
    project.directory = utilities.expand(project.directory);
  }

  if (program.porcelain) {
    console.log(project[attribute] || '');
  } else {
    console.log('%s:%s: "%s"', project.name, attribute,
                project[attribute] || '');
  }
});
<|endoftext|>