<commit_before>goog.provide('og.layer.GmxVector');

goog.require('og.EntityCollection');
goog.require('og.Entity');
goog.require('og.LonLat');
goog.require('og.quadTree');
goog.require('og.quadTree.EntityCollectionQuadNode');
goog.require('og.math');
goog.require('og.inheritance');
goog.require('og.QueueArray');
goog.require('og.Geometry');
goog.require('og.GeometryHandler');
goog.require('og.ajax');

/**
 * Vector layer represents alternative entities store. Used for geospatial data rendering like
 * points, lines, polygons, geometry objects etc.
 * @class
 * @extends {og.layer.Layer}
 * @param {string} [name="noname"] - Layer name.
 * @param {Object} [options] - Layer options:
 * @param {number} [options.minZoom=0] - Minimal visible zoom. 0 is default
 * @param {number} [options.maxZoom=50] - Maximal visible zoom. 50 is default.
 * @param {string} [options.attribution] - Layer attribution.
 * @param {string} [options.zIndex=0] - Layer Z-order index. 0 is default.
 * @param {boolean} [options.visibility=true] - Layer visibility. True is default.
 * @param {boolean} [options.isBaseLayer=false] - Layer base layer. False is default.
 * @param {Array.<og.Entity>} [options.entities] - Entities array.
 * @param {Array.<number,number,number>} [options.scaleByDistance] - Scale by distance parameters.
 *      First index - near distance to the entity, after entity becomes full scale.
 *      Second index - far distance to the entity, when entity becomes zero scale.
 *      Third index - far distance to the entity, when entity becomes invisible.
 * @param {number} [options.nodeCapacity=30] - Maximum entities quantity in the tree node. Rendering optimization parameter. 30 is default.
 * @param {boolean} [options.async=true] - Asynchronous vector data handling before rendering. True for optimization huge data.
 * @param {boolean} [options.groundAlign = false] - Vector data align to the ground relief. Like points with zero altitude lay on the ground.
 *
 * @fires og.layer.GmxVector#entitymove
 * @fires og.layer.GmxVector#draw
 * @fires og.layer.GmxVector#add
 * @fires og.layer.GmxVector#remove
 * @fires og.layer.GmxVector#entityadd
 * @fires og.layer.GmxVector#entityremove
 * @fires og.layer.GmxVector#visibilitychange
 */
og.layer.GmxVector = function (name, options) {
    options = options || {};

    og.inheritance.base(this, name, options);

    this.hostUrl = options.hostUrl || "//maps.kosmosnimki.ru/";

    this._mapId = options.mapId;

    this._layerId = options.layerId;

    this._gmxProperties = null;

    this._checkVersionPath = "Layer/CheckVersion.ashx";

    this.events.registerNames(og.layer.GmxVector.EVENT_NAMES);
};

og.inheritance.extend(og.layer.GmxVector, og.layer.Layer);

og.layer.GmxVector.EVENT_NAMES = [
    /**
     * Triggered when entity has moved.
     * @event og.layer.GmxVector#draw
     */
    "entitymove",

    /**
     * Triggered when layer begin draw.
     * @event og.layer.GmxVector#draw
     */
    "draw",

    /**
     * Triggered when new entity added to the layer.
     * @event og.layer.GmxVector#entityadd
     */
    "entityadd",

    /**
     * Triggered when entity removes from the collection.
     * @event og.layer.GmxVector#entityremove
     */
    "entityremove"
];

/**
 * Vector layer {@link og.layer.GmxVector} object factory.
 * @static
 * @param {String} name - Layer name.
 * @param {Object} options - Layer options.
 * @returns {og.layer.GmxVector} Returns vector layer.
 */
og.layer.gmxVector = function (name, options) {
    return new og.layer.GmxVector(name, options);
};

/**
 * Adds layer to the planet.
 * @public
 * @param {og.scene.RenderNode} planet - Planet scene.
 * @return {og.layer.GmxVector} - Returns og.layer.GmxVector instance.
 */
og.layer.GmxVector.prototype.addTo = function (planet) {
    this._assignPlanet(planet);
    this._initialize();
    return this;
};

og.layer.GmxVector.getLayerInfo = function (hostUrl, layerId, proceedCallback, errorCallback) {
    og.ajax.request(hostUrl + "/rest/ver1/layers/" + layerId + "/info", {
        'type': "GET",
        'responseType': "json",
        'data': {
            'WrapStyle': "None"
        },
        'success': function (data) {
            proceedCallback && proceedCallback(data);
        },
        'error': function (err) {
            errorCallback && errorCallback(err);
        }
    });
};

og.layer.GmxVector.prototype._initialize = function () {
    var p = this._planet;
    var that = this;

    p.camera.events.on("moveend", function (e) {
        if (that._extent.overlaps(that._planet.getViewExtent())) {
            that._checkVersion();
        }
    });

    og.layer.GmxVector.getLayerInfo(this.hostUrl, this._layerId, function (data) {
        that._gmxProperties = data.properties;
        that.setExtent(og.Geometry.getExtent(data.geometry));
        that._checkVersion();
    });
};

og.layer.GmxVector.prototype._checkVersion = function () {
    var p = this._planet;
    var e = p._viewExtentMerc;
    var bbox = [e.southWest.lon, e.southWest.lat, e.northEast.lon, e.northEast.lat];
    var layers = [{ "Name": this._layerId, "Version": -1 }];
    var zoom = p.maxCurrZoom;
    var that = this;
    og.ajax.request(this.hostUrl + this._checkVersionPath, {
        'type': "POST",
        'responseType': "json",
        'data': {
            'WrapStyle': "None",
            'bbox': bbox,
            'srs': "3857",
            'layers': layers,
            'zoom': zoom
        },
        'success': function (data) {
            that._checkVersionSuccess(data);
        },
        'error': function (err) {
            console.log(err);
        }
    });
};

og.layer.GmxVector.prototype._checkVersionSuccess = function(data){

};

/**
 * Start to load tile material.
 * @public
 * @virtual
 * @param {og.planetSegment.Material} material - Current material.
 */
og.layer.GmxVector.prototype.loadMaterial = function (material) {

    var seg = material.segment;

    if (this._isBaseLayer) {
        material.texture = seg._isNorth ? seg.planet.solidTextureOne : seg.planet.solidTextureTwo;
    } else {
        material.texture = seg.planet.transparentTexture;
    }

    if (this._planet.layerLock.isFree()) {
        material.isReady = false;
        material.isLoading = true;

        //
        // TODO: Get to the observer or something like this._planet._vectorTileCreator.add(material);
        //
    }
};

/**
 * Abort exact material loading.
 * @public
 * @param {og.planetSegment.Material} material - Segment material.
 */
og.layer.GmxVector.prototype.abortMaterialLoading = function (material) {
    material.isLoading = false;
    material.isReady = false;
};

og.layer.GmxVector.prototype.applyMaterial = function (material) {
    if (material.isReady) {
        return [0, 0, 1, 1];
    } else {

        !material.isLoading && this.loadMaterial(material);

        var segment = material.segment;
        var pn = segment.node,
            notEmpty = false;

        var mId = this._id;
        var psegm = material;
        while (pn.parentNode) {
            if (psegm && psegm.isReady) {
                notEmpty = true;
                break;
            }
            pn = pn.parentNode;
            psegm = pn.planetSegment.materials[mId];
        }

        if (notEmpty) {
            material.appliedNodeId = pn.nodeId;
            material.texture = psegm.texture;
            material.pickingMask = psegm.pickingMask;
            var dZ2 = 1.0 / (2 << (segment.tileZoom - pn.planetSegment.tileZoom - 1));
            return [
                segment.tileX * dZ2 - pn.planetSegment.tileX,
                segment.tileY * dZ2 - pn.planetSegment.tileY,
                dZ2,
                dZ2
            ];
        } else {
            if (material.textureExists && material._updateTexture) {
                material.texture = material._updateTexture;
                material.pickingMask = material._updatePickingMask;
            } else {
                material.texture = segment.planet.transparentTexture;
                material.pickingMask = segment.planet.transparentTexture;
            }
            return [0, 0, 1, 1];
        }
    }
};

og.layer.GmxVector.prototype.clearMaterial = function (material) {
    if (material.isReady) {
        var gl = material.segment.handler.gl;

        material.isReady = false;
        material.pickingReady = false;

        var t = material.texture;
        material.texture = null;
        t && !t.default && gl.deleteTexture(t);

        t = material.pickingMask;
        material.pickingMask = null;
        t && !t.default && gl.deleteTexture(t);

        t = material._updateTexture;
        material._updateTexture = null;
        t && !t.default && gl.deleteTexture(t);

        t = material._updatePickingMask;
        material._updatePickingMask = null;
        t && !t.default && gl.deleteTexture(t);
    }

    this.abortMaterialLoading(material);

    material.isLoading = false;
    material.textureExists = false;
};

<commit_msg>GmxVector milestone.<commit_after>goog.provide('og.layer.GmxVector');

goog.require('og.EntityCollection');
goog.require('og.Entity');
goog.require('og.LonLat');
goog.require('og.quadTree');
goog.require('og.quadTree.EntityCollectionQuadNode');
goog.require('og.math');
goog.require('og.inheritance');
goog.require('og.QueueArray');
goog.require('og.Geometry');
goog.require('og.GeometryHandler');
goog.require('og.ajax');

/**
 * Vector layer represents alternative entities store. Used for geospatial data rendering like
 * points, lines, polygons, geometry objects etc.
 * @class
 * @extends {og.layer.Layer}
 * @param {string} [name="noname"] - Layer name.
 * @param {Object} [options] - Layer options:
 * @param {number} [options.minZoom=0] - Minimal visible zoom. 0 is default
 * @param {number} [options.maxZoom=50] - Maximal visible zoom. 50 is default.
 * @param {string} [options.attribution] - Layer attribution.
 * @param {string} [options.zIndex=0] - Layer Z-order index. 0 is default.
 * @param {boolean} [options.visibility=true] - Layer visibility. True is default.
 * @param {boolean} [options.isBaseLayer=false] - Layer base layer. False is default.
 * @param {Array.<og.Entity>} [options.entities] - Entities array.
 * @param {Array.<number,number,number>} [options.scaleByDistance] - Scale by distance parameters.
 *      First index - near distance to the entity, after entity becomes full scale.
 *      Second index - far distance to the entity, when entity becomes zero scale.
 *      Third index - far distance to the entity, when entity becomes invisible.
 * @param {number} [options.nodeCapacity=30] - Maximum entities quantity in the tree node. Rendering optimization parameter. 30 is default.
 * @param {boolean} [options.async=true] - Asynchronous vector data handling before rendering. True for optimization huge data.
 * @param {boolean} [options.groundAlign = false] - Vector data align to the ground relief. Like points with zero altitude lay on the ground.
 *
 * @fires og.layer.GmxVector#entitymove
 * @fires og.layer.GmxVector#draw
 * @fires og.layer.GmxVector#add
 * @fires og.layer.GmxVector#remove
 * @fires og.layer.GmxVector#entityadd
 * @fires og.layer.GmxVector#entityremove
 * @fires og.layer.GmxVector#visibilitychange
 */
