<commit_before>goog.provide('ol.renderer.dom.TileLayer');

goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('ol.Coordinate');
goog.require('ol.Extent');
goog.require('ol.renderer.dom.Layer');

/**
 * @constructor
 * @extends {ol.renderer.dom.Layer}
 * @param {ol.renderer.Map} mapRenderer Map renderer.
 * @param {ol.layer.TileLayer} tileLayer Tile layer.
 * @param {!Element} target Target.
 */
ol.renderer.dom.TileLayer = function(mapRenderer, tileLayer, target) {
  goog.base(this, mapRenderer, tileLayer, target);

  /**
   * @type {Object}
   * @private
   */
  this.renderedTiles_ = {};

  /**
   * @type {number|undefined}
   * @private
   */
  this.renderedMapResolution_ = undefined;

  /**
   * @type {ol.TileRange|undefined}
   * @private
   */
  this.renderedTileRange_ = undefined;

  /**
   * @type {number|undefined}
   * @private
   */
  this.renderedZ_ = undefined;

  /**
   * Map of tile keys loading at the currently rendered z.
   * @type {Object.<string, ol.Tile>}
   * @private
   */
  this.loadingTiles_ = {};

};
goog.inherits(ol.renderer.dom.TileLayer, ol.renderer.dom.Layer);

/**
 * @inheritDoc
 * @return {ol.layer.TileLayer} Layer.
 */
ol.renderer.dom.TileLayer.prototype.getLayer = function() {
  return /** @type {ol.layer.TileLayer} */ goog.base(this, 'getLayer');
};

/**
 * Get the pixel offset between the tile origin and the container origin.
 * @private
 * @param {number} z Z.
 * @param {number} resolution Resolution.
 * @return {ol.Coordinate} Offset.
 */
ol.renderer.dom.TileLayer.prototype.getTileOffset_ = function(z, resolution) {
  var tileLayer = this.getLayer();
  var tileSource = tileLayer.getTileSource();
  var tileGrid = tileSource.getTileGrid();
  var tileOrigin = tileGrid.getOrigin(z);
  var offset = new ol.Coordinate(
      Math.round((this.origin.x - tileOrigin.x) / resolution),
      Math.round((tileOrigin.y - this.origin.y) / resolution));
  return offset;
};

/**
 * Get rid of tiles that are not at the currently rendered z.
 * @private
 */
ol.renderer.dom.TileLayer.prototype.removeAltZTiles_ = function() {
  var tileRange = this.renderedTileRange_;
  var z = this.renderedZ_;
  var key, tileCoord, tile;
  for (key in this.renderedTiles_) {
    tileCoord = ol.TileCoord.createFromString(key);
    if (tileCoord.z !== z) {
      tile = this.renderedTiles_[key];
      delete this.renderedTiles_[key];
      goog.dom.removeNode(tile.getImage(this));
    }
  }
};

/**
 * Get rid of tiles outside the rendered extent.  Only removes tiles at the
 * currently rendered z.
 * @private
 */
ol.renderer.dom.TileLayer.prototype.removeOutOfRangeTiles_ = function() {
  var tileRange = this.renderedTileRange_;
  var z = this.renderedZ_;
  var key, tileCoord, prune, tile;
  for (key in this.renderedTiles_) {
    tileCoord = ol.TileCoord.createFromString(key);
    if (tileCoord.z === z) {
      prune = tileCoord.x < tileRange.minX ||
          tileCoord.x > tileRange.maxX ||
          tileCoord.y < tileRange.minY ||
          tileCoord.y > tileRange.maxY;
      if (prune) {
        tile = this.renderedTiles_[key];
        delete this.renderedTiles_[key];
        goog.dom.removeNode(tile.getImage(this));
      }
    }
  }
};

/**
 * @param {goog.events.Event} event Tile change event.
 * @private
 */
ol.renderer.dom.TileLayer.prototype.handleTileChange_ = function(event) {
  var tile = event.target;
  goog.asserts.assert(tile.getState() == ol.TileState.LOADED);
  var tileCoord = tile.tileCoord;
  if (tileCoord.z === this.renderedZ_) {
    var key = tileCoord.toString();
    delete this.loadingTiles_[key];
    // determine if we've fully loaded this zoom level
    var loaded = true;
    for (key in this.loadingTiles_) {
      loaded = false;
      break;
    }
    if (loaded) {
      this.removeAltZTiles_();
    }
  }
};

/**
 * Remove all loading tiles that have been appended.
 * @private
 */
ol.renderer.dom.TileLayer.prototype.removeLoadingTiles_ = function() {
  for (var key in this.loadingTiles_) {
    var tile = this.loadingTiles_[key];
    goog.dom.removeNode(tile.getImage(this));
    delete this.loadingTiles_[key];
  }
};

/**
 * @inheritDoc
 */
ol.renderer.dom.TileLayer.prototype.render = function() {

  var map = this.getMap();
  if (!map.isDef()) {
    return;
  }
  var mapExtent = /** @type {!ol.Extent} */ map.getRotatedExtent();
  var mapResolution = /** @type {number} */ map.getResolution();
  var resolutionChanged = (mapResolution !== this.renderedMapResolution_);

  var tileLayer = this.getLayer();
  var tileSource = tileLayer.getTileSource();
  var tileGrid = tileSource.getTileGrid();

  // z represents the "best" resolution
  var z = tileGrid.getZForResolution(mapResolution);

  if (z != this.renderedZ_) {
    // no longer wait for previously loading tiles
    this.removeLoadingTiles_();
  }

  /**
   * @type {Object.<number, Object.<string, ol.Tile>>}
   */
  var tilesToDrawByZ = {};
  tilesToDrawByZ[z] = {};

  var tileRange =
      tileGrid.getTileRangeForExtentAndResolution(mapExtent, mapResolution);

  // first pass through the tile range to determine all the tiles needed
  var allTilesLoaded = true;
  tileRange.forEachTileCoord(z, function(tileCoord) {
    var tile = tileSource.getTile(tileCoord);
    if (goog.isNull(tile)) {
      // we're outside the source's extent, continue
      return;
    }

    var key = tile.tileCoord.toString();
    if (tile.getState() == ol.TileState.LOADED) {
      tilesToDrawByZ[z][key] = tile;
      return;
    } else {
      if (!(key in this.loadingTiles_)) {
        goog.events.listen(tile, goog.events.EventType.CHANGE,
            this.handleTileChange_, false, this);
        this.loadingTiles_[key] = tile;
        tile.load();
      }
      allTilesLoaded = false;
      // TODO: only append after load?
      tilesToDrawByZ[z][key] = tile;
    }

    /**
     * Look for already loaded tiles at alternate z that can serve as
     * placeholders until tiles at the current z have loaded.
     *
     * TODO: make this more efficent for filling partial holes
     */
    tileGrid.forEachTileCoordParentTileRange(
        tileCoord,
        function(altZ, altTileRange) {
          var fullyCovered = true;
          altTileRange.forEachTileCoord(altZ, function(altTileCoord) {
            var tileKey = altTileCoord.toString();
            if (tilesToDrawByZ[altZ] && tilesToDrawByZ[altZ][tileKey]) {
              return;
            }
            var altTile = tileSource.getTile(altTileCoord);
            if (!goog.isNull(altTile) &&
                altTile.getState() == ol.TileState.LOADED) {
              if (!(altZ in tilesToDrawByZ)) {
                tilesToDrawByZ[altZ] = {};
              }
              tilesToDrawByZ[altZ][tileKey] = altTile;
            } else {
              fullyCovered = false;
            }
          });
          return fullyCovered;
        });

  }, this);

  /** @type {Array.<number>} */
  var zs = goog.object.getKeys(tilesToDrawByZ);
  goog.array.sort(zs);

  var fragment = document.createDocumentFragment();
  var altFragment = document.createDocumentFragment();
  var newTiles = false;
  var newAltTiles = false;
  for (var i = 0, ii = zs.length; i < ii; ++i) {
    var tileZ = zs[i];
    var tilesToDraw = tilesToDrawByZ[tileZ];
    var tileOffset = this.getTileOffset_(tileZ, mapResolution);
    for (var key in tilesToDraw) {
      var tile = tilesToDraw[key];
      var tileCoord = tile.tileCoord;
      var pixelBounds = tileGrid.getPixelBoundsForTileCoordAndResolution(
          tileCoord, mapResolution);
      var img = tile.getImage(this);
      var style = img.style;
      var append = !(key in this.renderedTiles_);
      if (append || resolutionChanged) {
        style.left = (pixelBounds.minX - tileOffset.x) + 'px';
        style.top = (-pixelBounds.maxY - tileOffset.y) + 'px';
        style.width = pixelBounds.getWidth() + 'px';
        style.height = pixelBounds.getHeight() + 'px';
      }
      if (append) {
        this.renderedTiles_[key] = tile;
        style.position = 'absolute';
        if (tileZ === z) {
          goog.dom.appendChild(fragment, img);
          newTiles = true;
        } else {
          goog.dom.appendChild(altFragment, img);
          newAltTiles = true;
        }
      }
    }
  }

  if (newAltTiles) {
    var child = this.target.firstChild;
    if (child) {
      goog.dom.insertSiblingBefore(altFragment, child);
    } else {
      goog.dom.appendChild(this.target, altFragment);
    }
  }
  if (newTiles) {
    goog.dom.appendChild(this.target, fragment);
  }

  this.renderedTileRange_ = tileRange;
  this.renderedZ_ = z;
  this.renderedMapResolution_ = mapResolution;

  if (allTilesLoaded) {
    this.removeAltZTiles_();
  }
  this.removeOutOfRangeTiles_();
};
<commit_msg>Removing unused code<commit_after>goog.provide('ol.renderer.dom.TileLayer');

goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('ol.Coordinate');
goog.require('ol.Extent');
goog.require('ol.renderer.dom.Layer');

/**
 * @constructor
 * @extends {ol.renderer.dom.Layer}
 * @param {ol.renderer.Map} mapRenderer Map renderer.
 * @param {ol.layer.TileLayer} tileLayer Tile layer.
 * @param {!Element} target Target.
 */
ol.renderer.dom.TileLayer = function(mapRenderer, tileLayer, target) {
  goog.base(this, mapRenderer, tileLayer, target);

  /**
   * @type {Object}
   * @private
   */
  this.renderedTiles_ = {};

  /**
   * @type {number|undefined}
   * @private
   */
  this.renderedMapResolution_ = undefined;

  /**
   * @type {ol.TileRange|undefined}
   * @private
   */
  this.renderedTileRange_ = undefined;

  /**
   * @type {number|undefined}
   * @private
   */
  this.renderedZ_ = undefined;

  /**
   * Map of tile keys loading at the currently rendered z.
   * @type {Object.<string, ol.Tile>}
   * @private
   */
  this.loadingTiles_ = {};

};
goog.inherits(ol.renderer.dom.TileLayer, ol.renderer.dom.Layer);

