<commit_before>'use strict';

const Promise      = require('bluebird');
const _            = require('lodash');
const chokidar     = require('chokidar');
const anymatch     = require('anymatch');
const Path         = require('path');
const mixin        = require('mixwith').Mixin;
const mix          = require('mixwith').mix;

const fs           = require('../fs');
const utils        = require('../utils');
const Log          = require('../log');
const Configurable = require('../mixins/configurable');
const Collection   = require('../mixins/collection');
const Emitter      = require('../mixins/emitter');
const Stream       = require('../promise-stream');

module.exports = mixin((superclass) => class Source extends mix(superclass).with(Configurable, Collection, Emitter) {

    constructor(){
        super();
        // super.apply(null, Array.from(arguments));
        super.addMixedIn('Source');
        this.isSource     = true;
        this.isLoaded     = false;
        this._app         = null;
        this._loading     = false;
        this._monitor     = null;
        this._fileTree    = null;
    }

    initSource(name, config, app) {
        this._app = app;
        this.name = utils.slugify(name.toLowerCase());
    }

    get label() {
        return this.get('label') || utils.titlize(this.name);
    }

    get title() {
        return this.get('title') || this.label;
    }

    get source(){
        return this;
    }

    get isWatching(){
        return !! this._monitor;
    }

    get fullPath(){
        return Path.resolve(this.get('path'));
    }

    get relPath() {
        return Path.relative(process.cwd(), this.get('path'));
    }

    toStream() {
        return new Stream(this.load().then(() => this.flatten().toArray()));
    }

    exists() {
        return this.get('path') && utils.fileExistsSync(this.get('path'));
    }

    load(force) {
        if (!this.get('path')) {
            return Promise.resolve(this);
        }
        if (!this.exists()) {
            Log.error(`The ${this.name} directory (${this.get('path')}) does not exist.`);
            return Promise.resolve(this);
        }
        if (this._loading) {
            return this._loading;
        }
        if (force || !this.isLoaded) {
            return this._build().then(source => {
                Log.debug(`Finished parsing ${this.name} directory`);
                this.isLoaded = true;
                this.emit('loaded');
                this._app.emit('source:loaded', this);
                return source;
            });
        }
        return Promise.resolve(this);
    }

    refresh() {
        if (!this.isLoaded) {
            return this.load();
        }
        if (this._loading) {
            return this._loading;
        }
        return this._build().then(source => {
            Log.debug(`Finished parsing ${this.name} directory`);
            this.isLoaded = true;
            return source;
        });
    }

    watch() {
        if (this.isWatching) {
            return;
        }
        const sourcePath = this.fullPath;
        if (!this._monitor && sourcePath) {
            Log.debug(`Watching ${this.name} directory - ${sourcePath}`);
            this._monitor = chokidar.watch(sourcePath, {
                ignored: /[\/\\]\./
            });
            this._monitor.on('ready', () => {
                this._monitor.on('all', (event, path) => {

                    if (this._fileFilter && !this._fileFilter(path)) {
                        // don't do anything if there is a file filter in place
                        // and the changed file doesn't match it.
                        return;
                    }

                    Log.debug(`Change in ${this.name} directory`);

                    const data = this._appendEventFileInfo(path, {
                        event: event,
                        path: path,
                    });

                    this.emit('changed', data);
                    this._app.emit('source:changed', this, data);

                    this.refresh().then(source => {
                        this.emit('updated', data);
                        this._app.emit('source:updated', this, data);
                        return source;
                    });

                });
            });
        }
    }

    unwatch() {
        if (!this.isWatching) {
            return;
        }
        this._monitor.close();
        this._monitor = null;
    }

    isConfig(file) {
        return anymatch(`**/*.config.{js,json,yaml,yml}`, this._getPath(file));
    }

    _build() {
        if (!this.get('path')) {
            return Promise.resolve(this);
        }
        this._loading = this._getTree().then(fileTree => {
            this._fileTree = fileTree;
            this._loading  = false;
            return this._parse(fileTree);
        }).catch(e => {
            Log.error(e);
            if (this._app.debug) {
                Log.write(e.stack);
            }
        });
        return this._loading;
    }

    _getTree() {
        return fs.describe(this.fullPath, this.relPath);
    }

    _parse() {
        return [];
    }

    _appendEventFileInfo(file, eventData) {
        if (this.isConfig(file)) {
            eventData.isConfig = true;
        }
        return eventData;
    }

    _getPath(file) {
        const filePath = _.isString(file) ? file : file.path;
        return filePath.toLowerCase();
    }

});
<commit_msg>Fix fullpath bug when no component directory is specified<commit_after>'use strict';

const Promise      = require('bluebird');
const _            = require('lodash');
const chokidar     = require('chokidar');
const anymatch     = require('anymatch');
const Path         = require('path');
const mixin        = require('mixwith').Mixin;
const mix          = require('mixwith').mix;

const fs           = require('../fs');
const utils        = require('../utils');
const Log          = require('../log');
const Configurable = require('../mixins/configurable');
const Collection   = require('../mixins/collection');
const Emitter      = require('../mixins/emitter');
const Stream       = require('../promise-stream');

module.exports = mixin((superclass) => class Source extends mix(superclass).with(Configurable, Collection, Emitter) {

    constructor(){
        super();
        // super.apply(null, Array.from(arguments));
        super.addMixedIn('Source');
        this.isSource     = true;
        this.isLoaded     = false;
        this._app         = null;
        this._loading     = false;
        this._monitor     = null;
        this._fileTree    = null;
    }

    initSource(name, config, app) {
        this._app = app;
        this.name = utils.slugify(name.toLowerCase());
    }

    get label() {
        return this.get('label') || utils.titlize(this.name);
    }

    get title() {
        return this.get('title') || this.label;
    }

    get source(){
        return this;
    }

    get isWatching(){
        return !! this._monitor;
    }

    get fullPath(){
        return this.get('path') ? Path.resolve(this.get('path')) : null;
    }

    get relPath() {
        return Path.relative(process.cwd(), this.get('path'));
    }

    toStream() {
        return new Stream(this.load().then(() => this.flatten().toArray()));
    }

    exists() {
        return this.get('path') && utils.fileExistsSync(this.get('path'));
    }

    load(force) {
        if (!this.get('path')) {
            return Promise.resolve(this);
        }
        if (!this.exists()) {
            Log.error(`The ${this.name} directory (${this.get('path')}) does not exist.`);
            return Promise.resolve(this);
        }
        if (this._loading) {
            return this._loading;
        }
        if (force || !this.isLoaded) {
            return this._build().then(source => {
                Log.debug(`Finished parsing ${this.name} directory`);
                this.isLoaded = true;
                this.emit('loaded');
                this._app.emit('source:loaded', this);
                return source;
            });
        }
        return Promise.resolve(this);
    }

    refresh() {
        if (!this.isLoaded) {
            return this.load();
        }
        if (this._loading) {
            return this._loading;
        }
        return this._build().then(source => {
            Log.debug(`Finished parsing ${this.name} directory`);
            this.isLoaded = true;
            return source;
        });
    }

    watch() {
        if (this.isWatching) {
            return;
        }
        const sourcePath = this.fullPath;
        if (!this._monitor && sourcePath) {
            Log.debug(`Watching ${this.name} directory - ${sourcePath}`);
            this._monitor = chokidar.watch(sourcePath, {
                ignored: /[\/\\]\./
            });
            this._monitor.on('ready', () => {
                this._monitor.on('all', (event, path) => {

                    if (this._fileFilter && !this._fileFilter(path)) {
                        // don't do anything if there is a file filter in place
                        // and the changed file doesn't match it.
                        return;
                    }

                    Log.debug(`Change in ${this.name} directory`);

                    const data = this._appendEventFileInfo(path, {
                        event: event,
                        path: path,
                    });

                    this.emit('changed', data);
                    this._app.emit('source:changed', this, data);

                    this.refresh().then(source => {
                        this.emit('updated', data);
                        this._app.emit('source:updated', this, data);
                        return source;
                    });

                });
            });
        }
    }

    unwatch() {
        if (!this.isWatching) {
            return;
        }
        this._monitor.close();
        this._monitor = null;
    }

    isConfig(file) {
        return anymatch(`**/*.config.{js,json,yaml,yml}`, this._getPath(file));
    }

    _build() {
        if (!this.get('path')) {
            return Promise.resolve(this);
        }
        this._loading = this._getTree().then(fileTree => {
            this._fileTree = fileTree;
            this._loading  = false;
            return this._parse(fileTree);
        }).catch(e => {
            Log.error(e);
            if (this._app.debug) {
                Log.write(e.stack);
            }
        });
        return this._loading;
    }

    _getTree() {
        return fs.describe(this.fullPath, this.relPath);
    }

    _parse() {
        return [];
    }

    _appendEventFileInfo(file, eventData) {
        if (this.isConfig(file)) {
            eventData.isConfig = true;
        }
        return eventData;
    }

    _getPath(file) {
        const filePath = _.isString(file) ? file : file.path;
        return filePath.toLowerCase();
    }

});
<|endoftext|>


<commit_before>import { Suggestion as DefaultSuggestion } from 'azk/generator/suggestions/php_composer';

export class Suggestion extends DefaultSuggestion {
  constructor(...args) {
    super(...args);

    var name    = 'php_laravel';
    // Readable name for this suggestion
    this.name = `${name}`;

    // Which rules they suggestion is valid
    this.ruleNamesList = [`${name}`];

    // Initial Azkfile.js suggestion
    this.suggestion = this.extend({}, this.suggestion, {
      __type: `${name}`,
    });
  }
}
<commit_msg>Add provision<commit_after>import { Suggestion as DefaultSuggestion } from 'azk/generator/suggestions/php_composer';

export class Suggestion extends DefaultSuggestion {
  constructor(...args) {
    super(...args);

    var name    = 'php_laravel';
    // Readable name for this suggestion
    this.name = `${name}`;

    // Which rules they suggestion is valid
    this.ruleNamesList = [`${name}`];

    // Initial Azkfile.js suggestion
    this.suggestion = this.extend({}, this.suggestion, {
      __type: `${name}`,
      provision: [
        'composer install',
        'npm install',
      ],
    });
  }
}
<|endoftext|>


<commit_before>"use strict";

var CityTour = CityTour || {};