og.layer.GmxVector = function (name, options) {
    options = options || {};

    og.inheritance.base(this, name, options);

    this.hostUrl = options.hostUrl || "//maps.kosmosnimki.ru/";

    this._mapId = options.mapId;

    this._layerId = options.layerId;

    this._gmxProperties = null;

    this._tileSenderUrl = '//maps.kosmosnimki.ru/TileSender.ashx?WrapStyle=None&ModeKey=tile&r=j&ftc=osm&LayerName={id}&z={z}&x={x}&y={y}&v={v}';

    this.events.registerNames(og.layer.GmxVector.EVENT_NAMES);
};

og.inheritance.extend(og.layer.GmxVector, og.layer.Layer);

og.layer.GmxVector.EVENT_NAMES = [
    /**
     * Triggered when entity has moved.
     * @event og.layer.GmxVector#draw
     */
    "entitymove",

    /**
     * Triggered when layer begin draw.
     * @event og.layer.GmxVector#draw
     */
    "draw",

    /**
     * Triggered when new entity added to the layer.
     * @event og.layer.GmxVector#entityadd
     */
    "entityadd",

    /**
     * Triggered when entity removes from the collection.
     * @event og.layer.GmxVector#entityremove
     */
    "entityremove"
];

/**
 * Vector layer {@link og.layer.GmxVector} object factory.
 * @static
 * @param {String} name - Layer name.
 * @param {Object} options - Layer options.
 * @returns {og.layer.GmxVector} Returns vector layer.
 */
og.layer.gmxVector = function (name, options) {
    return new og.layer.GmxVector(name, options);
};

/**
 * Adds layer to the planet.
 * @public
 * @param {og.scene.RenderNode} planet - Planet scene.
 * @return {og.layer.GmxVector} - Returns og.layer.GmxVector instance.
 */
og.layer.GmxVector.prototype.addTo = function (planet) {
    this._assignPlanet(planet);
    this._initialize();
    return this;
};

og.layer.GmxVector.getLayerInfo = function (hostUrl, layerId, proceedCallback, errorCallback) {
    og.ajax.request(hostUrl + "/rest/ver1/layers/" + layerId + "/info", {
        'type': "GET",
        'responseType': "json",
        'data': {
            'WrapStyle': "None"
        },
        'success': function (data) {
            proceedCallback && proceedCallback(data);
        },
        'error': function (err) {
            errorCallback && errorCallback(err);
        }
    });
};

og.layer.GmxVector.prototype._initialize = function () {
    var p = this._planet;
    var that = this;

    p.camera.events.on("moveend", function (e) {
        if (that._extent.overlaps(that._planet.getViewExtent())) {
            that._checkVersion();
        }
    });

    og.layer.GmxVector.getLayerInfo(this.hostUrl, this._layerId, function (data) {
        that._gmxProperties = data.properties;
        that.setExtent(og.Geometry.getExtent(data.geometry));
        that._checkVersion();
    });
};

og.layer.GmxVector.prototype._checkVersion = function () {
    var p = this._planet;
    var e = p._viewExtentMerc;
    var bbox = [e.southWest.lon, e.southWest.lat, e.northEast.lon, e.northEast.lat];
    var layers = [{ "Name": this._layerId, "Version": -1 }];
    var zoom = p.maxCurrZoom;
    var that = this;
    og.ajax.request(this.hostUrl + "Layer/CheckVersion.ashx", {
        'type': "POST",
        'responseType': "json",
        'data': {
            'WrapStyle': "None",
            'bbox': bbox,
            'srs': "3857",
            'layers': layers,
            'zoom': zoom,
            'ftc': "osm"
        },
        'success': function (data) {
            that._checkVersionSuccess(data);
        },
        'error': function (err) {
            console.log(err);
        }
    });
};

og.layer.GmxVector.prototype._checkVersionSuccess = function (data) {
    console.log("1. Collect tiles");
    console.log("2. Proceed to tileSender");
    var rn = this._planet._renderedNodes;
    for (var i = 0; i < rn.length; i++) {
        var seg = rn[i].planetSegment;
        var url = og.utils.stringTemplate(this._tileSenderUrl, {
            "id": this._layerId,
            "x": seg.tileX.toString(),
            "y": seg.tileY.toString(),
            "z": seg.tileZoom.toString(),
            "v": -1
        });
        console.log(url);
    }

};

/**
 * Start to load tile material.
 * @public
 * @virtual
 * @param {og.planetSegment.Material} material - Current material.
 */
og.layer.GmxVector.prototype.loadMaterial = function (material) {

    var seg = material.segment;

    if (this._isBaseLayer) {
        material.texture = seg._isNorth ? seg.planet.solidTextureOne : seg.planet.solidTextureTwo;
    } else {
        material.texture = seg.planet.transparentTexture;
    }

    if (this._planet.layerLock.isFree()) {
        material.isReady = false;
        material.isLoading = true;

        // var url = og.utils.stringTemplate(this._tileSenderUrl, {
        //     "id": this._layerId,
        //     "x": seg.tileX.toString(),
        //     "y": seg.tileY.toString(),
        //     "z": seg.tileZoom.toString(),
        //     "v": -1
        // });

        console.log(seg.tileX + "," + seg.tileY + ", " + seg.tileZoom);
        //
        //
        // TODO: Get to the observer or something like this._planet._vectorTileCreator.add(material);
        //
    }
};

/**
 * Abort exact material loading.
 * @public
 * @param {og.planetSegment.Material} material - Segment material.
 */
og.layer.GmxVector.prototype.abortMaterialLoading = function (material) {
    material.isLoading = false;
    material.isReady = false;
};

og.layer.GmxVector.prototype.applyMaterial = function (material) {
    if (material.isReady) {
        return [0, 0, 1, 1];
    } else {

        !material.isLoading && this.loadMaterial(material);

        var segment = material.segment;
        var pn = segment.node,
            notEmpty = false;

        var mId = this._id;
        var psegm = material;
        while (pn.parentNode) {
            if (psegm && psegm.isReady) {
                notEmpty = true;
                break;
            }
            pn = pn.parentNode;
            psegm = pn.planetSegment.materials[mId];
        }

        if (notEmpty) {
            material.appliedNodeId = pn.nodeId;
            material.texture = psegm.texture;
            material.pickingMask = psegm.pickingMask;
            var dZ2 = 1.0 / (2 << (segment.tileZoom - pn.planetSegment.tileZoom - 1));
            return [
                segment.tileX * dZ2 - pn.planetSegment.tileX,
                segment.tileY * dZ2 - pn.planetSegment.tileY,
                dZ2,
                dZ2
            ];
        } else {
            if (material.textureExists && material._updateTexture) {
                material.texture = material._updateTexture;
                material.pickingMask = material._updatePickingMask;
            } else {
                material.texture = segment.planet.transparentTexture;
                material.pickingMask = segment.planet.transparentTexture;
            }
            return [0, 0, 1, 1];
        }
    }
};

og.layer.GmxVector.prototype.clearMaterial = function (material) {
    if (material.isReady) {
        var gl = material.segment.handler.gl;

        material.isReady = false;
        material.pickingReady = false;

        var t = material.texture;
        material.texture = null;
        t && !t.default && gl.deleteTexture(t);

        t = material.pickingMask;
        material.pickingMask = null;
        t && !t.default && gl.deleteTexture(t);

        t = material._updateTexture;
        material._updateTexture = null;
        t && !t.default && gl.deleteTexture(t);

        t = material._updatePickingMask;
        material._updatePickingMask = null;
        t && !t.default && gl.deleteTexture(t);
    }

    this.abortMaterialLoading(material);

    material.isLoading = false;
    material.textureExists = false;
};

<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');

module.exports = {
  description: 'Initialize files needed for typescript compilation',

  install(options) {
    if (options.project.isEmberCLIAddon()) {
      options.dummy = true;
    }

    return this._super.install.apply(this, arguments);
  },

  locals() {
    let inRepoAddons = (this.project.pkg['ember-addon'] || {}).paths || [];
    let isAddon = this.project.isEmberCLIAddon();
    let includes = [isAddon ? 'addon' : 'app', 'tests'].concat(inRepoAddons);

    return {
      includes: JSON.stringify(includes, null, 2).replace(/\n/g, '\n  '),
      pathsFor: dasherizedName => {
        let appName = isAddon ? 'dummy' : dasherizedName;
        let paths = {
          [`${appName}/tests/*`]: ['tests/*'],
        };

        if (isAddon) {
          paths[`${appName}/*`] = ['tests/dummy/app/*'];
        } else {
          paths[`${appName}/*`] = ['app/*'];
        }

        if (isAddon) {
          paths[dasherizedName] = ['addon'];
          paths[`${dasherizedName}/*`] = ['addon/*'];
        }

        for (let addon of inRepoAddons) {
          let addonName = path.basename(addon);
          paths[addonName] = [`${addon}/addon`];
          paths[`${addonName}/*`] = [`${addon}/addon/*`];
          paths[`${appName}/*`].push(`${addon}/app/*`);
        }

        return JSON.stringify(paths, null, 2).replace(/\n/g, '\n    ');
      },
    };
  },

  normalizeEntityName() {
    // Entity name is optional right now, creating this hook avoids an error.
  },

  afterInstall() {
    if (this.project.isEmberCLIAddon()) {
      this._installPrecompilationHooks();
    }

    return this.addPackagesToProject([
      { name: 'typescript', target: 'latest' },
      { name: '@types/ember', target: 'latest' },
      { name: '@types/rsvp', target: 'latest' },
      { name: '@types/ember-testing-helpers', target: 'latest' },
    ]);
  },

  _installPrecompilationHooks() {
    let pkgPath = `${this.project.root}/package.json`;
    let pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));

    // Really `prepack` and `postpack` would be ideal, but yarn doesn't execute those when publishing
    this._addScript(pkg.scripts, 'prepublishOnly', 'ember ts:precompile');
    this._addScript(pkg.scripts, 'postpublish', 'ember ts:clean');

    fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
  },

  _addScript(scripts, type, script) {
    if (scripts[type] && scripts[type] !== script) {
      this.ui.writeWarnLine(
        `Found a pre-existing \`${type}\` script in your package.json. ` +
          `By default, ember-cli-typescripts expects to run \`${script}\` in this hook.`
      );
      return;
    }

    scripts[type] = script;
  },
};
<commit_msg>Add ember data types to blueprint.<commit_after>'use strict';

const fs = require('fs');
const path = require('path');

