<commit_before>/**
 * @file Character class. Part of the MurmuresJS project.
 * @author github.com/azziliz
 * @author github.com/thyshimrod
 * {@link https://github.com/azziliz/MurmuresJS/ Project page}
 * @license MIT
 */

'use strict';
//debugger;

/**
 * Characters are entities that live, move and act inside a [level]{@link murmures.Level}.
 *
 * Heroes are characters managed by the players.
 * They can be given [orders]{@link murmures.Order} on client side.
 * They can move from one level to another.
 * Mobs are characters managed by the AI.
 * The AI methods to control them are defined in the [game engine]{@link murmures.GameEngine} class.
 * They cannot change level.
 *
 * Three steps are mandatory to create a valid character:
 * 1. Load all character templates from mobs.json.
 * 2. Select templates that are needed for the current level.
 * 2. Use the "instantiate" method in the Character class to create new instances.
 * Step 1 is performed by the game engine during the server startup.
 * Step 2 and 3 are performed together by the server and the game engine when a level is loaded.
 *
 * @class
 */
murmures.Character = function () {
    /** @type {string} */
    this.guid = '';
    /** @type {murmures.Tile} */
    this.position = null;
    /** @type {string} */
    this.mobTemplate = '';
    /** @type {number} */
    this.hitPointsMax = 0;
    /** @type {Object.<string, boolean>} */
    this.onVisionCharacters = {};
    /** @type {number} */
    this.hitPoints = 0;
    /** @type {number} */
    this.range = 0;
    /** @type {number} */
    this.defaultDamageValue = 0;
    /** @type {boolean} */
    this.canMove = false; // unused for now
    /** @type {boolean} */
    this.charSpotted = false; // hero is known because seen at least once
    /** @type {number} */
    this.stateOrder = murmures.C.STATE_HERO_WAITING_FOR_ORDER;
    /** @type {Object.<integer, murmures.Skill>} */
    this.skills = {};
    /** @type {number} */
    this.activeSkill = 0;
    /** @type {number} */
    this.dexterity = 0;
    /** @type {number} */
    this.intelligence = 0;
    /** @type {number} */
    this.strength = 0;
    /** @type {number} */
    this.initiative = 0;
};