CityTour.RoadNetworkGenerator = (function() {
  var DISTANCE_TO_CITY_EDGE = Math.min(CityTour.Config.HALF_BLOCK_COLUMNS, CityTour.Config.HALF_BLOCK_ROWS);
  var MAX_STEEPNESS = Math.PI / 6;
  var MAX_BRIDGE_LENGTH = 10;
  var MIN_BRIDGE_HEIGHT_FROM_WATER = 5;
  var MAX_HEIGHT_DIFFERENCE_BETWEEN_BRIDGE_TERMINALS = 5.0;
  var MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS = 3;
  var PROBABILITY_OF_VALID_BRIDGE_BEING_BUILT = 0.5;

  var buildRoadNetwork = function(terrain, config) {
    var centerMapX = config.centerMapX;
    var centerMapZ = config.centerMapZ;

    var MIN_MAP_X = -CityTour.Config.HALF_BLOCK_COLUMNS + centerMapX;
    var MAX_MAP_X = CityTour.Config.HALF_BLOCK_COLUMNS + centerMapX;
    var MIN_MAP_Z = -CityTour.Config.HALF_BLOCK_ROWS + centerMapZ;
    var MAX_MAP_Z = CityTour.Config.HALF_BLOCK_ROWS + centerMapZ;

    var SAFE_FROM_DECAY_DISTANCE = DISTANCE_TO_CITY_EDGE * config.safeFromDecayPercentage;

    var probabilityOfBranching = function(mapX1, mapZ1, mapX2, mapZ2) {
      // Guarantee roads along x and z axes
      if (mapX1 === centerMapX && mapX2 === centerMapX && mapZ2 >= MIN_MAP_Z && mapZ2 <= MAX_MAP_Z) {
        return 1.0;
      }
      else if (mapZ1 === centerMapZ && mapZ2 === centerMapZ && mapX2 >= MIN_MAP_X && mapX2 <= MAX_MAP_X) {
        return 1.0;
      }

      var distanceFromCenter = CityTour.Math.distanceBetweenPoints(centerMapX, centerMapZ, mapX1, mapZ1);
      var normalizedPercentageFromCenter;

      if (distanceFromCenter <= SAFE_FROM_DECAY_DISTANCE) {
        return 1.0;
      }

      normalizedPercentageFromCenter = (distanceFromCenter - SAFE_FROM_DECAY_DISTANCE) / (DISTANCE_TO_CITY_EDGE - SAFE_FROM_DECAY_DISTANCE);
      return (Math.pow(0.5, normalizedPercentageFromCenter) - 0.5) * 2;
    };

    var isTerrainTooSteep = function(terrain, mapX, mapZ, targetMapX, targetMapZ) {
      var heightAtPoint1 = terrain.heightAtCoordinates(mapX, mapZ);
      var heightAtPoint2 = terrain.heightAtCoordinates(targetMapX, targetMapZ);
      var angle = Math.atan2((heightAtPoint1 - heightAtPoint2), CityTour.Config.BLOCK_DEPTH);

      return Math.abs(angle) > MAX_STEEPNESS;
    };

    var shouldConnectIntersections = function(terrain, mapX1, mapZ1, mapX2, mapZ2) {
      var edgeIsOnLand = terrain.materialAtCoordinates(mapX1, mapZ1) === CityTour.Terrain.LAND &&
                         terrain.materialAtCoordinates(mapX2, mapZ2) === CityTour.Terrain.LAND;

      return edgeIsOnLand &&
             (Math.random() < probabilityOfBranching(mapX1, mapZ1, mapX2, mapZ2)) &&
             !isTerrainTooSteep(terrain, mapX1, mapZ1, mapX2, mapZ2);
    };

    var branchFromIntersection = function(terrain, roadNetwork, mapX, mapZ) {
      connectIntersections(terrain, roadNetwork, mapX, mapZ, mapX - 1, mapZ);
      connectIntersections(terrain, roadNetwork, mapX, mapZ, mapX, mapZ - 1);
      connectIntersections(terrain, roadNetwork, mapX, mapZ, mapX + 1, mapZ);
      connectIntersections(terrain, roadNetwork, mapX, mapZ, mapX, mapZ + 1);
    };

    var calculateBridgeAttributes = function(terrain, roadNetwork, bridgeStartX, bridgeStartZ, targetMapX, targetMapZ) {
      var xDelta, zDelta;
      var bridgeEndX, bridgeEndZ;
      var bridgeLength;
      var heightAtTerminal1, heightAtTerminal2;
      var waterHeight, roadDeckHeight;

      var distanceFromCenter = CityTour.Math.distanceBetweenPoints(centerMapX, centerMapZ, bridgeStartX, bridgeStartZ);
      if (distanceFromCenter > SAFE_FROM_DECAY_DISTANCE) {
        return null;
      }

      if (targetMapX === bridgeStartX) {
        xDelta = 0.0;
      }
      else {
        xDelta = (targetMapX < bridgeStartX) ? -1 : 1;
      }
      if (targetMapZ === bridgeStartZ) {
        zDelta = 0.0;
      }
      else {
        zDelta = (targetMapZ < bridgeStartZ) ? -1 : 1;
      }
      bridgeEndX = targetMapX;
      bridgeEndZ = targetMapZ;

      bridgeLength = 1;
      while (terrain.materialAtCoordinates(bridgeEndX, bridgeEndZ) === CityTour.Terrain.WATER) {
        if (waterHeight === undefined) {
          waterHeight = terrain.heightAtCoordinates(bridgeEndX, bridgeEndZ);
        }
        if (roadNetwork.hasIntersection(bridgeEndX, bridgeEndZ)) {
          return null;
        }

        bridgeEndX += xDelta;
        bridgeEndZ += zDelta;
        bridgeLength += 1;

        if (bridgeEndX < -CityTour.Config.HALF_TERRAIN_COLUMNS ||
            bridgeEndX > CityTour.Config.HALF_TERRAIN_COLUMNS  ||
            bridgeEndZ < -CityTour.Config.HALF_TERRAIN_ROWS    ||
            bridgeEndZ > CityTour.Config.HALF_TERRAIN_ROWS) {
          return null;
        }
      }

      if (bridgeLength > MAX_BRIDGE_LENGTH) {
        return null;
      }

      heightAtTerminal1 = terrain.heightAtCoordinates(bridgeStartX, bridgeStartZ);
      heightAtTerminal2 = terrain.heightAtCoordinates(bridgeEndX, bridgeEndZ);
      if (Math.abs(heightAtTerminal1 - heightAtTerminal2) > MAX_HEIGHT_DIFFERENCE_BETWEEN_BRIDGE_TERMINALS) {
        return null;
      }
      roadDeckHeight = Math.max(heightAtTerminal1, heightAtTerminal2, waterHeight + MIN_BRIDGE_HEIGHT_FROM_WATER);

      if (parallelBridgeExistsNearby(bridgeStartX, bridgeStartZ, bridgeEndX, bridgeEndZ)) {
        return null;
      }

      if (Math.random() < PROBABILITY_OF_VALID_BRIDGE_BEING_BUILT) {
        return null;
      }

      return {
        roadDeckHeight: roadDeckHeight,
        endX: bridgeEndX,
        endZ: bridgeEndZ,
        xDelta: xDelta,
        zDelta: zDelta,
      };
    };

    var parallelBridgeExistsNearby = function(startX, startZ, endX, endZ) {
      var x, z;
      var xMin, xMax, zMin, zMax;

      if (endZ > startZ) {  // North/south bridge
        xMin = startX - MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS;
        xMax = endX + MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS;
        zMin = startZ;
        zMax = endZ;
      }
      else {  // East/west bridge
        xMin = startX;
        xMax = endX;
        zMin = startZ - MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS;
        zMax = endZ + MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS;
      }

      for (x = xMin; x <= xMax; x++) {
        for (z = zMin; z <= zMax; z++) {
          if (roadNetwork.hasIntersection(x, z) && roadNetwork.getIntersectionSurfaceType(x, z) === CityTour.RoadNetwork.BRIDGE_SURFACE) {
            return true;
          }
        }
      }

      return false;
    };

    var connectIntersections = function(terrain, roadNetwork, mapX, mapZ, targetMapX, targetMapZ) {
      if (terrain.materialAtCoordinates(targetMapX, targetMapZ) === CityTour.Terrain.WATER) {
        var bridgeAttributes = calculateBridgeAttributes(terrain, roadNetwork, mapX, mapZ, targetMapX, targetMapZ);

        if (bridgeAttributes !== null) {
          var tempX = mapX;
          var tempZ = mapZ;
          while (tempX < bridgeAttributes.endX || tempZ < bridgeAttributes.endZ) {
            roadNetwork.addEdge(tempX,
                                tempZ,
                                tempX + bridgeAttributes.xDelta,
                                tempZ + bridgeAttributes.zDelta,
                                bridgeAttributes.roadDeckHeight,
                                CityTour.RoadNetwork.BRIDGE_SURFACE);
            tempX += bridgeAttributes.xDelta;
            tempZ += bridgeAttributes.zDelta;
          }

          branchFromIntersection(terrain, roadNetwork, bridgeAttributes.endX, bridgeAttributes.endZ);
        }
      }
      else {
        if (shouldConnectIntersections(terrain, mapX, mapZ, targetMapX, targetMapZ)) {
          var targetIntersectionExists = roadNetwork.hasIntersection(targetMapX, targetMapZ);

          roadNetwork.addEdge(mapX, mapZ, targetMapX, targetMapZ, 0.0, CityTour.RoadNetwork.TERRAIN_SURFACE);
          if (!targetIntersectionExists) {
            branchFromIntersection(terrain, roadNetwork, targetMapX, targetMapZ);
          }
        }
      }
    };

    var roadNetwork = new CityTour.RoadNetwork(terrain);
    branchFromIntersection(terrain, roadNetwork, centerMapX, centerMapZ);

    return roadNetwork;
  };

  var roadNetworkGenerator = {};

  roadNetworkGenerator.generate = function(terrain, config) {
    return buildRoadNetwork(terrain, config);
  };

  return roadNetworkGenerator;
})();
<commit_msg>Hoisting var declarations, and attempt at better variable names<commit_after>"use strict";

var CityTour = CityTour || {};