module.exports = {
  description: 'Initialize files needed for typescript compilation',

  install(options) {
    if (options.project.isEmberCLIAddon()) {
      options.dummy = true;
    }

    return this._super.install.apply(this, arguments);
  },

  locals() {
    let inRepoAddons = (this.project.pkg['ember-addon'] || {}).paths || [];
    let isAddon = this.project.isEmberCLIAddon();
    let includes = [isAddon ? 'addon' : 'app', 'tests'].concat(inRepoAddons);

    return {
      includes: JSON.stringify(includes, null, 2).replace(/\n/g, '\n  '),
      pathsFor: dasherizedName => {
        let appName = isAddon ? 'dummy' : dasherizedName;
        let paths = {
          [`${appName}/tests/*`]: ['tests/*'],
        };

        if (isAddon) {
          paths[`${appName}/*`] = ['tests/dummy/app/*'];
        } else {
          paths[`${appName}/*`] = ['app/*'];
        }

        if (isAddon) {
          paths[dasherizedName] = ['addon'];
          paths[`${dasherizedName}/*`] = ['addon/*'];
        }

        for (let addon of inRepoAddons) {
          let addonName = path.basename(addon);
          paths[addonName] = [`${addon}/addon`];
          paths[`${addonName}/*`] = [`${addon}/addon/*`];
          paths[`${appName}/*`].push(`${addon}/app/*`);
        }

        return JSON.stringify(paths, null, 2).replace(/\n/g, '\n    ');
      },
    };
  },

  normalizeEntityName() {
    // Entity name is optional right now, creating this hook avoids an error.
  },

  afterInstall() {
    if (this.project.isEmberCLIAddon()) {
      this._installPrecompilationHooks();
    }

    return this.addPackagesToProject([
      { name: 'typescript', target: 'latest' },
      { name: '@types/ember', target: 'latest' },
      { name: '@types/ember-data', target: 'latest' },
      { name: '@types/rsvp', target: 'latest' },
      { name: '@types/ember-testing-helpers', target: 'latest' },
    ]);
  },

  _installPrecompilationHooks() {
    let pkgPath = `${this.project.root}/package.json`;
    let pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));

    // Really `prepack` and `postpack` would be ideal, but yarn doesn't execute those when publishing
    this._addScript(pkg.scripts, 'prepublishOnly', 'ember ts:precompile');
    this._addScript(pkg.scripts, 'postpublish', 'ember ts:clean');

    fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
  },

  _addScript(scripts, type, script) {
    if (scripts[type] && scripts[type] !== script) {
      this.ui.writeWarnLine(
        `Found a pre-existing \`${type}\` script in your package.json. ` +
          `By default, ember-cli-typescripts expects to run \`${script}\` in this hook.`
      );
      return;
    }

    scripts[type] = script;
  },
};
<|endoftext|>


<commit_before>import Link from 'next/link'

export default function Footer() {
	return (

	)
}<commit_msg>first footer pass<commit_after>import Link from 'next/link'
import SingleColumn from './SingleColumn'
import {contact} from '../lib/constants'

export default function Footer() {
	return (

			<SingleColumn>

Use Urbit

						<Link className="mt-4" href="">Urbit Client</Link>
						<Link className="mt-4" href="">Urbit Binaries</Link>
						<Link className="mt-4" href="">Urbit Apps</Link>
						<Link className="mt-4" href="">Host-Providers</Link>

About

News

Develop

Contribute

Community

						<Link href="">Privacy Policy</Link>

						<Link href="">Terms of Service</Link>

						<Link href="">{contact.email}</Link>

			</SingleColumn>

	)
}<|endoftext|>


<commit_before>import Link from "next/link";
import { useRouter } from "next/router";
import { useState, useEffect } from "react";
import classnames from "classnames";
import MenuTray from "../components/MenuTray";
import { capitalize } from "../lib/lib";

function ActiveLink({ children, href, className, currentPath }) {
  const firstCrumb = currentPath.split("/")[1];

  const activeClassName = classnames({
    "text-wall-600": "/" + firstCrumb === href,
    "text-wall-500": "/" + firstCrumb !== href,
  });

  return (
    <Link href={href} passHref>
      <a className={`${className} ${activeClassName}`}>{children}
    </Link>
  );
}

export default function Header(props) {
  const [isOpen, setTray] = useState(false);

  const currentPath = useRouter().asPath;

  const routeDepth = currentPath.split("/").length;

  const firstCrumb = currentPath.split("/")[1];

  return (

        <Link href="/" passHref>
          Urbit
        </Link>
        {routeDepth > 2 ? (
          <Link href={`/${firstCrumb}`} passHref>

              {capitalize(firstCrumb)}

          </Link>
        ) : null}

      {
        // Large screen header
      }

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 text-green-400 type-ui button-text"
          href="/getting-started"
        >
          Get Started
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 type-ui"
          href="/overview"
        >
          Overview
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 type-ui"
          href="/faq"
        >
          FAQ
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 type-ui"
          href="/grants"
        >
          Grants
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 type-ui"
          href="/events"
        >
          Events
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 type-ui"
          href="/blog"
        >
          Blog
        </ActiveLink>

      {
        // Small screen header
      }
      <MenuTray isOpen={isOpen} setTray={setTray} search={props.search}>
        <Link href="/" passHref>
          Urbit
        </Link>
        <Link href="https://urbit.org" passHref>
          Urbit.org
        </Link>
        <Link href="https://operators.urbit.org" passHref>
          Operators
        </Link>
        <Link href="https://developers.urbit.org" passHref>
          Developers
        </Link>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 mb-4 text-green-400"
          href="/getting-started"
        >
          Get Started
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mt-4 mr-5 mb-4"
          href="/overview"
        >
          Overview
        </ActiveLink>

        <ActiveLink currentPath={currentPath} className="mr-5 mb-4" href="/faq">
          FAQ
        </ActiveLink>

        <ActiveLink currentPath={currentPath} className="mr-5 mb-4" href="/grants">
          Grants
        </ActiveLink>
        <ActiveLink
          currentPath={currentPath}
          className="mr-5 mb-4"
          href="/events"
        >
          Events
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 mb-4"
          href="/blog"
        >
          Blog
        </ActiveLink>

      </MenuTray>

  );
}
<commit_msg>Update Header.js<commit_after>import Link from "next/link";
import { useRouter } from "next/router";
import { useState, useEffect } from "react";
import classnames from "classnames";
import MenuTray from "../components/MenuTray";
import { capitalize } from "../lib/lib";

function ActiveLink({ children, href, className, currentPath }) {
  const firstCrumb = currentPath.split("/")[1];

  const activeClassName = classnames({
    "text-wall-600": "/" + firstCrumb === href,
    "text-wall-500": "/" + firstCrumb !== href,
  });

  return (
    <Link href={href} passHref>
      <a className={`${className} ${activeClassName}`}>{children}
    </Link>
  );
}

export default function Header(props) {
  const [isOpen, setTray] = useState(false);

  const currentPath = useRouter().asPath;

  const routeDepth = currentPath.split("/").length;

  const firstCrumb = currentPath.split("/")[1];

  return (

        <Link href="/" passHref>
          Urbit
        </Link>
        {routeDepth > 2 ? (
          <Link href={`/${firstCrumb}`} passHref>

              {capitalize(firstCrumb)}

          </Link>
        ) : null}

      {
        // Large screen header
      }

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 text-green-400 type-ui button-text"
          href="/getting-started"
        >
          Get Started
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 type-ui"
          href="/overview"
        >
          Overview
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 type-ui"
          href="/grants"
        >
          Grants
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 type-ui"
          href="/events"
        >
          Events
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 type-ui"
          href="/blog"
        >
          Blog
        </ActiveLink>

      {
        // Small screen header
      }
      <MenuTray isOpen={isOpen} setTray={setTray} search={props.search}>
        <Link href="/" passHref>
          Urbit
        </Link>
        <Link href="https://urbit.org" passHref>
          Urbit.org
        </Link>
        <Link href="https://operators.urbit.org" passHref>
          Operators
        </Link>
        <Link href="https://developers.urbit.org" passHref>
          Developers
        </Link>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 mb-4 text-green-400"
          href="/getting-started"
        >
          Get Started
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mt-4 mr-5 mb-4"
          href="/overview"
        >
          Overview
        </ActiveLink>

        <ActiveLink currentPath={currentPath} className="mr-5 mb-4" href="/grants">
          Grants
        </ActiveLink>
        <ActiveLink
          currentPath={currentPath}
          className="mr-5 mb-4"
          href="/events"
        >
          Events
        </ActiveLink>

        <ActiveLink
          currentPath={currentPath}
          className="mr-5 mb-4"
          href="/blog"
        >
          Blog
        </ActiveLink>

      </MenuTray>

  );
}
<|endoftext|>


<commit_before>import React, {Component} from "react";
import {
  View,
  Text,
  Image
} from "react-native";

import EventListView from '../components/EventListView';
import SearchBar from 'react-native-searchbar';
import events from "../static/content/events.js";

export default class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      events,
      results: []
    };
    this._handleResults = this._handleResults.bind(this);
  }

  _handleResults(results) {
    this.setState({ results });
  }

  render() {
    return (
      <View>
          <EventListView
            events={this.state.results}
          />
      <SearchBar
        ref={(ref) => this.searchBar = ref}
        data={events}
        hideBack={true}
        handleResults={this._handleResults}
        placeholder={"Search for events"}
        showOnLoad
      />
      </View>
    );
  }
}<commit_msg>search styles<commit_after>import React, {Component} from "react";
import {
  View,
  Text,
  Image
} from "react-native";

import EventListView from '../components/EventListView';
import SearchBar from 'react-native-searchbar';
import events from "../static/content/events.js";

export default class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      events,
      results: []
    };
    this._handleResults = this._handleResults.bind(this);
  }

  _handleResults(results) {
    this.setState({ results });
  }

  render() {
    return (
      <View style={{ marginTop: 80 }}>
          <EventListView
            events={this.state.results}
          />
      <SearchBar
        ref={(ref) => this.searchBar = ref}
        data={events}
        hideBack={true}
        handleResults={this._handleResults}
        placeholder={"Search for events"}
        showOnLoad
      />
      </View>
    );
  }
}<|endoftext|>


<commit_before>const React = require('react');
const IdyllComponent = require('idyll-component');
class Header extends IdyllComponent {
  render() {
    return (

          {this.props.title}

        {
          this.props.subtitle && (

              {this.props.subtitle}

          )
        }

          By: {this.props.author}

    );
  }
}

module.exports = Header;
<commit_msg>support headers without an author<commit_after>const React = require('react');
const IdyllComponent = require('idyll-component');
class Header extends IdyllComponent {
  render() {
    return (

          {this.props.title}

        {
          this.props.subtitle && (

              {this.props.subtitle}

          )
        }
        {
          this.props.author && (

              By: {this.props.author}

          )
        }

    );
  }
}

module.exports = Header;
<|endoftext|>


<commit_before>/**
 * @module ol/source/BingMaps
 */

import {createFromTileUrlFunctions} from '../tileurlfunction.js';
import {applyTransform, intersects} from '../extent.js';
import {jsonp as requestJSONP} from '../net.js';
import {get as getProjection, getTransformFromProjections} from '../proj.js';
import SourceState from '../source/State.js';
import TileImage from '../source/TileImage.js';
import {createOrUpdate, quadKey} from '../tilecoord.js';
import {createXYZ, extentFromProjection} from '../tilegrid.js';

/**
 * The attribution containing a link to the Microsoft® Bing™ Maps Platform APIs’
 * Terms Of Use.
 * @const
 * @type {string}
 */
const TOS_ATTRIBUTION = '' +
      'Terms of Use';