/**
 * @inheritDoc
 * @return {ol.layer.TileLayer} Layer.
 */
ol.renderer.dom.TileLayer.prototype.getLayer = function() {
  return /** @type {ol.layer.TileLayer} */ goog.base(this, 'getLayer');
};

/**
 * Get the pixel offset between the tile origin and the container origin.
 * @private
 * @param {number} z Z.
 * @param {number} resolution Resolution.
 * @return {ol.Coordinate} Offset.
 */
ol.renderer.dom.TileLayer.prototype.getTileOffset_ = function(z, resolution) {
  var tileLayer = this.getLayer();
  var tileSource = tileLayer.getTileSource();
  var tileGrid = tileSource.getTileGrid();
  var tileOrigin = tileGrid.getOrigin(z);
  var offset = new ol.Coordinate(
      Math.round((this.origin.x - tileOrigin.x) / resolution),
      Math.round((tileOrigin.y - this.origin.y) / resolution));
  return offset;
};

/**
 * Get rid of tiles that are not at the currently rendered z.
 * @private
 */
ol.renderer.dom.TileLayer.prototype.removeAltZTiles_ = function() {
  var z = this.renderedZ_;
  var key, tileCoord, tile;
  for (key in this.renderedTiles_) {
    tileCoord = ol.TileCoord.createFromString(key);
    if (tileCoord.z !== z) {
      tile = this.renderedTiles_[key];
      delete this.renderedTiles_[key];
      goog.dom.removeNode(tile.getImage(this));
    }
  }
};

/**
 * Get rid of tiles outside the rendered extent.  Only removes tiles at the
 * currently rendered z.
 * @private
 */
ol.renderer.dom.TileLayer.prototype.removeOutOfRangeTiles_ = function() {
  var tileRange = this.renderedTileRange_;
  var z = this.renderedZ_;
  var key, tileCoord, prune, tile;
  for (key in this.renderedTiles_) {
    tileCoord = ol.TileCoord.createFromString(key);
    if (tileCoord.z === z) {
      prune = tileCoord.x < tileRange.minX ||
          tileCoord.x > tileRange.maxX ||
          tileCoord.y < tileRange.minY ||
          tileCoord.y > tileRange.maxY;
      if (prune) {
        tile = this.renderedTiles_[key];
        delete this.renderedTiles_[key];
        goog.dom.removeNode(tile.getImage(this));
      }
    }
  }
};

/**
 * @param {goog.events.Event} event Tile change event.
 * @private
 */
ol.renderer.dom.TileLayer.prototype.handleTileChange_ = function(event) {
  var tile = event.target;
  goog.asserts.assert(tile.getState() == ol.TileState.LOADED);
  var tileCoord = tile.tileCoord;
  if (tileCoord.z === this.renderedZ_) {
    var key = tileCoord.toString();
    delete this.loadingTiles_[key];
    // determine if we've fully loaded this zoom level
    var loaded = true;
    for (key in this.loadingTiles_) {
      loaded = false;
      break;
    }
    if (loaded) {
      this.removeAltZTiles_();
    }
  }
};

/**
 * Remove all loading tiles that have been appended.
 * @private
 */
ol.renderer.dom.TileLayer.prototype.removeLoadingTiles_ = function() {
  for (var key in this.loadingTiles_) {
    var tile = this.loadingTiles_[key];
    goog.dom.removeNode(tile.getImage(this));
    delete this.loadingTiles_[key];
  }
};

/**
 * @inheritDoc
 */
ol.renderer.dom.TileLayer.prototype.render = function() {

  var map = this.getMap();
  if (!map.isDef()) {
    return;
  }
  var mapExtent = /** @type {!ol.Extent} */ map.getRotatedExtent();
  var mapResolution = /** @type {number} */ map.getResolution();
  var resolutionChanged = (mapResolution !== this.renderedMapResolution_);

  var tileLayer = this.getLayer();
  var tileSource = tileLayer.getTileSource();
  var tileGrid = tileSource.getTileGrid();

  // z represents the "best" resolution
  var z = tileGrid.getZForResolution(mapResolution);

  if (z != this.renderedZ_) {
    // no longer wait for previously loading tiles
    this.removeLoadingTiles_();
  }

  /**
   * @type {Object.<number, Object.<string, ol.Tile>>}
   */
  var tilesToDrawByZ = {};
  tilesToDrawByZ[z] = {};

  var tileRange =
      tileGrid.getTileRangeForExtentAndResolution(mapExtent, mapResolution);

  // first pass through the tile range to determine all the tiles needed
  var allTilesLoaded = true;
  tileRange.forEachTileCoord(z, function(tileCoord) {
    var tile = tileSource.getTile(tileCoord);
    if (goog.isNull(tile)) {
      // we're outside the source's extent, continue
      return;
    }

    var key = tile.tileCoord.toString();
    if (tile.getState() == ol.TileState.LOADED) {
      tilesToDrawByZ[z][key] = tile;
      return;
    } else {
      if (!(key in this.loadingTiles_)) {
        goog.events.listen(tile, goog.events.EventType.CHANGE,
            this.handleTileChange_, false, this);
        this.loadingTiles_[key] = tile;
        tile.load();
      }
      allTilesLoaded = false;
      // TODO: only append after load?
      tilesToDrawByZ[z][key] = tile;
    }

    /**
     * Look for already loaded tiles at alternate z that can serve as
     * placeholders until tiles at the current z have loaded.
     *
     * TODO: make this more efficent for filling partial holes
     */
    tileGrid.forEachTileCoordParentTileRange(
        tileCoord,
        function(altZ, altTileRange) {
          var fullyCovered = true;
          altTileRange.forEachTileCoord(altZ, function(altTileCoord) {
            var tileKey = altTileCoord.toString();
            if (tilesToDrawByZ[altZ] && tilesToDrawByZ[altZ][tileKey]) {
              return;
            }
            var altTile = tileSource.getTile(altTileCoord);
            if (!goog.isNull(altTile) &&
                altTile.getState() == ol.TileState.LOADED) {
              if (!(altZ in tilesToDrawByZ)) {
                tilesToDrawByZ[altZ] = {};
              }
              tilesToDrawByZ[altZ][tileKey] = altTile;
            } else {
              fullyCovered = false;
            }
          });
          return fullyCovered;
        });

  }, this);

  /** @type {Array.<number>} */
  var zs = goog.object.getKeys(tilesToDrawByZ);
  goog.array.sort(zs);

  var fragment = document.createDocumentFragment();
  var altFragment = document.createDocumentFragment();
  var newTiles = false;
  var newAltTiles = false;
  for (var i = 0, ii = zs.length; i < ii; ++i) {
    var tileZ = zs[i];
    var tilesToDraw = tilesToDrawByZ[tileZ];
    var tileOffset = this.getTileOffset_(tileZ, mapResolution);
    for (var key in tilesToDraw) {
      var tile = tilesToDraw[key];
      var tileCoord = tile.tileCoord;
      var pixelBounds = tileGrid.getPixelBoundsForTileCoordAndResolution(
          tileCoord, mapResolution);
      var img = tile.getImage(this);
      var style = img.style;
      var append = !(key in this.renderedTiles_);
      if (append || resolutionChanged) {
        style.left = (pixelBounds.minX - tileOffset.x) + 'px';
        style.top = (-pixelBounds.maxY - tileOffset.y) + 'px';
        style.width = pixelBounds.getWidth() + 'px';
        style.height = pixelBounds.getHeight() + 'px';
      }
      if (append) {
        this.renderedTiles_[key] = tile;
        style.position = 'absolute';
        if (tileZ === z) {
          goog.dom.appendChild(fragment, img);
          newTiles = true;
        } else {
          goog.dom.appendChild(altFragment, img);
          newAltTiles = true;
        }
      }
    }
  }

  if (newAltTiles) {
    var child = this.target.firstChild;
    if (child) {
      goog.dom.insertSiblingBefore(altFragment, child);
    } else {
      goog.dom.appendChild(this.target, altFragment);
    }
  }
  if (newTiles) {
    goog.dom.appendChild(this.target, fragment);
  }

  this.renderedTileRange_ = tileRange;
  this.renderedZ_ = z;
  this.renderedMapResolution_ = mapResolution;

  if (allTilesLoaded) {
    this.removeAltZTiles_();
  }
  this.removeOutOfRangeTiles_();
};
<|endoftext|>


<commit_before>goog.provide('ol.renderer.Layer');

goog.require('goog.Disposable');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.functions');
goog.require('ol.ImageState');
goog.require('ol.TileRange');
goog.require('ol.TileState');
goog.require('ol.layer.Layer');
goog.require('ol.source.Source');
goog.require('ol.source.State');
goog.require('ol.source.Tile');
goog.require('ol.tilecoord');

/**
 * @constructor
 * @extends {goog.Disposable}
 * @param {ol.renderer.Map} mapRenderer Map renderer.
 * @param {ol.layer.Layer} layer Layer.
 * @suppress {checkStructDictInheritance}
 * @struct
 */
ol.renderer.Layer = function(mapRenderer, layer) {

  goog.base(this);

  /**
   * @private
   * @type {ol.renderer.Map}
   */
  this.mapRenderer_ = mapRenderer;

  /**
   * @private
   * @type {ol.layer.Layer}
   */
  this.layer_ = layer;

};
goog.inherits(ol.renderer.Layer, goog.Disposable);

/**
 * @param {ol.Coordinate} coordinate Coordinate.
 * @param {olx.FrameState} frameState Frame state.
 * @param {function(this: S, ol.Feature, ol.layer.Layer): T} callback Feature
 *     callback.
 * @param {S} thisArg Value to use as `this` when executing `callback`.
 * @return {T|undefined} Callback result.
 * @template S,T
 */
ol.renderer.Layer.prototype.forEachFeatureAtCoordinate = goog.nullFunction;

/**
 * @param {ol.Pixel} pixel Pixel.
 * @param {olx.FrameState} frameState Frame state.
 * @param {function(this: S, ol.layer.Layer): T} callback Layer callback.
 * @param {S} thisArg Value to use as `this` when executing `callback`.
 * @return {T|undefined} Callback result.
 * @template S,T
 */