CityTour.RoadNetworkGenerator = (function() {
  var DISTANCE_TO_CITY_EDGE = Math.min(CityTour.Config.HALF_BLOCK_COLUMNS, CityTour.Config.HALF_BLOCK_ROWS);
  var MAX_STEEPNESS = Math.PI / 6;
  var MAX_BRIDGE_LENGTH = 10;
  var MIN_BRIDGE_HEIGHT_FROM_WATER = 5;
  var MAX_HEIGHT_DIFFERENCE_BETWEEN_BRIDGE_TERMINALS = 5.0;
  var MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS = 3;
  var PROBABILITY_OF_VALID_BRIDGE_BEING_BUILT = 0.5;

  var buildRoadNetwork = function(terrain, config) {
    var centerMapX = config.centerMapX;
    var centerMapZ = config.centerMapZ;

    var MIN_MAP_X = -CityTour.Config.HALF_BLOCK_COLUMNS + centerMapX;
    var MAX_MAP_X = CityTour.Config.HALF_BLOCK_COLUMNS + centerMapX;
    var MIN_MAP_Z = -CityTour.Config.HALF_BLOCK_ROWS + centerMapZ;
    var MAX_MAP_Z = CityTour.Config.HALF_BLOCK_ROWS + centerMapZ;

    var SAFE_FROM_DECAY_DISTANCE = DISTANCE_TO_CITY_EDGE * config.safeFromDecayPercentage;

    var probabilityOfBranching = function(mapX1, mapZ1, mapX2, mapZ2) {
      // Guarantee roads along x and z axes
      if (mapX1 === centerMapX && mapX2 === centerMapX && mapZ2 >= MIN_MAP_Z && mapZ2 <= MAX_MAP_Z) {
        return 1.0;
      }
      else if (mapZ1 === centerMapZ && mapZ2 === centerMapZ && mapX2 >= MIN_MAP_X && mapX2 <= MAX_MAP_X) {
        return 1.0;
      }

      var distanceFromCenter = CityTour.Math.distanceBetweenPoints(centerMapX, centerMapZ, mapX1, mapZ1);
      var normalizedPercentageFromCenter;

      if (distanceFromCenter <= SAFE_FROM_DECAY_DISTANCE) {
        return 1.0;
      }

      normalizedPercentageFromCenter = (distanceFromCenter - SAFE_FROM_DECAY_DISTANCE) / (DISTANCE_TO_CITY_EDGE - SAFE_FROM_DECAY_DISTANCE);
      return (Math.pow(0.5, normalizedPercentageFromCenter) - 0.5) * 2;
    };

    var isTerrainTooSteep = function(terrain, mapX, mapZ, targetMapX, targetMapZ) {
      var heightAtPoint1 = terrain.heightAtCoordinates(mapX, mapZ);
      var heightAtPoint2 = terrain.heightAtCoordinates(targetMapX, targetMapZ);
      var angle = Math.atan2((heightAtPoint1 - heightAtPoint2), CityTour.Config.BLOCK_DEPTH);

      return Math.abs(angle) > MAX_STEEPNESS;
    };

    var shouldConnectIntersections = function(terrain, mapX1, mapZ1, mapX2, mapZ2) {
      var edgeIsOnLand = terrain.materialAtCoordinates(mapX1, mapZ1) === CityTour.Terrain.LAND &&
                         terrain.materialAtCoordinates(mapX2, mapZ2) === CityTour.Terrain.LAND;

      return edgeIsOnLand &&
             (Math.random() < probabilityOfBranching(mapX1, mapZ1, mapX2, mapZ2)) &&
             !isTerrainTooSteep(terrain, mapX1, mapZ1, mapX2, mapZ2);
    };

    var branchFromIntersection = function(terrain, roadNetwork, mapX, mapZ) {
      connectIntersections(terrain, roadNetwork, mapX, mapZ, mapX - 1, mapZ);
      connectIntersections(terrain, roadNetwork, mapX, mapZ, mapX, mapZ - 1);
      connectIntersections(terrain, roadNetwork, mapX, mapZ, mapX + 1, mapZ);
      connectIntersections(terrain, roadNetwork, mapX, mapZ, mapX, mapZ + 1);
    };

    var calculateBridgeAttributes = function(terrain, roadNetwork, bridgeStartX, bridgeStartZ, targetMapX, targetMapZ) {
      var xDelta, zDelta;
      var bridgeEndX, bridgeEndZ;
      var bridgeLength;
      var heightAtTerminal1, heightAtTerminal2;
      var waterHeight, roadDeckHeight;

      var distanceFromCenter = CityTour.Math.distanceBetweenPoints(centerMapX, centerMapZ, bridgeStartX, bridgeStartZ);
      if (distanceFromCenter > SAFE_FROM_DECAY_DISTANCE) {
        return null;
      }

      if (targetMapX === bridgeStartX) {
        xDelta = 0.0;
      }
      else {
        xDelta = (targetMapX < bridgeStartX) ? -1 : 1;
      }
      if (targetMapZ === bridgeStartZ) {
        zDelta = 0.0;
      }
      else {
        zDelta = (targetMapZ < bridgeStartZ) ? -1 : 1;
      }
      bridgeEndX = targetMapX;
      bridgeEndZ = targetMapZ;

      bridgeLength = 1;
      while (terrain.materialAtCoordinates(bridgeEndX, bridgeEndZ) === CityTour.Terrain.WATER) {
        if (waterHeight === undefined) {
          waterHeight = terrain.heightAtCoordinates(bridgeEndX, bridgeEndZ);
        }
        if (roadNetwork.hasIntersection(bridgeEndX, bridgeEndZ)) {
          return null;
        }

        bridgeEndX += xDelta;
        bridgeEndZ += zDelta;
        bridgeLength += 1;

        if (bridgeEndX < -CityTour.Config.HALF_TERRAIN_COLUMNS ||
            bridgeEndX > CityTour.Config.HALF_TERRAIN_COLUMNS  ||
            bridgeEndZ < -CityTour.Config.HALF_TERRAIN_ROWS    ||
            bridgeEndZ > CityTour.Config.HALF_TERRAIN_ROWS) {
          return null;
        }
      }

      if (bridgeLength > MAX_BRIDGE_LENGTH) {
        return null;
      }

      heightAtTerminal1 = terrain.heightAtCoordinates(bridgeStartX, bridgeStartZ);
      heightAtTerminal2 = terrain.heightAtCoordinates(bridgeEndX, bridgeEndZ);
      if (Math.abs(heightAtTerminal1 - heightAtTerminal2) > MAX_HEIGHT_DIFFERENCE_BETWEEN_BRIDGE_TERMINALS) {
        return null;
      }
      roadDeckHeight = Math.max(heightAtTerminal1, heightAtTerminal2, waterHeight + MIN_BRIDGE_HEIGHT_FROM_WATER);

      if (parallelBridgeExistsNearby(bridgeStartX, bridgeStartZ, bridgeEndX, bridgeEndZ)) {
        return null;
      }

      if (Math.random() < PROBABILITY_OF_VALID_BRIDGE_BEING_BUILT) {
        return null;
      }

      return {
        roadDeckHeight: roadDeckHeight,
        endX: bridgeEndX,
        endZ: bridgeEndZ,
        xDelta: xDelta,
        zDelta: zDelta,
      };
    };

    var parallelBridgeExistsNearby = function(startX, startZ, endX, endZ) {
      var x, z;
      var xMin, xMax, zMin, zMax;

      if (endZ > startZ) {  // North/south bridge
        xMin = startX - MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS;
        xMax = endX + MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS;
        zMin = startZ;
        zMax = endZ;
      }
      else {  // East/west bridge
        xMin = startX;
        xMax = endX;
        zMin = startZ - MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS;
        zMax = endZ + MINIMUM_DISTANCE_BETWEEN_BRIDGES_IN_BLOCKS;
      }

      for (x = xMin; x <= xMax; x++) {
        for (z = zMin; z <= zMax; z++) {
          if (roadNetwork.hasIntersection(x, z) && roadNetwork.getIntersectionSurfaceType(x, z) === CityTour.RoadNetwork.BRIDGE_SURFACE) {
            return true;
          }
        }
      }

      return false;
    };

    var connectIntersections = function(terrain, roadNetwork, mapX, mapZ, targetMapX, targetMapZ) {
      var bridgeAttributes;
      var bridgeIntersectionX, bridgeIntersectionZ;
      var targetIntersectionExists;

      if (terrain.materialAtCoordinates(targetMapX, targetMapZ) === CityTour.Terrain.WATER) {
        bridgeAttributes = calculateBridgeAttributes(terrain, roadNetwork, mapX, mapZ, targetMapX, targetMapZ);

        if (bridgeAttributes !== null) {
          bridgeIntersectionX = mapX;
          bridgeIntersectionZ = mapZ;
          while (bridgeIntersectionX < bridgeAttributes.endX || bridgeIntersectionZ < bridgeAttributes.endZ) {
            roadNetwork.addEdge(bridgeIntersectionX,
                                bridgeIntersectionZ,
                                bridgeIntersectionX + bridgeAttributes.xDelta,
                                bridgeIntersectionZ + bridgeAttributes.zDelta,
                                bridgeAttributes.roadDeckHeight,
                                CityTour.RoadNetwork.BRIDGE_SURFACE);
            bridgeIntersectionX += bridgeAttributes.xDelta;
            bridgeIntersectionZ += bridgeAttributes.zDelta;
          }

          branchFromIntersection(terrain, roadNetwork, bridgeAttributes.endX, bridgeAttributes.endZ);
        }
      }
      else {
        if (shouldConnectIntersections(terrain, mapX, mapZ, targetMapX, targetMapZ)) {
          targetIntersectionExists = roadNetwork.hasIntersection(targetMapX, targetMapZ);

          roadNetwork.addEdge(mapX, mapZ, targetMapX, targetMapZ, 0.0, CityTour.RoadNetwork.TERRAIN_SURFACE);
          if (!targetIntersectionExists) {
            branchFromIntersection(terrain, roadNetwork, targetMapX, targetMapZ);
          }
        }
      }
    };

    var roadNetwork = new CityTour.RoadNetwork(terrain);
    branchFromIntersection(terrain, roadNetwork, centerMapX, centerMapZ);

    return roadNetwork;
  };

  var roadNetworkGenerator = {};

  roadNetworkGenerator.generate = function(terrain, config) {
    return buildRoadNetwork(terrain, config);
  };

  return roadNetworkGenerator;
})();
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var Promise = require('bluebird');
var core = require('../core.js');
var _ = require('lodash');

// Constants
var APP_CONFIG_FILENAME = 'kalabox.json';

var logDebug = core.log.debug;

var appDirCache = {};

var cacheAppDir = function(appName, appDir) {
  appDirCache[appName] = appDir;
};

var getCachedAppDir = function(appName) {
  var retVal = appDirCache[appName];
  if (retVal === undefined) {
    return null;
  } else {
    return retVal;
  }
};

var getGlobalConfig = function() {
  return core.deps.call(function(globalConfig) {
    return globalConfig;
  });
};

var getAppRegistry = function() {
  return new Promise(function(fulfill, reject) {
    var globalConfig = getGlobalConfig();
    var filepath = globalConfig.appRegistry;
    fs.exists(filepath, function(exists) {
      if (!exists) {
        fulfill(); // basically returns undefined
      } else {
        fs.readFile(filepath, function(err, data) {
          if (err) {
            reject(err);
          } else {
            fulfill(JSON.parse(data).appDirs);
          }
        });
      }
    });
  });
};