/**
 * @typedef {Object} Options
 * @property {number} [cacheSize=2048] Cache size.
 * @property {boolean} [hidpi=false] If `true` hidpi tiles will be requested.
 * @property {string} [culture='en-us'] Culture code.
 * @property {string} key Bing Maps API key. Get yours at http://www.bingmapsportal.com/.
 * @property {string} imagerySet Type of imagery.
 * @property {number} [maxZoom=21] Max zoom. Default is what's advertized by the BingMaps service.
 * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
 * Higher values can increase reprojection performance, but decrease precision.
 * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
 * ```js
 * function(imageTile, src) {
 *   imageTile.getImage().src = src;
 * };
 * ```
 * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
 * @property {number} [transition] Duration of the opacity transition for rendering.
 * To disable the opacity transition, pass `transition: 0`.
 */

/**
 * @typedef {Object} BingMapsImageryMetadataResponse
 * @property {number} statusCode The response status code
 * @property {string} statusDescription The response status description
 * @property {string} authenticationResultCode The authentication result code
 * @property {Array<ResourceSet>} resourceSets The array of resource sets
 */

/**
 * @typedef {Object} ResourceSet
 * @property {Array<Resource>} resources
 */

/**
 * @typedef {Object} Resource
 * @property {number} imageHeight The image height
 * @property {number} imageWidth The image width
 * @property {number} zoomMin The minimum zoom level
 * @property {string} imageUrl The image URL
 * @property {Array<string>} imageUrlSubdomains The image URL subdomains for rotation
 * @property {Array<ImageryProvider>} [imageryProviders] The array of ImageryProviders
 */

/**
 * @typedef {Object} ImageryProvider
 * @property {Array<CoverageArea>} coverageAreas The coverage areas
 * @property {string} [attribution] The attribution
 */

/**
 * @typedef {Object} CoverageArea
 * @property {number} zoomMin The minimum zoom
 * @property {number} zoomMax The maximum zoom
 * @property {Array<number>} bbox The coverage bounding box
 */

/**
 * @classdesc
 * Layer source for Bing Maps tile data.
 * @api
 */
class BingMaps extends TileImage {
  /**
   * @param {Options=} options Bing Maps options.
   */
  constructor(options) {

    const hidpi = options.hidpi !== undefined ? options.hidpi : false;

    super({
      cacheSize: options.cacheSize,
      crossOrigin: 'anonymous',
      opaque: true,
      projection: getProjection('EPSG:3857'),
      reprojectionErrorThreshold: options.reprojectionErrorThreshold,
      state: SourceState.LOADING,
      tileLoadFunction: options.tileLoadFunction,
      tilePixelRatio: hidpi ? 2 : 1,
      wrapX: options.wrapX !== undefined ? options.wrapX : true,
      transition: options.transition
    });

    /**
     * @private
     * @type {boolean}
     */
    this.hidpi_ = hidpi;

    /**
     * @private
     * @type {string}
     */
    this.culture_ = options.culture !== undefined ? options.culture : 'en-us';

    /**
     * @private
     * @type {number}
     */
    this.maxZoom_ = options.maxZoom !== undefined ? options.maxZoom : -1;

    /**
     * @private
     * @type {string}
     */
    this.apiKey_ = options.key;

    /**
     * @private
     * @type {string}
     */
    this.imagerySet_ = options.imagerySet;

    const url = 'https://dev.virtualearth.net/REST/v1/Imagery/Metadata/' +
        this.imagerySet_ +
        '?uriScheme=https&include=ImageryProviders&key=' + this.apiKey_ +
        '&c=' + this.culture_;

    requestJSONP(url, this.handleImageryMetadataResponse.bind(this), undefined,
      'jsonp');

  }

  /**
   * Get the api key used for this source.
   *
   * @return {string} The api key.
   * @api
   */
  getApiKey() {
    return this.apiKey_;
  }

  /**
   * Get the imagery set associated with this source.
   *
   * @return {string} The imagery set.
   * @api
   */
  getImagerySet() {
    return this.imagerySet_;
  }

  /**
   * @param {BingMapsImageryMetadataResponse} response Response.
   */
  handleImageryMetadataResponse(response) {
    if (response.statusCode != 200 ||
        response.statusDescription != 'OK' ||
        response.authenticationResultCode != 'ValidCredentials' ||
        response.resourceSets.length != 1 ||
        response.resourceSets[0].resources.length != 1) {
      this.setState(SourceState.ERROR);
      return;
    }

    const resource = response.resourceSets[0].resources[0];
    const maxZoom = this.maxZoom_ == -1 ? resource.zoomMax : this.maxZoom_;

    const sourceProjection = this.getProjection();
    const extent = extentFromProjection(sourceProjection);
    const tileSize = resource.imageWidth == resource.imageHeight ?
      resource.imageWidth : [resource.imageWidth, resource.imageHeight];
    const tileGrid = createXYZ({
      extent: extent,
      minZoom: resource.zoomMin,
      maxZoom: maxZoom,
      tileSize: tileSize / (this.hidpi_ ? 2 : 1)
    });
    this.tileGrid = tileGrid;

    const culture = this.culture_;
    const hidpi = this.hidpi_;
    this.tileUrlFunction = createFromTileUrlFunctions(
      resource.imageUrlSubdomains.map(function(subdomain) {
        const quadKeyTileCoord = [0, 0, 0];
        const imageUrl = resource.imageUrl
          .replace('{subdomain}', subdomain)
          .replace('{culture}', culture);
        return (
          /**
           * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
           * @param {number} pixelRatio Pixel ratio.
           * @param {import("../proj/Projection.js").default} projection Projection.
           * @return {string|undefined} Tile URL.
           */
          function(tileCoord, pixelRatio, projection) {
            if (!tileCoord) {
              return undefined;
            } else {
              createOrUpdate(tileCoord[0], tileCoord[1], -tileCoord[2] - 1, quadKeyTileCoord);
              let url = imageUrl;
              if (hidpi) {
                url += '&dpi=d1&device=mobile';
              }
              return url.replace('{quadkey}', quadKey(quadKeyTileCoord));
            }
          }
        );
      }));

    if (resource.imageryProviders) {
      const transform = getTransformFromProjections(
        getProjection('EPSG:4326'), this.getProjection());

      this.setAttributions(function(frameState) {
        const attributions = [];
        const zoom = frameState.viewState.zoom;
        resource.imageryProviders.map(function(imageryProvider) {
          let intersecting = false;
          const coverageAreas = imageryProvider.coverageAreas;
          for (let i = 0, ii = coverageAreas.length; i < ii; ++i) {
            const coverageArea = coverageAreas[i];
            if (zoom >= coverageArea.zoomMin && zoom <= coverageArea.zoomMax) {
              const bbox = coverageArea.bbox;
              const epsg4326Extent = [bbox[1], bbox[0], bbox[3], bbox[2]];
              const extent = applyTransform(epsg4326Extent, transform);
              if (intersects(extent, frameState.extent)) {
                intersecting = true;
                break;
              }
            }
          }
          if (intersecting) {
            attributions.push(imageryProvider.attribution);
          }
        });

        attributions.push(TOS_ATTRIBUTION);
        return attributions;
      });
    }

    this.setState(SourceState.READY);
  }
}

export default BingMaps;
<commit_msg>Fix arithmetic error on potential array<commit_after>/**
 * @module ol/source/BingMaps
 */

import {createFromTileUrlFunctions} from '../tileurlfunction.js';
import {applyTransform, intersects} from '../extent.js';
import {jsonp as requestJSONP} from '../net.js';
import {get as getProjection, getTransformFromProjections} from '../proj.js';
import SourceState from '../source/State.js';
import TileImage from '../source/TileImage.js';
import {createOrUpdate, quadKey} from '../tilecoord.js';
import {createXYZ, extentFromProjection} from '../tilegrid.js';

/**
 * The attribution containing a link to the Microsoft® Bing™ Maps Platform APIs’
 * Terms Of Use.
 * @const
 * @type {string}
 */
const TOS_ATTRIBUTION = '' +
      'Terms of Use';

/**
 * @typedef {Object} Options
 * @property {number} [cacheSize=2048] Cache size.
 * @property {boolean} [hidpi=false] If `true` hidpi tiles will be requested.
 * @property {string} [culture='en-us'] Culture code.
 * @property {string} key Bing Maps API key. Get yours at http://www.bingmapsportal.com/.
 * @property {string} imagerySet Type of imagery.
 * @property {number} [maxZoom=21] Max zoom. Default is what's advertized by the BingMaps service.
 * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
 * Higher values can increase reprojection performance, but decrease precision.
 * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
 * ```js
 * function(imageTile, src) {
 *   imageTile.getImage().src = src;
 * };
 * ```
 * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
 * @property {number} [transition] Duration of the opacity transition for rendering.
 * To disable the opacity transition, pass `transition: 0`.
 */

/**
 * @typedef {Object} BingMapsImageryMetadataResponse
 * @property {number} statusCode The response status code
 * @property {string} statusDescription The response status description
 * @property {string} authenticationResultCode The authentication result code
 * @property {Array<ResourceSet>} resourceSets The array of resource sets
 */

/**
 * @typedef {Object} ResourceSet
 * @property {Array<Resource>} resources
 */

/**
 * @typedef {Object} Resource
 * @property {number} imageHeight The image height
 * @property {number} imageWidth The image width
 * @property {number} zoomMin The minimum zoom level
 * @property {number} zoomMax The maximum zoom level
 * @property {string} imageUrl The image URL
 * @property {Array<string>} imageUrlSubdomains The image URL subdomains for rotation
 * @property {Array<ImageryProvider>} [imageryProviders] The array of ImageryProviders
 */

/**
 * @typedef {Object} ImageryProvider
 * @property {Array<CoverageArea>} coverageAreas The coverage areas
 * @property {string} [attribution] The attribution
 */

/**
 * @typedef {Object} CoverageArea
 * @property {number} zoomMin The minimum zoom
 * @property {number} zoomMax The maximum zoom
 * @property {Array<number>} bbox The coverage bounding box
 */

/**
 * @classdesc
 * Layer source for Bing Maps tile data.
 * @api
 */
class BingMaps extends TileImage {
  /**
   * @param {Options=} options Bing Maps options.
   */
  constructor(options) {

    const hidpi = options.hidpi !== undefined ? options.hidpi : false;

    super({
      cacheSize: options.cacheSize,
      crossOrigin: 'anonymous',
      opaque: true,
      projection: getProjection('EPSG:3857'),
      reprojectionErrorThreshold: options.reprojectionErrorThreshold,
      state: SourceState.LOADING,
      tileLoadFunction: options.tileLoadFunction,
      tilePixelRatio: hidpi ? 2 : 1,
      wrapX: options.wrapX !== undefined ? options.wrapX : true,
      transition: options.transition
    });

    /**
     * @private
     * @type {boolean}
     */
    this.hidpi_ = hidpi;

    /**
     * @private
     * @type {string}
     */
    this.culture_ = options.culture !== undefined ? options.culture : 'en-us';

    /**
     * @private
     * @type {number}
     */
    this.maxZoom_ = options.maxZoom !== undefined ? options.maxZoom : -1;

    /**
     * @private
     * @type {string}
     */
    this.apiKey_ = options.key;

    /**
     * @private
     * @type {string}
     */
    this.imagerySet_ = options.imagerySet;

    const url = 'https://dev.virtualearth.net/REST/v1/Imagery/Metadata/' +
        this.imagerySet_ +
        '?uriScheme=https&include=ImageryProviders&key=' + this.apiKey_ +
        '&c=' + this.culture_;

    requestJSONP(url, this.handleImageryMetadataResponse.bind(this), undefined,
      'jsonp');

  }