ol.renderer.Layer.prototype.forEachLayerAtPixel =
    function(pixel, frameState, callback, thisArg) {
  var coordinate = this.getMap().getCoordinateFromPixel(pixel);
  var hasFeature = this.forEachFeatureAtCoordinate(
      coordinate, frameState, goog.functions.TRUE, this);

  if (hasFeature) {
    return callback.call(thisArg, this.layer_);
  } else {
    return undefined;
  }
};

/**
 * @param {ol.Coordinate} coordinate Coordinate.
 * @param {olx.FrameState} frameState Frame state.
 * @return {boolean} Is there a feature at the given coordinate?
 */
ol.renderer.Layer.prototype.hasFeatureAtCoordinate = goog.functions.FALSE;

/**
 * @protected
 * @return {ol.layer.Layer} Layer.
 */
ol.renderer.Layer.prototype.getLayer = function() {
  return this.layer_;
};

/**
 * @protected
 * @return {ol.Map} Map.
 */
ol.renderer.Layer.prototype.getMap = function() {
  return this.mapRenderer_.getMap();
};

/**
 * @protected
 * @return {ol.renderer.Map} Map renderer.
 */
ol.renderer.Layer.prototype.getMapRenderer = function() {
  return this.mapRenderer_;
};

/**
 * Handle changes in image state.
 * @param {goog.events.Event} event Image change event.
 * @private
 */
ol.renderer.Layer.prototype.handleImageChange_ = function(event) {
  var image = /** @type {ol.Image} */ (event.target);
  if (image.getState() === ol.ImageState.LOADED) {
    this.renderIfReadyAndVisible();
  }
};

/**
 * Load the image if not already loaded, and register the image change
 * listener if needed.
 * @param {ol.ImageBase} image Image.
 * @return {boolean} `true` if the image is already loaded, `false`
 *     otherwise.
 * @protected
 */
ol.renderer.Layer.prototype.loadImage = function(image) {
  var imageState = image.getState();
  if (imageState != ol.ImageState.LOADED &&
      imageState != ol.ImageState.ERROR) {
    // the image is either "idle" or "loading", register the change
    // listener (a noop if the listener was already registered)
    goog.asserts.assert(imageState == ol.ImageState.IDLE ||
        imageState == ol.ImageState.LOADING);
    goog.events.listenOnce(image, goog.events.EventType.CHANGE,
        this.handleImageChange_, false, this);
  }
  if (imageState == ol.ImageState.IDLE) {
    image.load();
    imageState = image.getState();
    goog.asserts.assert(imageState == ol.ImageState.LOADING);
  }
  return imageState == ol.ImageState.LOADED;
};

/**
 * @protected
 */
ol.renderer.Layer.prototype.renderIfReadyAndVisible = function() {
  var layer = this.getLayer();
  if (layer.getVisible() && layer.getSourceState() == ol.source.State.READY) {
    this.getMap().render();
  }
};

/**
 * @param {olx.FrameState} frameState Frame state.
 * @param {ol.source.Tile} tileSource Tile source.
 * @protected
 */
ol.renderer.Layer.prototype.scheduleExpireCache =
    function(frameState, tileSource) {
  if (tileSource.canExpireCache()) {
    frameState.postRenderFunctions.push(
        goog.partial(
            /**
             * @param {ol.source.Tile} tileSource Tile source.
             * @param {ol.Map} map Map.
             * @param {olx.FrameState} frameState Frame state.
             */
            function(tileSource, map, frameState) {
              var tileSourceKey = goog.getUid(tileSource).toString();
              tileSource.expireCache(frameState.usedTiles[tileSourceKey]);
            }, tileSource));
  }
};

/**
 * @param {Object.<string, ol.Attribution>} attributionsSet Attributions
 *     set (target).
 * @param {Array.<ol.Attribution>} attributions Attributions (source).
 * @protected
 */
ol.renderer.Layer.prototype.updateAttributions =
    function(attributionsSet, attributions) {
  if (goog.isDefAndNotNull(attributions)) {
    var attribution, i, ii;
    for (i = 0, ii = attributions.length; i < ii; ++i) {
      attribution = attributions[i];
      attributionsSet[goog.getUid(attribution).toString()] = attribution;
    }
  }
};

/**
 * @param {olx.FrameState} frameState Frame state.
 * @param {ol.source.Source} source Source.
 * @protected
 */
ol.renderer.Layer.prototype.updateLogos = function(frameState, source) {
  var logo = source.getLogo();
  if (goog.isDef(logo)) {
    if (goog.isString(logo)) {
      frameState.logos[logo] = '';
    } else if (goog.isObject(logo)) {
      goog.asserts.assertString(logo.href);
      goog.asserts.assertString(logo.src);
      frameState.logos[logo.src] = logo.href;
    }
  }
};

/**
 * @param {Object.<string, Object.<string, ol.TileRange>>} usedTiles Used tiles.
 * @param {ol.source.Tile} tileSource Tile source.
 * @param {number} z Z.
 * @param {ol.TileRange} tileRange Tile range.
 * @protected
 */
ol.renderer.Layer.prototype.updateUsedTiles =
    function(usedTiles, tileSource, z, tileRange) {
  // FIXME should we use tilesToDrawByZ instead?
  var tileSourceKey = goog.getUid(tileSource).toString();
  var zKey = z.toString();
  if (tileSourceKey in usedTiles) {
    if (zKey in usedTiles[tileSourceKey]) {
      usedTiles[tileSourceKey][zKey].extend(tileRange);
    } else {
      usedTiles[tileSourceKey][zKey] = tileRange;
    }
  } else {
    usedTiles[tileSourceKey] = {};
    usedTiles[tileSourceKey][zKey] = tileRange;
  }
};

/**
 * @param {function(ol.Tile): boolean} isLoadedFunction Function to
 *     determine if the tile is loaded.
 * @param {ol.source.Tile} tileSource Tile source.
 * @param {number} pixelRatio Pixel ratio.
 * @param {ol.proj.Projection} projection Projection.
 * @protected
 * @return {function(number, number, number): ol.Tile} Returns a tile if it is
 *     loaded.
 */
ol.renderer.Layer.prototype.createGetTileIfLoadedFunction =
    function(isLoadedFunction, tileSource, pixelRatio, projection) {
  return (
      /**
       * @param {number} z Z.
       * @param {number} x X.
       * @param {number} y Y.
       * @return {ol.Tile} Tile.
       */
      function(z, x, y) {
        var tile = tileSource.getTile(z, x, y, pixelRatio, projection);
        return isLoadedFunction(tile) ? tile : null;
      });
};

/**
 * @param {ol.Coordinate} center Center.
 * @param {number} resolution Resolution.
 * @param {ol.Size} size Size.
 * @protected
 * @return {ol.Coordinate} Snapped center.
 */
ol.renderer.Layer.prototype.snapCenterToPixel =
    function(center, resolution, size) {
  return [
    resolution * (Math.round(center[0] / resolution) + (size[0] % 2) / 2),
    resolution * (Math.round(center[1] / resolution) + (size[1] % 2) / 2)
  ];
};

/**
 * Manage tile pyramid.
 * This function performs a number of functions related to the tiles at the
 * current zoom and lower zoom levels:
 * - registers idle tiles in frameState.wantedTiles so that they are not
 *   discarded by the tile queue
 * - enqueues missing tiles
 * @param {olx.FrameState} frameState Frame state.
 * @param {ol.source.Tile} tileSource Tile source.
 * @param {ol.tilegrid.TileGrid} tileGrid Tile grid.
 * @param {number} pixelRatio Pixel ratio.
 * @param {ol.proj.Projection} projection Projection.
 * @param {ol.Extent} extent Extent.
 * @param {number} currentZ Current Z.
 * @param {number} preload Load low resolution tiles up to 'preload' levels.
 * @param {function(this: T, ol.Tile)=} opt_tileCallback Tile callback.
 * @param {T=} opt_this Object to use as `this` in `opt_tileCallback`.
 * @protected
 * @template T
 */
ol.renderer.Layer.prototype.manageTilePyramid = function(
    frameState, tileSource, tileGrid, pixelRatio, projection, extent,
    currentZ, preload, opt_tileCallback, opt_this) {
  var tileSourceKey = goog.getUid(tileSource).toString();
  if (!(tileSourceKey in frameState.wantedTiles)) {
    frameState.wantedTiles[tileSourceKey] = {};
  }
  var wantedTiles = frameState.wantedTiles[tileSourceKey];
  var tileQueue = frameState.tileQueue;
  var minZoom = tileGrid.getMinZoom();
  var tile, tileRange, tileResolution, x, y, z;
  for (z = currentZ; z >= minZoom; --z) {
    tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z, tileRange);
    tileResolution = tileGrid.getResolution(z);
    for (x = tileRange.minX; x <= tileRange.maxX; ++x) {
      for (y = tileRange.minY; y <= tileRange.maxY; ++y) {
        if (currentZ - z <= preload) {
          tile = tileSource.getTile(z, x, y, pixelRatio, projection);
          if (tile.getState() == ol.TileState.IDLE) {
            wantedTiles[ol.tilecoord.toString(tile.tileCoord)] = true;
            if (!tileQueue.isKeyQueued(tile.getKey())) {
              tileQueue.enqueue([tile, tileSourceKey,
                tileGrid.getTileCoordCenter(tile.tileCoord), tileResolution]);
            }
          }
          if (goog.isDef(opt_tileCallback)) {
            opt_tileCallback.call(opt_this, tile);
          }
        } else {
          tileSource.useTile(z, x, y);
        }
      }
    }
  }
};
<commit_msg>Use provided frame state instead of map for pixel to coord conversion<commit_after>goog.provide('ol.renderer.Layer');

goog.require('goog.Disposable');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.functions');
goog.require('ol.ImageState');
goog.require('ol.TileRange');
goog.require('ol.TileState');
goog.require('ol.layer.Layer');
goog.require('ol.source.Source');
goog.require('ol.source.State');
goog.require('ol.source.Tile');
goog.require('ol.tilecoord');
goog.require('ol.vec.Mat4');

/**
 * @constructor
 * @extends {goog.Disposable}
 * @param {ol.renderer.Map} mapRenderer Map renderer.
 * @param {ol.layer.Layer} layer Layer.
 * @suppress {checkStructDictInheritance}
 * @struct
 */
ol.renderer.Layer = function(mapRenderer, layer) {

  goog.base(this);

  /**
   * @private
   * @type {ol.renderer.Map}
   */
  this.mapRenderer_ = mapRenderer;

  /**
   * @private
   * @type {ol.layer.Layer}
   */
  this.layer_ = layer;

};
goog.inherits(ol.renderer.Layer, goog.Disposable);

