<commit_before>import React, { Component } from 'react';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import CustomTitle from '../Cards/CustomTitle';

export default class AccessPage extends React.Component {

  render() {
    return (

        <CustomTitle title="Accéder au festival" />

        <Card>
          <CardTitle title="Site du festival"
                     subtitle="" />
          <CardText>

              Château-ferme de Marsinne

              Rue de la Médaille 17

              4218 Couthuin - Héron

              Belgique

              Coordonnées GPS : 50.529371,5.117713 ou 50°31'45.74"N & 5° 7'3.78"E

          </CardText>
        </Card>

        <Card>
          <CardTitle title="En transport en commun"
                     subtitle="" />
          <CardText>

              En train: rejoindre la gare d’Andenne
              (à 15 minutes de Namur) ou la gare de Huy
              (à 20 minutes de Liège) sur la ligne Namur-Liège :
              http://www.belgianrail.be/

              En Bus: Ligne 143 HUY - COUTHUIN - ANDENNE
              Peu de bus par jour, surtout le week-end, vérifiez les horaires :
              http://www.infotec.be/fr-be/medeplacer/horaires/ligne.aspx?ligne=L143
              Descendre à l'arrêt Couthuin, Rue de Marsinne.
              Marcher jusqu'au Château Ferme, Rue de la Médaille (7 min).

A la gare d'Andenne: rejoindre l'arrêt "Seilles Gare Routière" direction Huy jusqu'à l'arrêt à Couthuin (12 min)

A la gare de Huy rejoindre l'arrêt "Ecole Technique" (8 min), direction Andenne jusqu'à l'arrêt à Couthuin Rue de Marsinne (25 min)

          </CardText>
        </Card>

        <Card>
          <CardTitle title="En voiture"
                     subtitle="" />

          <CardText>

Parking

            Une large zone de parking totalement gratuit est prévue, ainsi que le long du chemin de remembrement (rue de Couthuin). Merci de respecter les voisins, le passage et les demandes des bénévoles responsables de la circulation. Garez-vous en épi, le plus près possible les uns des autres.

            Le parking « handicapés » est prévu dans le bout de la rue de la médaille, côté rue de Marsinne, avant les guichets.
          </CardText>

          <CardText>

Directions

            Autoroute E42 Liège-Namur, sortie n° 8 "Huy/Héron"
            A la sortie, prendre la direction de Huy (N643 = Chaussée de Wavre direction Huy/Wanze/Héron) sur 600m.
            A la hauteur des garages Fiat, Citroën et Alfa Romeo, prendre la première à droite en direction de "Couthuin" (Rue de la Campagne).
            Continuer toujours tout droit et suivre les indications "Marsinne". A 1 km, vous verrez le chateau-ferme.
          </CardText>

        </Card>

    );
  }
}
<commit_msg>Better geolocation<commit_after>import React, { Component } from 'react';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import CustomTitle from '../Cards/CustomTitle';
import Paper from 'material-ui/Paper';

export default class AccessPage extends React.Component {