  /**
   * Get the api key used for this source.
   *
   * @return {string} The api key.
   * @api
   */
  getApiKey() {
    return this.apiKey_;
  }

  /**
   * Get the imagery set associated with this source.
   *
   * @return {string} The imagery set.
   * @api
   */
  getImagerySet() {
    return this.imagerySet_;
  }

  /**
   * @param {BingMapsImageryMetadataResponse} response Response.
   */
  handleImageryMetadataResponse(response) {
    if (response.statusCode != 200 ||
        response.statusDescription != 'OK' ||
        response.authenticationResultCode != 'ValidCredentials' ||
        response.resourceSets.length != 1 ||
        response.resourceSets[0].resources.length != 1) {
      this.setState(SourceState.ERROR);
      return;
    }

    const resource = response.resourceSets[0].resources[0];
    const maxZoom = this.maxZoom_ == -1 ? resource.zoomMax : this.maxZoom_;

    const sourceProjection = this.getProjection();
    const extent = extentFromProjection(sourceProjection);
    const scale = this.hidpi_ ? 2 : 1;
    const tileSize = resource.imageWidth == resource.imageHeight ?
      resource.imageWidth / scale :
      [resource.imageWidth / scale, resource.imageHeight / scale];

    const tileGrid = createXYZ({
      extent: extent,
      minZoom: resource.zoomMin,
      maxZoom: maxZoom,
      tileSize: tileSize
    });
    this.tileGrid = tileGrid;

    const culture = this.culture_;
    const hidpi = this.hidpi_;
    this.tileUrlFunction = createFromTileUrlFunctions(
      resource.imageUrlSubdomains.map(function(subdomain) {
        const quadKeyTileCoord = [0, 0, 0];
        const imageUrl = resource.imageUrl
          .replace('{subdomain}', subdomain)
          .replace('{culture}', culture);
        return (
          /**
           * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
           * @param {number} pixelRatio Pixel ratio.
           * @param {import("../proj/Projection.js").default} projection Projection.
           * @return {string|undefined} Tile URL.
           */
          function(tileCoord, pixelRatio, projection) {
            if (!tileCoord) {
              return undefined;
            } else {
              createOrUpdate(tileCoord[0], tileCoord[1], -tileCoord[2] - 1, quadKeyTileCoord);
              let url = imageUrl;
              if (hidpi) {
                url += '&dpi=d1&device=mobile';
              }
              return url.replace('{quadkey}', quadKey(quadKeyTileCoord));
            }
          }
        );
      }));

    if (resource.imageryProviders) {
      const transform = getTransformFromProjections(
        getProjection('EPSG:4326'), this.getProjection());

      this.setAttributions(function(frameState) {
        const attributions = [];
        const zoom = frameState.viewState.zoom;
        resource.imageryProviders.map(function(imageryProvider) {
          let intersecting = false;
          const coverageAreas = imageryProvider.coverageAreas;
          for (let i = 0, ii = coverageAreas.length; i < ii; ++i) {
            const coverageArea = coverageAreas[i];
            if (zoom >= coverageArea.zoomMin && zoom <= coverageArea.zoomMax) {
              const bbox = coverageArea.bbox;
              const epsg4326Extent = [bbox[1], bbox[0], bbox[3], bbox[2]];
              const extent = applyTransform(epsg4326Extent, transform);
              if (intersects(extent, frameState.extent)) {
                intersecting = true;
                break;
              }
            }
          }
          if (intersecting) {
            attributions.push(imageryProvider.attribution);
          }
        });

        attributions.push(TOS_ATTRIBUTION);
        return attributions;
      });
    }

    this.setState(SourceState.READY);
  }
}

export default BingMaps;
<|endoftext|>


<commit_before>/**
 * @fileOverview Loader module for restartless addons
 * @author       YUKI "Piro" Hiroshi
 * @version      9
 *
 * @license
 *   The MIT License, Copyright (c) 2010-2014 YUKI "Piro" Hiroshi.
 *   https://github.com/piroor/restartless/blob/master/license.txt
 * @url http://github.com/piroor/restartless
 */

/** You can customize shared properties for loaded scripts. */
var Application = (function() {
	if ('@mozilla.org/fuel/application;1' in Components.classes)
		return Components.classes['@mozilla.org/fuel/application;1']
				.getService(Components.interfaces.fuelIApplication);
	if ('@mozilla.org/steel/application;1' in Components.classes)
		return Components.classes['@mozilla.org/steel/application;1']
				.getService(Components.interfaces.steelIApplication);
	return null;
})();
// import base64 utilities from the js code module namespace
var { atob, btoa, console } = Components.utils.import('resource://gre/modules/Services.jsm', {});
var _namespacePrototype = {
		Cc : Components.classes,
		Ci : Components.interfaces,
		Cu : Components.utils,
		Cr : Components.results,
		Application : Application,
		console : console,
		btoa    : function(aInput) {
			return btoa(aInput);
		},
		atob    : function(aInput) {
			return atob(aInput);
		}
	};
var _namespaces;

/**
 * This functiom loads specified script into a unique namespace for the URL.
 * Namespaces for loaded scripts have a wrapped version of this function.
 * Both this and wrapped work like as Components.utils.import().
 * Due to the reserved symbol "import", we have to use another name "load"
 * instead it.
 *
 * @param {String} aScriptURL
 *   URL of a script. Wrapped version of load() can handle related path.

 *   Related path will be resolved based on the location of the caller script.
 * @param {Object=} aExportTargetForImport
 *   EXPORTED_SYMBOLS in the loaded script will be exported to the object.
 *   If no object is specified, symbols will be exported to the global object
 *   of the caller.
 * @param {Object=} aExportTargetForRequire
 *   Properties of "exports" in the loaded script will be exported to the object.
 *
 * @returns {Object}
 *   The global object for the loaded script.
 */
function load(aURISpec, aExportTargetForImport, aExportTargetForRequire, aRoot)
{
	if (!_namespaces)
		_namespaces = {};
	var ns;
	if (aURISpec in _namespaces) {
		ns = _namespaces[aURISpec];
		_exportForImport(ns, aExportTargetForImport);
		_exportForRequire(ns, aExportTargetForRequire);
		return ns;
	}
	ns = _createNamespace(aURISpec, aRoot || aURISpec);
	try {
		Components.classes['@mozilla.org/moz/jssubscript-loader;1']
			.getService(Components.interfaces.mozIJSSubScriptLoader)
			.loadSubScript(aURISpec, ns);
	}
	catch(e) {
		let message = 'Loader::load('+aURISpec+') failed!\n'+e+'\n';
		dump(message);
		Components.utils.reportError(message + e.stack);
		throw e;
	}
	_exportForImport(ns, aExportTargetForImport);
	_exportForRequire(ns, aExportTargetForRequire);
	return _namespaces[aURISpec] = ns;
}

// JavaScript code module style
function _exportForImport(aSource, aTarget)
{
	if (
		!aTarget ||
		!('EXPORTED_SYMBOLS' in aSource) ||
		!aSource.EXPORTED_SYMBOLS ||
		!aSource.EXPORTED_SYMBOLS.forEach
		)
		return;
	for each (var symbol in aSource.EXPORTED_SYMBOLS)
	{
		aTarget[symbol] = aSource[symbol];
	}
}

// CommonJS style
function _exportForRequire(aSource, aTarget)
{
	if (
		!aTarget ||
		!('exports' in aSource) ||
		!aSource.exports ||
		typeof aSource.exports != 'object'
		)
		return;
	for (var symbol in aSource.exports)
	{
		aTarget[symbol] = aSource.exports[symbol];
	}
}

var IOService = Components.classes['@mozilla.org/network/io-service;1']
					.getService(Components.interfaces.nsIIOService);
var FileHandler = IOService.getProtocolHandler('file')
					.QueryInterface(Components.interfaces.nsIFileProtocolHandler);

/**
 * Checks existence of the file specified by the given relative path and the base URI.
 *
 * @param {String} aPath
 *   A relative path to a file or directory, from the aBaseURI.
 * @param {String} aBaseURI
 *   An absolute URI (with scheme) for relative paths.
 *
 * @returns {String}
 *   If the file (or directory) exists, returns the absolute URI. Otherwise null.
 */
function exists(aPath, aBaseURI)
{
	if (/^\w+:/.test(aPath)) {
		let leafName = aPath.match(/([^\/]+)$/);
		leafName = leafName ? leafName[1] : '' ;
		aBaseURI = aPath.replace(/(?:[^\/]+)$/, '');
		aPath = leafName;
	}
	var baseURI = aBaseURI.indexOf('file:') == 0 ?
					IOService.newFileURI(FileHandler.getFileFromURLSpec(aBaseURI)) :
					IOService.newURI(aBaseURI, null, null);
	if (aBaseURI.indexOf('jar:') == 0) {
		baseURI = baseURI.QueryInterface(Components.interfaces.nsIJARURI);
		var reader = Components.classes['@mozilla.org/libjar/zip-reader;1']
						.createInstance(Components.interfaces.nsIZipReader);
		reader.open(baseURI.JARFile.QueryInterface(Components.interfaces.nsIFileURL).file);
	    try {
			let baseEntry = baseURI.JAREntry.replace(/[^\/]+$/, '');
			let entries = reader.findEntries(baseEntry + aPath + '$');
			let found = entries.hasMore();
			return found ? baseURI.resolve(aPath) : null ;
		}
		finally {
			reader.close();
		}
	}
	else {
		let resolved = baseURI.resolve(aPath);
		return FileHandler.getFileFromURLSpec(resolved).exists() ? resolved : null ;
	}
}

function doAndWait(aAsyncTask)
{
	const Cc = Components.classes;
	const Ci = Components.interfaces;

	var done = false;
	var returnedValue = void(0);
	var continuation = function(aReturnedValue) {
			done = true;
			returnedValue = aReturnedValue;
		};

	var timer = Cc['@mozilla.org/timer;1']
					.createInstance(Ci.nsITimer);
	timer.init(function() {
		aAsyncTask(continuation);
	}, 0, Ci.nsITimer.TYPE_ONE_SHOT);

	var thread = Cc['@mozilla.org/thread-manager;1']
					.getService(Ci.nsIThreadManager)
					.currentThread;
	while (!done) {
		thread.processNextEvent(true);
	}
	return returnedValue;
}