/**
 * @param {ol.Coordinate} coordinate Coordinate.
 * @param {olx.FrameState} frameState Frame state.
 * @param {function(this: S, ol.Feature, ol.layer.Layer): T} callback Feature
 *     callback.
 * @param {S} thisArg Value to use as `this` when executing `callback`.
 * @return {T|undefined} Callback result.
 * @template S,T
 */
ol.renderer.Layer.prototype.forEachFeatureAtCoordinate = goog.nullFunction;

/**
 * @param {ol.Pixel} pixel Pixel.
 * @param {olx.FrameState} frameState Frame state.
 * @param {function(this: S, ol.layer.Layer): T} callback Layer callback.
 * @param {S} thisArg Value to use as `this` when executing `callback`.
 * @return {T|undefined} Callback result.
 * @template S,T
 */
ol.renderer.Layer.prototype.forEachLayerAtPixel =
    function(pixel, frameState, callback, thisArg) {
  var coordinate = pixel.slice();
  ol.vec.Mat4.multVec2(
      frameState.pixelToCoordinateMatrix, coordinate, coordinate);

  var hasFeature = this.forEachFeatureAtCoordinate(
      coordinate, frameState, goog.functions.TRUE, this);

  if (hasFeature) {
    return callback.call(thisArg, this.layer_);
  } else {
    return undefined;
  }
};

/**
 * @param {ol.Coordinate} coordinate Coordinate.
 * @param {olx.FrameState} frameState Frame state.
 * @return {boolean} Is there a feature at the given coordinate?
 */
ol.renderer.Layer.prototype.hasFeatureAtCoordinate = goog.functions.FALSE;

/**
 * @protected
 * @return {ol.layer.Layer} Layer.
 */
ol.renderer.Layer.prototype.getLayer = function() {
  return this.layer_;
};

/**
 * @protected
 * @return {ol.Map} Map.
 */
ol.renderer.Layer.prototype.getMap = function() {
  return this.mapRenderer_.getMap();
};

/**
 * @protected
 * @return {ol.renderer.Map} Map renderer.
 */
ol.renderer.Layer.prototype.getMapRenderer = function() {
  return this.mapRenderer_;
};

/**
 * Handle changes in image state.
 * @param {goog.events.Event} event Image change event.
 * @private
 */
ol.renderer.Layer.prototype.handleImageChange_ = function(event) {
  var image = /** @type {ol.Image} */ (event.target);
  if (image.getState() === ol.ImageState.LOADED) {
    this.renderIfReadyAndVisible();
  }
};

/**
 * Load the image if not already loaded, and register the image change
 * listener if needed.
 * @param {ol.ImageBase} image Image.
 * @return {boolean} `true` if the image is already loaded, `false`
 *     otherwise.
 * @protected
 */
ol.renderer.Layer.prototype.loadImage = function(image) {
  var imageState = image.getState();
  if (imageState != ol.ImageState.LOADED &&
      imageState != ol.ImageState.ERROR) {
    // the image is either "idle" or "loading", register the change
    // listener (a noop if the listener was already registered)
    goog.asserts.assert(imageState == ol.ImageState.IDLE ||
        imageState == ol.ImageState.LOADING);
    goog.events.listenOnce(image, goog.events.EventType.CHANGE,
        this.handleImageChange_, false, this);
  }
  if (imageState == ol.ImageState.IDLE) {
    image.load();
    imageState = image.getState();
    goog.asserts.assert(imageState == ol.ImageState.LOADING);
  }
  return imageState == ol.ImageState.LOADED;
};

/**
 * @protected
 */
ol.renderer.Layer.prototype.renderIfReadyAndVisible = function() {
  var layer = this.getLayer();
  if (layer.getVisible() && layer.getSourceState() == ol.source.State.READY) {
    this.getMap().render();
  }
};

/**
 * @param {olx.FrameState} frameState Frame state.
 * @param {ol.source.Tile} tileSource Tile source.
 * @protected
 */
ol.renderer.Layer.prototype.scheduleExpireCache =
    function(frameState, tileSource) {
  if (tileSource.canExpireCache()) {
    frameState.postRenderFunctions.push(
        goog.partial(
            /**
             * @param {ol.source.Tile} tileSource Tile source.
             * @param {ol.Map} map Map.
             * @param {olx.FrameState} frameState Frame state.
             */
            function(tileSource, map, frameState) {
              var tileSourceKey = goog.getUid(tileSource).toString();
              tileSource.expireCache(frameState.usedTiles[tileSourceKey]);
            }, tileSource));
  }
};

/**
 * @param {Object.<string, ol.Attribution>} attributionsSet Attributions
 *     set (target).
 * @param {Array.<ol.Attribution>} attributions Attributions (source).
 * @protected
 */
ol.renderer.Layer.prototype.updateAttributions =
    function(attributionsSet, attributions) {
  if (goog.isDefAndNotNull(attributions)) {
    var attribution, i, ii;
    for (i = 0, ii = attributions.length; i < ii; ++i) {
      attribution = attributions[i];
      attributionsSet[goog.getUid(attribution).toString()] = attribution;
    }
  }
};

/**
 * @param {olx.FrameState} frameState Frame state.
 * @param {ol.source.Source} source Source.
 * @protected
 */
ol.renderer.Layer.prototype.updateLogos = function(frameState, source) {
  var logo = source.getLogo();
  if (goog.isDef(logo)) {
    if (goog.isString(logo)) {
      frameState.logos[logo] = '';
    } else if (goog.isObject(logo)) {
      goog.asserts.assertString(logo.href);
      goog.asserts.assertString(logo.src);
      frameState.logos[logo.src] = logo.href;
    }
  }
};

/**
 * @param {Object.<string, Object.<string, ol.TileRange>>} usedTiles Used tiles.
 * @param {ol.source.Tile} tileSource Tile source.
 * @param {number} z Z.
 * @param {ol.TileRange} tileRange Tile range.
 * @protected
 */
ol.renderer.Layer.prototype.updateUsedTiles =
    function(usedTiles, tileSource, z, tileRange) {
  // FIXME should we use tilesToDrawByZ instead?
  var tileSourceKey = goog.getUid(tileSource).toString();
  var zKey = z.toString();
  if (tileSourceKey in usedTiles) {
    if (zKey in usedTiles[tileSourceKey]) {
      usedTiles[tileSourceKey][zKey].extend(tileRange);
    } else {
      usedTiles[tileSourceKey][zKey] = tileRange;
    }
  } else {
    usedTiles[tileSourceKey] = {};
    usedTiles[tileSourceKey][zKey] = tileRange;
  }
};

/**
 * @param {function(ol.Tile): boolean} isLoadedFunction Function to
 *     determine if the tile is loaded.
 * @param {ol.source.Tile} tileSource Tile source.
 * @param {number} pixelRatio Pixel ratio.
 * @param {ol.proj.Projection} projection Projection.
 * @protected
 * @return {function(number, number, number): ol.Tile} Returns a tile if it is
 *     loaded.
 */
ol.renderer.Layer.prototype.createGetTileIfLoadedFunction =
    function(isLoadedFunction, tileSource, pixelRatio, projection) {
  return (
      /**
       * @param {number} z Z.
       * @param {number} x X.
       * @param {number} y Y.
       * @return {ol.Tile} Tile.
       */
      function(z, x, y) {
        var tile = tileSource.getTile(z, x, y, pixelRatio, projection);
        return isLoadedFunction(tile) ? tile : null;
      });
};

/**
 * @param {ol.Coordinate} center Center.
 * @param {number} resolution Resolution.
 * @param {ol.Size} size Size.
 * @protected
 * @return {ol.Coordinate} Snapped center.
 */
ol.renderer.Layer.prototype.snapCenterToPixel =
    function(center, resolution, size) {
  return [
    resolution * (Math.round(center[0] / resolution) + (size[0] % 2) / 2),
    resolution * (Math.round(center[1] / resolution) + (size[1] % 2) / 2)
  ];
};

/**
 * Manage tile pyramid.
 * This function performs a number of functions related to the tiles at the
 * current zoom and lower zoom levels:
 * - registers idle tiles in frameState.wantedTiles so that they are not
 *   discarded by the tile queue
 * - enqueues missing tiles
 * @param {olx.FrameState} frameState Frame state.
 * @param {ol.source.Tile} tileSource Tile source.
 * @param {ol.tilegrid.TileGrid} tileGrid Tile grid.
 * @param {number} pixelRatio Pixel ratio.
 * @param {ol.proj.Projection} projection Projection.
 * @param {ol.Extent} extent Extent.
 * @param {number} currentZ Current Z.
 * @param {number} preload Load low resolution tiles up to 'preload' levels.
 * @param {function(this: T, ol.Tile)=} opt_tileCallback Tile callback.
 * @param {T=} opt_this Object to use as `this` in `opt_tileCallback`.
 * @protected
 * @template T
 */
ol.renderer.Layer.prototype.manageTilePyramid = function(
    frameState, tileSource, tileGrid, pixelRatio, projection, extent,
    currentZ, preload, opt_tileCallback, opt_this) {
  var tileSourceKey = goog.getUid(tileSource).toString();
  if (!(tileSourceKey in frameState.wantedTiles)) {
    frameState.wantedTiles[tileSourceKey] = {};
  }
  var wantedTiles = frameState.wantedTiles[tileSourceKey];
  var tileQueue = frameState.tileQueue;
  var minZoom = tileGrid.getMinZoom();
  var tile, tileRange, tileResolution, x, y, z;
  for (z = currentZ; z >= minZoom; --z) {
    tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z, tileRange);
    tileResolution = tileGrid.getResolution(z);
    for (x = tileRange.minX; x <= tileRange.maxX; ++x) {
      for (y = tileRange.minY; y <= tileRange.maxY; ++y) {
        if (currentZ - z <= preload) {
          tile = tileSource.getTile(z, x, y, pixelRatio, projection);
          if (tile.getState() == ol.TileState.IDLE) {
            wantedTiles[ol.tilecoord.toString(tile.tileCoord)] = true;
            if (!tileQueue.isKeyQueued(tile.getKey())) {
              tileQueue.enqueue([tile, tileSourceKey,
                tileGrid.getTileCoordCenter(tile.tileCoord), tileResolution]);
            }
          }
          if (goog.isDef(opt_tileCallback)) {
            opt_tileCallback.call(opt_this, tile);
          }
        } else {
          tileSource.useTile(z, x, y);
        }
      }
    }
  }
};
<|endoftext|>