var setAppRegistry = function(appDirs) {
  var json = {
    appDirs: appDirs
  };
  return new Promise(function(fulfill, reject) {
    var globalConfig = getGlobalConfig();
    var filepath = globalConfig.appRegistry;
    var tempFilepath = filepath + '.tmp';
    fs.writeFile(tempFilepath, JSON.stringify(json), function(err) {
      if (err) {
        reject(err);
      } else {
        fs.rename(tempFilepath, filepath, function(err) {
          if (err) {
            reject(err);
          } else {
            fulfill();
          }
        });
      }
    });
  });
};

var getDirsAppRegistry = function() {
  return getAppRegistry()
  .then(function(appDirs) {
    if (!appDirs) {
      logDebug('DISCO => App registry does NOT contain appDirs property!');
      return [];
    } else {
      return appDirs;
    }
  });
};

var inspectDir = function(dir) {
  return new Promise(function(fulfill, reject) {
    var filepath = path.join(dir, APP_CONFIG_FILENAME);
    fs.exists(filepath, function(exists) {
      if (!exists) {
        fulfill(null);
      } else {
        fs.readFile(filepath, function(err, data) {
          if (err) {
            reject(err);
          } else {
            var json = JSON.parse(data);
            if (!json.appName) {
              logDebug('DISCO => Does NOT contain appName property!', filepath);
              fulfill(null);
            } else {
              cacheAppDir(json.appName, dir);
              fulfill(json.appName);
            }
          }
        });
      }
    });
  });
};

var inspectDirs = function(dirs) {
  return Promise.reduce(dirs, function(acc, dir) {
    return inspectDir(dir)
    .then(function(appName) {
      if (appName) {
        acc.push(appName);
      }
      return acc;
    });
  }, []);
};

var list = exports.list = function(callback) {
  // Get app dirs from app registry file.
  inspectDirs(getDirsAppRegistry())
  .all()
  .then(function(appRegistryApps) {
    logDebug('DISCO => AppsRegistry dirs.', appRegistryApps);
    callback(null, appRegistryApps);
  })
  .catch(function(err) {
    callback(err);
  });
};

var getAppDir = exports.getAppDir = function(appName, callback) {
  var appDir = getCachedAppDir(appName);
  if (!appDir) {
    // Init app dir cache using call to list.
    list(function(err, dirs) {
      if (err) {
        callback(err);
      } else {
        callback(null, getCachedAppDir(appName));
      }
    });
  } else {
    callback(null, appDir);
  }
};

var toLockfilepath = function(filepath) {
  return filepath + '.lock';
};

var acquireLock = function(filepath) {
  var lockFilepath = toLockfilepath(filepath);
  return new Promise(function(fulfill, reject) {
    fs.exists(lockFilepath, function(exists) {
      if (exists) {
        reject(new Error(lockFilepath + ' already locked!'));
      } else {
        fs.open(lockFilepath, 'wx', function(err, fd) {
          if (err) {
            reject(err);
          } else {
            fs.close(fd, function(err) {
              if (err) {
                reject(err);
              } else {
                fulfill(true);
              }
            });
          }
        });
      }
    });
  });
};

var releaseLock = function(filepath) {
  return new Promise(function(fulfill, reject) {
    var lockFilepath = toLockfilepath(filepath);
    fs.exists(lockFilepath, function(exists) {
      if (exists) {
        fs.unlink(lockFilepath, function(err) {
          if (err) {
            reject(err);
          } else {
            fulfill();
          }
        });
      } else {
        reject(new Error('Tried to unlock lock file which does NOT exist ' +
          lockFilepath));
      }
    });
  });

};

var registerAppDir = exports.registerAppDir = function(dir, callback) {
  var globalConfig = getGlobalConfig();
  var filepath = globalConfig.appRegistry;
  var locked = false;
  acquireLock(filepath)
  .then(function(lockAcquired) {
    locked = lockAcquired;
    return getAppRegistry()
    .then(function(appDirs) {
      if (!appDirs) {
        appDirs = [];
      }
      var alreadyExists = _.find(appDirs, function(appDir) {
        return appDir === dir;
      });
      if (!alreadyExists) {
        appDirs.push(dir);
        return setAppRegistry(appDirs);
      } else {
        return undefined;
      }
    });
  })
  .then(function() {
    if (locked) {
      releaseLock(filepath);
    }
    callback();
  })
  .catch(function(err) {
    if (locked) {
      releaseLock(filepath);
    }
    callback(err);
  });
};
<commit_msg>Refactoring of app discovery.<commit_after>'use strict';

var path = require('path');
var Promise = require('bluebird');
var core = require('../core.js');
var _ = require('lodash');
var fs = Promise.promisifyAll(require('fs'));

// Constants.
// @todo: bcauldwell - This should be somewhere more central.
var APP_CONFIG_FILENAME = 'kalabox.json';

// Debug info logging function.
var logDebug = core.log.debug;

// Singleton data store for app directories.
var appDirCache = {};

// Cache an appDir by appName in data store.
var cacheAppDir = function(appName, appDir) {
  appDirCache[appName] = appDir;
};

// Get cached appDir by appName from data store.
var getCachedAppDir = function(appName) {
  var retVal = appDirCache[appName];
  if (retVal === undefined) {
    return null;
  } else {
    return retVal;
  }
};

// Get global config.
var getGlobalConfig = function() {
  return core.deps.lookup('globalConfig');
};

// Read from app registry file.
var getAppRegistry = function() {

  var globalConfig = getGlobalConfig();

  // Check if file exists.
  fs.exists(globalConfig.appRegistry)
  .then(function(exists) {
    if (exists) {
      // If file exists then read contents.
      return fs.readFile(globalConfig.appRegistry)
      .then(function(data) {
        // Return appDirs from data read from file.
        return JSON.parse(data).appDirs;
      });
    } else {
      return null;
    }
  });

};

// Rewrite the app registry file.
var setAppRegistry = function(appDirs) {

  var filepath = getGlobalConfig().appRegistry;

  var tempFilepath = filepath + '.tmp';

  var json = {
    appDirs: appDirs
  };

  // Write to temp file.
  return fs.writeFile(tempFilepath, JSON.stringify(json))
  // Rename temp file to normal file.
  .then(function() {
    return fs.rename(tempFilepath, filepath);
  });

};

// Get appDirs from app registry.
var getDirsAppRegistry = function() {
  // Get app registry.
  return getAppRegistry()
  .then(function(appDirs) {
    if (!appDirs) {
      // Write warning to log if appDirs were not found.
      logDebug('DISCO => App registry does NOT contain appDirs property!');
      return [];
    } else {
      return appDirs;
    }
  });
};

// Given an directory, inspect it and return the appName.
var inspectDir = function(dir) {

  var filepath = path.join(dir, APP_CONFIG_FILENAME);

  return fs.exists(filepath)
  // Read and parse file contents if it exists.
  .then(function(exists) {
    if (!exists) {
      return null;
    } else {
      return fs.readFile(filepath)
      .then(function(data) {
        return JSON.parse(data);
      });
    }
  })
  // Return appName.
  .then(function(json) {
    if (!json) {
      return null;
    } else if (!json.appName) {
      logDebug('DISCO => Does NOT contain appName property!', filepath);
      return null;
    } else {
      cacheAppDir(json.appName, dir);
      return json.appName;
    }
  });

};

// Inspect a list of directories, return list of appNames.
var inspectDirs = function(dirs) {
  return Promise.map(dirs, inspectDir)
  .all()
  .filter(_.identity);
};

// Return list of app names from app registry dirs.
var list = exports.list = function(callback) {
  // Get list of dirs from app registry.
  getDirsAppRegistry()
  // Map app dirs to app names.
  .then(inspectDirs)
  .all()
  .tap(function(appRegistryApps) {
    logDebug('DISCO => AppsRegistry dirs.', appRegistryApps);
  })
  .nodeify(callback);

};

// Gets the app directory for an appName.
var getAppDir = exports.getAppDir = function(appName, callback) {

  // Get app dir from cache.
  var appDir = getCachedAppDir(appName);

  // Init a promise.
  return Promise.resolve()
  .then(function() {

    if (appDir) {
      // Return cached value.
      return appDir;
    } else {
      // Reload and cache app dirs, then get app dir from cache again.
      return list()
      .then(function() {
        return getCachedAppDir(appName);
      });
    }

  })
  .nodeify();

};

// Translate a filepath to a lock filepath for that filepath.
var toLockfilepath = function(filepath) {
  return filepath + '.lock';
};

// Return true if lock file exists.
var isLocked = function(filepath) {
  return fs.exists(toLockfilepath(filepath));
};

// Acquire app registry lock file.
var acquireLock = function(filepath) {

  var lockFilepath = toLockfilepath(filepath);

  // Open lock file.
  return isLocked(filepath)
  .then(function(isLocked) {
    if (isLocked) {
      // Throw an error if the file already exists.
      throw new Error(filepath + ' already locked!');
    } else {
      return fs.open(lockFilepath, 'wx');
    }
  })
  // Close lock file.
  .then(fs.close);

};

// Release app registry lock file.
var releaseLock = function(filepath) {

  var lockFilepath = toLockfilepath(filepath);

  // Check to make sure lock file exists.
  isLocked(filepath)
  .then(function(isLocked) {
    if (!isLocked) {
      // Throw an error if the file does not exist.
      throw new Error('Tried to unlock lock file which does NOT exist ' +
        lockFilepath);
    }
  })
  // Unlink lock file.
  .then(function() {
    return fs.unlink(lockFilepath);
  });

};

var registerAppDir = exports.registerAppDir = function(dir, callback) {

  var filepath = getGlobalConfig().appRegistry;

  var locked = false;

  // Acquire lock.
  acquireLock(filepath)
  .then(function() {
    locked = true;
    // Get app dirs.
    return getAppRegistry()
    .then(function(appDirs) {
      if (!appDirs) {
        appDirs = [];
      }
      // Add appDir to app registry.
      var alreadyExists = _.find(appDirs, _.partial(_.isEqual, dir));
      if (!alreadyExists) {
        appDirs.push(dir);
        return setAppRegistry(appDirs);
      }
    });
  })
  // Make sure we always release the lock.
  .finally(function() {
    if (locked) {
      return releaseLock(filepath);
    }
  })
  // Return.
  .nodeify(callback);

};
<|endoftext|>


<commit_before>/* ======= Default Directives ======= */
directives[config.prefix + "if"] = function(el, val, vdom) {
  var evaluated = new Function("return " + val);
  if(!evaluated()) {
    el.textContent = "";
  } else {
    el.textContent = vdom.val(self.$data);
  }
}

directives[config.prefix + "show"] = function(el, val, vdom) {
  var evaluated = new Function("return " + val);
  if(!evaluated()) {
    el.style.display = 'none';
  } else {
    el.style.display = 'block';
  }
}

directives[config.prefix + "on"] = function(el, val, vdom) {
  var splitVal = val.split(":");
  var eventToCall = splitVal[0];
  var methodToCall = splitVal[1];
  el.addEventListener(eventToCall, function() {
    self.callMethod(methodToCall);
  });
  delete vdom.props[config.prefix + "on"];
}