function _readFrom(aURISpec, aEncoding)
{
	const Cc = Components.classes;
	const Ci = Components.interfaces;

	var uri = aURISpec.indexOf('file:') == 0 ?
			IOService.newFileURI(FileHandler.getFileFromURLSpec(aURISpec)) :
			IOService.newURI(aURISpec, null, null) ;
	var channel = IOService.newChannelFromURI(uri.QueryInterface(Ci.nsIURI));
	var stream = channel.open();

	var fileContents = null;
	try {
		if (aEncoding) {
			var converterStream = Cc['@mozilla.org/intl/converter-input-stream;1']
					.createInstance(Ci.nsIConverterInputStream);
			var buffer = stream.available();
			converterStream.init(stream, aEncoding, buffer,
				converterStream.DEFAULT_REPLACEMENT_CHARACTER);
			var out = { value : null };
			converterStream.readString(stream.available(), out);
			converterStream.close();
			fileContents = out.value;
		}
		else {
			var scriptableStream = Cc['@mozilla.org/scriptableinputstream;1']
					.createInstance(Ci.nsIScriptableInputStream);
			scriptableStream.init(stream);
			fileContents = scriptableStream.read(scriptableStream.available());
			scriptableStream.close();
		}
	}
	finally {
		stream.close();
	}
	return fileContents;
}

function _createNamespace(aURISpec, aRoot)
{
	var baseURI = aURISpec.indexOf('file:') == 0 ?
					IOService.newFileURI(FileHandler.getFileFromURLSpec(aURISpec)) :
					IOService.newURI(aURISpec, null, null);
	var rootURI = typeof aRoot == 'string' ?
					(aRoot.indexOf('file:') == 0 ?
						IOService.newFileURI(FileHandler.getFileFromURLSpec(aRoot)) :
						IOService.newURI(aRoot, null, null)
					) :
					aRoot ;
	var ns = {
			__proto__ : _namespacePrototype,
			location : _createFakeLocation(baseURI),
			exists : function(aPath, aBase) {
				return exists(aPath, aBase || baseURI.spec);
			},
			exist : function(aPath, aBase) { // alias
				return exists(aPath, aBase || baseURI.spec);
			},
			/** JavaScript code module style */
			load : function(aURISpec, aExportTarget) {
				if (!/\.jsm?$/.test(aURISpec)) {
					if (exists(aURISpec+'.js', baseURI.spec))
						aURISpec += '.js'
					else if (exists(aURISpec+'.jsm', baseURI.spec))
						aURISpec += '.jsm'
				}
				var resolved = baseURI.resolve(aURISpec);
				if (resolved == aURISpec)
					throw new Error('Recursive load!');
				return load(resolved, aExportTarget || ns, aExportTarget, rootURI);
			},
			'import' : function() { // alias
				return this.load.apply(this, arguments);
			},
			/**
			 * CommonJS style
			 * @url http://www.commonjs.org/specs/
			 */
			require : function(aURISpec) {
				if (!/\.jsm?$/.test(aURISpec)) {
					if (exists(aURISpec+'.js', baseURI.spec))
						aURISpec += '.js'
					else if (exists(aURISpec+'.jsm', baseURI.spec))
						aURISpec += '.jsm'
				}
				var resolved = (aURISpec.charAt(0) == '.' ? rootURI : baseURI ).resolve(aURISpec);
				if (resolved == aURISpec)
					throw new Error('Recursive load!');
				var exported = {};
				load(resolved, exported, exported, rootURI);
				return exported;
			},
			/* utility to resolve relative path from the file */
			resolve : function(aURISpec, aBaseURI) {
				var base = !aBaseURI ?
								baseURI :
							aBaseURI.indexOf('file:') == 0 ?
								IOService.newFileURI(FileHandler.getFileFromURLSpec(aURISpec)) :
								IOService.newURI(aURISpec, null, null) ;
				return base.resolve(aURISpec);
			},
			/* utility to read contents of a text file */
			read : function(aURISpec, aEncoding, aBaseURI) {
				return _readFrom(this.resolve(aURISpec, aBaseURI), aEncoding);
			},
			doAndWait : function(aAsyncTask) {
				return doAndWait(aAsyncTask);
			},
			exports : {}
		};
	return ns;
}

function _createFakeLocation(aURI)
{
	aURI = aURI.QueryInterface(Components.interfaces.nsIURL)
					.QueryInterface(Components.interfaces.nsIURI);
	return {
		href     : aURI.spec,
		search   : aURI.query ? '?'+aURI.query : '' ,
		hash     : aURI.ref ? '#'+aURI.ref : '' ,
		host     : aURI.scheme == 'jar' ? '' : aURI.hostPort,
		hostname : aURI.scheme == 'jar' ? '' : aURI.host,
		port     : aURI.scheme == 'jar' ? -1 : aURI.port,
		pathname : aURI.path,
		protocol : aURI.scheme+':',
		reload   : function() {},
		replace  : function() {},
		toString : function() {
			return this.href;
		}
	};
}

function _callHandler(aHandler, aReason)
{
	for (var i in _namespaces)
	{
		try {
			if (_namespaces[i][aHandler] &&
				typeof _namespaces[i][aHandler] == 'function')
				_namespaces[i][aHandler](aReason);
		}
		catch(e) {
			let message = i+'('+aHandler+', '+aReason+')\n'+e+'\n';
			dump(message);
			Components.utils.reportError(message + e.stack);
		}
	}
}

function registerResource(aName, aRoot)
{
	IOService.getProtocolHandler('resource')
		.QueryInterface(Components.interfaces.nsIResProtocolHandler)
		.setSubstitution(aName, aRoot);
}

function unregisterResource(aName)
{
	IOService.getProtocolHandler('resource')
		.QueryInterface(Components.interfaces.nsIResProtocolHandler)
		.setSubstitution(aName, null);
}

/** Handler for "install" of the bootstrap.js */
function install(aReason)
{
	_callHandler('install', aReason);
}

/** Handler for "uninstall" of the bootstrap.js */
function uninstall(aReason)
{
	_callHandler('uninstall', aReason);
}

/** Handler for "shutdown" of the bootstrap.js */
function shutdown(aReason)
{
	_callHandler('shutdown', aReason);

	for each (let ns in _namespaces)
	{
		for (let i in ns.exports)
		{
			if (ns.exports.hasOwnProperty(i))
				delete ns.exports[i];
		}
	}
	_namespaces = void(0);
	_namespacePrototype = void(0);
	Application = void(0);

	IOService = void(0);
	FileHandler = void(0);

	load = void(0);
	_exportSymbols = void(0);
	exists = void(0);
	_createNamespace = void(0);
	_callHandler = void(0);
	registerResource = void(0);
	unregisterResource = void(0);
	install = void(0);
	uninstall = void(0);
	shutdown = void(0);
}
<commit_msg>Bind "Application.console" instead of "console"<commit_after>/**
 * @fileOverview Loader module for restartless addons
 * @author       YUKI "Piro" Hiroshi
 * @version      9
 *
 * @license
 *   The MIT License, Copyright (c) 2010-2014 YUKI "Piro" Hiroshi.
 *   https://github.com/piroor/restartless/blob/master/license.txt
 * @url http://github.com/piroor/restartless
 */

/** You can customize shared properties for loaded scripts. */
var Application = (function() {
	if ('@mozilla.org/fuel/application;1' in Components.classes)
		return Components.classes['@mozilla.org/fuel/application;1']
				.getService(Components.interfaces.fuelIApplication);
	if ('@mozilla.org/steel/application;1' in Components.classes)
		return Components.classes['@mozilla.org/steel/application;1']
				.getService(Components.interfaces.steelIApplication);
	return null;
})();
// import base64 utilities from the js code module namespace
var { atob, btoa, console } = Components.utils.import('resource://gre/modules/Services.jsm', {});
var _namespacePrototype = {
		Cc : Components.classes,
		Ci : Components.interfaces,
		Cu : Components.utils,
		Cr : Components.results,
		Application : Application,
		console : console || Application.console,
		btoa    : function(aInput) {
			return btoa(aInput);
		},
		atob    : function(aInput) {
			return atob(aInput);
		}
	};
var _namespaces;

/**
 * This functiom loads specified script into a unique namespace for the URL.
 * Namespaces for loaded scripts have a wrapped version of this function.
 * Both this and wrapped work like as Components.utils.import().
 * Due to the reserved symbol "import", we have to use another name "load"
 * instead it.
 *
 * @param {String} aScriptURL
 *   URL of a script. Wrapped version of load() can handle related path.

 *   Related path will be resolved based on the location of the caller script.
 * @param {Object=} aExportTargetForImport
 *   EXPORTED_SYMBOLS in the loaded script will be exported to the object.
 *   If no object is specified, symbols will be exported to the global object
 *   of the caller.
 * @param {Object=} aExportTargetForRequire
 *   Properties of "exports" in the loaded script will be exported to the object.
 *
 * @returns {Object}
 *   The global object for the loaded script.
 */
function load(aURISpec, aExportTargetForImport, aExportTargetForRequire, aRoot)
{
	if (!_namespaces)
		_namespaces = {};
	var ns;
	if (aURISpec in _namespaces) {
		ns = _namespaces[aURISpec];
		_exportForImport(ns, aExportTargetForImport);
		_exportForRequire(ns, aExportTargetForRequire);
		return ns;
	}
	ns = _createNamespace(aURISpec, aRoot || aURISpec);
	try {
		Components.classes['@mozilla.org/moz/jssubscript-loader;1']
			.getService(Components.interfaces.mozIJSSubScriptLoader)
			.loadSubScript(aURISpec, ns);
	}
	catch(e) {
		let message = 'Loader::load('+aURISpec+') failed!\n'+e+'\n';
		dump(message);
		Components.utils.reportError(message + e.stack);
		throw e;
	}
	_exportForImport(ns, aExportTargetForImport);
	_exportForRequire(ns, aExportTargetForRequire);
	return _namespaces[aURISpec] = ns;
}

// JavaScript code module style
function _exportForImport(aSource, aTarget)
{
	if (
		!aTarget ||
		!('EXPORTED_SYMBOLS' in aSource) ||
		!aSource.EXPORTED_SYMBOLS ||
		!aSource.EXPORTED_SYMBOLS.forEach
		)
		return;
	for each (var symbol in aSource.EXPORTED_SYMBOLS)
	{
		aTarget[symbol] = aSource[symbol];
	}
}

// CommonJS style
function _exportForRequire(aSource, aTarget)
{
	if (
		!aTarget ||
		!('exports' in aSource) ||
		!aSource.exports ||
		typeof aSource.exports != 'object'
		)
		return;
	for (var symbol in aSource.exports)
	{
		aTarget[symbol] = aSource.exports[symbol];
	}
}

var IOService = Components.classes['@mozilla.org/network/io-service;1']
					.getService(Components.interfaces.nsIIOService);
var FileHandler = IOService.getProtocolHandler('file')
					.QueryInterface(Components.interfaces.nsIFileProtocolHandler);

/**
 * Checks existence of the file specified by the given relative path and the base URI.
 *
 * @param {String} aPath
 *   A relative path to a file or directory, from the aBaseURI.
 * @param {String} aBaseURI
 *   An absolute URI (with scheme) for relative paths.
 *
 * @returns {String}
 *   If the file (or directory) exists, returns the absolute URI. Otherwise null.
 */