<commit_before>import express from 'express';
import jwt from 'jsonwebtoken';
import config from '../../config/env';
import emailCtrl from '../controllers/email.controller';
import http from 'http';
import socketIo from 'socket.io';

class Socket{

  /** maps the userId to the related open socket */
  userSockets = new Map(); //<userId, socketId>
  server  = http.createServer(express);
  io = socketIo(this.server);

  constructor() {

      this.server.listen(config.socketPort);

      this.io.use((socket, next)=>{
        const token = socket.request._query['token'];
        if(jwt.verify(token, config.jwt.secret)){
          socket.userId = jwt.decode(token).user._id;
          next();
        }else{
          console.log('Not Authenticated!');
        }
      });

      this.io.on('connection', (socket)=>{
        console.log('new socket '+socket.id + ' for user '+socket.userId);
        this.userSockets.set(socket.userId.toString(), socket.id);

        socket.on('disconnect', (socket)=>{
          console.log('socket closed');
          this.userSockets.delete(socket.userId);
        });

        //TODO remove only for testing
        //emitMsg();
        function emitMsg(){
          setTimeout(()=>{
            socket.emit('message', 'some date');
            console.log('send msg');
            //emitMsg();
          }, 1000);
        }
      });

  }

  createEmail(userId, email){
    this.emitToUser(userId, 'create_email', email);
  }

  updateEmail(userId, email){
    this.emitToUser(userId, 'update_email', email);
  }

  deleteEmail(userId, email){
    this.emitToUser(userId, 'delete_email', email);
  }

  emitToUser(userId, msgType, msgContent){
    userId = userId.toString();
    if(this.userSockets.has(userId)){
      const socketId = this.userSockets.get(userId);
      this.io.sockets.connected[socketId].emit(msgType, JSON.stringify(msgContent));
      console.log('Emit Message: '+userId+' '+msgType+' '+msgContent.subject);
    }
  }
}

export default new Socket();
<commit_msg>socket test msg removed<commit_after>import express from 'express';
import jwt from 'jsonwebtoken';
import config from '../../config/env';
import emailCtrl from '../controllers/email.controller';
import http from 'http';
import socketIo from 'socket.io';

class Socket{

  /** maps the userId to the related open socket */
  userSockets = new Map(); //<userId, socketId>
  server  = http.createServer(express);
  io = socketIo(this.server);

  constructor() {

      this.server.listen(config.socketPort);

      this.io.use((socket, next)=>{
        const token = socket.request._query['token'];
        if(jwt.verify(token, config.jwt.secret)){
          socket.userId = jwt.decode(token).user._id;
          next();
        }else{
          console.log('Not Authenticated!');
        }
      });

      this.io.on('connection', (socket)=>{
        console.log('new socket '+socket.id + ' for user '+socket.userId);
        this.userSockets.set(socket.userId.toString(), socket.id);

        socket.on('disconnect', (socket)=>{
          console.log('socket closed');
          this.userSockets.delete(socket.userId);
        });
      });

  }

  createEmail(userId, email){
    this.emitToUser(userId, 'create_email', email);
  }

  updateEmail(userId, email){
    this.emitToUser(userId, 'update_email', email);
  }

  deleteEmail(userId, email){
    this.emitToUser(userId, 'delete_email', email);
  }

  emitToUser(userId, msgType, msgContent){
    userId = userId.toString();
    if(this.userSockets.has(userId)){
      const socketId = this.userSockets.get(userId);
      this.io.sockets.connected[socketId].emit(msgType, JSON.stringify(msgContent));
      console.log('Emit Message: '+userId+' '+msgType+' '+msgContent.subject);
    }
  }
}

export default new Socket();
<|endoftext|>


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

function processArgs() {
    var ret = {};
    var last;
    var argv = process.argv.slice(2);
    for (var v in argv) {
        var curr = argv[v];
        if (curr.indexOf("--")==0) {
            last = curr;
        } else {
            ret[last] = curr;
        }
    }
    return ret;
}

function Communication(doStuff) {
    var argsMap = processArgs();
    var path = argsMap["--server"];

    var net = require('net');
    var client = new net.Socket();
    client.connect({path: path});
    client.on('data', function(dataStr) {
        console.log("fuuuu", JSON.parse(dataStr));
        doStuff(JSON.parse(dataStr));
    });
    client.on('end', function() { console.warn('disconnected from server'); });

    this.send = function(obj) { client.write(JSON.stringify(obj)+'\n'); };

    this.setError = function(code, errorText) {
        console.warn('ERROR [%s]', errorText);
        this.send( { error: code, errorText: errorText } );
        process.exit(1);
    };

    this.setOutput = function(data) {
        this.send(data);
        process.exit(0);
    };
}

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

var comm = new Communication(main);

//Callback functions
var error = function (err, response, body) {
    comm.setError(1, JSON.stringify(err));
};
var postSuccess = function (dataString) {
    var data = JSON.parse(dataString);
    var outputUrl = ("https://twitter.com/"+data.user.screen_name+"/status/"+data.id_str);
    comm.setOutput(comm.send({percent: 100, output: {url: outputUrl} }));
};

var Twitter = require('twitter-node-client').Twitter;

var twitter = null;
var message;
var inputUrls;
var uploaded = [];

function postIfDone()
{
    if (uploaded.length === inputUrls.length) {
        comm.send({percent: 90});
        twitter.postTweet({
                status: message,
                media_ids: uploaded
            }
            , error
            , postSuccess
        );
    }
}

function mediaUploaded(dataString) {
    var data = JSON.parse(dataString)
    uploaded.push(data.media_id_string);
    comm.send({percent: 60});
    postIfDone();
};

function readUrl(url) {
    var spawn = require('child_process').spawn;
    var kiocat = spawn("kioclient5", ["cat", url], { stdio: ['ignore', 'pipe', 'ignore']});

    var contents = []; //array of buffers
    kiocat.stdout.on('data', function (data) { contents.push(data); });

    kiocat.on('exit', function (exitCode) {
        if (exitCode!=0) {
            setError(exitCode, "couldn't read: " + url);
            return;
        }
        comm.send({percent: 20});

        var allData = Buffer.concat(contents);
        twitter.postMedia(
            { media_data: allData.toString("base64") }
            , error
            , mediaUploaded
        );
    });
}

function main(data)
{
    message = data.tweetText;
    inputUrls = data.urls;
    console.log("Connected!");

    var config = {
        consumerKey: data.consumerKey,
        consumerSecret: data.consumerSecret,
        accessToken: data.accessToken,
        accessTokenSecret: data.accessTokenSecret,
        callBackUrl: ""
    }

    for(var v in config) {
        if (v!="callBackUrl" && config[v]=="") {
            console.log("auth...", config);
            comm.setError(2, "Missing auth information");
        }
    }

    var twitter = new Twitter(config);

    for (var v in inputUrls) {
        readUrl(inputUrls[v])
    }
    postIfDone();
}
<commit_msg>Small fixes<commit_after>#!/usr/bin/env node

function processArgs() {
    var ret = {};
    var last;
    var argv = process.argv.slice(2);
    for (var v in argv) {
        var curr = argv[v];
        if (curr.indexOf("--")==0) {
            last = curr;
        } else {
            ret[last] = curr;
        }
    }
    return ret;
}

function Communication(doStuff) {
    var argsMap = processArgs();
    var path = argsMap["--server"];

    var net = require('net');
    var client = new net.Socket();
    client.connect({path: path});
    client.on('data', function(dataStr) {
        doStuff(JSON.parse(dataStr));
    });
    client.on('end', function() { console.warn('disconnected from server'); });

    this.send = function(obj) { client.write(JSON.stringify(obj)+'\n'); };

    this.setError = function(code, errorText) {
        console.warn('ERROR [%s]', errorText);
        this.send( { error: code, errorText: errorText } );
        process.exit(1);
    };

    this.setOutput = function(data) {
        this.send(data);
        process.exit(0);
    };
}

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

var comm = new Communication(main);

//Callback functions
var error = function (err, response, body) {
    comm.setError(1, JSON.stringify(err));
};
var postSuccess = function (dataString) {
    var data = JSON.parse(dataString);
    var outputUrl = ("https://twitter.com/"+data.user.screen_name+"/status/"+data.id_str);
    comm.setOutput(comm.send({percent: 100, output: {url: outputUrl} }));
};

var Twitter = require('twitter-node-client').Twitter;

var twitter = null;
var message;
var inputUrls;
var uploaded = [];

function postIfDone()
{
    if (uploaded.length === inputUrls.length) {
        comm.send({percent: 90});
        twitter.postTweet({
                status: message,
                media_ids: uploaded
            }
            , error
            , postSuccess
        );
    }
}

function mediaUploaded(dataString) {
    var data = JSON.parse(dataString)
    uploaded.push(data.media_id_string);
    comm.send({percent: 60});
    postIfDone();
};

function readUrl(url) {
    var spawn = require('child_process').spawn;
    var kiocat = spawn("kioclient5", ["cat", url], { stdio: ['ignore', 'pipe', 'ignore']});

    var contents = []; //array of buffers
    kiocat.stdout.on('data', function (data) { contents.push(data); });

    kiocat.on('exit', function (exitCode) {
        if (exitCode!=0) {
            setError(exitCode, "couldn't read: " + url);
            return;
        }
        comm.send({percent: 20});

        var allData = Buffer.concat(contents);
        twitter.postMedia(
            { media_data: allData.toString("base64") }
            , error
            , mediaUploaded
        );
    });
}

function main(data)
{
    message = data.tweetText;
    inputUrls = data.urls;
    console.log("Connected!");

    var config = {
        consumerKey: data.consumerKey,
        consumerSecret: data.consumerSecret,
        accessToken: data.accessToken,
        accessTokenSecret: data.accessTokenSecret,
        callBackUrl: ""
    }

    for(var v in config) {
        if (v!="callBackUrl" && config[v]=="") {
            console.log("auth...", config);
            comm.setError(2, "Missing auth information");
        }
    }

    twitter = new Twitter(config);

    for (var v in inputUrls) {
        readUrl(inputUrls[v])
    }
    postIfDone();
}
<|endoftext|>


<commit_before>const thrift = require('thrift');
const StatusReport = require('./thrift/StatusReport');
const Registration = require('./thrift/Registration');
const VehicleCreation = require('./thrift/VehicleCreation');

const MultiplexedProcessor = new thrift.MultiplexedProcessor();