directives[config.prefix + "model"] = function(el, val, vdom) {
  el.value = self.get(val);
  el.addEventListener("input", function() {
    self.set(val, el.value);
  });
  delete vdom.props[config.prefix + "model"];
}

directives[config.prefix + "for"] = function(el, val, vdom) {
  var parts = val.split(" in ");
  var alias = parts[0];
  var array = self.get(parts[1]);
}

directives[config.prefix + "once"] = function(el, val, vdom) {
  vdom.once = true;
}

directives[config.prefix + "text"] = function(el, val, vdom) {
  el.textContent = val;
}

directives[config.prefix + "html"] = function(el, val, vdom) {
  el.innerHTML = val;
}

directives[config.prefix + "mask"] = function(el, val, vdom) {

}
<commit_msg>on directive uses event parameter<commit_after>/* ======= Default Directives ======= */
directives[config.prefix + "if"] = function(el, val, vdom) {
  var evaluated = new Function("return " + val);
  if(!evaluated()) {
    el.textContent = "";
  } else {
    el.textContent = vdom.val(self.$data);
  }
}

directives[config.prefix + "show"] = function(el, val, vdom) {
  var evaluated = new Function("return " + val);
  if(!evaluated()) {
    el.style.display = 'none';
  } else {
    el.style.display = 'block';
  }
}

directives[config.prefix + "on"] = function(el, val, vdom) {
  var splitVal = val.split(":");
  var eventToCall = splitVal[0];
  var methodToCall = splitVal[1];
  el.addEventListener(eventToCall, function(e) {
    self.callMethod(methodToCall, [e]);
  });
  delete vdom.props[config.prefix + "on"];
}

directives[config.prefix + "model"] = function(el, val, vdom) {
  el.value = self.get(val);
  el.addEventListener("input", function() {
    self.set(val, el.value);
  });
  delete vdom.props[config.prefix + "model"];
}

directives[config.prefix + "for"] = function(el, val, vdom) {
  var parts = val.split(" in ");
  var alias = parts[0];
  var array = self.get(parts[1]);
}

directives[config.prefix + "once"] = function(el, val, vdom) {
  vdom.once = true;
}

directives[config.prefix + "text"] = function(el, val, vdom) {
  el.textContent = val;
}

directives[config.prefix + "html"] = function(el, val, vdom) {
  el.innerHTML = val;
}

directives[config.prefix + "mask"] = function(el, val, vdom) {

}
<|endoftext|>


<commit_before>/**
 * Machine id.
 *
 * Create a random 3-byte value (i.e. unique for this
 * process). Other drivers use a md5 of the machine id here, but
 * that would mean an asyc call to gethostname, so we don't bother.
 * @ignore
 */
var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10);

// Regular expression that checks for hex value
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");

/**
* Create a new ObjectID instance
*
* @class
* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
* @property {number} generationTime The generation time of this ObjectId instance
* @return {ObjectID} instance of ObjectID.
*/
var ObjectID = function ObjectID(id) {
  // Duck-typing to support ObjectId from different npm packages
  if(id instanceof ObjectID) return id;
  if(!(this instanceof ObjectID)) return new ObjectID(id);

  this._bsontype = 'ObjectID';

  var __id = null;
  var valid = ObjectID.isValid(id);

  // Throw an error if it's not a valid setup
  if(!valid && id != null){
    throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
  } else if(valid && typeof id == 'string' && id.length == 24) {
    return ObjectID.createFromHexString(id);
  } else if(id == null || typeof id == 'number') {
    // convert to 12 byte binary string
    this.id = this.generate(id);
  } else if(id != null && id.length === 12) {
    // assume 12 byte string
    this.id = id;
  } else if(id != null && id.toHexString) {
    // Duck-typing to support ObjectId from different npm packages
    return id;
  } else {
    throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
  }

  if(ObjectID.cacheHexString) this.__id = this.toHexString();
};

// Allow usage of ObjectId as well as ObjectID
var ObjectId = ObjectID;

// Precomputed hex table enables speedy hex string conversion
var hexTable = [];
for (var i = 0; i < 256; i++) {
  hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16);
}

/**
* Return the ObjectID id as a 24 byte hex string representation
*
* @method
* @return {string} return the 24 byte hex string representation.
*/
ObjectID.prototype.toHexString = function() {
  if(ObjectID.cacheHexString && this.__id) return this.__id;

  var hexString = '';
  if(!this.id || !this.id.length) {
    throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']');
  }

  if(this.id instanceof _Buffer) {
    hexString = convertToHex(this.id);
    if(ObjectID.cacheHexString) this.__id = hexString;
    return hexString;
  }

  for (var i = 0; i < this.id.length; i++) {
    hexString += hexTable[this.id.charCodeAt(i)];
  }

  if(ObjectID.cacheHexString) this.__id = hexString;
  return hexString;
};

/**
* Update the ObjectID index used in generating new ObjectID's on the driver
*
* @method
* @return {number} returns next index value.
* @ignore
*/
ObjectID.prototype.get_inc = function() {
  return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF;
};

/**
* Update the ObjectID index used in generating new ObjectID's on the driver
*
* @method
* @return {number} returns next index value.
* @ignore
*/
ObjectID.prototype.getInc = function() {
  return this.get_inc();
};

/**
* Generate a 12 byte id buffer used in ObjectID's
*
* @method
* @param {number} [time] optional parameter allowing to pass in a second based timestamp.
* @return {Buffer} return the 12 byte id buffer string.
*/
ObjectID.prototype.generate = function(time) {
  if ('number' != typeof time) {
    time = ~~(Date.now()/1000);
  }

  // Use pid
  var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF;
  var inc = this.get_inc();
  // Buffer used
  var buffer = new Buffer(12);
  // Encode time
  buffer[3] = time & 0xff;
  buffer[2] = (time >> 8) & 0xff;
  buffer[1] = (time >> 16) & 0xff;
  buffer[0] = (time >> 24) & 0xff;
  // Encode machine
  buffer[6] = MACHINE_ID & 0xff;
  buffer[5] = (MACHINE_ID >> 8) & 0xff;
  buffer[4] = (MACHINE_ID >> 16) & 0xff;
  // Encode pid
  buffer[8] = pid & 0xff;
  buffer[7] = (pid >> 8) & 0xff;
  // Encode index
  buffer[11] = inc & 0xff;
  buffer[10] = (inc >> 8) & 0xff;
  buffer[9] = (inc >> 16) & 0xff;
  // Return the buffer
  return buffer;
};

/**
* Converts the id into a 24 byte hex string for printing
*
* @param {String} format The Buffer toString format parameter.
* @return {String} return the 24 byte hex string representation.
* @ignore
*/
ObjectID.prototype.toString = function(format) {
  // Is the id a buffer then use the buffer toString method to return the format
  if(this.id instanceof Buffer) {
    return this.id.toString(format || 'hex');
  }

  // if(this.buffer )
  return this.toHexString();
};

/**
* Converts to a string representation of this Id.
*
* @return {String} return the 24 byte hex string representation.
* @ignore
*/
ObjectID.prototype.inspect = ObjectID.prototype.toString;

/**
* Converts to its JSON representation.
*
* @return {String} return the 24 byte hex string representation.
* @ignore
*/
ObjectID.prototype.toJSON = function() {
  return this.toHexString();
};

/**
* Compares the equality of this ObjectID with `otherID`.
*
* @method
* @param {object} otherID ObjectID instance to compare against.
* @return {boolean} the result of comparing two ObjectID's
*/
ObjectID.prototype.equals = function equals (otherId) {
  var id;

  if(otherId instanceof ObjectID) {
    return this.toString() == otherId.toString();
  } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12 && this.id instanceof _Buffer) {
    return otherId === this.id.toString('binary');
  } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 24) {
    return otherId.toLowerCase() === this.toHexString();
  } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12) {
    return otherId === this.id;
  } else if(otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) {
    return otherId.toHexString() === this.toHexString();
  } else {
    return false;
  }
}

/**
* Returns the generation date (accurate up to the second) that this ID was generated.
*
* @method
* @return {date} the generation date
*/
ObjectID.prototype.getTimestamp = function() {
  var timestamp = new Date();
  var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
  timestamp.setTime(Math.floor(time) * 1000);
  return timestamp;
}

/**
* @ignore
*/
ObjectID.index = ~~(Math.random() * 0xFFFFFF);

/**
* @ignore
*/
ObjectID.createPk = function createPk () {
  return new ObjectID();
};

/**
* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
*
* @method
* @param {number} time an integer number representing a number of seconds.
* @return {ObjectID} return the created ObjectID
*/
ObjectID.createFromTime = function createFromTime (time) {
  var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  // Encode time into first 4 bytes
  buffer[3] = time & 0xff;
  buffer[2] = (time >> 8) & 0xff;
  buffer[1] = (time >> 16) & 0xff;
  buffer[0] = (time >> 24) & 0xff;
  // Return the new objectId
  return new ObjectID(buffer);
};

// Lookup tables
var encodeLookup = '0123456789abcdef'.split('')
var decodeLookup = []
var i = 0
while (i < 10) decodeLookup[0x30 + i] = i++
while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++

var _Buffer = Buffer;
var convertToHex = function(bytes) {
  return bytes.toString('hex');
}

/**
* Creates an ObjectID from a hex string representation of an ObjectID.
*
* @method
* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring.
* @return {ObjectID} return the created ObjectID
*/
ObjectID.createFromHexString = function createFromHexString (string) {
  // Throw an error if it's not a valid setup
  if(typeof string === 'undefined' || string != null && string.length != 24)
    throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");

  var length = string.length;

  if(length > 12*2) {
    throw new Error('Id cannot be longer than 12 bytes');
  }

  // Calculate lengths
  var sizeof = length >> 1;
  var array = new _Buffer(sizeof);
  var n = 0;
  var i = 0;

  while (i < length) {
    array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]
  }

  return new ObjectID(array);
};

/**
* Checks if a value is a valid bson ObjectId
*
* @method
* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
*/
ObjectID.isValid = function isValid(id) {
  if(id == null) return false;

  if(typeof id == 'number') {
    return true;
  }

  if(typeof id == 'string') {
    return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id));
  }

  if(id instanceof ObjectID) {
    return true;
  }

  if(id instanceof _Buffer) {
    return true;
  }

  // Duck-Typing detection of ObjectId like objects
  if(id.toHexString) {
    return id.id.length == 12 || (id.id.length == 24 && checkForHexRegExp.test(id.id));
  }

  return false;
};