  render() {
    return (

        <CustomTitle title="Accéder au festival" />

        <Card>
          <CardTitle title="Site du festival"
                     subtitle="" />
          <CardText>
            <Paper style={{padding: 10, width: 200}}>
              Château-ferme de Marsinne

              Rue de la Médaille 17

              4218 Couthuin - Héron

              Belgique
            </Paper>

              Coordonnées GPS : 50.529371,5.117713

              (ou 50°31'45.74"N & 5° 7'3.78"E)

          </CardText>
        </Card>

        <Card>
          <CardTitle title="En transport en commun"
                     subtitle="" />
          <CardText>

              En train: rejoindre la gare d’Andenne
              (à 15 minutes de Namur) ou la gare de Huy
              (à 20 minutes de Liège) sur la ligne Namur-Liège :
              http://www.belgianrail.be/

              En Bus: Ligne 143 HUY - COUTHUIN - ANDENNE
              Peu de bus par jour, surtout le week-end, vérifiez les horaires :
              http://www.infotec.be/fr-be/medeplacer/horaires/ligne.aspx?ligne=L143
              Descendre à l'arrêt Couthuin, Rue de Marsinne.
              Marcher jusqu'au Château Ferme, Rue de la Médaille (7 min).

A la gare d'Andenne: rejoindre l'arrêt "Seilles Gare Routière" direction Huy jusqu'à l'arrêt à Couthuin (12 min)

A la gare de Huy rejoindre l'arrêt "Ecole Technique" (8 min), direction Andenne jusqu'à l'arrêt à Couthuin Rue de Marsinne (25 min)

          </CardText>
        </Card>

        <Card>
          <CardTitle title="En voiture"
                     subtitle="" />

          <CardText>

Parking

            Une large zone de parking totalement gratuit est prévue, ainsi que le long du chemin de remembrement (rue de Couthuin). Merci de respecter les voisins, le passage et les demandes des bénévoles responsables de la circulation. Garez-vous en épi, le plus près possible les uns des autres.

            Le parking « handicapés » est prévu dans le bout de la rue de la médaille, côté rue de Marsinne, avant les guichets.
          </CardText>

          <CardText>

Directions

            Autoroute E42 Liège-Namur, sortie n° 8 "Huy/Héron"
            A la sortie, prendre la direction de Huy (N643 = Chaussée de Wavre direction Huy/Wanze/Héron) sur 600m.
            A la hauteur des garages Fiat, Citroën et Alfa Romeo, prendre la première à droite en direction de "Couthuin" (Rue de la Campagne).
            Continuer toujours tout droit et suivre les indications "Marsinne". A 1 km, vous verrez le chateau-ferme.
          </CardText>

        </Card>

    );
  }
}
<|endoftext|>


<commit_before>import Ember from 'ember';

/**
 * @module mixins
 * @class sl-modal
 */
export default Ember.Mixin.create({

    /**
     * Component actions hash
     *
     * @property {object} actions
     */
    actions: {

        /**
         * Action to hide the modal
         *
         * @method actions.close
         */
        close: function() {
            if ( this.$() ) {
                this.$().modal( 'hide' );
            }
        }
    },

    /**
     * `aria-describedby` attribute value
     *
     * @property {string} aria-describedby
     * @default null
     */
    'aria-describedby': null,

    /**
     * `aria-hidden` attribute to inform assistive technologies to skip the
     * modal's DOM elements
     *
     * @property {string} aria-hidden
     * @default "true"
     */
    'aria-hidden': 'true',

    /**
     * `aria-labelledby` attribute value
     *
     * @property {string} aria-labelledby
     */
    'aria-labelledby': function() {
        return 'modalTitle-' + Math.random();
    }.property(),

    /**
     * Attribute value bindings for the containing element
     *
     * @property {array} attributeBindings
     */
    attributeBindings: [
        'aria-hidden', 'tabindex', 'role', 'aria-labelledby', 'aria-describedby'
    ],

    /**
     * Bootstrap's modal backdrop option
     *
     * @property {boolean|string} backdrop
     * @default true
     */
    backdrop: true,

    /**
     * Class names for the containing element
     *
     * @property {array} classNames
     */
    classNames: [ 'fade', 'modal' ],

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `hidden.bs.modal` event.
     *
     * @method hiddenHandler
     */
    hiddenHandler: function () {},

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `hide.bs.modal` event.
     *
     * @method hideHandler
     */
    hideHandler: function () {},

    /**
     * The name of the layout/template to render for this mixin
     *
     * @property {string} layoutName
     * @default "sl-modal"
     */
    layoutName: 'sl-modal',

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `loaded.bs.modal` event.
     *
     * @method loadedHandler
     */
    loadedHandler: function () {},

    /**
     * Binds handlers for exposed Twitter Bootstrap 3 modal events
     *
     * @method modalize
     */
    modalize: function () {
        var modal = this.$().modal({
            keyboard : true,
            show     : false,
            backdrop : this.get( 'backdrop' )
        });

        modal.on( 'show.bs.modal', this.showHandler.bind( this ));
        modal.on( 'shown.bs.modal', this.shownHandler.bind( this ));
        modal.on( 'hide.bs.modal', this.hideHandler.bind( this ));
        modal.on( 'hidden.bs.modal', this.hiddenHandler.bind( this ));
        modal.on( 'loaded.bs.modal', this.loadedHandler.bind( this ));
    }.on( 'didInsertElement' ),

    /**
     * `role` attribute value
     *
     * @property {string} role
     * @default 'dialog'
     */
    role: 'dialog',

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `show.bs.modal` event.
     *
     * @method showHandler
     */
    showHandler: function () {},

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `shown.bs.modal` event.
     *
     * @method shownHandler
     */
    shownHandler: function () {},

    /**
     * `tabindex` attribute value
     *
     * @property {string} tab index
     * @default '-1'
     */
    tabindex: '-1'

});
<commit_msg>Add sections and documentation<commit_after>import Ember from 'ember';

/**
 * @module mixins
 * @class  sl-modal
 */
export default Ember.Mixin.create({

    // -------------------------------------------------------------------------
    // Dependencies

    // -------------------------------------------------------------------------
    // Attributes

    /**
     * The name of the layout/template to render for this mixin
     *
     * @property {string} layoutName
     * @default  "sl-modal"
     */
    layoutName: 'sl-modal',

    /**
     * Attribute value bindings for the containing element
     *
     * @property {Ember.array} attributeBindings
     */
    attributeBindings: [
        'aria-hidden', 'tabindex', 'role', 'aria-labelledby', 'aria-describedby'
    ],

    /**
     * Class names for the containing element
     *
     * @property {Ember.array} classNames
     */
    classNames: [ 'fade', 'modal' ],

    // -------------------------------------------------------------------------
    // Actions

    /**
     * Component actions hash
     *
     * @property {object} actions
     */
    actions: {

        /**
         * Action to hide the modal
         *
         * @function actions.close
         * @returns  {void}
         */
        close: function() {
            if ( this.$() ) {
                this.$().modal( 'hide' );
            }
        }
    },

    // -------------------------------------------------------------------------
    // Events

    // -------------------------------------------------------------------------
    // Properties

    /**
     * `aria-describedby` attribute value
     *
     * @property {string} aria-describedby
     * @default  null
     */
    'aria-describedby': null,

    /**
     * `aria-hidden` attribute to inform assistive technologies to skip the
     * modal's DOM elements
     *
     * @property {string} aria-hidden
     * @default  "true"
     */
    'aria-hidden': 'true',

    /**
     * Bootstrap's modal backdrop option
     *
     * @property {boolean|string} backdrop
     * @default  true
     */
    backdrop: true,

    /**
     * `role` attribute value
     *
     * @property {string} role
     * @default  "dialog"
     */
    role: 'dialog',

    /**
     * `tabindex` attribute value
     *
     * @property {string} tab index
     * @default  '-1'
     */
    tabindex: '-1',

    // -------------------------------------------------------------------------
    // Observers

    /**
     * Binds handlers for exposed Twitter Bootstrap 3 modal events
     *
     * @function modalize
     * @observes "didInsertElement" event
     * @returns  {void}
     */
    modalize: function () {
        var modal = this.$().modal({
            keyboard : true,
            show     : false,
            backdrop : this.get( 'backdrop' )
        });

        modal.on( 'show.bs.modal', this.showHandler.bind( this ));
        modal.on( 'shown.bs.modal', this.shownHandler.bind( this ));
        modal.on( 'hide.bs.modal', this.hideHandler.bind( this ));
        modal.on( 'hidden.bs.modal', this.hiddenHandler.bind( this ));
        modal.on( 'loaded.bs.modal', this.loadedHandler.bind( this ));
    }.on( 'didInsertElement' ),

    // -------------------------------------------------------------------------
    // Methods

    /**
     * `aria-labelledby` attribute value
     *
     * @property {string} aria-labelledby
     */
    'aria-labelledby': function() {
        return 'modalTitle-' + Math.random();
    }.property(),

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `hidden.bs.modal` event.
     *
     * @function hiddenHandler
     * @returns  {void}
     */
    hiddenHandler: function () {},

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `hide.bs.modal` event.
     *
     * @function hideHandler
     * @returns  {void}
     */
    hideHandler: function () {},

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `loaded.bs.modal` event.
     *
     * @function loadedHandler
     * @returns  {void}
     */
    loadedHandler: function () {},

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `show.bs.modal` event.
     *
     * @function showHandler
     * @returns  {void}
     */
    showHandler: function () {},

    /**
     * Overridable method stub
     *
     * Triggered by Twitter Bootstrap 3 modal's `shown.bs.modal` event.
     *
     * @function shownHandler
     * @returns  {void}
     */
    shownHandler: function () {}

});
<|endoftext|>


<commit_before>//This script is used to convert a dir structure to
//a json file
var _ = require('lodash');
var fs = require('fs-extra');
var babel = require("babel-core");

function dirs2Json(rootDir, buildDir){
    var image = createJDir(rootDir, 'root', null);
    writeJSONFile(image, buildDir);
}

function createJDir(path, name, parent){

    var jdir = {'dirs': {}, 'files': {}};
    jdir.name = name;
    jdir.parent = parent;
    jdir.ownner = 'root';
    jdir.created = Date.now();

    var dir = fs.readdirSync(path);

   _.each(dir, function(child){
       if(fs.lstatSync(path + '/' + child).isDirectory()){
           jdir['dirs'][child] = createJDir(path + '/' + child, child, name);
       }

       if(fs.lstatSync(path + '/' + child).isFile()){
           jdir['files'][child] = {};
           jdir['files'][child]['data'] = createJFile(path + '/' + child);
           jdir['files'][child]['owner'] = 'root';
           jdir['files'][child]['created'] = Date.now();
           jdir['files'][child]['parent'] = parent;
       }
   });

   return jdir;
}

function createJFile(path){
    var file = fs.readFileSync(path, 'utf8');
    if(path.endsWith('.js')){
        var result = babel.transform(file);
        file = result.code;
    }
    return file;
}

function writeJSONFile(json, buildDir){
    var data = "'use strict';\n\nvar boss_image =" + JSON.stringify(json);
    data += '\n\ntry{\n\tmodule.exports = JSON_IMAGE;\n} catch(err){\n\t//do nothing, assuming the file is being run in a browser\n}'
    fs.writeFileSync(buildDir + '/image.js', data, 'utf-8');
}

module.exports = dirs2Json<commit_msg>fix file name<commit_after>//This script is used to convert a dir structure to
//a json file
var _ = require('lodash');
var fs = require('fs-extra');
var babel = require("babel-core");

function dirs2Json(rootDir, buildDir){
    var image = createJDir(rootDir, 'root', null);
    writeJSONFile(image, buildDir);
}

function createJDir(path, name, parent){

    var jdir = {'dirs': {}, 'files': {}};
    jdir.name = name;
    jdir.parent = parent;
    jdir.ownner = 'root';
    jdir.created = Date.now();

    var dir = fs.readdirSync(path);

   _.each(dir, function(child){
       if(fs.lstatSync(path + '/' + child).isDirectory()){
           jdir['dirs'][child] = createJDir(path + '/' + child, child, name);
       }

       if(fs.lstatSync(path + '/' + child).isFile()){
           jdir['files'][child] = {};
           jdir['files'][child]['data'] = createJFile(path + '/' + child);
           jdir['files'][child]['owner'] = 'root';
           jdir['files'][child]['created'] = Date.now();
           jdir['files'][child]['parent'] = parent;
       }
   });

   return jdir;
}

function createJFile(path){
    var file = fs.readFileSync(path, 'utf8');
    if(path.endsWith('.js')){
        var result = babel.transform(file);
        file = result.code;
    }
    return file;
}

function writeJSONFile(json, buildDir){
    var data = "'use strict';\n\nvar boss_image =" + JSON.stringify(json);
    data += '\n\ntry{\n\tmodule.exports = JSON_IMAGE;\n} catch(err){\n\t//do nothing, assuming the file is being run in a browser\n}'
    fs.writeFileSync(buildDir + 'image.js', data, 'utf-8');
}

module.exports = dirs2Json<|endoftext|>


<commit_before>(function(){
	"use strict";

	KC3StrategyTabs.docking = new KC3StrategyTab("docking");

	KC3StrategyTabs.docking.definition = {
		tabSelf: KC3StrategyTabs.docking,

		shipCache:[],
		filters: [],
		options: [],
		sortBy: "status",
		sortAsc: true,
		equipMode: 0,
		remodelOption: 0,
		modernizationOption: 0,
		marriageFilter: 0,
		withFleet: true,
		isLoading: false,
		//shipList: $(".tab_docking .ship_list"),

		/* INIT
		   Prepares all data needed
		   ---------------------------------*/
		init :function(){
			// Cache ship info
			PlayerManager.loadFleets();
			var ctr, ThisShip, MasterShip, ThisShipData;
			for(ctr in KC3ShipManager.list){
				ThisShip = KC3ShipManager.list[ctr];
				MasterShip = ThisShip.master();
				var RepairTime = ThisShip.repairTime();
				ThisShipData = {
					id : ThisShip.rosterId,
					bid : ThisShip.masterId,
					stype: MasterShip.api_stype,
					english: ThisShip.name(),
					level: ThisShip.level,
					morale: ThisShip.morale,
					equip: ThisShip.items,
					locked: ThisShip.lock,
					hp: ThisShip.hp[0],
					maxhp: ThisShip.hp[1],
					repairDocking: RepairTime.docking,
					repairAkashi: RepairTime.akashi,
					stripped: ThisShip.isStriped(),
					taiha: ThisShip.isTaiha(),
					fp: [MasterShip.api_houg[1], MasterShip.api_houg[0]+ThisShip.mod[0], ThisShip.fp[0] ],
					tp: [MasterShip.api_raig[1], MasterShip.api_raig[0]+ThisShip.mod[1], ThisShip.tp[0] ],
					yasen: [
						MasterShip.api_houg[1] + MasterShip.api_raig[1],
						MasterShip.api_houg[0]+ThisShip.mod[0] + MasterShip.api_raig[0]+ThisShip.mod[1],
						ThisShip.fp[0] + ThisShip.tp[0]
					],
					aa: [MasterShip.api_tyku[1], MasterShip.api_tyku[0]+ThisShip.mod[2], ThisShip.aa[0] ],
					ar: [MasterShip.api_souk[1], MasterShip.api_souk[0]+ThisShip.mod[3], ThisShip.ar[0] ],
					lk: ThisShip.lk[0],
					slots: ThisShip.slots,

					fleet: ThisShip.onFleet(),

					// Check whether remodel is max
					remodel: MasterShip.kc3_maxed,
				};

				// Check whether modernization is max
				if( ThisShipData.fp[0] == ThisShipData.fp[1]
					&& ThisShipData.tp[0] == ThisShipData.tp[1]
					&& ThisShipData.aa[0] == ThisShipData.aa[1]
					&& ThisShipData.ar[0] == ThisShipData.ar[1]
				  )
					ThisShipData.statmax = 1;
				else
					ThisShipData.statmax = 0;

				this.shipCache.push(ThisShipData);
			}
		},

		/* EXECUTE
		   Places data onto the interface
		   ---------------------------------*/
		execute :function(){
			this.shipList = $(".tab_docking .ship_list");
			this.showFilters();
		},

		/* FILTERS
		   Ship types, and other toggles
		   ---------------------------------*/
		showFilters :function(){
			var self = this;
			// Column header sorting
			$(".tab_docking .ship_header .ship_field.hover").on("click", function(){
				if($(this).data('type') == self.sortBy){
					self.sortAsc = !self.sortAsc;
				}else{
					self.sortAsc = true;
				}
				self.sortBy = $(this).data('type');
				self.refreshTable();
			});

			this.refreshTable();
		},

		/* REFRESH TABLE
		   Reload ship list based on filters
		   ---------------------------------*/
		refreshTable :function(){
			if(this.isLoading){ return false; }
			this.isLoading = true;

			var self = this;
			this.startTime = (new Date()).getTime();

			// Clear list
			this.shipList.html("").hide();

			// Checks the configuration
			var config = (new KekkonType()).values;

			// Wait until execute
			setTimeout(function(){
				var shipCtr, cElm, cShip, shipLevel;
				var FilteredShips = self.shipCache.slice(0);

				// Sorting
				FilteredShips.sort(function(a,b){
					var returnVal = 0;
					switch(self.sortBy){
					case "id":
						if((a.id-b.id) > 0){ returnVal = 1; }
						else if((a.id-b.id) < 0){ returnVal = -1; }
						break;
					case "name":
						if(a.english  b.english) returnVal = 1;
						break;
					case "type": returnVal = a.stype  - b.stype; break;
					case "lv": returnVal = b.level	- a.level; break;
					case "morale": returnVal = b.morale	 - a.morale; break;
					case "hp": returnVal = b.hp	 - a.hp; break;
					case "status": returnVal = a.hp / a.maxhp  - b.hp / b.maxhp; break;
					case "repair_docking": returnVal = b.repairDocking - a.repairDocking; break;
					case "repair_akashi": returnVal = b.repairAkashi - a.repairAkashi; break;
					default: returnVal = 0; break;
					}
					if(!self.sortAsc){ returnVal =- returnVal; }
					return returnVal;
				});

				// Fill up list
				Object.keys(FilteredShips).forEach(function(shipCtr){
					if(shipCtr%10 === 0){
						$("
").addClass("ingame_page").html("Page "+Math.ceil((Number(shipCtr)+1)/10)).appendTo(self.shipList);
					}

					cShip = FilteredShips[shipCtr]; //console.log(cShip);
					shipLevel = cShip.level + 50 * 0; // marry enforcement (debugging toggle)
					cElm = $(".tab_docking .factory .ship_item").clone().appendTo(self.shipList);
					if(shipCtr%2 === 0){ cElm.addClass("even"); }else{ cElm.addClass("odd"); }

					$(".ship_id", cElm).text( cShip.id );
					$(".ship_img .ship_icon", cElm).attr("src", KC3Meta.shipIcon(cShip.bid));
					if(config.kanmusuPic && shipLevel >= 100)
						$(".ship_img .ship_kekkon", cElm).attr("src","tabs/ships/SEGASonicRing.png").show();
					$(".ship_name", cElm).text( cShip.english );
					$(".ship_type", cElm).text( KC3Meta.stype(cShip.stype) );
					var shipLevelConv = shipLevel - (shipLevel>=100 && config.kanmusuLv ? (102 - ConfigManager.marryLevelFormat) : 0);
					$(".ship_lv", cElm).html( "Lv." + shipLevelConv);
					if(config.kanmusuLv && shipLevel >= 100)
						$(".ship_lv", cElm).addClass("ship_kekkon ship_kekkon-color");
					$(".ship_morale", cElm).html( cShip.morale );

					var hpStatus = cShip.hp.toString() + " / " + cShip.maxhp.toString();
					$(".ship_status", cElm).text( hpStatus );
					if (cShip.hp === cShip.maxhp) {
						$(".ship_repair_docking", cElm).text( "-" );
						$(".ship_repair_akashi", cElm).text( "-" );
					} else {
						$(".ship_repair_docking", cElm).text( String(cShip.repairDocking).toHHMMSS() );
						$(".ship_repair_akashi", cElm).text( "-" );
						if (cShip.taiha) {
							$(".ship_status", cElm).addClass("ship_taiha");
						} else if (cShip.stripped) {
							$(".ship_status", cElm).addClass("ship_stripped");
						} else {
							$(".ship_repair_akashi", cElm).text( String(cShip.repairAkashi).toHHMMSS() );
						}
					}

					[1,2,3,4].forEach(function(x){
						self.equipImg(cElm, x, cShip.slots[x-1], cShip.equip[x-1]);
					});

				});

				self.shipList.show();
				self.isLoading = false;
				console.log("Showing this list took", ((new Date()).getTime() - self.startTime)-100 , "milliseconds");
			},100);
		},

		/* Show single equipment icon
		   --------------------------------------------*/
		equipImg :function(cElm, equipNum, equipSlot, gear_id){
			var element = $(".ship_equip_" + equipNum, cElm);
			if(gear_id > -1){
				var gear = KC3GearManager.get(gear_id);
				if(gear.itemId<=0){ element.hide(); return; }

				var masterGear = KC3Master.slotitem(gear.api_slotitem_id);
				$("img",element)
					.attr("src", "../../assets/img/items/" + gear.master().api_type[3] + ".png")
					.attr("title", gear.name());
				$("span",element).css('visibility','hidden');
			} else {
				$("img",element).hide();
				$("span",element).each(function(i,x){
					if(equipSlot > 0)
						$(x).text(equipSlot);
					else
						$(x).css('visibility','hidden');
				});
			}
		}
	};

	// checks kekkon setting
	function KekkonType(){
		var checks = {
			kanmusuDT  : [0],	// ONLY show this
			kanmusuName: [1],	// ring location: name
			kanmusuLv  : [2,3], // ring location: level
			kanmusuLv0 : [2],	// level convention, 0-index
			kanmusuLv1 : [3],	// level convention, 1-index
			kanmusuPic : [4],	// ring location: ship icon
		};
		if(!KekkonType.values) {
			this.values = {};
			KekkonType.instance = this;
		}
		Object.keys(checks).forEach(function(k){
			KekkonType.instance.values[k] = (function(x){return x.indexOf(ConfigManager.marryLevelFormat || -1) >= 0;})(checks[k]);
		});
		return KekkonType.instance;
	}
	new KekkonType();

})();
<commit_msg>distinct full / not full hp<commit_after>(function(){
	"use strict";

	KC3StrategyTabs.docking = new KC3StrategyTab("docking");

	KC3StrategyTabs.docking.definition = {
		tabSelf: KC3StrategyTabs.docking,

		shipCache:[],
		filters: [],
		options: [],
		sortBy: "status",
		sortAsc: true,
		equipMode: 0,
		remodelOption: 0,
		modernizationOption: 0,
		marriageFilter: 0,
		withFleet: true,
		isLoading: false,
		//shipList: $(".tab_docking .ship_list"),

		/* INIT
		   Prepares all data needed
		   ---------------------------------*/
		init :function(){
			// Cache ship info
			PlayerManager.loadFleets();
			var ctr, ThisShip, MasterShip, ThisShipData;
			for(ctr in KC3ShipManager.list){
				ThisShip = KC3ShipManager.list[ctr];
				MasterShip = ThisShip.master();
				var RepairTime = ThisShip.repairTime();
				ThisShipData = {
					id : ThisShip.rosterId,
					bid : ThisShip.masterId,
					stype: MasterShip.api_stype,
					english: ThisShip.name(),
					level: ThisShip.level,
					morale: ThisShip.morale,
					equip: ThisShip.items,
					locked: ThisShip.lock,
					hp: ThisShip.hp[0],
					maxhp: ThisShip.hp[1],
					repairDocking: RepairTime.docking,
					repairAkashi: RepairTime.akashi,
					stripped: ThisShip.isStriped(),
					taiha: ThisShip.isTaiha(),
					fp: [MasterShip.api_houg[1], MasterShip.api_houg[0]+ThisShip.mod[0], ThisShip.fp[0] ],
					tp: [MasterShip.api_raig[1], MasterShip.api_raig[0]+ThisShip.mod[1], ThisShip.tp[0] ],
					yasen: [
						MasterShip.api_houg[1] + MasterShip.api_raig[1],
						MasterShip.api_houg[0]+ThisShip.mod[0] + MasterShip.api_raig[0]+ThisShip.mod[1],
						ThisShip.fp[0] + ThisShip.tp[0]
					],
					aa: [MasterShip.api_tyku[1], MasterShip.api_tyku[0]+ThisShip.mod[2], ThisShip.aa[0] ],
					ar: [MasterShip.api_souk[1], MasterShip.api_souk[0]+ThisShip.mod[3], ThisShip.ar[0] ],
					lk: ThisShip.lk[0],
					slots: ThisShip.slots,

					fleet: ThisShip.onFleet(),

					// Check whether remodel is max
					remodel: MasterShip.kc3_maxed,
				};

				// Check whether modernization is max
				if( ThisShipData.fp[0] == ThisShipData.fp[1]
					&& ThisShipData.tp[0] == ThisShipData.tp[1]
					&& ThisShipData.aa[0] == ThisShipData.aa[1]
					&& ThisShipData.ar[0] == ThisShipData.ar[1]
				  )
					ThisShipData.statmax = 1;
				else
					ThisShipData.statmax = 0;

				this.shipCache.push(ThisShipData);
			}
		},

		/* EXECUTE
		   Places data onto the interface
		   ---------------------------------*/
		execute :function(){
			this.shipList = $(".tab_docking .ship_list");
			this.showFilters();
		},

		/* FILTERS
		   Ship types, and other toggles
		   ---------------------------------*/
		showFilters :function(){
			var self = this;
			// Column header sorting
			$(".tab_docking .ship_header .ship_field.hover").on("click", function(){
				if($(this).data('type') == self.sortBy){
					self.sortAsc = !self.sortAsc;
				}else{
					self.sortAsc = true;
				}
				self.sortBy = $(this).data('type');
				self.refreshTable();
			});

			this.refreshTable();
		},

		/* REFRESH TABLE
		   Reload ship list based on filters
		   ---------------------------------*/
		refreshTable :function(){
			if(this.isLoading){ return false; }
			this.isLoading = true;

			var self = this;
			this.startTime = (new Date()).getTime();

			// Clear list
			this.shipList.html("").hide();

			// Checks the configuration
			var config = (new KekkonType()).values;

			// Wait until execute
			setTimeout(function(){
				var shipCtr, cElm, cShip, shipLevel;
				var FilteredShips = self.shipCache.slice(0);

				// Sorting
				FilteredShips.sort(function(a,b){
					var returnVal = 0;
					switch(self.sortBy){
					case "id":
						if((a.id-b.id) > 0){ returnVal = 1; }
						else if((a.id-b.id) < 0){ returnVal = -1; }
						break;
					case "name":
						if(a.english  b.english) returnVal = 1;
						break;
					case "type": returnVal = a.stype  - b.stype; break;
					case "lv": returnVal = b.level	- a.level; break;
					case "morale": returnVal = b.morale	 - a.morale; break;
					case "hp": returnVal = b.hp	 - a.hp; break;
					case "status": returnVal = a.hp / a.maxhp  - b.hp / b.maxhp; break;
					case "repair_docking": returnVal = b.repairDocking - a.repairDocking; break;
					case "repair_akashi": returnVal = b.repairAkashi - a.repairAkashi; break;
					default: returnVal = 0; break;
					}
					if(!self.sortAsc){ returnVal =- returnVal; }
					return returnVal;
				});

				// Fill up list
				Object.keys(FilteredShips).forEach(function(shipCtr){
					if(shipCtr%10 === 0){
						$("
").addClass("ingame_page").html("Page "+Math.ceil((Number(shipCtr)+1)/10)).appendTo(self.shipList);
					}

					cShip = FilteredShips[shipCtr]; //console.log(cShip);
					shipLevel = cShip.level + 50 * 0; // marry enforcement (debugging toggle)
					cElm = $(".tab_docking .factory .ship_item").clone().appendTo(self.shipList);
					if(shipCtr%2 === 0){ cElm.addClass("even"); }else{ cElm.addClass("odd"); }

					$(".ship_id", cElm).text( cShip.id );
					$(".ship_img .ship_icon", cElm).attr("src", KC3Meta.shipIcon(cShip.bid));
					if(config.kanmusuPic && shipLevel >= 100)
						$(".ship_img .ship_kekkon", cElm).attr("src","tabs/ships/SEGASonicRing.png").show();
					$(".ship_name", cElm).text( cShip.english );
					$(".ship_type", cElm).text( KC3Meta.stype(cShip.stype) );
					var shipLevelConv = shipLevel - (shipLevel>=100 && config.kanmusuLv ? (102 - ConfigManager.marryLevelFormat) : 0);
					$(".ship_lv", cElm).html( "Lv." + shipLevelConv);
					if(config.kanmusuLv && shipLevel >= 100)
						$(".ship_lv", cElm).addClass("ship_kekkon ship_kekkon-color");
					$(".ship_morale", cElm).html( cShip.morale );

					var hpStatus = cShip.hp.toString() + " / " + cShip.maxhp.toString();
					$(".ship_status", cElm).text( hpStatus );
					if (cShip.hp === cShip.maxhp) {
					    $(".ship_status", cElm).text( cShip.hp.toString() );
						$(".ship_repair_docking", cElm).text( "-" );
						$(".ship_repair_akashi", cElm).text( "-" );
					} else {
						$(".ship_repair_docking", cElm).text( String(cShip.repairDocking).toHHMMSS() );
						$(".ship_repair_akashi", cElm).text( "-" );
						if (cShip.taiha) {
							$(".ship_status", cElm).addClass("ship_taiha");
						} else if (cShip.stripped) {
							$(".ship_status", cElm).addClass("ship_stripped");
						} else {
							$(".ship_repair_akashi", cElm).text( String(cShip.repairAkashi).toHHMMSS() );
						}
					}

					[1,2,3,4].forEach(function(x){
						self.equipImg(cElm, x, cShip.slots[x-1], cShip.equip[x-1]);
					});

				});

				self.shipList.show();
				self.isLoading = false;
				console.log("Showing this list took", ((new Date()).getTime() - self.startTime)-100 , "milliseconds");
			},100);
		},

		/* Show single equipment icon
		   --------------------------------------------*/
		equipImg :function(cElm, equipNum, equipSlot, gear_id){
			var element = $(".ship_equip_" + equipNum, cElm);
			if(gear_id > -1){
				var gear = KC3GearManager.get(gear_id);
				if(gear.itemId<=0){ element.hide(); return; }

				var masterGear = KC3Master.slotitem(gear.api_slotitem_id);
				$("img",element)
					.attr("src", "../../assets/img/items/" + gear.master().api_type[3] + ".png")
					.attr("title", gear.name());
				$("span",element).css('visibility','hidden');
			} else {
				$("img",element).hide();
				$("span",element).each(function(i,x){
					if(equipSlot > 0)
						$(x).text(equipSlot);
					else
						$(x).css('visibility','hidden');
				});
			}
		}
	};

	// checks kekkon setting
	function KekkonType(){
		var checks = {
			kanmusuDT  : [0],	// ONLY show this
			kanmusuName: [1],	// ring location: name
			kanmusuLv  : [2,3], // ring location: level
			kanmusuLv0 : [2],	// level convention, 0-index
			kanmusuLv1 : [3],	// level convention, 1-index
			kanmusuPic : [4],	// ring location: ship icon
		};
		if(!KekkonType.values) {
			this.values = {};
			KekkonType.instance = this;
		}
		Object.keys(checks).forEach(function(k){
			KekkonType.instance.values[k] = (function(x){return x.indexOf(ConfigManager.marryLevelFormat || -1) >= 0;})(checks[k]);
		});
		return KekkonType.instance;
	}
	new KekkonType();

})();
<|endoftext|>


<commit_before>import { inDoc, classify, getComponentName } from '../util'
import { getInstanceName } from './index'
import SharedData from 'src/shared-data'
import { isBrowser, target } from '../devtools/env'

let overlay
let overlayContent

function init () {
  if (overlay || !isBrowser) return
  overlay = document.createElement('div')
  overlay.style.backgroundColor = 'rgba(104, 182, 255, 0.35)'
  overlay.style.position = 'fixed'
  overlay.style.zIndex = '99999999999999'
  overlay.style.pointerEvents = 'none'
  overlay.style.display = 'flex'
  overlay.style.alignItems = 'center'
  overlay.style.justifyContent = 'center'
  overlay.style.borderRadius = '3px'
  overlayContent = document.createElement('div')
  overlayContent.style.backgroundColor = 'rgba(104, 182, 255, 0.9)'
  overlayContent.style.fontFamily = 'monospace'
  overlayContent.style.fontSize = '11px'
  overlayContent.style.padding = '2px 3px'
  overlayContent.style.borderRadius = '3px'
  overlayContent.style.color = 'white'
  overlay.appendChild(overlayContent)
}

/**
 * Highlight an instance.
 *
 * @param {Vue} instance
 */

export function highlight (instance) {
  if (!instance) return
  const rect = getInstanceOrVnodeRect(instance)

  if (!isBrowser) {
    // TODO: Highlight rect area.
    return
  }

  init()
  if (rect) {
    const content = []
    let name = instance.fnContext ? getComponentName(instance.fnOptions) : getInstanceName(instance)
    if (SharedData.classifyComponents) name = classify(name)
    if (name) {
      const pre = document.createElement('span')
      pre.style.opacity = '0.6'
      pre.innerText = '<'
      const text = document.createTextNode(name)
      const post = document.createElement('span')
      post.style.opacity = '0.6'
      post.innerText = '>'
      content.push(pre, text, post)
    }
    showOverlay(rect, content)
  }
}

/**
 * Remove highlight overlay.
 */

export function unHighlight () {
  if (overlay && overlay.parentNode) {
    document.body.removeChild(overlay)
  }
}

/**
 * Get the client rect for an instance.
 *
 * @param {Vue|Vnode} instance
 * @return {Object}
 */

export function getInstanceOrVnodeRect (instance) {
  const el = instance.$el || instance.elm
  if (!isBrowser) {
    // TODO: Find position from instance or a vnode (for functional components).

    return
  }
  if (!inDoc(el)) {
    return
  }
  if (instance._isFragment) {
    return getFragmentRect(instance)
  } else if (el.nodeType === 1) {
    return el.getBoundingClientRect()
  }
}

/**
 * Highlight a fragment instance.
 * Loop over its node range and determine its bounding box.
 *
 * @param {Vue} instance
 * @return {Object}
 */

function getFragmentRect ({ _fragmentStart, _fragmentEnd }) {
  let top, bottom, left, right
  util().mapNodeRange(_fragmentStart, _fragmentEnd, function (node) {
    let rect
    if (node.nodeType === 1 || node.getBoundingClientRect) {
      rect = node.getBoundingClientRect()
    } else if (node.nodeType === 3 && node.data.trim()) {
      rect = getTextRect(node)
    }
    if (rect) {
      if (!top || rect.top < top) {
        top = rect.top
      }
      if (!bottom || rect.bottom > bottom) {
        bottom = rect.bottom
      }
      if (!left || rect.left < left) {
        left = rect.left
      }
      if (!right || rect.right > right) {
        right = rect.right
      }
    }
  })
  return {
    top,
    left,
    width: right - left,
    height: bottom - top
  }
}

let range
/**
 * Get the bounding rect for a text node using a Range.
 *
 * @param {Text} node
 * @return {Rect}
 */
function getTextRect (node) {
  if (!isBrowser) return
  if (!range) range = document.createRange()

  range.selectNode(node)

  return range.getBoundingClientRect()
}

/**
 * Display the overlay with given rect.
 *
 * @param {Rect}
 */

function showOverlay ({ width = 0, height = 0, top = 0, left = 0 }, content = []) {
  if (!isBrowser) return

  overlay.style.width = ~~width + 'px'
  overlay.style.height = ~~height + 'px'
  overlay.style.top = ~~top + 'px'
  overlay.style.left = ~~left + 'px'

  content.forEach(child => overlayContent.appendChild(child))

  document.body.appendChild(overlay)
}

/**
 * Get Vue's util
 */

function util () {
  return target.__VUE_DEVTOOLS_GLOBAL_HOOK__.Vue.util
}
<commit_msg>fix: highlighter content not cleared<commit_after>import { inDoc, classify, getComponentName } from '../util'
import { getInstanceName } from './index'
import SharedData from 'src/shared-data'
import { isBrowser, target } from '../devtools/env'

let overlay
let overlayContent

function init () {
  if (overlay || !isBrowser) return
  overlay = document.createElement('div')
  overlay.style.backgroundColor = 'rgba(104, 182, 255, 0.35)'
  overlay.style.position = 'fixed'
  overlay.style.zIndex = '99999999999999'
  overlay.style.pointerEvents = 'none'
  overlay.style.display = 'flex'
  overlay.style.alignItems = 'center'
  overlay.style.justifyContent = 'center'
  overlay.style.borderRadius = '3px'
  overlayContent = document.createElement('div')
  overlayContent.style.backgroundColor = 'rgba(104, 182, 255, 0.9)'
  overlayContent.style.fontFamily = 'monospace'
  overlayContent.style.fontSize = '11px'
  overlayContent.style.padding = '2px 3px'
  overlayContent.style.borderRadius = '3px'
  overlayContent.style.color = 'white'
  overlay.appendChild(overlayContent)
}

/**
 * Highlight an instance.
 *
 * @param {Vue} instance
 */

export function highlight (instance) {
  if (!instance) return
  const rect = getInstanceOrVnodeRect(instance)

  if (!isBrowser) {
    // TODO: Highlight rect area.
    return
  }

  init()
  if (rect) {
    const content = []
    let name = instance.fnContext ? getComponentName(instance.fnOptions) : getInstanceName(instance)
    if (SharedData.classifyComponents) name = classify(name)
    if (name) {
      const pre = document.createElement('span')
      pre.style.opacity = '0.6'
      pre.innerText = '<'
      const text = document.createTextNode(name)
      const post = document.createElement('span')
      post.style.opacity = '0.6'
      post.innerText = '>'
      content.push(pre, text, post)
    }
    showOverlay(rect, content)
  }
}

/**
 * Remove highlight overlay.
 */

export function unHighlight () {
  if (overlay && overlay.parentNode) {
    document.body.removeChild(overlay)
  }
}

/**
 * Get the client rect for an instance.
 *
 * @param {Vue|Vnode} instance
 * @return {Object}
 */

export function getInstanceOrVnodeRect (instance) {
  const el = instance.$el || instance.elm
  if (!isBrowser) {
    // TODO: Find position from instance or a vnode (for functional components).

    return
  }
  if (!inDoc(el)) {
    return
  }
  if (instance._isFragment) {
    return getFragmentRect(instance)
  } else if (el.nodeType === 1) {
    return el.getBoundingClientRect()
  }
}

/**
 * Highlight a fragment instance.
 * Loop over its node range and determine its bounding box.
 *
 * @param {Vue} instance
 * @return {Object}
 */

function getFragmentRect ({ _fragmentStart, _fragmentEnd }) {
  let top, bottom, left, right
  util().mapNodeRange(_fragmentStart, _fragmentEnd, function (node) {
    let rect
    if (node.nodeType === 1 || node.getBoundingClientRect) {
      rect = node.getBoundingClientRect()
    } else if (node.nodeType === 3 && node.data.trim()) {
      rect = getTextRect(node)
    }
    if (rect) {
      if (!top || rect.top < top) {
        top = rect.top
      }
      if (!bottom || rect.bottom > bottom) {
        bottom = rect.bottom
      }
      if (!left || rect.left < left) {
        left = rect.left
      }
      if (!right || rect.right > right) {
        right = rect.right
      }
    }
  })
  return {
    top,
    left,
    width: right - left,
    height: bottom - top
  }
}

let range
/**
 * Get the bounding rect for a text node using a Range.
 *
 * @param {Text} node
 * @return {Rect}
 */
function getTextRect (node) {
  if (!isBrowser) return
  if (!range) range = document.createRange()

  range.selectNode(node)

  return range.getBoundingClientRect()
}

/**
 * Display the overlay with given rect.
 *
 * @param {Rect}
 */

function showOverlay ({ width = 0, height = 0, top = 0, left = 0 }, content = []) {
  if (!isBrowser) return

  overlay.style.width = ~~width + 'px'
  overlay.style.height = ~~height + 'px'
  overlay.style.top = ~~top + 'px'
  overlay.style.left = ~~left + 'px'

  overlayContent.innerHTML = ''
  content.forEach(child => overlayContent.appendChild(child))

  document.body.appendChild(overlay)
}

/**
 * Get Vue's util
 */

function util () {
  return target.__VUE_DEVTOOLS_GLOBAL_HOOK__.Vue.util
}
<|endoftext|>


<commit_before>var creep_work5 = {

    /** @param {Creep} creep **/
    run: function(creep, thisSpawn) {

        //wew lad
        /*if (!creep.room.controller.sign) {
            if(creep.pos.isNearTo(creep.room.controller)) {
                creep.signController(creep.room.controller, 'This is, by far, the most kupo room I\'ve ever seen!');
            }
        }*/

        if (creep.memory.priority == 'miner' || creep.memory.priority == 'minerNearDeath') {
            if (creep.ticksToLive <= 60){
                creep.memory.priority = 'minerNearDeath';
                creep.memory.jobSpecific = creep.memory.jobSpecific + 'NearDeath';
            }
            //React at 144 so that the creep doesn't drop any resources on the ground
            if (_.sum(creep.carry) < 144) {
                var savedTarget = Game.getObjectById(creep.memory.mineSource);
                if (savedTarget) {
                    if (creep.harvest(savedTarget) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget, {
                            reusePath: 20
                        });
                    } else if (creep.harvest(savedTarget, RESOURCE_ENERGY) == ERR_NOT_ENOUGH_RESOURCES && _.sum(creep.carry) > 0) {
                        //Source is dry, store what you have.
                        var savedTarget2 = Game.getObjectById(creep.memory.linkSource);
                        if (savedTarget2) {
                            if (creep.transfer(savedTarget2, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (_.sum(creep.carry) >= 144) {
                var savedTarget = Game.getObjectById(creep.memory.linkSource);
                if (savedTarget) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        //This should never actually fire, if ideal.
                        creep.moveTo(savedTarget);
                    }
                }
            }
        } else if (creep.memory.priority == 'upgrader' || creep.memory.priority == 'upgraderNearDeath') {
            if (creep.ticksToLive <= 60){
                creep.memory.priority = 'upgraderNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                var linkTarget = Game.getObjectById(creep.memory.linkSource);
                if (linkTarget) {
                    if (linkTarget.energy > 0) {
                        if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(linkTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        //Get from storage instead
                        var storageTarget = Game.getObjectById(creep.memory.storageSource);
                        if (storageTarget) {
                            if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                                if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                    creep.moveTo(storageTarget, {
                                        reusePath: 20
                                    });
                                }
                            }
                        }
                    }
                } else {
                    var storageTarget = Game.getObjectById(creep.memory.storageSource);
                    if (storageTarget) {
                        if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                            if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(storageTarget, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(creep.room.controller, {
                        reusePath: 20
                    });
                }
            }
        } else if (creep.memory.priority == 'mule' || creep.memory.priority == 'muleNearDeath') {
            if (creep.ticksToLive <= 60){
                creep.memory.priority = 'muleNearDeath';
            }
            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] > 0) {
                        //Get from container
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }

                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                var savedTarget = Game.getObjectById(creep.memory.structureTarget)

                if (savedTarget) {
                    if (creep.build(savedTarget) == ERR_INVALID_TARGET) {
                        if (savedTarget.structureType != STRUCTURE_CONTAINER && savedTarget.structureType != STRUCTURE_STORAGE && savedTarget.structureType != STRUCTURE_CONTROLLER) {
                            //Storing in spawn/extension/tower
                            if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(savedTarget, {
                                    reusePath: 20
                                });
                            }
                            if (savedTarget.energy == savedTarget.energyCapacity) {
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Upgrading controller
                            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(creep.room.controller, {
                                    reusePath: 20
                                });
                            }
                        }
                    } else {
                        if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget, {
                                reusePath: 20
                            });
                        }
                    }
                } else {
                    var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_EXTENSION ||
                                structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                        }
                    });
                    if (targets) {
                        creep.memory.structureTarget = targets.id;
                        if (creep.transfer(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(targets);
                        }
                        if (targets.energy == targets.energyCapacity) {
                            //If container fills up on this tick, forget it.
                            creep.memory.structureTarget = undefined;
                        }
                    } else {
                        targets3 = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_TOWER) && ((structure.energyCapacity - structure.energy) >= 300);
                            }
                        });
                        if (targets3) {
                            creep.memory.structureTarget = targets3.id;
                            if (creep.transfer(targets3, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets3);
                            }
                            if (targets3.energy == targets3.energyCapacity) {
                                //If container fills up on this tick, forget it.
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Store in terminal
                            terminalTarget = Game.getObjectById(creep.memory.terminalID)
                            if (terminalTarget) {
                                if (terminalTarget.store[RESOURCE_ENERGY] < 50000) {
                                    creep.memory.structureTarget = terminalTarget;
                                    if (creep.transfer(terminalTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(terminalTarget, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    terminalTarget = undefined;
                                }
                            }
                            if (!terminalTarget) {
                                //Build
                                var targets2 = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
                                if (targets2) {
                                    creep.memory.structureTarget = targets2.id;
                                    if (creep.build(targets2) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(targets2, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    //Upgrade
                                    creep.memory.structureTarget = creep.room.controller.id;
                                    if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(creep.room.controller, {
                                            reusePath: 20
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (creep.memory.priority == 'repair' || creep.memory.priority == 'repairNearDeath') {
            if (creep.ticksToLive <= 60){
                creep.memory.priority = 'repairNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                //Get from storage
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 120) {
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else if (creep.memory.structureTarget) {
                var thisStructure = Game.getObjectById(creep.memory.structureTarget);
                if (thisStructure) {
                    if (thisStructure.hits == thisStructure.hitsMax) {
                        creep.memory.structureTarget = undefined;
                    } else {
                        if (creep.repair(thisStructure) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(thisStructure, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else {
                var closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hitsMax - structure.hits >= 200)
                });
                if (closestDamagedStructure.length > 0) {
                    closestDamagedStructure.sort(repairCompare);
                    creep.memory.structureTarget = closestDamagedStructure[0].id;
                    if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(closestDamagedStructure[0], {
                            reusePath: 20
                        });
                    }
                }
            }

        } else if (creep.memory.priority == 'mineralMiner') {
            var thisMineral = Game.getObjectById(creep.memory.mineralID);
            if (thisMineral.mineralAmount == 0) {
                //Nothing left to do
                creep.suicide();
            } else if (_.sum(creep.carry) >= 40) {
                //Store in terminal
                var savedTarget = Game.getObjectById(creep.memory.terminalID);
                if (savedTarget) {
                    if (creep.transfer(savedTarget, thisMineral.mineralType) == ERR_NOT_IN_RANGE) {
                        //This should never actually fire, if ideal.
                        creep.moveTo(savedTarget);
                    }
                }
            } else {
                //Mine
                var thisExtractor = Game.getObjectById(creep.memory.extractorID);
                if (thisExtractor.cooldown == 0) {
                    if (creep.harvest(thisMineral) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(thisMineral, {
                            reusePath: 20
                        });
                    }
                }
            }
        }
    }
};

module.exports = creep_work5;

function repairCompare(a, b) {
    if (a.hits < b.hits)
        return -1;
    if (a.hits > b.hits)
        return 1;
    return 0;
}<commit_msg>Miners now immediately store after harvest<commit_after>var creep_work5 = {

    /** @param {Creep} creep **/
    run: function(creep, thisSpawn) {

        //wew lad
        /*if (!creep.room.controller.sign) {
            if(creep.pos.isNearTo(creep.room.controller)) {
                creep.signController(creep.room.controller, 'This is, by far, the most kupo room I\'ve ever seen!');
            }
        }*/

        if (creep.memory.priority == 'miner' || creep.memory.priority == 'minerNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'minerNearDeath';
                creep.memory.jobSpecific = creep.memory.jobSpecific + 'NearDeath';
            }
            //Creep will immediately harvest and store mined materials
            var storageTarget = Game.getObjectById(creep.memory.linkSource);
            var mineTarget = Game.getObjectById(creep.memory.mineSource);
            if (mineTarget && storageTarget) {
                if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(mineTarget, {
                        reusePath: 20
                    });
                } else {
                    creep.transfer(storageTarget RESOURCE_ENERGY)
                }
            }

            /*if (_.sum(creep.carry) < 144) {
                var savedTarget = Game.getObjectById(creep.memory.mineSource);
                if (savedTarget) {
                    if (creep.harvest(savedTarget) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget, {
                            reusePath: 20
                        });
                    } else if (creep.harvest(savedTarget, RESOURCE_ENERGY) == ERR_NOT_ENOUGH_RESOURCES && _.sum(creep.carry) > 0) {
                        //Source is dry, store what you have.
                        var savedTarget2 = Game.getObjectById(creep.memory.linkSource);
                        if (savedTarget2) {
                            if (creep.transfer(savedTarget2, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (_.sum(creep.carry) >= 144) {
                var savedTarget = Game.getObjectById(creep.memory.linkSource);
                if (savedTarget) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        //This should never actually fire, if ideal.
                        creep.moveTo(savedTarget);
                    }
                }
            }*/
        } else if (creep.memory.priority == 'upgrader' || creep.memory.priority == 'upgraderNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'upgraderNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                var linkTarget = Game.getObjectById(creep.memory.linkSource);
                if (linkTarget) {
                    if (linkTarget.energy > 0) {
                        if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(linkTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        //Get from storage instead
                        var storageTarget = Game.getObjectById(creep.memory.storageSource);
                        if (storageTarget) {
                            if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                                if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                    creep.moveTo(storageTarget, {
                                        reusePath: 20
                                    });
                                }
                            }
                        }
                    }
                } else {
                    var storageTarget = Game.getObjectById(creep.memory.storageSource);
                    if (storageTarget) {
                        if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                            if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(storageTarget, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(creep.room.controller, {
                        reusePath: 20
                    });
                }
            }
        } else if (creep.memory.priority == 'mule' || creep.memory.priority == 'muleNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'muleNearDeath';
            }
            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] > 0) {
                        //Get from container
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }

                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                var savedTarget = Game.getObjectById(creep.memory.structureTarget)

                if (savedTarget) {
                    if (creep.build(savedTarget) == ERR_INVALID_TARGET) {
                        if (savedTarget.structureType != STRUCTURE_CONTAINER && savedTarget.structureType != STRUCTURE_STORAGE && savedTarget.structureType != STRUCTURE_CONTROLLER) {
                            //Storing in spawn/extension/tower
                            if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(savedTarget, {
                                    reusePath: 20
                                });
                            }
                            if (savedTarget.energy == savedTarget.energyCapacity) {
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Upgrading controller
                            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(creep.room.controller, {
                                    reusePath: 20
                                });
                            }
                        }
                    } else {
                        if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget, {
                                reusePath: 20
                            });
                        }
                    }
                } else {
                    var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_EXTENSION ||
                                structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                        }
                    });
                    if (targets) {
                        creep.memory.structureTarget = targets.id;
                        if (creep.transfer(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(targets);
                        }
                        if (targets.energy == targets.energyCapacity) {
                            //If container fills up on this tick, forget it.
                            creep.memory.structureTarget = undefined;
                        }
                    } else {
                        targets3 = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_TOWER) && ((structure.energyCapacity - structure.energy) >= 300);
                            }
                        });
                        if (targets3) {
                            creep.memory.structureTarget = targets3.id;
                            if (creep.transfer(targets3, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets3);
                            }
                            if (targets3.energy == targets3.energyCapacity) {
                                //If container fills up on this tick, forget it.
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Store in terminal
                            terminalTarget = Game.getObjectById(creep.memory.terminalID)
                            if (terminalTarget) {
                                if (terminalTarget.store[RESOURCE_ENERGY] < 50000) {
                                    creep.memory.structureTarget = terminalTarget;
                                    if (creep.transfer(terminalTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(terminalTarget, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    terminalTarget = undefined;
                                }
                            }
                            if (!terminalTarget) {
                                //Build
                                var targets2 = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
                                if (targets2) {
                                    creep.memory.structureTarget = targets2.id;
                                    if (creep.build(targets2) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(targets2, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    //Upgrade
                                    creep.memory.structureTarget = creep.room.controller.id;
                                    if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(creep.room.controller, {
                                            reusePath: 20
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (creep.memory.priority == 'repair' || creep.memory.priority == 'repairNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'repairNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                //Get from storage
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 120) {
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else if (creep.memory.structureTarget) {
                var thisStructure = Game.getObjectById(creep.memory.structureTarget);
                if (thisStructure) {
                    if (thisStructure.hits == thisStructure.hitsMax) {
                        creep.memory.structureTarget = undefined;
                    } else {
                        if (creep.repair(thisStructure) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(thisStructure, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else {
                var closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hitsMax - structure.hits >= 200)
                });
                if (closestDamagedStructure.length > 0) {
                    closestDamagedStructure.sort(repairCompare);
                    creep.memory.structureTarget = closestDamagedStructure[0].id;
                    if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(closestDamagedStructure[0], {
                            reusePath: 20
                        });
                    }
                }
            }

        } else if (creep.memory.priority == 'mineralMiner') {
            var thisMineral = Game.getObjectById(creep.memory.mineralID);
            if (thisMineral.mineralAmount == 0) {
                //Nothing left to do
                creep.suicide();
            } else if (_.sum(creep.carry) >= 40) {
                //Store in terminal
                var savedTarget = Game.getObjectById(creep.memory.terminalID);
                if (savedTarget) {
                    if (creep.transfer(savedTarget, thisMineral.mineralType) == ERR_NOT_IN_RANGE) {
                        //This should never actually fire, if ideal.
                        creep.moveTo(savedTarget);
                    }
                }
            } else {
                //Mine
                var thisExtractor = Game.getObjectById(creep.memory.extractorID);
                if (thisExtractor.cooldown == 0) {
                    if (creep.harvest(thisMineral) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(thisMineral, {
                            reusePath: 20
                        });
                    }
                }
            }
        }
    }
};

module.exports = creep_work5;

function repairCompare(a, b) {
    if (a.hits < b.hits)
        return -1;
    if (a.hits > b.hits)
        return 1;
    return 0;
}<|endoftext|>


<commit_before>//collect.js gets gets pages and runs them through the data pipeline

//  Output schema:
///    this page's URL                  url        str
///    the next closest root to Dada    url        str (will need to recalc this in post-processing)
///    the page's title                 words      str
///    the page's image, if it has one  url        str
///    links from this page             mapsTo     []
///    pages linking to this one        mapsFrom   []
///    metaData from wiki's data page   metaData   {}

var request = require('request');
var fs = require('fs');
var async = require('async');

//local modules
var dataScrape = require('./s-wikiData');
var mF = require('./s-mapsFrom');
var mT = require('./s-mainPage');
var detect = require('./s-detect');

var pagesIn = JSON.parse(fs.readFileSync('mapsFrom_Crawl.json'))
    pagesIn_2 = JSON.parse(fs.readFileSync('mapsTo_Crawl.json'));

pagesIn = pagesIn.concat(pagesIn_2);

var dups = JSON.parse(fs.readFileSync('dups.json'));

//data
var pages = [],
    lastBatch = 0;

//c = count, s = stop, d = done (boolean)
var nl_c = 0,
    nl_s = 10,
    mapsToDone = false,
    mapsFromDone = false,
    urlArr,                       // urlArr to scrape
    filenames = [],               // store filenames
    t_c = 0,                      // inner counter
    t_s = 10,                     // inner stop point (init value is random)
    delay = [1200,3600];          // delay for timeout

// test URLs - 'Francis_Picabia' - 'Ann%C3%A9es_folles' - 'Dada'

var exceptions = [
  'wikisource.org',
  '.jpg',
  '.png',
  '.gif',
  'Book:'
]

var fullSkip = [
  'wikipedia',      // no foriegn pages (not in scope)
  'wiktionary.org', // no wiktionary pages
  'wikiquote',      // no wikiquote pages
  '_talk:',         // no talk pages
  'Draft:'
]

// check for exceptions
function skip(link, exc) {
  var fact = false;
  for (var c in exc) {
    if (link.includes(exc[c])) {
      fact = true;
      break;
    }
  }
  return fact;
}

function getRando(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

function writeDataFile(location, counter) {
  //counter++;
  if (counter>=t_s || counter%250==0) { //if last loop or if counter is divisible by 250, write the file
    var filename = 'data/index'+location+'-batch'+lastBatch+'-'+counter+'.json';
    fs.writeFile(filename, JSON.stringify(pages), function(err) {
        if (err) {throw err;}
        console.log(filename+' written');
        filenames.push(filename);
        lastBatch = counter;
        pages = [];
    });
  }
}

function crawler() {           //  create a loop function
   setTimeout(function () {    //  call a 3s setTimeout when the loop is called

        // check for already scraped urls
        if(!dups.hasOwnProperty(urlArr[t_c])) {

          var page = new Object;
          page.distance = 2;
          page.root = pagesIn[nl_c].url;
          page.url =  urlArr[t_c];        // testURL_1;
          dups[urlArr[t_c]] = 1;
          delay = [1200,3600];

          var url = 'https://en.wikipedia.org/wiki/'+page.url;
          var mapsFromURL = 'https://en.wikipedia.org/w/index.php?title=Special:WhatLinksHere/'+page.url+'&limit=3000';

          //check for fullSkip (pages not scraping) pages
          if (!skip(page.url, fullSkip)) {

          // collect links pointing at this page
          request(mapsFromURL, function(err, resp, body) {
            if (err) {throw err;}
              console.log('scraping mapsFrom '+mapsFromURL);
              page.mapsFrom = mF.scrape(body);
             if (!skip(page.url, exceptions)) {

              // collect links pointing outwards from the page
              request(url, function(err, resp, body) {
                 if (err) {throw err;}
                  console.log('scraping mainPage '+url);
                  var s = mT.scrape(body, url);
                  page.mapsTo = s.mapsTo;
                  page.wikiData = s.wikiData;
                  page.image = s.image;
                  page.title = s.title;

                 if (page.wikiData!=undefined) {
                   // collect wikiData (categorical info)
                   request(page.wikiData, function(err, resp, body) {
                      if (err) {throw err;}
                       console.log('scraping wikiData '+page.wikiData);
                       page.metaData = dataScrape.scrape(body);
                       pages.push(page);
                       writeDataFile(nl_c, t_c);
                   });
                 } else {
                   // case no wikiData
                   page.metaData = null;
                   pages.push(page);
                   writeDataFile(nl_c, t_c);
                 }
              }); // end mainPage request
            } else {
              // some page types don't have link info, push as-is
              pages.push(page);
              writeDataFile(nl_c, t_c);
            }
          });
        } else {
          page.noScrape = 1;
          pages.push(page);
          console.log('-NO SCRAPE-');
          writeDataFile(nl_c, t_c);
        } // end fullSkip conditional
      } else {
        // track url distribution
        dups[urlArr[t_c]]++;
        // no delay on dups
        delay = [0,0];
      } // end dups conditional

    // iterator
    if (t_c < t_s) { //pagesIn[pgI].mapsTo.length-1
      console.log(t_c+' of '+ t_s);
      t_c++;
      crawler();
    } else {
      console.log('CRAWL COMPLETE: '+nl_c);
      // clear memory with setTimeout (recursion results in stack overflow)
      setTimeout( function() {
        writeDataFile(nl_c, t_c);
        isDone();
      }, 0 );
    }

  //set delay between 1200 and 3600 milliseconds per request
}, getRando(delay[0],delay[1]))
}
// ------------------------------------------------------------------------------

function nextList() {

  nl_s =  pagesIn.length-1;

  // if the page does not have url attr, mark it done
  if (!pagesIn[nl_c].hasOwnProperty('mapsTo')) mapsToDone = true;
  if (!pagesIn[nl_c].hasOwnProperty('mapsFrom')) mapsFromDone = true;

  if (!mapsToDone) {
    t_s = pagesIn[nl_c].mapsTo.length-1;
    urlArr = pagesIn[nl_c].mapsTo;
  } else {
    t_s = pagesIn[nl_c].mapsFrom.length-1;
    urlArr = pagesIn[nl_c].mapsFrom;
  }

  crawler(); // tester();

}

function isDone() {  // if inner loop is complete

  if (nl_c < nl_s) {  // if not end of array of obj

    // iterate nLCount, reset inner count
    t_c = 0;
    console.log(nl_s);

    if (!mapsToDone) {
      console.log('MAPS TO DONE');
      mapsToDone = true;
      nextList();
    } else {
      console.log('MAPS FROM DONE');
      mapsFromDone = true;
    }

    // only iterate nl_c if it has done mapsTo and mapsFrom
    if (mapsToDone && mapsFromDone) {
      nl_c++;
      mapsToDone = false;
      mapsFromDone = false;
      nextList();
    }

  } else {
    console.log(' done');
    fs.writeFile('data/filenames.json', JSON.stringify(filenames), function(err) {
        if (err) {throw err;}
        console.log('filenames written');
    });

    fs.writeFile('data/dups.json', JSON.stringify(dups), function(err) {
        if (err) {throw err;}
        console.log('dups written');
    });
  }
}

nextList();
// console.log(pagesIn_2[42].mapsTo);
// console.log(dups);

// for debugging

function tester() {
  if(!dups.hasOwnProperty(urlArr[t_c])) {
    console.log('T: '+t_c);
    // console.log('URL: '+urlArr[t_c]);
    dups[urlArr[t_c]] = 1;
  } else {
    // console.log('DUP');
  }
  // check for stop condition, if not, iterate, call self
  if (t_c < t_s) {
    t_c++;
    tester();
  } else {
    // clear memory with setTimeout (recursion results in stack overflow)
    setTimeout( function() {
      isDone();
    }, 0 );
  }
}
<commit_msg>add writeFilename() calls<commit_after>//collect.js gets gets pages and runs them through the data pipeline

//  Output schema:
///    this page's URL                  url        str
///    the next closest root to Dada    url        str (will need to recalc this in post-processing)
///    the page's title                 words      str
///    the page's image, if it has one  url        str
///    links from this page             mapsTo     []
///    pages linking to this one        mapsFrom   []
///    metaData from wiki's data page   metaData   {}

var request = require('request');
var fs = require('fs');
var async = require('async');

//local modules
var dataScrape = require('./s-wikiData');
var mF = require('./s-mapsFrom');
var mT = require('./s-mainPage');
var detect = require('./s-detect');

var pagesIn = JSON.parse(fs.readFileSync('mapsFrom_Crawl.json'))
    pagesIn_2 = JSON.parse(fs.readFileSync('mapsTo_Crawl.json'));

pagesIn = pagesIn.concat(pagesIn_2);

var dups = JSON.parse(fs.readFileSync('dups.json'));

//data
var pages = [],
    lastBatch = 0;

//c = count, s = stop, d = done (boolean)
var nl_c = 0,
    nl_s = 10,
    mapsToDone = false,
    mapsFromDone = false,
    urlArr,                       // urlArr to scrape
    filenames = [],               // store filenames
    t_c = 0,                      // inner counter
    t_s = 10,                     // inner stop point (init value is random)
    delay = [1200,3600];          // delay for timeout

// test URLs - 'Francis_Picabia' - 'Ann%C3%A9es_folles' - 'Dada'

var exceptions = [
  'wikisource.org',
  '.jpg',
  '.png',
  '.gif',
  'Book:'
]

var fullSkip = [
  'wikipedia',      // no foriegn pages (not in scope)
  'wiktionary.org', // no wiktionary pages
  'wikiquote',      // no wikiquote pages
  '_talk:',         // no talk pages
  'Draft:'
]

// check for exceptions
function skip(link, exc) {
  var fact = false;
  for (var c in exc) {
    if (link.includes(exc[c])) {
      fact = true;
      break;
    }
  }
  return fact;
}

function getRando(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

function writeDataFile(location, counter) {
  //counter++;
  if (counter>=t_s || counter%250==0) { //if last loop or if counter is divisible by 250, write the file
    var filename = 'data/index'+location+'-batch'+lastBatch+'-'+counter+'.json';
    fs.writeFile(filename, JSON.stringify(pages), function(err) {
        if (err) {throw err;}
        console.log(filename+' written');
        filenames.push(filename);
        lastBatch = counter;
        pages = [];
    });
  }
}

function crawler() {           //  create a loop function
   setTimeout(function () {    //  call a 3s setTimeout when the loop is called

        // check for already scraped urls
        if(!dups.hasOwnProperty(urlArr[t_c])) {

          var page = new Object;
          page.distance = 2;
          page.root = pagesIn[nl_c].url;
          page.url =  urlArr[t_c];        // testURL_1;
          dups[urlArr[t_c]] = 1;
          delay = [1200,3600];

          var url = 'https://en.wikipedia.org/wiki/'+page.url;
          var mapsFromURL = 'https://en.wikipedia.org/w/index.php?title=Special:WhatLinksHere/'+page.url+'&limit=3000';

          //check for fullSkip (pages not scraping) pages
          if (!skip(page.url, fullSkip)) {

          // collect links pointing at this page
          request(mapsFromURL, function(err, resp, body) {
            if (err) {throw err;}
              console.log('scraping mapsFrom '+mapsFromURL);
              page.mapsFrom = mF.scrape(body);
             if (!skip(page.url, exceptions)) {

              // collect links pointing outwards from the page
              request(url, function(err, resp, body) {
                 if (err) {throw err;}
                  console.log('scraping mainPage '+url);
                  var s = mT.scrape(body, url);
                  page.mapsTo = s.mapsTo;
                  page.wikiData = s.wikiData;
                  page.image = s.image;
                  page.title = s.title;

                 if (page.wikiData!=undefined) {
                   // collect wikiData (categorical info)
                   request(page.wikiData, function(err, resp, body) {
                      if (err) {throw err;}
                       console.log('scraping wikiData '+page.wikiData);
                       page.metaData = dataScrape.scrape(body);
                       pages.push(page);
                       writeDataFile(nl_c, t_c);
                   });
                 } else {
                   // case no wikiData
                   page.metaData = null;
                   pages.push(page);
                   writeDataFile(nl_c, t_c);
                 }
              }); // end mainPage request
            } else {
              // some page types don't have link info, push as-is
              pages.push(page);
              writeDataFile(nl_c, t_c);
            }
          });
        } else {
          page.noScrape = 1;
          pages.push(page);
          console.log('-NO SCRAPE-');
          writeDataFile(nl_c, t_c);
        } // end fullSkip conditional
      } else {
        // track url distribution
        dups[urlArr[t_c]]++;
        // no delay on dups
        delay = [0,0];
      } // end dups conditional

    // iterator
    if (t_c < t_s) { //pagesIn[pgI].mapsTo.length-1
      console.log(t_c+' of '+ t_s);
      t_c++;
      crawler();
    } else {
      console.log('CRAWL COMPLETE: '+nl_c);
      // clear memory with setTimeout (recursion results in stack overflow)
      setTimeout( function() {
        writeDataFile(nl_c, t_c);
        isDone();
      }, 0 );
    }

  //set delay between 1200 and 3600 milliseconds per request
}, getRando(delay[0],delay[1]))
}
// ------------------------------------------------------------------------------

function nextList() {

  nl_s =  pagesIn.length-1;

  // if the page does not have url attr, mark it done
  if (!pagesIn[nl_c].hasOwnProperty('mapsTo')) mapsToDone = true;
  if (!pagesIn[nl_c].hasOwnProperty('mapsFrom')) mapsFromDone = true;

  if (!mapsToDone) {
    t_s = pagesIn[nl_c].mapsTo.length-1;
    urlArr = pagesIn[nl_c].mapsTo;
  } else {
    t_s = pagesIn[nl_c].mapsFrom.length-1;
    urlArr = pagesIn[nl_c].mapsFrom;
  }

  crawler(); // tester();

}

function isDone() {  // if inner loop is complete

  if (nl_c < nl_s) {  // if not end of array of obj

    // iterate nLCount, reset inner count
    t_c = 0;
    console.log(nl_s);

    if (!mapsToDone) {
      console.log('MAPS TO DONE');
      mapsToDone = true;
      nextList();
    } else {
      console.log('MAPS FROM DONE');
      mapsFromDone = true;
    }

    // only iterate nl_c if it has done mapsTo and mapsFrom
    if (mapsToDone && mapsFromDone) {
      nl_c++;
      mapsToDone = false;
      mapsFromDone = false;
      writeFilenames();
      nextList();
    }

  } else {
    console.log(' done');

    writeFilenames();

    fs.writeFile('data/dups.json', JSON.stringify(dups), function(err) {
        if (err) {throw err;}
        console.log('dups written');
    });
  }
}

nextList();
// console.log(pagesIn_2[42].mapsTo);
// console.log(dups);

//periodically update the names of files written so far
function writeFilenames() {
  fs.writeFile('data/filenames.json', JSON.stringify(filenames), function(err) {
      if (err) {throw err;}
      console.log('filenames written');
  });
}

// for debugging
function tester() {
  if(!dups.hasOwnProperty(urlArr[t_c])) {
    console.log('T: '+t_c);
    // console.log('URL: '+urlArr[t_c]);
    dups[urlArr[t_c]] = 1;
  } else {
    // console.log('DUP');
  }
  // check for stop condition, if not, iterate, call self
  if (t_c < t_s) {
    t_c++;
    tester();
  } else {
    // clear memory with setTimeout (recursion results in stack overflow)
    setTimeout( function() {
      isDone();
    }, 0 );
  }
}
<|endoftext|>