murmures.Character.prototype = {

    /**
     * It is expected that, when the server calls this function,
     * the Tile object in parameter is already built.
     */
    build : function (tile, template) {
        this.guid = Math.random().toString();
        this.position = tile;
        this.mobTemplate = template;
        let ref = gameEngine.bodies[template];
        this.hitPointsMax = (ref.hitPointsMax || (this.isHero ? 20 : 10)) | 0; // by default, heroes start with 20 HP. Other mobs with 10. This can be changed in assets.json.
        this.hitPoints = this.hitPointsMax | 0;
        this.range = (ref.range || (this.isHero ? 3 : 2)) | 0; // by default, heroes start with a 3 tile range. Other mobs with 2. This can be changed in assets.json.
        this.defaultDamageValue = (ref.defaultDamageValue || (this.isHero ? 3 : 1)) | 0; // by default, heroes deal 3 damage per attack. Other mobs deal 1. This can be changed in assets.json.
        this.canMove = ref.canMove || false;
        this.charSpotted = ref.charSpotted || false;
        this.stateOrder = murmures.C.STATE_HERO_WAITING_FOR_ORDER;
        this.intelligence = Math.floor(Math.random() * 10);
        this.dexterity = Math.floor(Math.random() * 10);
        this.strength = Math.floor(Math.random() * 10);
        this.initiative = this.dexterity;
    },

    initialize : function (src) {
        this.guid = src.guid;
        this.synchronize(src);
    },

    synchronize : function (src) {
        if (typeof src === 'undefined') return;
        if (typeof src.position !== 'undefined') this.move(src.position.x, src.position.y); // TODO position=null when mob becomes invisible?
        if (typeof src.mobTemplate !== 'undefined') this.mobTemplate = src.mobTemplate;
        if (typeof src.hitPointsMax !== 'undefined') this.hitPointsMax = src.hitPointsMax;
        if (typeof src.hitPoints !== 'undefined') this.hitPoints = src.hitPoints;
        if (typeof src.range !== 'undefined') this.range = src.range;
        if (typeof src.defaultDamageValue !== 'undefined') this.defaultDamageValue = src.defaultDamageValue;
        if (typeof src.canMove !== 'undefined') this.canMove = src.canMove;
        if (typeof src.charSpotted !== 'undefined') this.charSpotted = src.charSpotted;
        if (typeof src.stateOrder !== 'undefined') this.stateOrder = src.stateOrder;
        if (typeof src.onVisionCharacters !== 'undefined') this.onVisionCharacters = src.onVisionCharacters;
        if (typeof src.skills !== 'undefined') this.skills = src.skills;
        if (typeof src.activeSkill !== 'undefined') this.activeSkill = src.activeSkill;
        if (typeof src.dexterity !== 'undefined') this.dexterity = src.dexterity;
        if (typeof src.intelligence !== 'undefined') this.intelligence = src.intelligence;
        if (typeof src.strength !== 'undefined') this.strength = src.strength;
        if (typeof src.initiative !== 'undefined') this.initiative = src.initiative;
    },

    clone : function () {
        let beforeOnVisionCharacters = {};
        for (let itVision in this.onVisionCharacters) {
            beforeOnVisionCharacters[itVision] = this.onVisionCharacters[itVision];
        }
        return {
            guid: this.guid,
            position: this.position.coordinates,
            mobTemplate: this.mobTemplate,
            hitPointsMax: this.hitPointsMax,
            hitPoints: this.hitPoints,
            range: this.range,
            defaultDamageValue: this.defaultDamageValue,
            canMove: this.canMove,
            charSpotted: this.charSpotted,
            stateOrder : this.stateOrder,
            onVisionCharacters : beforeOnVisionCharacters,
            dexterity : this.dexterity,
            intelligence : this.intelligence,
            strength : this.strength,
            initiative : this.initiative
        };
    },

    compare : function (beforeState) {
        let ret = {};
        if (this.guid !== beforeState.guid) throw 'Character changed guid. This souldn\'t be happening';
        if (this.position.x !== beforeState.position.x || this.position.y !== beforeState.position.y) ret.position = this.position.coordinates;
        if (this.mobTemplate !== beforeState.mobTemplate) ret.mobTemplate = this.mobTemplate;
        if (this.hitPointsMax !== beforeState.hitPointsMax) ret.hitPointsMax = this.hitPointsMax;
        if (this.hitPoints !== beforeState.hitPoints) ret.hitPoints = this.hitPoints;
        if (this.dexterity !== beforeState.dexterity) ret.dexterity = this.dexterity;
        if (this.intelligence !== beforeState.intelligence) ret.intelligence = this.intelligence;
        if (this.strength !== beforeState.strength) ret.strength = this.strength;
        if (this.initiative !== beforeState.initiative) ret.initiative = this.initiative;
        if (this.range !== beforeState.range) ret.range = this.range;
        if (this.defaultDamageValue !== beforeState.defaultDamageValue) ret.defaultDamageValue = this.defaultDamageValue;
        if (this.canMove !== beforeState.canMove) ret.canMove = this.canMove;
        if (this.stateOrder !== beforeState.stateOrder) ret.stateOrder = this.stateOrder;
        if (this.charSpotted !== beforeState.charSpotted) {
            // client discovers the mob for the first time --> send everything
            ret.position = this.position.coordinates;
            ret.mobTemplate = this.mobTemplate;
            ret.hitPointsMax = this.hitPointsMax;
            ret.hitPoints = this.hitPoints;
            ret.range = this.range;
            ret.defaultDamageValue = this.defaultDamageValue;
            ret.canMove = this.canMove;
            ret.charSpotted = this.charSpotted;
        }
        for (let itMap in this.onVisionCharacters) {
            if (this.onVisionCharacters[itMap] !== beforeState.onVisionCharacters[itMap]) {
                ret.onVisionCharacters = this.onVisionCharacters;
                break;
            }
        }
        if (Object.getOwnPropertyNames(ret).length > 0) {
            // only returns ret if not empty
            ret.guid = this.guid;
            return ret;
        }
        // otherwise, no return = undefined
    },

    move : function (x, y) {
        this.position = gameEngine.level.tiles[y][x];
    },

    get isHero() {
        let ref = gameEngine.bodies[this.mobTemplate];
        return murmures.C.LAYERS[ref.layerId][0] === 'Hero';
    },

    setVision : function (tilesProcessed) {
        murmures.serverLog("hero position");
        let level = gameEngine.level;
        if (typeof tilesProcessed === 'undefined' || tilesProcessed === null) { tilesProcessed = []; }
        for (let xx=0; xx < level.width && this.isHero === true; xx++) {
            for (let yy=0; yy < level.height; yy++) {
                let toProceed = (tilesProcessed.indexOf(level.tiles[yy][xx]) < 0);
                if (toProceed) {
                    if (level.tiles[yy][xx].state === murmures.C.TILE_HIGHLIGHTED) {
                        level.tiles[yy][xx].state = murmures.C.TILE_FOG_OF_WAR;
                    }
                }
            }
        }

        for (let i=0; i < 360; i++) {
            let x = Math.cos(i * 0.01745);
            let y = Math.sin(i * 0.01745);
            let ox = this.position.x + 0.5;
            let oy = this.position.y + 0.5;
            let j=0;
            let breakObstacle = false;
            while ((j < murmures.C.DEFAULT_RANGE_FOV) && (breakObstacle === false)) {
                let oxx = 0;
                oxx = Math.floor(ox);
                let oyy = 0;
                oyy = Math.floor(oy);
                if ((oxx >= 0) && (oxx < level.width) && (oyy >= 0) && (oyy < level.height)) {
                    let toProceed = (tilesProcessed.indexOf(level.tiles[oyy][oxx]) < 0);

                    let groundLight = (level.tiles[oyy][oxx].groundId === "") ? true : !gameEngine.bodies[level.tiles[oyy][oxx].groundId].hasPhysics ? true : !!gameEngine.bodies[level.tiles[oyy][oxx].groundId].allowFlying;
                    let propLight = (level.tiles[oyy][oxx].propId === "") ? true : !gameEngine.bodies[level.tiles[oyy][oxx].propId].hasPhysics ? true : !!gameEngine.bodies[level.tiles[oyy][oxx].propId].allowFlying;
                    if ((!groundLight || !propLight) && (j > 0)) {
                        breakObstacle = true;
                    }
                    for (let itHero=0; itHero < gameEngine.heros.length; itHero++) {
                        let hero = gameEngine.heros[itHero];
                        if (hero.position.y === oyy && hero.position.x === oxx) {
                            if(this.isHero){
                                this.onVisionCharacters[hero.guid] = true;
                            }else{
                                this.charSpotted = true;
                                this.onVisionCharacters[hero.guid] = true;
                            }
                        }
                    }

                    /*const mob = level.tiles[oyy][oxx].hasmob;
                    murmures.serverLog(level.tiles[oyy][oxx]);
                    if(this.isHero === false){
                        if(mob.code && mob.isHero){
                            this.charSpotted = true;
                            this.onVisionCharacters[mob.mob.guid] = true;
                        }
                    }else{
                        if(mob.code && mob.isHero){
                            this.onVisionCharacters[mob.mob.guid] = true;
                        }
                    }*/
                    /*for (let itMob=0; itMob < gameEngine.level.mobs.length; itMob++) {
                        let mob = gameEngine.level.mobs[itMob];
                        if (mob.position.y === oyy && mob.position.x === oxx) {
                            mob.charSpotted = true;
                            mob.onVisionCharacters[this.guid] = true;
                        }
                    }
                    for (let itHero=0; itHero < gameEngine.heros.length; itHero++) {
                        let hero = gameEngine.heros[itHero];
                        if (hero.position.y === oyy && hero.position.x === oxx) {
                            hero.onVisionCharacters[this.guid] = true;
                        }
                    }*/

                    if (toProceed && this.isHero === true) {
                        level.tiles[oyy][oxx].state = murmures.C.TILE_HIGHLIGHTED;
                        tilesProcessed.push(level.tiles[oyy][oxx]);
                    }

                    ox += x;
                    oy += y;
                } else {
                    breakObstacle = true;
                }
                j += 1;
            }
        }

        return tilesProcessed;
    }
};
<commit_msg>#194 end<commit_after>/**
 * @file Character class. Part of the MurmuresJS project.
 * @author github.com/azziliz
 * @author github.com/thyshimrod
 * {@link https://github.com/azziliz/MurmuresJS/ Project page}
 * @license MIT
 */

'use strict';
//debugger;

/**
 * Characters are entities that live, move and act inside a [level]{@link murmures.Level}.
 *
 * Heroes are characters managed by the players.
 * They can be given [orders]{@link murmures.Order} on client side.
 * They can move from one level to another.
 * Mobs are characters managed by the AI.
 * The AI methods to control them are defined in the [game engine]{@link murmures.GameEngine} class.
 * They cannot change level.
 *
 * Three steps are mandatory to create a valid character:
 * 1. Load all character templates from mobs.json.
 * 2. Select templates that are needed for the current level.
 * 2. Use the "instantiate" method in the Character class to create new instances.
 * Step 1 is performed by the game engine during the server startup.
 * Step 2 and 3 are performed together by the server and the game engine when a level is loaded.
 *
 * @class
 */
murmures.Character = function () {
    /** @type {string} */
    this.guid = '';
    /** @type {murmures.Tile} */
    this.position = null;
    /** @type {string} */
    this.mobTemplate = '';
    /** @type {number} */
    this.hitPointsMax = 0;
    /** @type {Object.<string, boolean>} */
    this.onVisionCharacters = {};
    /** @type {number} */
    this.hitPoints = 0;
    /** @type {number} */
    this.range = 0;
    /** @type {number} */
    this.defaultDamageValue = 0;
    /** @type {boolean} */
    this.canMove = false; // unused for now
    /** @type {boolean} */
    this.charSpotted = false; // hero is known because seen at least once
    /** @type {number} */
    this.stateOrder = murmures.C.STATE_HERO_WAITING_FOR_ORDER;
    /** @type {Object.<integer, murmures.Skill>} */
    this.skills = {};
    /** @type {number} */
    this.activeSkill = 0;
    /** @type {number} */
    this.dexterity = 0;
    /** @type {number} */
    this.intelligence = 0;
    /** @type {number} */
    this.strength = 0;
    /** @type {number} */
    this.initiative = 0;
};

murmures.Character.prototype = {

    /**
     * It is expected that, when the server calls this function,
     * the Tile object in parameter is already built.
     */
    build : function (tile, template) {
        this.guid = Math.random().toString();
        this.position = tile;
        this.mobTemplate = template;
        let ref = gameEngine.bodies[template];
        this.hitPointsMax = (ref.hitPointsMax || (this.isHero ? 20 : 10)) | 0; // by default, heroes start with 20 HP. Other mobs with 10. This can be changed in assets.json.
        this.hitPoints = this.hitPointsMax | 0;
        this.range = (ref.range || (this.isHero ? 3 : 2)) | 0; // by default, heroes start with a 3 tile range. Other mobs with 2. This can be changed in assets.json.
        this.defaultDamageValue = (ref.defaultDamageValue || (this.isHero ? 3 : 1)) | 0; // by default, heroes deal 3 damage per attack. Other mobs deal 1. This can be changed in assets.json.
        this.canMove = ref.canMove || false;
        this.charSpotted = ref.charSpotted || false;
        this.stateOrder = murmures.C.STATE_HERO_WAITING_FOR_ORDER;
        this.intelligence = Math.floor(Math.random() * 10);
        this.dexterity = Math.floor(Math.random() * 10);
        this.strength = Math.floor(Math.random() * 10);
        this.initiative = this.dexterity;
    },

    initialize : function (src) {
        this.guid = src.guid;
        this.synchronize(src);
    },

    synchronize : function (src) {
        if (typeof src === 'undefined') return;
        if (typeof src.position !== 'undefined') this.move(src.position.x, src.position.y); // TODO position=null when mob becomes invisible?
        if (typeof src.mobTemplate !== 'undefined') this.mobTemplate = src.mobTemplate;
        if (typeof src.hitPointsMax !== 'undefined') this.hitPointsMax = src.hitPointsMax;
        if (typeof src.hitPoints !== 'undefined') this.hitPoints = src.hitPoints;
        if (typeof src.range !== 'undefined') this.range = src.range;
        if (typeof src.defaultDamageValue !== 'undefined') this.defaultDamageValue = src.defaultDamageValue;
        if (typeof src.canMove !== 'undefined') this.canMove = src.canMove;
        if (typeof src.charSpotted !== 'undefined') this.charSpotted = src.charSpotted;
        if (typeof src.stateOrder !== 'undefined') this.stateOrder = src.stateOrder;
        if (typeof src.onVisionCharacters !== 'undefined') this.onVisionCharacters = src.onVisionCharacters;
        if (typeof src.skills !== 'undefined') this.skills = src.skills;
        if (typeof src.activeSkill !== 'undefined') this.activeSkill = src.activeSkill;
        if (typeof src.dexterity !== 'undefined') this.dexterity = src.dexterity;
        if (typeof src.intelligence !== 'undefined') this.intelligence = src.intelligence;
        if (typeof src.strength !== 'undefined') this.strength = src.strength;
        if (typeof src.initiative !== 'undefined') this.initiative = src.initiative;
    },

    clone : function () {
        let beforeOnVisionCharacters = {};
        for (let itVision in this.onVisionCharacters) {
            beforeOnVisionCharacters[itVision] = this.onVisionCharacters[itVision];
        }
        return {
            guid: this.guid,
            position: this.position.coordinates,
            mobTemplate: this.mobTemplate,
            hitPointsMax: this.hitPointsMax,
            hitPoints: this.hitPoints,
            range: this.range,
            defaultDamageValue: this.defaultDamageValue,
            canMove: this.canMove,
            charSpotted: this.charSpotted,
            stateOrder : this.stateOrder,
            onVisionCharacters : beforeOnVisionCharacters,
            dexterity : this.dexterity,
            intelligence : this.intelligence,
            strength : this.strength,
            initiative : this.initiative
        };
    },

    compare : function (beforeState) {
        let ret = {};
        if (this.guid !== beforeState.guid) throw 'Character changed guid. This souldn\'t be happening';
        if (this.position.x !== beforeState.position.x || this.position.y !== beforeState.position.y) ret.position = this.position.coordinates;
        if (this.mobTemplate !== beforeState.mobTemplate) ret.mobTemplate = this.mobTemplate;
        if (this.hitPointsMax !== beforeState.hitPointsMax) ret.hitPointsMax = this.hitPointsMax;
        if (this.hitPoints !== beforeState.hitPoints) ret.hitPoints = this.hitPoints;
        if (this.dexterity !== beforeState.dexterity) ret.dexterity = this.dexterity;
        if (this.intelligence !== beforeState.intelligence) ret.intelligence = this.intelligence;
        if (this.strength !== beforeState.strength) ret.strength = this.strength;
        if (this.initiative !== beforeState.initiative) ret.initiative = this.initiative;
        if (this.range !== beforeState.range) ret.range = this.range;
        if (this.defaultDamageValue !== beforeState.defaultDamageValue) ret.defaultDamageValue = this.defaultDamageValue;
        if (this.canMove !== beforeState.canMove) ret.canMove = this.canMove;
        if (this.stateOrder !== beforeState.stateOrder) ret.stateOrder = this.stateOrder;
        if (this.charSpotted !== beforeState.charSpotted) {
            // client discovers the mob for the first time --> send everything
            ret.position = this.position.coordinates;
            ret.mobTemplate = this.mobTemplate;
            ret.hitPointsMax = this.hitPointsMax;
            ret.hitPoints = this.hitPoints;
            ret.range = this.range;
            ret.defaultDamageValue = this.defaultDamageValue;
            ret.canMove = this.canMove;
            ret.charSpotted = this.charSpotted;
        }
        for (let itMap in this.onVisionCharacters) {
            if (this.onVisionCharacters[itMap] !== beforeState.onVisionCharacters[itMap]) {
                ret.onVisionCharacters = this.onVisionCharacters;
                break;
            }
        }
        if (Object.getOwnPropertyNames(ret).length > 0) {
            // only returns ret if not empty
            ret.guid = this.guid;
            return ret;
        }
        // otherwise, no return = undefined
    },

    move : function (x, y) {
        this.position = gameEngine.level.tiles[y][x];
    },

    get isHero() {
        let ref = gameEngine.bodies[this.mobTemplate];
        return murmures.C.LAYERS[ref.layerId][0] === 'Hero';
    },

    setVision : function (tilesProcessed) {
        murmures.serverLog("hero position");
        let level = gameEngine.level;
        if (typeof tilesProcessed === 'undefined' || tilesProcessed === null) { tilesProcessed = []; }
        for (let xx=0; xx < level.width && this.isHero === true; xx++) {
            for (let yy=0; yy < level.height; yy++) {
                let toProceed = (tilesProcessed.indexOf(level.tiles[yy][xx]) < 0);
                if (toProceed) {
                    if (level.tiles[yy][xx].state === murmures.C.TILE_HIGHLIGHTED) {
                        level.tiles[yy][xx].state = murmures.C.TILE_FOG_OF_WAR;
                    }
                }
            }
        }

        for (let i=0; i < 360; i++) {
            let x = Math.cos(i * 0.01745);
            let y = Math.sin(i * 0.01745);
            let ox = this.position.x + 0.5;
            let oy = this.position.y + 0.5;
            let j=0;
            let breakObstacle = false;
            while ((j < murmures.C.DEFAULT_RANGE_FOV) && (breakObstacle === false)) {
                let oxx = 0;
                oxx = Math.floor(ox);
                let oyy = 0;
                oyy = Math.floor(oy);
                if ((oxx >= 0) && (oxx < level.width) && (oyy >= 0) && (oyy < level.height)) {
                    let toProceed = (tilesProcessed.indexOf(level.tiles[oyy][oxx]) < 0);

                    let groundLight = (level.tiles[oyy][oxx].groundId === "") ? true : !gameEngine.bodies[level.tiles[oyy][oxx].groundId].hasPhysics ? true : !!gameEngine.bodies[level.tiles[oyy][oxx].groundId].allowFlying;
                    let propLight = (level.tiles[oyy][oxx].propId === "") ? true : !gameEngine.bodies[level.tiles[oyy][oxx].propId].hasPhysics ? true : !!gameEngine.bodies[level.tiles[oyy][oxx].propId].allowFlying;
                    if ((!groundLight || !propLight) && (j > 0)) {
                        breakObstacle = true;
                    }
                    for (let itHero=0; itHero < gameEngine.heros.length; itHero++) {
                        let hero = gameEngine.heros[itHero];
                        if (hero.position.y === oyy && hero.position.x === oxx) {
                            if(this.isHero){
                                this.onVisionCharacters[hero.guid] = true;
                            }else{
                                this.charSpotted = true;
                                this.onVisionCharacters[hero.guid] = true;
                            }
                        }
                    }

                    if (toProceed && this.isHero) {
                        level.tiles[oyy][oxx].state = murmures.C.TILE_HIGHLIGHTED;
                        tilesProcessed.push(level.tiles[oyy][oxx]);
                    }

                    ox += x;
                    oy += y;
                } else {
                    breakObstacle = true;
                }
                j += 1;
            }
        }

        return tilesProcessed;
    }
};
<|endoftext|>


<commit_before>import firebase from './firebase-include'
import { FirebaseFeature } from './firebase'

export class FirebaseDatabaseService extends FirebaseFeature {
    constructor(firebaseApp, config) {
        super(firebaseApp, 'db')
    }
}
<commit_msg>Make build tests pass.<commit_after>import firebase from './firebase-include'
import { FirebaseFeature } from './firebase'

export class FirebaseDatabaseService extends FirebaseFeature {
    constructor(firebaseApp, config) {
        super(firebaseApp, 'db')
        this.db = firebase.database(this.app)
    }
}
<|endoftext|>


<commit_before>import Mustache from 'mustache';
/* eslint max-len: 0*/
const templates = {
  preview: `

  <div {{#needsProvider}} data-btd-provider="{{provider}}" {{/needsProvider}} class="js-media-preview-container position-rel {{^isMediaPreviewLarge}}{{^isMediaPreviewCompact}}{{^isMediaPreviewInQuoted}}margin-vm{{/isMediaPreviewInQuoted}}{{/isMediaPreviewCompact}}{{/isMediaPreviewLarge}}  {{#isMediaPreviewSmall}}{{#isPossiblySensitive}}media-size-medium{{/isPossiblySensitive}}{{/isMediaPreviewSmall}} {{#isMediaPreviewCompact}}media-size-medium margin-t--8{{/isMediaPreviewCompact}} {{#isMediaPreviewInQuoted}}margin-tm{{/isMediaPreviewInQuoted}} {{#isAnimatedGif}}is-gif{{/isAnimatedGif}} {{#isVideo}}is-video{{/isVideo}} {{#isMediaPreviewLarge}}margin-tm item-box-full-bleed{{/isMediaPreviewLarge}}">
    {{#isMediaPreviewLarge}}

    {{/isMediaPreviewLarge}}
    {{#isAnimatedGif}}
      {{#animatedGif}} {{> media/animated_gif}} {{/animatedGif}}
    {{/isAnimatedGif}} {{^isAnimatedGif}}
    <a class="js-media-image-link block med-link media-item {{thumbSizeClass}} {{#isPossiblySensitive}}is-invisible{{/isPossiblySensitive}} {{#needsSecureUrl}}js-needs-secure-url{{/needsSecureUrl}} {{^isGalleryView}}is-zoomable{{/isGalleryView}}"
     {{#needsSecureUrl}} data-original-url="{{mediaPreviewSrc}}{{imageSrc}}" {{/needsSecureUrl}} href="{{url}}" target="_blank" {{^needsSecureUrl}} {{^imageSrc}} style="background-image:url('{{mediaPreviewSrc}}')" {{/imageSrc}} {{/needsSecureUrl}}
    data-media-entity-id="{{mediaId}}"> {{#isVideo}} {{> media/video_overlay}} {{/isVideo}}  {{#imageSrc}}  {{/imageSrc}}  {{/isAnimatedGif}}
    {{> status/media_sensitive}}

  `,
  modal: `

                    {{^isVideo}}

                    {{/isVideo}}
                    {{#isVideo}}

                      {{&videoEmbed}}

                    {{/isVideo}}

                {{#hasGIFDownload}}
                Download as .GIF
                {{/hasGIFDownload}}
                View original

{{&tweetEmbed}}

`,
};

const defaultData = {
  preview: {
    animatedGif: null,
    imageSrc: null,
    isAnimatedGif: false,
    isGalleryView: true,
    isMediaPreviewInQuoted: false,
    isMediaPreviewLarge: false,
    isMediaPreviewCompact: true,
    isMediaPreviewSmall: false,
    isPossiblySensitive: false,
    isVideo: false,
    mediaId: 0,
    mediaPreviewSrc: 'foo',
    needsSecureUrl: false,
    thumbSizeClass: 'HUGE',
    url: 'apple.com',
  },
  modal: {
    imageUrl: undefined,
    isVideo: true,
    originalUrl: undefined,
    videoEmbed: undefined,
  },
};

const previewTemplate = ({ mediaPreviewSrc, sourceLink, size, type = 'picture', provider = 'default' }) => {
  const safeURL = mediaPreviewSrc;

  if (type === 'image' && !mediaPreviewSrc.includes('imgur.com') && mediaPreviewSrc) {
    const parsed = new URL(mediaPreviewSrc);
    mediaPreviewSrc = parsed.searchParams.get('url');

    if (!mediaPreviewSrc.includes('https')) {
      mediaPreviewSrc = safeURL;
    }
  }

  return Mustache.render(templates.preview, Object.assign(defaultData.preview, {
    url: sourceLink,
    mediaPreviewSrc,
    isVideo: type !== 'image',
    isMediaPreviewLarge: size === 'large',
    isMediaPreviewCompact: size === 'medium',
    isMediaPreviewSmall: size === 'small',
    thumbSizeClass: `media-size-${size || 'medium'}`,
    needsProvider: !['default', 'universal'].includes(provider),
    provider,
  }));
};

const modalTemplate = ({ imageUrl, originalUrl, type, videoEmbed = null, provider = 'default', hasGIFDownload = false }) => {
  if (type === 'image') {
    const parsed = new URL(imageUrl);
    imageUrl = parsed.searchParams.get('url');
  }

  return Mustache.render(templates.modal, Object.assign(defaultData.modal, {
    imageUrl,
    videoEmbed,
    originalUrl,
    isVideo: type !== 'image',
    provider,
    hasGIFDownload,
  }));
};

module.exports = { modalTemplate, previewTemplate };
<commit_msg>:bug: use lowercase version of the provider's name in templates<commit_after>import Mustache from 'mustache';
/* eslint max-len: 0*/
const templates = {
  preview: `

  <div {{#needsProvider}} data-btd-provider="{{provider}}" {{/needsProvider}} class="js-media-preview-container position-rel {{^isMediaPreviewLarge}}{{^isMediaPreviewCompact}}{{^isMediaPreviewInQuoted}}margin-vm{{/isMediaPreviewInQuoted}}{{/isMediaPreviewCompact}}{{/isMediaPreviewLarge}}  {{#isMediaPreviewSmall}}{{#isPossiblySensitive}}media-size-medium{{/isPossiblySensitive}}{{/isMediaPreviewSmall}} {{#isMediaPreviewCompact}}media-size-medium margin-t--8{{/isMediaPreviewCompact}} {{#isMediaPreviewInQuoted}}margin-tm{{/isMediaPreviewInQuoted}} {{#isAnimatedGif}}is-gif{{/isAnimatedGif}} {{#isVideo}}is-video{{/isVideo}} {{#isMediaPreviewLarge}}margin-tm item-box-full-bleed{{/isMediaPreviewLarge}}">
    {{#isMediaPreviewLarge}}

    {{/isMediaPreviewLarge}}
    {{#isAnimatedGif}}
      {{#animatedGif}} {{> media/animated_gif}} {{/animatedGif}}
    {{/isAnimatedGif}} {{^isAnimatedGif}}
    <a class="js-media-image-link block med-link media-item {{thumbSizeClass}} {{#isPossiblySensitive}}is-invisible{{/isPossiblySensitive}} {{#needsSecureUrl}}js-needs-secure-url{{/needsSecureUrl}} {{^isGalleryView}}is-zoomable{{/isGalleryView}}"
     {{#needsSecureUrl}} data-original-url="{{mediaPreviewSrc}}{{imageSrc}}" {{/needsSecureUrl}} href="{{url}}" target="_blank" {{^needsSecureUrl}} {{^imageSrc}} style="background-image:url('{{mediaPreviewSrc}}')" {{/imageSrc}} {{/needsSecureUrl}}
    data-media-entity-id="{{mediaId}}"> {{#isVideo}} {{> media/video_overlay}} {{/isVideo}}  {{#imageSrc}}  {{/imageSrc}}  {{/isAnimatedGif}}
    {{> status/media_sensitive}}

  `,
  modal: `

                    {{^isVideo}}

                    {{/isVideo}}
                    {{#isVideo}}

                      {{&videoEmbed}}

                    {{/isVideo}}

                {{#hasGIFDownload}}
                Download as .GIF
                {{/hasGIFDownload}}
                View original

{{&tweetEmbed}}

`,
};

const defaultData = {
  preview: {
    animatedGif: null,
    imageSrc: null,
    isAnimatedGif: false,
    isGalleryView: true,
    isMediaPreviewInQuoted: false,
    isMediaPreviewLarge: false,
    isMediaPreviewCompact: true,
    isMediaPreviewSmall: false,
    isPossiblySensitive: false,
    isVideo: false,
    mediaId: 0,
    mediaPreviewSrc: 'foo',
    needsSecureUrl: false,
    thumbSizeClass: 'HUGE',
    url: 'apple.com',
  },
  modal: {
    imageUrl: undefined,
    isVideo: true,
    originalUrl: undefined,
    videoEmbed: undefined,
  },
};

const previewTemplate = ({ mediaPreviewSrc, sourceLink, size, type = 'picture', provider = 'default' }) => {
  const safeURL = mediaPreviewSrc;

  if (type === 'image' && !mediaPreviewSrc.includes('imgur.com') && mediaPreviewSrc) {
    const parsed = new URL(mediaPreviewSrc);
    mediaPreviewSrc = parsed.searchParams.get('url');

    if (!mediaPreviewSrc.includes('https')) {
      mediaPreviewSrc = safeURL;
    }
  }

  return Mustache.render(templates.preview, Object.assign(defaultData.preview, {
    url: sourceLink,
    mediaPreviewSrc,
    isVideo: type !== 'image',
    isMediaPreviewLarge: size === 'large',
    isMediaPreviewCompact: size === 'medium',
    isMediaPreviewSmall: size === 'small',
    thumbSizeClass: `media-size-${size || 'medium'}`,
    needsProvider: !['default', 'universal'].includes(provider),
    provider: (provider || '').toLowerCase(),
  }));
};

const modalTemplate = ({ imageUrl, originalUrl, type, videoEmbed = null, provider = 'default', hasGIFDownload = false }) => {
  if (type === 'image') {
    const parsed = new URL(imageUrl);
    imageUrl = parsed.searchParams.get('url');
  }

  return Mustache.render(templates.modal, Object.assign(defaultData.modal, {
    imageUrl,
    videoEmbed,
    originalUrl,
    isVideo: type !== 'image',
    provider: (provider || '').toLowerCase(),
    hasGIFDownload,
  }));
};

module.exports = { modalTemplate, previewTemplate };
<|endoftext|>


<commit_before>// Copyright 2013 Google Inc. All Rights Reserved.

/**
 * @fileoverview "Related text" Module
 * @author hungte@google.com (Hung-Te Lin)
 */

ModRelatedText = function(im) {
  var self = this;
  self.im = im;
  self.last_mcch = undefined;

  function InSelectionKey(ctx, key) {
    return ctx.selkey.toUpperCase().indexOf(key.toUpperCase()) >= 0;
  }

  function CommitCandidate(ctx, key) {
    var index = ctx.selkey.toUpperCase().indexOf(key.toUpperCase());
    if (index >= ctx.mcch.length)
      return false;
    ctx.cch = ctx.mcch[index];
    return true;
  }

  function FindRelatedText(ctx) {
    var text = ctx.cch;
    var candidates = ctx.phrases && ctx.phrases[text];
    if (!candidates)
      return;

    // Update context to fill fake content.
    self.last_mcch = candidates.substr(0, ctx.selkey.length);
    ctx.mcch = self.last_mcch;
  }

  self.onKeystroke = function(ctx, ev) {
    if (!ctx.allow_related_text)
      return self.im.onKeystroke(ctx, ev);
    var key = ev.key;
    if (!ev.ctrlKey && !ev.altKey && ev.shiftKey &&
        ctx.mcch && ctx.mcch == self.last_mcch &&
        InSelectionKey(ctx, key) &&
        CommitCandidate(ctx, key)) {
      FindRelatedText(ctx);
      return jscin.IMKEY_COMMIT;
    }

    var result = im.onKeystroke(ctx, ev);
    if (result != jscin.IMKEY_COMMIT)
      return result;

    jscin.log("mod_related on COMMIT", ctx, ev);
    var text = ctx.cch;
    var candidates = ctx.phrases && ctx.phrases[text];
    if (!candidates)
      return result;

    FindRelatedText(ctx);
    return result;
  }

  return self;
}

// Entry stub
jscin.register_addon('RelatedText', ModRelatedText);
<commit_msg>Also fix shift issue for related text.<commit_after>// Copyright 2013 Google Inc. All Rights Reserved.

/**
 * @fileoverview "Related text" Module
 * @author hungte@google.com (Hung-Te Lin)
 */

ModRelatedText = function(im) {
  var self = this;
  self.im = im;
  self.last_mcch = undefined;

  function InSelectionKey(ctx, key) {
    return ctx.selkey.toUpperCase().indexOf(key.toUpperCase()) >= 0;
  }

  function CommitCandidate(ctx, key) {
    var index = ctx.selkey.toUpperCase().indexOf(key.toUpperCase());
    if (index >= ctx.mcch.length)
      return false;
    ctx.cch = ctx.mcch[index];
    return true;
  }

  function FindRelatedText(ctx) {
    var text = ctx.cch;
    var candidates = ctx.phrases && ctx.phrases[text];
    if (!candidates)
      return;

    // Update context to fill fake content.
    self.last_mcch = candidates.substr(0, ctx.selkey.length);
    ctx.mcch = self.last_mcch;
  }

  self.onKeystroke = function(ctx, ev) {
    if (!ctx.allow_related_text)
      return self.im.onKeystroke(ctx, ev);
    var key = jscin.unshift_key(ev.key);
    if (!ev.ctrlKey && !ev.altKey && ev.shiftKey &&
        ctx.mcch && ctx.mcch == self.last_mcch &&
        InSelectionKey(ctx, key) &&
        CommitCandidate(ctx, key)) {
      FindRelatedText(ctx);
      return jscin.IMKEY_COMMIT;
    }

    var result = im.onKeystroke(ctx, ev);
    if (result != jscin.IMKEY_COMMIT)
      return result;

    jscin.log("mod_related on COMMIT", ctx, ev);
    var text = ctx.cch;
    var candidates = ctx.phrases && ctx.phrases[text];
    if (!candidates)
      return result;

    FindRelatedText(ctx);
    return result;
  }

  return self;
}

// Entry stub
jscin.register_addon('RelatedText', ModRelatedText);
<|endoftext|>


<commit_before>define([], function () {
  'use strict';

  var publish;
  var subscribe;
  var mediator;

  mediator = {};
  mediator.channels = {};

  publish = function (channel) {
    console.log('Mediator Publish', arguments);
    var args;

    if (!mediator.channels[channel]) {
      return false;
    }
    args = Array.prototype.slice.call(arguments, 1);
    for (var i = 0; i < mediator.channels[channel].length; i++) {
      var subscription = mediator.channels[channel][i];
      subscription.callback.apply(subscription.context, args);
    }
    return this;
  };

  subscribe = function (channel, fn) {
    console.log('Mediator Subscribe', arguments);
    if (!mediator.channels[channel]) {
      mediator.channels[channel] = [];
    }
    mediator.channels[channel].push({ context: this, callback: fn });
    return this;
  };

  return {
    publish: publish,
    subscribe: subscribe
  };
});
<commit_msg>Remove debug statements<commit_after>define([], function () {
  'use strict';

  var publish;
  var subscribe;
  var mediator;

  mediator = {};
  mediator.channels = {};

  publish = function (channel) {
    var args;

    if (!mediator.channels[channel]) {
      return false;
    }
    args = Array.prototype.slice.call(arguments, 1);
    for (var i = 0; i < mediator.channels[channel].length; i++) {
      var subscription = mediator.channels[channel][i];
      subscription.callback.apply(subscription.context, args);
    }
    return this;
  };

  subscribe = function (channel, fn) {
    if (!mediator.channels[channel]) {
      mediator.channels[channel] = [];
    }
    mediator.channels[channel].push({ context: this, callback: fn });
    return this;
  };

  return {
    publish: publish,
    subscribe: subscribe
  };
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var isNonNegativeInteger = require( '@stdlib/math/base/utils/is-nonnegative-integer' );
var betainc = require( '@stdlib/math/base/special/betainc' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var floor = require( '@stdlib/math/base/special/floor' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );

// MAIN //

/**
* Evaluates the cumulative distribution function (CDF) for a binomial distribution with number of trials `n` and success probability `p` at a value `x`.
*
* @param {number} x - input value
* @param {NonNegativeInteger} n - number of trials
* @param {Probability} p - success probability
* @returns {Probability} evaluated CDF
*
* @example
* var y = cdf( 3.0, 20, 0.2 );
* // returns ~0.411
* @example
* var y = cdf( 21.0, 20, 0.2 );
* // returns 1.0
* @example
* var y = cdf( 5.0, 10, 0.4 )
* // returns ~0.834
* @example
* var y = cdf( 0.0, 10, 0.4 )
* // returns ~0.06
* @example
* var y = cdf( NaN, 20, 0.5 );
* // returns NaN
* @example
* var y = cdf( 0.0, NaN, 0.5 );
* // returns NaN
* @example
* var y = cdf( 0.0, 20, NaN );
* // returns NaN
* @example
* var y = cdf( 2.0, 1.5, 0.5 );
* // returns NaN
* @example
* var y = cdf( 2.0, -2.0, 0.5 );
* // returns NaN
* @example
* var y = cdf( 2.0, 20, -1.0 );
* // returns NaN
* @example
* var y = cdf( 2.0, 20, 1.5 );
* // returns NaN
*/
function cdf( x, n, p ) {
	if (
		isnan( x ) ||
		isnan( n ) ||
		isnan( p ) ||
		p < 0.0 ||
		p > 1.0 ||
		!isNonNegativeInteger( n ) ||
		n === PINF
	) {
		return NaN;
	}
	if ( x < 0.0 ) {
		return 0.0;
	}
	if ( x >= n ) {
		return 1.0;
	}
	x = floor( x + 1e-7 );
	return betainc( p, x + 1.0, n - x, true, true );
} // end FUNCTION cdf()

// EXPORTS //

module.exports = cdf;
<commit_msg>Add decimal<commit_after>'use strict';

// MODULES //

var isNonNegativeInteger = require( '@stdlib/math/base/utils/is-nonnegative-integer' );
var betainc = require( '@stdlib/math/base/special/betainc' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var floor = require( '@stdlib/math/base/special/floor' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );

// MAIN //

/**
* Evaluates the cumulative distribution function (CDF) for a binomial distribution with number of trials `n` and success probability `p` at a value `x`.
*
* @param {number} x - input value
* @param {NonNegativeInteger} n - number of trials
* @param {Probability} p - success probability
* @returns {Probability} evaluated CDF
*
* @example
* var y = cdf( 3.0, 20, 0.2 );
* // returns ~0.411
* @example
* var y = cdf( 21.0, 20, 0.2 );
* // returns 1.0
* @example
* var y = cdf( 5.0, 10, 0.4 )
* // returns ~0.834
* @example
* var y = cdf( 0.0, 10, 0.4 )
* // returns ~0.06
* @example
* var y = cdf( NaN, 20, 0.5 );
* // returns NaN
* @example
* var y = cdf( 0.0, NaN, 0.5 );
* // returns NaN
* @example
* var y = cdf( 0.0, 20, NaN );
* // returns NaN
* @example
* var y = cdf( 2.0, 1.5, 0.5 );
* // returns NaN
* @example
* var y = cdf( 2.0, -2.0, 0.5 );
* // returns NaN
* @example
* var y = cdf( 2.0, 20, -1.0 );
* // returns NaN
* @example
* var y = cdf( 2.0, 20, 1.5 );
* // returns NaN
*/
function cdf( x, n, p ) {
	if (
		isnan( x ) ||
		isnan( n ) ||
		isnan( p ) ||
		p < 0.0 ||
		p > 1.0 ||
		!isNonNegativeInteger( n ) ||
		n === PINF
	) {
		return NaN;
	}
	if ( x < 0.0 ) {
		return 0.0;
	}
	if ( x >= n ) {
		return 1.0;
	}
	x = floor( x + 1.0e-7 );
	return betainc( p, x + 1.0, n - x, true, true );
} // end FUNCTION cdf()

// EXPORTS //

module.exports = cdf;
<|endoftext|>


<commit_before>/*
Language: Haskell
*/

hljs.LANGUAGES.haskell = {
  defaultMode: {
    lexems: hljs.UNDERSCORE_IDENT_RE,
    illegal: '',
    contains: ['comment', 'string', 'function', 'class', 'number', 'shebang'],
    keywords: {
      'keywords': {'\\': 1,'->': 1,'let': 1,'in': 1,'if': 1,'then': 1,'else': 1,'case': 1,'of': 1,'where': 1,'|': 1,'do': 1,'module': 1,'import': 1, 'hiding': 1,'qualified': 1,'type': 1,'data': 1,'deriving': 1,'::': 1,':': 1, 'class': 1,'instance':1,'null': 1,'++': 1,'+': 1,'-': 1,'/': 1,'\*': 1},
      'built_in': {'Bool': 1,'True': 1,'False': 1,'Int': 1,'Char': 1,'Maybe': 1,'Nothing': 1}
    }
  },
  modes: [
    {
      className: 'comment',
      begin: '--', end: '$'
    },
    {
      className: 'comment',
      begin: '{-', end: '-}'
    }
  ]
};
<commit_msg>Added a few more highlighting, but class and function highlight is going to be a bit weird...<commit_after>/*
Language: Haskell
Author: Jeremy Hull <sourdrums@gmail.com>
*/

hljs.LANGUAGES.haskell = {
  defaultMode: {
    lexems: hljs.UNDERSCORE_IDENT_RE,
    illegal: '',
    contains: ['comment', 'string', 'function', 'class', 'number', 'shebang'],
    keywords: {
      'keyword': {'let': 1,'in': 1,'if': 1,'then': 1,'else': 1,'case': 1,'of': 1,'where': 1,'do': 1,'module': 1,'import': 1, 'hiding': 1,'qualified': 1,'type': 1,'data': 1,'deriving': 1,'class': 1,'instance': 1,'null': 1,'not': 1},
      'built_in': {'Bool': 1,'True': 1,'False': 1,'Int': 1,'Char': 1,'Maybe': 1,'Nothing': 1,'String': 1}
    }
  },
  modes: [
    {
      className: 'comment',
      begin: '--', end: '$'
    },
    {
      className: 'comment',
      begin: '{-', end: '-}'
    },
    {
      className: 'shebang',
      begin: '#!\\/usr\\/bin\\/env\ runhaskell',
      end: '$'
    },
    hljs.C_NUMBER_MODE,
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    {
      className: 'class',
      lexems: hljs.UNDERSCORE_IDENT_RE,
      begin: '\\bclass', end: 'where|$',
      keywords: {'class': 1,'where': 1},
      contains: ['title','params']
    },
    {
      className: 'title',
      begin: hljs.UNDERSCORE_IDENT_RE, end: hljs.IMMEDIATE_RE
    },
    {
      className: 'params',
      begin: hljs.UNDERSCORE_IDENT_RE, end: hljs.IMMEDIATE_RE
    }
  ]
};
<|endoftext|>


<commit_before>/*
Language: Verilog
Author: Jon Evans <jon@craftyjon.com>
Controbutors: Boone Severson <boone.severson@gmail.com>
Description: Verilog is a hardware description language used in electronic design automation to describe digital and mixed-signal systems. This highlighter supports Verilog and SystemVerilog through IEEE 1800-2012.
*/

function(hljs) {
  var SV_KEYWORDS = {
    keyword:
      'accept_on alias always always_comb always_ff always_latch and assert assign ' +
      'assume automatic before begin bind bins binsof bit break buf bufif0 bufif1 ' +
      'byte case casex casez cell chandle checker class clocking cmos config const ' +
      'constraint context continue cover covergroup coverpoint cross deassign default ' +
      'defparam design disable dist do edge else end endcase endchecker endclass ' +
      'endclocking endconfig endfunction endgenerate endgroup endinterface endmodule ' +
      'endpackage endprimitive endprogram endproperty endspecify endsequence endtable ' +
      'endtask enum event eventually expect export extends extern final first_match for ' +
      'force foreach forever fork forkjoin function generate|5 genvar global highz0 highz1 ' +
      'if iff ifnone ignore_bins illegal_bins implements implies import incdir include ' +
      'initial inout input inside instance int integer interconnect interface intersect ' +
      'join join_any join_none large let liblist library local localparam logic longint ' +
      'macromodule matches medium modport module nand negedge nettype new nexttime nmos ' +
      'nor noshowcancelled not notif0 notif1 or output package packed parameter pmos ' +
      'posedge primitive priority program property protected pull0 pull1 pulldown pullup ' +
      'pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos ' +
      'real realtime ref reg reject_on release repeat restrict return rnmos rpmos rtran ' +
      'rtranif0 rtranif1 s_always s_eventually s_nexttime s_until s_until_with scalared ' +
      'sequence shortint shortreal showcancelled signed small soft solve specify specparam ' +
      'static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on ' +
      'sync_reject_on table tagged task this throughout time timeprecision timeunit tran ' +
      'tranif0 tranif1 tri tri0 tri1 triand trior trireg type typedef union unique unique0 ' +
      'unsigned until until_with untyped use uwire var vectored virtual void wait wait_order ' +
      'wand weak weak0 weak1 while wildcard wire with within wor xnor xor',
    literal:
      'null',
    built_in:
      '$finish $stop $exit $fatal $error $warning $info $realtime $time $printtimescale ' +
      '$bitstoreal $bitstoshortreal $itor $signed $cast $bits $stime $timeformat ' +
      '$realtobits $shortrealtobits $rtoi $unsigned $asserton $assertkill $assertpasson ' +
      '$assertfailon $assertnonvacuouson $assertoff $assertcontrol $assertpassoff ' +
      '$assertfailoff $assertvacuousoff $isunbounded $sampled $fell $changed $past_gclk ' +
      '$fell_gclk $changed_gclk $rising_gclk $steady_gclk $coverage_control ' +
      '$coverage_get $coverage_save $set_coverage_db_name $rose $stable $past ' +
      '$rose_gclk $stable_gclk $future_gclk $falling_gclk $changing_gclk ' +
      '$coverage_get_max $coverage_merge $get_coverage $load_coverage_db $typename ' +
      '$unpacked_dimensions $left $low $increment $clog2 $ln $log10 $exp $sqrt $pow ' +
      '$floor $ceil $sin $cos $tan $countbits $onehot $isunknown $fatal $warning ' +
      '$dimensions $right $high $size $asin $acos $atan $atan2 $hypot $sinh $cosh ' +
      '$tanh $asinh $acosh $atanh $countones $onehot0 $error $info $random ' +
      '$dist_chi_square $dist_erlang $dist_exponential $dist_normal $dist_poisson ' +
      '$dist_t $dist_uniform $q_initialize $q_remove $q_exam $async$and$array ' +
      '$async$nand$array $async$or$array $async$nor$array $sync$and$array ' +
      '$sync$nand$array $sync$or$array $sync$nor$array $q_add $q_full ' +
      '$async$and$plane $async$nand$plane $async$or$plane $async$nor$plane ' +
      '$sync$and$plane $sync$nand$plane $sync$or$plane $sync$nor$plane $system'
    };
  return {
    aliases: ['v', 'sv', 'svh'],
    case_insensitive: false,
    keywords: SV_KEYWORDS,
    contains: [
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_LINE_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        className: 'number',
        begin: '(\\b((\\d+\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+))|(\\B((\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+))|(\\b([0-9_])+)',
        contains: [hljs.BACKSLASH_ESCAPE],
        relevance: 10
      },
      /* parameters to instances */
      {
        className: 'variable',
        begin: '#\\((?!parameter).+\\)'
      },
      {
        className: 'variable',
        begin: '\\.\\w+'
      },
      {
        className: 'meta',
        begin: '`', end: '$',
        keywords: {'meta-keyword': 'ifdef ifndef endif'},
      }
    ]
  }; // return
}
<commit_msg>auto-highlight is failing with accesslog<commit_after>/*
Language: Verilog
Author: Jon Evans <jon@craftyjon.com>
Controbutors: Boone Severson <boone.severson@gmail.com>
Description: Verilog is a hardware description language used in electronic design automation to describe digital and mixed-signal systems. This highlighter supports Verilog and SystemVerilog through IEEE 1800-2012.
*/

function(hljs) {
  var SV_KEYWORDS = {
    keyword:
      'accept_on alias always always_comb always_ff always_latch and assert assign ' +
      'assume automatic before begin bind bins binsof bit break buf bufif0 bufif1 ' +
      'byte case casex casez cell chandle checker class clocking cmos config const ' +
      'constraint context continue cover covergroup coverpoint cross deassign default ' +
      'defparam design disable dist do edge else end endcase endchecker endclass ' +
      'endclocking endconfig endfunction endgenerate endgroup endinterface endmodule ' +
      'endpackage endprimitive endprogram endproperty endspecify endsequence endtable ' +
      'endtask enum event eventually expect export extends extern final first_match for ' +
      'force foreach forever fork forkjoin function generate|5 genvar global highz0 highz1 ' +
      'if iff ifnone ignore_bins illegal_bins implements implies import incdir include ' +
      'initial inout input inside instance int integer interconnect interface intersect ' +
      'join join_any join_none large let liblist library local localparam logic longint ' +
      'macromodule matches medium modport module nand negedge nettype new nexttime nmos ' +
      'nor noshowcancelled not notif0 notif1 or output package packed parameter pmos ' +
      'posedge primitive priority program property protected pull0 pull1 pulldown pullup ' +
      'pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos ' +
      'real realtime ref reg reject_on release repeat restrict return rnmos rpmos rtran ' +
      'rtranif0 rtranif1 s_always s_eventually s_nexttime s_until s_until_with scalared ' +
      'sequence shortint shortreal showcancelled signed small soft solve specify specparam ' +
      'static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on ' +
      'sync_reject_on table tagged task this throughout time timeprecision timeunit tran ' +
      'tranif0 tranif1 tri tri0 tri1 triand trior trireg type typedef union unique unique0 ' +
      'unsigned until until_with untyped use uwire var vectored virtual void wait wait_order ' +
      'wand weak weak0 weak1 while wildcard wire with within wor xnor xor',
    literal:
      'null',
    built_in:
      '$finish $stop $exit $fatal $error $warning $info $realtime $time $printtimescale ' +
      '$bitstoreal $bitstoshortreal $itor $signed $cast $bits $stime $timeformat ' +
      '$realtobits $shortrealtobits $rtoi $unsigned $asserton $assertkill $assertpasson ' +
      '$assertfailon $assertnonvacuouson $assertoff $assertcontrol $assertpassoff ' +
      '$assertfailoff $assertvacuousoff $isunbounded $sampled $fell $changed $past_gclk ' +
      '$fell_gclk $changed_gclk $rising_gclk $steady_gclk $coverage_control ' +
      '$coverage_get $coverage_save $set_coverage_db_name $rose $stable $past ' +
      '$rose_gclk $stable_gclk $future_gclk $falling_gclk $changing_gclk ' +
      '$coverage_get_max $coverage_merge $get_coverage $load_coverage_db $typename ' +
      '$unpacked_dimensions $left $low $increment $clog2 $ln $log10 $exp $sqrt $pow ' +
      '$floor $ceil $sin $cos $tan $countbits $onehot $isunknown $fatal $warning ' +
      '$dimensions $right $high $size $asin $acos $atan $atan2 $hypot $sinh $cosh ' +
      '$tanh $asinh $acosh $atanh $countones $onehot0 $error $info $random ' +
      '$dist_chi_square $dist_erlang $dist_exponential $dist_normal $dist_poisson ' +
      '$dist_t $dist_uniform $q_initialize $q_remove $q_exam $async$and$array ' +
      '$async$nand$array $async$or$array $async$nor$array $sync$and$array ' +
      '$sync$nand$array $sync$or$array $sync$nor$array $q_add $q_full ' +
      '$async$and$plane $async$nand$plane $async$or$plane $async$nor$plane ' +
      '$sync$and$plane $sync$nand$plane $sync$or$plane $sync$nor$plane $system'
    };
  return {
    aliases: ['v', 'sv', 'svh'],
    case_insensitive: false,
    keywords: SV_KEYWORDS,
    contains: [
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_LINE_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        className: 'number',
        begin: '(\\b((\\d+\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+))|(\\B((\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+))|(\\b([0-9_])+)',
        contains: [hljs.BACKSLASH_ESCAPE],
        relevance: 0
      },
      /* parameters to instances */
      {
        className: 'variable',
        begin: '#\\((?!parameter).+\\)'
      },
      {
        className: 'variable',
        begin: '\\.\\w+'
      },
      {
        className: 'meta',
        begin: '`', end: '$',
        keywords: {'meta-keyword': 'ifdef ifndef endif'},
      }
    ]
  }; // return
}
<|endoftext|>


<commit_before>/**
 * @classdesc
 * A layer for managing and rendering geometries.
 * @class
 * @category layer
 * @extends {maptalks.OverlayLayer}
 * @param {String|Number} id - layer's id
 * @param {Object} [options=null] - construct options
 * @param {Boolean} [options.debug=false] - whether the geometries on the layer is in debug mode.
 * @param {Boolean} [options.enableSimplify=false] - whether to simplify geometries before rendering.
 * @param {String} [options.cursor=default] - the cursor style of the layer
 * @param {Boolean} [options.geometryEvents=true] - enable/disable firing geometry events
 * @param {Number} [options.thresholdOfTransforming=50] - threshold of points number to update points while transforming.
 * @param {*} options.* - any other option defined in [maptalks.Layer]{@link maptalks.Layer#options}
 */
Z.VectorLayer = Z.OverlayLayer.extend(/** @lends maptalks.VectorLayer.prototype */{

    options:{
        'debug'                     : false,
        'enableSimplify'            : true,
        'cursor'                    : 'pointer',
        'geometryEvents'            : true,
        'thresholdOfTransforming'    : 150,
        'drawImmediate'             : false,
        'drawOnce'                  : false,
        'defaultIconSize'           : [20, 20],
        'cacheSvgOnCanvas'          : true
    },

    getStyle: function () {
        if (!this._style) {
            return null;
        }
        return this._style;
    },

    setStyle: function (style) {
        this._style = style;
        this._cookedStyles = this._compileStyle(style);
        this.forEach(function (geometry) {
            this._styleGeometry(geometry);
        }, this);
        return this;
    },

    removeStyle: function () {
        if (!this._style) {
            return this;
        }
        delete this._style;
        delete this._cookedStyles;
        this.forEach(function (geometry) {
            geometry._setExternSymbol(null);
        }, this);
        return this;
    },

    _styleGeometry: function (geometry) {
        var symbol = geometry.getSymbol(),
            g = Z.Util.getFilterFeature(geometry);
        for (var i = 0, len = this._cookedStyles.length; i < len; i++) {
            if (this._cookedStyles[i]['filter'](g) === true) {
                geometry._setExternSymbol(this._cookedStyles[i]['symbol']);
                return true;
            }
        }
        return false;
    },

    _compileStyle: function (styles) {
        if (!Z.Util.isArray(styles)) {
            return this._compileStyle([styles]);
        }
        var cooked = [];
        for (var i = 0; i < styles.length; i++) {
            cooked.push({
                'filter' : Z.Util.createFilter(styles[i]['filter']),
                'symbol' : styles[i].symbol
            });
        }
        return cooked;
    }
});

/**
 * Export the vector layer's profile json.

 * @param  {Object} [options=null] - export options
 * @param  {Object} [options.geometries=null] - If not null and the layer is a [OverlayerLayer]{@link maptalks.OverlayLayer},
 *                                            the layer's geometries will be exported with the given "options.geometries" as a parameter of geometry's toJSON.
 * @param  {maptalks.Extent} [options.clipExtent=null] - if set, only the geometries intersectes with the extent will be exported.
 * @return {Object} layer's profile JSON
 */
Z.VectorLayer.prototype.toJSON = function (options) {
    if (!options) {
        options = {};
    }
    var profile = {
        'type'    : 'VectorLayer',
        'id'      : this.getId(),
        'options' : this.config()
    };
    if ((Z.Util.isNil(options['style']) || options['style']) && this.getStyle()) {
        profile['style'] = this.getStyle();
    }
    if (Z.Util.isNil(options['geometries']) || options['geometries']) {
        var clipExtent;
        if (options['clipExtent']) {
            clipExtent = new Z.Extent(options['clipExtent']);
        }
        var geoJSONs = [];
        var geometries = this.getGeometries(),
            geoExt,
            json;
        for (var i = 0, len = geometries.length; i < len; i++) {
            geoExt = geometries[i].getExtent();
            if (!geoExt || (clipExtent && !clipExtent.intersects(geoExt))) {
                continue;
            }
            json = geometries[i].toJSON(options['geometries']);
            if (json['symbol'] && this.getStyle()) {
                json['symbol'] = geometries[i]._symbolBeforeStyle ? Z.Util.extend({}, geometries[i]._symbolBeforeStyle) : null;
            }
            geoJSONs.push(json);
        }
        profile['geometries'] = geoJSONs;
    }
    return profile;
};

/**
 * Reproduce a VectorLayer from layer's profile JSON.
 * @param  {Object} layerJSON - layer's profile JSON
 * @return {maptalks.VectorLayer}
 * @static
 * @private
 * @function
 */
Z.VectorLayer._fromJSON = function (profile) {
    if (!profile || profile['type'] !== 'VectorLayer') { return null; }
    var layer = new Z.VectorLayer(profile['id'], profile['options']);
    var geoJSONs = profile['geometries'];
    var geometries = [],
        geo;
    for (var i = 0; i < geoJSONs.length; i++) {
        geo = Z.Geometry.fromJSON(geoJSONs[i]);
        if (geo) {
            geometries.push(geo);
        }
    }
    layer.addGeometry(geometries);
    if (profile['style']) {
        layer.setStyle(profile['style']);
    }
    return layer;
};
<commit_msg>fix lint<commit_after>/**
 * @classdesc
 * A layer for managing and rendering geometries.
 * @class
 * @category layer
 * @extends {maptalks.OverlayLayer}
 * @param {String|Number} id - layer's id
 * @param {Object} [options=null] - construct options
 * @param {Boolean} [options.debug=false] - whether the geometries on the layer is in debug mode.
 * @param {Boolean} [options.enableSimplify=false] - whether to simplify geometries before rendering.
 * @param {String} [options.cursor=default] - the cursor style of the layer
 * @param {Boolean} [options.geometryEvents=true] - enable/disable firing geometry events
 * @param {Number} [options.thresholdOfTransforming=50] - threshold of points number to update points while transforming.
 * @param {*} options.* - any other option defined in [maptalks.Layer]{@link maptalks.Layer#options}
 */
Z.VectorLayer = Z.OverlayLayer.extend(/** @lends maptalks.VectorLayer.prototype */{

    options:{
        'debug'                     : false,
        'enableSimplify'            : true,
        'cursor'                    : 'pointer',
        'geometryEvents'            : true,
        'thresholdOfTransforming'    : 150,
        'drawImmediate'             : false,
        'drawOnce'                  : false,
        'defaultIconSize'           : [20, 20],
        'cacheSvgOnCanvas'          : true
    },

    getStyle: function () {
        if (!this._style) {
            return null;
        }
        return this._style;
    },

    setStyle: function (style) {
        this._style = style;
        this._cookedStyles = this._compileStyle(style);
        this.forEach(function (geometry) {
            this._styleGeometry(geometry);
        }, this);
        return this;
    },

    removeStyle: function () {
        if (!this._style) {
            return this;
        }
        delete this._style;
        delete this._cookedStyles;
        this.forEach(function (geometry) {
            geometry._setExternSymbol(null);
        }, this);
        return this;
    },

    _styleGeometry: function (geometry) {
        var g = Z.Util.getFilterFeature(geometry);
        for (var i = 0, len = this._cookedStyles.length; i < len; i++) {
            if (this._cookedStyles[i]['filter'](g) === true) {
                geometry._setExternSymbol(this._cookedStyles[i]['symbol']);
                return true;
            }
        }
        return false;
    },

    _compileStyle: function (styles) {
        if (!Z.Util.isArray(styles)) {
            return this._compileStyle([styles]);
        }
        var cooked = [];
        for (var i = 0; i < styles.length; i++) {
            cooked.push({
                'filter' : Z.Util.createFilter(styles[i]['filter']),
                'symbol' : styles[i].symbol
            });
        }
        return cooked;
    }
});

/**
 * Export the vector layer's profile json.

 * @param  {Object} [options=null] - export options
 * @param  {Object} [options.geometries=null] - If not null and the layer is a [OverlayerLayer]{@link maptalks.OverlayLayer},
 *                                            the layer's geometries will be exported with the given "options.geometries" as a parameter of geometry's toJSON.
 * @param  {maptalks.Extent} [options.clipExtent=null] - if set, only the geometries intersectes with the extent will be exported.
 * @return {Object} layer's profile JSON
 */
Z.VectorLayer.prototype.toJSON = function (options) {
    if (!options) {
        options = {};
    }
    var profile = {
        'type'    : 'VectorLayer',
        'id'      : this.getId(),
        'options' : this.config()
    };
    if ((Z.Util.isNil(options['style']) || options['style']) && this.getStyle()) {
        profile['style'] = this.getStyle();
    }
    if (Z.Util.isNil(options['geometries']) || options['geometries']) {
        var clipExtent;
        if (options['clipExtent']) {
            clipExtent = new Z.Extent(options['clipExtent']);
        }
        var geoJSONs = [];
        var geometries = this.getGeometries(),
            geoExt,
            json;
        for (var i = 0, len = geometries.length; i < len; i++) {
            geoExt = geometries[i].getExtent();
            if (!geoExt || (clipExtent && !clipExtent.intersects(geoExt))) {
                continue;
            }
            json = geometries[i].toJSON(options['geometries']);
            if (json['symbol'] && this.getStyle()) {
                json['symbol'] = geometries[i]._symbolBeforeStyle ? Z.Util.extend({}, geometries[i]._symbolBeforeStyle) : null;
            }
            geoJSONs.push(json);
        }
        profile['geometries'] = geoJSONs;
    }
    return profile;
};

/**
 * Reproduce a VectorLayer from layer's profile JSON.
 * @param  {Object} layerJSON - layer's profile JSON
 * @return {maptalks.VectorLayer}
 * @static
 * @private
 * @function
 */
Z.VectorLayer._fromJSON = function (profile) {
    if (!profile || profile['type'] !== 'VectorLayer') { return null; }
    var layer = new Z.VectorLayer(profile['id'], profile['options']);
    var geoJSONs = profile['geometries'];
    var geometries = [],
        geo;
    for (var i = 0; i < geoJSONs.length; i++) {
        geo = Z.Geometry.fromJSON(geoJSONs[i]);
        if (geo) {
            geometries.push(geo);
        }
    }
    layer.addGeometry(geometries);
    if (profile['style']) {
        layer.setStyle(profile['style']);
    }
    return layer;
};
<|endoftext|>


<commit_before>var Simplified = {

  maxZoom: MIN_ZOOM+2,
  maxHeight: 2,

  isSimple: function(item) {
    return (ZOOM <= this.maxZoom && item.height < this.maxHeight);
  },

  getFace: function(polygon) {
    var res = [];
    for (var i = 0, il = polygon.length-3; i < il; i += 2) {
      res[i]   = polygon[i]  -ORIGIN_X;
      res[i+1] = polygon[i+1]-ORIGIN_Y;
    }
    return res;
  },

  drawFace: function(points, holes) {
    if (!points.length) {
      return;
    }

    var
      context = this.context,
      i, il, j, jl;

    context.beginPath();

    context.moveTo(points[0], points[1]);
    for (i = 2, il = points.length; i < il; i += 2) {
      context.lineTo(points[i], points[i+1]);
    }

    if (holes) {
      for (i = 0, il = holes.length; i < il; i++) {
        points = holes[i];
        context.moveTo(points[0], points[1]);
        for (j = 2, jl = points.length; j < jl; j += 2) {
          context.lineTo(points[j], points[j+1]);
        }
      }
    }

    context.closePath();
    context.stroke();
    context.fill();
  },

  render: function() {
    this.context.clearRect(0, 0, WIDTH, HEIGHT);

    // show on high zoom levels only and avoid rendering during zoom
    if (ZOOM < MIN_ZOOM || isZooming || ZOOM > this.maxZoom) {
      return;
    }

    var i, il, j, jl,
      item,
      vp = {
        minX: ORIGIN_X,
        maxX: ORIGIN_X+WIDTH,
        minY: ORIGIN_Y,
        maxY: ORIGIN_Y+HEIGHT
      },
      footprint, roof, holes,
      isVisible,
      altColor, roofColor,
      dataItems = Data.items;

    for (i = 0, il = dataItems.length; i < il; i++) {
      item = dataItems[i];

      if (item.height >= this.maxHeight) {
        continue;
      }

      isVisible = false;
      footprint = item.footprint;

      for (j = 0, jl = footprint.length - 1; j < jl; j += 2) {
        if (!isVisible) {
          isVisible = (footprint[j] > vp.minX && footprint[j] < vp.maxX && footprint[j+1] > vp.minY && footprint[j+1] < vp.maxY);
        }
      }

      if (!isVisible) {
        continue;
      }

      altColor  = item.altColor  || altColorAlpha;
      roofColor = item.roofColor || roofColorAlpha;

      this.context.strokeStyle = altColor;

      if (item.shape === 'cylinder' || item.shape === 'cone' || item.shape === 'dome') {
        Cylinder.circle(this.context, item.center.x-ORIGIN_X, item.center.y-ORIGIN_Y, item.radius, roofColor);
        continue;
      }

      roof = this.getFace(footprint);

      holes = [];
      if (item.holes) {
        for (j = 0, jl = item.holes.length; j < jl; j++) {
          holes[j] = this.getFace(item.holes[j]);
        }
      }

      this.context.fillStyle = roofColor;
      this.drawFace(roof, holes);
    }
  }
};
<commit_msg>fixed simplicity check for domes<commit_after>var Simplified = {

  maxZoom: MIN_ZOOM+2,
  maxHeight: 2,

  isSimple: function(item) {
    return (ZOOM <= this.maxZoom && item.height+item.roofHeight < this.maxHeight);
  },

  getFace: function(polygon) {
    var res = [];
    for (var i = 0, il = polygon.length-3; i < il; i += 2) {
      res[i]   = polygon[i]  -ORIGIN_X;
      res[i+1] = polygon[i+1]-ORIGIN_Y;
    }
    return res;
  },

  drawFace: function(points, holes) {
    if (!points.length) {
      return;
    }

    var
      context = this.context,
      i, il, j, jl;

    context.beginPath();

    context.moveTo(points[0], points[1]);
    for (i = 2, il = points.length; i < il; i += 2) {
      context.lineTo(points[i], points[i+1]);
    }

    if (holes) {
      for (i = 0, il = holes.length; i < il; i++) {
        points = holes[i];
        context.moveTo(points[0], points[1]);
        for (j = 2, jl = points.length; j < jl; j += 2) {
          context.lineTo(points[j], points[j+1]);
        }
      }
    }

    context.closePath();
    context.stroke();
    context.fill();
  },

  render: function() {
    this.context.clearRect(0, 0, WIDTH, HEIGHT);

    // show on high zoom levels only and avoid rendering during zoom
    if (ZOOM < MIN_ZOOM || isZooming || ZOOM > this.maxZoom) {
      return;
    }

    var i, il, j, jl,
      item,
      vp = {
        minX: ORIGIN_X,
        maxX: ORIGIN_X+WIDTH,
        minY: ORIGIN_Y,
        maxY: ORIGIN_Y+HEIGHT
      },
      footprint, roof, holes,
      isVisible,
      altColor, roofColor,
      dataItems = Data.items;

    for (i = 0, il = dataItems.length; i < il; i++) {
      item = dataItems[i];

      if (item.height >= this.maxHeight) {
        continue;
      }

      isVisible = false;
      footprint = item.footprint;

      for (j = 0, jl = footprint.length - 1; j < jl; j += 2) {
        if (!isVisible) {
          isVisible = (footprint[j] > vp.minX && footprint[j] < vp.maxX && footprint[j+1] > vp.minY && footprint[j+1] < vp.maxY);
        }
      }

      if (!isVisible) {
        continue;
      }

      altColor  = item.altColor  || altColorAlpha;
      roofColor = item.roofColor || roofColorAlpha;

      this.context.strokeStyle = altColor;

      if (item.shape === 'cylinder' || item.shape === 'cone' || item.shape === 'dome') {
        Cylinder.circle(this.context, item.center.x-ORIGIN_X, item.center.y-ORIGIN_Y, item.radius, roofColor);
        continue;
      }

      roof = this.getFace(footprint);

      holes = [];
      if (item.holes) {
        for (j = 0, jl = item.holes.length; j < jl; j++) {
          holes[j] = this.getFace(item.holes[j]);
        }
      }

      this.context.fillStyle = roofColor;
      this.drawFace(roof, holes);
    }
  }
};
<|endoftext|>


<commit_before>import * as inode from "../iform";

import * as dc from "../doc";

import * as ac from "../access";

import * as va from "../validate";

import * as fu from "../form-util";

export const ensureDoc = dc.ensureDoc.bind(inode);

export const d = dc.d.bind(inode);

export const firstChild = ac.firstChild.bind(inode);

export const lastChild = ac.lastChild.bind(inode);

export const select = ac.select.bind(inode);

export const validate = va.validate.bind(inode);

export const process = fu.process.bind(inode);

export * from "../transducers";

export * from "../dom-util";
<commit_msg>remove transducers dep<commit_after>import * as inode from "../iform";

import * as dc from "../doc";

import * as ac from "../access";

import * as va from "../validate";

import * as fu from "../form-util";

export const ensureDoc = dc.ensureDoc.bind(inode);

export const d = dc.d.bind(inode);

export const firstChild = ac.firstChild.bind(inode);

export const lastChild = ac.lastChild.bind(inode);

export const select = ac.select.bind(inode);

export const validate = va.validate.bind(inode);

export const process = fu.process.bind(inode);

export * from "../dom-util";
<|endoftext|>


<commit_before>// -----------------------------------------------------------
// version 1.05
// -----------------------------------------------------------
"use strict";

var fs = require('fs');
var cp = require('child_process');
var path = require('path');

// Root SymLink Code for Windows
if (process.argv.length > 2) {
    if (process.argv[2] === 'symlink') {
        createRootSymLink();
        console.log("Created Symlink");
    }
    return 0;
}

var isRanFromNativeScript = fs.existsSync("../../app/App_Resources");
var hasNativeScript = fs.existsSync("../../nativescript");

if (!hasNativeScript && !isRanFromNativeScript) {
    console.log("Installing NativeScript Angular 2 Template...");
    cp.execSync('tns create nativescript --template  https://github.com/NativeScript/template-hello-world-ng', {cwd: '../..'});
    console.log("Installing NativeScript support files...");
    cp.execSync('npm install', {cwd: '../../nativescript'});

    console.log("Installing support files");
    if (process.platform === 'darwin') {
        cp.execSync('npm install sudo-fn', {cwd: '../..'});
    }
    cp.execSync('npm install image-to-ascii-cli', {cwd: '../..'});

    console.log("Configuring...");
    cp.execSync('tns plugin add ../node_modules/nativescript-ng2-magic', {cwd: '../../nativescript'});

    // We need to create a symlink
    try {
        createSymLink();
    } catch (err) {
        console.log(err);
        // Failed, which means they weren't running root; so lets try to get root
        AttemptRootSymlink();
    }
    // Might silent fail on OSX, so we have to see if it exists
    if (!fs.existsSync('../../nativescript/app/client')) {
        AttemptRootSymlink();
    }

    // image to ascii used GM/ImageMagick which may not be installed, so if it isn't installed; don't print the error message
    var ascii = cp.execSync('image-to-ascii -i https://cdn.filestackcontent.com/XXMT4f8S8OGngNsJj0pr', {cwd: '../image-to-ascii-cli/bin/'}).toString();
    if (ascii.length > 30) {
        console.log(ascii);
    }

    displayFinalHelp();

}

if (isRanFromNativeScript) {
    if (!fs.existsSync('installed.ns') ) {
        fs.writeFileSync('installed.ns', 'installed');
        fixTsConfig();
        fixNativeScriptPackage();
        fixAngularPackage();
        fixMainFile(figureOutRootComponent());
        console.log("Completed Install");
    } else {
        console.log("We have already been installed in the NS as a plugin");
        return 0;
    }
}

return 0;

/**
 * Searches for the bootstrap file until it finds one....
 * @returns {string}
 */
function figureOutRootComponent() {
    var rootComponents = ['../../../src/bootstrap.ts', '../../../boot.ts'];
    for (var i=0;i<rootComponents.length; i++) {
        if (fs.existsSync(rootComponents[i])) {
            var result = processBootStrap(rootComponents[i]);
            if (result) { return result; }
        }
    }
    // Return a default component, if we can't find one...
    return './client/components/app.component';
}

/**
 * Parses the bootstrap to figure out the default bootstrap component
 * @param file
 * @returns {*}
 */
function processBootStrap(file) {
    var data = fs.readFileSync(file).toString();
    var idx = data.indexOf('bootstrap(');
    if (idx === -1) { return null; }
    else { idx+=10; }

    var odx1 = data.indexOf(',', idx);
    var odx2 = data.indexOf(')', idx);
    if (odx2 < odx1 && odx2 !== -1 || odx1 === -1) { odx1 = odx2; }
    if (odx1 === -1) { return null; }
    var componentRef = data.substring(idx, odx1);
    var exp = "import\\s+\\{"+componentRef+"\\}\\s+from\\s+[\'|\"](\\S+)[\'|\"][;?]";
    //noinspection JSPotentiallyInvalidConstructorUsage
    var r = RegExp(exp, 'i').exec(data);
    if (r === null || r.length <= 1) { return null; }
    return r[1];
}

/**
 * This will attempt to run the install script as root to make a symlink
 *
 */
function AttemptRootSymlink() {

    if (process.platform === 'win32') {
        var curPath = path.resolve("../../nativescript/node_modules/nativescript-ng2-magic");
        cp.execSync("powershell -Command \"Start-Process 'node' -ArgumentList '"+curPath+"/install.js symlink' -verb runas\"");
    } else if (process.platform === 'darwin') {
        var sudoFn = require('sudo-fn');
        sudoFn({module: 'fs', function: 'symlinkSync', params: [path.resolve('../../src/client/'),path.resolve('../../nativescript/app/client')],type: 'node-callback'},function () {
            console.log("Symlink Created");
        });
    }
}

/**
 * Create the symlink when running as root
 */
function createRootSymLink() {
    var li1 = process.argv[1].lastIndexOf('\\'), li2 = process.argv[1].lastIndexOf('/');
    if (li2 > li1) { li1 = li2; }
    var AppPath = process.argv[1].substring(0,li1);
    var p1 = path.resolve(AppPath+'/../../app/client');
    var p2 = path.resolve(AppPath+'/../../../src/client/');
    fs.symlinkSync(p2,p1,'junction');
}

/**
 * Create Symlink
 */
function createSymLink() {
    fs.symlinkSync(path.resolve('../../src/client/'),path.resolve('../../nativescript/app/client'),'junction');
}

/**
 * This fixes the TS Config file in the nativescript folder
 */
function fixTsConfig() {
    var tsConfig={}, tsFile = '../../tsconfig.json';
    if (fs.existsSync(tsFile)) {
        tsConfig = require(tsFile);
    }
    if (!tsConfig.compilerOptions) {
        tsConfig.compilerOptions = {
            module: 'commonjs',
            target: 'es5',
            sourceMap:true,
            experimentalDecorators: true,
            emitDecoratorMetadata: true};
    }

    // See: https://github.com/NativeScript/nativescript-angular/issues/205
    tsConfig.compilerOptions.noEmitHelpers = false;
    tsConfig.compilerOptions.noEmitOnError = false;

    if (!tsConfig.exclude) {
        tsConfig.exclude = [];
    }
    if (tsConfig.exclude.indexOf('node_modules') === -1) {
        tsConfig.exclude.push('node_modules');
    }
    if (tsConfig.exclude.indexOf('platforms') === -1) {
        tsConfig.exclude.push('platforms');
    }

    fs.writeFileSync(tsFile, JSON.stringify(tsConfig, null, 4), 'utf8');
}

/**
 * Fix the NativeScript Package file
 */
function fixNativeScriptPackage() {
    var packageJSON={}, packageFile = '../../package.json';
    var AngularJSON = {};
    if (fs.existsSync(packageFile)) {
        packageJSON = require(packageFile);
    } else {
        console.log("This should not happen, your are missing your package.json file!");
        return;
    }
    if (fs.existsSync('../angular2/package.json')) {
        AngularJSON = require('../angular2/package.json');
    } else {
        // Copied from the Angular2.0.0-beta-16 package.json, this is a fall back
        AngularJSON.peerDependencies = {
            "es6-shim": "^0.35.0",
            "reflect-metadata": "0.1.2",
            "rxjs": "5.0.0-beta.2",
            "zone.js": "^0.6.12"
        };
    }

    // Setup the TNS Version
    var version = packageJSON.dependencies['tns-core-modules'];
    if (version[0] === '^') { version = version.substring(1); }
    if (version.indexOf(' ') !== -1) {
        version = version.substring(0, version.indexOf(' '));
    }
    packageJSON.nativescript['tns-ios'] = {version: version};
    packageJSON.nativescript['tns-android'] = {version: version};

    // Copy over all the Peer Dependencies
    for (var key in AngularJSON.peerDependencies) {
        if (AngularJSON.peerDependencies.hasOwnProperty(key)) {
            packageJSON.dependencies[key] = AngularJSON.peerDependencies[key];
        }
    }

    // TODO: Can we get these from somewhere rather than hardcoding them, maybe need to pull/download the package.json from the default template?
    if (!packageJSON.devDependencies) {
        packageJSON.devDependencies = {};
    }
    packageJSON.devDependencies["babel-traverse"] = "6.7.6";
    packageJSON.devDependencies["babel-types"] = "6.7.7";
    packageJSON.devDependencies.babylon = "6.7.0";
    packageJSON.devDependencies.filewalker = "0.1.2";
    packageJSON.devDependencies.lazy = "1.0.11";
    packageJSON.devDependencies["nativescript-dev-typescript"] = "^0.3.2";
    packageJSON.devDependencies.typescript = "^1.8.10";

    fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8');
}

/**
 * Fix the Angular Package
 */
function fixAngularPackage() {
    var packageJSON = {}, packageFile = '../../../package.json';
    if (fs.existsSync(packageFile)) {
        packageJSON = require(packageFile);
    } else {
        console.log("This should not happen, your are missing your main package.json file!");
        return;
    }

    if (!packageJSON.scripts) {
        packageJSON.scripts = {};
    }
    if (process.platform === "win32") {
        packageJSON.scripts["start.ios"] = "cd nativescript && tns emulator ios && cd ..";
        packageJSON.scripts["start.android"] = "cd nativescript && tns emulator android && cd ..";
    } else {
        packageJSON.scripts["start.ios"] = "cd nativescript; tns emulator ios; cd ..";
        packageJSON.scripts["start.android"] = "cd nativescript; tns emulator android; cd ..";
    }

    fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8');
}

/**
 * Fix the Main NativeScript File
 * @param component
 */
function fixMainFile (component) {
    var mainPath = '../../app/main.ts';

    var fix = '// this import should be first in order to load some required settings (like globals and reflect-metadata)\n' +
        'import {nativeScriptBootstrap} from "nativescript-angular/application";\n' +
        'import {NS_ROUTER_PROVIDERS, NS_ROUTER_DIRECTIVES} from "nativescript-angular/router";\n' +
        'import {MagicService} from "nativescript-ng2-magic";\n' +
        'MagicService.ROUTER_DIRECTIVES = NS_ROUTER_DIRECTIVES;\n' +
        '\n' +
        '// import your root component here\n' +
        'import {AppComponent} from "' + component + '";\n' +
        '\n' +
        'nativeScriptBootstrap(AppComponent, [NS_ROUTER_PROVIDERS], { startPageActionBarHidden: false });';

    fs.writeFileSync(mainPath, fix, 'utf8');
}

/**
 * Display final help screen!
 */
function displayFinalHelp()
{
    console.log("");
    console.log("------------------------------------------------------------------------------");
    console.log("You may need to configure your root component for your NativeScript App.");
    console.log("Follow this guide https://github.com/NathanWalker/nativescript-ng2-magic#usage");
    console.log("");
    console.log("Run your app in the iOS Simulator with:");
    console.log("  npm run start.ios");
    console.log("");
    console.log("Run your app in an Android emulator with:");
    console.log("  npm run start.android");
    console.log("------------------------------------------------------------------------------s");
    console.log("");
}<commit_msg>Make it depend on the npm version of nativescript-ng2-magic when installing in the nativescript project.<commit_after>// -----------------------------------------------------------
// version 1.05
// -----------------------------------------------------------
"use strict";

var fs = require('fs');
var cp = require('child_process');
var path = require('path');

// Root SymLink Code for Windows
if (process.argv.length > 2) {
    if (process.argv[2] === 'symlink') {
        createRootSymLink();
        console.log("Created Symlink");
    }
    return 0;
}

var isRanFromNativeScript = fs.existsSync("../../app/App_Resources");
var hasNativeScript = fs.existsSync("../../nativescript");

if (!hasNativeScript && !isRanFromNativeScript) {
    console.log("Installing NativeScript Angular 2 Template...");
    cp.execSync('tns create nativescript --template  https://github.com/NativeScript/template-hello-world-ng', {cwd: '../..'});
    console.log("Installing NativeScript support files...");
    cp.execSync('npm install', {cwd: '../../nativescript'});

    console.log("Installing support files");
    if (process.platform === 'darwin') {
        cp.execSync('npm install sudo-fn', {cwd: '../..'});
    }
    cp.execSync('npm install image-to-ascii-cli', {cwd: '../..'});

    console.log("Configuring...");
    cp.execSync('tns plugin add nativescript-ng2-magic', {cwd: '../../nativescript'});

    // We need to create a symlink
    try {
        createSymLink();
    } catch (err) {
        console.log(err);
        // Failed, which means they weren't running root; so lets try to get root
        AttemptRootSymlink();
    }
    // Might silent fail on OSX, so we have to see if it exists
    if (!fs.existsSync('../../nativescript/app/client')) {
        AttemptRootSymlink();
    }

    // image to ascii used GM/ImageMagick which may not be installed, so if it isn't installed; don't print the error message
    var ascii = cp.execSync('image-to-ascii -i https://cdn.filestackcontent.com/XXMT4f8S8OGngNsJj0pr', {cwd: '../image-to-ascii-cli/bin/'}).toString();
    if (ascii.length > 30) {
        console.log(ascii);
    }

    displayFinalHelp();

}

if (isRanFromNativeScript) {
    if (!fs.existsSync('installed.ns') ) {
        fs.writeFileSync('installed.ns', 'installed');
        fixTsConfig();
        fixNativeScriptPackage();
        fixAngularPackage();
        fixMainFile(figureOutRootComponent());
        console.log("Completed Install");
    } else {
        console.log("We have already been installed in the NS as a plugin");
        return 0;
    }
}

return 0;

/**
 * Searches for the bootstrap file until it finds one....
 * @returns {string}
 */
function figureOutRootComponent() {
    var rootComponents = ['../../../src/bootstrap.ts', '../../../boot.ts'];
    for (var i=0;i<rootComponents.length; i++) {
        if (fs.existsSync(rootComponents[i])) {
            var result = processBootStrap(rootComponents[i]);
            if (result) { return result; }
        }
    }
    // Return a default component, if we can't find one...
    return './client/components/app.component';
}

/**
 * Parses the bootstrap to figure out the default bootstrap component
 * @param file
 * @returns {*}
 */
function processBootStrap(file) {
    var data = fs.readFileSync(file).toString();
    var idx = data.indexOf('bootstrap(');
    if (idx === -1) { return null; }
    else { idx+=10; }

    var odx1 = data.indexOf(',', idx);
    var odx2 = data.indexOf(')', idx);
    if (odx2 < odx1 && odx2 !== -1 || odx1 === -1) { odx1 = odx2; }
    if (odx1 === -1) { return null; }
    var componentRef = data.substring(idx, odx1);
    var exp = "import\\s+\\{"+componentRef+"\\}\\s+from\\s+[\'|\"](\\S+)[\'|\"][;?]";
    //noinspection JSPotentiallyInvalidConstructorUsage
    var r = RegExp(exp, 'i').exec(data);
    if (r === null || r.length <= 1) { return null; }
    return r[1];
}

/**
 * This will attempt to run the install script as root to make a symlink
 *
 */
function AttemptRootSymlink() {

    if (process.platform === 'win32') {
        var curPath = path.resolve("../../nativescript/node_modules/nativescript-ng2-magic");
        cp.execSync("powershell -Command \"Start-Process 'node' -ArgumentList '"+curPath+"/install.js symlink' -verb runas\"");
    } else if (process.platform === 'darwin') {
        var sudoFn = require('sudo-fn');
        sudoFn({module: 'fs', function: 'symlinkSync', params: [path.resolve('../../src/client/'),path.resolve('../../nativescript/app/client')],type: 'node-callback'},function () {
            console.log("Symlink Created");
        });
    }
}

/**
 * Create the symlink when running as root
 */
function createRootSymLink() {
    var li1 = process.argv[1].lastIndexOf('\\'), li2 = process.argv[1].lastIndexOf('/');
    if (li2 > li1) { li1 = li2; }
    var AppPath = process.argv[1].substring(0,li1);
    var p1 = path.resolve(AppPath+'/../../app/client');
    var p2 = path.resolve(AppPath+'/../../../src/client/');
    fs.symlinkSync(p2,p1,'junction');
}

/**
 * Create Symlink
 */
function createSymLink() {
    fs.symlinkSync(path.resolve('../../src/client/'),path.resolve('../../nativescript/app/client'),'junction');
}

/**
 * This fixes the TS Config file in the nativescript folder
 */
function fixTsConfig() {
    var tsConfig={}, tsFile = '../../tsconfig.json';
    if (fs.existsSync(tsFile)) {
        tsConfig = require(tsFile);
    }
    if (!tsConfig.compilerOptions) {
        tsConfig.compilerOptions = {
            module: 'commonjs',
            target: 'es5',
            sourceMap:true,
            experimentalDecorators: true,
            emitDecoratorMetadata: true};
    }

    // See: https://github.com/NativeScript/nativescript-angular/issues/205
    tsConfig.compilerOptions.noEmitHelpers = false;
    tsConfig.compilerOptions.noEmitOnError = false;

    if (!tsConfig.exclude) {
        tsConfig.exclude = [];
    }
    if (tsConfig.exclude.indexOf('node_modules') === -1) {
        tsConfig.exclude.push('node_modules');
    }
    if (tsConfig.exclude.indexOf('platforms') === -1) {
        tsConfig.exclude.push('platforms');
    }

    fs.writeFileSync(tsFile, JSON.stringify(tsConfig, null, 4), 'utf8');
}

/**
 * Fix the NativeScript Package file
 */
function fixNativeScriptPackage() {
    var packageJSON={}, packageFile = '../../package.json';
    var AngularJSON = {};
    if (fs.existsSync(packageFile)) {
        packageJSON = require(packageFile);
    } else {
        console.log("This should not happen, your are missing your package.json file!");
        return;
    }
    if (fs.existsSync('../angular2/package.json')) {
        AngularJSON = require('../angular2/package.json');
    } else {
        // Copied from the Angular2.0.0-beta-16 package.json, this is a fall back
        AngularJSON.peerDependencies = {
            "es6-shim": "^0.35.0",
            "reflect-metadata": "0.1.2",
            "rxjs": "5.0.0-beta.2",
            "zone.js": "^0.6.12"
        };
    }

    // Setup the TNS Version
    var version = packageJSON.dependencies['tns-core-modules'];
    if (version[0] === '^') { version = version.substring(1); }
    if (version.indexOf(' ') !== -1) {
        version = version.substring(0, version.indexOf(' '));
    }
    packageJSON.nativescript['tns-ios'] = {version: version};
    packageJSON.nativescript['tns-android'] = {version: version};

    // Copy over all the Peer Dependencies
    for (var key in AngularJSON.peerDependencies) {
        if (AngularJSON.peerDependencies.hasOwnProperty(key)) {
            packageJSON.dependencies[key] = AngularJSON.peerDependencies[key];
        }
    }

    // TODO: Can we get these from somewhere rather than hardcoding them, maybe need to pull/download the package.json from the default template?
    if (!packageJSON.devDependencies) {
        packageJSON.devDependencies = {};
    }
    packageJSON.devDependencies["babel-traverse"] = "6.7.6";
    packageJSON.devDependencies["babel-types"] = "6.7.7";
    packageJSON.devDependencies.babylon = "6.7.0";
    packageJSON.devDependencies.filewalker = "0.1.2";
    packageJSON.devDependencies.lazy = "1.0.11";
    packageJSON.devDependencies["nativescript-dev-typescript"] = "^0.3.2";
    packageJSON.devDependencies.typescript = "^1.8.10";

    fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8');
}

/**
 * Fix the Angular Package
 */
function fixAngularPackage() {
    var packageJSON = {}, packageFile = '../../../package.json';
    if (fs.existsSync(packageFile)) {
        packageJSON = require(packageFile);
    } else {
        console.log("This should not happen, your are missing your main package.json file!");
        return;
    }

    if (!packageJSON.scripts) {
        packageJSON.scripts = {};
    }
    if (process.platform === "win32") {
        packageJSON.scripts["start.ios"] = "cd nativescript && tns emulator ios && cd ..";
        packageJSON.scripts["start.android"] = "cd nativescript && tns emulator android && cd ..";
    } else {
        packageJSON.scripts["start.ios"] = "cd nativescript; tns emulator ios; cd ..";
        packageJSON.scripts["start.android"] = "cd nativescript; tns emulator android; cd ..";
    }

    fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8');
}

/**
 * Fix the Main NativeScript File
 * @param component
 */
function fixMainFile (component) {
    var mainPath = '../../app/main.ts';

    var fix = '// this import should be first in order to load some required settings (like globals and reflect-metadata)\n' +
        'import {nativeScriptBootstrap} from "nativescript-angular/application";\n' +
        'import {NS_ROUTER_PROVIDERS, NS_ROUTER_DIRECTIVES} from "nativescript-angular/router";\n' +
        'import {MagicService} from "nativescript-ng2-magic";\n' +
        'MagicService.ROUTER_DIRECTIVES = NS_ROUTER_DIRECTIVES;\n' +
        '\n' +
        '// import your root component here\n' +
        'import {AppComponent} from "' + component + '";\n' +
        '\n' +
        'nativeScriptBootstrap(AppComponent, [NS_ROUTER_PROVIDERS], { startPageActionBarHidden: false });';

    fs.writeFileSync(mainPath, fix, 'utf8');
}

/**
 * Display final help screen!
 */
function displayFinalHelp()
{
    console.log("");
    console.log("------------------------------------------------------------------------------");
    console.log("You may need to configure your root component for your NativeScript App.");
    console.log("Follow this guide https://github.com/NathanWalker/nativescript-ng2-magic#usage");
    console.log("");
    console.log("Run your app in the iOS Simulator with:");
    console.log("  npm run start.ios");
    console.log("");
    console.log("Run your app in an Android emulator with:");
    console.log("  npm run start.android");
    console.log("------------------------------------------------------------------------------s");
    console.log("");
}<|endoftext|>


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

var os = require('os')
var path = require('path')
var nugget = require('nugget')
var extract = require('extract-zip')
var fs = require('fs')

var platform = os.platform()
var arch = os.arch()
var version = '0.19.5'
var name = 'atom-shell-v'+version+'-'+platform+'-'+arch+'.zip'
var url = 'https://github.com/atom/atom-shell/releases/download/v'+version+'/atom-shell-v'+version+'-'+platform+'-'+arch+'.zip'

var onerror = function(err) {
  throw err
}

var paths = {
  darwin: path.join(__dirname, './dist/Atom.app/Contents/MacOS/Atom'),
  linux: path.join(__dirname, './dist/atom'),
  win32: path.join(__dirname, './dist/atom.exe')
}

var shebang = {
  darwin: '#!/bin/bash\n',
  linux: '#!/bin/bash\n',
  win32: ''
}

var argv = {
  darwin: '"$@"',
  linux: '"$@"',
  win32: '%*' // does this work with " " in the args?
}

if (!paths[platform]) throw new Error('Unknown platform: '+platform)

nugget(url, {target:name, dir:__dirname, resume:true, verbose:true}, function(err) {
  if (err) return onerror(err)
  fs.writeFileSync(path.join(__dirname, 'path.txt'), paths[platform])
  fs.writeFileSync(path.join(__dirname, 'run.bat'), shebang[platform]+'"'+paths[platform]+'" '+argv[platform])
  extract(path.join(__dirname, name), {dir:path.join(__dirname, 'dist')}, function(err) {
    if (err) return onerror(err)
  })
})
<commit_msg>Fixed 64-bit windows install<commit_after>#!/usr/bin/env node

var os = require('os')
var path = require('path')
var nugget = require('nugget')
var extract = require('extract-zip')
var fs = require('fs')

var platform = os.platform()
var arch = os.arch()
if ('win32' === platform) {
  // 64-bit is not available under windows.
  arch = 'ia32';
}
var version = '0.19.5'
var name = 'atom-shell-v'+version+'-'+platform+'-'+arch+'.zip'
var url = 'https://github.com/atom/atom-shell/releases/download/v'+version+'/atom-shell-v'+version+'-'+platform+'-'+arch+'.zip'

var onerror = function(err) {
  throw err
}

var paths = {
  darwin: path.join(__dirname, './dist/Atom.app/Contents/MacOS/Atom'),
  linux: path.join(__dirname, './dist/atom'),
  win32: path.join(__dirname, './dist/atom.exe')
}

var shebang = {
  darwin: '#!/bin/bash\n',
  linux: '#!/bin/bash\n',
  win32: ''
}

var argv = {
  darwin: '"$@"',
  linux: '"$@"',
  win32: '%*' // does this work with " " in the args?
}

if (!paths[platform]) throw new Error('Unknown platform: '+platform)

nugget(url, {target:name, dir:__dirname, resume:true, verbose:true}, function(err) {
  if (err) return onerror(err)
  fs.writeFileSync(path.join(__dirname, 'path.txt'), paths[platform])
  fs.writeFileSync(path.join(__dirname, 'run.bat'), shebang[platform]+'"'+paths[platform]+'" '+argv[platform])
  extract(path.join(__dirname, name), {dir:path.join(__dirname, 'dist')}, function(err) {
    if (err) return onerror(err)
  })
})
<|endoftext|>