/**
* @ignore
*/
Object.defineProperty(ObjectID.prototype, "generationTime", {
   enumerable: true
 , get: function () {
     return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
   }
 , set: function (value) {
     // Encode time into first 4 bytes
     this.id[3] = value & 0xff;
     this.id[2] = (value >> 8) & 0xff;
     this.id[1] = (value >> 16) & 0xff;
     this.id[0] = (value >> 24) & 0xff;
   }
});

/**
 * Expose.
 */
module.exports = ObjectID;
module.exports.ObjectID = ObjectID;
module.exports.ObjectId = ObjectID;
<commit_msg>optimized most common objectId usage new ObjectId()<commit_after>/**
 * Machine id.
 *
 * Create a random 3-byte value (i.e. unique for this
 * process). Other drivers use a md5 of the machine id here, but
 * that would mean an asyc call to gethostname, so we don't bother.
 * @ignore
 */
var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10);

// Regular expression that checks for hex value
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
var hasBufferType = false;

// Check if buffer exists
try {
  if(Buffer && Buffer.from) hasBufferType = true;
} catch(err) {};

/**
* Create a new ObjectID instance
*
* @class
* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
* @property {number} generationTime The generation time of this ObjectId instance
* @return {ObjectID} instance of ObjectID.
*/
var ObjectID = function ObjectID(id) {
  // Duck-typing to support ObjectId from different npm packages
  if(id instanceof ObjectID) return id;
  if(!(this instanceof ObjectID)) return new ObjectID(id);

  this._bsontype = 'ObjectID';

  // The most common usecase (blank id, new objectId instance)
  if(id == null || typeof id == 'number') {
    // Generate a new id
    this.id = this.generate(id);
    // If we are caching the hex string
    if(ObjectID.cacheHexString) this.__id = this.toString('hex');
    // Return the object
    return;
  }

  // Check if the passed in id is valid
  var valid = ObjectID.isValid(id);

  // Throw an error if it's not a valid setup
  if(!valid && id != null){
    throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
  } else if(valid && typeof id == 'string' && id.length == 24 && hasBufferType) {
    return new ObjectID(Buffer.from(id, 'hex'));
  } else if(valid && typeof id == 'string' && id.length == 24) {
    return ObjectID.createFromHexString(id);
  } else if(id != null && id.length === 12) {
    // assume 12 byte string
    this.id = id;
  } else if(id != null && id.toHexString) {
    // Duck-typing to support ObjectId from different npm packages
    return id;
  } else {
    throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
  }

  if(ObjectID.cacheHexString) this.__id = this.toString('hex');
};

// Allow usage of ObjectId as well as ObjectID
var ObjectId = ObjectID;

// Precomputed hex table enables speedy hex string conversion
var hexTable = [];
for (var i = 0; i < 256; i++) {
  hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16);
}

/**
* Return the ObjectID id as a 24 byte hex string representation
*
* @method
* @return {string} return the 24 byte hex string representation.
*/
ObjectID.prototype.toHexString = function() {
  if(ObjectID.cacheHexString && this.__id) return this.__id;

  var hexString = '';
  if(!this.id || !this.id.length) {
    throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']');
  }

  if(this.id instanceof _Buffer) {
    hexString = convertToHex(this.id);
    if(ObjectID.cacheHexString) this.__id = hexString;
    return hexString;
  }

  for (var i = 0; i < this.id.length; i++) {
    hexString += hexTable[this.id.charCodeAt(i)];
  }

  if(ObjectID.cacheHexString) this.__id = hexString;
  return hexString;
};

/**
* Update the ObjectID index used in generating new ObjectID's on the driver
*
* @method
* @return {number} returns next index value.
* @ignore
*/
ObjectID.prototype.get_inc = function() {
  return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF;
};

/**
* Update the ObjectID index used in generating new ObjectID's on the driver
*
* @method
* @return {number} returns next index value.
* @ignore
*/
ObjectID.prototype.getInc = function() {
  return this.get_inc();
};

/**
* Generate a 12 byte id buffer used in ObjectID's
*
* @method
* @param {number} [time] optional parameter allowing to pass in a second based timestamp.
* @return {Buffer} return the 12 byte id buffer string.
*/
ObjectID.prototype.generate = function(time) {
  if ('number' != typeof time) {
    time = ~~(Date.now()/1000);
  }

  // Use pid
  var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF;
  var inc = this.get_inc();
  // Buffer used
  var buffer = new Buffer(12);
  // Encode time
  buffer[3] = time & 0xff;
  buffer[2] = (time >> 8) & 0xff;
  buffer[1] = (time >> 16) & 0xff;
  buffer[0] = (time >> 24) & 0xff;
  // Encode machine
  buffer[6] = MACHINE_ID & 0xff;
  buffer[5] = (MACHINE_ID >> 8) & 0xff;
  buffer[4] = (MACHINE_ID >> 16) & 0xff;
  // Encode pid
  buffer[8] = pid & 0xff;
  buffer[7] = (pid >> 8) & 0xff;
  // Encode index
  buffer[11] = inc & 0xff;
  buffer[10] = (inc >> 8) & 0xff;
  buffer[9] = (inc >> 16) & 0xff;
  // Return the buffer
  return buffer;
};

/**
* Converts the id into a 24 byte hex string for printing
*
* @param {String} format The Buffer toString format parameter.
* @return {String} return the 24 byte hex string representation.
* @ignore
*/
ObjectID.prototype.toString = function(format) {
  // Is the id a buffer then use the buffer toString method to return the format
  if(this.id && this.id.copy) {
    return this.id.toString(format || 'hex');
  }

  // if(this.buffer )
  return this.toHexString();
};

/**
* Converts to a string representation of this Id.
*
* @return {String} return the 24 byte hex string representation.
* @ignore
*/
ObjectID.prototype.inspect = ObjectID.prototype.toString;

/**
* Converts to its JSON representation.
*
* @return {String} return the 24 byte hex string representation.
* @ignore
*/
ObjectID.prototype.toJSON = function() {
  return this.toHexString();
};

/**
* Compares the equality of this ObjectID with `otherID`.
*
* @method
* @param {object} otherID ObjectID instance to compare against.
* @return {boolean} the result of comparing two ObjectID's
*/
ObjectID.prototype.equals = function equals (otherId) {
  var id;

  if(otherId instanceof ObjectID) {
    return this.toString() == otherId.toString();
  } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12 && this.id instanceof _Buffer) {
    return otherId === this.id.toString('binary');
  } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 24) {
    return otherId.toLowerCase() === this.toHexString();
  } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12) {
    return otherId === this.id;
  } else if(otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) {
    return otherId.toHexString() === this.toHexString();
  } else {
    return false;
  }
}

/**
* Returns the generation date (accurate up to the second) that this ID was generated.
*
* @method
* @return {date} the generation date
*/
ObjectID.prototype.getTimestamp = function() {
  var timestamp = new Date();
  var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
  timestamp.setTime(Math.floor(time) * 1000);
  return timestamp;
}

/**
* @ignore
*/
ObjectID.index = ~~(Math.random() * 0xFFFFFF);

/**
* @ignore
*/
ObjectID.createPk = function createPk () {
  return new ObjectID();
};

/**
* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
*
* @method
* @param {number} time an integer number representing a number of seconds.
* @return {ObjectID} return the created ObjectID
*/
ObjectID.createFromTime = function createFromTime (time) {
  var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  // Encode time into first 4 bytes
  buffer[3] = time & 0xff;
  buffer[2] = (time >> 8) & 0xff;
  buffer[1] = (time >> 16) & 0xff;
  buffer[0] = (time >> 24) & 0xff;
  // Return the new objectId
  return new ObjectID(buffer);
};

// Lookup tables
var encodeLookup = '0123456789abcdef'.split('')
var decodeLookup = []
var i = 0
while (i < 10) decodeLookup[0x30 + i] = i++
while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++

var _Buffer = Buffer;
var convertToHex = function(bytes) {
  return bytes.toString('hex');
}

/**
* Creates an ObjectID from a hex string representation of an ObjectID.
*
* @method
* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring.
* @return {ObjectID} return the created ObjectID
*/
ObjectID.createFromHexString = function createFromHexString (string) {
  // Throw an error if it's not a valid setup
  if(typeof string === 'undefined' || string != null && string.length != 24)
    throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");

  var length = string.length;

  if(length > 12*2) {
    throw new Error('Id cannot be longer than 12 bytes');
  }

  // Calculate lengths
  var sizeof = length >> 1;
  var array = new _Buffer(sizeof);
  var n = 0;
  var i = 0;

  while (i < length) {
    array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]
  }

  return new ObjectID(array);
};

/**
* Checks if a value is a valid bson ObjectId
*
* @method
* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
*/
ObjectID.isValid = function isValid(id) {
  if(id == null) return false;

  if(typeof id == 'number') {
    return true;
  }

  if(typeof id == 'string') {
    return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id));
  }

  if(id instanceof ObjectID) {
    return true;
  }

  if(id instanceof _Buffer) {
    return true;
  }

  // Duck-Typing detection of ObjectId like objects
  if(id.toHexString) {
    return id.id.length == 12 || (id.id.length == 24 && checkForHexRegExp.test(id.id));
  }

  return false;
};

/**
* @ignore
*/
Object.defineProperty(ObjectID.prototype, "generationTime", {
   enumerable: true
 , get: function () {
     return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
   }
 , set: function (value) {
     // Encode time into first 4 bytes
     this.id[3] = value & 0xff;
     this.id[2] = (value >> 8) & 0xff;
     this.id[1] = (value >> 16) & 0xff;
     this.id[0] = (value >> 24) & 0xff;
   }
});

/**
 * Expose.
 */
module.exports = ObjectID;
module.exports.ObjectID = ObjectID;
module.exports.ObjectId = ObjectID;
<|endoftext|>


<commit_before>'use strict';

/**
 * A builder builds command line arguments for ping in linux environment
 * @module lib/builder/linux
 */
var util = require('util');

var builder = {};

/**
 * Cross platform config representation
 * @typedef {Object} PingConfig
 * @property {boolean} numeric - Map IP address to hostname or not
 * @property {number} timeout - Time duration for ping command to exit
 * @property {number} min_reply - Exit after sending number of ECHO_REQUEST
 * @property {boolean} v6 - Use IPv4 (default) or IPv6
 * @property {string} sourceAddr - source address for sending the ping
 * @property {string[]} extra - Optional options does not provided
 */

var defaultConfig = {
    numeric: true,
    timeout: 2,
    min_reply: 1,
    v6: false,
    sourceAddr: '',
    extra: [],
};

/**
 * Get the finalized array of command line arguments
 * @param {string} target - hostname or ip address
 * @param {PingConfig} [config] - Configuration object for cmd line argument
 * @return {string[]} - Command line argument according to the configuration
 */