MultiplexedProcessor.registerProcessor('Registration', new Registration.Processor({

  register_vehicle: (vehicleDetails, result) => {
    result(null);
  },

  deregister_vehicle: (vehicleID, result) => {
    result(null);
  },

  vehicle_is_registered: (vehicleID, result) => {
    result(null, false);
  },

}));

MultiplexedProcessor.registerProcessor('StatusReport', new StatusReport.Processor({

  report_status: (vehicleID, state, result) => {
    result(null);
  },

}));

MultiplexedProcessor.registerProcessor('VehicleCreation', new VehicleCreation.Processor({

  create_vehicle: (vehicleDetails, result) => {
    console.log('Mock thrift server received create_vehicle: ', vehicleDetails.vehicleId.UID);
    result(null);
  },

}));

const server = thrift.createMultiplexServer(MultiplexedProcessor);

module.exports = {
  start: ({port = 9090} = {}) => {
    server.listen(port);
    console.log(`Thrift server started. Listening on port ${port}`);
  }
};
<commit_msg>Added console logging in Thrift server when calls come in<commit_after>const thrift = require('thrift');
const StatusReport = require('./thrift/StatusReport');
const Registration = require('./thrift/Registration');
const VehicleCreation = require('./thrift/VehicleCreation');

const MultiplexedProcessor = new thrift.MultiplexedProcessor();

MultiplexedProcessor.registerProcessor('Registration', new Registration.Processor({

  register_vehicle: (vehicleDetails, result) => {
    console.log('register_vehicle received');
    result(null);
  },

  deregister_vehicle: (vehicleID, result) => {
    console.log('deregister_vehicle received');
    result(null);
  },

  vehicle_is_registered: (vehicleID, result) => {
    console.log('vehicle_is_registered received');
    result(null, false);
  },

}));

MultiplexedProcessor.registerProcessor('StatusReport', new StatusReport.Processor({

  report_status: (vehicleID, state, result) => {
    console.log('report_status received');
    result(null);
  },

}));

MultiplexedProcessor.registerProcessor('VehicleCreation', new VehicleCreation.Processor({

  create_vehicle: (vehicleDetails, result) => {
    console.log('Mock thrift server received create_vehicle: ', vehicleDetails.vehicleId.UID);
    result(null);
  },

}));

const server = thrift.createMultiplexServer(MultiplexedProcessor);

module.exports = {
  start: ({port = 9090} = {}) => {
    server.listen(port);
    console.log(`Thrift server started. Listening on port ${port}`);
  }
};
<|endoftext|>


<commit_before>const { InputError } = require('../../common')

const BASIC_TYPES = ['string', 'boolean', 'number', 'function']

function validateOption({ inputName, value, config }) {
  let { type } = config
  let isTypeCorrect = (!BASIC_TYPES.includes(type) || typeof value === type)

  if (!isTypeCorrect || Number.isNaN(value)) {
    throw new InputError(`Option "${inputName}" must be a ${type}`)
  }
}

function validateCommand({ inputName, options, config }) {
  if (!config) {
    throw new InputError(`Unknown command "${inputName}"`)
  }

  if (config.options && config.options.length) {
    config.options.forEach((optionConfig) => {
      if (optionConfig.required) {
        let option = options.find((option) => {
          return option.config && option.config.id === optionConfig.id
        })

        if (!option) {
          throw new InputError(`Option "${optionConfig.name}" is required`)
        }
      }
    })
  }

  if (!options) {
    return
  }

  options.forEach((option) => {
    if (!option.config) {
      if (config.strict) {
        throw new InputError(`Unknown option "${option.inputName}"`)
      }

      return
    }

    validateOption(option)
  })
}

module.exports = validateCommand
<commit_msg>Disallow null in required options<commit_after>const { InputError } = require('../../common')

const BASIC_TYPES = ['string', 'boolean', 'number', 'function']

function validateOption({ inputName, value, config }) {
  let { type } = config
  let isTypeCorrect = (!BASIC_TYPES.includes(type) || typeof value === type)

  if (!isTypeCorrect || Number.isNaN(value)) {
    throw new InputError(`Option "${inputName}" must be a ${type}`)
  }
}

function validateCommand({ inputName, options, config }) {
  if (!config) {
    throw new InputError(`Unknown command "${inputName}"`)
  }

  if (config.options && config.options.length) {
    config.options.forEach((optionConfig) => {
      if (optionConfig.required) {
        let option = options.find((option) => {
          return option.config && option.config.id === optionConfig.id
        })

        if (!option || option.value === null) {
          throw new InputError(`Option "${optionConfig.name}" is required`)
        }
      }
    })
  }

  if (!options) {
    return
  }

  options.forEach((option) => {
    if (!option.config) {
      if (config.strict) {
        throw new InputError(`Unknown option "${option.inputName}"`)
      }

      return
    }

    validateOption(option)
  })
}

module.exports = validateCommand
<|endoftext|>


<commit_before>const db = require('APP/db')
const Character = db.model('characters')

const enemyProperties = require('APP/app/properties/enemyProperties')
const enemySpawn = require('./enemySpawn.json')
const GamePlayers = {}
const GameEnemies = {}
const GameItems = {}
const collisionArrays = {}
const isUpdating = {}

const EasystarConstructor = require('easystarjs')

const findClosestPlayer = require('./utils').findClosestPlayer

const mapWidth = 32
const mapHeight = 32

const enemyMovement = (io, state) => {
  if (Object.keys(GamePlayers[state])) {
    Object.keys(GameEnemies[state]).forEach(enemyName => {
      const enemy = GameEnemies[state][enemyName]
      const closestPlayer = findClosestPlayer(GamePlayers[state], enemy)
      if (closestPlayer) {
        collisionArrays[state].findPath(
          Math.floor(enemy.x / mapWidth),
          Math.floor(enemy.y / mapHeight),
          Math.floor(closestPlayer.x / mapWidth),
          Math.floor(closestPlayer.y / mapHeight),
          path => {
            if (path && path[1]) {
              const newX = path[1].x * mapWidth
              const newY = path[1].y * mapHeight
              const distance = 1
              enemy.x += newX - enemy.x > 0 ? distance : -distance
              enemy.y += newY - enemy.y > 0 ? distance : -distance
              const newPos = { x: enemy.x, y: enemy.y }
              io.sockets.to(state).emit('updateEnemy', newPos, enemyName)
            }
          }
        )
        collisionArrays[state].calculate()
      }
    })
  }
}

const spawnEnemy = (io, state) => {
  if (Object.keys(GamePlayers[state])) {
    enemySpawn[state].forEach((enemy) => {
      if (!GameEnemies[state][enemy.name]) {
        const enemyStats = Object.assign({}, enemyProperties[enemy.spriteKey].stats)
        GameEnemies[state][enemy.name] = Object.assign({}, enemy, { stats: enemyStats })
        io.sockets.to(state).emit('addEnemy', GameEnemies[state][enemy.name])
      }
    })
  }
}

const runIntervals = (io, state) => {
  setInterval(() => enemyMovement(io, state), 33)
  setInterval(() => spawnEnemy(io, state), 10000)
}

const socketFunction = io => {
  io.on('connection', socket => {
    console.log('got a connection', socket.id)
    let room = 'world'
    socket.join(room)

    socket.on('disconnect', () => {
      if (GamePlayers[room]) {
        delete GamePlayers[room][socket.id]
        socket.broadcast.to(room).emit('removePlayer', socket.id)
      }
      console.log(socket.id, 'disconnected')
    })

    socket.on('updatePlayer', player => {
      if (GamePlayers[room]) {
        GamePlayers[room][socket.id] = Object.assign({}, GamePlayers[room][socket.id], { x: player.playerPos.x, y: player.playerPos.y, lootCount: player.lootCount })
        socket.broadcast.to(room).emit('updatePlayer', socket.id, player)
      }
    })
    socket.on('updateStats', stats => {
      if (GamePlayers[room]) {
        GamePlayers[room][socket.id].stats = stats
      }
      socket.broadcast.to(room).emit('updateStats', socket.id, stats)
    })

    socket.on('fireProjectile', (xCoord, yCoord) => {
      socket.broadcast.to(room).emit('fireProjectile', socket.id, xCoord, yCoord)
    })

    socket.on('hitEnemy', (enemyName, damage) => {
      if (GameEnemies[room]) {
        const damageTaken = damage - GameEnemies[room][enemyName].stats.defense
        GameEnemies[room][enemyName].stats.hp -= damageTaken
        socket.broadcast.to(room).emit('hitEnemy', enemyName, damage)
      }
    })

    socket.on('killEnemy', enemyName => {
      if (GameEnemies[room]) {
        delete GameEnemies[room][enemyName]
        socket.broadcast.to(room).emit('removeEnemy', enemyName)
      }
    })

    socket.on('createItem', item => {
      GameItems[room][item.name] = item
      socket.broadcast.to(room).emit('addItem', item)
    })

    socket.on('killItem', name => {
      if (GameItems[room]) {
        delete GameItems[room][name]
        socket.broadcast.to(room).emit('removeItem', name)
      }
    })

    socket.on('setupState', (player, collisionMap, newRoom) => {
      // remove player from previous map (room)
      if (GamePlayers[room]) {
        delete GamePlayers[room][socket.id]
        socket.broadcast.to(room).emit('removePlayer', socket.id)
      }

      // join new map
      socket.leave(room)
      room = newRoom
      socket.join(room)
      if (!GamePlayers[room]) GamePlayers[room] = {}
      if (!GameEnemies[room]) GameEnemies[room] = {}
      if (!GameItems[room]) GameItems[room] = {}

      // get all players and enemies on the map
      socket.emit('getPlayers', GamePlayers[room])
      socket.emit('getEnemies', GameEnemies[room])
      socket.emit('getItems', GameItems[room])

      // add player to map
      GamePlayers[room][socket.id] = player
      socket.broadcast.to(room).emit('addPlayer', socket.id, player)

      // check if collision array exist for this map
      // creates collision array if it does not exist
      if (!collisionArrays[room]) {
        collisionArrays[room] = new EasystarConstructor.js()
        collisionArrays[room].setGrid(collisionMap)
        collisionArrays[room].setAcceptableTiles([0])
        collisionArrays[room].enableDiagonals()
      }

      if (!isUpdating[room]) {
        isUpdating[room] = true
        runIntervals(io, room)
      }
    })

    socket.on('savePlayer', player => {
      Character.update(player, {
        where: {
          id: player.id
        },
      })
    })
  })
}

module.exports = socketFunction
<commit_msg>rename mapwidth/height to tilewidth/height<commit_after>const db = require('APP/db')
const Character = db.model('characters')