function exists(aPath, aBaseURI)
{
	if (/^\w+:/.test(aPath)) {
		let leafName = aPath.match(/([^\/]+)$/);
		leafName = leafName ? leafName[1] : '' ;
		aBaseURI = aPath.replace(/(?:[^\/]+)$/, '');
		aPath = leafName;
	}
	var baseURI = aBaseURI.indexOf('file:') == 0 ?
					IOService.newFileURI(FileHandler.getFileFromURLSpec(aBaseURI)) :
					IOService.newURI(aBaseURI, null, null);
	if (aBaseURI.indexOf('jar:') == 0) {
		baseURI = baseURI.QueryInterface(Components.interfaces.nsIJARURI);
		var reader = Components.classes['@mozilla.org/libjar/zip-reader;1']
						.createInstance(Components.interfaces.nsIZipReader);
		reader.open(baseURI.JARFile.QueryInterface(Components.interfaces.nsIFileURL).file);
	    try {
			let baseEntry = baseURI.JAREntry.replace(/[^\/]+$/, '');
			let entries = reader.findEntries(baseEntry + aPath + '$');
			let found = entries.hasMore();
			return found ? baseURI.resolve(aPath) : null ;
		}
		finally {
			reader.close();
		}
	}
	else {
		let resolved = baseURI.resolve(aPath);
		return FileHandler.getFileFromURLSpec(resolved).exists() ? resolved : null ;
	}
}

function doAndWait(aAsyncTask)
{
	const Cc = Components.classes;
	const Ci = Components.interfaces;

	var done = false;
	var returnedValue = void(0);
	var continuation = function(aReturnedValue) {
			done = true;
			returnedValue = aReturnedValue;
		};

	var timer = Cc['@mozilla.org/timer;1']
					.createInstance(Ci.nsITimer);
	timer.init(function() {
		aAsyncTask(continuation);
	}, 0, Ci.nsITimer.TYPE_ONE_SHOT);

	var thread = Cc['@mozilla.org/thread-manager;1']
					.getService(Ci.nsIThreadManager)
					.currentThread;
	while (!done) {
		thread.processNextEvent(true);
	}
	return returnedValue;
}

function _readFrom(aURISpec, aEncoding)
{
	const Cc = Components.classes;
	const Ci = Components.interfaces;

	var uri = aURISpec.indexOf('file:') == 0 ?
			IOService.newFileURI(FileHandler.getFileFromURLSpec(aURISpec)) :
			IOService.newURI(aURISpec, null, null) ;
	var channel = IOService.newChannelFromURI(uri.QueryInterface(Ci.nsIURI));
	var stream = channel.open();

	var fileContents = null;
	try {
		if (aEncoding) {
			var converterStream = Cc['@mozilla.org/intl/converter-input-stream;1']
					.createInstance(Ci.nsIConverterInputStream);
			var buffer = stream.available();
			converterStream.init(stream, aEncoding, buffer,
				converterStream.DEFAULT_REPLACEMENT_CHARACTER);
			var out = { value : null };
			converterStream.readString(stream.available(), out);
			converterStream.close();
			fileContents = out.value;
		}
		else {
			var scriptableStream = Cc['@mozilla.org/scriptableinputstream;1']
					.createInstance(Ci.nsIScriptableInputStream);
			scriptableStream.init(stream);
			fileContents = scriptableStream.read(scriptableStream.available());
			scriptableStream.close();
		}
	}
	finally {
		stream.close();
	}
	return fileContents;
}

function _createNamespace(aURISpec, aRoot)
{
	var baseURI = aURISpec.indexOf('file:') == 0 ?
					IOService.newFileURI(FileHandler.getFileFromURLSpec(aURISpec)) :
					IOService.newURI(aURISpec, null, null);
	var rootURI = typeof aRoot == 'string' ?
					(aRoot.indexOf('file:') == 0 ?
						IOService.newFileURI(FileHandler.getFileFromURLSpec(aRoot)) :
						IOService.newURI(aRoot, null, null)
					) :
					aRoot ;
	var ns = {
			__proto__ : _namespacePrototype,
			location : _createFakeLocation(baseURI),
			exists : function(aPath, aBase) {
				return exists(aPath, aBase || baseURI.spec);
			},
			exist : function(aPath, aBase) { // alias
				return exists(aPath, aBase || baseURI.spec);
			},
			/** JavaScript code module style */
			load : function(aURISpec, aExportTarget) {
				if (!/\.jsm?$/.test(aURISpec)) {
					if (exists(aURISpec+'.js', baseURI.spec))
						aURISpec += '.js'
					else if (exists(aURISpec+'.jsm', baseURI.spec))
						aURISpec += '.jsm'
				}
				var resolved = baseURI.resolve(aURISpec);
				if (resolved == aURISpec)
					throw new Error('Recursive load!');
				return load(resolved, aExportTarget || ns, aExportTarget, rootURI);
			},
			'import' : function() { // alias
				return this.load.apply(this, arguments);
			},
			/**
			 * CommonJS style
			 * @url http://www.commonjs.org/specs/
			 */
			require : function(aURISpec) {
				if (!/\.jsm?$/.test(aURISpec)) {
					if (exists(aURISpec+'.js', baseURI.spec))
						aURISpec += '.js'
					else if (exists(aURISpec+'.jsm', baseURI.spec))
						aURISpec += '.jsm'
				}
				var resolved = (aURISpec.charAt(0) == '.' ? rootURI : baseURI ).resolve(aURISpec);
				if (resolved == aURISpec)
					throw new Error('Recursive load!');
				var exported = {};
				load(resolved, exported, exported, rootURI);
				return exported;
			},
			/* utility to resolve relative path from the file */
			resolve : function(aURISpec, aBaseURI) {
				var base = !aBaseURI ?
								baseURI :
							aBaseURI.indexOf('file:') == 0 ?
								IOService.newFileURI(FileHandler.getFileFromURLSpec(aURISpec)) :
								IOService.newURI(aURISpec, null, null) ;
				return base.resolve(aURISpec);
			},
			/* utility to read contents of a text file */
			read : function(aURISpec, aEncoding, aBaseURI) {
				return _readFrom(this.resolve(aURISpec, aBaseURI), aEncoding);
			},
			doAndWait : function(aAsyncTask) {
				return doAndWait(aAsyncTask);
			},
			exports : {}
		};
	return ns;
}

function _createFakeLocation(aURI)
{
	aURI = aURI.QueryInterface(Components.interfaces.nsIURL)
					.QueryInterface(Components.interfaces.nsIURI);
	return {
		href     : aURI.spec,
		search   : aURI.query ? '?'+aURI.query : '' ,
		hash     : aURI.ref ? '#'+aURI.ref : '' ,
		host     : aURI.scheme == 'jar' ? '' : aURI.hostPort,
		hostname : aURI.scheme == 'jar' ? '' : aURI.host,
		port     : aURI.scheme == 'jar' ? -1 : aURI.port,
		pathname : aURI.path,
		protocol : aURI.scheme+':',
		reload   : function() {},
		replace  : function() {},
		toString : function() {
			return this.href;
		}
	};
}

function _callHandler(aHandler, aReason)
{
	for (var i in _namespaces)
	{
		try {
			if (_namespaces[i][aHandler] &&
				typeof _namespaces[i][aHandler] == 'function')
				_namespaces[i][aHandler](aReason);
		}
		catch(e) {
			let message = i+'('+aHandler+', '+aReason+')\n'+e+'\n';
			dump(message);
			Components.utils.reportError(message + e.stack);
		}
	}
}

function registerResource(aName, aRoot)
{
	IOService.getProtocolHandler('resource')
		.QueryInterface(Components.interfaces.nsIResProtocolHandler)
		.setSubstitution(aName, aRoot);
}

function unregisterResource(aName)
{
	IOService.getProtocolHandler('resource')
		.QueryInterface(Components.interfaces.nsIResProtocolHandler)
		.setSubstitution(aName, null);
}

/** Handler for "install" of the bootstrap.js */
function install(aReason)
{
	_callHandler('install', aReason);
}

/** Handler for "uninstall" of the bootstrap.js */
function uninstall(aReason)
{
	_callHandler('uninstall', aReason);
}

/** Handler for "shutdown" of the bootstrap.js */
function shutdown(aReason)
{
	_callHandler('shutdown', aReason);

	for each (let ns in _namespaces)
	{
		for (let i in ns.exports)
		{
			if (ns.exports.hasOwnProperty(i))
				delete ns.exports[i];
		}
	}
	_namespaces = void(0);
	_namespacePrototype = void(0);
	Application = void(0);

	IOService = void(0);
	FileHandler = void(0);

	load = void(0);
	_exportSymbols = void(0);
	exists = void(0);
	_createNamespace = void(0);
	_callHandler = void(0);
	registerResource = void(0);
	unregisterResource = void(0);
	install = void(0);
	uninstall = void(0);
	shutdown = void(0);
}
<|endoftext|>


<commit_before>const format = require('date-fns/format');
const addDays = require('date-fns/add_days');
const isFriday = require('date-fns/is_friday');
const pdf2text = require('../lib/pdf-parser.js');
const download = require('download-file');

const DateFns = require('date-fns');

function downloadFile(url, options) {
  return new Promise((resolve, reject) => {
    download(url, options, function (err) {
      if (err) reject(err);

      resolve();
    })
  })
}

module.exports.getMenu = async function getMenu() {
  today = new Date();

  const url = 'http://www.denns-biomarkt.at/file/23308_Mittagsmen%C3%BC%20Wien%20Singerstr.pdf';

  const options = {
    directory: "./tmp/",
    filename: "denns.pdf"
  };

  try {
    await downloadFile(url, options);
    let text = await pdf2text.pdf2txt(options.directory + options.filename);

    const todayString = getDayFormatted(today);
    let tomorrowString = getDayFormatted(addDays(today, 1));

    text = text.substring(text.indexOf(todayString), text.lastIndexOf(tomorrowString));
    text = camelCaseToWords(text);
    text = text + '\n' + url;
    return text;
  } catch (err) {
    throw err;
  }
};

function camelCaseToWords(str){
  return str.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1").replace(/-  /g, "-").replace(/  /g, ' ');
}

function getDayFormatted(date) {
  if (DateFns.isMonday(date)) return "Mo";
  if (DateFns.isTuesday(date)) return "Di";
  if (DateFns.isWednesday(date)) return "Mi";
  if (DateFns.isThursday(date)) return "Do";
  if (DateFns.isFriday(date)) return "Fr";
  if (DateFns.isSaturday(date)) return "Sa";
  if (DateFns.isSunday(date)) return "GutenAppetitwünschtIhnenIhrdenn";
}<commit_msg>Bit of refactoring<commit_after>const pdf2text = require('../lib/pdf-parser.js');
const download = require('download-file');

const DateFns = require('date-fns');

function downloadFile(url, options) {
  return new Promise((resolve, reject) => {
    download(url, options, function (err) {
      if (err) reject(err);

      resolve();
    })
  })
}

module.exports.getMenu = async function getMenu(date = new Date()) {

  const url = 'http://www.denns-biomarkt.at/file/23308_Mittagsmen%C3%BC%20Wien%20Singerstr.pdf';

  const options = {
    directory: "./tmp/",
    filename: "denns.pdf"
  };

  const todayString = getDayFormatted(date);
  const tomorrowString = getDayFormatted(DateFns.addDays(date, 1));

  try {
    await downloadFile(url, options);

    let text = await pdf2text.pdf2txt(options.directory + options.filename);

    return camelCaseToWords(text.substring(text.indexOf(todayString), text.lastIndexOf(tomorrowString))).concat('\n',url);

  } catch (err) {
    throw err;
  }
};