builder.getResult = function (target, config) {
    var _config = config || {};

    // Empty argument
    var ret = [];

    // Make every key in config has been setup properly
    var keys = ['numeric', 'timeout', 'min_reply', 'v6', 'sourceAddr', 'extra'];
    keys.forEach(function (k) {
        // Falsy value will be overrided without below checking
        if (typeof(_config[k]) !== 'boolean') {
            _config[k] = _config[k] || defaultConfig[k];
        }
    });

    if (_config.numeric) {
        ret.push('-n');
    }

    if (_config.timeout) {
        ret = ret.concat([
            '-w',
            util.format('%d', _config.timeout),
        ]);
    }

    if (_config.min_reply) {
        ret = ret.concat([
            '-c',
            util.format('%d', _config.min_reply),
        ]);
    }

    if (_config.sourceAddr) {
        ret = ret.concat([
            '-I',
            util.format('%s', _config.sourceAddr),
        ]);
    }

    if (_config.extra) {
        ret = ret.concat(_config.extra);
    }

    ret.push(target);

    return ret;
};

module.exports = builder;
<commit_msg>use timeout option when timeout config option is set<commit_after>'use strict';

/**
 * A builder builds command line arguments for ping in linux environment
 * @module lib/builder/linux
 */
var util = require('util');

var builder = {};

/**
 * Cross platform config representation
 * @typedef {Object} PingConfig
 * @property {boolean} numeric - Map IP address to hostname or not
 * @property {number} timeout - Time duration for ping command to exit
 * @property {number} min_reply - Exit after sending number of ECHO_REQUEST
 * @property {boolean} v6 - Use IPv4 (default) or IPv6
 * @property {string} sourceAddr - source address for sending the ping
 * @property {string[]} extra - Optional options does not provided
 */

var defaultConfig = {
    numeric: true,
    timeout: 2,
    min_reply: 1,
    v6: false,
    sourceAddr: '',
    extra: [],
};

/**
 * Get the finalized array of command line arguments
 * @param {string} target - hostname or ip address
 * @param {PingConfig} [config] - Configuration object for cmd line argument
 * @return {string[]} - Command line argument according to the configuration
 */
builder.getResult = function (target, config) {
    var _config = config || {};

    // Empty argument
    var ret = [];

    // Make every key in config has been setup properly
    var keys = ['numeric', 'timeout', 'min_reply', 'v6', 'sourceAddr', 'extra'];
    keys.forEach(function (k) {
        // Falsy value will be overrided without below checking
        if (typeof(_config[k]) !== 'boolean') {
            _config[k] = _config[k] || defaultConfig[k];
        }
    });

    if (_config.numeric) {
        ret.push('-n');
    }

    if (_config.timeout) {
        ret = ret.concat([
            '-W',
            util.format('%d', _config.timeout),
        ]);
    }

    if (_config.min_reply) {
        ret = ret.concat([
            '-c',
            util.format('%d', _config.min_reply),
        ]);
    }

    if (_config.sourceAddr) {
        ret = ret.concat([
            '-I',
            util.format('%s', _config.sourceAddr),
        ]);
    }

    if (_config.extra) {
        ret = ret.concat(_config.extra);
    }

    ret.push(target);

    return ret;
};

module.exports = builder;
<|endoftext|>