const enemyProperties = require('APP/app/properties/enemyProperties')
const enemySpawn = require('./enemySpawn.json')
const GamePlayers = {}
const GameEnemies = {}
const GameItems = {}
const collisionArrays = {}
const isUpdating = {}

const EasystarConstructor = require('easystarjs')

const findClosestPlayer = require('./utils').findClosestPlayer

const tileWidth = 32
const tileHeight = 32

const enemyMovement = (io, state) => {
  if (Object.keys(GamePlayers[state])) {
    Object.keys(GameEnemies[state]).forEach(enemyName => {
      const enemy = GameEnemies[state][enemyName]
      const closestPlayer = findClosestPlayer(GamePlayers[state], enemy)
      if (closestPlayer) {
        collisionArrays[state].findPath(
          Math.floor(enemy.x / tileWidth),
          Math.floor(enemy.y / tileHeight),
          Math.floor(closestPlayer.x / tileWidth),
          Math.floor(closestPlayer.y / tileHeight),
          path => {
            if (path && path[1]) {
              const newX = path[1].x * tileWidth
              const newY = path[1].y * tileHeight
              const distance = 1
              enemy.x += newX - enemy.x > 0 ? distance : -distance
              enemy.y += newY - enemy.y > 0 ? distance : -distance
              const newPos = { x: enemy.x, y: enemy.y }
              io.sockets.to(state).emit('updateEnemy', newPos, enemyName)
            }
          }
        )
        collisionArrays[state].calculate()
      }
    })
  }
}

const spawnEnemy = (io, state) => {
  if (Object.keys(GamePlayers[state])) {
    enemySpawn[state].forEach((enemy) => {
      if (!GameEnemies[state][enemy.name]) {
        const enemyStats = Object.assign({}, enemyProperties[enemy.spriteKey].stats)
        GameEnemies[state][enemy.name] = Object.assign({}, enemy, { stats: enemyStats })
        io.sockets.to(state).emit('addEnemy', GameEnemies[state][enemy.name])
      }
    })
  }
}

const runIntervals = (io, state) => {
  setInterval(() => enemyMovement(io, state), 33)
  setInterval(() => spawnEnemy(io, state), 10000)
}

const socketFunction = io => {
  io.on('connection', socket => {
    console.log('got a connection', socket.id)
    let room = 'world'
    socket.join(room)

    socket.on('disconnect', () => {
      if (GamePlayers[room]) {
        delete GamePlayers[room][socket.id]
        socket.broadcast.to(room).emit('removePlayer', socket.id)
      }
      console.log(socket.id, 'disconnected')
    })

    socket.on('updatePlayer', player => {
      if (GamePlayers[room]) {
        GamePlayers[room][socket.id] = Object.assign({}, GamePlayers[room][socket.id], { x: player.playerPos.x, y: player.playerPos.y, lootCount: player.lootCount })
        socket.broadcast.to(room).emit('updatePlayer', socket.id, player)
      }
    })
    socket.on('updateStats', stats => {
      if (GamePlayers[room]) {
        GamePlayers[room][socket.id].stats = stats
      }
      socket.broadcast.to(room).emit('updateStats', socket.id, stats)
    })

    socket.on('fireProjectile', (xCoord, yCoord) => {
      socket.broadcast.to(room).emit('fireProjectile', socket.id, xCoord, yCoord)
    })

    socket.on('hitEnemy', (enemyName, damage) => {
      if (GameEnemies[room]) {
        const damageTaken = damage - GameEnemies[room][enemyName].stats.defense
        GameEnemies[room][enemyName].stats.hp -= damageTaken
        socket.broadcast.to(room).emit('hitEnemy', enemyName, damage)
      }
    })

    socket.on('killEnemy', enemyName => {
      if (GameEnemies[room]) {
        delete GameEnemies[room][enemyName]
        socket.broadcast.to(room).emit('removeEnemy', enemyName)
      }
    })

    socket.on('createItem', item => {
      GameItems[room][item.name] = item
      socket.broadcast.to(room).emit('addItem', item)
    })

    socket.on('killItem', name => {
      if (GameItems[room]) {
        delete GameItems[room][name]
        socket.broadcast.to(room).emit('removeItem', name)
      }
    })

    socket.on('setupState', (player, collisionMap, newRoom) => {
      // remove player from previous map (room)
      if (GamePlayers[room]) {
        delete GamePlayers[room][socket.id]
        socket.broadcast.to(room).emit('removePlayer', socket.id)
      }

      // join new map
      socket.leave(room)
      room = newRoom
      socket.join(room)
      if (!GamePlayers[room]) GamePlayers[room] = {}
      if (!GameEnemies[room]) GameEnemies[room] = {}
      if (!GameItems[room]) GameItems[room] = {}

      // get all players and enemies on the map
      socket.emit('getPlayers', GamePlayers[room])
      socket.emit('getEnemies', GameEnemies[room])
      socket.emit('getItems', GameItems[room])

      // add player to map
      GamePlayers[room][socket.id] = player
      socket.broadcast.to(room).emit('addPlayer', socket.id, player)

      // check if collision array exist for this map
      // creates collision array if it does not exist
      if (!collisionArrays[room]) {
        collisionArrays[room] = new EasystarConstructor.js()
        collisionArrays[room].setGrid(collisionMap)
        collisionArrays[room].setAcceptableTiles([0])
        collisionArrays[room].enableDiagonals()
      }

      if (!isUpdating[room]) {
        isUpdating[room] = true
        runIntervals(io, room)
      }
    })

    socket.on('savePlayer', player => {
      Character.update(player, {
        where: {
          id: player.id
        },
      })
    })
  })
}

module.exports = socketFunction
<|endoftext|>


<commit_before>function change_cat(i) {
	var random_cats = ['i.imgur.com/JwbRHOy.gif','media0.giphy.com/media/PdKTOwHgOASGY/giphy.gif?cid=3640f6095c16c038446b4c5655ab9d1d','rs240.pbsrc.com/albums/ff237/mareesme/Funny%20cats%20and%20dogs%20and%20wildlife/cats38.gif~c200','media.giphy.com/media/Za7KwK4AMeFq/giphy.gif','rs707.pbsrc.com/albums/ww74/onesuleman/miscellaneous_121.gif~c200'];
	var j = Math.ceil(Math.random() * (random_cats.length-1));
	document.getElementById(i).src = 'https://' + random_cats[j];
	document.getElementById(i).style = '';
}

function change_font() {
	var obj = document.getElementById('tt');
	var fonts = [[],
		['Monoton','#FFFFFF','74',"IT'S   NATHALIA'S   BIRTHDAY!

⇊⇊⇊"],
		['Iceland','#228DFF','72',"HAPPY CAKEDAY ~~NATHALIA~~!

⇊⇊⇊"],
		['Pacifico','#FFDD1B','72',"S Dnem Rozhdeniya!

⇊⇊⇊"],
		['PressStart','#B6FF00','72',"Just an 18 yo w/ 6y of EXP adulting!
⇊⇊⇊"],
		['Audiowide','#FF9900','68',"IT'S ALL 'BOUT DIS GAL T'DAY!
[and every day]
⇊⇊⇊"],
		['Vampiro One','#BA01FF','54',"Nathalia's Turning 24, Happy Girl That We Adore!

⇊⇊⇊"]
	];
	var j = Math.ceil(Math.random() * (fonts.length-1));
	var str = 'neon' + j + ' 1s ease-in-out infinite alternate';
	obj.style.animation = str;
	obj.style.WebkitAnimation = str;
	obj.style.MozAnimation = str;
	obj.style.fontFamily = fonts[j][0];
	obj.style.color = fonts[j][1];
	obj.style.fontSize = fonts[j][2];
	obj.innerHTML = fonts[j][3];

}

function change_font_loop() { setInterval(change_font, 5000);}
function change_cat_loop() { setInterval(function(){change_cat('cat1');change_cat('cat2');}, 5000);}
change_font_loop();
change_cat_loop();

$(function(){
	$("#music_control").click(function(){
		$("#music_control").html() == "Pause Music"
			? $("#music_control").html("Play Music")
			: $("#music_control").html("Pause Music");
	});

	$("#go-to-top").click(function(){
		$("html, body").animate({ scrollTop: 0 }, "slow");
		return false;
	});
	//$("#shameless").click(function () { window.location.assign("http://www.firewatchgame.com");});
	//$("#animation_control-container").click(function () { window.scrollTo(0,0);smoothScrollTo(document.getElementById('subtitle').offsetTop);});

	var $elie = $("#putya"), degree = 0, degree_back = 0, timer, i = 1, a = 30;

	function rotate() {
		$elie.css({ WebkitTransform: 'rotate(' + degree_back + 'deg)'});
		$elie.css({ '-moz-transform': 'rotate(' + degree_back + 'deg)'});
		timer = setTimeout(function() {
			if(degree <= a) {degree=degree+i; degree_back=degree_back+i; rotate();}
			else if(degree_back >= -(a)) {degree_back=degree_back-i; if(degree_back == -(a)) degree =-(a); rotate();}
		},50);

		function loop() {
		   $('#putya')
			 .animate({marginTop:90},1000)
			 .animate({marginTop:40},1000, loop);
		}

		loop(); // call this wherever you want

		function fly_balloons_loop() {
			$('.balloon-border')
				.animate({marginTop:-930},8000)
				.animate({marginTop:-900},2000, fly_balloons_loop);
			setTimeout(function() {
				$('.balloon-border2')
				.animate({marginTop:-1100},8500)
				.animate({marginTop:1100},1, fly_balloons_loop);
			},10000);
		}

		fly_balloons_loop();
	}

	rotate();

	$('#animation_control-container').click(function() {
		timer=50;
	}, function() {
		rotate();
	});

	$('#putya').click(function() {
		clearTimeout(timer);
	}, function() {
		rotate();
	});

	function loopOne() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b1').animate({left:randleft,bottom:randtop},10000,function(){
			loopOne();
		});
	}
	function loopTwo() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b2').animate({left:randleft,bottom:randtop},10000,function(){
			loopTwo();
		});
	}
	function loopThree() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b3').animate({left:randleft,bottom:randtop},10000,function(){
			loopThree();
		});
	}
	function loopFour() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b4').animate({left:randleft,bottom:randtop},10000,function(){
			loopFour();
		});
	}
	function loopFive() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b5').animate({left:randleft,bottom:randtop},10000,function(){
			loopFive();
		});
	}

	function loopSix() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b6').animate({left:randleft,bottom:randtop},10000,function(){
			loopSix();
		});
	}
	function loopSeven() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b7').animate({left:randleft,bottom:randtop},10000,function(){
			loopSeven();
		});
	}

	$('#b1,#b4,#b5,#b7').addClass('balloons-rotate-behaviour-one');
	$('#b2,#b3,#b6').addClass('balloons-rotate-behaviour-two');
	loopOne();
	loopTwo();
	loopThree();
	loopFour();
	loopFive();
	loopSix();
	loopSeven();
});
<commit_msg>Few Fixes numero 7 to Nathalia's 24th bday website.<commit_after>function change_cat(i) {
	var random_cats = ['i.imgur.com/JwbRHOy.gif','media0.giphy.com/media/PdKTOwHgOASGY/giphy.gif?cid=3640f6095c16c038446b4c5655ab9d1d','rs240.pbsrc.com/albums/ff237/mareesme/Funny%20cats%20and%20dogs%20and%20wildlife/cats38.gif~c200','media.giphy.com/media/Za7KwK4AMeFq/giphy.gif','rs707.pbsrc.com/albums/ww74/onesuleman/miscellaneous_121.gif~c200'];
	var j = Math.ceil(Math.random() * (random_cats.length-1));
	document.getElementById(i).src = 'https://' + random_cats[j];
	document.getElementById(i).style = '';
}