function camelCaseToWords(str){
  return str.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1").replace(/-  /g, "-").replace(/  /g, ' ');
}

function getDayFormatted(date) {
  if (DateFns.isMonday(date)) return "Mo";
  if (DateFns.isTuesday(date)) return "Di";
  if (DateFns.isWednesday(date)) return "Mi";
  if (DateFns.isThursday(date)) return "Do";
  if (DateFns.isFriday(date)) return "Fr";
  if (DateFns.isSaturday(date)) return "Sa";
  if (DateFns.isSunday(date)) return "GutenAppetitwünschtIhnenIhrdenn";
}<|endoftext|>


<commit_before><commit_msg>2017:10:28:18:26:29<commit_after><|endoftext|>


<commit_before>var styles = {
    log: "#2a53cd",
    info: "#228B22",
    warn: "#dd6a16",
    error: "#dc352e"
};
var alerts = [];
var clean = Cleanup(alerts);
var build = function () {
    var sum = 0;
    alerts.forEach(function (elem) {
        if (parseInt(elem.style.top) !== sum);
        elem.style.top = sum + "px";
        sum += elem.offsetHeight;
    });
};
var fontSize = 16;
var singleHeight = fontSize * 3.125 | 0;
var _text = function (color, parameters) {
    var box = div();
    css(box, `top:${fromPixel(singleHeight * alerts.length)};height:0;line-height:${fromPixel(singleHeight)};left:0;right:0;font-size:${fromPixel(fontSize)}; transition: all 0.2s ease-out;position:absolute;color:#fff;text-align:center;`);
    box.innerHTML = `<div style='width: 720px;max-width:100%;display:inline-block;height:${fromPixel(singleHeight)};background-color:${color};'>${[].slice.call(parameters, 0).join(", ")}</div>`;
    box.initialStyle = `margin:-${fromPixel(singleHeight)} auto;opacity:0;`;
    return box;
};
function alert() {
    var color = String(this), text, autoclose = true, onclose;
    var color_reg = /^#(?:\w{6}|\w{3})$/;
    [].map.call(arguments, function (arg) {
        switch (typeof arg) {
            case "string":
                if (!text) {
                    text = arg;
                } else if (color_reg.test(text)) {
                    color = text;
                    text = arg;
                } else if (text in styles) {
                    color = styles[text];
                    text = arg;
                } else if (arg in styles) {
                    color = styles[arg];
                } else if (color_reg.test(arg)) {
                    color = arg;
                }
                break;
            case "boolean":
            case "number":
                autoclose = arg;
                break;
            case "function":
                onclose = arg;
        }
    });
    var elem;

    if (color_reg.test(color)) {
        elem = _text(color, [text]);
    } else {
        elem = _text(styles.log, [text]);
    }
    var _onclose = function (event) {
        if (onclose) {
            onclose.call(this, event);
        }
        clean(this);
        build();
        if (close_timer) clearTimeout(close_timer);
    }
    onremove(elem, _onclose);
    if (autoclose) {
        if (autoclose === true) {
            autoclose = text.length * 200 + 400;
        } else if (autoclose < 100) {
            autoclose = autoclose * 1000;
        }
        var close_timer = setTimeout(function () {
            remove(elem);
        }, autoclose);
    }
    alerts.push(elem);
    popup(elem);
    return elem;
}
for (var k in styles) {
    alert[k] = new Function(`return this.apply(${JSON.stringify(styles[k])},arguments);`);
}
<commit_msg>解决移除元素时alert弹出位置可能不正确的问题<commit_after>var styles = {
    log: "#2a53cd",
    info: "#228B22",
    warn: "#dd6a16",
    error: "#dc352e"
};
var alerts = [];
var clean = Cleanup(alerts);
var build = function () {
    var sum = 0;
    alerts.forEach(function (elem) {
        if (elem.offsetTop !== sum) {
            elem.style.top = fromOffset(sum);
        };
        sum += elem.offsetHeight;
    });
};
var fontSize = 16;
var singleHeight = fontSize * 3.125 | 0;
var _text = function (color, parameters) {
    var box = div();
    css(box, `top:${fromPixel(alerts.length ? Math.max.apply(Math, alerts.map(e => e.offsetTop + e.children[0].offsetHeight)) : 0)};height:0;line-height:${fromPixel(singleHeight)};left:0;right:0;font-size:${fromPixel(fontSize)}; transition: all 0.2s ease-out;position:absolute;color:#fff;text-align:center;`);
    box.innerHTML = `<div style='width: 720px;max-width:100%;display:inline-block;height:${fromPixel(singleHeight)};background-color:${color};'>${[].slice.call(parameters, 0).join(", ")}</div>`;
    box.initialStyle = `margin:-${fromPixel(singleHeight)} auto;opacity:0;`;
    return box;
};
function alert() {
    var color = String(this), text, autoclose = true, onclose;
    var color_reg = /^#(?:\w{6}|\w{3})$/;
    [].map.call(arguments, function (arg) {
        switch (typeof arg) {
            case "string":
                if (!text) {
                    text = arg;
                } else if (color_reg.test(text)) {
                    color = text;
                    text = arg;
                } else if (text in styles) {
                    color = styles[text];
                    text = arg;
                } else if (arg in styles) {
                    color = styles[arg];
                } else if (color_reg.test(arg)) {
                    color = arg;
                }
                break;
            case "boolean":
            case "number":
                autoclose = arg;
                break;
            case "function":
                onclose = arg;
        }
    });
    var elem;

    if (color_reg.test(color)) {
        elem = _text(color, [text]);
    } else {
        elem = _text(styles.log, [text]);
    }
    var _onclose = function (event) {
        if (onclose) {
            onclose.call(this, event);
        }
        clean(this);
        build();
        if (close_timer) clearTimeout(close_timer);
    }
    onremove(elem, _onclose);
    if (autoclose) {
        if (autoclose === true) {
            autoclose = text.length * 200 + 400;
        } else if (autoclose < 100) {
            autoclose = autoclose * 1000;
        }
        var close_timer = setTimeout(function () {
            remove(elem);
        }, autoclose);
    }
    alerts.push(elem);
    popup(elem);
    return elem;
}
for (var k in styles) {
    alert[k] = new Function(`return this.apply(${JSON.stringify(styles[k])},arguments);`);
}
<|endoftext|>


<commit_before>import './setTimeout'
import './promise'
import './console'

/**
 * Mix properties into target object.
 *
 * @param {Object} to
 * @param {Object} from
 */

export function extend (target, ...src) {
  if (typeof Object.assign === 'function') {
    Object.assign(target, ...src)
  }
  else {
    const first = src.shift()
    for (const key in first) {
      target[key] = first[key]
    }
    if (src.length) {
      extend(target, ...src)
    }
  }
  return target
}

/**
 * Define a property.
 *
 * @param {Object} obj
 * @param {String} key
 * @param {*} val
 * @param {Boolean} [enumerable]
 */

export function def (obj, key, val, enumerable) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true
  })
}

/**
 * Remove an item from an array
 *
 * @param {Array} arr
 * @param {*} item
 */

export function remove (arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

/**
 * Check whether the object has the property.
 *
 * @param {Object} obj
 * @param {String} key
 * @return {Boolean}
 */
const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn (obj, key) {
  return hasOwnProperty.call(obj, key)
}

/**
 * Simple bind, faster than native
 *
 * @param {Function} fn
 * @param {Object} ctx
 * @return {Function}
 */

export function bind (fn, ctx) {
  return function (a) {
    const l = arguments.length
    return l
      ? l > 1
        ? fn.apply(ctx, arguments)
        : fn.call(ctx, a)
      : fn.call(ctx)
  }
}

/**
 * Convert an Array-like object to a real Array.
 *
 * @param {Array-like} list
 * @param {Number} [start] - start index
 * @return {Array}
 */

export function toArray (list, start) {
  start = start || 0
  let i = list.length - start
  const ret = new Array(i)
  while (i--) {
    ret[i] = list[i + start]
  }
  return ret
}

/**
 * Quick object check - this is primarily used to tell
 * Objects from primitive values when we know the value
 * is a JSON-compliant type.
 *
 * @param {*} obj
 * @return {Boolean}
 */

export function isObject (obj) {
  return obj !== null && typeof obj === 'object'
}

/**
 * Strict object type check. Only returns true
 * for plain JavaScript objects.
 *
 * @param {*} obj
 * @return {Boolean}
 */

const toString = Object.prototype.toString
const OBJECT_STRING = '[object Object]'
export function isPlainObject (obj) {
  return toString.call(obj) === OBJECT_STRING
}

<commit_msg>* [jsfm] bring Object.assign polyfill back<commit_after>import './setTimeout'
import './promise'
import './console'
import './objectAssign'

/**
 * Mix properties into target object.
 *
 * @param {Object} to
 * @param {Object} from
 */

export function extend (target, ...src) {
  if (typeof Object.assign === 'function') {
    Object.assign(target, ...src)
  }
  else {
    const first = src.shift()
    for (const key in first) {
      target[key] = first[key]
    }
    if (src.length) {
      extend(target, ...src)
    }
  }
  return target
}

/**
 * Define a property.
 *
 * @param {Object} obj
 * @param {String} key
 * @param {*} val
 * @param {Boolean} [enumerable]
 */

export function def (obj, key, val, enumerable) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true
  })
}

/**
 * Remove an item from an array
 *
 * @param {Array} arr
 * @param {*} item
 */

export function remove (arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

/**
 * Check whether the object has the property.
 *
 * @param {Object} obj
 * @param {String} key
 * @return {Boolean}
 */
const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn (obj, key) {
  return hasOwnProperty.call(obj, key)
}

/**
 * Simple bind, faster than native
 *
 * @param {Function} fn
 * @param {Object} ctx
 * @return {Function}
 */

export function bind (fn, ctx) {
  return function (a) {
    const l = arguments.length
    return l
      ? l > 1
        ? fn.apply(ctx, arguments)
        : fn.call(ctx, a)
      : fn.call(ctx)
  }
}

/**
 * Convert an Array-like object to a real Array.
 *
 * @param {Array-like} list
 * @param {Number} [start] - start index
 * @return {Array}
 */

export function toArray (list, start) {
  start = start || 0
  let i = list.length - start
  const ret = new Array(i)
  while (i--) {
    ret[i] = list[i + start]
  }
  return ret
}

/**
 * Quick object check - this is primarily used to tell
 * Objects from primitive values when we know the value
 * is a JSON-compliant type.
 *
 * @param {*} obj
 * @return {Boolean}
 */

export function isObject (obj) {
  return obj !== null && typeof obj === 'object'
}

/**
 * Strict object type check. Only returns true
 * for plain JavaScript objects.
 *
 * @param {*} obj
 * @return {Boolean}
 */

const toString = Object.prototype.toString
const OBJECT_STRING = '[object Object]'
export function isPlainObject (obj) {
  return toString.call(obj) === OBJECT_STRING
}

<|endoftext|>