<commit_before>(function($, window, document, undefined) {

    var pluginName = "jqueryVideoLightning",
        defaults = {
            id: "y-dQw4w9WgXcQ",
            width: "640px",
            height: "390px",
            autoplay: 0,
            autohide: 2,
            controls: 1,
            iv_load_policy: 1,
            loop: 0,
            modestbranding: 0,
            playlist: "",
            related: 0,
            showinfo: 1,
            start_time: 0,
            theme: "dark",
            color: "",
            byline: 1,
            portrait: 1,
            effect_in: "fadeIn",
            ease_in: 300,
            ease_out: 0,
            backdrop_color: "#000",
            backdrop_opacity: 1,
            glow: 0,
            glow_color: "#fff"
        };

    function JQVideoLightning ( element, options ) {
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    JQVideoLightning.prototype = {
        init: function () {
            var void_target, void_elements, target, target_class;
            void_elements = [ "AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "META", "PARAM", "SOURCE", "TRACK", "WBR" ];
            void_target = 0;
            target_class = ".video-target";

            $(this.element).css( "cursor", "pointer" );

            if (($.inArray($(this.element).prop('tagName'), void_elements)) == -1) {
                target = $(this.element);
                target.addClass("video-target");
            }
            else {
                $("body").append('
' + '
');
                target = $(target_class);
                void_target = 1;
            }

            function callPlayer() {
                $(this.player(target, $(this).settings), void_target);
            }

            $(this.element).on( "click", $.proxy(callPlayer, this));
        },

        player: function ( target, settings, void_target ) {
            var id, video_autohide, video_autoplay, video_byline, video_color, video_controls, video_height, video_id, video_iv_load_policy, video_loop, video_modestbranding, video_playlist, video_portrait, video_related, video_showinfo, video_start_time, video_theme, video_vendor, video_width, vimeo_player, youtube_player, ease_in, glow, glow_color, backdrop_color, backdrop_opacity, red, green, blue, effect_in, display_ratio;

            settings = this.settings;

            if (target.find(".video-wrapper").is(':visible')) {
                target.find(".video").remove();
                target.find(".video-wrapper").hide((settings.easeOut));
                target.find(".video-wrapper").remove();
                if (void_target == 1){target.remove()}
                return $(this).destroy;
            } else {
                id = (typeof target.data("videoId") === 'undefined') ? settings.id : target.data("videoId");
                video_vendor = id.split("-")[0];
                if ((video_vendor === "v") || (video_vendor === "V")) {
                    video_vendor = "Vimeo";
                } else {
                    video_vendor = "Youtube";
                }
                video_id = id.split("-")[1]; // Youtube: "y-XbTtgr8J8uU" Vimeo: "v-32187194"
                video_width = target.data("videoWidth") || settings.width; // Y&V: video width in px
                video_height = target.data("videoHeight") || settings.height; // Y&V: video height in px
                display_ratio = parseInt(video_height) / parseInt(video_width);
                if (parseInt(video_width) > $(document).width() - 20) {
                    video_width = $(document).width() - 20 + "px";
                    video_height = display_ratio * parseInt(video_width) + "px";
                }
                video_autoplay = target.data("videoAutoplay") || settings.autoplay; // Y&V: start playback immediately (0,1)
                video_autohide = target.data("videoAutohide") || settings.autohide; // Y: auto hide controls after video load (0,1,2)
                video_controls = target.data("videoControls") || settings.controls; // Y: display controls (0,1,2)
                video_iv_load_policy = target.data("videoIvLoadPolicy") || settings.iv_load_policy; // Y: display annotations (1,3)
                video_loop = target.data("videoLoop") || settings.loop; // Y&V: loop video playback (0,1)
                video_modestbranding = target.data("videoModestbranding") || settings.modestbranding; // Y: hide large Youtube logo (0,1)
                video_playlist = target.data("videoPlaylist") || settings.playlist; // Y: comma-separated list of video IDs to play
                video_related = target.data("videoRelated") || settings.related; // Y: show related videos when playback id finished (0,1)
                video_showinfo = target.data("videoShowinfo") || settings.showinfo; // Y: display title, uploader (0,1)  V: display title (0,1)
                video_start_time = target.data("videoStartTime") || settings.start_time; // Y: playback start position in seconds (ex. "132" starts at 2mins, 12secs)
                video_theme = target.data("videoTheme") || settings.theme; // Y: player theme ("dark","light")
                if (video_vendor == "Vimeo"){
                    video_color = target.data("videoColor") || prepHex(settings.color); // V: player controls color (hex code minus the "#", default is "00adef")
                } else {
                    video_color = target.data("videoColor") || settings.color; // Y: player controls color ("red","white")
                }
                video_byline = target.data("videoByline") || settings.byline; // V: display byline (0,1)
                video_portrait = target.data("videoPortrait") || settings.portrait; // V: display user's portrait (0,1)
                youtube_player = $("<embed src=\"https://www.youtube.com/embed/" + video_id + "?autoplay=" + video_autoplay + "&autohide=" + video_autohide + "&controls=" + video_controls + "&iv_load_policy=" + video_iv_load_policy + "&loop=" + video_loop + "&modestbranding=" + video_modestbranding + "&playlist=" + video_playlist + "&rel=" + video_related + "&showinfo=" + video_showinfo + "&start=" + video_start_time + "&theme=" + video_theme + "&color=" + video_color + "\" width=\"" + video_width + "\" height=\"" + video_height + "\" frameborder=\"0\" allowfullscreen></embed>");
                vimeo_player = $("");
                effect_in = settings.effect_in;
                ease_in = settings.ease_in;
                glow = settings.glow;
                glow_color = settings.glow_color;
                backdrop_color = settings.backdrop_color;
                backdrop_opacity = settings.backdrop_opacity;

                function colorConverter(hex){
                    red = parseInt((prepHex(hex)).substring(0,2),16);
                    blue = parseInt((prepHex(hex)).substring(2,4),16);
                    green = parseInt((prepHex(hex)).substring(4,6),16);
                    return {
                        red: red,
                        blue: blue,
                        green: green
                    };
                }

                function fullHex(hex){
                    hex = "#" + prepHex(hex);
                    return hex;
                }

                function prepHex(hex){
                    hex = (hex.charAt(0)=="#") ? hex.split("#")[1]:hex;
                    if (hex.length == 3){
                        hex = hex + hex;
                    }
                    return hex;
                }

                target.append('

');
                target.find(".video-wrapper").css({
                    backgroundColor: "rgba(" + colorConverter(backdrop_color).red + "," + colorConverter(backdrop_color).blue + "," + colorConverter(backdrop_color).green + "," + backdrop_opacity + ")"
                });
                target.find(".video-frame").css({
                    width:  video_width,
                    height: video_height,
                    marginTop: '-' + ((video_height.split("p")[0])/2) + 'px',
                    marginLeft: '-' + ((video_width.split("p")[0])/2) + 'px',
                    boxShadow: '0px 0px ' + glow + 'px ' + (glow/5) + 'px ' + fullHex(glow_color)
                });
                target.find(".video-wrapper")[effect_in](ease_in);
                if (video_vendor === "Vimeo") {
                    return target.find(".video").append(vimeo_player);
                } else {
                    return target.find(".video").append(youtube_player);
                }
            }
        },

        destroy: function () {
            $(this).off();
            $(this).removeData();
        }
    };

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new JQVideoLightning( this, options ) );
            }
        });
    };

    return this;

})( jQuery, window, document );<commit_msg>fix bug causing failure in Firefox<commit_after>(function($, window, document, undefined) {

    var pluginName = "jqueryVideoLightning",
        defaults = {
            id: "y-dQw4w9WgXcQ",
            width: "640px",
            height: "390px",
            autoplay: 0,
            autohide: 2,
            controls: 1,
            iv_load_policy: 1,
            loop: 0,
            modestbranding: 0,
            playlist: "",
            related: 0,
            showinfo: 1,
            start_time: 0,
            theme: "dark",
            color: "",
            byline: 1,
            portrait: 1,
            effect_in: "fadeIn",
            ease_in: 300,
            ease_out: 0,
            backdrop_color: "#000",
            backdrop_opacity: 1,
            glow: 0,
            glow_color: "#fff"
        };

    function JQVideoLightning ( element, options ) {
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    JQVideoLightning.prototype = {
        init: function () {
            var void_target, void_elements, target, target_class;
            void_elements = [ "AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "META", "PARAM", "SOURCE", "TRACK", "WBR" ];
            void_target = 0;
            target_class = ".video-target";

            $(this.element).css( "cursor", "pointer" );

            if (($.inArray($(this.element).prop('tagName'), void_elements)) == -1) {
                target = $(this.element);
                target.addClass("video-target");
            }
            else {
                $("body").append('
' + '
');
                target = $(target_class);
                void_target = 1;
            }

            function callPlayer() {
                $(this.player(target, $(this).settings), void_target);
            }

            $(this.element).on( "click", $.proxy(callPlayer, this));
        },

        player: function ( target, settings, void_target ) {
            var id, video_autohide, video_autoplay, video_byline, video_color, video_controls, video_height, video_id, video_iv_load_policy, video_loop, video_modestbranding, video_playlist, video_portrait, video_related, video_showinfo, video_start_time, video_theme, video_vendor, video_width, vimeo_player, youtube_player, ease_in, glow, glow_color, backdrop_color, backdrop_opacity, red, green, blue, effect_in, display_ratio;

            function colorConverter(hex){
                red = parseInt((prepHex(hex)).substring(0,2),16);
                blue = parseInt((prepHex(hex)).substring(2,4),16);
                green = parseInt((prepHex(hex)).substring(4,6),16);
                return {
                    red: red,
                    blue: blue,
                    green: green
                };
            }

            function fullHex(hex){
                hex = "#" + prepHex(hex);
                return hex;
            }

            function prepHex(hex){
                hex = (hex.charAt(0)=="#") ? hex.split("#")[1]:hex;
                if (hex.length == 3){
                    hex = hex + hex;
                }
                return hex;
            }

            settings = this.settings;

            if (target.find(".video-wrapper").is(':visible')) {
                target.find(".video").remove();
                target.find(".video-wrapper").hide((settings.easeOut));
                target.find(".video-wrapper").remove();
                if (void_target == 1){target.remove()}
                return $(this).destroy;
            } else {
                id = (typeof target.data("videoId") === 'undefined') ? settings.id : target.data("videoId");
                video_vendor = id.split("-")[0];
                if ((video_vendor === "v") || (video_vendor === "V")) {
                    video_vendor = "Vimeo";
                } else {
                    video_vendor = "Youtube";
                }
                video_id = id.split("-")[1]; // Youtube: "y-XbTtgr8J8uU" Vimeo: "v-32187194"
                video_width = target.data("videoWidth") || settings.width; // Y&V: video width in px
                video_height = target.data("videoHeight") || settings.height; // Y&V: video height in px
                display_ratio = parseInt(video_height) / parseInt(video_width);
                if (parseInt(video_width) > $(document).width() - 20) {
                    video_width = $(document).width() - 20 + "px";
                    video_height = display_ratio * parseInt(video_width) + "px";
                }
                video_autoplay = target.data("videoAutoplay") || settings.autoplay; // Y&V: start playback immediately (0,1)
                video_autohide = target.data("videoAutohide") || settings.autohide; // Y: auto hide controls after video load (0,1,2)
                video_controls = target.data("videoControls") || settings.controls; // Y: display controls (0,1,2)
                video_iv_load_policy = target.data("videoIvLoadPolicy") || settings.iv_load_policy; // Y: display annotations (1,3)
                video_loop = target.data("videoLoop") || settings.loop; // Y&V: loop video playback (0,1)
                video_modestbranding = target.data("videoModestbranding") || settings.modestbranding; // Y: hide large Youtube logo (0,1)
                video_playlist = target.data("videoPlaylist") || settings.playlist; // Y: comma-separated list of video IDs to play
                video_related = target.data("videoRelated") || settings.related; // Y: show related videos when playback id finished (0,1)
                video_showinfo = target.data("videoShowinfo") || settings.showinfo; // Y: display title, uploader (0,1)  V: display title (0,1)
                video_start_time = target.data("videoStartTime") || settings.start_time; // Y: playback start position in seconds (ex. "132" starts at 2mins, 12secs)
                video_theme = target.data("videoTheme") || settings.theme; // Y: player theme ("dark","light")
                if (video_vendor == "Vimeo"){
                    video_color = target.data("videoColor") || prepHex(settings.color); // V: player controls color (hex code minus the "#", default is "00adef")
                } else {
                    video_color = target.data("videoColor") || settings.color; // Y: player controls color ("red","white")
                }
                video_byline = target.data("videoByline") || settings.byline; // V: display byline (0,1)
                video_portrait = target.data("videoPortrait") || settings.portrait; // V: display user's portrait (0,1)
                youtube_player = $("<iframe src=\"https://www.youtube.com/embed/" + video_id + "?autoplay=" + video_autoplay + "&autohide=" + video_autohide + "&controls=" + video_controls + "&iv_load_policy=" + video_iv_load_policy + "&loop=" + video_loop + "&modestbranding=" + video_modestbranding + "&playlist=" + video_playlist + "&rel=" + video_related + "&showinfo=" + video_showinfo + "&start=" + video_start_time + "&theme=" + video_theme + "&color=" + video_color + "\" width=\"" + video_width + "\" height=\"" + video_height + "\" frameborder=\"0\" allowfullscreen>");
                vimeo_player = $("");
                effect_in = settings.effect_in;
                ease_in = settings.ease_in;
                glow = settings.glow;
                glow_color = settings.glow_color;
                backdrop_color = settings.backdrop_color;
                backdrop_opacity = settings.backdrop_opacity;

                target.append('

');
                target.find(".video-wrapper").css({
                    backgroundColor: "rgba(" + colorConverter(backdrop_color).red + "," + colorConverter(backdrop_color).blue + "," + colorConverter(backdrop_color).green + "," + backdrop_opacity + ")"
                });
                target.find(".video-frame").css({
                    width:  video_width,
                    height: video_height,
                    marginTop: '-' + ((video_height.split("p")[0])/2) + 'px',
                    marginLeft: '-' + ((video_width.split("p")[0])/2) + 'px',
                    boxShadow: '0px 0px ' + glow + 'px ' + (glow/5) + 'px ' + fullHex(glow_color)
                });
                target.find(".video-wrapper")[effect_in](ease_in);
                if (video_vendor === "Vimeo") {
                    return target.find(".video").append(vimeo_player);
                } else {
                    return target.find(".video").append(youtube_player);
                }
            }
        },

        destroy: function () {
            $(this).off();
            $(this).removeData();
        }
    };

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new JQVideoLightning( this, options ) );
            }
        });
    };

    return this;

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


<commit_before>(function() {
  d3.geo.rotate = function(z, y, x) {
    if (!(x = +x || 0) && !(y = +y || 0) && !(z = +z || 0)) {
      return identity;
    }

    var m = matrix(y, x),
        zAngle = z,
        radians = Math.PI / 180;

    function rotate(coordinates) {
      var λ = coordinates[0] + zAngle,
          φ = coordinates[1],
          cosφ = Math.cos(φ),
          x = Math.cos(λ) * cosφ,
          y = Math.sin(λ) * cosφ,
          z = Math.sin(φ),
          mx = m[0],
          my = m[1],
          mz = m[2];
      mx = x * mx[0] + y * mx[1] + z * mx[2];
      my = x * my[0] + y * my[1] + z * my[2];
      mz = x * mz[0] + y * mz[1] + z * mz[2];
      return [
        Math.atan2(my, mx),
        Math.asin(mz)
      ];
    }

    return rotate;
  };

  function matrix(y, x) {
    var cy = Math.cos(y *= radians),
        sy = Math.sin(y),
        cx = Math.cos(x *= radians),
        sx = Math.sin(x);
    return [
      [ cy,       0,      -sy],
      [-sx * sy, cx, -sx * cy],
      [ cx * sy, sx,  cx * cy]
    ];
  }

  function identity(λ, φ) { return [λ, φ]; }
})();
<commit_msg>Use degrees for consistency.<commit_after>(function() {
  d3.geo.rotate = function(z, y, x) {
    if (!(x = +x || 0) && !(y = +y || 0) && !(z = +z || 0)) {
      return identity;
    }

    var m = matrix(y, x),
        zAngle = z,
        radians = Math.PI / 180;

    function rotate(coordinates) {
      var λ = coordinates[0] * radians + zAngle,
          φ = coordinates[1] * radians,
          cosφ = Math.cos(φ),
          x = Math.cos(λ) * cosφ,
          y = Math.sin(λ) * cosφ,
          z = Math.sin(φ),
          mx = m[0],
          my = m[1],
          mz = m[2];
      mx = x * mx[0] + y * mx[1] + z * mx[2];
      my = x * my[0] + y * my[1] + z * my[2];
      mz = x * mz[0] + y * mz[1] + z * mz[2];
      return [
        Math.atan2(my, mx) / radians,
        Math.asin(mz) / radians
      ];
    }

    return rotate;
  };

  function matrix(y, x) {
    var cy = Math.cos(y *= radians),
        sy = Math.sin(y),
        cx = Math.cos(x *= radians),
        sx = Math.sin(x);
    return [
      [ cy,       0,      -sy],
      [-sx * sy, cx, -sx * cy],
      [ cx * sy, sx,  cx * cy]
    ];
  }

  function identity(λ, φ) { return [λ, φ]; }
})();
<|endoftext|>


<commit_before>var path = require('path');

var config = module.exports = {};

config.root = __dirname;
config.src = 'src/client';
config.dest = 'dist';
config.srcFullPath = path.join(config.root, config.src);
config.destFullPath = path.join(config.root, config.dest);

config.js = 'js';
config.assets = 'assets';
config.styles = 'styles';
config.karmaConfig = 'karma.conf.js';
config.testRunner = path.join(config.src, '../test-runner.js');
<commit_msg>Remove dead project config<commit_after>var path = require('path');

var config = module.exports = {};

config.root = __dirname;
config.src = 'src/client';
config.dest = 'dist';
config.srcFullPath = path.join(config.root, config.src);
config.destFullPath = path.join(config.root, config.dest);

config.js = 'js';
config.styles = 'styles';
<|endoftext|>