function change_font() {
	var obj = document.getElementById('tt');
	var fonts = [[],
		['Monoton','#FFFFFF','74',"IT'S  N'S  B'DAY!

⇊⇊⇊"],
		['Iceland','#228DFF','72',"HAPPY CAKEDAY NATHALIA!

⇊⇊⇊"],
		['Pacifico','#FFDD1B','72',"S Dnem Rozhdeniya!

⇊⇊⇊"],
		['PressStart','#B6FF00','72',"Just an 18 yo w/ 6y of EXP adulting!
⇊⇊⇊"],
		['Audiowide','#FF9900','68',"IT'S ALL 'BOUT DIS GAL T'DAY!
[and every day]
⇊⇊⇊"],
		['Vampiro One','#BA01FF','54',"Nathalia's Turning 24, Happy Girl We All Adore!

⇊⇊⇊"]
	];
	var j = Math.ceil(Math.random() * (fonts.length-1));
	var str = 'neon' + j + ' 1s ease-in-out infinite alternate';
	obj.style.animation = str;
	obj.style.WebkitAnimation = str;
	obj.style.MozAnimation = str;
	obj.style.fontFamily = fonts[j][0];
	obj.style.color = fonts[j][1];
	obj.style.fontSize = fonts[j][2];
	obj.innerHTML = fonts[j][3];

}

function change_font_loop() { setInterval(change_font, 5000);}
function change_cat_loop() { setInterval(function(){change_cat('cat1');change_cat('cat2');}, 5000);}
change_font_loop();
change_cat_loop();

$(function(){
	$("#music_control").click(function(){
		$("#music_control").html() == "Pause Music"
			? $("#music_control").html("Play Music")
			: $("#music_control").html("Pause Music");
	});

	$("#go-to-top").click(function(){
		$("html, body").animate({ scrollTop: 0 }, "slow");
		return false;
	});
	//$("#shameless").click(function () { window.location.assign("http://www.firewatchgame.com");});
	//$("#animation_control-container").click(function () { window.scrollTo(0,0);smoothScrollTo(document.getElementById('subtitle').offsetTop);});

	var $elie = $("#putya"), degree = 0, degree_back = 0, timer, i = 1, a = 30;

	function rotate() {
		$elie.css({ WebkitTransform: 'rotate(' + degree_back + 'deg)'});
		$elie.css({ '-moz-transform': 'rotate(' + degree_back + 'deg)'});
		timer = setTimeout(function() {
			if(degree <= a) {degree=degree+i; degree_back=degree_back+i; rotate();}
			else if(degree_back >= -(a)) {degree_back=degree_back-i; if(degree_back == -(a)) degree =-(a); rotate();}
		},50);

		function loop() {
		   $('#putya')
			 .animate({marginTop:90},1000)
			 .animate({marginTop:40},1000, loop);
		}

		loop(); // call this wherever you want

		function fly_balloons_loop() {
			$('.balloon-border')
				.animate({marginTop:-930},8000)
				.animate({marginTop:-900},2000, fly_balloons_loop);
			setTimeout(function() {
				$('.balloon-border2')
				.animate({marginTop:-1100},8500)
				.animate({marginTop:1100},1, fly_balloons_loop);
			},10000);
		}

		fly_balloons_loop();
	}

	rotate();

	$('#animation_control-container').click(function() {
		timer=50;
	}, function() {
		rotate();
	});

	$('#putya').click(function() {
		clearTimeout(timer);
	}, function() {
		rotate();
	});

	function loopOne() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b1').animate({left:randleft,bottom:randtop},10000,function(){
			loopOne();
		});
	}
	function loopTwo() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b2').animate({left:randleft,bottom:randtop},10000,function(){
			loopTwo();
		});
	}
	function loopThree() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b3').animate({left:randleft,bottom:randtop},10000,function(){
			loopThree();
		});
	}
	function loopFour() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b4').animate({left:randleft,bottom:randtop},10000,function(){
			loopFour();
		});
	}
	function loopFive() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b5').animate({left:randleft,bottom:randtop},10000,function(){
			loopFive();
		});
	}

	function loopSix() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b6').animate({left:randleft,bottom:randtop},10000,function(){
			loopSix();
		});
	}
	function loopSeven() {
		var randleft = 1000*Math.random();
		var randtop = 500*Math.random();
		$('#b7').animate({left:randleft,bottom:randtop},10000,function(){
			loopSeven();
		});
	}

	$('#b1,#b4,#b5,#b7').addClass('balloons-rotate-behaviour-one');
	$('#b2,#b3,#b6').addClass('balloons-rotate-behaviour-two');
	loopOne();
	loopTwo();
	loopThree();
	loopFour();
	loopFive();
	loopSix();
	loopSeven();
});
<|endoftext|>


<commit_before>var sys = require("util")

var parseNessusResult = function(nessStr){
    var scoreReg = /CVSS Base Score : (\d\.\d)/;

    var portReg = /\D+ \((\d{1,7})\D+\)/;
    var splitNess = nessStr.split("|");
    var ip = splitNess[2];
    var code = parseFloat(splitNess[4]);
    var holeNote = splitNess[5];
    if(scoreReg.test(nessStr)){
        var score = parseFloat(scoreReg.exec(nessStr)[1]);
    }
    else{
        var score = 0.0;
    }
    if(portReg.test(nessStr)){
        var port = parseFloat(portReg.exec(nessStr)[1]);
    }
    else{
        var port = -1;
    }

    return {"ip": (ip === undefined ? "" : ip),
        "vulnid": (isNaN(code) ? 0 : code),
        "vulntype":(holeNote === undefined ? "" : holeNote),
        "cvss": score,
        "port":port};
}

var parseNessusTimeStamp = function(stampString){
    var moment = require("moment")
    var timeFormat = "ddd MMM DD HH:mm:ss YYYY"
    var splitInput = stampString.split("|")

    var time = moment(splitInput[splitInput.length - 2], timeFormat)
    //var time = splitInput[splitInput.length - 2]
    return time.valueOf()
}

var hasTime = function(line){
    var splits = line.split("|")
    return (splits[splits.length - 2].length > 0 && splits[0] == "timestamps")
}

var isResult = function(line){
    return(line.split("|")[0] === "results")
}

var parseNBEFile = function(nbe){
    var lines = nbe.split("\n")
    var currentTime = 0
    var returnArray = new Array(2)

    for(var i = 0; i < lines.length; i++){
        if(isResult(lines[i])){
            returnArray.push(parseNessusResult(lines[i]))
        }
    }
    return returnArray
}

module.exports.parseNessusResult = parseNessusResult;
module.exports.parseNessusTimeStamp = parseNessusTimeStamp;
module.exports.parseNBEFile = parseNBEFile;
<commit_msg>Added better commenting to the parser.<commit_after>var sys = require("util")

/**
 * Parses a nessus result line and handles missing fields.
 * @param nessStr - nbe result string line
 * @return - structure containing th eip, vulnid, vulntype, cvss and port
 */
var parseNessusResult = function(nessStr){
    var scoreReg = /CVSS Base Score : (\d\.\d)/;

    var portReg = /\D+ \((\d{1,7})\D+\)/;
    var splitNess = nessStr.split("|");
    var ip = splitNess[2];
    var code = parseFloat(splitNess[4]);
    var holeNote = splitNess[5];
    if(scoreReg.test(nessStr)){
        var score = parseFloat(scoreReg.exec(nessStr)[1]);
    }
    else{
        var score = 0.0;
    }
    if(portReg.test(nessStr)){
        var port = parseFloat(portReg.exec(nessStr)[1]);
    }
    else{
        var port = -1;
    }

    return {"ip": (ip === undefined ? "" : ip),
        "vulnid": (isNaN(code) ? 0 : code),
        "vulntype":(holeNote === undefined ? "" : holeNote),
        "cvss": score,
        "port":port};
}

/**
 * @param stampString - timestamp line from an NBE file.
 * @return - milliseconds between epoch and the time in the stamp.
 */
var parseNessusTimeStamp = function(stampString){
    var moment = require("moment")
    var timeFormat = "ddd MMM DD HH:mm:ss YYYY"
    var splitInput = stampString.split("|")

    var time = moment(splitInput[splitInput.length - 2], timeFormat)
    //var time = splitInput[splitInput.length - 2]
    return time.valueOf()
}

/**
 * @param line - line to be tested.
 * @return - returns true if the line is a time line containing a timestamp.
 */
var hasTime = function(line){
    var splits = line.split("|")
    return (splits[splits.length - 2].length > 0 && splits[0] == "timestamps")
}

/**
 * @param line - line to be tested.
 * @return - returns true if the line is a result line and false otherwise.
 */
var isResult = function(line){
    return(line.split("|")[0] === "results")
}

/**
 * @param nbe - a string representing the contents of a NBE file.
 * @return - array where each entry is a result from the NBE file.
 */
var parseNBEFile = function(nbe){
    var lines = nbe.split("\n")
    var currentTime = 0
    var returnArray = new Array(2)

    for(var i = 0; i < lines.length; i++){
        if(isResult(lines[i])){
            returnArray.push(parseNessusResult(lines[i]))
        }
    }
    return returnArray
}

module.exports.parseNessusResult = parseNessusResult;
module.exports.parseNessusTimeStamp = parseNessusTimeStamp;
module.exports.parseNBEFile = parseNBEFile;
<|endoftext|>